Memory Safety
with
Delphi
Jim McKeeth
jim@gdksoftware.com
gdksoftware.com
Webinar Logistics
• Be sure you registered for slides, code, and replays
mailing.gdksoftware.com/webinars
• If watching live, there is Q&A at the end
• Future webinars in series
• Essential Delphi Add-Ins (19th of June)
• Debugging in Delphi (26th of June)
• Ask Jim Anything (10th of July)
• Build Automation and Supply Chain Security (24th of July)
• Essential Delphi Libraries (7th of August)
• Open to webinar suggestions too!
jim@gdksoftware.com
youtube.com/live/-SotB4lloII
youtube.com/live/-SotB4lloII
Replay
The YouTube logo is made of a red round-rectangular box with a white triangular "play" button inside and the word "YouTube" written in black.
BEGIN
Delphi Summit
• Return of the global Delphi conference
• Amsterdam - 13 and 14 June 2024
• 2 Days, 3 Tracks, 23 Speakers, 26 Sessions
• All sessions recorded
• Attend in person € 399 or online only € 199
• delphisummit.com
About Jim McKeeth
• Director of GDK Software, USA & Delphi MVP
• Previously Embarcadero Chief Dev Advocate
• Over 30 years experience in software development
• Worked professionally in many languages and platforms,
including Delphi, C#, C/C++, Java, JavaScript, and Python
• Multiple technology patents & book contributions
• Spoken on software development all around the world
• Professional improv comedy performer for 10 years
GDK Software
• Offices in US, UK, the Netherlands, & Brazil
• 25+ Delphi development experts
• gdksoftware.com
• We are Delphi.
• Codolex 2.0 is now Free
• More than just Delphi low-code
• codolex.com
INTERFACE
Agenda
• What is Memory Safety
• Why does it matter
• “Recommended” languages
• How Delphi fits in the list
• Best practices for memory safety
• Tools and tips
• Code samples
• A lot of opinion
IMPLEMENTATION
I’m Not Crazy
Charlie Day conspiracy meme from
It's Always Sunny In Philadelphia
by 20th Century Fox Television/FX
The Report
• Released in Feb 2024 by the US
White House Office of the National
Cyber Director (ONCD)
• Emphasis on Memory Safety &
Software Measurability
• References US Executive Order
14028 from 2021
• whitehouse.gov/oncd/briefing-
room/2024/02/26/press-release-technical-report/
Report isn’t Perfect
• It oversimplifies the problem
• Language selection alone is
insufficient
• Security issues are multifaceted,
involving design flaws, human
factors, and existing legacy systems
• Better tools, training, and practices,
are also needed
• hackaday.com/2024/02/29/the-white-house-
memory-safety-appeal-is-a-security-red-
herring/
This Isn’t Out of the Blue
• 2010 – Stuxnet – en.wikipedia.org/wiki/Stuxnet
• 2017 May 12 – WannaCry ransomware – en.wikipedia.org/wiki/WannaCry_ransomware_attack
• 2017 Jun 27 – NotPetya malware – en.wikipedia.org/wiki/Petya_(malware_family)#NotPetya
• 2018 – Meltdown and Spectre – meltdownattack.com
• 2020 Dec – SolarWinds breach – sans.org/blog/what-you-need-to-know-about-the-solarwinds-supply-chain-
attack/
• 2021 May 12 – US Executive Order 14028 on Cybersecurity – whitehouse.gov/briefing-room/presidential-
actions/2021/05/12/executive-order-on-improving-the-nations-cybersecurity/
• 2021 Nov 24 – Log4j / Log4ShellVulnerability – en.wikipedia.org/wiki/Log4Shell
• 2021 May 6 – Colonial Pipeline ransomware attack –en.wikipedia.org/wiki/Colonial_Pipeline_ransomware_attack
• 2021 July – Equifax data breach – en.wikipedia.org/wiki/2017_Equifax_data_breach
• Things only gotworse…
• 2024 Feb 26 – Report on Memory Safety – whitehouse.gov/oncd/briefing-room/2024/02/26/press-release-technical-report/
Both powered by EternalBlue,
which the NSA developed
en.wikipedia.org/wiki/EternalBlue
Let’s Talk About CVE
• The Common Vulnerabilities and Exposures (CVE) system
• Public reference database that assigns unique identifiers to known
cybersecurity vulnerabilities
• Managed by MITRE Corporation
• Standardizes the identification and cataloging of security flaws in
software and hardware
• Facilitates the sharing of information across tools, organizations, and
vendors.
• Usually links to US National Vulnerabilities Database (nvd.nist.gov)
• CVE#s also used in Metasploit metasploit.com
cve.mitre.org
Some Memory Safety CVE Records
• Heartbleed – CVE-2014-0160
• Shellshock – CVE-2014-6271
• Stagefright – CVE-2015-3864
• Android Out of Bounds Write – CVE-2020-0041
• Buffer overflow in TPicture – CVE-2014-0994
• Buffer overflow in Skype via SysUtils.WideFmtStr –
CVE-2005-3265
• URI Normalization buffer overflow CVE-2021-22991
Microsoft Estimates ~70%
• Report from Microsoft Security Response Centre (MSRC)
• From 2006 to 2018 ~70% of the vulnerabilities Microsoft
assigns a CVE each year continue to be memory safety issues
• msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code
CWE 2023 Stubborn Weaknesses List
Present in the last 5 lists of top 25 Most Dangerous Software Weaknesses
1. CWE-787 – Out-of-bounds Write
4. CWE-416 – Use After Free
7. CWE-125 – Out-of-bounds Read
12. CWE-476 – NULL Pointer Dereference
14. CWE-190 – Integer Overflow or Wraparound
17. CWE-119 – Improper Restriction of Operations within Bounds of a
Memory Buffer
• Source: cwe.mitre.org/top25/archive/2023/2023_stubborn_weaknesses.html (includes mitigation recommendations)
CWE – Common Weakness Enumeration – cwe.mitre.org
Dimensions of Memory Issues
TARDIS
Time And Relative
Dimension In Space
Out of bounds
Time Before Allocation After Free
Underrun
Overflow
Space
NULL Reference
Invalid Pointer
Operation
Access Violation
NSA Memory Safe Language List
• US National Security Agency nsa.gov
• Originally published 2022 Nov 10, & updated 2023 Apr 27
• Excerpts:
• Examples of memory safe language include Python, Java, C#, Go, Delphi/Object
Pascal, Swift, Ruby, Rust, and Ada.
• Even with a memory safe language, memory management is not entirely memory
safe.
• Languages vary in their degree of memory safety instituted through inherent
protections and mitigations.
• Memory safety can be costly in performance and flexibility.
• Leveraging options, such as Control Flow Guard (CFG) … Address Space Layout
Randomization (ASLR) and Data Execution Prevention (DEP)…
• media.defense.gov/2023/Apr/27/2003210083/-1/-1/0/CSI_SOFTWARE_MEMORY_SAFETY_V1.1.PDF
NSA Memory Safe Language List
Compiled GUI Typing Performance
Memory
Management
Ada Native none Statically High Manual/Safe
C# IL WPF Statically Moderate Auto/GC
Delphi Native VCL / FMX Statically High Hybrid
Go Native none Statically High Auto/GC
Java bytecode JavaFX & Swing Statically Moderate Auto/GC
Python interpreted none Dynamic Lower Hybrid
Ruby interpreted none Dynamic Lower Auto/GC
Rust Native none Statically High Manual/Safe
Swift Native SwiftUI Statically Moderate Auto/GC
Is C/C++ Really Bad?
Why is everybody always picking on C?
Modern C/C++
• Now with memory safety features such as smart pointers,
bounds checking, and AddressSanitizer.
• Still lacks many of the other memory safety features.
• Huge amount of legacy code without safety features.
• Java and C# were also created to address C/C++ safety issues.
• C/C++ aren’t bad, but developers can be.
The Different Types of
Developers and
Their Code
This is a generalization and will probably offend some people.
There are always exceptions!
Different Types of Code
Application Code
• The majority of development
• Applications that solve
problems for end users
• Very focused on productivity
• Performance is less important
• Underengineered
Library Code
• Used in applications
• Focused on correctness,
robustness, and reusability
• Testing is more important than
shipping
• Performance is very important
• Overengineered
Both can still write good, clean code
The FizzBuzz Example
For numbers 1 through 100,
• if the number is divisible by 3 print Fizz;
• if the number is divisible by 5 print Buzz;
• if the number is divisible by 3 and 5 (15) print FizzBuzz;
• else, print the number.
Application Solution
procedure RunFizzBuzz;
begin
for var i := 1 to 100 do
begin
if (i mod 3 = 0) and (i mod 5 = 0) then
WriteLn('FizzBuzz')
else if i mod 3 = 0 then
WriteLn('Fizz')
else if i mod 5 = 0 then
WriteLn('Buzz')
else
WriteLn(i);
end;
end;
The “Enterprise” Solution
• Heavy use of Factory pattern, Dependency Injection, and the
Strategy pattern
• Everything has an object, every object has an interface
• A processor to handle the rules
• Modularity to add or remove rules as needed
• 200+ line example in Delphi:
gist.github.com/jimmckeeth/63af8b48f8cbd1d6d4ff2c9ca7c7baae
• This is a joke to illustrate a point.
• See also:
• github.com/jongeorge1/FizzBuzzEnterpriseEdition-CSharp 48 C# files, over 6 projects
• github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition 89 Java files
So What?
• Most of the time we are writing application code
• Don’t over engineer it
• Avoid premature optimization
• Use safeguards
• Still write clean code
• Still use tests and best practices
• Get it done and ship the application
Is Delphi Memory Safe?
Yes, or it wouldn’t be on the list,
and we wouldn’t have this webinar…
How Delphi addresses different memory safety issues.
Buffer Overflows and Underflows
• These occur when a program writes more data to a
buffer, or less, respectively, than it can hold, potentially
overwriting important data or leading to unauthorized
access to memory.
• Delphi uses strong typing and array bounds checking,
which can prevent buffer overflow and underflow
conditions by ensuring that data written to a buffer does
not exceed its allocated size.
• The runtime checks for array bounds help catch out-of-
range access before it leads to a vulnerability.
Use-After-Free & Double Free
Vulnerabilities
• This happens when a program continues to use a pointer
after it has been freed, leading to potentially executing
arbitrary code or modifying the program's flow in an
unintended manner.
• Delphi minimizes the risk of use-after-free errors through
• Interface reference counting
• Minimizing reference scope (inline variables)
• FreeAndNil
Improper Memory Access
• This includes scenarios where a program accesses
uninitialized, freed, or out-of-scope memory, which can lead
to unpredictable behavior, including the exposure of
sensitive information or system crashes.
• Delphi’s string types and dynamic arrays are managed types,
reducing the risk of improper memory access.
• Access to these types is checked at runtime to prevent out-
of-bounds errors and uninitialized memory access.
• Generic collections enforce type safety on the contents of
the collection, removing the need to type cast items when
removed from the collection.
Memory Leaks
• While not always directly exploitable, memory leaks can lead to a
degradation of system performance over time, eventually causing
software or systems to crash.
• This can be leveraged in certain attacks to facilitate more severe
exploits.
• Delphi’s interface reference counting, and the component owner
model limit memory leaks.
• For manually allocated objects the TRY/FINALLY block helps
ensure memory is freed.
• Use the built-in memory leak reporting tool to identify and resolve
leaks during the development phase.
Best Practices
for Memory Safety
Time for the good stuff
The Basics
1. Always use the minimal scope possible, even better if you
use inline variable declarations.
2. If you create or allocated it, then free it (unless there is a
specific agreement to hand it off)
3. References accessible in a broader scope should always
be set to nil when not assigned.
4. If you create it in the constructor, free it in the
destructor.
5. Use TRY/FINALLY when creating local objects.
• If creating multiple objects, set the references all to nil first.
6. Address ALL HINTS and WARNINGS
Creating Multiple Objects
var Obj1, Obj2, Obj3: TMyObject;
begin
Obj1 := nil;
Obj2 := nil;
Obj3 := TMyObject.Create;
try
Obj2 := TMyObject.Create;
Obj1 := TMyObject.Create;
// Use the objects
finally
Obj3.Free;
Obj2.Free;
Obj1.Free;
end;
end;
• The order isn’t important
• Free isn’t virtual and is safe to call on
a nil object.
• docwiki.embarcadero.com/RADStudio/en/Me
thods_(Delphi)#Destructors
Constructors and Destructors
constructor TShape.Create
(Owner: TComponent);
begin
// Initialize inherited parts
inherited Create(Owner);
// Change inherited properties
Width := 65;
// Initialize new fields
FPen := TPen.Create;
end;
destructor TShape.Destroy;
begin
FBrush.Free;
FPen.Free;
inherited Destroy;
end;
• When an exception is raised during the
creation of an object, Destroy is automatically
called to dispose of the unfinished object.
• Constructor sets the fields of a new object to
zero or empty values before performing other
actions
• Class-type and pointer-type fields in a partially
constructed object are always nil.
• A destructor should check for nil values
before operating on class-type or pointer-type
fields.
• Calling the Free method (defined in TObject)
rather than Destroy offers a convenient way
to check for nil values before destroying an
object.
docwiki.embarcadero.com/RADStudio/en/Methods_(Delphi)#Constructors
docwiki.embarcadero.com/RADStudio/en/Methods_(Delphi)#Destructors
Address Space Randomization (ASLR)
• {$DYNAMICBASE} enables the Address Space Randomization
(ASLR) on Windows Vista and above, providing secure
protection against attacks based on buffer overrun.
• Switch {$DYNAMICBASE} on to prevent attacks in memory-
corruption vulnerabilities by enabling ASLR to randomly
arrange the address space positions for the stack, heap,
libraries, and key data areas of a process.
• docwiki.embarcadero.com/RADStudio/en/Dynamic_base_(Delphi)
High-entropy 64-bit ASLR
• Enabling the flag {$HIGHENTROPYVA} provides secure
protection against attacks based on buffer overrun.
• Enable this flag to prevent attacks in memory-corruption
vulnerabilities by enabling ASLR to randomly arrange the
address space positions for the stack, heap, libraries, and key
data areas of a process.
• docwiki.embarcadero.com/RADStudio/en/Support_high-
entropy_64-bit_ASLR
Data Execution Prevention (DEP)
• Enabled by Default {$NXCOMPAT ON}
• docwiki.embarcadero.com/RADStudio/en/Data_Execution_Prevention_compatible
• Windows feature that prevents executable code launching
from places it's not supposed to.
• Marks some areas memory as being for data only, not allowing
executable code from running.
• Make it harder for buffer overflows to execute code.
• learn.microsoft.com/en-us/windows/win32/memory/data-execution-prevention
Controversial Advice
• Leave runtime checks enabled in production.
• Range Checking {$R+} {$RANGECHECKS ON}
• IO Checking {$T+} {$TYPEDADDRESS ON}
• Overflow Checking {$Q+} {$OVERFLOWCHECKS ON}
• Assertions {$C+} {$ASSERTIONS ON}
• Make liberal use of assertions
• Safety is usually worth the small impact on performance
• Consider Generic collections to enforce type safety
• When storing Objects use the Object version of the
collection and OwnsObjects option
$R- $R+
$R+ produces ERangeError exception, without it just runs!
Win32
Win64 $R- $R+
Going Further
• Read Delphi Memory Management by Dalija Prasnikar &
Neven Prasnikar Jr.
• https://igoto.co/DelphiMM
• Make use of Records, Interfaces, Smart Pointers, and Auto
Release Pools when possible.
• dalijap.blogspot.com/2021/02/autorelease-pool.html
• Use Spring4D’s Smart Pointers
• Shared<T> and Weak<T>
• bitbucket.org/sglienke/spring4d
• Use FastMM’s ReportMemoryLeaksOnShutdown during
development (don’t ship with it on)
Dalija’s Auto Release Pool
var
Foo: TFoo;
Bar: TBar;
begin
Foo := TFoo.Create;
AutoPool.Add(Foo);
Bar := TBar.Create;
AutoPool.Add(Bar);
// use Foo and Bar
end; // AutoPool frees Foo and Bar
dalijap.blogspot.com/2021/02/autorelease-pool.html
JEDI JCL SafeGuard
var
SafeGuard: ISafeGuard;
Strings: TStrings;
begin
Strings := TStrings(Guard(TStringList.Create, SafeGuard));
Strings.ReadFromFile('d:delphijclsourceJclBase.pas');
// code to manipulate strings goes here
Strings.SaveToFile('d:delphijclsourceJclBase.pas');
end; // SafeGuard frees the Tstrings
https://wiki.delphi-jedi.org/wiki/JCL_Help:Guard@Pointer@IMultiSafeGuard
JEDI JCL MultiSafeGuard
var
SafeGuard: IMultiSafeGuard;
O1, O2: TObject;
begin
O1 := Guard(TObject.Create, SafeGuard);
O2 := Guard(TObject.Create, SafeGuard);
// use O1 and O2 here
end; // Guard frees objects
wiki.delphi-jedi.org/wiki/JCL_Help:IMultiSafeGuard
More on Spring4D
• Installation: youtube.com/watch?v=cusRfnlow0g
• Download the code and run Build.dpr
• It takes quite a while
• Introduction: youtube.com/watch?v=izI0Vah2CRs
• Source: bitbucket.org/sglienke/spring4d/
• Wiki: bitbucket.org/sglienke/spring4d/wiki/browse/
• Docs: devjetsoftware.com/docs/spring4d/
• Support:
• Email list: groups.google.com/g/spring4d
• Stefan’s blog: delphisorcery.blogspot.com/
• Delphi Praxis 3rd Party: en.delphipraxis.net/forum/13-delphi-third-party/
• Stack Overflow: stackoverflow.com/questions/tagged/spring4d
Shared<T>
var
sl: Shared<TStringList>;
begin
sl := TStringList.Create;
sl.Value.Add('Shared<T>');
log.Items.Add(sl.Value.ClassName);
// Pass as a TStrings
Log.Items.AddStrings(sl);
// Freed when it goes out of scope
end;
IShared<T>
var
sl: IShared<TStringList>;
begin
sl := Shared.Make(TStringList.Create);
// Directly access members
sl.Add('IShared<T>');
log.Items.Add(sl.ClassName);
// Freed when it goes out of scope
end;
IShared<T> with Finalizer
var
sl: IShared<TStrings>;
begin
// The type is TStrings, but the instance is TStringList
sl := Shared.Make<TStrings>(TStringList.Create,
procedure(const s: TStrings)
begin
Sleep(1000);
s.Add(‘Goodbye');
Log.Items.AddStrings(s);
// the finalizer replaces the default one so must free it here
s.Free;
end);
sl.Add('IShared<T> with Finalizer');
// Finalizer called when it goes out of scope
end;
Weak<T>
var
sl: TStringList;
weakRef: Weak<TStringList>;
begin
sl := TStringList.Create;
weakRef := sl;
sl.Add('Hello World');
Log.Items.Add(WeakRef.IsAlive.ToString(False));
Log.Items.AddStrings(WeakRef);
// Usually any *other* reference pointing to sl after this Free
// Will have a "dangling reference" FreeAndNil would not help with that either
sl.Free;
// with Weak<T> this will work on any platform
Log.Items.Add(weakRef.IsAlive.ToString(TUseBoolStrs.True));
Log.Items.Add(Assigned(weakRef.Target).ToString(TUseBoolStrs.True));
Log.Items.Add((weakRef <> nil).ToString(TUseBoolStrs.True));
end;
More Tools
• Use tools like EurkaLog and Deleaker
• Run TMS FixInsight to find more Hints and Warnings
• Use DerScanner to find security issues
• Use SonarQube for Delphi for more analysis
FINALIZATION
GDK Software
• Offices in US, UK, the Netherlands, & Brazil
• 25+ Delphi development experts
• gdksoftware.com
• We are Delphi.
• Codolex 2.0 is now Free
• More than just Delphi low-code
• codolex.com
Delphi Summit
• Return of the global Delphi conference
• Amsterdam - 13 and 14 June 2024
• 2 Days, 3 Tracks, 23 Speakers, 26 Sessions
• All sessions recorded
• Attend in person € 399 or online only € 199
• delphisummit.com
Webinar Logistics
• Be sure you registered for slides, code, and replays
mailing.gdksoftware.com/webinars
• Future webinars in series
• Essential Delphi Add-Ins (19th of June)
• Debugging in Delphi (26th of June)
• Ask Jim Anything (10th of July)
• Build Automation and Supply Chain Security (24th of July)
• Essential Delphi Libraries (7th of August)
• Open to webinar suggestions too!
jim@gdksoftware.com
youtube.com/live/-SotB4lloII
youtube.com/live/-SotB4lloII
Replay
The YouTube logo is made of a red round-rectangular box with a white triangular "play" button inside and the word "YouTube" written in black.
Q&A
youtube.com/live/-SotB4lloII
youtube.com/live/-SotB4lloII
Replay
The YouTube logo is made of a red round-rectangular box with a white triangular "play" button inside and the word "YouTube" written in black.
END

Memory Safety with Delphi - Jim McKeeth - Webinar June 2024

  • 1.
  • 2.
    Webinar Logistics • Besure you registered for slides, code, and replays mailing.gdksoftware.com/webinars • If watching live, there is Q&A at the end • Future webinars in series • Essential Delphi Add-Ins (19th of June) • Debugging in Delphi (26th of June) • Ask Jim Anything (10th of July) • Build Automation and Supply Chain Security (24th of July) • Essential Delphi Libraries (7th of August) • Open to webinar suggestions too! jim@gdksoftware.com youtube.com/live/-SotB4lloII youtube.com/live/-SotB4lloII Replay The YouTube logo is made of a red round-rectangular box with a white triangular "play" button inside and the word "YouTube" written in black.
  • 3.
  • 4.
    Delphi Summit • Returnof the global Delphi conference • Amsterdam - 13 and 14 June 2024 • 2 Days, 3 Tracks, 23 Speakers, 26 Sessions • All sessions recorded • Attend in person € 399 or online only € 199 • delphisummit.com
  • 5.
    About Jim McKeeth •Director of GDK Software, USA & Delphi MVP • Previously Embarcadero Chief Dev Advocate • Over 30 years experience in software development • Worked professionally in many languages and platforms, including Delphi, C#, C/C++, Java, JavaScript, and Python • Multiple technology patents & book contributions • Spoken on software development all around the world • Professional improv comedy performer for 10 years
  • 6.
    GDK Software • Officesin US, UK, the Netherlands, & Brazil • 25+ Delphi development experts • gdksoftware.com • We are Delphi. • Codolex 2.0 is now Free • More than just Delphi low-code • codolex.com
  • 7.
  • 8.
    Agenda • What isMemory Safety • Why does it matter • “Recommended” languages • How Delphi fits in the list • Best practices for memory safety • Tools and tips • Code samples • A lot of opinion
  • 9.
  • 10.
    I’m Not Crazy CharlieDay conspiracy meme from It's Always Sunny In Philadelphia by 20th Century Fox Television/FX
  • 11.
    The Report • Releasedin Feb 2024 by the US White House Office of the National Cyber Director (ONCD) • Emphasis on Memory Safety & Software Measurability • References US Executive Order 14028 from 2021 • whitehouse.gov/oncd/briefing- room/2024/02/26/press-release-technical-report/
  • 12.
    Report isn’t Perfect •It oversimplifies the problem • Language selection alone is insufficient • Security issues are multifaceted, involving design flaws, human factors, and existing legacy systems • Better tools, training, and practices, are also needed • hackaday.com/2024/02/29/the-white-house- memory-safety-appeal-is-a-security-red- herring/
  • 13.
    This Isn’t Outof the Blue • 2010 – Stuxnet – en.wikipedia.org/wiki/Stuxnet • 2017 May 12 – WannaCry ransomware – en.wikipedia.org/wiki/WannaCry_ransomware_attack • 2017 Jun 27 – NotPetya malware – en.wikipedia.org/wiki/Petya_(malware_family)#NotPetya • 2018 – Meltdown and Spectre – meltdownattack.com • 2020 Dec – SolarWinds breach – sans.org/blog/what-you-need-to-know-about-the-solarwinds-supply-chain- attack/ • 2021 May 12 – US Executive Order 14028 on Cybersecurity – whitehouse.gov/briefing-room/presidential- actions/2021/05/12/executive-order-on-improving-the-nations-cybersecurity/ • 2021 Nov 24 – Log4j / Log4ShellVulnerability – en.wikipedia.org/wiki/Log4Shell • 2021 May 6 – Colonial Pipeline ransomware attack –en.wikipedia.org/wiki/Colonial_Pipeline_ransomware_attack • 2021 July – Equifax data breach – en.wikipedia.org/wiki/2017_Equifax_data_breach • Things only gotworse… • 2024 Feb 26 – Report on Memory Safety – whitehouse.gov/oncd/briefing-room/2024/02/26/press-release-technical-report/ Both powered by EternalBlue, which the NSA developed en.wikipedia.org/wiki/EternalBlue
  • 14.
    Let’s Talk AboutCVE • The Common Vulnerabilities and Exposures (CVE) system • Public reference database that assigns unique identifiers to known cybersecurity vulnerabilities • Managed by MITRE Corporation • Standardizes the identification and cataloging of security flaws in software and hardware • Facilitates the sharing of information across tools, organizations, and vendors. • Usually links to US National Vulnerabilities Database (nvd.nist.gov) • CVE#s also used in Metasploit metasploit.com cve.mitre.org
  • 15.
    Some Memory SafetyCVE Records • Heartbleed – CVE-2014-0160 • Shellshock – CVE-2014-6271 • Stagefright – CVE-2015-3864 • Android Out of Bounds Write – CVE-2020-0041 • Buffer overflow in TPicture – CVE-2014-0994 • Buffer overflow in Skype via SysUtils.WideFmtStr – CVE-2005-3265 • URI Normalization buffer overflow CVE-2021-22991
  • 16.
    Microsoft Estimates ~70% •Report from Microsoft Security Response Centre (MSRC) • From 2006 to 2018 ~70% of the vulnerabilities Microsoft assigns a CVE each year continue to be memory safety issues • msrc.microsoft.com/blog/2019/07/a-proactive-approach-to-more-secure-code
  • 17.
    CWE 2023 StubbornWeaknesses List Present in the last 5 lists of top 25 Most Dangerous Software Weaknesses 1. CWE-787 – Out-of-bounds Write 4. CWE-416 – Use After Free 7. CWE-125 – Out-of-bounds Read 12. CWE-476 – NULL Pointer Dereference 14. CWE-190 – Integer Overflow or Wraparound 17. CWE-119 – Improper Restriction of Operations within Bounds of a Memory Buffer • Source: cwe.mitre.org/top25/archive/2023/2023_stubborn_weaknesses.html (includes mitigation recommendations) CWE – Common Weakness Enumeration – cwe.mitre.org
  • 18.
    Dimensions of MemoryIssues TARDIS Time And Relative Dimension In Space Out of bounds Time Before Allocation After Free Underrun Overflow Space NULL Reference Invalid Pointer Operation Access Violation
  • 19.
    NSA Memory SafeLanguage List • US National Security Agency nsa.gov • Originally published 2022 Nov 10, & updated 2023 Apr 27 • Excerpts: • Examples of memory safe language include Python, Java, C#, Go, Delphi/Object Pascal, Swift, Ruby, Rust, and Ada. • Even with a memory safe language, memory management is not entirely memory safe. • Languages vary in their degree of memory safety instituted through inherent protections and mitigations. • Memory safety can be costly in performance and flexibility. • Leveraging options, such as Control Flow Guard (CFG) … Address Space Layout Randomization (ASLR) and Data Execution Prevention (DEP)… • media.defense.gov/2023/Apr/27/2003210083/-1/-1/0/CSI_SOFTWARE_MEMORY_SAFETY_V1.1.PDF
  • 20.
    NSA Memory SafeLanguage List Compiled GUI Typing Performance Memory Management Ada Native none Statically High Manual/Safe C# IL WPF Statically Moderate Auto/GC Delphi Native VCL / FMX Statically High Hybrid Go Native none Statically High Auto/GC Java bytecode JavaFX & Swing Statically Moderate Auto/GC Python interpreted none Dynamic Lower Hybrid Ruby interpreted none Dynamic Lower Auto/GC Rust Native none Statically High Manual/Safe Swift Native SwiftUI Statically Moderate Auto/GC
  • 21.
    Is C/C++ ReallyBad? Why is everybody always picking on C?
  • 22.
    Modern C/C++ • Nowwith memory safety features such as smart pointers, bounds checking, and AddressSanitizer. • Still lacks many of the other memory safety features. • Huge amount of legacy code without safety features. • Java and C# were also created to address C/C++ safety issues. • C/C++ aren’t bad, but developers can be.
  • 23.
    The Different Typesof Developers and Their Code This is a generalization and will probably offend some people. There are always exceptions!
  • 24.
    Different Types ofCode Application Code • The majority of development • Applications that solve problems for end users • Very focused on productivity • Performance is less important • Underengineered Library Code • Used in applications • Focused on correctness, robustness, and reusability • Testing is more important than shipping • Performance is very important • Overengineered Both can still write good, clean code
  • 25.
    The FizzBuzz Example Fornumbers 1 through 100, • if the number is divisible by 3 print Fizz; • if the number is divisible by 5 print Buzz; • if the number is divisible by 3 and 5 (15) print FizzBuzz; • else, print the number.
  • 26.
    Application Solution procedure RunFizzBuzz; begin forvar i := 1 to 100 do begin if (i mod 3 = 0) and (i mod 5 = 0) then WriteLn('FizzBuzz') else if i mod 3 = 0 then WriteLn('Fizz') else if i mod 5 = 0 then WriteLn('Buzz') else WriteLn(i); end; end;
  • 27.
    The “Enterprise” Solution •Heavy use of Factory pattern, Dependency Injection, and the Strategy pattern • Everything has an object, every object has an interface • A processor to handle the rules • Modularity to add or remove rules as needed • 200+ line example in Delphi: gist.github.com/jimmckeeth/63af8b48f8cbd1d6d4ff2c9ca7c7baae • This is a joke to illustrate a point. • See also: • github.com/jongeorge1/FizzBuzzEnterpriseEdition-CSharp 48 C# files, over 6 projects • github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition 89 Java files
  • 28.
    So What? • Mostof the time we are writing application code • Don’t over engineer it • Avoid premature optimization • Use safeguards • Still write clean code • Still use tests and best practices • Get it done and ship the application
  • 29.
    Is Delphi MemorySafe? Yes, or it wouldn’t be on the list, and we wouldn’t have this webinar… How Delphi addresses different memory safety issues.
  • 30.
    Buffer Overflows andUnderflows • These occur when a program writes more data to a buffer, or less, respectively, than it can hold, potentially overwriting important data or leading to unauthorized access to memory. • Delphi uses strong typing and array bounds checking, which can prevent buffer overflow and underflow conditions by ensuring that data written to a buffer does not exceed its allocated size. • The runtime checks for array bounds help catch out-of- range access before it leads to a vulnerability.
  • 31.
    Use-After-Free & DoubleFree Vulnerabilities • This happens when a program continues to use a pointer after it has been freed, leading to potentially executing arbitrary code or modifying the program's flow in an unintended manner. • Delphi minimizes the risk of use-after-free errors through • Interface reference counting • Minimizing reference scope (inline variables) • FreeAndNil
  • 32.
    Improper Memory Access •This includes scenarios where a program accesses uninitialized, freed, or out-of-scope memory, which can lead to unpredictable behavior, including the exposure of sensitive information or system crashes. • Delphi’s string types and dynamic arrays are managed types, reducing the risk of improper memory access. • Access to these types is checked at runtime to prevent out- of-bounds errors and uninitialized memory access. • Generic collections enforce type safety on the contents of the collection, removing the need to type cast items when removed from the collection.
  • 33.
    Memory Leaks • Whilenot always directly exploitable, memory leaks can lead to a degradation of system performance over time, eventually causing software or systems to crash. • This can be leveraged in certain attacks to facilitate more severe exploits. • Delphi’s interface reference counting, and the component owner model limit memory leaks. • For manually allocated objects the TRY/FINALLY block helps ensure memory is freed. • Use the built-in memory leak reporting tool to identify and resolve leaks during the development phase.
  • 34.
    Best Practices for MemorySafety Time for the good stuff
  • 35.
    The Basics 1. Alwaysuse the minimal scope possible, even better if you use inline variable declarations. 2. If you create or allocated it, then free it (unless there is a specific agreement to hand it off) 3. References accessible in a broader scope should always be set to nil when not assigned. 4. If you create it in the constructor, free it in the destructor. 5. Use TRY/FINALLY when creating local objects. • If creating multiple objects, set the references all to nil first. 6. Address ALL HINTS and WARNINGS
  • 36.
    Creating Multiple Objects varObj1, Obj2, Obj3: TMyObject; begin Obj1 := nil; Obj2 := nil; Obj3 := TMyObject.Create; try Obj2 := TMyObject.Create; Obj1 := TMyObject.Create; // Use the objects finally Obj3.Free; Obj2.Free; Obj1.Free; end; end; • The order isn’t important • Free isn’t virtual and is safe to call on a nil object. • docwiki.embarcadero.com/RADStudio/en/Me thods_(Delphi)#Destructors
  • 37.
    Constructors and Destructors constructorTShape.Create (Owner: TComponent); begin // Initialize inherited parts inherited Create(Owner); // Change inherited properties Width := 65; // Initialize new fields FPen := TPen.Create; end; destructor TShape.Destroy; begin FBrush.Free; FPen.Free; inherited Destroy; end; • When an exception is raised during the creation of an object, Destroy is automatically called to dispose of the unfinished object. • Constructor sets the fields of a new object to zero or empty values before performing other actions • Class-type and pointer-type fields in a partially constructed object are always nil. • A destructor should check for nil values before operating on class-type or pointer-type fields. • Calling the Free method (defined in TObject) rather than Destroy offers a convenient way to check for nil values before destroying an object. docwiki.embarcadero.com/RADStudio/en/Methods_(Delphi)#Constructors docwiki.embarcadero.com/RADStudio/en/Methods_(Delphi)#Destructors
  • 38.
    Address Space Randomization(ASLR) • {$DYNAMICBASE} enables the Address Space Randomization (ASLR) on Windows Vista and above, providing secure protection against attacks based on buffer overrun. • Switch {$DYNAMICBASE} on to prevent attacks in memory- corruption vulnerabilities by enabling ASLR to randomly arrange the address space positions for the stack, heap, libraries, and key data areas of a process. • docwiki.embarcadero.com/RADStudio/en/Dynamic_base_(Delphi)
  • 39.
    High-entropy 64-bit ASLR •Enabling the flag {$HIGHENTROPYVA} provides secure protection against attacks based on buffer overrun. • Enable this flag to prevent attacks in memory-corruption vulnerabilities by enabling ASLR to randomly arrange the address space positions for the stack, heap, libraries, and key data areas of a process. • docwiki.embarcadero.com/RADStudio/en/Support_high- entropy_64-bit_ASLR
  • 40.
    Data Execution Prevention(DEP) • Enabled by Default {$NXCOMPAT ON} • docwiki.embarcadero.com/RADStudio/en/Data_Execution_Prevention_compatible • Windows feature that prevents executable code launching from places it's not supposed to. • Marks some areas memory as being for data only, not allowing executable code from running. • Make it harder for buffer overflows to execute code. • learn.microsoft.com/en-us/windows/win32/memory/data-execution-prevention
  • 41.
    Controversial Advice • Leaveruntime checks enabled in production. • Range Checking {$R+} {$RANGECHECKS ON} • IO Checking {$T+} {$TYPEDADDRESS ON} • Overflow Checking {$Q+} {$OVERFLOWCHECKS ON} • Assertions {$C+} {$ASSERTIONS ON} • Make liberal use of assertions • Safety is usually worth the small impact on performance • Consider Generic collections to enforce type safety • When storing Objects use the Object version of the collection and OwnsObjects option
  • 42.
    $R- $R+ $R+ producesERangeError exception, without it just runs! Win32
  • 43.
  • 44.
    Going Further • ReadDelphi Memory Management by Dalija Prasnikar & Neven Prasnikar Jr. • https://igoto.co/DelphiMM • Make use of Records, Interfaces, Smart Pointers, and Auto Release Pools when possible. • dalijap.blogspot.com/2021/02/autorelease-pool.html • Use Spring4D’s Smart Pointers • Shared<T> and Weak<T> • bitbucket.org/sglienke/spring4d • Use FastMM’s ReportMemoryLeaksOnShutdown during development (don’t ship with it on)
  • 45.
    Dalija’s Auto ReleasePool var Foo: TFoo; Bar: TBar; begin Foo := TFoo.Create; AutoPool.Add(Foo); Bar := TBar.Create; AutoPool.Add(Bar); // use Foo and Bar end; // AutoPool frees Foo and Bar dalijap.blogspot.com/2021/02/autorelease-pool.html
  • 46.
    JEDI JCL SafeGuard var SafeGuard:ISafeGuard; Strings: TStrings; begin Strings := TStrings(Guard(TStringList.Create, SafeGuard)); Strings.ReadFromFile('d:delphijclsourceJclBase.pas'); // code to manipulate strings goes here Strings.SaveToFile('d:delphijclsourceJclBase.pas'); end; // SafeGuard frees the Tstrings https://wiki.delphi-jedi.org/wiki/JCL_Help:Guard@Pointer@IMultiSafeGuard
  • 47.
    JEDI JCL MultiSafeGuard var SafeGuard:IMultiSafeGuard; O1, O2: TObject; begin O1 := Guard(TObject.Create, SafeGuard); O2 := Guard(TObject.Create, SafeGuard); // use O1 and O2 here end; // Guard frees objects wiki.delphi-jedi.org/wiki/JCL_Help:IMultiSafeGuard
  • 48.
    More on Spring4D •Installation: youtube.com/watch?v=cusRfnlow0g • Download the code and run Build.dpr • It takes quite a while • Introduction: youtube.com/watch?v=izI0Vah2CRs • Source: bitbucket.org/sglienke/spring4d/ • Wiki: bitbucket.org/sglienke/spring4d/wiki/browse/ • Docs: devjetsoftware.com/docs/spring4d/ • Support: • Email list: groups.google.com/g/spring4d • Stefan’s blog: delphisorcery.blogspot.com/ • Delphi Praxis 3rd Party: en.delphipraxis.net/forum/13-delphi-third-party/ • Stack Overflow: stackoverflow.com/questions/tagged/spring4d
  • 49.
    Shared<T> var sl: Shared<TStringList>; begin sl :=TStringList.Create; sl.Value.Add('Shared<T>'); log.Items.Add(sl.Value.ClassName); // Pass as a TStrings Log.Items.AddStrings(sl); // Freed when it goes out of scope end;
  • 50.
    IShared<T> var sl: IShared<TStringList>; begin sl :=Shared.Make(TStringList.Create); // Directly access members sl.Add('IShared<T>'); log.Items.Add(sl.ClassName); // Freed when it goes out of scope end;
  • 51.
    IShared<T> with Finalizer var sl:IShared<TStrings>; begin // The type is TStrings, but the instance is TStringList sl := Shared.Make<TStrings>(TStringList.Create, procedure(const s: TStrings) begin Sleep(1000); s.Add(‘Goodbye'); Log.Items.AddStrings(s); // the finalizer replaces the default one so must free it here s.Free; end); sl.Add('IShared<T> with Finalizer'); // Finalizer called when it goes out of scope end;
  • 52.
    Weak<T> var sl: TStringList; weakRef: Weak<TStringList>; begin sl:= TStringList.Create; weakRef := sl; sl.Add('Hello World'); Log.Items.Add(WeakRef.IsAlive.ToString(False)); Log.Items.AddStrings(WeakRef); // Usually any *other* reference pointing to sl after this Free // Will have a "dangling reference" FreeAndNil would not help with that either sl.Free; // with Weak<T> this will work on any platform Log.Items.Add(weakRef.IsAlive.ToString(TUseBoolStrs.True)); Log.Items.Add(Assigned(weakRef.Target).ToString(TUseBoolStrs.True)); Log.Items.Add((weakRef <> nil).ToString(TUseBoolStrs.True)); end;
  • 53.
    More Tools • Usetools like EurkaLog and Deleaker • Run TMS FixInsight to find more Hints and Warnings • Use DerScanner to find security issues • Use SonarQube for Delphi for more analysis
  • 54.
  • 55.
    GDK Software • Officesin US, UK, the Netherlands, & Brazil • 25+ Delphi development experts • gdksoftware.com • We are Delphi. • Codolex 2.0 is now Free • More than just Delphi low-code • codolex.com
  • 56.
    Delphi Summit • Returnof the global Delphi conference • Amsterdam - 13 and 14 June 2024 • 2 Days, 3 Tracks, 23 Speakers, 26 Sessions • All sessions recorded • Attend in person € 399 or online only € 199 • delphisummit.com
  • 57.
    Webinar Logistics • Besure you registered for slides, code, and replays mailing.gdksoftware.com/webinars • Future webinars in series • Essential Delphi Add-Ins (19th of June) • Debugging in Delphi (26th of June) • Ask Jim Anything (10th of July) • Build Automation and Supply Chain Security (24th of July) • Essential Delphi Libraries (7th of August) • Open to webinar suggestions too! jim@gdksoftware.com youtube.com/live/-SotB4lloII youtube.com/live/-SotB4lloII Replay The YouTube logo is made of a red round-rectangular box with a white triangular "play" button inside and the word "YouTube" written in black.
  • 58.
    Q&A youtube.com/live/-SotB4lloII youtube.com/live/-SotB4lloII Replay The YouTube logois made of a red round-rectangular box with a white triangular "play" button inside and the word "YouTube" written in black.
  • 59.