SlideShare une entreprise Scribd logo
1  sur  18
Writing (In)Secure Code
Leontin Bîrsan
Solution Architect
Thursday, 26 June 2014
Software’s Vulnerability to Attack
• What makes it so easy for attackers to target software
is the virtually guaranteed presence of vulnerabilities,
which can be exploited to violate one or more of the
software’s security properties
• Most successful attacks result from targeting and
exploiting known, non-patched software vulnerabilities
and insecure software configurations, many of which
are introduced during design and code
• Many successful attacks result from poor coding which
open the applications vulnerable to SQL injection,
buffer overflows etc.
When Is There a Threat?
The software’s security can be threatened:
• during its development:
– A developer may corrupt the software (intentionally or
unintentionally) in ways that will compromise the
software’s dependability and trustworthiness when it is
operational.
When Is There a Threat? (2)
The software’s security can be threatened:
• during its deployment (distribution and installation):
– If those responsible for distributing the software fail to
tamperproof the software before shipping or uploading,
or transmit it over easily intercepted communications
channels, they leave the software vulnerable to
intentional or unintentional corruption.
– Similarly, if the software’s installer fails to “lock down”
the host platform, or configures the software insecurely,
the software is left vulnerable to access by attackers.
When Is There a Threat? (3)
The software’s security can be threatened:
• during its operation:
– Once software has gone operational, vulnerabilities may be
discovered and publicized; unless security patches and
updates are applied and newer supported versions (from
which the root causes of vulnerabilities have been eliminated)
are adopted, such software will become increasingly
vulnerable.
– Any software system that runs on a network-connected
platform has its vulnerabilities exposed during its operation.
The level of exposure will vary depending on whether the
network is public or private, Internet-connected or not, and
whether the software’s environment has been configured to
minimize its exposure.
– But even in highly controlled networks and “locked down”
environments, the software may be threatened by malicious
insiders (users, administrators, etc.).
When Is There a Threat? (4)
The software’s security can be threatened:
• during its maintenance:
– If those responsible for addressing discovered
vulnerabilities in released software fail to issue patches
or updates in a timely manner, or fail to seek out and
eliminate the root causes of the vulnerabilities to prevent
their perpetuation in future releases of the software, the
software will become increasingly vulnerable to threats
over time.
– Also, the software’s maintainer may prove to be a
malicious insider, and may embed malicious code,
exploitable flaws, etc., in updated versions of the code.
The Challenge of Building Secure Software
• To be considered secure, software must exhibit three
properties:
– Dependability: Dependable software executes
predictably and operates correctly under all conditions,
including hostile conditions, including when the software
comes under attack or runs on a malicious host.
– Trustworthiness: Trustworthy software contains few (if
any) vulnerabilities or weaknesses that can be
intentionally exploited to subvert or sabotage the
software’s dependability. In addition, to be considered
trustworthy, the software must contain no malicious logic
that causes it to behave in a malicious manner.
The Challenge of Building Secure Software (2)
• To be considered secure, software must exhibit three
properties:
– Survivability (also referred to as “Resilience”):
Survivable (or resilient) software is software that is
resilient enough to
• (1) either resist (i.e., protect itself against) or tolerate (i.e.,
continue operating dependably in spite of) most known
attacks plus as many novel attacks as possible, and
• (2) recover as quickly as possible, and with as little
damage as possible, from those attacks that it can neither
resist nor tolerate.
Practical Example
How To Protect Code
In two words: Defensive Coding.
1. Never trust the user input and I do mean NEVER
– Trusting user input is a generally bad idea, as seen in
the examples we do open the application to various
attacks
– User input should be sanitized and validated, if not
done automatically by the framework (e.g. ASP.NET
MVC)
– Always perform basic tests over the input, such as
length and range
How To Protect Code (2)
2. Do not relay solely on client-side validation, re-
validate always on server-side
– Validating only on client side does not protect against
call injection which will bypass the protection
– JavaScript can be disabled in the browser options
disabling the validation
– Use framework built-in validation, e.g. for ASP.MVC use
data annotations such as [Required], [StringLength(10)],
[Range(10, 20)] etc. which will fire automatically on each
request, then use subsequently ModelState.IsValid to
check the validity of the request
How To Protect Code (3)
3. Never build SQL by means of concatenating
strings that contain user input. Always use
parameters.
– In general, building SQLs with “+” is a really bad idea
– However, in some cases, dynamic SQL must be built,
but it should not contain any user-generated content
– If dynamic SQL is to be created use a factory method or
class to contain the respective code in one place
– Such code must be reviewed for possible security issues
How To Protect Code (4)
4. Test parameters of the functions
– Test for NULL and allowed ranges and throw exceptions
if the validation fails
– If unit tests are built, test for the respective exceptions by
passing intentionally incorrect parameters and expecting
the exceptions
5. Prevent errors
– If an error is possible, no matter how probable, try to
prevent it
6. Fail Early And Openly
– Fail early, cleanly, and openly, stating what happened,
where and how to fix it
How To Protect Code (5)
7. Document Assumptions
– Clearly state the pre-conditions, post-conditions, and
invariants
8. Avoid Over Documentation
– Do not do documentation that can be done with code or
avoided completely
– Code is the best documentation
– Always document hard to understand parts
9. Simplify And Clarify
– Always simplify the code to the smallest, cleanest form
that works without sacrificing safety
– Keep methods to one task only, delegate subtasks to
other methods
How To Protect Code (6)
10. Use static code analysis
– Run tools such as FxCop and StyleCop to analyze the
code and react to all received warnings
• FxCop warnings are over 90% of the time correct and
therefore they must be addressed
• StyleCop warnings are tailored for a different set of coding
standards than the one used internally and must be
twaked
11. Unit test the code
– Regardless of Test Driven Development (TDD) or After
Development Testing (ADT) strategy used, when
possible create unit tests as they:
• help on finding bugs early
• help on regression testing
How To Protect Data
• Encrypt passwords with a strong, salted, one-way
hash such as SHA-512
• Encrypt sensitive data with AES-256 or even better
with an asymmetrical algorithm
• Use database-level encryption if possible
• Use secured storage for files, do not store files under
the web application root, always use an external folder
properly configured to allow access to required users
only
• Transfer sensitive data over secured connections
(e.g. use HTTPS instead of HTTP)
• Do not invent security algorithms, stick to standards
Other Protection Methods
• Log everything, although this does not protect
anything, can help detect issues and break-ins and it
also helps debug the application
• Avoid using the disk. Do not store data on the disk if
possible, use the database or BLOB storage.
• Setup and secure the backups as backups are most
often left unsecured
• Define data retention policies
• Logically deleted data must not be visible in the
application (except for the data recovery tools of the
application) and must be explicitly excluded from all
queries
Questions?

Contenu connexe

Tendances

So Your Company Hired A Pentester
So Your Company Hired A PentesterSo Your Company Hired A Pentester
So Your Company Hired A Pentester
NorthBayWeb
 
Testingfor Sw Security
Testingfor Sw SecurityTestingfor Sw Security
Testingfor Sw Security
ankitmehta21
 

Tendances (20)

Secure Coding and Threat Modeling
Secure Coding and Threat ModelingSecure Coding and Threat Modeling
Secure Coding and Threat Modeling
 
Cloud Security vs Security in the Cloud
Cloud Security vs Security in the CloudCloud Security vs Security in the Cloud
Cloud Security vs Security in the Cloud
 
Penetration Testing Execution Phases
Penetration Testing Execution Phases Penetration Testing Execution Phases
Penetration Testing Execution Phases
 
So Your Company Hired A Pentester
So Your Company Hired A PentesterSo Your Company Hired A Pentester
So Your Company Hired A Pentester
 
Continuous security testing - sharing responsibility
Continuous security testing - sharing responsibilityContinuous security testing - sharing responsibility
Continuous security testing - sharing responsibility
 
Introduction to Application Security Testing
Introduction to Application Security TestingIntroduction to Application Security Testing
Introduction to Application Security Testing
 
Vulnerability and Assessment Penetration Testing
Vulnerability and Assessment Penetration TestingVulnerability and Assessment Penetration Testing
Vulnerability and Assessment Penetration Testing
 
Penetration testing in wireless network
Penetration testing in wireless networkPenetration testing in wireless network
Penetration testing in wireless network
 
Finacle - Secure Coding Practices
Finacle - Secure Coding PracticesFinacle - Secure Coding Practices
Finacle - Secure Coding Practices
 
Ethical Hacking n VAPT presentation by Suvrat jain
Ethical Hacking n VAPT presentation by Suvrat jainEthical Hacking n VAPT presentation by Suvrat jain
Ethical Hacking n VAPT presentation by Suvrat jain
 
Develop, Test & Maintain Secure Systems (While Being PCI Compliant)
Develop, Test & Maintain Secure Systems (While Being PCI Compliant)Develop, Test & Maintain Secure Systems (While Being PCI Compliant)
Develop, Test & Maintain Secure Systems (While Being PCI Compliant)
 
Penetration testing dont just leave it to chance
Penetration testing dont just leave it to chancePenetration testing dont just leave it to chance
Penetration testing dont just leave it to chance
 
Client-Side Penetration Testing Presentation
Client-Side Penetration Testing PresentationClient-Side Penetration Testing Presentation
Client-Side Penetration Testing Presentation
 
501 ch 7 advanced attacks
501 ch 7 advanced attacks501 ch 7 advanced attacks
501 ch 7 advanced attacks
 
Securing your web applications a pragmatic approach
Securing your web applications a pragmatic approachSecuring your web applications a pragmatic approach
Securing your web applications a pragmatic approach
 
Aliens in Your Apps! Are You Using Components With Known Vulnerabilities?
Aliens in Your Apps! Are You Using Components With Known Vulnerabilities?Aliens in Your Apps! Are You Using Components With Known Vulnerabilities?
Aliens in Your Apps! Are You Using Components With Known Vulnerabilities?
 
AlienVault Brute Force Attacks- Keeping the Bots at Bay with AlienVault USM +...
AlienVault Brute Force Attacks- Keeping the Bots at Bay with AlienVault USM +...AlienVault Brute Force Attacks- Keeping the Bots at Bay with AlienVault USM +...
AlienVault Brute Force Attacks- Keeping the Bots at Bay with AlienVault USM +...
 
Scanning web vulnerabilities
Scanning web vulnerabilitiesScanning web vulnerabilities
Scanning web vulnerabilities
 
Testingfor Sw Security
Testingfor Sw SecurityTestingfor Sw Security
Testingfor Sw Security
 
Career In Information security
Career In Information securityCareer In Information security
Career In Information security
 

En vedette

Что должен знать будущий первоклассник
Что должен знать будущий первоклассникЧто должен знать будущий первоклассник
Что должен знать будущий первоклассник
Titenko1
 
Bloodborne pathogens 2014
Bloodborne pathogens 2014Bloodborne pathogens 2014
Bloodborne pathogens 2014
Mdunnam
 
Bloodborne pathogens 2014
Bloodborne pathogens 2014Bloodborne pathogens 2014
Bloodborne pathogens 2014
Mdunnam
 
презентация Microsoft office power point
презентация Microsoft office power pointпрезентация Microsoft office power point
презентация Microsoft office power point
Titenko1
 
Психологическая готовность к школе
Психологическая готовность к школеПсихологическая готовность к школе
Психологическая готовность к школе
Titenko1
 
Завхоз с 20 по 25 апреля
Завхоз с 20 по 25 апреляЗавхоз с 20 по 25 апреля
Завхоз с 20 по 25 апреля
Titenko1
 
Presetasi hotspot Mubad Zahroni
Presetasi hotspot Mubad ZahroniPresetasi hotspot Mubad Zahroni
Presetasi hotspot Mubad Zahroni
indonesiku
 

En vedette (20)

Что должен знать будущий первоклассник
Что должен знать будущий первоклассникЧто должен знать будущий первоклассник
Что должен знать будущий первоклассник
 
NHGSA Annual Yearbook 2014
NHGSA Annual Yearbook 2014NHGSA Annual Yearbook 2014
NHGSA Annual Yearbook 2014
 
Bloodborne pathogens 2014
Bloodborne pathogens 2014Bloodborne pathogens 2014
Bloodborne pathogens 2014
 
прадедушка саши горякова 24 04_2016
прадедушка саши горякова 24 04_2016прадедушка саши горякова 24 04_2016
прадедушка саши горякова 24 04_2016
 
собрание5
собрание5собрание5
собрание5
 
гиа 9 9.04.2016
гиа 9 9.04.2016гиа 9 9.04.2016
гиа 9 9.04.2016
 
Презентация
ПрезентацияПрезентация
Презентация
 
Readiciderevised
ReadiciderevisedReadiciderevised
Readiciderevised
 
Bloodborne pathogens 2014
Bloodborne pathogens 2014Bloodborne pathogens 2014
Bloodborne pathogens 2014
 
Web design company budnet
Web design company   budnetWeb design company   budnet
Web design company budnet
 
4 g technology
4 g  technology4 g  technology
4 g technology
 
Web design coibatore, Web design company budnet
Web design coibatore, Web design company   budnetWeb design coibatore, Web design company   budnet
Web design coibatore, Web design company budnet
 
презентация Microsoft office power point
презентация Microsoft office power pointпрезентация Microsoft office power point
презентация Microsoft office power point
 
Ramanan smart
Ramanan   smartRamanan   smart
Ramanan smart
 
Для родителей будущих первоклассников
Для родителей будущих первоклассниковДля родителей будущих первоклассников
Для родителей будущих первоклассников
 
Психологическая готовность к школе
Психологическая готовность к школеПсихологическая готовность к школе
Психологическая готовность к школе
 
Завхоз с 20 по 25 апреля
Завхоз с 20 по 25 апреляЗавхоз с 20 по 25 апреля
Завхоз с 20 по 25 апреля
 
Presetasi hotspot Mubad Zahroni
Presetasi hotspot Mubad ZahroniPresetasi hotspot Mubad Zahroni
Presetasi hotspot Mubad Zahroni
 
Kvm简介
Kvm简介Kvm简介
Kvm简介
 
Аутизм
АутизмАутизм
Аутизм
 

Similaire à Eirtight writing secure code

Software security (vulnerabilities) and physical security
Software security (vulnerabilities) and physical securitySoftware security (vulnerabilities) and physical security
Software security (vulnerabilities) and physical security
Nicholas Davis
 
10 Tips to Keep Your Software a Step Ahead of the Hackers
10 Tips to Keep Your Software a Step Ahead of the Hackers10 Tips to Keep Your Software a Step Ahead of the Hackers
10 Tips to Keep Your Software a Step Ahead of the Hackers
Checkmarx
 

Similaire à Eirtight writing secure code (20)

Security Patterns - An Introduction
Security Patterns - An IntroductionSecurity Patterns - An Introduction
Security Patterns - An Introduction
 
chap-1 : Vulnerabilities in Information Systems
chap-1 : Vulnerabilities in Information Systemschap-1 : Vulnerabilities in Information Systems
chap-1 : Vulnerabilities in Information Systems
 
Securing the Cloud
Securing the CloudSecuring the Cloud
Securing the Cloud
 
Owasp Proactive Controls for Web developer
Owasp  Proactive Controls for Web developerOwasp  Proactive Controls for Web developer
Owasp Proactive Controls for Web developer
 
AppSec How-To: Achieving Security in DevOps
AppSec How-To: Achieving Security in DevOpsAppSec How-To: Achieving Security in DevOps
AppSec How-To: Achieving Security in DevOps
 
Cyber security webinar 6 - How to build systems that resist attacks?
Cyber security webinar 6 - How to build systems that resist attacks?Cyber security webinar 6 - How to build systems that resist attacks?
Cyber security webinar 6 - How to build systems that resist attacks?
 
8 Patterns For Continuous Code Security by Veracode CTO Chris Wysopal
8 Patterns For Continuous Code Security by Veracode CTO Chris Wysopal8 Patterns For Continuous Code Security by Veracode CTO Chris Wysopal
8 Patterns For Continuous Code Security by Veracode CTO Chris Wysopal
 
Unit4
Unit4Unit4
Unit4
 
Survey Presentation About Application Security
Survey Presentation About Application SecuritySurvey Presentation About Application Security
Survey Presentation About Application Security
 
Arved sandstrom - the rotwithin - atlseccon2011
Arved sandstrom - the rotwithin - atlseccon2011Arved sandstrom - the rotwithin - atlseccon2011
Arved sandstrom - the rotwithin - atlseccon2011
 
Software security (vulnerabilities) and physical security
Software security (vulnerabilities) and physical securitySoftware security (vulnerabilities) and physical security
Software security (vulnerabilities) and physical security
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
 
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
Manoj Purandare - Application Security - Secure Code Assessment Program - Pre...
 
Bringing Security Testing to Development: How to Enable Developers to Act as ...
Bringing Security Testing to Development: How to Enable Developers to Act as ...Bringing Security Testing to Development: How to Enable Developers to Act as ...
Bringing Security Testing to Development: How to Enable Developers to Act as ...
 
Module 4 qui parle de la sécurisation des applications
Module 4 qui parle de la sécurisation des applicationsModule 4 qui parle de la sécurisation des applications
Module 4 qui parle de la sécurisation des applications
 
CohenNancyPresentation.ppt
CohenNancyPresentation.pptCohenNancyPresentation.ppt
CohenNancyPresentation.ppt
 
Secure coding guidelines
Secure coding guidelinesSecure coding guidelines
Secure coding guidelines
 
10 Tips to Keep Your Software a Step Ahead of the Hackers
10 Tips to Keep Your Software a Step Ahead of the Hackers10 Tips to Keep Your Software a Step Ahead of the Hackers
10 Tips to Keep Your Software a Step Ahead of the Hackers
 
Cyber security - It starts with the embedded system
Cyber security - It starts with the embedded systemCyber security - It starts with the embedded system
Cyber security - It starts with the embedded system
 

Dernier

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Dernier (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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 Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
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...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
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
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%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
 
%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
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
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
 

Eirtight writing secure code

  • 1. Writing (In)Secure Code Leontin Bîrsan Solution Architect Thursday, 26 June 2014
  • 2. Software’s Vulnerability to Attack • What makes it so easy for attackers to target software is the virtually guaranteed presence of vulnerabilities, which can be exploited to violate one or more of the software’s security properties • Most successful attacks result from targeting and exploiting known, non-patched software vulnerabilities and insecure software configurations, many of which are introduced during design and code • Many successful attacks result from poor coding which open the applications vulnerable to SQL injection, buffer overflows etc.
  • 3. When Is There a Threat? The software’s security can be threatened: • during its development: – A developer may corrupt the software (intentionally or unintentionally) in ways that will compromise the software’s dependability and trustworthiness when it is operational.
  • 4. When Is There a Threat? (2) The software’s security can be threatened: • during its deployment (distribution and installation): – If those responsible for distributing the software fail to tamperproof the software before shipping or uploading, or transmit it over easily intercepted communications channels, they leave the software vulnerable to intentional or unintentional corruption. – Similarly, if the software’s installer fails to “lock down” the host platform, or configures the software insecurely, the software is left vulnerable to access by attackers.
  • 5. When Is There a Threat? (3) The software’s security can be threatened: • during its operation: – Once software has gone operational, vulnerabilities may be discovered and publicized; unless security patches and updates are applied and newer supported versions (from which the root causes of vulnerabilities have been eliminated) are adopted, such software will become increasingly vulnerable. – Any software system that runs on a network-connected platform has its vulnerabilities exposed during its operation. The level of exposure will vary depending on whether the network is public or private, Internet-connected or not, and whether the software’s environment has been configured to minimize its exposure. – But even in highly controlled networks and “locked down” environments, the software may be threatened by malicious insiders (users, administrators, etc.).
  • 6. When Is There a Threat? (4) The software’s security can be threatened: • during its maintenance: – If those responsible for addressing discovered vulnerabilities in released software fail to issue patches or updates in a timely manner, or fail to seek out and eliminate the root causes of the vulnerabilities to prevent their perpetuation in future releases of the software, the software will become increasingly vulnerable to threats over time. – Also, the software’s maintainer may prove to be a malicious insider, and may embed malicious code, exploitable flaws, etc., in updated versions of the code.
  • 7. The Challenge of Building Secure Software • To be considered secure, software must exhibit three properties: – Dependability: Dependable software executes predictably and operates correctly under all conditions, including hostile conditions, including when the software comes under attack or runs on a malicious host. – Trustworthiness: Trustworthy software contains few (if any) vulnerabilities or weaknesses that can be intentionally exploited to subvert or sabotage the software’s dependability. In addition, to be considered trustworthy, the software must contain no malicious logic that causes it to behave in a malicious manner.
  • 8. The Challenge of Building Secure Software (2) • To be considered secure, software must exhibit three properties: – Survivability (also referred to as “Resilience”): Survivable (or resilient) software is software that is resilient enough to • (1) either resist (i.e., protect itself against) or tolerate (i.e., continue operating dependably in spite of) most known attacks plus as many novel attacks as possible, and • (2) recover as quickly as possible, and with as little damage as possible, from those attacks that it can neither resist nor tolerate.
  • 10. How To Protect Code In two words: Defensive Coding. 1. Never trust the user input and I do mean NEVER – Trusting user input is a generally bad idea, as seen in the examples we do open the application to various attacks – User input should be sanitized and validated, if not done automatically by the framework (e.g. ASP.NET MVC) – Always perform basic tests over the input, such as length and range
  • 11. How To Protect Code (2) 2. Do not relay solely on client-side validation, re- validate always on server-side – Validating only on client side does not protect against call injection which will bypass the protection – JavaScript can be disabled in the browser options disabling the validation – Use framework built-in validation, e.g. for ASP.MVC use data annotations such as [Required], [StringLength(10)], [Range(10, 20)] etc. which will fire automatically on each request, then use subsequently ModelState.IsValid to check the validity of the request
  • 12. How To Protect Code (3) 3. Never build SQL by means of concatenating strings that contain user input. Always use parameters. – In general, building SQLs with “+” is a really bad idea – However, in some cases, dynamic SQL must be built, but it should not contain any user-generated content – If dynamic SQL is to be created use a factory method or class to contain the respective code in one place – Such code must be reviewed for possible security issues
  • 13. How To Protect Code (4) 4. Test parameters of the functions – Test for NULL and allowed ranges and throw exceptions if the validation fails – If unit tests are built, test for the respective exceptions by passing intentionally incorrect parameters and expecting the exceptions 5. Prevent errors – If an error is possible, no matter how probable, try to prevent it 6. Fail Early And Openly – Fail early, cleanly, and openly, stating what happened, where and how to fix it
  • 14. How To Protect Code (5) 7. Document Assumptions – Clearly state the pre-conditions, post-conditions, and invariants 8. Avoid Over Documentation – Do not do documentation that can be done with code or avoided completely – Code is the best documentation – Always document hard to understand parts 9. Simplify And Clarify – Always simplify the code to the smallest, cleanest form that works without sacrificing safety – Keep methods to one task only, delegate subtasks to other methods
  • 15. How To Protect Code (6) 10. Use static code analysis – Run tools such as FxCop and StyleCop to analyze the code and react to all received warnings • FxCop warnings are over 90% of the time correct and therefore they must be addressed • StyleCop warnings are tailored for a different set of coding standards than the one used internally and must be twaked 11. Unit test the code – Regardless of Test Driven Development (TDD) or After Development Testing (ADT) strategy used, when possible create unit tests as they: • help on finding bugs early • help on regression testing
  • 16. How To Protect Data • Encrypt passwords with a strong, salted, one-way hash such as SHA-512 • Encrypt sensitive data with AES-256 or even better with an asymmetrical algorithm • Use database-level encryption if possible • Use secured storage for files, do not store files under the web application root, always use an external folder properly configured to allow access to required users only • Transfer sensitive data over secured connections (e.g. use HTTPS instead of HTTP) • Do not invent security algorithms, stick to standards
  • 17. Other Protection Methods • Log everything, although this does not protect anything, can help detect issues and break-ins and it also helps debug the application • Avoid using the disk. Do not store data on the disk if possible, use the database or BLOB storage. • Setup and secure the backups as backups are most often left unsecured • Define data retention policies • Logically deleted data must not be visible in the application (except for the data recovery tools of the application) and must be explicitly excluded from all queries