SlideShare a Scribd company logo
1 of 22
Download to read offline
Secure .NET programming
    ante.gulam[at]ri-ing.hr
                     Skype: ante.gulam
                Twitter: h44rp (L4uf3r)
              http://www.phearless.org
Agenda [Overview]
• .NET platform [intro (CLR, MSIL, JIT, PE/COFF..)]
• MSIL decompile/recompile (ILDAsm/ILAsm).exe
• Guidelines for safer code[SecureString class, unsafe,
  checked keywords, ‘foreign’ delegates..]
• Underneath the ice: vulnerabilities
• WPF/WCF configuration files[(*.config), debug=“true”,
  deployment retail=“true”…]
• WCF communication (SOAP/xml, REST/json) – (HTTP/TCP vs.
  WS) vs. SSL, hashing, auth etc.
• Runtime security – CAS vs. RBS, stack walking, reflection,
  advance framework configuration
• Outro [conclusion]
.NET platform [intro (CLR, MSIL, JIT,
                      PE/COFF..)]
• About .NET framework playground (1.0 - 4.0)
    – Bottom to top: from BCL (FCL) to Linq
• Common Language Runtime engine details
• .NET assembly structure
    – PE header, CLR header, CLR metadata, CLR IL code, Native data
• MSIL compiling and metalanguage basics
• Metadata (.param, .assembly, .method…)…)
• .NET development technologies
    – (WPF/WinForms, WCF, ASP.NET, Silverlight...)
• Default .NET security measures (OOTB)
    – Buffer overruns (System.IndexOutOfRangeException)
    – Format strings StringBuilder.AppendFormat (%n prevention)
    – Arithmetic overflow (unsigned/signed mix error (cast ))
    – CS0123 error (f() pointer type check), InvalidCastException (base/derived)
• Source code manipulation?
• MSIL reversing (dll hijacking), IL ASM – speaking CLR’s language..
    – Change the logic, add backdoors, kraak and smaak
MSIL decompile/recompile (ILDAsm/ILAsm)
• Attacking executable files (!= attack on structures in
  memory / at runtime)
• Tools for decompilation(JetBrain dotPeek, Dis#,
  Salamander, .NET Reflector, IL Spy, Gray Wolf)
• ILAsm.exe/ILDasm.exe
• ILAsm basics (instruction set - Inside Microsoft .NET IL
  Assembler)
• Program logic  object control  access and value
  manipulation!!!
• Obfuscation/Deobfuscation (Salamander, Skater,
  Dotfuscator, Eazfuscator .NET...)
   – symbol renaming, overload and more...
.NET obfuscation example
symbol renaming with overload induction
Guidelines for safer code[SecureString class,
      unsafe, checked keywords, delegates…]

• Memory dumping (SecureString mandatory!!)
• Unmanaged code (when and where go ‘unsafe’?)
   – int* p = stackalloc int[32];
• Checked keyword in practice (OverflowException)
• Assert usage? (CAS classes, PermissionSet class)
• Security of delegates “from outside”
   – SecurityPermission(SecurityPermissionFlag.Execution).PermitOnly();
   – AllowPartiallyTrustedCallersAttribute
• Input validation (SQL..), hardcoding, exception throwing,
  assemblies, privileges, crypto…
• Code signing (GAC)
   – Authenticode (chaining certificates), Strong Names (PKI)
   – MakeCat , SignTool, Strong Name Tool (sn.exe)
Guidelines for safer code[SecureString class,
        unsafe, checked keywords, delegates…]

• Memory dumping (SecureString mandatory!!)
• Unmanaged code (when and where go ‘unsafe’?)
             System.Security.SecureString X = new System.Security.SecureString();
     – int* p = stackalloc int[32];
                    secString.AppendChar(p);
• Checked keyword in practice (OverflowException)
                IntPtr p = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(X);
• Assert usage?string dekript = System.Runtime.InteropServices.Marshal.PtrToStringUni(p);
                  (CAS classes, PermissionSet class)
• Security of delegates “from outside”
                secString.Dispose();
     – SecurityPermission(SecurityPermissionFlag.Execution).PermitOnly();
     – AllowPartiallyTrustedCallersAttribute
• Input validation (SQL..), hardcoding, exception throwing,
  assemblies, privileges, crypto…
• Code signing (GAC)
     – Authenticode (chaining certificates), Strong Names (PKI)
     – MakeCat , SignTool, Strong Name Tool (sn.exe)
Underneath the ice: vulnerabilities
• Web vulnerabilities as we know them (XSS, SQL injection, CSRF,
  Response splitting (CRLF injection), SOAP injection, HPP, Xpath
  injection, File upload/download, directory traversal …)
• Using technologies like LINQ/Entity framework as SQL query
  language for data sanitization
• ValidateRequest="true“ inside Machine.config
• Compare validator <asp:CompareValidator >, htmlEncode
• Games without frontiers: Oracle Padding (CBC), Object parsing,
  Direct Object Reference, Error handling, GV DataKeys……
• TFS – Check-in/Get latest version sniffing?
   – WYSIWYG on the wire/air (POST/gzip mess-up)
   – Always HTTPS for Team Explorer
<Button Height="23" Margin="10,130,90,0“
Name="btnPromjeni" VerticalAlignment=“
Top" Click="btnPromjeni_Click">Spremi</Button>
Don’t do this at home (or work)

                         Real-world examples:

                                    the bad ones

                             ugly
                         the
                     and
                 bad
             the
        bad,
    The
Bad practice No.1
     binding ConnString to Cb control
• ddlServer.DataSource = sc.DohvatiServere();
                 ddlServer.DataTextField=ServerName";
                 ddlServer.DataValueField=ConnString";
                 ddlServer.DataBind();

  ConnString = “DataSource=10.10.10.2DB1;Initial
  Catalog=Database_1;Persist Security Info=True;User
  ID=korisnik1;Password=123#pass”
Bad practice No.2
     ad hoc SQL query – passing input
• protected void btn1_Click(object sender, EventArgs e)
   { string dbcon =
  "Server=(local);Database=Northwind;Integrated
  Security=SSPI";
  string cmdStr = "insert into Korisnici (ImePrez, Telefon)
       values ('" + txtIme.Text + "', '" + txtTel.Text + "')";  
  using (SqlConnection konekcija = new
  SqlConnection(dbcon)) = new SqlCommand(cmdStr, conn))
  { conn.Open(); cmd.ExecuteNonQuery(); }
  using (SqlCommand cmd = new SqlCommand(cmdStr,
  konekcija)) { konekcija.Open(); cmd.ExecuteNonQuery(); }
}
[Drive Letter]:WindowsMicrosoft.NetFramework
                      [.NET version number]config

 WPF/WCF configuration files[(*.config),
debug=“true”, deployment retail=“true”…]
• Default .NET configuration files
   –   enterprisesec.config - enterprise-level security policies
   –   security.config - machine-level security
   –   machine.config - .NET environment installation settings
   –   web.config / app.config – default settings
• Compilation debug=“true” problem
   – Runtime mem, batch optimization …
• Deployment retail=“true” as a solution
• Max message size value (“2147483647”)
• Encryption of configuration files
   – Command line tools / inside code
[Drive Letter]:WindowsMicrosoft.NetFramework
                          [.NET version number]config

 WPF/WCF configuration files[(*.config),
debug=“true”, deployment retail=“true”…]
• Default .NET configuration files
     –   enterprisesec.config - enterprise-level security policies
     –   security.config - machine-level security
                                 [DriveLetter]:WindowsMicrosoft.Net
     –                           Framework[.NET version number]config
         machine.config - .NET environment installation settings
     –   web.config / app.config – default settings
• Compilation debug=“true” problem
     – Runtime mem, batch void Page_Load(object sender, EventArgs e)
                  protected optimization …
                   {
•   Deployment retail=“true” as aConfigurationSection configSection;
                   Configuration config; solution
•   Max message size value (“2147483647”) = config.GetSection(“
                   config = WebConfigurationManager.OpenWebConfiguration
                   (Request.ApplicationPath); configSection
•   Encryption of configuration files
                   connectionStrings");
     – Command line tools / inside null)
                   if (configSection != code
                   { if (!(configSection.SectionInformation.IsLocked))
                   { configSection.SectionInformation.ProtectSection
                   ("DataProtectionConfigurationProvider"); config.Save(); } } }
WCF communication (SOAP/xml, REST/json) -
    (basicHTTP vs. WS) vs. SSL, hashing, auth etc.
• WCF in details (rolling in the deep)
• SOAP vs. REST inside MS service
• Bindings and their security (basic, ws, web, nettcp, custom…)
    – transport, encoding & protocol
• SSL tunneling or secure binding (WS – SCT/RSTR)?
    – Transport vs. Message level, in-transit vs. Processing
• Filtering remote access to WCF services (IP)
• Message integrity check
    – Hashing xml/json messages (HMAC, SHA1..)
• Custom authorization for service access
    – SOAP header based, method argument, WCF session…
• Request load-balancing (WCF throttling)
    – Setting maxConcurrent(Calls (16),Sessions (10),Instances)
Runtime security – CAS vs. RBS, stack walking,
reflection, advance framework configuration
• RBS - Role-Based Security
• CAS - Code-Access Security (evidence based permissions)
   – Evaluate Assembly
• Stack walking? Method access grant..
• LinkDemand vs. stack walk (Luring Attacks)
   – Immediate caller vs. all callers
• Garbage collector
• Reflection (ReflectionPermission (CAS))
   – Reflection.Emit – create assembly
   – System.Reflection.Assembly.Load
   – System.Reflection.MethodInfo.Invoke
• Configuring framework (tuning settings)
Outro [conclusion]
• Microsoft .NET platform == secure env. ???
   – This is the world as we know it: brainless development
• Stay tuned and up2date: “Keep your friends close, and your
  enemies closer.” Sun Tzu
• Make safest possible .NET environment (CAS, RBS..)
• Constrain and sanitize all input data
• Encrypt your config’s (Triple DES)
• WCF wargames (“You have all the weapons you need… now fight!”)
   – Encrypt, authenticate, check integrity, authorization
   – DPAPI for sensitive data (protected registry key)
• Secure assemblies (obfuscate, pack, request minimum)
   – .NETZ compressor (OSS), .netshrink (LZMA alg. + pass)..
thank you for your attention
           questions and comments




                         ?
             ante.gulam[at]ri-ing.hr
Shouts: h4z4rd, c0ld, n00ne, fr1c, c0de, all gnoblets, phZine crew…

More Related Content

What's hot

">&lt;img src="x">
">&lt;img src="x">">&lt;img src="x">
">&lt;img src="x">testeracua
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by pythonwonyong hwang
 
I Have the Power(View)
I Have the Power(View)I Have the Power(View)
I Have the Power(View)Will Schroeder
 
Metaprogramming with JavaScript
Metaprogramming with JavaScriptMetaprogramming with JavaScript
Metaprogramming with JavaScriptTimur Shemsedinov
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCanSecWest
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsAndrei Pangin
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsTimur Shemsedinov
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra Max Penet
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBMongoDB
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM ProfilingAndrei Pangin
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for CassandraEdward Capriolo
 
Node.js in action
Node.js in actionNode.js in action
Node.js in actionSimon Su
 
Webinar slides: How to Secure MongoDB with ClusterControl
Webinar slides: How to Secure MongoDB with ClusterControlWebinar slides: How to Secure MongoDB with ClusterControl
Webinar slides: How to Secure MongoDB with ClusterControlSeveralnines
 
Password (in)security
Password (in)securityPassword (in)security
Password (in)securityEnrico Zimuel
 
When dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniquesWhen dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniquesWim Godden
 
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門tamtam180
 

What's hot (19)

">&lt;img src="x">
">&lt;img src="x">">&lt;img src="x">
">&lt;img src="x">
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by python
 
I Have the Power(View)
I Have the Power(View)I Have the Power(View)
I Have the Power(View)
 
Metaprogramming with JavaScript
Metaprogramming with JavaScriptMetaprogramming with JavaScript
Metaprogramming with JavaScript
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
 
Everything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap DumpsEverything you wanted to know about Stack Traces and Heap Dumps
Everything you wanted to know about Stack Traces and Heap Dumps
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.js
 
Clojure ♥ cassandra
Clojure ♥ cassandra Clojure ♥ cassandra
Clojure ♥ cassandra
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
Building Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDBBuilding Your First Data Science Applicatino in MongoDB
Building Your First Data Science Applicatino in MongoDB
 
Top Node.js Metrics to Watch
Top Node.js Metrics to WatchTop Node.js Metrics to Watch
Top Node.js Metrics to Watch
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
 
Node.js in action
Node.js in actionNode.js in action
Node.js in action
 
Webinar slides: How to Secure MongoDB with ClusterControl
Webinar slides: How to Secure MongoDB with ClusterControlWebinar slides: How to Secure MongoDB with ClusterControl
Webinar slides: How to Secure MongoDB with ClusterControl
 
Password (in)security
Password (in)securityPassword (in)security
Password (in)security
 
When dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniquesWhen dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniques
 
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
Introduction httpClient on Java11 / Java11時代のHTTPアクセス再入門
 
Nancy + rest mow2012
Nancy + rest   mow2012Nancy + rest   mow2012
Nancy + rest mow2012
 

Similar to Secure .NET programming

Secure code
Secure codeSecure code
Secure codeddeogun
 
Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by defaultSlawomir Jasek
 
Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by defaultSecuRing
 
Containers: The What, Why, and How
Containers: The What, Why, and HowContainers: The What, Why, and How
Containers: The What, Why, and HowSneha Inguva
 
Attacks against Microsoft network web clients
Attacks against Microsoft network web clients Attacks against Microsoft network web clients
Attacks against Microsoft network web clients Positive Hack Days
 
InSecure Remote Operations - NullCon 2023 by Yossi Sassi
InSecure Remote Operations - NullCon 2023 by Yossi SassiInSecure Remote Operations - NullCon 2023 by Yossi Sassi
InSecure Remote Operations - NullCon 2023 by Yossi SassiYossi Sassi
 
Talk about html5 security
Talk about html5 securityTalk about html5 security
Talk about html5 securityHuang Toby
 
Secure erasure code based cloud storage system with secure data forwarding
Secure erasure code based cloud storage system with secure data forwardingSecure erasure code based cloud storage system with secure data forwarding
Secure erasure code based cloud storage system with secure data forwardingPriyank Rupera
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applicationsDevnology
 
WCF Security, FSec
WCF Security, FSecWCF Security, FSec
WCF Security, FSecAnte Gulam
 
Monitoring with Prometheus
Monitoring with PrometheusMonitoring with Prometheus
Monitoring with PrometheusShiao-An Yuan
 
JS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsJS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsTimur Shemsedinov
 
Automate or die! Rootedcon 2017
Automate or die! Rootedcon 2017Automate or die! Rootedcon 2017
Automate or die! Rootedcon 2017Toni de la Fuente
 
Toni de la Fuente - Automate or die! How to survive to an attack in the Cloud...
Toni de la Fuente - Automate or die! How to survive to an attack in the Cloud...Toni de la Fuente - Automate or die! How to survive to an attack in the Cloud...
Toni de la Fuente - Automate or die! How to survive to an attack in the Cloud...RootedCON
 
Dynamic Database Credentials: Security Contingency Planning
Dynamic Database Credentials: Security Contingency PlanningDynamic Database Credentials: Security Contingency Planning
Dynamic Database Credentials: Security Contingency PlanningSean Chittenden
 
How Secure Are Docker Containers?
How Secure Are Docker Containers?How Secure Are Docker Containers?
How Secure Are Docker Containers?Ben Hall
 
Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming Stratio
 

Similar to Secure .NET programming (20)

Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
 
Secure code
Secure codeSecure code
Secure code
 
Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by default
 
Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by default
 
Containers: The What, Why, and How
Containers: The What, Why, and HowContainers: The What, Why, and How
Containers: The What, Why, and How
 
Attacks against Microsoft network web clients
Attacks against Microsoft network web clients Attacks against Microsoft network web clients
Attacks against Microsoft network web clients
 
InSecure Remote Operations - NullCon 2023 by Yossi Sassi
InSecure Remote Operations - NullCon 2023 by Yossi SassiInSecure Remote Operations - NullCon 2023 by Yossi Sassi
InSecure Remote Operations - NullCon 2023 by Yossi Sassi
 
Talk about html5 security
Talk about html5 securityTalk about html5 security
Talk about html5 security
 
Secure erasure code based cloud storage system with secure data forwarding
Secure erasure code based cloud storage system with secure data forwardingSecure erasure code based cloud storage system with secure data forwarding
Secure erasure code based cloud storage system with secure data forwarding
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
WCF Security, FSec
WCF Security, FSecWCF Security, FSec
WCF Security, FSec
 
Monitoring with Prometheus
Monitoring with PrometheusMonitoring with Prometheus
Monitoring with Prometheus
 
JS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js AntipatternsJS Fest 2019 Node.js Antipatterns
JS Fest 2019 Node.js Antipatterns
 
Rails Security
Rails SecurityRails Security
Rails Security
 
Stress test data pipeline
Stress test data pipelineStress test data pipeline
Stress test data pipeline
 
Automate or die! Rootedcon 2017
Automate or die! Rootedcon 2017Automate or die! Rootedcon 2017
Automate or die! Rootedcon 2017
 
Toni de la Fuente - Automate or die! How to survive to an attack in the Cloud...
Toni de la Fuente - Automate or die! How to survive to an attack in the Cloud...Toni de la Fuente - Automate or die! How to survive to an attack in the Cloud...
Toni de la Fuente - Automate or die! How to survive to an attack in the Cloud...
 
Dynamic Database Credentials: Security Contingency Planning
Dynamic Database Credentials: Security Contingency PlanningDynamic Database Credentials: Security Contingency Planning
Dynamic Database Credentials: Security Contingency Planning
 
How Secure Are Docker Containers?
How Secure Are Docker Containers?How Secure Are Docker Containers?
How Secure Are Docker Containers?
 
Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming Spark Summit - Stratio Streaming
Spark Summit - Stratio Streaming
 

Recently uploaded

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 

Secure .NET programming

  • 1. Secure .NET programming ante.gulam[at]ri-ing.hr Skype: ante.gulam Twitter: h44rp (L4uf3r) http://www.phearless.org
  • 2. Agenda [Overview] • .NET platform [intro (CLR, MSIL, JIT, PE/COFF..)] • MSIL decompile/recompile (ILDAsm/ILAsm).exe • Guidelines for safer code[SecureString class, unsafe, checked keywords, ‘foreign’ delegates..] • Underneath the ice: vulnerabilities • WPF/WCF configuration files[(*.config), debug=“true”, deployment retail=“true”…] • WCF communication (SOAP/xml, REST/json) – (HTTP/TCP vs. WS) vs. SSL, hashing, auth etc. • Runtime security – CAS vs. RBS, stack walking, reflection, advance framework configuration • Outro [conclusion]
  • 3. .NET platform [intro (CLR, MSIL, JIT, PE/COFF..)] • About .NET framework playground (1.0 - 4.0) – Bottom to top: from BCL (FCL) to Linq • Common Language Runtime engine details • .NET assembly structure – PE header, CLR header, CLR metadata, CLR IL code, Native data • MSIL compiling and metalanguage basics • Metadata (.param, .assembly, .method…)…) • .NET development technologies – (WPF/WinForms, WCF, ASP.NET, Silverlight...) • Default .NET security measures (OOTB) – Buffer overruns (System.IndexOutOfRangeException) – Format strings StringBuilder.AppendFormat (%n prevention) – Arithmetic overflow (unsigned/signed mix error (cast )) – CS0123 error (f() pointer type check), InvalidCastException (base/derived) • Source code manipulation? • MSIL reversing (dll hijacking), IL ASM – speaking CLR’s language.. – Change the logic, add backdoors, kraak and smaak
  • 4. MSIL decompile/recompile (ILDAsm/ILAsm) • Attacking executable files (!= attack on structures in memory / at runtime) • Tools for decompilation(JetBrain dotPeek, Dis#, Salamander, .NET Reflector, IL Spy, Gray Wolf) • ILAsm.exe/ILDasm.exe • ILAsm basics (instruction set - Inside Microsoft .NET IL Assembler) • Program logic  object control  access and value manipulation!!! • Obfuscation/Deobfuscation (Salamander, Skater, Dotfuscator, Eazfuscator .NET...) – symbol renaming, overload and more...
  • 5. .NET obfuscation example symbol renaming with overload induction
  • 6.
  • 7.
  • 8. Guidelines for safer code[SecureString class, unsafe, checked keywords, delegates…] • Memory dumping (SecureString mandatory!!) • Unmanaged code (when and where go ‘unsafe’?) – int* p = stackalloc int[32]; • Checked keyword in practice (OverflowException) • Assert usage? (CAS classes, PermissionSet class) • Security of delegates “from outside” – SecurityPermission(SecurityPermissionFlag.Execution).PermitOnly(); – AllowPartiallyTrustedCallersAttribute • Input validation (SQL..), hardcoding, exception throwing, assemblies, privileges, crypto… • Code signing (GAC) – Authenticode (chaining certificates), Strong Names (PKI) – MakeCat , SignTool, Strong Name Tool (sn.exe)
  • 9. Guidelines for safer code[SecureString class, unsafe, checked keywords, delegates…] • Memory dumping (SecureString mandatory!!) • Unmanaged code (when and where go ‘unsafe’?) System.Security.SecureString X = new System.Security.SecureString(); – int* p = stackalloc int[32]; secString.AppendChar(p); • Checked keyword in practice (OverflowException) IntPtr p = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(X); • Assert usage?string dekript = System.Runtime.InteropServices.Marshal.PtrToStringUni(p); (CAS classes, PermissionSet class) • Security of delegates “from outside” secString.Dispose(); – SecurityPermission(SecurityPermissionFlag.Execution).PermitOnly(); – AllowPartiallyTrustedCallersAttribute • Input validation (SQL..), hardcoding, exception throwing, assemblies, privileges, crypto… • Code signing (GAC) – Authenticode (chaining certificates), Strong Names (PKI) – MakeCat , SignTool, Strong Name Tool (sn.exe)
  • 10. Underneath the ice: vulnerabilities • Web vulnerabilities as we know them (XSS, SQL injection, CSRF, Response splitting (CRLF injection), SOAP injection, HPP, Xpath injection, File upload/download, directory traversal …) • Using technologies like LINQ/Entity framework as SQL query language for data sanitization • ValidateRequest="true“ inside Machine.config • Compare validator <asp:CompareValidator >, htmlEncode • Games without frontiers: Oracle Padding (CBC), Object parsing, Direct Object Reference, Error handling, GV DataKeys…… • TFS – Check-in/Get latest version sniffing? – WYSIWYG on the wire/air (POST/gzip mess-up) – Always HTTPS for Team Explorer
  • 11. <Button Height="23" Margin="10,130,90,0“ Name="btnPromjeni" VerticalAlignment=“ Top" Click="btnPromjeni_Click">Spremi</Button>
  • 12. Don’t do this at home (or work) Real-world examples: the bad ones ugly the and bad the bad, The
  • 13. Bad practice No.1 binding ConnString to Cb control • ddlServer.DataSource = sc.DohvatiServere();                ddlServer.DataTextField=ServerName";                ddlServer.DataValueField=ConnString";                ddlServer.DataBind(); ConnString = “DataSource=10.10.10.2DB1;Initial Catalog=Database_1;Persist Security Info=True;User ID=korisnik1;Password=123#pass”
  • 14. Bad practice No.2 ad hoc SQL query – passing input • protected void btn1_Click(object sender, EventArgs e) { string dbcon = "Server=(local);Database=Northwind;Integrated Security=SSPI"; string cmdStr = "insert into Korisnici (ImePrez, Telefon) values ('" + txtIme.Text + "', '" + txtTel.Text + "')";   using (SqlConnection konekcija = new SqlConnection(dbcon)) = new SqlCommand(cmdStr, conn)) { conn.Open(); cmd.ExecuteNonQuery(); } using (SqlCommand cmd = new SqlCommand(cmdStr, konekcija)) { konekcija.Open(); cmd.ExecuteNonQuery(); } }
  • 15.
  • 16. [Drive Letter]:WindowsMicrosoft.NetFramework [.NET version number]config WPF/WCF configuration files[(*.config), debug=“true”, deployment retail=“true”…] • Default .NET configuration files – enterprisesec.config - enterprise-level security policies – security.config - machine-level security – machine.config - .NET environment installation settings – web.config / app.config – default settings • Compilation debug=“true” problem – Runtime mem, batch optimization … • Deployment retail=“true” as a solution • Max message size value (“2147483647”) • Encryption of configuration files – Command line tools / inside code
  • 17. [Drive Letter]:WindowsMicrosoft.NetFramework [.NET version number]config WPF/WCF configuration files[(*.config), debug=“true”, deployment retail=“true”…] • Default .NET configuration files – enterprisesec.config - enterprise-level security policies – security.config - machine-level security [DriveLetter]:WindowsMicrosoft.Net – Framework[.NET version number]config machine.config - .NET environment installation settings – web.config / app.config – default settings • Compilation debug=“true” problem – Runtime mem, batch void Page_Load(object sender, EventArgs e) protected optimization … { • Deployment retail=“true” as aConfigurationSection configSection; Configuration config; solution • Max message size value (“2147483647”) = config.GetSection(“ config = WebConfigurationManager.OpenWebConfiguration (Request.ApplicationPath); configSection • Encryption of configuration files connectionStrings"); – Command line tools / inside null) if (configSection != code { if (!(configSection.SectionInformation.IsLocked)) { configSection.SectionInformation.ProtectSection ("DataProtectionConfigurationProvider"); config.Save(); } } }
  • 18.
  • 19. WCF communication (SOAP/xml, REST/json) - (basicHTTP vs. WS) vs. SSL, hashing, auth etc. • WCF in details (rolling in the deep) • SOAP vs. REST inside MS service • Bindings and their security (basic, ws, web, nettcp, custom…) – transport, encoding & protocol • SSL tunneling or secure binding (WS – SCT/RSTR)? – Transport vs. Message level, in-transit vs. Processing • Filtering remote access to WCF services (IP) • Message integrity check – Hashing xml/json messages (HMAC, SHA1..) • Custom authorization for service access – SOAP header based, method argument, WCF session… • Request load-balancing (WCF throttling) – Setting maxConcurrent(Calls (16),Sessions (10),Instances)
  • 20. Runtime security – CAS vs. RBS, stack walking, reflection, advance framework configuration • RBS - Role-Based Security • CAS - Code-Access Security (evidence based permissions) – Evaluate Assembly • Stack walking? Method access grant.. • LinkDemand vs. stack walk (Luring Attacks) – Immediate caller vs. all callers • Garbage collector • Reflection (ReflectionPermission (CAS)) – Reflection.Emit – create assembly – System.Reflection.Assembly.Load – System.Reflection.MethodInfo.Invoke • Configuring framework (tuning settings)
  • 21. Outro [conclusion] • Microsoft .NET platform == secure env. ??? – This is the world as we know it: brainless development • Stay tuned and up2date: “Keep your friends close, and your enemies closer.” Sun Tzu • Make safest possible .NET environment (CAS, RBS..) • Constrain and sanitize all input data • Encrypt your config’s (Triple DES) • WCF wargames (“You have all the weapons you need… now fight!”) – Encrypt, authenticate, check integrity, authorization – DPAPI for sensitive data (protected registry key) • Secure assemblies (obfuscate, pack, request minimum) – .NETZ compressor (OSS), .netshrink (LZMA alg. + pass)..
  • 22. thank you for your attention questions and comments ? ante.gulam[at]ri-ing.hr Shouts: h4z4rd, c0ld, n00ne, fr1c, c0de, all gnoblets, phZine crew…