Databases on AWS Security requirmets-

Posted by:

|

On:

|

  1. RDS Security requirements
AWS – Enable automated backups –
Sign in to the AWS Management Console and open the Amazon RDS console at https://console.aws.amazon.com/rds/.
In the navigation pane, choose DB Instances, and then select the DB instance that you want to modify.
Choose Instance Actions, and then choose Modify. The Modify DB Instance page appears.
For Backup Retention Period, choose a positive non-zero value.Select Apply Immediately.
Choose Continue.
On the confirmation page, choose Modify DB Instance to save your changes and enable automated backups.Resource:Working With Backups
AWS – Set the Publicly accessible option to No while launching the DB instance.-
While creating a DB instance, In Connectivity step, select No for Public Access.If your DB instance isn’t publicly accessible, you can also use an AWS Site-to-Site VPN connection or an AWS Direct Connect connection to access it from a private network. For more information, see Internetwork traffic privacy.Resource:Creating an RDS DB Instance
AWS – Maintain Internetwork Traffic Privacy –
You have two connectivity options between your private network and AWS:An AWS Site-to-Site VPN connection: By default, instances that you launch into an Amazon VPC can’t communicate with your own (remote) network. You can enable access to your remote network from your VPC by creating an AWS Site-to-Site VPN (Site-to-Site VPN) connection, and configuring routing to pass traffic through the connection.An AWS Direct Connect connection: AWS Direct Connect links your internal network to an AWS Direct Connect location over a standard Ethernet fiber-optic cable. One end of the cable is connected to your router, the other to an AWS Direct Connect router. With this connection, you can create virtual interfaces directly to public AWS services (for example, to Amazon S3) or to Amazon VPC, bypassing internet service providers in your network path.You get access to Amazon Web Services through the network by using AWS-published API operations. Clients must support Transport Layer Security (TLS) 1.0. We recommend TLS 1.2. Clients must also support cipher suites with Perfect Forward Secrecy (PFS), such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Diffie-Hellman Ephemeral (ECDHE). Most modern systems such as Java 7 and later support these modes. Additionally, you must sign requests using an access key ID and a secret access key that is associated with an IAM principal. Or you can use the AWS Security Token Service (STS) to generate temporary security credentials to sign requests.
Resource:
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/inter-network-traffic-privacy.html
https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html
AWS – Launch RDS in private subnet-
Create a VPC security group for your DB instances to be in. This security group can be used to restrict access to the DB instances. For example, you can create a custom rule for this security group that allows TCP access using the port you assigned to the DB instance when you created it and an IP address you use to access the DB instance for development or other purposes.
 – Create a VPC security group for your EC2 instances (web servers and clients) to be in. This security group can, if needed, allow access to the EC2 instance from the internet by using the VPC’s routing table. For example, you can set rules on this security group to allow TCP access to the EC2 instance over port 22.
 – Create custom rules in the security group for your DB instances that allow connections from the security group you created for your EC2 instances. This would allow any member of the security group to access the DB instances.
For a tutorial that shows you how to create a VPC with both public and private subnets for this scenario, see Tutorial: Create an Amazon VPC for Use with a DB Instance.
To create a rule in a VPC security group that allows connections from another security group, do the following:
Sign in to the AWS Management Console and open the Amazon VPC console at https://console.aws.amazon.com/vpc.
In the navigation pane, choose Security Groups.
Choose or create a security group for which you want to allow access to members of another security group. In the scenario preceding, this is the security group that you use for your DB instances. Choose the Inbound Rules tab, and then choose Edit rule.
On the Edit inbound rules page, choose Add Rule.
5.vFrom Type, choose one of the All ICMP options. In the Source box, start typing the ID of the security group; this provides you with a list of security groups. Choose the security group with members that you want to have access to the resources protected by this security group. In the scenario preceding, this is the security group that you use for your EC2 instance.
Repeat the steps for the TCP protocol by creating a rule with All TCP as the Type and your security group in the Source box. If you intend to use the UDP protocol, create a rule with All UDP as the Type and your security group in the Source box.
Create a custom TCP rule that permits access via the port you used when you created your DB instance, such as port 3306 for MySQL. Enter your security group or an IP address to use in the Source box.
Choose Save when you are done.
Reference:
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.html
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.Scenarios.html
AWS – Ensure RDS snapshots are not public-
Sharing an Encrypted SnapshotYou can share DB snapshots that have been encrypted at rest using the AES-256 encryption algorithm, as described in Encrypting Amazon RDS Resources. To do this, you must take the following steps:Share the AWS Key Management Service (AWS KMS) encryption key that was used to encrypt the snapshot with any accounts that you want to be able to access the snapshot.You can share AWS KMS encryption keys with another AWS account by adding the other account to the KMS key policy. For details on updating a key policy, see Key Policies in the AWS KMS Developer Guide. For an example of creating a key policy, see Allowing Access to an AWS KMS Encryption Key later in this topic.Use the AWS Management Console, AWS CLI, or Amazon RDS API to share the encrypted snapshot with the other accounts.These restrictions apply to sharing encrypted snapshots:You can’t share encrypted snapshots as public.You can’t share Oracle or Microsoft SQL Server snapshots that are encrypted using Transparent Data Encryption (TDE).You can’t share a snapshot that has been encrypted using the default AWS KMS encryption key of the AWS account that shared the snapshot.Enabling Amazon RDS Encryption for a DB InstanceTo enable encryption for a new DB instance, choose Enable encryption on the Amazon RDS console. If you use the create-db-instance AWS CLI command to create an encrypted DB instance, set the –storage-encrypted parameter to true. If you use the CreateDBInstance API operation, set the StorageEncrypted parameter to true.When you create an encrypted DB instance, you can also supply the AWS KMS key identifier for your encryption key. If you don’t specify an AWS KMS key identifier, then Amazon RDS uses your default encryption key for your new DB instance. AWS KMS creates your default encryption key for Amazon RDS for your AWS account. Your AWS account has a different default encryption key for each AWS Region.Once you have created an encrypted DB instance, you can’t change the type of encryption key used by that DB instance. Therefore, be sure to determine your encryption key requirements before you create your encrypted DB instance.Resource:Sharing Encrypted snapshotsRDS Encryption Overview
AWS – Ensure RDS instances are provisioned across multiple Availability Zones-
Using the AWS Management Console, you can easily create new Multi-AZ deployments or modify existing Single-AZ instances to become Multi-AZ deployments. To create a new Multi-AZ deployment using the AWS Management Console, simply click the “Yes” option for “Multi-AZ Deployment” when launching a DB Instance. To convert an existing Single-AZ DB Instance to a Multi-AZ deployment, use the “Modify” option corresponding to your DB Instance in the AWS Management Console.Resource:Creating an Amazon RDS DB Instance
AWS – Enable auto minor version upgrade to ensure the patching of the security updates-
Enable auto minor version upgrade to ensure the patching of the security updates
If you want Amazon RDS to upgrade the DB engine version of a database automatically, you can enable auto minor version upgrades for the database.When Amazon RDS designates a minor engine version as the preferred minor engine version, each database that meets both of the following conditions is upgraded to the minor engine version automatically:The database is running a minor version of the DB engine that is lower than the preferred minor engine version.The database has auto minor version upgrade enabled.You can control whether auto minor version upgrade is enabled for a DB instance when you perform the following tasks:Creating a DB InstanceModifying a DB InstanceCreating a read replicaRestoring a DB Instance from snapshotRestoring a DB Instance to specific timeImporting a DB Instance from Amazon S3 (for MySQL backup on S3)AWS publishes security bulletins regularly to update the patches.

2. Dynamo DB

AWS – Ensure communication to global resources is only through VPC endpoints or Privatelink

3. Web Services Security Requirements

SQL injection prevention
This  is focused on providing clear, simple, actionable guidance for preventing SQL Injection flaws in your applications. SQL Injection attacks are unfortunately very common, and this is due to two factors:the significant prevalence of SQL Injection vulnerabilities, and the attractiveness of the target (i.e., the database typically contains all the interesting/critical data for your application).Developers need to either:
a) stop writing dynamic queries; and/or
b) prevent user supplied input which contains malicious SQL from affecting the logic of the executed query.
This article provides a set of simple techniques for preventing SQL Injection vulnerabilities by avoiding these two problems.
These techniques can be used with practically any kind of programming language with any type of database. There are other types of databases, like XML databases, which can have similar problems (e.g., XPath and XQuery injection) and these techniques can be used to protect them as well.
Primary Defenses:
Option#1: Use of Prepared Statements (Parameterized Queries)
Option#2: Use of Stored ProceduresOption#3: Escaping all User Supplied InputAdditional Defenses:
Also Enforce: Least PrivilegeAlso Perform: White List Input Validation Unsafe ExampleSQL injection flaws typically look like this:
The following (Java) example is UNSAFE, and would allow an attacker to inject code into the query that would be executed by the database.
The unvalidated “customerName” parameter that is simply appended to the query allows an attacker to inject any SQL code they want. Unfortunately, this method for accessing databases is all too common. String query = “SELECT account_balance FROM user_data WHERE user_name = ” + request.getParameter(“customerName”); try { Statement statement = connection.createStatement( … ); ResultSet results = statement.executeQuery( query ); }Primary Defenses
Defense
Option 1: Prepared Statements (Parameterized Queries)The use of prepared statements (aka parameterized queries) is how all developers should first be taught how to write database queries. They are simple to write, and easier to understand than dynamic queries. Parameterized queries force the developer to first define all the SQL code, and then pass in each parameter to the query later. This coding style allows the database to distinguish between code and data, regardless of what user input is supplied.Prepared statements ensure that an attacker is not able to change the intent of a query, even if SQL commands are inserted by an attacker. In the safe example below, if an attacker were to enter the userID of tom’ or ‘1’=’1, the parameterized query would not be vulnerable and would instead look for a username which literally matched the entire string tom’ or ‘1’=’1.Language specific recommendations:Java EE – use PreparedStatement() with bind variables.NET – use parameterized queries like SqlCommand() or OleDbCommand() with bind variablesPHP – use PDO with strongly typed parameterized queries (using bindParam())Hibernate – use createQuery() with bind variables (called named parameters in Hibernate)SQLite – use sqlite3_prepare() to create a statement objectIn rare circumstances, prepared statements can harm performance. When confronted with this situation, it is best to eithera) strongly validate all data orb) escape all user supplied input using an escaping routine specific to your database vendor as described below, rather than using a prepared statement.Another option which might solve your performance issue is to use a stored procedure instead.Safe Java Prepared Statement ExampleThe following code example uses a PreparedStatement, Java’s implementation of a parameterized query, to execute the same database query. String custname = request.getParameter(“customerName”); // This should REALLY be validated too // perform input validation to detect attacks String query = “SELECT account_balance FROM user_data WHERE user_name = ? “; PreparedStatement pstmt = connection.prepareStatement( query ); pstmt.setString( 1, custname); ResultSet results = pstmt.executeQuery( );Safe C# .NET Prepared Statement ExampleWith .NET, it’s even more straightforward. The creation and execution of the query doesn’t change. All you have to do is simply pass the parameters to the query using the Parameters.Add() call as shown here. String query = “SELECT account_balance FROM user_data WHERE user_name = ?”; try { OleDbCommand command = new OleDbCommand(query, connection); command.Parameters.Add(new OleDbParameter(“customerName”, CustomerName Name.Text)); OleDbDataReader reader = command.ExecuteReader(); // … } catch (OleDbException se) { // error handling } We have shown examples in Java and .NET but practically all other languages, including Cold Fusion, and Classic ASP, support parameterized query interfaces. Even SQL abstraction layers, like the Hibernate Query Language (HQL) have the same type of injection problems (which we call HQL Injection). HQL supports parameterized queries as well, so we can avoid this problem:Hibernate Query Language (HQL) Prepared Statement (Named Parameters) Examples First is an unsafe HQL Statement Query unsafeHQLQuery = session.createQuery(“from Inventory where productID=’”+userSuppliedParameter+”‘”); Here is a safe version of the same query using named parameters Query safeHQLQuery = session.createQuery(“from Inventory where productID=:productid”); safeHQLQuery.setParameter(“productid”, userSuppliedParameter);For examples of parameterized queries in other languages, including Ruby, PHP, Cold Fusion, and Perl, see the Query Parameterization Cheat Sheet.Developers tend to like the Prepared Statement approach because all the SQL code stays within the application. This makes your application relatively database independent. However, other options allow you to store all the SQL code in the database itself, which has both security and non-security advantages. That approach, called Stored Procedures, is described next.Defense Option 2: Stored ProceduresStored procedures have the same effect as the use of prepared statements when implemented safely. They require the developer to define the SQL code first, and then pass in the parameters after. The difference between prepared statements and stored procedures is that the SQL code for a stored procedure is defined and stored in the database itself, and then called from the application. Both of these techniques have the same effectiveness in preventing SQL injection so your organization should choose which approach makes the most sense for you.Note: ‘Implemented safely’ means the stored procedure does not include any unsafe dynamic SQL generation. Developers do not usually generate dynamic SQL inside stored procedures. However, it can be done, but should be avoided. If it can’t be avoided, the stored procedure must use input validation or proper escaping as described in this article to make sure that all user supplied input to the stored procedure can’t be used to inject SQL code into the dynamically generated query. Auditors should always look for uses of sp_execute, execute or exec within SQL Server stored procedures. Similar audit guidelines are necessary for similar functions for other vendors.There are also several cases where stored procedures can increase risk. For example, on MS SQL server, you have 3 main default roles: db_datareader, db_datawriter and db_owner. Before stored procedures came into use, DBA’s would give db_datareader or db_datawriter rights to the webservice’s user, depending on the requirements. However, stored procedures require execute rights, a role that is not available by default. Some setups where the user management has been centralized, but is limited to those 3 roles, cause all web apps to run under db_owner rights so stored procedures can work. Naturally, that means that if a server is breached the attacker has full rights to the database, where previously they might only have had read-access. More on this topic here. http://www.sqldbatips.com/showarticle.asp?ID=8Safe Java Stored Procedure ExampleThe following code example uses a CallableStatement, Java’s implementation of the stored procedure interface, to execute the same database query. The “sp_getAccountBalance” stored procedure would have to be predefined in the database and implement the same functionality as the query defined above. String custname = request.getParameter(“customerName”); // This should REALLY be validated try { CallableStatement cs = connection.prepareCall(“{call sp_getAccountBalance(?)}”); cs.setString(1, custname); ResultSet results = cs.executeQuery(); // … result set handling } catch (SQLException se) { // … logging and error handling }Safe VB .NET Stored Procedure ExampleThe following code example uses a SqlCommand, .NET’s implementation of the stored procedure interface, to execute the same database query. The “sp_getAccountBalance” stored procedure would have to be predefined in the database and implement the same functionality as the query defined above. Try Dim command As SqlCommand = new SqlCommand(“sp_getAccountBalance”, connection) command.CommandType = CommandType.StoredProcedure command.Parameters.Add(new SqlParameter(“@CustomerName”, CustomerName.Text)) Dim reader As SqlDataReader = command.ExecuteReader() ‘ … Catch se As SqlException ‘ error handling End TryWe have shown examples in Java and .NET but practically all other languages, including Cold Fusion, and Classic ASP, support the ability to invoke stored procedures.For organizations that already make significant or even exclusive use of stored procedures, it is far less likely that they have SQL injection flaws in the first place. However, you still need to be careful with stored procedures because it is possible, although relatively rare, to create a dynamic query inside of a stored procedure that is subject to SQL injection. If dynamic queries in your stored procedures can’t be avoided, you can use bind variables inside your stored procedures, just like in a prepared statement. Alternatively, you can validate or properly escape all user supplied input to the dynamic query, before you construct it. For examples of the use of bind variables inside of a stored procedure, see the Stored Procedure There are also some additional security and non-security benefits of stored procedures that are worth considering. One security benefit is that if you make exclusive use of stored procedures for your database, you can restrict all database user accounts to only have access to the stored procedures. This means that database accounts do not have permission to submit dynamic queries to the database, giving you far greater confidence that you do not have any SQL injection vulnerabilities in the applications that access that database. Some non-security benefits include performance benefits (in most situations), and having all the SQL code in one location, potentially simplifying maintenance of the code and keeping the SQL code out of the application developers’ hands, leaving it for the database developers to develop and maintain.Defense Option 3: Escaping All User Supplied InputThis third technique is to escape user input before putting it in a query. If you are concerned that rewriting your dynamic queries as prepared statements or stored procedures might break your application or adversely affect performance, then this might be the best approach for you. However, this methodology is frail compared to using parameterized queries and we cannot guarantee it will prevent all SQL Injection in all situations. This technique should only be used, with caution, to retrofit legacy code in a cost effective way. Applications built from scratch, or applications requiring low risk tolerance should be built or re-written using parameterized queries.This technique works like this. Each DBMS supports one or more character escaping schemes specific to certain kinds of queries. If you then escape all user supplied input using the proper escaping scheme for the database you are using, the DBMS will not confuse that input with SQL code written by the developer, thus avoiding any possible SQL injection vulnerabilities.The javadoc for ESAPI is available here at its Google Code repository.You can also directly browse the source at Google, which is frequently helpful if the javadoc isn’t perfectly clear.To find the javadoc specifically for the database encoders, click on the ‘Codec’ class on the left hand side. There are lots of Codecs implemented. The two Database specific codecs are OracleCodec, and MySQLCodec.Just click on their names in the ‘All Known Implementing Classes:’ at the top of the Interface Codec page.At this time, ESAPI currently has database encoders for:OracleMySQL (Both ANSI and native modes are supported)Database encoders for:SQL ServerPostgreSQLAre forthcoming. If your database encoder is missing, please let us know.Turn off character replacementUse SET DEFINE OFF or SET SCAN OFF to ensure that automatic character replacement is turned off. If this character replacement is turned on, the & character will be treated like a SQLPlus variable prefix that could allow an attacker to retrieve private data.See http://download.oracle.com/docs/cd/B19306_01/server.102/b14357/ch12040.htm#i2698854 and http://stackoverflow.com/questions/152837/how-to-insert-a-string-which-contains-an for more informationEscaping Wildcard characters in Like ClausesThe LIKE keyword allows for text scanning searches. In Oracle, the underscore ‘‘ character matches only one character, while the ampersand ‘%’ is used to match zero or more occurrences of any characters. These characters must be escaped in LIKE clause criteria. For example:SELECT name FROM emp WHERE id LIKE ‘%/%’ ESCAPE ‘/’;SELECT name FROM emp WHERE id LIKE ‘%\%%’ ESCAPE ‘\’;Oracle 10g escapingAn alternative for Oracle 10g and later is to place { and } around the string to escape the entire string. However, you have to be careful that there isn’t a } character already in the string. You must search for these and if there is one, then you must replace it with }}. Otherwise that character will end the escaping early, and may introduce a vulnerability.MySQL EscapingMySQL supports two escaping modes:ANSI_QUOTES SQL mode, and a mode with this off, which we call MySQL mode.ANSI SQL mode: Simply encode all ‘ (single tick) characters with ” (two single ticks)MySQL mode, do the following: NUL (0x00) –> \0 [This is a zero, not the letter O] BS (0x08) –> \b TAB (0x09) –> \t LF (0x0a) –> \n CR (0x0d) –> \r SUB (0x1a) –> \Z ” (0x22) –> \” % (0x25) –> \% ‘ (0x27) –> \’ \ (0x5c) –> \ _ (0x5f) –> _ all other non-alphanumeric characters with ASCII values less than 256 –> \c where ‘c’ is the original non-alphanumeric character.This information is based on the MySQL Escape character information found here: http://mirror.yandex.ru/mirrors/ftp.mysql.com/doc/refman/5.0/en/string-syntax.htmlSQL Server EscapingWe have not implemented the SQL Server escaping routine yet, but the following has good pointers to articles describing how to prevent SQL injection attacks on SQL serverhttp://blogs.msdn.com/raulga/archive/2007/01/04/dynamic-sql-sql-injection.aspx DB2 EscapingTo minimize the potential damage of a successful SQL injection attack, you should minimize the privileges assigned to every database account in your environment. Do not assign DBA or admin type access rights to your application accounts. We understand that this is easy, and everything just ‘works’ when you do it this way, but it is very dangerous. Start from the ground up to determine what access rights your application accounts require, rather than trying to figure out what access rights you need to take away. Make sure that accounts that only need read access are only granted read access to the tables they need access to. If an account only needs access to portions of a table, consider creating a view that limits access to that portion of the data and assigning the account access to the view instead, rather than the underlying table. Rarely, if ever, grant create or delete access to database accounts.If you adopt a policy where you use stored procedures everywhere, and don’t allow application accounts to directly execute their own queries, then restrict those accounts to only be able to execute the stored procedures they need. Don’t grant them any rights directly to the tables in the database.SQL injection is not the only threat to your database data. Attackers can simply change the parameter values from one of the legal values they are presented with, to a value that is unauthorized for them, but the application itself might be authorized to access. As such, minimizing the privileges granted to your application will reduce the likelihood of such unauthorized access attempts, even when an attacker is not trying to use SQL injection as part of their exploit.While you are at it, you should minimize the privileges of the operating system account that the DBMS runs under. Don’t run your DBMS as root or system! Most DBMSs run out of the box with a very powerful system account. For example, MySQL runs as system on Windows by default! Change the DBMS’s OS account to something more appropriate, with restricted privileges.White List Input ValidationInput validation can be used to detect unauthorized input before it is passed to the SQL query. For more information please see the Input Validation Cheat Sheet.
Authentication policy
Forceful Browsing prevention
Forceful browsing can also be made difficult to a large extent by not hard-coding names of application pages or resources. This way, the attacker cannot figure out, from the application alone, the resources available from the present context.
Multi-factor Authentication and Access Control
Use obfuscation and other techniques to prevent reverse engineering.
Use Static Analysis and Dynamic Tools
Data safety in environment variables
Enforce Principle of Least Privilege
Generic Error Pages-
Use of custom error pages – Attackers can glean information about the nature of queries from descriptive error messages. Input validation must be coupled with customized error pages that inform about an error without disclosing information about the database or application.Improper handling of errors can introduce a variety of security problems for a web site. The most common problem is when detailed internal error messages such as stack traces, database dumps, and error codes are displayed to the user (hacker). These messages reveal implementation details that should never be revealed. Such details can provide hackers important clues on potential flaws in the site and such messages are also disturbing to normal users.Web applications frequently generate error conditions during normal operation. Out of memory, null pointer exceptions, system call failure, database unavailable, network timeout, and hundreds of other common conditions can cause errors to be generated. These errors must be handled according to a well thought out scheme that will provide a meaningful error message to the user, diagnostic information to the site maintainers, and no useful information to an attacker.Even when error messages don’t provide a lot of detail, inconsistencies in such messages can still reveal important clues on how a site works, and what information is present under the covers. For example, when a user tries to access a file that does not exist, the error message typically indicates, “file not found”. When accessing a file that the user is not authorized for, it indicates, “access denied”. The user is not supposed to know the file even exists, but such inconsistencies will readily reveal the presence or absence of inaccessible files or the site’s directory structure.A specific policy for how to handle errors should be documented, including the types of errors to be handled and for each, what information is going to be reported back to the user, and what information is going to be logged. All developers need to understand the policy and ensure that their code follows it.Implementation:Ensure that the site is built to gracefully handle all possible errors. When errors occur, the site should respond with a specifically designed result that is helpful to the user without revealing unnecessary internal details. Certain classes of errors should be logged to help detect implementation flaws in the site and/or hacking attempts. Very few sites have any intrusion detection capabilities in their web application, but it is certainly conceivable that a web application could track repeated failed attempts and generate alerts. Note that the vast majority of web application attacks are never detected because so few sites have the capability to detect them. Therefore, the prevalence of web application security attacks is likely to be seriously underestimated.The OWASP Filters project is producing reusable components in several languages to help prevent error codes leaking into user’s web pages by filtering pages when they are constructed dynamically by the application.Reference:https://owasp.org/www-community/Improper_Error_Handling
Avoid passing User Input to Filesystem or Framework API.
Protect the schema against unauthorized modification.
-Design: Protect the schema against unauthorized modification.Implementation: For applications that use a known schema, use a local copy or a known good repository instead of the schema reference supplied in the XML document.
Secure coding using the XMLHttpRequest
-XML HTTP Request: The main disadvantages of building web applications is that once a particular webpage is loaded within the user’s browser, the related server connection is cut off. Further browsing (even) within the page itself requires establishing another connection with the server and sending the whole page back even though the user might have simply wanted to expand a simple link. XML HTTP Request allows asynchronous data retrieval or ensuring that the page does not reload in its entirety each time the user requests the smallest of changes.Service provider should not use the XMLHttpRequest method to create a local proxy for content from other sites, because the client will not be able to discern what content comes from which host.
Throttling mechanism for resource allocation-
Build throttling mechanism into the resource allocation. Provide for a timeout mechanism for allocated resources whose transaction does not complete within a specified interval.
Using SSL
Update software and apply the latest security patches
Applications that handle highly sensitive information should consider disabling copy and paste functionality
Encryption: Always ensure data integrity and authenticity
Store sensitive information at the server
-Do not store sensitive information, such as usernames or authentication and authorization information, in user-controllable locations.
Sensitive Information defining user state to be protected
-At all times sensitive information that is part of the user state must be appropriately protected to ensure confidentiality and integrity at each request
No sensitive data from server to client via JSON objects
Encrypt all Communication between the Client and Server.
Least Privilege Execution
-Run your code using the lowest privileges that are required to accomplish the necessary tasks. If possible, create isolated accounts with limited privileges that are only used for a single task.
Run server interfaces with a non-root account
-Run server interfaces with a non-root account and/or utilize chroot jails or other configuration techniques to constrain privileges even if attacker gains some limited access to commands.
Perform testing such as pen-testing and vulnerability scanning
Restrict Access to the Web Root and the Directories Within
-Ensure proper permissions on directories that are accessible through a web server.Disallow remote access to the web root. Disable execution on directories within the web root. Ensure that permissions of the web server process are only what is required by not using built-in accounts and instead create specific accounts to limit unnecessary access or permissions overlap across multiple systems.
Cross-site request forgery prevention
-Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious Web site, email, blog, instant message, or program causes a user’s Web browser to perform an unwanted action on a trusted site for which the user is currently authenticated. The impact of a successful cross-site request forgery attack is limited to the capabilities exposed by the vulnerable application. For example, this attack could result in a transfer of funds, changing a password, or purchasing an item in the user’s context. To prevent CSRF attacks, it is important to understand that you must already be authenticated into a certain website to be vulnerable. Banking or any site that performs financial transactions and has a high usage rate are the primary targets of these attacks. Actions you can take to prevent a CSRF attack:Make sure your anti-virus software is up to date. Many malicious scripts can be blocked and quarantined by this software.Do not open any emails, browse to other sites or perform any other social network communication while authenticated to your banking site or any site that performs financial transactions. This will prevent any malicious scripts from being executed while being authenticated to a financial site.Whenever you finish a banking or financial transaction on a site always log off immediately. Don’t just minimize or close the browser. If you do, it will make you vulnerable to an attack. Never save your login or password for a banking or financial institution site within your browser. Malicious code in CSRF attacks is usually written to take advantage of this information that is within your browserDisable scripting in your browser. Firefox has a plugin that can prevent scripts from running.Run all your financial or banking transactions in one browser and all your other browsing within another. This way an attacker cannot make your general web browser do anything malicious to your banking or financial transaction browser.
Prevent Information Leak from the HTTP Response
-Implementation:Obfuscate server fields of HTTP response.Hide inner ordering of HTTP response header.Customizing HTTP error codes such as 404 or 500.Hide URL file extension.Hide HTTP response header software information filed.Hide cookie’s software information filed.Appropriately deal with error messages.Obfuscate database type in Database API’s error message.
White List against XSS
Escaping Output Properly
Avoid clicking on untrusted links
Input Sanitization
Disable Script Execution
-If possible, disable script execution in the administrative interface.
Use libraries and templates that minimize unfiltered input
TM – Authentication: Error Messages
Minimize error or response output
-Incorrectly implemented error messages in the case of authentication functionality can be used for the purposes of user ID and password enumeration. An application should respond (both HTTP and HTML) in a generic manner.
Authentication Responses
An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account.
Incorrect Response Examples
"Login for User foo: invalid password" "Login failed, invalid user ID" "Login failed; account disabled" "Login failed; this user is not active"
Correct Response Example
"Login failed; Invalid userID or password"
The correct response does not indicate if the user ID or password is the incorrect parameter and hence inferring a valid user ID.
Error Codes and URL’s
The application may return a different HTTP Error code depending on the authentication attempt response. It may respond with a 200 for a positive result and a 403 for a negative result. Even though a generic error page is shown to a user, the HTTP response code may differ which can leak information about whether the account is valid or not.
Construct a Code Book for Error Messages
Customizing HTTP error codes such as 404 or 500
Use innerText against XSS
-If you use the innerHTML property to build a page and the HTML is based on potentially untrusted input, you must use HtmlEncode to make it safe. To avoid having to remember to do this, use innerText instead. The innerText property renders content safe and ensures that scripts are not executed.
The following example shows this approach for two HTML controls. The code in the Page_Load method sets the text displayed in the Welcome1 element using the innerText property, so HTML-encoding is unnecessary. The code sets the text in the Welcome2 element by using the innerHtml property; therefore, you must HtmlEncode it first to make it safe.
Use Browser Technologies
Attackers can embed scripts within scripts which can exploit a programs’ vulnerabilities that are brought on by allowing remote hosts to execute scripts. To prevent this from happening it is recommended that you use browser technologies that do not allow client side scripting.When client side scripting is used it can relieve some of the processing burden placed on a web server. This must be balanced against the threat of bad actors running scripts within scripts.Utilize strict type, character, and encoding enforcement.It is necessary to validate all input from the user/client/browser as it is received at the server.The more limits placed on what is accepted will allow client side scripts to be used, but not maliciously.Reference: https://capec.mitre.org/data/definitions/19.html 
Ensure all Content coming from the Client is using the same Encoding
– Ensure all content coming from the client is using the same encoding; if not, the server-side application must canonicalize the data before applying any filtering.
Server Side Security Check
-For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side
Use Digital Signatures
TM – Cookies
Separate the Presentation Layer and The Business Logic Layer
Do not Rely on Client Validation or Encoding for Security Purposes.
Protect Client Side Authentication Tokens
Enable Integrity Checks – Code Signing
HTML5 – Enable XSS filter
TM – Cross-Site Scripting Prevention
Minimal Privileges on XML Parsing
Sanitize incoming DTDs to prevent excessive expansion
Use Static Analysis Tools
Log File Protection
Secure communication across tiers
Default Deny Access Control Policies
Get Components from a Trusted Source
Restrict access of the System to Authorized members only
Defense in Depth
Avoid using the GET method to submit data
Refer to the RFCs to safely decode URL.
TM – Parameterized Queries
Suppressing Error Messages
Make sure that your program or service fail safely
Ensure the System can properly process Unicode Data
Encode URL Output
Avoid making Decisions based on Names of Resources
WS – User Authentication
WS – Input Validation
WS – Message Size
REST – Authentication and Session Management
ACL on HTTP methods
Perform URL encoding
Configure the XML processor
Pick a robust implementation of an XML parser
Run anti-malware scans regularly
Limit the waiting period of an opened HTTP sessions
Verify arguments supplied from external sources
Limit permissions to only those required
Leverage system penetration testing and other defense in depth methods
Use Software Restriction Policy or Tools that Restrict Program Execution
Protecting the Authentication Function
HTTP GET safety
Granular Access Control
Use Indirect References and Possible Permissions on File Access
Heavy peer-review of code before deployment
Smart contract testing performed by independent testing facilities

5. S3 bucket

AWS – Ensure the S3 bucket CloudTrail logs to is not publicly accessible
AWS – Ensure log retention policy is setup on S3 bucket configured in the logging account
AWS – Ensure logs generated by services are ingested in a bucket in the central logging account
AWS – Ensure communication to global resources is only through VPC endpoints or Privatelink
AWS – Ensure encryption of S3 buckets
AWS – Ensure sensitive data is masked for Analytics workloads
AWS – Ensure S3 bucket access logging is enabled on the CloudTrail S3 bucket
AWS – Ensure versioning is enabled on S3 buckets
AWS – Add a Replication Rule to an S3 Bucket

6.CloudFront

AWS – Enable Access Logs
AWS – Disable origin identity
AWS – Sign the restricted URL
AWS – Configure CloudFront to return a custom error page when a request is blocked
AWS – Encrypt data in transit
AWS – Use AWS WAF to allow or block requests based on the rules in a web access control list
AWS – Ensure applications are protected against DDoS attacks

7. ELB Security Requirments

AWS – Enable Access Logs
-Access LogsElastic Load Balancing provides access logs that capture detailed information about requests sent to your load balancer. Each log contains information such as the time the request was received, the client’s IP address, latencies, request paths, and server responses. You can use these access logs to analyze traffic patterns and to troubleshoot issues.Implement the steps discussed belowTo enable access logging using the consoleStep 1: Create an S3 BucketStep 2: Attach a Policy to Your S3 Bucket.Step 3: Enable Access LogsStep 4: Verify that the Load Balancer Created a Test File in the S3 BucketCloudfront Access Logs: Server access logs provide detailed records about requests that are made to a distribution. Server access logs are useful for many applications. For example, access log information can be useful in security and access audits.The below links provide guidance on enabling logs for individual services:ELB Access LogsELBCloudfront Access LogsRoute53DynamoDBRDSElastic BeanstalkAthena
AWS – Use secure listeners to support encrypted communication between clients and your load balancers. Application Load Balancers support HTTPS listeners
-Follow the steps to Create and Enable a secured Listener:1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.2. On the navigation pane, under LOAD BALANCING, choose Load Balancers.3. Select a load balancer, and choose Listeners, Add listener.4. For Protocol: port, choose HTTPS. Keep the default port or type a different port.5. To authenticate users, for Default actions, choose Add action, Authenticate and provide the requested information. To save the action, choose the checkmark icon. For more information, see Authenticate Users Using an Application Load Balancer.6. For Default actions, do one of the following:Choose Add action, Forward to and choose a target group.Choose Add action, Redirect to and provide the URL for the redirect. For more information, see Redirect Actions.Choose Add action, Return fixed response and provide a response code and optional response body. For more information, see Fixed-Response Actions.To save the action, choose the checkmark icon.7. For Security policy, we recommend that you keep the default security policy.8. For a Default SSL certificate, do one of the following:If you created or imported a certificate using AWS Certificate Manager, choose From ACM and choose the certificate.If you uploaded a certificate using IAM, choose From IAM and choose the certificate.9. Choose Save.Reference: http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-create-https-ssl-load-balancer.htmlTo update Security Policy for HTTPS Listener
AWS – Encrypt Data At Rest
-Data encryption helps prevent unauthorized users from reading data on a cluster and associated data storage systems.
This includes data saved to persistent media, known as data-at-rest and data that may be intercepted as it travels the network, known as data-in-transit.The following links provide further guidance on encrypting data at rest for individual services:RDS and Amazon AuroraCloudtrailLambdaElasticacheEFSCloudfrontDynamoDBSNSSQSATHENARedshiftAWS EC2 Auto ScalingResource:How AWS Services use KMSAWS KMS FeaturesProtecting data using SSE-S3
AWS – Ensure logs generated by services are ingested in a bucket in the central logging account
-You can export log data from your log groups to an Amazon S3 bucket and use this data in custom processing and analysis, or to load onto other systems.To begin the export process, you must create an S3 bucket to store the exported log data. You can store the exported files in your Amazon S3 bucket and define Amazon S3 lifecycle rules to archive or delete exported files automatically.Implement the steps discussed below:Step 1: Create an Amazon S3 BucketWe recommend that you use a bucket that was created specifically for CloudWatch Logs. However, if you want to use an existing bucket, you can skip to Step 2.Note: The Amazon S3 bucket must reside in the same Region as the log data to export. CloudWatch Logs doesn’t support exporting data to Amazon S3 buckets in a different Region.To create an Amazon S3 bucket1. Open the Amazon S3 console at https://console.aws.amazon.com/s3/.2. If necessary, change the Region. From the navigation bar, choose the Region where your CloudWatch Logs reside.3. Choose Create Bucket.4. For Bucket Name, enter a name for the bucket.5. For Region, select the Region where your CloudWatch Logs data resides.6. Choose Create.Step 2: Create an IAM User with Full Access to Amazon S3 and CloudWatch LogsIn the following steps, you create the IAM user with the necessary permissions.To create the necessary IAM user1. Open the IAM console at https://console.aws.amazon.com/iam/.2. Choose Users, Add user.3. Enter a user name, such as CWLExportUser.4. Select both Programmatic access and AWS Management Console access.5. Choose either Autogenerated password or a Custom password.6. Choose Next: Permissions.7. Choose to Attach existing policies directly, and attach the AmazonS3FullAccess and CloudWatchLogsFullAccess policies to the user. You can use the search box to find the policies.8. Choose Next: Tags, Next: Review, and then Create user.Resources:https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/S3ExportTasksConsole.htmlhttps://aws.amazon.com/answers/logging/aws-native-security-logging-capabilities/
AWS – Ensure communication to global resources is only through VPC endpoints or Privatelink
-A VPC endpoint enables you to privately connect your VPC to supported AWS services and VPC endpoint services powered by PrivateLink without requiring an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection. Instances in your VPC do not require public IP addresses to communicate with resources in the service. Traffic between your VPC and the other service does not leave the Amazon network. Endpoints are virtual devices. They are horizontally scaled, redundant, and highly available VPC components that allow communication between instances in your VPC and services without imposing availability risks or bandwidth constraints on your network traffic.
There are two types of VPC endpoints: interface endpoints and gateway endpoints.
Steps to Implement:To create an interface endpoint to an AWS service using the consoleOpen the Amazon VPC console at https://console.aws.amazon.com/vpc/In the navigation pane, choose Endpoints, Create Endpoint.For the Service category, ensure that AWS services are selectedFor Service Name, choose the service to which to connect. For Type, ensure that it indicates InterfaceComplete the following information and then choose Create endpoint: VPC: Select VPC in which to create the endpoint; Subnets: select the subnets (Availability Zones) in which to create the endpoint network interfaces; DNS: To enable private DNS for the interface endpoint, for Enable Private DNS Name, select the check box; Security group: select the security groups to associate with the endpoint network interfaces; Tags: (Optional) add any tags.Resources:S3 Bucket Cloudwatch ELB DynamoDB ECS
Glacier SNS
SQS Athena ECREMR Elastic Beanstalk CodeBuild SageMakerDataSyncApp Mesh SQSAWS EC2 Auto ScalingConfigEFSKMS
AWS – Encrypt data in transit
-Protecting your data in transit by defining your requirements and implementing controls, including encryption, reduces the risk of unauthorized access or exposure. 
If your organization is subject to corporate or regulatory policies that require encryption of data in transit, we recommend using encryption of data in transit on every client accessing the file system. Encryption and decryption are configured at the connection level and adds another layer of security.The following links provide further guidance on encrypting data in transit for individual services:BeanstalkSQSCloudfrontEFSAthenaElasticacheRDS
AWS – Configure the security groups for your load balancers
-Configure the security groups for your Application Load Balancers and Classic Load Balancers to accept traffic only from specific clients. These security groups must allow inbound traffic from clients on the listener ports and outbound traffic to the clients.A security group acts as a virtual stateful firewall that controls the traffic for one or more instances.When you launch an instance, you associate one or more security groups with the instance.You add rules to each security group that allows traffic to or from its associated instances.You can modify the rules for a security group at any time; the new rules are automatically applied to all instances that are associated with the security group after a short period. Note: security groups are more effective at restricting/regulating network traffic than NACLs (Network Access Control Lists)Resource:Infrastructure Security for Load Balancinghttps://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html
AWS – Use AWS WAF to allow or block requests based on the rules in a web access control list
-A web access control list (web ACL) gives you fine-grained control over the web requests that your Amazon CloudFront distribution, Amazon API Gateway API, or Application Load Balancer responds to.
You can use criteria like the following to allow or block requests:
IP address origin of the request Country of origin of the request String match or regular expression (regex) match in a part of the request Size of a particular part of the request Detection of malicious SQL code or scripting.When you make changes to web ACLs or web ACL components, like rules and rule groups, AWS WAF propagates the changes everywhere that the web ACL and its components are stored and used. Your changes are applied within seconds, but there might be a brief period of inconsistency when the changes have arrived in some places and not in others. So, for example, if you add an IP address to an IP set that’s referenced by a blocking rule in a web ACL, the new address might briefly be blocked in one area while still allowed in another. This temporary inconsistency can occur when you first associate a web ACL with an AWS resource and when you change a web ACL that is already associated with a resource. Generally, any inconsistencies of this type last only a few seconds.
Working with Web ACLs
To create a web ACL
Sign in to the AWS Management Console and open the AWS WAF console at https://console.aws.amazon.com/wafv2/.
Choose Web ACLs in the navigation pane, and then choose Create web ACL.
For Name, enter the name that you want to use to identify this web ACL.
Note: You can’t change the name after you create the web ACL.
(Optional) For Description – optional, enter a longer description for the web ACL if you want to.
For CloudWatch metric name, change the default name if applicable. Follow the guidance on the console for valid characters. The name can’t contain special characters, white space, or metric names reserved for AWS WAF, including “All” and “Default_Action.”
Note: You can’t change the CloudWatch metric name after you create the web ACL.
For Resource type, choose the category of AWS resource that you want to associate with this web ACL. For more information, see Associating or disassociating a Web ACL with an AWS resource.
For Region, if you’ve chosen a regional resource type, choose the Region where you want AWS WAF to store the web ACL.
You only need to choose this option for regional resource types. For CloudFront distributions, the region is hardcoded to the US East (N. Virginia) Region, us-east-1, for Global (CloudFront) applications.
For Associated AWS resources – optional, choose Add AWS resources. In the dialog box, choose the resources that you want to associate, and then choose Add. AWS WAF returns you to the Describe web ACL and associated AWS resources page.
Choose Next.
(Optional) If you want to add managed rule groups, on the Add rules and rule groups page, choose Add rules, and then choose Add managed rule groups. Do the following for each managed rule group that you want to add:
10a. On the Add managed rule groups page, expand the listing for AWS managed rule groups or for the AWS Marketplace seller of your choice.
10b. For the rule group that you want to add, turn on the Add to web ACL toggle in the Action column.
10c. If you want to set the action for all rules in the rule group to count only, turn on the Set rule’s action to count toggle. For information about this option, see Overriding the actions of an entire rule group.
10d. Choose Add rules to finish adding managed rules and return to the Add rules and rule groups page.
(Optional) If you want to add your own rule group, on the Add rules and rule groups page, choose Add rules, and then choose Add my own rules and rule groups. Do the following for each rule group that you want to add:
11a. On the Add my own rules and rule groups page, choose Rule group.
11b. Choose your rule group from the list. If you want to override the rule actions for the group, turn on the Set rule’s action to count toggle. For information about this option, see Overriding the actions of an entire rule group.
(Optional) If you want to add your own rule, on the Add rules and rule groups page, choose Add rules, Add my own rules and rule groups, Rule builder, then Rule visual editor.
Note: The console Rule visual editor supports one level of nesting. For example, you can use a single logical AND or OR statement and nest one level of other statements inside it, but you can’t nest logical statements within logical statements. To manage more complex rule statements, use the Rule JSON editor. For information about all options for rules, see AWS WAF rules.
This procedure covers the Rule visual editor.
12a. For Name, enter the name that you want to use to identify this rule.
12b. Enter your rule definition, according to your needs. You can combine rules inside logical AND and OR rule statements. The wizard guides you through the options for each rule, according to context. For information about your rules options, see AWS WAF rules.
12c. For Action, select the action you want the rule to take when it matches a web request. For information on your choices, see AWS WAF rule action and How AWS WAF processes a Web ACL.
12d. Choose Add rule.
Choose the default action for the web ACL. This is the action that AWS WAF takes when a web request doesn’t match any of the rules in the web ACL. For more information, see Deciding on the default action for a Web ACL.
Choose Next.
In the Set rule priority page, select and move your rules and rule groups to the order that you want AWS WAF to process them. For more information, see How AWS WAF processes a Web ACL.
Choose Next.
In the Configure metrics page, deselect anything you don’t want metrics for, and update names as needed. You can combine metrics from multiple sources by providing the same CloudWatch metric name.
Choose Next.
In the Review and create web ACL page, check over your definitions. If you want to change any area, choose Edit for the area. This returns you to the page in the web ACL wizard. Make any changes, then choose Next through the pages until you come back to the Review and create a web ACL page.
Choose Create web ACL. Your new web ACL is listed on the Web ACLs page.
Reference:
https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-creating.html
https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-editing.html
AWS – Configure an Application Load Balancer to securely authenticate users as they access your applications
-You can configure an Application Load Balancer to securely authenticate users as they access your applications. This enables you to offload the work of authenticating users to your load balancer so that your applications can focus on their business logic.The following use cases are supported:Authenticate users through an identity provider (IdP) that is OpenID Connect (OIDC) compliant.Authenticate users through well-known social IdPs, such as Amazon, Facebook, or Google, through the user pools supported by Amazon Cognito.Authenticate users through corporate identities, using SAML, LDAP, or Microsoft AD, through the user pools supported by Amazon Cognito.Resource:Authenticate Users Using an Application Load Balancer
AWS – Ensure applications are protected against DDoS attacks
-For higher levels of protection against attacks targeting your web applications running on Amazon Elastic Compute Cloud, Elastic Load Balancing (ELB), Amazon CloudFront, Amazon Route 53, and AWS Global Accelerator, you can subscribe to AWS Shield Advanced. AWS Shield Advanced provides expanded DDoS attack protection for these resources.As an example of this added protection:If you use Shield Advanced to protect an Elastic IP address, during an attack Shield Advanced will automatically deploy your network ACLs to the border of the AWS network, which allows Shield Advanced to provide protection against larger DDoS events. Typically, network ACLs are applied near your Amazon EC2 instances within your Amazon VPC. The network ACL can mitigate attacks only as large as your Amazon VPC and the instance can handle. For example, if the network interface attached to your Amazon EC2 instance can process up to 10 Gbps, volumes over 10 Gbps will slow down and possibly block traffic to that instance. During an attack, Shield Advanced promotes your network ACL to the AWS border, which can process multiple terabytes of traffic. Your network ACL is able to provide protection for your resource well beyond your network’s typical capacity.Resource:What are AWS WAF, AWS Shield, and AWS Firewall Manager?

Posted by

in