SlideShare una empresa de Scribd logo
1 de 28
How to find 0days
in the Linux kernel
Andrey Konovalov <andreyknvl@google.com>
PHDays 2017
May 23-24th 2017
Userspace tools
● AddressSanitizer, ThreadSanitizer, MemorySanitizer, ...
○ C/C++/Go bug detectors
○ Detect wide range of bug types (use-after-frees and out-of-bounds, data
races and deadlocks, uninitialized memory uses, undefined behaviors)
○ Built into Clang, GCC and Go compiler
● libFuzzer
○ In-process coverage-guided fuzzing engine for C/C++
● oss-fuzz
○ Continuous fuzzing service for open source software
Finding bugs in the Linux kernel
Dynamic bug finding tools:
● Bug detectors
● Fuzzers
Bug detectors:
KASAN, KTSAN, KMSAN
Kernel Sanitizers
● KASAN (use-after-frees and out-of-bounds)
○ CONFIG_KASAN available upstream since 4.0
● KTSAN (data-races and deadlocks)
○ prototype available at https://github.com/google/ktsan
● KMSAN (uninitialized-memory-use)
○ prototype available at https://github.com/google/kmsan
KASAN report
BUG: KASAN: use-after-free in sctp_id2assoc+0x3a3/0x3b0
net/sctp/socket.c:224
Read of size 8 at addr ffff8800385b6838 by task syz-executor2/5889
Call Trace:
sctp_id2assoc+0x3a3/0x3b0 net/sctp/socket.c:224
sctp_setsockopt_rtoinfo net/sctp/socket.c:2931 [inline]
sctp_setsockopt+0x4b7/0x60f0 net/sctp/socket.c:4018
sock_common_setsockopt+0x95/0xd0 net/core/sock.c:2850
SYSC_setsockopt net/socket.c:1798 [inline]
SyS_setsockopt+0x270/0x3a0 net/socket.c:1777
entry_SYSCALL_64_fastpath+0x1f/0xbe
KASAN report
Allocated by task 5841:
kzalloc include/linux/slab.h:663 [inline]
sctp_association_new+0x114/0x2180 net/sctp/associola.c:309
...
SyS_connect+0x24/0x30 net/socket.c:1569
entry_SYSCALL_64_fastpath+0x1f/0xbe
Freed by task 5882:
kfree+0xe8/0x2b0 mm/slub.c:3882
sctp_association_destroy net/sctp/associola.c:435 [inline]
...
syscall_return_slowpath+0x3ba/0x410 arch/x86/entry/common.c:263
entry_SYSCALL_64_fastpath+0xbc/0xbe
Fuzzer:
syzkaller
syzkaller
● Coverage-guided syscall fuzzer for the Linux kernel
● As of now found over 400 bugs
(https://github.com/google/syzkaller/wiki/Found-Bugs)
● Over 25 CVEs
● At least 3 public local privilege escalation bugs over the
last few months (CVE-2017-7308, CVE-2017-6074,
CVE-2017-2636)
● Can generate C reproducers for found bugs
Coverage-guided fuzzing
(Think AFL or libFuzzer)
void TestOneInput(const char *data, int size) {
/* do something with data */
}
Fuzzer invokes the function with different inputs
Code coverage guiding:
● Corpus of “interesting” inputs
● Mutate and execute inputs from corpus
● If inputs gives new coverage, add it to corpus
Kernel inputs
Kernel
Userspace
syscalls
network ... USB
Syscall descriptions
open(file filename, flags flags[open_flags],
mode flags[open_mode]) fd
read(fd fd, buf buffer[out], count len[buf])
close(fd fd)
open_flags = O_RDONLY, O_WRONLY, O_RDWR, O_APPEND ...
Syscall descriptions:
discriminated syscalls
socket$inet_tcp(
domain const[AF_INET],
type const[SOCK_STREAM],
proto const[0]) sock_tcp
socket$packet(
domain const[AF_PACKET],
type flags[packet_socket_type],
proto const[ETH_P_ALL_BE]) sock_packet
Syscall descriptions:
structs layout
sockaddr_ll {
sll_family const[AF_PACKET, int16]
sll_protocol flags[packet_protocols, int16be]
sll_ifindex ifindex
sll_hatype const[ARPHRD_ETHER, int16]
sll_pkttype int8
sll_halen const[6, int8]
sll_addr mac_addr
pad array[const[0, int8], 2]
}
bind$packet(fd sock_packet, addr ptr[in, sockaddr_ll], addrlen len[addr])
Syscall descriptions:
resources
resource sock[fd]
socket(domain flags[socket_domain], type flags[socket_type],
proto int8) sock
bind(fd sock, addr ptr[in, sockaddr_storage], addrlen len[addr])
resource sock_packet[sock]
socket$packet(domain const[AF_PACKET], type flags[packet_socket_type],
proto const[ETH_P_ALL_BE]) sock_packet
bind$packet(fd sock_packet, addr ptr[in, sockaddr_ll], addrlen len[addr])
Programs
The description allows to generate and mutate "programs" in
the following form:
mmap(&(0x7f0000000000), (0x1000), 0x3, 0x32, -1, 0)
r0 = open(&(0x7f0000000000)="./file0", 0x3, 0x9)
read(r0, &(0x7f0000000000), 42)
close(r0)
Algorithm
1. Start with empty corpus of programs
2. Generate a new program, or choose an existing program
from corpus and mutate it
3. Interpret the program, collect coverage
4. If a syscall covers code that wasn't covered previously,
minimize program and add to corpus
5. Goto 1
External kernel inputs
Kernel
Userspace
syscalls
network ... USB
TUN/TAP
gadgetfs /
functionfs
Demo
Finding 0days in the Linux kernel
1. Setup syzkaller
2. Write syscall descriptions for some previously untested
kernel interface
3. Specify syscalls required to interact with this interface in
the configuration file
4. Run syzkaller and discover bugs
Questions?
https://github.com/google/kasan/wiki
https://github.com/google/syzkaller
kasan-dev@googlegroups.com
syzkaller@googlegroups.com
Andrey Konovalov, andreyknvl@google.com
Dmitry Vyukov, dvyukov@google.com
Backup
Coverage for the Linux kernel
● Available upstream with CONFIG_KCOV
● GCC pass that inserts a function call into every basic block
● kernel debugfs extension that collects and exposes coverage per-thread
__fuzz_coverage();
if (...) {
__fuzz_coverage();
...
}
__fuzz_coverage();
if (...) {
...
}
Process structure
Kernel system call fuzzers
● Trinity (https://github.com/kernelslacker/trinity)
● syzkaller (https://github.com/google/syzkaller)
Other Linux kernel fuzzers
● https://github.com/oracle/kernel-fuzzing
● https://github.com/nccgroup/TriforceLinuxSyscallFuzzer
● http://web.eece.maine.edu/~vweaver/projects/perf_events/f
uzzer/
● https://github.com/schumilo/vUSBf
External Stimulus
Systems calls and external stimulus in the same program:
listen(r0)
emit_ethernet(syn)
emit_ethernet(ack)
r1 = accept(r0)
emit_ethernet(data)
read(r1)
emit_ethernet(rst)
Work in progress; also applicable to USB, ...
Existing system call fuzzers
Trinity in essence:
syscall(rand(), rand(), rand());
Knows argument types, so more like:
syscall(rand(), rand_fd(), rand_addr());
● Tend to find shallow bugs
● Frequently no reproducers

Más contenido relacionado

La actualidad más candente

CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershellCSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CanSecWest
 
[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection
Moabi.com
 

La actualidad más candente (20)

Can We Prevent Use-after-free Attacks?
Can We Prevent Use-after-free Attacks?Can We Prevent Use-after-free Attacks?
Can We Prevent Use-after-free Attacks?
 
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
App secforum2014 andrivet-cplusplus11-metaprogramming_applied_to_software_obf...
 
There is more to C
There is more to CThere is more to C
There is more to C
 
Kernel Recipes 2015: Anatomy of an atomic KMS driver
Kernel Recipes 2015: Anatomy of an atomic KMS driverKernel Recipes 2015: Anatomy of an atomic KMS driver
Kernel Recipes 2015: Anatomy of an atomic KMS driver
 
Compromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging MechanismsCompromising Linux Virtual Machines with Debugging Mechanisms
Compromising Linux Virtual Machines with Debugging Mechanisms
 
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershellCSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
 
Tegra 186のu-boot & Linux
Tegra 186のu-boot & LinuxTegra 186のu-boot & Linux
Tegra 186のu-boot & Linux
 
How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageable
 
Specializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network StackSpecializing the Data Path - Hooking into the Linux Network Stack
Specializing the Data Path - Hooking into the Linux Network Stack
 
Kernel crashdump
Kernel crashdumpKernel crashdump
Kernel crashdump
 
Intel Nervana Graph とは?
Intel Nervana Graph とは?Intel Nervana Graph とは?
Intel Nervana Graph とは?
 
Linux Kernel Crashdump
Linux Kernel CrashdumpLinux Kernel Crashdump
Linux Kernel Crashdump
 
[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection[Defcon24] Introduction to the Witchcraft Compiler Collection
[Defcon24] Introduction to the Witchcraft Compiler Collection
 
Reverse engineering Swisscom's Centro Grande Modem
Reverse engineering Swisscom's Centro Grande ModemReverse engineering Swisscom's Centro Grande Modem
Reverse engineering Swisscom's Centro Grande Modem
 
[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis[CCC-28c3] Post Memory Corruption Memory Analysis
[CCC-28c3] Post Memory Corruption Memory Analysis
 
44CON London - Attacking VxWorks: from Stone Age to Interstellar
44CON London - Attacking VxWorks: from Stone Age to Interstellar44CON London - Attacking VxWorks: from Stone Age to Interstellar
44CON London - Attacking VxWorks: from Stone Age to Interstellar
 
Статический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDLСтатический анализ кода в контексте SSDL
Статический анализ кода в контексте SSDL
 
QEMU - Binary Translation
QEMU - Binary Translation QEMU - Binary Translation
QEMU - Binary Translation
 
Zn task - defcon russia 20
Zn task  - defcon russia 20Zn task  - defcon russia 20
Zn task - defcon russia 20
 
The origin: Init (compact version)
The origin: Init (compact version)The origin: Init (compact version)
The origin: Init (compact version)
 

Similar a Ищем уязвимости нулевого дня в ядре Linux

44 con slides
44 con slides44 con slides
44 con slides
geeksec80
 
44 con slides (1)
44 con slides (1)44 con slides (1)
44 con slides (1)
geeksec80
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
Kernel TLV
 
Go Native : Squeeze the juice out of your 64-bit processor using C++
Go Native : Squeeze the juice out of your 64-bit processor using C++Go Native : Squeeze the juice out of your 64-bit processor using C++
Go Native : Squeeze the juice out of your 64-bit processor using C++
Fernando Moreira
 

Similar a Ищем уязвимости нулевого дня в ядре Linux (20)

Linux seccomp(2) vs OpenBSD pledge(2)
Linux seccomp(2) vs OpenBSD pledge(2)Linux seccomp(2) vs OpenBSD pledge(2)
Linux seccomp(2) vs OpenBSD pledge(2)
 
Programar para GPUs
Programar para GPUsProgramar para GPUs
Programar para GPUs
 
44 con slides
44 con slides44 con slides
44 con slides
 
44 con slides (1)
44 con slides (1)44 con slides (1)
44 con slides (1)
 
Compiler basics: lisp to assembly
Compiler basics: lisp to assemblyCompiler basics: lisp to assembly
Compiler basics: lisp to assembly
 
Scylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them All
Scylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them AllScylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them All
Scylla Summit 2022: ScyllaDB Rust Driver: One Driver to Rule Them All
 
r2con 2017 r2cLEMENCy
r2con 2017 r2cLEMENCyr2con 2017 r2cLEMENCy
r2con 2017 r2cLEMENCy
 
Golang
GolangGolang
Golang
 
Linux device drivers
Linux device drivers Linux device drivers
Linux device drivers
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 
Gpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cudaGpu workshop cluster universe: scripting cuda
Gpu workshop cluster universe: scripting cuda
 
Go Native : Squeeze the juice out of your 64-bit processor using C++
Go Native : Squeeze the juice out of your 64-bit processor using C++Go Native : Squeeze the juice out of your 64-bit processor using C++
Go Native : Squeeze the juice out of your 64-bit processor using C++
 
Querying 1.8 billion reddit comments with python
Querying 1.8 billion reddit comments with pythonQuerying 1.8 billion reddit comments with python
Querying 1.8 billion reddit comments with python
 
NSC #2 - Challenge Solution
NSC #2 - Challenge SolutionNSC #2 - Challenge Solution
NSC #2 - Challenge Solution
 
Cryptography and secure systems
Cryptography and secure systemsCryptography and secure systems
Cryptography and secure systems
 
Introduction to Docker (as presented at December 2013 Global Hackathon)
Introduction to Docker (as presented at December 2013 Global Hackathon)Introduction to Docker (as presented at December 2013 Global Hackathon)
Introduction to Docker (as presented at December 2013 Global Hackathon)
 
Oczyszczacz powietrza i stos sieciowy? Czas na test! Semihalf Barcamp 13/06/2018
Oczyszczacz powietrza i stos sieciowy? Czas na test! Semihalf Barcamp 13/06/2018Oczyszczacz powietrza i stos sieciowy? Czas na test! Semihalf Barcamp 13/06/2018
Oczyszczacz powietrza i stos sieciowy? Czas na test! Semihalf Barcamp 13/06/2018
 
Hardware Open Source
Hardware Open SourceHardware Open Source
Hardware Open Source
 
44CON 2013 - Browser bug hunting - Memoirs of a last man standing - Atte Kett...
44CON 2013 - Browser bug hunting - Memoirs of a last man standing - Atte Kett...44CON 2013 - Browser bug hunting - Memoirs of a last man standing - Atte Kett...
44CON 2013 - Browser bug hunting - Memoirs of a last man standing - Atte Kett...
 
Linux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloudLinux kernel tracing superpowers in the cloud
Linux kernel tracing superpowers in the cloud
 

Más de Positive Hack Days

Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»
Positive Hack Days
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложений
Positive Hack Days
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Positive Hack Days
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET Core
Positive Hack Days
 

Más de Positive Hack Days (20)

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release Notes
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows Docker
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive Technologies
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + Qlik
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQube
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps Community
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для Approof
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложений
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложений
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application Security
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 лет
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПО
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке Си
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET Core
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опыт
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services Center
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атаки
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

Ищем уязвимости нулевого дня в ядре Linux

  • 1. How to find 0days in the Linux kernel Andrey Konovalov <andreyknvl@google.com> PHDays 2017 May 23-24th 2017
  • 2. Userspace tools ● AddressSanitizer, ThreadSanitizer, MemorySanitizer, ... ○ C/C++/Go bug detectors ○ Detect wide range of bug types (use-after-frees and out-of-bounds, data races and deadlocks, uninitialized memory uses, undefined behaviors) ○ Built into Clang, GCC and Go compiler ● libFuzzer ○ In-process coverage-guided fuzzing engine for C/C++ ● oss-fuzz ○ Continuous fuzzing service for open source software
  • 3. Finding bugs in the Linux kernel Dynamic bug finding tools: ● Bug detectors ● Fuzzers
  • 5. Kernel Sanitizers ● KASAN (use-after-frees and out-of-bounds) ○ CONFIG_KASAN available upstream since 4.0 ● KTSAN (data-races and deadlocks) ○ prototype available at https://github.com/google/ktsan ● KMSAN (uninitialized-memory-use) ○ prototype available at https://github.com/google/kmsan
  • 6. KASAN report BUG: KASAN: use-after-free in sctp_id2assoc+0x3a3/0x3b0 net/sctp/socket.c:224 Read of size 8 at addr ffff8800385b6838 by task syz-executor2/5889 Call Trace: sctp_id2assoc+0x3a3/0x3b0 net/sctp/socket.c:224 sctp_setsockopt_rtoinfo net/sctp/socket.c:2931 [inline] sctp_setsockopt+0x4b7/0x60f0 net/sctp/socket.c:4018 sock_common_setsockopt+0x95/0xd0 net/core/sock.c:2850 SYSC_setsockopt net/socket.c:1798 [inline] SyS_setsockopt+0x270/0x3a0 net/socket.c:1777 entry_SYSCALL_64_fastpath+0x1f/0xbe
  • 7. KASAN report Allocated by task 5841: kzalloc include/linux/slab.h:663 [inline] sctp_association_new+0x114/0x2180 net/sctp/associola.c:309 ... SyS_connect+0x24/0x30 net/socket.c:1569 entry_SYSCALL_64_fastpath+0x1f/0xbe Freed by task 5882: kfree+0xe8/0x2b0 mm/slub.c:3882 sctp_association_destroy net/sctp/associola.c:435 [inline] ... syscall_return_slowpath+0x3ba/0x410 arch/x86/entry/common.c:263 entry_SYSCALL_64_fastpath+0xbc/0xbe
  • 9. syzkaller ● Coverage-guided syscall fuzzer for the Linux kernel ● As of now found over 400 bugs (https://github.com/google/syzkaller/wiki/Found-Bugs) ● Over 25 CVEs ● At least 3 public local privilege escalation bugs over the last few months (CVE-2017-7308, CVE-2017-6074, CVE-2017-2636) ● Can generate C reproducers for found bugs
  • 10. Coverage-guided fuzzing (Think AFL or libFuzzer) void TestOneInput(const char *data, int size) { /* do something with data */ } Fuzzer invokes the function with different inputs Code coverage guiding: ● Corpus of “interesting” inputs ● Mutate and execute inputs from corpus ● If inputs gives new coverage, add it to corpus
  • 12. Syscall descriptions open(file filename, flags flags[open_flags], mode flags[open_mode]) fd read(fd fd, buf buffer[out], count len[buf]) close(fd fd) open_flags = O_RDONLY, O_WRONLY, O_RDWR, O_APPEND ...
  • 13. Syscall descriptions: discriminated syscalls socket$inet_tcp( domain const[AF_INET], type const[SOCK_STREAM], proto const[0]) sock_tcp socket$packet( domain const[AF_PACKET], type flags[packet_socket_type], proto const[ETH_P_ALL_BE]) sock_packet
  • 14. Syscall descriptions: structs layout sockaddr_ll { sll_family const[AF_PACKET, int16] sll_protocol flags[packet_protocols, int16be] sll_ifindex ifindex sll_hatype const[ARPHRD_ETHER, int16] sll_pkttype int8 sll_halen const[6, int8] sll_addr mac_addr pad array[const[0, int8], 2] } bind$packet(fd sock_packet, addr ptr[in, sockaddr_ll], addrlen len[addr])
  • 15. Syscall descriptions: resources resource sock[fd] socket(domain flags[socket_domain], type flags[socket_type], proto int8) sock bind(fd sock, addr ptr[in, sockaddr_storage], addrlen len[addr]) resource sock_packet[sock] socket$packet(domain const[AF_PACKET], type flags[packet_socket_type], proto const[ETH_P_ALL_BE]) sock_packet bind$packet(fd sock_packet, addr ptr[in, sockaddr_ll], addrlen len[addr])
  • 16. Programs The description allows to generate and mutate "programs" in the following form: mmap(&(0x7f0000000000), (0x1000), 0x3, 0x32, -1, 0) r0 = open(&(0x7f0000000000)="./file0", 0x3, 0x9) read(r0, &(0x7f0000000000), 42) close(r0)
  • 17. Algorithm 1. Start with empty corpus of programs 2. Generate a new program, or choose an existing program from corpus and mutate it 3. Interpret the program, collect coverage 4. If a syscall covers code that wasn't covered previously, minimize program and add to corpus 5. Goto 1
  • 18. External kernel inputs Kernel Userspace syscalls network ... USB TUN/TAP gadgetfs / functionfs
  • 19. Demo
  • 20. Finding 0days in the Linux kernel 1. Setup syzkaller 2. Write syscall descriptions for some previously untested kernel interface 3. Specify syscalls required to interact with this interface in the configuration file 4. Run syzkaller and discover bugs
  • 23. Coverage for the Linux kernel ● Available upstream with CONFIG_KCOV ● GCC pass that inserts a function call into every basic block ● kernel debugfs extension that collects and exposes coverage per-thread __fuzz_coverage(); if (...) { __fuzz_coverage(); ... } __fuzz_coverage(); if (...) { ... }
  • 25. Kernel system call fuzzers ● Trinity (https://github.com/kernelslacker/trinity) ● syzkaller (https://github.com/google/syzkaller)
  • 26. Other Linux kernel fuzzers ● https://github.com/oracle/kernel-fuzzing ● https://github.com/nccgroup/TriforceLinuxSyscallFuzzer ● http://web.eece.maine.edu/~vweaver/projects/perf_events/f uzzer/ ● https://github.com/schumilo/vUSBf
  • 27. External Stimulus Systems calls and external stimulus in the same program: listen(r0) emit_ethernet(syn) emit_ethernet(ack) r1 = accept(r0) emit_ethernet(data) read(r1) emit_ethernet(rst) Work in progress; also applicable to USB, ...
  • 28. Existing system call fuzzers Trinity in essence: syscall(rand(), rand(), rand()); Knows argument types, so more like: syscall(rand(), rand_fd(), rand_addr()); ● Tend to find shallow bugs ● Frequently no reproducers