The document discusses database input vulnerabilities like SQL injection and inference problems. It provides remedies like using parameterized queries and stored procedures to prevent SQL injection, and applying statistical inference controls to queries to prevent sensitive data from being inferred. The document covers topics like never connecting as a system admin, building SQL statements securely, and using quotation functions to avoid injection when dynamically building SQL.
Implementing CQRS and Event Sourcing with RavenDBOren Eini
CQRS stands for Command Query Responsibility Segregation. That is, that command stack and query stack are designed separately. This leads to a dramatic simplification of design and potential enhancement of scalability.
Events are a new trend in software industry. In real-world, we perform actions and these actions generate a reaction. Event Sourcing is about persisting events and rebuilding the state of the aggregates from recorded events.
In this talk I will share a lot of examples about how to effective implementing CQRS and Event Sourcing with RavenDB
Introduction to Reactive Extensions (Rx)Tamir Dresher
Presentations from the june meeting of IDNDUG
http://ariely.info/Communities/IDNDUG/IDNDUG19thJune2013/tabid/171
The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, andparameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers
Implementing CQRS and Event Sourcing with RavenDBOren Eini
CQRS stands for Command Query Responsibility Segregation. That is, that command stack and query stack are designed separately. This leads to a dramatic simplification of design and potential enhancement of scalability.
Events are a new trend in software industry. In real-world, we perform actions and these actions generate a reaction. Event Sourcing is about persisting events and rebuilding the state of the aggregates from recorded events.
In this talk I will share a lot of examples about how to effective implementing CQRS and Event Sourcing with RavenDB
Introduction to Reactive Extensions (Rx)Tamir Dresher
Presentations from the june meeting of IDNDUG
http://ariely.info/Communities/IDNDUG/IDNDUG19thJune2013/tabid/171
The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, andparameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers
A Brief Introduction To Reactive ExtensionsJames World
An Introduction to Reactive Extensions. Demo Code available at http://github.com/james-world/rxtalk.
Note: Most of these slides were willfully plagiarised from slides and bits of demos done by the Rx-Team themselves, and repurposed to fit into a 20 minute datablast! Special thanks to the awesome Erik Meijer and Bart de Smet whose permission I didn't seek... I hope they don't mind!
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)Stephen Chin
Visage is a JVM language designed specifically for UI development, with special syntax for hierarchically describing UIs, binding data and behavior, and representing UI specific concepts such as animation, layout, and styles. It also is a full-featured language with a full compiler tool-chain, static compilation to JVM bytecodes, and IDE plug-ins. This talk will demonstrate how to use the Visage language to build UIs for JavaFX 2.0, Vaadin, and Android. Find out how you can take control of your UI development by writing cleaner, more maintainable UI code using the Visage language in your existing Java projects.
Ralph Schindler (of Zend Framework) and Jon Wage (of Doctrine) presented these slides for a webinar hosted by zend.com (webinar available online).
Links are contained within the slides to the demo application that was also used during the webinar.
More Stored Procedures and MUMPS for DivConqeTimeline, LLC
Reviews how Schema is used to define stored procedures and to validate the parameters during a call. Also, gives an example of updating the database from a stored procedure.
With the ever more frequent use of multiple servers and worker processes, issues which only occur when specific tasks are running in parallel become ever more likely to happen.
In this talk Marcos talks about some rails concurrency limitations you need to be aware of, including why you should never trust rails to check for uniqueness, why mysql can't do optimistic locking with retrying by default and how to fix it, how to properly choose between optimistic and pessimistic locking, how parallel processes can cause deadlocks even if you're not using locks, why you should never have serialized attributes in rows that might be edited in parallel, and why rails commits your transactions before they finish in case your multi threaded process is killed and how to prevent it from leaving your database on an inconsistent state.
JavaFX and Scala - Like Milk and CookiesStephen Chin
Presentation on Scala and JavaFX given at Scala Days. Shows how the ScalaFX API can be used to write cleaner and more maintainable code for your JavaFX applications in the Scala language. Also goes over implementation details that may be useful to other Scala DSL creators and has some quotes from Stephen Coulbourne to "lighten" things up.
A Brief Introduction To Reactive ExtensionsJames World
An Introduction to Reactive Extensions. Demo Code available at http://github.com/james-world/rxtalk.
Note: Most of these slides were willfully plagiarised from slides and bits of demos done by the Rx-Team themselves, and repurposed to fit into a 20 minute datablast! Special thanks to the awesome Erik Meijer and Bart de Smet whose permission I didn't seek... I hope they don't mind!
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)Stephen Chin
Visage is a JVM language designed specifically for UI development, with special syntax for hierarchically describing UIs, binding data and behavior, and representing UI specific concepts such as animation, layout, and styles. It also is a full-featured language with a full compiler tool-chain, static compilation to JVM bytecodes, and IDE plug-ins. This talk will demonstrate how to use the Visage language to build UIs for JavaFX 2.0, Vaadin, and Android. Find out how you can take control of your UI development by writing cleaner, more maintainable UI code using the Visage language in your existing Java projects.
Ralph Schindler (of Zend Framework) and Jon Wage (of Doctrine) presented these slides for a webinar hosted by zend.com (webinar available online).
Links are contained within the slides to the demo application that was also used during the webinar.
More Stored Procedures and MUMPS for DivConqeTimeline, LLC
Reviews how Schema is used to define stored procedures and to validate the parameters during a call. Also, gives an example of updating the database from a stored procedure.
With the ever more frequent use of multiple servers and worker processes, issues which only occur when specific tasks are running in parallel become ever more likely to happen.
In this talk Marcos talks about some rails concurrency limitations you need to be aware of, including why you should never trust rails to check for uniqueness, why mysql can't do optimistic locking with retrying by default and how to fix it, how to properly choose between optimistic and pessimistic locking, how parallel processes can cause deadlocks even if you're not using locks, why you should never have serialized attributes in rows that might be edited in parallel, and why rails commits your transactions before they finish in case your multi threaded process is killed and how to prevent it from leaving your database on an inconsistent state.
JavaFX and Scala - Like Milk and CookiesStephen Chin
Presentation on Scala and JavaFX given at Scala Days. Shows how the ScalaFX API can be used to write cleaner and more maintainable code for your JavaFX applications in the Scala language. Also goes over implementation details that may be useful to other Scala DSL creators and has some quotes from Stephen Coulbourne to "lighten" things up.
32 Ways a Digital Marketing Consultant Can Help Grow Your BusinessBarry Feldman
How can a digital marketing consultant help your business? In this resource we'll count the ways. 24 additional marketing resources are bundled for free.
Things I have learned over the years through experience of having to deliver code rapidly, with few defects and maximum functionality. I cover basic coding techniques, automated testing and sometimes I have enough time to review tools and code generation!
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
2. Agenda
• Introduction
• Sql Injection
• Issue
• Remedies
• Inference Problem
• Issue
• Remedies
• Sql Stored procedures
• Defense in Depth Example
• Conclusion
3. Introduction
• Many applications, like web based applications and xml based web services
store persistent data in databases.
• Trusting that the user has given well-formed input data to your
application, when infact the user has not
• Misplaced trust
• Database input vulnerabilities (aka sql injection)
4. Web Application Vulnerabilities
Source
void ProcessRequest()
{
Sanitizer string s = GetUserInput("name");
…
s = Validate(s);
…
…
ExecuteQuery(“select …" + s + “…”);
}
Sink
Critical
Database
5. Sql Injection
• Many applications include code that looks something like
the following.
String sql = “select * from client where name = ‘”+name+”’”
The variable name is provided by the user
What if an attacker enters this: Blake’ or 1=1 –
• select * from client where name = ’Blake’ or 1=1 –
• The comment operator “--” is supported by many
relational database servers, including Microsoft SQL
Server, IBM DB2, Oracle, PostgreSQL, and MySql.
6. Imagine that the database table
schema looks like this
C us tome r *
C ustome rID
La stNa me
F irstNa me
Middle Initia l
C us tome r C r e ditC ar d *
C ustome rID A ddre ss
C re ditC a rdID A pa rtme nt
C ity
Sta te
Posta lC ode
C ountry
C r e ditC ar d *
C re ditC a rdID
Ty pe
Numbe r
Ex pire s
When the attacker is happy that the SQL statement or statements are complete he
places a comment operator at the end to comment out any characters added by the
programmer.
7. SQL Injection
• Some database servers allow a client application to perform
more than one SQL statement at once.
• select * from table1 select * from table2
• SQL engines include support for data manipulation
constructs, such as the ability to create, delete (called drop),
an attacker could enter:
• Blake’ drop table client --
8. Can you spot security flaws?
string Status = “No";
string sqlstring = “"; Connecting as a super admin.
try {
SqlConnection sql= new SqlConnection(
@"data source=localhost;” + Sa is to SQL Server what SYSTEM is to
“user id=sa;password=password;”); Windows NT and later.
sql.Open();
sqlstring="SELECT HasShipped” +
“ FROM detail WHERE ID=‘“ + Id + “‘"; What if the connection fails to the
SqlCommand cmd = new SqlCommand(sqlstring,sql); database due to some network issue.
if ((int)cmd.ExecuteScalar() != 0)
Status = “Yes";
A complete description of how the
} catch (SqlException se) { failure occurred is given to the attacker.
Status = sqlstring + “ failednr";
foreach (SqlError e in se.Errors) {
Status += e.Message + “nr";
}
} catch (Exception e) {
Status = e.ToString();
}
9. Pseudoremedy:Quoting the Input
int age = ...; // age from user
string name = ...; // name from user
name = name.Replace(“‘","‘‘“);
SqlConnection sql= new SqlConnection(...);
sql.Open();
sqlstring=@"SELECT *” + “ FROM client WHERE name= ’” + name + “‘ or age=“ + age;
SqlCommand cmd = new SqlCommand(sqlstring,sql);
Replacing single quotes with two single quotes. Statement becomes invalid SQL Statement.
• select * FROM client WHERE ID = ’Michael’’ or 1=1 -- ’ or age=35
However, this does not deter our wily attacker; instead, he uses the age
field, which is not quoted, to attack the server. For example, age could be 35;
shutdown --.
declare @a char(20) select @a=0x73687574646f776e exec(@a)
This construct, when added to another SQL query, calls the shutdown command. The hexadecimal sequence is
the ASCII hex equivalent of the word shutdown.
10. Pseduremedy #2: Use Stored
Procedures
• A stored procedure is a procedure (like a subprogram in a regular
computing language) that is stored in the database
• Stored procedure: sp_GetName:
string name = ...; // name from user
SqlConnection sql= new SqlConnection(...);
sql.Open();
sqlstring=@"exec sp_GetName ’” + name + “‘";
SqlCommand cmd = new SqlCommand(sqlstring,sql);
• exec sp_GetName ’Blake’ or 1=1 -- ’ will fail
However performing data manipulation is perfectly valid.
• exec sp_GetName ’Blake’ insert into client values(1005, ’Mike’) -- ’
Another Scariest example
CREATE PROCEDURE sp_MySProc @input varchar(128)
AS
exec(@input)
11. Remedy 1: Never Ever Connect as
sysadmin
• Delete (drop) any database or table in the system
• Delete any data in any table in the system
• Change any data in any table in the system
• Change any stored procedure, trigger, or rule
• Delete logs
• Add new database users to the system
• Call any administrative stored procedure or extended stored procedure.
• Support authenticated connections by using native operating system
authentication and authorization by setting Trusted_connection = true
• create a specific database account that has just the correct privileges to
read, write, and update the appropriate data in the database,and you should use
that to connect to the database.
• SQL Server includes extended stored procedures such as xp_cmdshell through
which an attacker can invoke shell commands.
• Oracle databases include utl_file, which allows an attacker to read from and
write to the file system
12. Remedy #2: Building SQL Statements Securely
Function IsValidUserAndPwd(strName, strPwd)
’ Note I am using a trusted connection to SQL Server.
• Use parameterized commands. ’ Never use uid=sa;pwd=
strConn = “Provider=sqloledb;” + _
• SELECT count(*) FROM client “Server=server-sql;” + _
“database=client;” + _
WHERE name=? AND pwd=? “trusted_connection=yes"
Set cn = CreateObject(“ADODB.Connection”)
cn.Open strConn
Set cmd = CreateObject(“ADODB.Command”)
cmd.ActiveConnection = cn
cmd.CommandText = _
“select count(*) from client where name=? and pwd=?"
cmd.CommandType = 1 ’ 1 means adCmdText
cmd.Prepared = true
’ Explanation of numeric parameters:
’ data type is 200, varchar string;
’ direction is 1, input parameter only;
’ size of data is 32 chars max.
Set parm1 = cmd.CreateParameter(“name", 200, 1, 32, ““)
cmd.Parameters.Append parm1
parm1.Value = strName
Set parm2 = cmd.CreateParameter(“pwd", 200, 1, 32, ““)
cmd.Parameters.Append parm2
parm2.Value = strPwd
Set rs = cmd.Execute
IsValidUserAndPwd = false
If rs(0).value = 1 Then IsValidUserAndPwd = true
rs.Close
cn.Close
End Function
13. Building SQL Stored Procedures
Securely
• Use quotename function
select top 3 name from mytable would
become
select top 3 [name] from [mytable]
if you quote name and mytable .
declare @a varchar(20)
set @a=0x74735D27
select @a
set @a=quotename(@a)
select @a
set @a=‘ts]’’’
select @a
set @a=quotename(@a)
select @a
Use sp_executesql to execute sql statements build dynamically.
-- Test the code with these variables
declare @name varchar(64)
set @name = N’White’
-- Do the work
exec sp_executesql
N’select au_id from pubs.dbo.authors where au_lname=@lname’,
N’@lname varchar(64)’,
@lname = @name
14. Inference Problem ‐ 1
• The inference problem is a way to infer or derive
sensitive data from non‐sensitive data.
• Sum: An attack by sum tries to infer a value from
reported sum. Often helps us determine a negative
result.
• This report reveals that no female living in Grey is receiving
financial aid
15. Inference problem 2
• Count: count + sum average; average + count sum
• This report reveals that two males in Holmes and West are
receiving financial aid in the amount of $5000 and $4000,
respectively.
• Holmes Adams
• West Grof
17. Remedies: Statistical Inference
Controls Attacks
• Controls are applied to queries
• Difficult to determine if query discloses sensitive data
• Controls are applied to individual items within the database
(security vs. precision)
• Suppression: sensitive data values are not provided; query is
rejected without response
• Many results suppressed; precision high
• Concealing: answer provided is close to by not exactly the actual
value
• More results provided; precision low
18. Remedies: Limited Response
Suppression
• The n‐item k‐percent rule eliminates certain low‐frequency
elements from being displayed
• When one cell is suppressed in a table with totals for rows and
columns, must suppress at least one additional cell on the row
and one on the column to provide some confusion.
19. Other Suppression and
Concealing
• Combine rows or columns to protect sensitive values
• Take a random sample (sample must be large enough to be valid)
• Same sample set would be repeated for equivalent queries
• Query analysis
• Query and its implications are analyzed
• Can be difficult
• Maintain query history for each user
• … no perfect solution to inference problem
• … recognizing the problem leads to being defensive
20. Defense in Depth Example
//
// SafeQuery
//
//Add shipping ID parameter.
Using System; string str="sp_GetName";
Using System.Data; cmd = new SqlCommand(str,sqlConn);
Using System.Data.SqlTypes; cmd.CommandType = CommandType.StoredProcedure;
Using System.Data.SqlClient; cmd.Parameters.Add(“@ID",Convert.ToInt64(Id));
Using System.Security.Principal;
Using System.Security.Permissions; cmd.Connection.Open();
Using System.Text.RegularExpressions; Status = cmd.ExecuteScalar().ToString();
Using System.Threading;
Using System.Web; } catch (Exception e) {
Using Microsoft.Win32; if (HttpContext.Current.Request.UserHostAddress == “127.0.0.1”)
... Status = e.ToString();
else
[SqlClientPermissionAttribute(SecurityAction.PermitOnly, Status = “Error Processing Request";
AllowBlankPassword=false)] } finally {
[RegistryPermissionAttribute(SecurityAction.PermitOnly, //Shut down connection--even on failure.
Read=@"HKEY_LOCAL_MACHINESOFTWAREClient”)] if (cmd != null)
static string GetName(string Id) cmd.Connection.Close();
{ }
return Status;
SqlCommand cmd = null; }
string Status = “Name Unknown"; //Get connection string.
(continued) internal static string ConnectionString {
get {
try { return (string)Registry
//Check for valid shipping ID. .LocalMachine
Regex r = new Regex(@"^d{4,10}$”); .OpenSubKey(@"SOFTWAREClient”)
if (!r.Match(Id).Success) .GetValue(“ConnectionString”);
throw new Exception(“Invalid ID”); }
}
//Get connection string from registry.
SqlConnection sqlConn= new SqlConnection(ConnectionString);
21. Defense in Depth Example
• Blank passwords are never allowed when connecting to the database.
• Read only one specific key from the registry; it cannot be made to
perform other registry operations.
• The code is hard-core about valid input: 4–10 digits only. Anything else
is bad.
• The database connection string is in the registry, not in the code and not
in the Web service file space, such as a configuration file.
• The code uses a stored procedure, mainly to hide the application logic in
case the code is compromised.
• connection is not using sa. Rather, it’s using a least-privilege account
that has query and execute permissions in the appropriate tables.
• use parameters, not string concatenation, to build the query.
• The code forces the input into a 64-bit integer.
• On error, the attacker is told nothing, other than that a failure occurred.
• The connection to the database is always shut down regardless of
whether the code fails.
22. Conclusion
• Do not trust the user’s input!
• Be strict about what represents valid input and reject
everything else. Regular expressions are your friend.
• Use parameterized queries—not string concatenation—to
build queries.
• Do not divulge too much information to the attacker.
• Connect to the database server by using a least-privilege
account, not the sysadmin account.