SlideShare a Scribd company logo
1 of 15
Download to read offline
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

What's hot (20)

Trusted Platform Module (TPM)
Trusted Platform Module (TPM)Trusted Platform Module (TPM)
Trusted Platform Module (TPM)
 
OWASP Secure Coding
OWASP Secure CodingOWASP Secure Coding
OWASP Secure Coding
 
Java Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug ClassJava Deserialization Vulnerabilities - The Forgotten Bug Class
Java Deserialization Vulnerabilities - The Forgotten Bug Class
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
Understanding Penetration Testing & its Benefits for Organization
Understanding Penetration Testing & its Benefits for OrganizationUnderstanding Penetration Testing & its Benefits for Organization
Understanding Penetration Testing & its Benefits for Organization
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
CNIT 127: Ch 18: Source Code Auditing
CNIT 127: Ch 18: Source Code AuditingCNIT 127: Ch 18: Source Code Auditing
CNIT 127: Ch 18: Source Code Auditing
 
2021 ZAP Automation in CI/CD
2021 ZAP Automation in CI/CD2021 ZAP Automation in CI/CD
2021 ZAP Automation in CI/CD
 
Physical security
Physical securityPhysical security
Physical security
 
Secure by Design - Security Design Principles for the Rest of Us
Secure by Design - Security Design Principles for the Rest of UsSecure by Design - Security Design Principles for the Rest of Us
Secure by Design - Security Design Principles for the Rest of Us
 
CNIT 123: Ch 3: Network and Computer Attacks
CNIT 123: Ch 3: Network and Computer AttacksCNIT 123: Ch 3: Network and Computer Attacks
CNIT 123: Ch 3: Network and Computer Attacks
 
OWASP Top 10 2021 Presentation (Jul 2022)
OWASP Top 10 2021 Presentation (Jul 2022)OWASP Top 10 2021 Presentation (Jul 2022)
OWASP Top 10 2021 Presentation (Jul 2022)
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Thick Application Penetration Testing: Crash Course
Thick Application Penetration Testing: Crash CourseThick Application Penetration Testing: Crash Course
Thick Application Penetration Testing: Crash Course
 
Fileless Malware Infections
Fileless Malware InfectionsFileless Malware Infections
Fileless Malware Infections
 
Reverse engineering & immunity debugger
Reverse engineering & immunity debuggerReverse engineering & immunity debugger
Reverse engineering & immunity debugger
 
OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's New
 
CNIT 127 Ch 1: Before you Begin
CNIT 127 Ch 1: Before you BeginCNIT 127 Ch 1: Before you Begin
CNIT 127 Ch 1: Before you Begin
 

Viewers also liked

Установка_межкомнатных_дверей_инструкция
Установка_межкомнатных_дверей_инструкцияУстановка_межкомнатных_дверей_инструкция
Установка_межкомнатных_дверей_инструкция
specdveri
 
Думаете о будущем?
Думаете о будущем? Думаете о будущем?
Думаете о будущем?
april15alina
 
Download part two families on the front line report
Download part two families on the front line reportDownload part two families on the front line report
Download part two families on the front line report
Family and Childcare Trust
 
Event Management by Redefine SEL_Offsite
Event Management by Redefine SEL_Offsite Event Management by Redefine SEL_Offsite
Event Management by Redefine SEL_Offsite
Redefine
 

Viewers also liked (13)

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

Similar to Secure Coding in C/C++

Static Analysis Primer
Static Analysis PrimerStatic Analysis Primer
Static Analysis Primer
Coverity
 
Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...
Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...
Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...
Denim Group
 

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

DEF CON 27 - CHRISTOPHER ROBERTS - firmware slap
DEF CON 27 - CHRISTOPHER ROBERTS - firmware slapDEF CON 27 - CHRISTOPHER ROBERTS - firmware slap
DEF CON 27 - CHRISTOPHER ROBERTS - firmware slap
 
The Psychology of C# Analysis
The Psychology of C# AnalysisThe Psychology of C# Analysis
The Psychology of C# Analysis
 
Capability Building for Cyber Defense: Software Walk through and Screening
Capability Building for Cyber Defense: Software Walk through and Screening Capability Building for Cyber Defense: Software Walk through and Screening
Capability Building for Cyber Defense: Software Walk through and Screening
 
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tipsDEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
DEF CON 27 - DIMITRY SNEZHKOV - zombie ant farm practical tips
 
Code Quality - Security
Code Quality - SecurityCode Quality - Security
Code Quality - Security
 
Programming languages and techniques for today’s embedded andIoT world
Programming languages and techniques for today’s embedded andIoT worldProgramming languages and techniques for today’s embedded andIoT world
Programming languages and techniques for today’s embedded andIoT world
 
Static-Analysis-in-Industry.pptx
Static-Analysis-in-Industry.pptxStatic-Analysis-in-Industry.pptx
Static-Analysis-in-Industry.pptx
 
Static Analysis Primer
Static Analysis PrimerStatic Analysis Primer
Static Analysis Primer
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AI
 
Software Security
Software SecuritySoftware Security
Software Security
 
black-box testing is a type of software testing in which the tester is not co...
black-box testing is a type of software testing in which the tester is not co...black-box testing is a type of software testing in which the tester is not co...
black-box testing is a type of software testing in which the tester is not co...
 
chap-1 : Vulnerabilities in Information Systems
chap-1 : Vulnerabilities in Information Systemschap-1 : Vulnerabilities in Information Systems
chap-1 : Vulnerabilities in Information Systems
 
Vulnerability, exploit to metasploit
Vulnerability, exploit to metasploitVulnerability, exploit to metasploit
Vulnerability, exploit to metasploit
 
Software Protection Techniques
Software Protection TechniquesSoftware Protection Techniques
Software Protection Techniques
 
Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...
Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...
Threat Modeling the CI/CD Pipeline to Improve Software Supply Chain Security ...
 
Ch 18: Source Code Auditing
Ch 18: Source Code AuditingCh 18: Source Code Auditing
Ch 18: Source Code Auditing
 
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit MitigationsCaptain Hook: Pirating AVs to Bypass Exploit Mitigations
Captain Hook: Pirating AVs to Bypass Exploit Mitigations
 
Piratng Avs to bypass exploit mitigation
Piratng Avs to bypass exploit mitigationPiratng Avs to bypass exploit mitigation
Piratng Avs to bypass exploit mitigation
 
RIoT (Raiding Internet of Things) by Jacob Holcomb
RIoT  (Raiding Internet of Things)  by Jacob HolcombRIoT  (Raiding Internet of Things)  by Jacob Holcomb
RIoT (Raiding Internet of Things) by Jacob Holcomb
 
10290057.ppt
10290057.ppt10290057.ppt
10290057.ppt
 

Recently uploaded

%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 

Recently uploaded (20)

%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 

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?