Data Security and Privacy Archives - Thomas LaRock https://thomaslarock.com/category/data-security-and-privacy/ Thomas LaRock is an author, speaker, data expert, and SQLRockstar. He helps people connect, learn, and share. Along the way he solves data problems, too. Mon, 31 Jan 2022 19:33:57 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 https://thomaslarock.com/wp-content/uploads/2015/07/gravatar.jpg Data Security and Privacy Archives - Thomas LaRock https://thomaslarock.com/category/data-security-and-privacy/ 32 32 18470099 Stop Using Production Data For Development https://thomaslarock.com/2022/01/stop-using-production-refresh-development/ https://thomaslarock.com/2022/01/stop-using-production-refresh-development/#comments Mon, 31 Jan 2022 19:33:43 +0000 https://thomaslarock.com/?p=21592 A common software development practice is to take data from a production system and restore it to a different environment, often called “test”, “development”, “staging”, or even “QA”. This allows for support teams to troubleshoot issues without making changes to the true production environment. It also allows for development teams to build new versions and ... Read more

The post Stop Using Production Data For Development appeared first on Thomas LaRock.

]]>
A common software development practice is to take data from a production system and restore it to a different environment, often called “test”, “development”, “staging”, or even “QA”. This allows for support teams to troubleshoot issues without making changes to the true production environment. It also allows for development teams to build new versions and features of existing products in a non-production environment. Using production to refresh development is just one of those things everyone accepts and does, without question.

Of course the idea of testing in a non-production environment isn’t anything new. Consider Haggis. No way someone thought to themselves “let me just shove everything I can into this sheep’s stomach, boil it, and serve it for dinner tonight.” You know they first fed it to the neighbor nobody liked. Probably right after they shoved a carton of milk in their face and asked “does this smell bad to you?”

For decades software development has made it a standard practice to create copies of production data and restore it to other non-production environments. It was not without issues, however. For example, as data sizes grew so did the length of time to do a restore. This also clogged network bandwidth, not to mention the costs associated with storage.

And then there is this:

If you read that tweet and thought “yeah, what’s your point?” then you are part of the problem.

As an industry we focus on access to specific environments, but not the assets in the environments. This is wrong. The royal family knows where the Crown Jewels are stored but if they are moved to another location you know the Jewels are heavily guarded at all times. Access to the jewels is important no matter where the jewels are located. The same should be true of your production data.

Use production to refresh development.
Then again, that stick might be pointy enough to fend off any attacker.

Data is the most critical asset your company owns. If you make efforts to lock down production but allow production data to flow to less-secure environments, then you haven’t locked down production.

It is ludicrous to think about the billions of dollars spent to lock down physical access to data centers only to allow junior developers to stuff customer data on a laptop they will then leave behind on a bus. Or senior developers leaving S3 buckets open. Or forgetting they pushed credentials to a GitHub repo.

If you are still moving production data between environments you are a data breach waiting to happen. I don’t care what the auditors say, you are at an elevated and unnecessary risk. Like when Obi-Wan decides to protect baby Luke by keeping his name and taking him to Darth Vader’s home planet. Nice job, Ben, no way this ends up with you dying, naked, in front a few dozen onlookers.

I think what frustrates me most is this entire system is unnecessary. You have options when moving production data. You can use data masking, obfuscation, and encryption in order to reduce your risk. But the best method is to not move your data at all.

After years of being told “don’t test in production” it’s time to think about testing in production. Continuous integration and continuous delivery/deployment (CI/CD) allow for you to achieve this miracle. And for those that say “No, you dummy, CI/CD is what you do in test before you push to production,” I offer the following.

Use dummy data.

You don’t need production data, you need data that looks like production data. You don’t need actual customer names and address, you need similar names and address. And there are ways to simulate the statistics in your database, too, so your query plans have the same shape as production without the actual volume of data.

It’s possible for you to develop software code against simulated production data, as opposed to actual production data. But doing so requires more work, and nobody likes more work.

Until you are breached, of course. Then the extra work won’t be optional.

The post Stop Using Production Data For Development appeared first on Thomas LaRock.

]]>
https://thomaslarock.com/2022/01/stop-using-production-refresh-development/feed/ 5 21592
Create and Use an Email Alias https://thomaslarock.com/2021/01/create-and-use-an-email-alias/ https://thomaslarock.com/2021/01/create-and-use-an-email-alias/#respond Mon, 04 Jan 2021 22:49:13 +0000 https://thomaslarock.com/?p=20424 If you are using Microsoft 365, you can create and use an email alias through your admin center.

The post Create and Use an Email Alias appeared first on Thomas LaRock.

]]>
At this point I believe we all have a “burner” email account or two. An email account we use when an email address is required from us, but we do not trust the person making the request. In addition to using email accounts that are 20+ years old, we can also create and use an email alias. Using an alias gives us more flexibility, allowing for us to track any misuse of our data.

If you are using Office Microsoft 365, you can create and use an email alias through your admin center. Navigate to your username and click ‘Manage username and email’. In the blade that opens you can add your alias. I will add one named ‘blogtest’:

Create and Use an Email Alias

Click save and you are done, the alias is now ready to use. It is that simple. You can test it for yourself, here I sent blogtest an email:

Create and Use an Email Alias

Now, since this is an alias, the email arrives and looks as if it was sent to my primary email address. The whole idea of me giving you an alias is because I don’t want your spam in my inbox. So, we need to filter the message. Fortunately, Outlook has a way for us to create a rule that will filter for keywords in the message header. Here, I will create a rule that will redirect the email to a folder named Blogtest:

Create and Use an Email Alias

Now, the next time someone sends an email to the alias, it will arrive in the folder.

Create and Use an Email Alias

Create and use an email alias is a great way to track your data being shared, bought, sold, or stolen. I use them often, especially when I know a company that has my data is being merged, or is closing.

The post Create and Use an Email Alias appeared first on Thomas LaRock.

]]>
https://thomaslarock.com/2021/01/create-and-use-an-email-alias/feed/ 0 20424
Use SQLMap to Connect Directly to Azure SQL Database https://thomaslarock.com/2020/03/use-sqlmap-to-connect-directly-to-azure-sql-database/ https://thomaslarock.com/2020/03/use-sqlmap-to-connect-directly-to-azure-sql-database/#comments Thu, 12 Mar 2020 00:58:44 +0000 https://thomaslarock.com/?p=19757 I’ve written before about using sqlmap to perform sql injection testing against a website. It is also possible to use sqlmap to connect directly against a database. In this post I will show you how to use sqlmap to connect directly to Azure SQL Database. Once connected you can enumerate objects, open a shell, or ... Read more

The post Use SQLMap to Connect Directly to Azure SQL Database appeared first on Thomas LaRock.

]]>
I’ve written before about using sqlmap to perform sql injection testing against a website. It is also possible to use sqlmap to connect directly against a database. In this post I will show you how to use sqlmap to connect directly to Azure SQL Database. Once connected you can enumerate objects, open a shell, or run custom SQL injection scripts.

The sqlmap documentation is good, but not perfect. For example, if you go looking for details and examples on how to direct connect to a database you will find the following:

Use SQLMap to Connect Directly to Azure SQL Database

There is no example given for SQL Server, so I assume ‘mssql’ is the correct choice for DBMS. A quick test against my Contoso Clinic website database had me trying the following code (you will need to put it correct login, password, and server host names should you try to replicate my scenraios):

c:\python38\python.exe .\sqlmap.py --batch --flush-session -d "mssql://login:password@dbserver.database.windows.net:1433/Clinic"

This resulted in an error:

[CRITICAL] SQLAlchemy connection issue ('InterfaceError: (pyodbc.InterfaceError) ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')')

At first I focused my attention on the driver, thinking that my Surface laptop was not configured properly. I had just rebuilt the machine a few weeks ago, so it was reasonable to think something was amiss. However, it soon dawned on me that my attention should focus on SQLAlchemy, as that was being used by sqlmap to create the connection. So I decided that I would start running some tests using SQLAlchemy.

Use SQLAlchemy to Connect Directly to Azure SQL Database

Here’s the Python script I used as a first test:

import sqlalchemy as sa 

engine = sa.create_engine('mssql+pymssql://login:password@dbserver.database.windows.net:1433/Clinic')

connection = engine.connect()
result = connection.execute("select username from users")
for row in result:
    print("username:", row['username'])
connection.close()

This script threw the same error message, so I considered that to be a sign of progress. Now I set about researching how to connect to Azure SQL Database using SQLAlchemy. A few Google results later and I arrived at the following syntax as allowing for a successful connection:

"mssql+pymssql://login@dbserver:password@dbserver.database.windows.net:1433/Clinic"

I needed to add the @dbserver to the end of the login, and I needed to assign a default driver. Here I chose to use pymssql. This syntax allows me to connect SQLAlchemy to an Azure SQL Database. Now that I was able to make a connection from my laptop, I went back to sqlmap.

Use SQLMap to Connect Directly to Azure SQL Database

The first thing I tried was the following:

c:\python38\python.exe .\sqlmap.py --batch --flush-session -d "mssql+pymssql://login@dbserver:password@dbserver.database.windows.net:1433/Clinic"

This resulted in the following error:

[CRITICAL] invalid target details, valid syntax is for instance 'mysql://USER:PASSWORD@DBMS_IP:DBMS_PORT/DATABASE_NAME' or 'access://DATABASE_FILEPATH'

Again, I consider this to be a sign of progress. It is a different error message, here sqlmap is clearly telling me there is a syntax error. Since I made two changes to the string, I decided to remove one and see if that works. My next test was the following:

c:\python38\python.exe .\sqlmap.py --batch --flush-session -d "mssql://login@dbserver:password@dbserver.database.windows.net:1433/Clinic"

Success! We are able to create a connection:

[INFO] connection to Microsoft SQL Server server 'dbserver.database.windows.net:1433' established

Summary

Connecting to Azure SQL Database with sqlmap is easy, just remember the login@dbserver format. From there you can enumerate objects, open a shell, or run custom SQL injection scripts. This flexibility makes sqlmap a great tool to use for penetration testing. I also use sqlmap to test alerts configured with Advanced Threat Protection.

The post Use SQLMap to Connect Directly to Azure SQL Database appeared first on Thomas LaRock.

]]>
https://thomaslarock.com/2020/03/use-sqlmap-to-connect-directly-to-azure-sql-database/feed/ 1 19757
Modify SQL Audit for Azure SQL Database https://thomaslarock.com/2020/02/modify-sql-audit-for-azure-sql-database/ https://thomaslarock.com/2020/02/modify-sql-audit-for-azure-sql-database/#comments Tue, 11 Feb 2020 15:45:06 +0000 https://thomaslarock.com/?p=19735 At SQL Server Live last November, I demonstrated enabling SQL Audit for Azure SQL Database. During the class discussion I explained you must use Powershell to modify SQL Audit for Azure SQL Database. So, that’s my post today, showing you how it is done. By default, SQL Audit for Azure SQL Database will enable the ... Read more

The post Modify SQL Audit for Azure SQL Database appeared first on Thomas LaRock.

]]>
At SQL Server Live last November, I demonstrated enabling SQL Audit for Azure SQL Database. During the class discussion I explained you must use Powershell to modify SQL Audit for Azure SQL Database. So, that’s my post today, showing you how it is done.

By default, SQL Audit for Azure SQL Database will enable the following:

SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP
FAILED_DATABASE_AUTHENTICATION_GROUP
BATCH_COMPLETED_GROUP

If you want to alter that list, you must use Powershell. There is no GUI available. (If you connect to Azure SQL Database with SQL Server Management Studio v18.4 you will notice there is no option for Audit Specifications. I believe this should be possible at some point, so feel free to go upvote this suggestion.)

Using Set-AzSqlServerAudit

Let’s look at how to enable the DATABASE_PERMISSION_CHANGE_GROUP audit action group. I chose that Action Group for two reasons. First, it’s part of the list I recommend for anyone using SQL Audit along with Security Event Manager. Second, because I was curious to track activity for granting UNMASK when using Dynamic Data Masking.

Here’s some sample code that I used to add the DATABASE_PERMISSION_CHANGE_GROUP audit action group:

Set-AzSqlServerAudit -ResourceGroupName RGname -ServerName Server -AuditActionGroup SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP, FAILED_DATABASE_AUTHENTICATION_GROUP, BATCH_COMPLETED_GROUP, DATABASE_PERMISSION_CHANGE_GROUP

You can then use Get-AzSqlServerAudit to verify the change:

Viewing Audit Logs with Log Analytics

To test the activity is captured, I grant and revoke UNMASK to a user. I’m pushing the audit logs to Log Analytics, which returns the rows as expected:

From there we can build rules and alerts as needed.

Summary

I have been an advocate of SQL Audit for years. I was happy to see it added to Azure a while back. However, to modify SQL Audit for Azure SQL Database you must use Powershell. I’m hopeful Microsoft will get this functionality into SSMS at some point in the near future.

Together with Karen López, we will be delivering a full training day at SQL Konferenz in March. The title of our session is Advanced Data Protection: Security and Privacy Assessments in SQL Server. The above is a sample of the updated content Karen and I will be sharing. If you are in or around Darmstadt on the 3rd of March, we’d love to see you in our class.

REFERENCES:

https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions?view=sql-server-ver15
https://docs.microsoft.com/en-us/powershell/module/az.sql/set-azsqlserveraudit?view=azps-3.4.0
https://docs.microsoft.com/en-us/sql/relational-databases/security/dynamic-data-masking?view=sql-server-ver15

The post Modify SQL Audit for Azure SQL Database appeared first on Thomas LaRock.

]]>
https://thomaslarock.com/2020/02/modify-sql-audit-for-azure-sql-database/feed/ 1 19735
Black Hat London https://thomaslarock.com/2019/11/black-hat-london/ https://thomaslarock.com/2019/11/black-hat-london/#respond Wed, 27 Nov 2019 18:44:14 +0000 https://thomaslarock.com/?p=19680 My final event of the year will be Black Hat Europe in London, the first week in December. This will be my second Black Hat event; the first was this past August when me and 20,000 of my closest security professional friends invaded Las Vegas. I know it may seem odd for a career database ... Read more

The post Black Hat London appeared first on Thomas LaRock.

]]>
My final event of the year will be Black Hat Europe in London, the first week in December. This will be my second Black Hat event; the first was this past August when me and 20,000 of my closest security professional friends invaded Las Vegas.

I know it may seem odd for a career database administrator to attend an event catered to hackers and developers. But that’s the “old” Black Hat, in my opinion. Today’s security landscape is far different than when Black Hat started 20-plus years ago. Back then security was an afterthought. Today we understand security is a shared responsibility. The attendees of Black Hat reflect this shift, as do the vendors in the expo hall.

Being a new event for me, I went out of my way to meet people to better understand their community and culture. In Vegas, I was able to mingle with members of the Azure Sentinel team, including John Lambert. In conversation with John and his team, the quote “Defenders think in lists, attackers think in graphs” was mentioned.

Yeah, I found my people.

Many events I attend are hosted by large vendors (Microsoft, VMware, Cisco, AWS, etc.) and as such many of the sessions at those events are product marketing-focused. Even community sessions are often a showcase of product features. Black Hat is not a marketing event as much as it’s a university-level symposium. For example, in Vegas I attended a session on how researchers are using mice to help detect deep fakes. There was no company behind the session, just some graduate students talking about their research project. It was wonderful.

So, I’m looking forward to more of the same in London. I’ve no idea the size of this event, but I expect the content to be brilliant. I’m eager to meet people in and around the booth and talk to them about the portfolio of security products we have. I want valued feedback on how to make our products better. I want to help our customers shift their security focus, helping them move from protection to detection.

But most of all, I’m using this trip as an excuse to watch Arsenal play Brighton on Thursday evening. Look for me in the stands—I’ll be the one in the red jersey, red scarf, and Black Hat.

Look for me in the stands—I’ll be the one in the red jersey, red scarf, and Black Hat.
Who’s got two thumbs and is excited for his second match at Emirates? This guy.

The post Black Hat London appeared first on Thomas LaRock.

]]>
https://thomaslarock.com/2019/11/black-hat-london/feed/ 0 19680
SQL Injection Protection https://thomaslarock.com/2019/05/sql-injection-protection/ https://thomaslarock.com/2019/05/sql-injection-protection/#comments Wed, 22 May 2019 15:52:56 +0000 https://thomaslarock.com/?p=19528 SQL injection is a common form of data theft. I am hopeful we can make SQL injection protection more common. The 2018 TrustWave Global Security Report listed SQL Injection as the second most common technique for web attacks, trailing only cross-site scripting (XSS) attacks. This is a 38% increase from the previous year. That same ... Read more

The post SQL Injection Protection appeared first on Thomas LaRock.

]]>
SQL injection is a common form of data theft. I am hopeful we can make SQL injection protection more common.

The 2018 TrustWave Global Security Report listed SQL Injection as the second most common technique for web attacks, trailing only cross-site scripting (XSS) attacks. This is a 38% increase from the previous year. That same report also shows SQL Injection ranked fifth on a list of vulnerabilities that can be identified through simple penetration testing.

You may look at the increase and think “whoa, attacks are increasing”. But I believe that what we are seeing is a rising awareness in security. No longer the stepchild, security is a first-class citizen in application design and deployment today. As companies focus on security, they deploy tools and systems to help identify exploits, leading to more reporting of attacks.

SQL Injection is preventable. That’s the purpose of this post today, to help you understand what SQL Injection is, how to identify when it is happening, and how to prevent it from being an issue.

 

SQL Injection Explained

SQL injection is the method where an adversary appends a SQL statement to the input field inside a web page or application, thereby sending their own custom request to a database. That request could be to read data, or download the entire database, or even delete all data completely.

The most common example for SQL injection attacks are found inside username and password input boxes on a web page. This login design is standard for allowing users to access a website. Unfortunately, many websites do not take precautions to block SQL injection on these input fields, leading to SQL injection attacks.

Let’s look at a sample website built for the fictional Contoso Clinic. The source code for this can be found at https://github.com/Microsoft/azure-sql-security-sample.

On the Patients page you will find an input field at the top, next to a ‘Search’ button, and next to that a hyperlink for ‘SQLi Hints’.

 

contoso clinic sql injectoin example

 

Clicking on the SQLi Hints link will display some sample text to put into the search field.

 

sql injection example

 

I’m going to take the first statement and put it into the search field. Here is the result:

 

sql-injection-error

 

This is a common attack vector, as the adversary can use this method to determine what version of SQL Server is running. This is also a nice reminder to not allow your website to return such error details to the end user. More on that later.

Let’s talk a bit about how SQL injection works under the covers.

 

How SQL Injection works

The vulnerability in my sample website is the result of this piece of code:

return View(db.Patients.SqlQuery
("SELECT * FROM dbo.Patients
WHERE [FirstName] LIKE '%" + search + "%'
OR [LastName] LIKE '%" + search + "%'
OR [StreetAddress] LIKE '%" + search + "%'
OR [City] LIKE '%" + search + "%'
OR [State] LIKE '%" + search + "%'").ToList());

This is a common piece of code used by many websites. It is building a dynamic SQL statement based upon the input fields on the page. If I were to search the Patients page for ‘Rock’, the SQL statement sent to the database would then become:

SELECT * FROM dbo.Patients
WHERE [FirstName] LIKE '%Rock%'
OR [LastName] LIKE '%Rock%'
OR [StreetAddress] LIKE '%Rock%'
OR [City] LIKE '%Rock%'
OR [State] LIKE '%Rock%'

In the list of SQLi hints on that page you will notice that each example starts with a single quote, followed by a SQL statement, and at the end is a comment block (the two dashes). For the example I chose above, the resulting statement is as follows:

SELECT * FROM dbo.Patients
WHERE [FirstName] LIKE '%' OR CAST(@@version as int) = 1 --%'
OR [LastName] LIKE '%' OR CAST(@@version as int) = 1 --%'
OR [StreetAddress] LIKE '%' OR CAST(@@version as int) = 1 --%'
OR [City] LIKE '%' OR CAST(@@version as int) = 1 --%'
OR [State] LIKE '%' OR CAST(@@version as int) = 1 --%'

This results in the conversion error shown above. This also means that I can do interesting searches to return information about the database. Or I could do malicious things, like drop tables.

Chance are you have code like this, somewhere, right now. Let’s look at how to find out what your current code looks like.

 

SQL Injection Discovery

Discovering SQL injection is not trivial. You must examine your code to determine if it is vulnerable. You must also know if someone is actively trying SQL injection attacks against your website. Trying to roll your own solution can take considerable time and effort.

There are two tools I can recommend you use to help discover SQL injection.

 

Test Websites with sqlmap

One method is to use sqlmap, an open-source penetration testing project that will test websites for SQL injection vulnerabilities. This is a great way to uncover vulnerabilities in your code. However, sqlmap will not tell you if someone is actively using SQL injection against your website. You will need to use something else for alerts.

 

Azure Threat Detection

If you are using Azure SQL Database, then you have the option to enable Azure Threat Detection. This feature will discover code vulnerabilities as well as alert you to attacks. It also checks for anomalous client login, data exfiltration, and if a harmful application is trying to access your database.

(For fairness, I should mention that AWS WAF allows for SQL injection detection, but their process is a bit more manual that Azure).

If you try to roll your own discovery, you will want to focus on finding queries that have caused errors. Syntax errors, missing objects, permission errors, and UNION ALL errors are the most common. You can find a list of the common SQL Server error message numbers here.

It warrants mentioning that not all SQL injection attacks are discoverable. But when it comes to security, you will never eliminate all risk, you take steps to lower your risk. SQL injection discovery is one way to lower your risk.

 

SQL Injection Protection

Detection of SQL Injection vulnerabilities and attacks are only part of the solution. In an ideal world, your application code would not allow for SQL Injection. Here’s a handful of ways you can lower your risk of SQL injection attacks.

 

Parameterize Your Queries

Also known as ‘prepared statements’, this is a good way to prevent SQL injection attacks against the database. For SQL Server, prepared statements are typically done using the sp_executesql() system stored procedure.

Prepared statements should not allow an attacker to change the nature of the SQL statement by injecting additional code into the input field. I said “should”, because it is possible to write prepared statements in a way that would still be vulnerable to SQL injection. You must (1) know what you are doing and (2) learn to sanitize your inputs.

Traditionally, one argument against the use of prepared statements centers on performance. It is possible that a prepared statement may not perform as well as the original dynamic SQL statement. However, if you are reading this and believe performance is more important than security, you should reconsider your career in IT before someone does that for you.

 

Use Stored Procedures

Another method available are stored procedures. Stored procedures offer additional layers of security that prepared statements may not allow. While prepared statements require permissions on the underlying tables, stored procedures can execute against objects without the user having similar direct access.

Like prepared statements, stored procedures are not exempt from SQL injection. It is quite possible you could put vulnerable code into a stored procedure. You must take care to compose your stored procedures properly, making use of parameters. You should also consider validating the input parameters being passed to the procedure, either on the client side or in the procedure itself.

 

Use EXECUTE AS

You could use a security method such as EXECUTE AS to switch the context of the user as you make a request to the database. As mentioned above, stored procedures somewhat act in this manner by default. But EXECUTE AS can be used directly for requests such as prepared statements or ad-hoc queries.

 

Remove Extended Stored Procedures

Disabling the use of extended stored procedures is a good way to limit your risk with SQL injection. Not because you won’t be vulnerable, but because you limit the surface area for the attacker. By disabling these system procedures you limit a common way that an attacker can get details about your database system.

 

Sanitize Error Messages

You should never reveal error messages to the end user. Trap all errors and redirect to a log for review later. The less error information you bubble up, the better.

 

Use Firewalls

Whitelisting of IP addresses is a good way to limit activity from anomalous users. Use of VPNs and VNETs to segment traffic can also reduce your risk.

 

Summary

The #hardtruth here is that every database is susceptible to SQL injection attacks. No one platform is more at risk than any other. The weak link here is the code being written on top of the database. Most code development does not emphasize security enough, leaving themselves open to attacks.

When you combine poor database security techniques along with poor code, you get the recipe for SQL Injection.

 

REFERENCES

2018 TrustWave Global Security Report
Contoso Clinic Demo Application
sqlmap: Automatic SQL injection and database takeover tool
Azure SQL Database threat detection
Working with SQL Injection Match Conditions
How to Detect SQL Injection Attacks
sp_executesql (Transact-SQL)
EXECUTE AS (Transact-SQL)
Server Configuration Options (SQL Server)

The post SQL Injection Protection appeared first on Thomas LaRock.

]]>
https://thomaslarock.com/2019/05/sql-injection-protection/feed/ 1 19528
Use PWDCOMPARE() to Find SQL Logins With Weak Passwords https://thomaslarock.com/2019/02/use-pwdcompare-to-find-sql-logins-with-weak-passwords/ https://thomaslarock.com/2019/02/use-pwdcompare-to-find-sql-logins-with-weak-passwords/#comments Wed, 06 Feb 2019 14:55:15 +0000 https://thomaslarock.com/?p=19472 SQL Server ships with an internal system function, PWDCOMPARE(), that we can use to find SQL logins with weak passwords.

The post Use PWDCOMPARE() to Find SQL Logins With Weak Passwords appeared first on Thomas LaRock.

]]>
Not a day, week, or month goes by without news of yet another data breach.

And the breaches aren’t the result of some type of Mission Impossible heist. No, it’s often an unprotected S3 bucket, maybe some SQL Injection, or files left behind when relocating to a new office. Silly, fundamental mistakes made by people that should know better.

After decades of reviewing data breaches I have arrived at the following conclusion:

Data security is hard because people are dumb.

Don’t just take my word for it though. Do a quick search for “common password list” and you’ll see examples of passwords scraped from breaches. These are passwords often used by default to secure systems and data.

Chances are, these passwords are in your environment, right now.

Here’s what you can do to protect your data.

 

Use PWDCOMPARE() to Find SQL Logins With Weak Passwords

SQL Server ships with an internal system function, PWDCOMPARE(), that we can use to find SQL logins with weak passwords. We can combine this function, along with a list of weak passwords, and some PowerShell to do a quick check.

First, let’s build a list. I’ll store mine as a text file and it looks like this:

 

use PWDCOMPARE() to find sql logins with weak passwords

 

I can import that file as an array into PowerShell with one line of code:

$pwdList = Get-Content .\password_list.txt

And with just a few lines of code, we can build a query and execute against our instance of SQL Server:

foreach ($password in $pwdList) {
$SQLText = "SELECT name FROM sys.sql_logins WHERE PWDCOMPARE('$password', password_hash) = 1;"
Invoke-Sqlcmd -Query $SQLText -ServerInstance $SQLServer
}

And we find that the ITSupport login has a weak password:

 

weak password check result

 

As Dark Helmet once said, “Now you see that evil will always triumph, because good is dumb.”

 

Preventing Weak Passwords for SQL Logins

One of the easiest things you can do is to enable the CHECK_POLICY for SQL logins. By default, enabling the CHECK_POLICY option will also force the password expiration by enabling the CHECK_EXPIRATION flag. In other words, you can have passwords for SQL logins expire as if they were windows logins, and you can enforce complex passwords.

However, even with those checks enabled, I would advise you still do a manual check for weak passwords. Do not assume that by enabling the password policy checks that you are secure. In fact, you should do the opposite. You should take a stance of assume compromise. This is a fundamental aspect of modern Cybersecurity practices.

As a side note, I also want to point out that Troy Hunt has collected the passwords from many data breaches, and he has made the passwords searchable. Do yourself a favor and take some of the passwords you’ve used throughout the web and see if they have been exposed at some point.

Summary

SQL Server offers system functions to help you search for weak passwords, as well as policies to enforce complex passwords and password expiration. You should adopt a stance of “assume compromise” and be proactive about checking the passwords in your environment to make certain they are not considered weak.

[Hey there, dear reader, if you liked this post about passwords and data security, then you might also like the full day training session I am delivering with Karen Lopez in two weeks at SQL Konferenz. The title is Advanced Data Protection: Security and Privacy in SQL Server, and you’ll learn more about how to protect your data at rest, in use, and in motion.]

 

The post Use PWDCOMPARE() to Find SQL Logins With Weak Passwords appeared first on Thomas LaRock.

]]>
https://thomaslarock.com/2019/02/use-pwdcompare-to-find-sql-logins-with-weak-passwords/feed/ 6 19472