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

PPTX
Metasploit framework in Network Security
PPTX
OWASP Top 10 2021 What's New
PDF
Web Application Penetration Testing
PPTX
Best practices for ansible
PPT
Secure code practices
PDF
Automation with ansible
PDF
OWASP Top 10 Web Application Vulnerabilities
PDF
IPS (intrusion prevention system)
Metasploit framework in Network Security
OWASP Top 10 2021 What's New
Web Application Penetration Testing
Best practices for ansible
Secure code practices
Automation with ansible
OWASP Top 10 Web Application Vulnerabilities
IPS (intrusion prevention system)

What's hot (20)

PDF
The Measure of Success: Security Metrics to Tell Your Story
PDF
Ekoparty 2017 - The Bug Hunter's Methodology
PDF
Pentest with Metasploit
PDF
Ansible - Hands on Training
PDF
A'dan Z'ye | Social Engineer Toolkit (SET)
PDF
Mobile Application Security
PDF
A Threat Hunter Himself
PDF
Windows Threat Hunting
PDF
Introduction to burp suite
PDF
OWASP Mobile Top 10 Deep-Dive
PDF
Ansible Introduction
PPTX
OWASP Top 10 2021 Presentation (Jul 2022)
PDF
Ansible
PDF
Shell scripting
PPTX
Introduction to Docker - 2017
PDF
Spring Boot on Amazon Web Services with Spring Cloud AWS
PDF
Hunting Lateral Movement in Windows Infrastructure
PPTX
Integrated Tools in OSSIM
PPTX
Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...
PPTX
Vulnerability Assesment
The Measure of Success: Security Metrics to Tell Your Story
Ekoparty 2017 - The Bug Hunter's Methodology
Pentest with Metasploit
Ansible - Hands on Training
A'dan Z'ye | Social Engineer Toolkit (SET)
Mobile Application Security
A Threat Hunter Himself
Windows Threat Hunting
Introduction to burp suite
OWASP Mobile Top 10 Deep-Dive
Ansible Introduction
OWASP Top 10 2021 Presentation (Jul 2022)
Ansible
Shell scripting
Introduction to Docker - 2017
Spring Boot on Amazon Web Services with Spring Cloud AWS
Hunting Lateral Movement in Windows Infrastructure
Integrated Tools in OSSIM
Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...
Vulnerability Assesment
Ad

Viewers also liked (13)

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

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

PDF
DEF CON 27 - CHRISTOPHER ROBERTS - firmware slap
PPTX
The Psychology of C# Analysis
PPTX
Capability Building for Cyber Defense: Software Walk through and Screening
PDF
CNIT 127: Ch 18: Source Code Auditing
PDF
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
PPT
Code Quality - Security
PPTX
Programming languages and techniques for today’s embedded andIoT world
PPTX
Static-Analysis-in-Industry.pptx
PPTX
Static Analysis Primer
PDF
JS-Experts - Cybersecurity for Generative AI
PPTX
Software Security
PPTX
chap-1 : Vulnerabilities in Information Systems
PPTX
Vulnerability, exploit to metasploit
PPTX
Software Protection Techniques
PDF
Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...
PDF
Ch 18: Source Code Auditing
PDF
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
PDF
Piratng Avs to bypass exploit mitigation
PDF
RIoT (Raiding Internet of Things) by Jacob Holcomb
PPT
10290057.ppt
DEF CON 27 - CHRISTOPHER ROBERTS - firmware slap
The Psychology of C# Analysis
Capability Building for Cyber Defense: Software Walk through and Screening
CNIT 127: Ch 18: Source Code Auditing
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
Code Quality - Security
Programming languages and techniques for today’s embedded andIoT world
Static-Analysis-in-Industry.pptx
Static Analysis Primer
JS-Experts - Cybersecurity for Generative AI
Software Security
chap-1 : Vulnerabilities in Information Systems
Vulnerability, exploit to metasploit
Software Protection Techniques
Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...
Ch 18: Source Code Auditing
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
Piratng Avs to bypass exploit mitigation
RIoT (Raiding Internet of Things) by Jacob Holcomb
10290057.ppt

Recently uploaded (20)

PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
System and Network Administraation Chapter 3
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
System and Network Administration Chapter 2
PDF
Designing Intelligence for the Shop Floor.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
Transform Your Business with a Software ERP System
PPTX
Introduction to Artificial Intelligence
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
medical staffing services at VALiNTRY
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
System and Network Administraation Chapter 3
Understanding Forklifts - TECH EHS Solution
Operating system designcfffgfgggggggvggggggggg
Softaken Excel to vCard Converter Software.pdf
Computer Software and OS of computer science of grade 11.pptx
Upgrade and Innovation Strategies for SAP ERP Customers
System and Network Administration Chapter 2
Designing Intelligence for the Shop Floor.pdf
Design an Analysis of Algorithms I-SECS-1021-03
Odoo Companies in India – Driving Business Transformation.pdf
Transform Your Business with a Software ERP System
Introduction to Artificial Intelligence
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Navsoft: AI-Powered Business Solutions & Custom Software Development
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
medical staffing services at VALiNTRY

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?