SlideShare a Scribd company logo
6
Most read
7
Most read
9
Most read
McAfee Confidential—Internal Use Only
Secure Coding in C/C++
A technical perspective
September 25, 2013
Dan-Claudiu Dragoș
Software Development Engineer
What will we cover today:
• Software vulnerabilities: who and why?
• String and buffer overflows
• Pointer vulnerabilities
• Dynamic memory management
• Format strings (printf)
• Integer values
• Concurrency
• File I/O
McAfee Confidential—Internal Use Only
Software vulnerabilities: who and why?
3
• Script kiddies or illiterate cybercriminals do not find vulnerabilities:
• … they simply use them for profit or fame
• Vulnerabilities are found by security experts
• They may be working for McAfee or for the government of Elbonia
• … this is not a non profit activity!
• These experts can set up environments similar to yours
• They have a deep understanding of the system architecture
• They have access to the same tools as you do
» … including debuggers!
» … or even to the source code!
• They practice the attacks in controlled environments before going live.
McAfee Confidential—Internal Use Only
Software vulnerabilities: what to do?
4
• There is no magic recipe!
• The approach should be proactive, not reactive
» … it’s like pipe work when fixing leaks
• There are some good development practices
» … do’s and don’ts
• There is also some external help:
• Modern compilers may reorder parameters on stack or apply
optimizations
• Modern operating systems may use memory randomization
• Modern CPUs have “execute disable” flags
McAfee Confidential—Internal Use Only
Software vulnerabilities: Buffers
5
• Unbounded buffer operations are the recipe for disaster
– Never use:
• API functions that populate buffers without taking sizes
• C-String operations without allowing for buffer size!
• Array iterations without checking for bounds
• Unsafe functions marked as such in the documentation
– Do not rely on your own canary values, let the compiler do its job!
– During development:
• Build the source code with a debug library with strict bounds checking
• Use static analysis software (Coverity)
• Run the software through a dynamic analyser (Purify)
McAfee Confidential—Internal Use Only
Software vulnerabilities: Buffers
6
• Design patterns to keep in mind:
• Allocating memory for the use of (external) API functions is unsafe!
» On Linux the ELF dynamic linking table can be exploited
» Windows approach on using DLLs is safe
GNU libc (unsafe) GNU libc (safer) C++ STL (safest)
Caller allocates Calee allocates Callee allocates
Callee initializes
Caller uses
Caller frees Caller frees Callee frees
McAfee Confidential—Internal Use Only
Software vulnerabilities: Pointers
7
• Function pointers are dangerous!
– An attacker may modify the memory and use such pointer as a trampoline
to their own shell code
• C++ polymorphic approach is much safer
• Always initialize and set the pointers to NULL after use
– NULL pointers may point to valid memory on some architectures
• Linux platforms: running the program through valgrind may help
identify potential issues
– the attacker may very likely do this in search of vulnerabilities!
McAfee Confidential—Internal Use Only
Software vulnerabilities: Memory
8
• Never use buffer sizes based only on user input
» …argv[] elements can be empty strings!
» …including argv[0]
• Do not use malloc(0), the behaviour is undefined
• Always check the result of memory allocation (and handle the error)
• Always use the proper call pairs:
• new – delete
• malloc – free
• new[] – delete[]
• placement new – explicit destructor call
McAfee Confidential—Internal Use Only
Software vulnerabilities: Format strings
9
• Variadic functions such as printf are dangerous
• the C standard does not provide a reliable way to determine the call
argument count
• these functions must rely on the caller to provide the proper format, the
right number of arguments and the proper argument types
• If the format string contains unparsed user input, this is an exploit
invitation:
» the attacker can trigger reading arbitrary data from the stack
» the %n format specifier causes data to be written!
» specially crafted format strings can cause data to be written to
arbitrary memory locations!
• Localization code is a prime target for these attacks
McAfee Confidential—Internal Use Only
Software vulnerabilities: Integers
10
xkcd clipart released under Creative Commons license
McAfee Confidential—Internal Use Only
Software vulnerabilities: Integers
11
• C language defines multiple integer types and default conversions
• Integer values are prone to overflow
• Don’t:
• design your code with a certain architecture in mind
• forget that the safe storage of the multiplication result requires twice
the size of the largest argument
• mix signed and unsigned types
• forget about LSB/MSB or the negative numbers
• Do:
• check for bounds on any integer value received from the user
• test the code thoroughly on all relevant architectures
McAfee Confidential—Internal Use Only
Software vulnerabilities: Concurrency
12
• The concurrency issues do not usually result in privilege escalation
» …they are mostly used for denial of service
• An attacker may only want to get your system to an undefined state
» …but this is also a job for the QA!
• Always be on the look for:
• scalability issues
• race conditions
• deadlocks
• starvation and live locks
McAfee Confidential—Internal Use Only
Software vulnerabilities: File I/O
13
• Referring files by names is unsafe by design
• on Linux the race window between stat() and open() cannot be
(cleanly) avoided
• an attacker may replace the file in this race window
• The prime target for these attacks are the setuid() programs
• Mitigation strategies:
• use canonical names / paths, do not trust the user input
• perform all the operations with the lowest required privileges / drop
super user privileges when they are no longer required
• check that the file operation is not performed on a symlinked file
• the admin must ensure that no hard links are possible between user
files and system files
McAfee Confidential—Internal Use Only
Software vulnerabilities:
14
• Questions?
Secure Coding in C/C++

More Related Content

What's hot (20)

PPTX
malware analysis
20CS201AkashR
 
PDF
Hunting Lateral Movement in Windows Infrastructure
Sergey Soldatov
 
PDF
Hunting fileless malware
Olha Pasko
 
PPTX
Introduction To Exploitation & Metasploit
Raghav Bisht
 
PPTX
User authentication
CAS
 
PDF
No Easy Breach DerbyCon 2016
Matthew Dunwoody
 
PPT
6 buffer overflows
drewz lin
 
PDF
How fun of privilege escalation Red Pill2017
Ammarit Thongthua ,CISSP CISM GXPN CSSLP CCNP
 
PDF
Getting started with Android pentesting
Minali Arora
 
PPTX
How To Improve Quality With Static Code Analysis
Perforce
 
PPTX
Security Testing
Qualitest
 
PDF
How to Hunt for Lateral Movement on Your Network
Sqrrl
 
PDF
PHDays 2018 Threat Hunting Hands-On Lab
Teymur Kheirkhabarov
 
PPT
Practical Malware Analysis: Ch 7: Analyzing Malicious Windows Programs
Sam Bowne
 
PDF
Windows attacks - AT is the new black
Chris Gates
 
PPTX
Introduction to Malware Analysis
Andrew McNicol
 
PPTX
Practical Malware Analysis: Ch 4 A Crash Course in x86 Disassembly
Sam Bowne
 
PPTX
Password cracking and brute force
vishalgohel12195
 
malware analysis
20CS201AkashR
 
Hunting Lateral Movement in Windows Infrastructure
Sergey Soldatov
 
Hunting fileless malware
Olha Pasko
 
Introduction To Exploitation & Metasploit
Raghav Bisht
 
User authentication
CAS
 
No Easy Breach DerbyCon 2016
Matthew Dunwoody
 
6 buffer overflows
drewz lin
 
How fun of privilege escalation Red Pill2017
Ammarit Thongthua ,CISSP CISM GXPN CSSLP CCNP
 
Getting started with Android pentesting
Minali Arora
 
How To Improve Quality With Static Code Analysis
Perforce
 
Security Testing
Qualitest
 
How to Hunt for Lateral Movement on Your Network
Sqrrl
 
PHDays 2018 Threat Hunting Hands-On Lab
Teymur Kheirkhabarov
 
Practical Malware Analysis: Ch 7: Analyzing Malicious Windows Programs
Sam Bowne
 
Windows attacks - AT is the new black
Chris Gates
 
Introduction to Malware Analysis
Andrew McNicol
 
Practical Malware Analysis: Ch 4 A Crash Course in x86 Disassembly
Sam Bowne
 
Password cracking and brute force
vishalgohel12195
 

Viewers also liked (13)

PPTX
Library Management System Project in C
codewithc
 
PPTX
Philosophy and Strategy for Technology - 2013 Feb 8 VSB ICT Advisory Committe...
Brian Kuhn
 
PPTX
Framework IAM
Raymond Bronzwaer
 
DOCX
Установка_межкомнатных_дверей_инструкция
specdveri
 
PPTX
June 18th
Esmeralda Sisa Nobsa
 
PPTX
Vocabulary instruction june 24th
Esmeralda Sisa Nobsa
 
PPT
Думаете о будущем?
april15alina
 
PDF
Defining Security Intelligence for the Enterprise - What CISOs Need to Know
IBM Security
 
PDF
Download part two families on the front line report
Family and Childcare Trust
 
PPSX
Event Management by Redefine SEL_Offsite
Redefine
 
PPT
Variability of Coal Mine Drainage in Pennsylvania Resulting from Coal Mining ...
Michael Hewitt, GISP
 
DOCX
Escritorio ana 101
anita_guzman
 
PDF
Volaris Corporate Presentation November 2016
irvolaris
 
Library Management System Project in C
codewithc
 
Philosophy and Strategy for Technology - 2013 Feb 8 VSB ICT Advisory Committe...
Brian Kuhn
 
Framework IAM
Raymond Bronzwaer
 
Установка_межкомнатных_дверей_инструкция
specdveri
 
Vocabulary instruction june 24th
Esmeralda Sisa Nobsa
 
Думаете о будущем?
april15alina
 
Defining Security Intelligence for the Enterprise - What CISOs Need to Know
IBM Security
 
Download part two families on the front line report
Family and Childcare Trust
 
Event Management by Redefine SEL_Offsite
Redefine
 
Variability of Coal Mine Drainage in Pennsylvania Resulting from Coal Mining ...
Michael Hewitt, GISP
 
Escritorio ana 101
anita_guzman
 
Volaris Corporate Presentation November 2016
irvolaris
 
Ad

Similar to Secure Coding in C/C++ (20)

PPT
Software security
Roman Oliynykov
 
PPTX
20101017 program analysis_for_security_livshits_lecture03_security
Computer Science Club
 
PDF
Secure coding-guidelines
Trupti Shiralkar, CISSP
 
PDF
Insecure coding in C (and C++)
Olve Maudal
 
PPT
When good code goes bad
SensePost
 
DOCX
What
anity
 
PDF
Secure Coding Practices for Middleware
Manuel Brugnoli
 
PPT
Buffer Overflow Attacks
harshal kshatriya
 
PPTX
antoanthongtin_Lesson 3- Software Security (1).pptx
23162024
 
PDF
Software Security
Roman Oliynykov
 
PPT
Secure programming - Computer and Network Security
ssuser30902e
 
PPT
Testingfor Sw Security
ankitmehta21
 
PDF
CNIT 127: Ch 18: Source Code Auditing
Sam Bowne
 
PDF
AllBits presentation - Lower Level SW Security
AllBits BVBA (freelancer)
 
PPTX
Control hijacking
Prachi Gulihar
 
PPTX
Vulnerability, exploit to metasploit
Tiago Henriques
 
PDF
Ch 18: Source Code Auditing
Sam Bowne
 
PPTX
Safe and secure programming practices for embedded devices
Soumitra Bhattacharyya
 
PPTX
Stack-Based Buffer Overflows
Daniel Tumser
 
Software security
Roman Oliynykov
 
20101017 program analysis_for_security_livshits_lecture03_security
Computer Science Club
 
Secure coding-guidelines
Trupti Shiralkar, CISSP
 
Insecure coding in C (and C++)
Olve Maudal
 
When good code goes bad
SensePost
 
What
anity
 
Secure Coding Practices for Middleware
Manuel Brugnoli
 
Buffer Overflow Attacks
harshal kshatriya
 
antoanthongtin_Lesson 3- Software Security (1).pptx
23162024
 
Software Security
Roman Oliynykov
 
Secure programming - Computer and Network Security
ssuser30902e
 
Testingfor Sw Security
ankitmehta21
 
CNIT 127: Ch 18: Source Code Auditing
Sam Bowne
 
AllBits presentation - Lower Level SW Security
AllBits BVBA (freelancer)
 
Control hijacking
Prachi Gulihar
 
Vulnerability, exploit to metasploit
Tiago Henriques
 
Ch 18: Source Code Auditing
Sam Bowne
 
Safe and secure programming practices for embedded devices
Soumitra Bhattacharyya
 
Stack-Based Buffer Overflows
Daniel Tumser
 
Ad

Recently uploaded (20)

PDF
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
PDF
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
PPTX
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
 
PDF
Cloud computing Lec 02 - virtualization.pdf
asokawennawatte
 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
PDF
Rewards and Recognition (2).pdf
ethan Talor
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
PDF
Building scalbale cloud native apps with .NET 8
GillesMathieu10
 
PDF
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
PPTX
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
PDF
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
 
PPTX
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
PDF
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
PPTX
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
 
PDF
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
PDF
LPS25 - Operationalizing MLOps in GEP - Terradue.pdf
terradue
 
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
 
Cloud computing Lec 02 - virtualization.pdf
asokawennawatte
 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
Rewards and Recognition (2).pdf
ethan Talor
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
Building scalbale cloud native apps with .NET 8
GillesMathieu10
 
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
 
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
 
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
LPS25 - Operationalizing MLOps in GEP - Terradue.pdf
terradue
 

Secure Coding in C/C++

  • 1. McAfee Confidential—Internal Use Only Secure Coding in C/C++ A technical perspective September 25, 2013 Dan-Claudiu Dragoș Software Development Engineer
  • 2. What will we cover today: • Software vulnerabilities: who and why? • String and buffer overflows • Pointer vulnerabilities • Dynamic memory management • Format strings (printf) • Integer values • Concurrency • File I/O
  • 3. McAfee Confidential—Internal Use Only Software vulnerabilities: who and why? 3 • Script kiddies or illiterate cybercriminals do not find vulnerabilities: • … they simply use them for profit or fame • Vulnerabilities are found by security experts • They may be working for McAfee or for the government of Elbonia • … this is not a non profit activity! • These experts can set up environments similar to yours • They have a deep understanding of the system architecture • They have access to the same tools as you do » … including debuggers! » … or even to the source code! • They practice the attacks in controlled environments before going live.
  • 4. McAfee Confidential—Internal Use Only Software vulnerabilities: what to do? 4 • There is no magic recipe! • The approach should be proactive, not reactive » … it’s like pipe work when fixing leaks • There are some good development practices » … do’s and don’ts • There is also some external help: • Modern compilers may reorder parameters on stack or apply optimizations • Modern operating systems may use memory randomization • Modern CPUs have “execute disable” flags
  • 5. McAfee Confidential—Internal Use Only Software vulnerabilities: Buffers 5 • Unbounded buffer operations are the recipe for disaster – Never use: • API functions that populate buffers without taking sizes • C-String operations without allowing for buffer size! • Array iterations without checking for bounds • Unsafe functions marked as such in the documentation – Do not rely on your own canary values, let the compiler do its job! – During development: • Build the source code with a debug library with strict bounds checking • Use static analysis software (Coverity) • Run the software through a dynamic analyser (Purify)
  • 6. McAfee Confidential—Internal Use Only Software vulnerabilities: Buffers 6 • Design patterns to keep in mind: • Allocating memory for the use of (external) API functions is unsafe! » On Linux the ELF dynamic linking table can be exploited » Windows approach on using DLLs is safe GNU libc (unsafe) GNU libc (safer) C++ STL (safest) Caller allocates Calee allocates Callee allocates Callee initializes Caller uses Caller frees Caller frees Callee frees
  • 7. McAfee Confidential—Internal Use Only Software vulnerabilities: Pointers 7 • Function pointers are dangerous! – An attacker may modify the memory and use such pointer as a trampoline to their own shell code • C++ polymorphic approach is much safer • Always initialize and set the pointers to NULL after use – NULL pointers may point to valid memory on some architectures • Linux platforms: running the program through valgrind may help identify potential issues – the attacker may very likely do this in search of vulnerabilities!
  • 8. McAfee Confidential—Internal Use Only Software vulnerabilities: Memory 8 • Never use buffer sizes based only on user input » …argv[] elements can be empty strings! » …including argv[0] • Do not use malloc(0), the behaviour is undefined • Always check the result of memory allocation (and handle the error) • Always use the proper call pairs: • new – delete • malloc – free • new[] – delete[] • placement new – explicit destructor call
  • 9. McAfee Confidential—Internal Use Only Software vulnerabilities: Format strings 9 • Variadic functions such as printf are dangerous • the C standard does not provide a reliable way to determine the call argument count • these functions must rely on the caller to provide the proper format, the right number of arguments and the proper argument types • If the format string contains unparsed user input, this is an exploit invitation: » the attacker can trigger reading arbitrary data from the stack » the %n format specifier causes data to be written! » specially crafted format strings can cause data to be written to arbitrary memory locations! • Localization code is a prime target for these attacks
  • 10. McAfee Confidential—Internal Use Only Software vulnerabilities: Integers 10 xkcd clipart released under Creative Commons license
  • 11. McAfee Confidential—Internal Use Only Software vulnerabilities: Integers 11 • C language defines multiple integer types and default conversions • Integer values are prone to overflow • Don’t: • design your code with a certain architecture in mind • forget that the safe storage of the multiplication result requires twice the size of the largest argument • mix signed and unsigned types • forget about LSB/MSB or the negative numbers • Do: • check for bounds on any integer value received from the user • test the code thoroughly on all relevant architectures
  • 12. McAfee Confidential—Internal Use Only Software vulnerabilities: Concurrency 12 • The concurrency issues do not usually result in privilege escalation » …they are mostly used for denial of service • An attacker may only want to get your system to an undefined state » …but this is also a job for the QA! • Always be on the look for: • scalability issues • race conditions • deadlocks • starvation and live locks
  • 13. McAfee Confidential—Internal Use Only Software vulnerabilities: File I/O 13 • Referring files by names is unsafe by design • on Linux the race window between stat() and open() cannot be (cleanly) avoided • an attacker may replace the file in this race window • The prime target for these attacks are the setuid() programs • Mitigation strategies: • use canonical names / paths, do not trust the user input • perform all the operations with the lowest required privileges / drop super user privileges when they are no longer required • check that the file operation is not performed on a symlinked file • the admin must ensure that no hard links are possible between user files and system files
  • 14. McAfee Confidential—Internal Use Only Software vulnerabilities: 14 • Questions?