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

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 

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…