WS-Security: Is It Enough to Secure Your SOAP Web Services?

What Is WS-Security?

Web Services Security, also known as WS Security, is an extension to the SOAP specification, which specifies how to secure SOAP web services from external attacks. WS Security offers a set of API security measures that can help ensure security for SOAP-based messages, through the implementation of several principles that help achieve confidentiality, authentication and integrity.

Important aspects of the WS security standard include:

  • SOAP web services operate independently of specific hardware and software implementations. This means that WS Security protocols must be flexible enough to accommodate new security mechanisms as well as provide alternative mechanisms when a certain approach does not work. 
  • SOAP-based messages traverse multiple intermediaries. Security protocols must be able to identify fake nodes as well as prevent data interpretation at any nodes. 

Related content: Read our guide to SOAP security

In this article:

The WS-Security Standard

Here are the three main mechanisms described by the WS Security standard:

  • Signing SOAP messages – how to do this in a way that ensures both integrity and non-repudiation.
  • Encrypting SOAP messages – the standard explains how you can encrypt SOAP messages in a manner that ensures confidentiality.
  • Attaching security tokens – the standard recommends attaching security tokens in a way that helps ascertain the identity of the sender.

The WS Security specification considers a wide range of encryption algorithms and signature formats, as well as multiple trust domains. The standard is also open to a variety of security token models, including user ID/Password credentials, Kerberos tickets, X.509 certificates, SAML assertions, and custom-defined tokens. You can find information about semantics and token formats in the associated profile documents.

Can WS Security work as a complete security solution?

The WS-Security standard defines security measures that are incorporated within the header of a SOAP message. This means WS Security measures work in the application layer. By themselves, these mechanisms do not provide a complete security solution and WS Security alone does not offer a complete security guarantee for Web services. 

The WS Security specific serves as a building block, which you should use alongside other Web service extensions as well as with higher-level application-specific protocols. Ideally, your security should accommodate a variety of security technologies and security models. 

Note that trust bootstrapping key management, federation and agreement on the technical details (such as ciphers, algorithms, and formats) is outside the scope of WS Security. When you implement and use the WS Security framework and syntax, you are responsible to ensure that your result is not vulnerable. 

WS Security Threats and Countermeasures

To protect web services, you can use the HTTPS protocol, which helps establish secure communication between client and server over the web. To achieve secure communication, the HTTPS protocol uses the Secure Sockets Layer (SSL) protocol, which ensures that both client and server have a digital certificate that validates their identity. 

Here are several steps that occur during HTTPS communication between clients and servers:

  1. A client uses the client SSL certificate to send a request to a certain server. 
  2. The server receives the client certificate. 
  3. The server makes a note in the cache system. This ensures the server knows that a response to this request should go back only to this specific client.
  4. In order to authenticate itself to the client, the server sends its own certificate. This validation occurs to ensure the client achieves communication with the correct server.
  5. All future communication between the client and server is encrypted. If threat actors attempt to breach security and obtain this data, the encryption can prevent them from making use of the data.

The above security is effective in some cases, but does not offer complete protection for web services. For example, when a client talks to multiple servers, or when a client talks to a web server and a database simultaneously. In these scenarios, not all information can be transmitted through the HTTPS protocol.

SOAP and WS Security

WS Security specifications recommend applying several security measures to the SOAP security protocol. These measures should be defined within the SOAP header element, which can contain the following information:

  • If a message in the SOAP body is signed with any security key, then that key can be defined in the header element.
  • If any element in the SOAP body is encrypted, then the header should contain all necessary encryptions keys. This ensures that the message is decrypted once it reaches its destination.

Here is how the above SOAP authentication techniques can help contribute to the security of multiple server environments:

  • Only the host server can decrypt the SOAP body—by encrypting the SOAP body, you ensure that it can only be decrypted by the web server hosting your web service. 
  • A database server cannot read the message—if a message is transferred to a database server via an HTTP request, the database cannot decrypt it. This is because it does not have the mechanisms needed to decrypt the message.
  • Only a SOAP protocol message can be decrypted—a request can be decrypted only when it reaches the web server in the form of a SOAP protocol. The server can then decipher the message and send the relevant response back to the client.

Web Service Security Best Practices

In addition to using the WS Security standard, you can ensure your web services are secure by following these best practices.

Related content: For even more best practices, read our guide to general API security best practices

Ensure Transport Confidentiality

Transport confidentiality can help you protect against attacks like Man-in-the-Middle (MITM) and eavesdropping attacks trying to intercept, delete or modify communications made to and from your server. You should always assume that all communication with and between web services contain sensitive data.

Data transfer of any kind, particularly sensitive or regulated information, as well as authenticated sessions, must always be encrypted with properly-configured Transport Layer Security (TLS) protocols. The protocol offers additional benefits, such as protection against replay attacks and server authentication. 

Maintain Message Integrity

TLS can help you maintain the integrity of data at rest. This means you should implement TLS even if the content of a message is already encrypted. This is because TLS also protects the integrity of the transmitted data.

Public keys can protect the confidentiality of data but do not protect its integrity. This is because a public key may be accessed by others. Additionally, public-key encryption cannot maintain the identity of a sender.

To maintain XML data integrity, you need to use XML digital signatures. This process uses the private key of the sender for encryption. It enables recipients to validate the signature by using the public key of a sender. 

Maintain Message Confidentiality

You must always encrypt data with a strong encryption key. Ideally, the length of the key should be adequate to prevent brute force attacks. Here are several aspects to consider when implementing message confidentiality:

  • Identify messages containing sensitive or regulated data—always use strong encryption keys to protect sensitive data. You can implement both message encryption and transport encryption when the data is in transit. 
  • Identify sensitive data that must remain encrypted when at rest—always use strong encryption processes to protect this data. Transport encryption is not sufficient in this case. 

Prevent XML DoS Attacks

XML Denial-of-Service (DoS) attacks are highly common in web services and are arguably the most dangerous attacks that occur within web service environments. Here are two methods that can help you achieve XML DoS prevention:

  • Validate—always validate against XML entity expansion, oversized payloads and recursive payloads. You should also validate against overlong element names, especially in SOAP-based web services.
  • Test—develop test cases that can help you simulate and determine whether the XML parser or schema validator is capable of defending against XML DoS attacks. 

Ensure Availability

When attacks occur, a web service might need more resources than are available. This can lead to a state of instability and may result in denial of service. When configuring your resource usage, applying the following limits to ensure availability during attacks:

  • The number of CPU cycles—to ensure stability, you should set this limit according to the expected service rate. 
  • The amount of memory—to prevent system crashes, set a limit on the amount of memory the web service is allowed to use. 
  • The number of simultaneous operations—to ensure stability, set a limit to the number of processes, open files and network connections allowed to work simultaneously.

It is essential to prioritize security and ensure continuous protection for your web services. However, security should not come at the expense of availability. When implemented correctly, these WS security measures should help you maintain availability when attacks occur. When systems fail, you should be able to resume normal operations quickly and efficiently.

GraphQL Security: The Complete Guide to Protecting Your APIs

What is GraphQL?

Simply put, GraphQL is a query language specifically designed for processing data. It’s most often used to communicate between the client and server. The biggest GraphQL advantage is that it’s very efficient in saving bandwidth as it serves the data with a single query using schemas. 

However, given its wide array of usage, GraphQL is very sensitive to vulnerabilities, and you’ll want to be 100% sure that your queries are well protected as these issues could lead to endless vulnerabilities on your app.

In this article:

GraphQL Security Challenges

If implemented properly, GraphQL is an extremely elegant methodology for data retrieval. GraphQL offers more back-end stability and increased query efficiency.

Please note the phrase “when implemented properly.” The problem with GraphQL is that many people aren’t considering what adopting GraphQL means for their system, and what security implications come with its adoption.

With GraphQL, security concerns have changed. Thanks to the architectural differences and nuances, some security concerns have gone away, but others have been amplified. 

In this article, we are going to cover the security concerns that an API system supporting GraphQL should acknowledge.

The 5 Most Common GraphQL Security Vulnerabilities

1. Inconsistent Authorization Checks

When assessing GraphQL-based applications, flaws in authorization logic are a common issue. While GraphQL helps implement proper data validation, API developers are left to implement authorization and authentication methods on their own. The multiple  “layers’ ‘ of resolvers used for GraphQL APIs add complexity since authorization checks are required for both query-level resolvers and resolvers that load additional data. 

Generally, we see two types of authorization flaws in GraphQL APIs. The first and most common is seen when authorization functionality is controlled directly by resolvers at the GraphQL API layer. Authorization checks need to be performed separately in each location to prevent an exploitable authorization flaw. This is compounded as the complexity of the API schema enlarges and there are more distinct resolvers that are responsible for the access control to the same data. 

In our demo API example below, there are several ways to retrieve a listing of Post objects – a client can retrieve a list of users, public posts, or simply recover a post by its numeric ID. For example, the following query might be used to read all of the currently logged-in user’s posts:

query ReadMyPosts {
  # "me" returns the current user
  me {
    # then, resolve the posts
    posts {
      # finally, return the content
      # and whether this is a public post or not.
      public
      content
    }
  }
}

However, each of these various paths used to retrieve a post has its own set of logic to check the accessibility. Particularly, if examining the code to retrieve a post by its ID (for example the GetPostById function in lib/gql/types/post.ts of the source repository),it should be mentioned that there are no authorization checks in place. This is how the attacker is allowed to perform the GraphQL equivalent of a  traditional insecure direct object reference attack and retrieve any post they want to, whether it is public or private. Our database assigns Post object IDs by ascending order:

query ReadPost {
   # we shouldn't be able to read post "1"
   post(id: 1) {
       public
       content
   }
}

The example might seem simple, but similar issues are often found in real-world GraphQL deployments. A similar problem was recently disclosed to the HackerOne bug bounty program where an attacker was able to read all the email addresses that belong to users they sent an invitation to by their username. (The intended behavior is to only allow access to the email address if that was originally used to create the invitation object).

GraphQL documentation provides guidance on performing authorization safely. The advice is simple – instead of performing authorization logic inside of resolver functions, all the logic should be performed by the business-logic layer underneath it. This results in all authorization checks being performed in one location, which makes applying constraints easier and consistent. 

2. REST Proxies Allow Attacks on Underlying APIs

To adapt an existing REST API for GraphQL clients, you will usually begin the transition by implementing the new GraphQL interface as a thin proxy layer on top of internal REST APIs. In a very simple implementation, the API resolver will simply “translate” requests to the REST API format, and the response will be formatted in a way that the GraphQL client can understand. 

For example, the resolver for user(id: 1) could be implemented in the GraphQL proxy layer by making a request to GET /api/users/1 on the backend API. If this is implemented unsafely, the attacker is able to modify the path or parameters to the backend API, presenting a limited form of SSRF. If the attacker provides the ID 1/ delete, the GraphQL proxy layer might instead access GET /api/users/1/delete with its credentials, not the desired response. One could say this is not an ideal REST API design, but similar scenarios are not uncommon in real-world implementations.

We implemented the getAsset resolver in the following manner:

        getAsset: {
            type: GraphQLString,
            args: {
                name: {
                    type: GraphQLString
                }
            },
            resolve: async (_root, args, _context) => {
                let filename = args.name;
                let results = await axios.get(`http://localhost:8081/assets/${filename}`);
                return results.data;
            }
        }

In this instance, we’re using the name of the asset that we’re aiming for. The name of the asset itself is added to the full path of the service we’re trying to access. It’s not predefined whether we should add it to the beginning or the end of the path. By using the function below, we’re getting the secret path to the file in the root directory:

query ReadSecretFile {
   getAsset(name: "../secret");
}

To protect against this type of vulnerability, proper validation of any parameter passed to another service is required. You can do this by ensuring the GraphQL schema type validator requires a number for the file name, as the numbers are the valid inputs for this request. Alternatively, you can implement validation of input values. GraphQL will validate the types, but the format validation is left to you. A custom scalar type can be used to apply any custom validation rules that apply for a commonly used type. 

3. Missing Validation of Custom Scalars

The data that GraphQL works with is a scalar type, whether the data is input data or the returned output. There are five types of scalar data – int, float, string, ID, and bool. 

As a developer however, you can create your own custom data types,  for example, a time and date datatype.

While this is very useful, care and restraint are required as the responsibility for sanitizing the user input and validating the data properly lies with you. If you’re using JavaScript, for example,  you could implement parseValue and parseLiteral to keep your application safe.

You may also want to avoid using GraphQL libraries for creating new scalar types, as this could create vulnerabilities in your application. While it is an easier method to use, it creates many problems that you want to avoid as a security-conscious developer.

For example, in the below, we’ve used graphql-json library to obtain password reset mutation. 

export const PasswordReset: GraphQLFieldConfig = {
    type: UserType,
    args: {
        input: {
            type: GraphQLJSON
        },
    },
    resolve: async(_root, args, context) => {
        console.log(args);
        if (args.input.username === undefined || args.input.reset_token === undefined || args.input.new_password === undefined) {
            throw new Error("Must provide username, new_password, and reset_token.")
        }
        let user = await db.User.findOne({where: {username: args.input.username, resetToken: args.input.reset_token}})
        if (user) {
            // Update the user in the database first.
            user.password = await argon2.hash(args.input.new_password);
            user.save();
            // Now, return it.
            context.user = user;
            context.session.user_id = user.id;
            return user;
        }
        else {
            throw new Error('The password reset token you submitted was incorrect.')
        }
    }
}

The API queries that database for the input of a username, new password, and a password reset token. However, this process results in data being directly input from the form, resulting in a vulnerability as the input was not properly checked.

Our password reset function takes in a JSON object that contains a username, a new password, and a password reset token checked to ensure validity. The API backend queries the database to check if the token was correct, directly passing the username and reset token values that haven’t been properly checked from the input. Since our application uses the Sequelize ORM, which allows complex operators to be embedded in queries, removing the object in favor of a string gives us an option of creating a query that’s similar to NoSQL injection techniques. In the example below, a user is resetting the password to “RTest!”: 

mutation ResetPassword {
  passwordReset(input: {username:"Helena_Simonis", new_password: "RTest!", reset_token:{gt:""}}) {
    username
  }
}

4. Failure to Appropriately Rate-limit

Rate-limiting and creating DOS protection in general is getting more difficult by the day due to the complexity of GraphQL APIs. This is because the GraphQL query is able to take in multiple actions, meaning that no specific amount of server resources is prepared beforehand. This makes for an unpredictable application. This means that you cannot use the same strategy for limiting the number of requests for a GraphQL as you usually would with an API.

Even the smallest queries could easily “explode” in terms of the execution complexity. Here’s an example of our query where a User has a set of Posts, which in turn has an Author, that also has Posts. As you can see, the query, even though it looks small and simple, is actually very complex.

query Recurse {
  allUsers {
    posts {
      author {
        posts {
          author {
            posts {
              author {
                posts {
                  id
                }
              }
            }
          }
        }
      }
    }
  }
}

If we add another layer to this query the complexity is compounded even further. The most common strategy to prevent DOS attacks in GraphQL is to put a limit on the query depth. Although this can be quite limiting, it ensures your application is secure with a simple strategy to implement.

An alternative solution to this would be to implement a complexity score system. Every part of the query gets its own complexity score. Should the total score exceed a predetermined amount, the query is rejected. Although this is a popular solution, it’s also one that is subjective and difficult to implement in practice. 

In the below example, we’re using rate-limiting to prevent brute-force on the password reset token. The problem with GraphQL, in this case, is that a single query can contain multiple actions, allowing the attacker to send multiple requests, which may include a large number of guesses to try and retrieve data.

mutation BruteForce {
  p000000: passwordReset(input: {username:"Helena_Simonis", new_password: "CarveSystems!", reset_token:"000000"}) {
    username
  }
  p000001: passwordReset(input: {username:"Helena_Simonis", new_password: "CarveSystems!", reset_token:"000001"}) {
    username
  }
...
  p999999: passwordReset(input: {username:"Helena_Simonis", new_password: "CarveSystems!", reset_token:"999999"}) {
    username
  }
}

In this case, rate-limiting on individual mutation types may be a useful mitigation, along with using harder-to-guess password reset tokens.

5. Introspection Reveals Non-public Information

It can be beneficial  to add “hidden” API endpoints that provide functionality that is not accessible to the general public –  hidden administrative functionality, or an API endpoint for facilitating server to server communications, for example. Development tools such as GraphQL IDE use this to dynamically retrieve the schema. When it applies to a public API, introspection might improve the developer experience.

GraphQL Security Best Practices

You’d be surprised to see just how far using best practices with GraphQL could take you. The good thing is that there are plenty of ways to secure our queries in order to avoid malicious attempts. Things you should focus on when securing your apps include:

Query Timeouts

Query timeouts are a simple, yet incredibly effective way of limiting the operational window for the attacker. By using query timeouts, you’re basically setting a fixed limit on how long a single query can be executed. 

Limiting Query Depth 

Perhaps the biggest issue that GraphQL security has are unbounded queries. This means that an attacker is able to send huge queries to your server, potentially resulting in a denial of service. 

However, by limiting query depth to a reasonable stage, you’re effectively shutting down this possibility as the attacker won’t have the ability to spam your server with useless requests.

GraphQL Security with Bright

Bright offers the most advanced API testing automation. This allows you to test your GraphQL queries for any potential vulnerabilities. One of the biggest benefits of Bright is that you can deploy full depth parsing, meaning that you can parse varying interactive definitions (in this case, a good example would be an XML object inside a GraphQL query).

Bright offers simple updates on any potential vulnerabilities that your web application might have, and you can code freely knowing your apps are well guarded.

What is a Security Champion and Why You Need One

While a security culture for a successful DevOps and AppSec programme is important, to succeed, security needs to be top of mind for everyone across your pipeline. 

Your developers, QA and security teams must have a close working partnership to break down silos and improve security knowledge.

One effective way to achieve this is to create security champions to act as the voice of security across your teams.

In this article:

What is a security champion?

With the ratio of developers to security professionals being ~50:1, your security team is spread thin – they cannot make up for the lack of security experience of your developers, nor provide the full security coverage developers need.

A security champion can help bridge this gap, by evangelizing, managing and enforcing the security posture with your development team(s) acting as an extended member of the security team.

What are the benefits of a security champion program?

A security champion can help an organization compensate for a lack in security skills among existing teams. This can be achieved by providing a member of the development team with the knowledge and authority to assist with security tasks. The security champion can become a force multiplier who can address questions, ensure security awareness, and help enforce security best practices across the development organization. 

Because a security champion understands the terminology used by developers working on software projects, they can relay security concerns in a manner that the development team will understand and be able to implement. Also, by performing code reviews, they can improve code quality early in the development lifecycle, reducing security efforts later on.

Responsibilities of a security champion

Being in the Know – knowledge is key and your security champion will benefit from ongoing training to keep up-to-date with the latest practices, methodologies and tooling to share this knowledge.

Raising Awareness – disseminating security best practices, raising and maintaining continual security awareness around issues / threats with the development organization and answering security related questions

Being Part of Security – performing scans for security issues and being the go between to escalate issues for review by the security team, helping with QA and testing. This will also enable them to be involved in risk and threat assessments, as well as architectural and tooling reviews to identify opportunities to remediate security issues early. 

Getting and Maintaining Buy-In – Intrinsic to the project and speaking the developers’ language, your security champion can get their colleagues’ buy-in by communicating security issues in a way they understand, to produce secure products early in the SDLC. This increases the effectiveness and efficiency of your AppSec program while strengthening relationships across multifunctional teams, while minimizing the security testing bottlenecks further downstream, so your security team can focus on other critical tasks.

Collaboration – Connecting and partnering with other security champions and players, attending weekly meetings to share ideas and tips whilst assisting in making security decisions

Review and escalation – Evaluating code for security issues and taking responsibility for raising issues that require the involvement of the security team.

Inspiration – Creating team workshops, sharing best practices, or simply relaying news from the security field. Champions can get teams involved with security by starting challenges, hackathons, and competitions. These and other initiatives can create interest, share knowledge, and also have practical value by encouraging teams to identify and fix vulnerabilities. 

Do you already have a security champion in the making?

It is likely that the perfect candidate for a security champion is already part of your team. They are a colleague who is involved with and familiar with your product(s) while showing an interest in security issues. They could be a developer, QA, architect, or DevOps colleague.

They don’t need to be senior, but management needs to see the value in having a security champion to provide them the right support. Extra work will be required so having a willing ‘volunteer’ with a keen interest in the role is important to ensure they are effective and stay engaged.

Get Your Security Champion Programme Started today!

Here are some key aspects to consider to help build your security champion programme in your organisation. See the OWASP Playbook for a complete framework that can help you develop security champions.

Management buy-in

This is the most critical aspect, as without it, you are likely to fail. Management, along with security and engineering managers will need to invest time, money and resources to ensure security champions are effective, but the benefits will soon outweigh the investment

Nominate your security champions

Ideally you should nominate, rather than appoint, a security champion. This will ensure that they are attentive and keen to give time to the position. Because the aim is to nominate champions in a voluntary way, you should articulate the advantages that come with being a champion. People are not likely to want to participate and take on extra work if they don’t get something in return. 

If management approves, you may give champions the opportunity to attend security conferences. There is also the advantage of self-development – adopting the role of a security champion can help advance the career of an individual and increase their value within the organization. 

Establish communication channels 

Once you have nominated the champions, next you will need to establish communication channels they can use. These channels should make use of the technologies your organization already uses, such as Skype, Slack, or Stride channels. You may even use a traditional email mailing list – whatever is most likely to attract the attention and engagement of teams. 

Build a sound knowledge base 

Champions should be responsible for creating an internal base of knowledge, which will be the main focal point for security-related information. A knowledge base may provide access to the organization’s security approach, policies and procedures, information about vulnerabilities and risks relevant to the organization, and best practices relating to secure coding.

Define and track success

Security needs to be a fundamental KPI and the efficacy of the Security Champion, and the efficiencies they bring to the security team and DevOps pipeline, all need to be tracked to evaluate the ROI of the program

Training and education

A security champion can’t be expected to know everything…at least not initially. Build on their willingness to be part of the solution, by leveraging your internal security experts to define issues they want the security champion to manage. Provide the knowledge they will need to start reviewing products for issues early and pass on best practices to the development team, freeing up your security team

The right tooling

Consolidating your tooling, so your developers, security champion, QA and security team are able to use, understand the output of and effectively collaborate to remediate issues early is important. You need security tools that are developer friendly and dead accurate while providing comprehensive security compliance on every build to enable you to shift security testing left, coordinated by your security champion.

Bright is an automated security testing and vulnerability scanning tool that can promote security awareness among developers:

  • Built for Developers – empowers developers to detect and fix vulnerabilities on every build. It can initiative a scan based on crawling, HAR files generated per build/commit, OpenAPI (Swagger) files or Postman Collections for testing APIs.
  • Smart scanning – uses sophisticated algorithms to carry out the right tests against the target, removing complexity for developers, and running scans fast to ensure they do not hurt developer productivity.
  • Supports modern architecture – microservices, single page applications, SOAP, REST, and GraphQL APIs.
  • No false positives – developers don’t have the time and expertise to weed out false positives from the results of security tools. Bright performs automated validation of every vulnerability detected, ensuring that every alert represents a real security threat.
  • Integrates with CI/CD – provides a convenient CLI for developers, and integrates with tools like CircleCI, Jenkins, Jira, GitLab, Github, and Azure DevOps.

Learn more about Bright and get started free!

WebSocket Security: Top 8 Vulnerabilities and How to Solve Them

What is a WebSocket?

WebSockets are becoming increasingly popular, because they greatly simplify the communication between a client and a server. 

The WebSocket protocol uses OSI model application layer (Layer 7) to allow a client and server to perform bidirectional (full duplix) communication. This makes it possible to create dynamic, real-time web applications such as instant messaging and photo sharing apps.

This is part of a series of articles about Web Application Security.

WebSockets overcome some of the traditional restrictions of communications between browsers and servers:

  • Client requests/server responds – n the past servers had permanent listeners. The client (the one using the browser) didn’t have a fixed listener for long term connections. This made each communication centered around the client demanding and the server responding.
  • Communication dependent on client – he server can only push a resource to a client when the client requests it.
  • Continual checking – clients are constantly forced to refresh results from the server. This is why libraries focus on making all asynchronous calls optimized. They also have to identify their response. The most common solution to this problem is the use of callback functions.

WebSocket overcomes the latency inherent in unidirectional communication from the client to the browser. In the http[s]:// protocol, the client initiates a request and waits for a response. This is called a transaction. Each request/response starts a different transaction, and each transaction has an overhead. In the ws[s]:// protocol, WebSockets initiate long-lived transactions with multiple requests and responses. The server can also send data without prior request, making communication much more efficient.

This is part of a series of articles about Web Application Security.

In this article:

Most Common WebSocket Vulnerabilities

Let’s go over the most common WebSocket vulnerabilities and see how they’re exploited.

DoS Attacks

WebSockets let an unlimited number of connections reach the server. This lets an attacker flood the server with a DOS attack. This greatly strains the server and exhausts the resources on that server. Then the website slows down greatly.

No Authentication During the Handshake Process

The problem here is that the WebSocket protocol doesn’t let a server authenticate the client during the handshake process. Only the normal mechanisms for HTTP connections are available. That includes HTTP and TLS authentication and cookies. The upgraded handshake still occurs from HTTP to WebSocket. But, the HTTP sends the authentication information directly to WS. This can be exploited and we call this attack Cross-Site WebSocket Hijacking.

Unencrypted TCP Channels

Another issue with WebSockets is that they can be used over an unencrypted TCP channel. This leads to all kinds of issues that are listed in the OWASP Top 10 A6-Sensitive Data Exposure.

Vulnerability to Input Data Attacks

What happens when a component is vulnerable to malicious input data attacks? A technique like Cross-Site Scripting. It’s a common yet very dangerous attack that can greatly damage your website. 

Learn more in our detailed blog post about  Cross-Site Scripting.

Data Masking

Data masking isn’t inherently bad. WebSockets protocols use it to stop things like proxy cache poisoning. However, there’s a problem. Masking prevents security tools from actions like identifying a pattern in the traffic. 

Software like DLP (Data Loss Prevention) isn’t even aware of the existence of WebSockets. This makes them unable to perform data analysis on WebSocket traffic. This also prevents these software programs from being able to identify things like malicious JavaScript and data leakage.

Learn more in our detailed guide to mobile security.

WhenSocket Authorization/Authentication

A big flaw of WebSocket protocols is that they don’t handle authorization/authentication. Any application-level protocols need to handle this separately. Especially in cases when sensitive data gets transferred.

Tunneling

WebSockets let anyone tunnel an arbitrary TCP service. An example is tunneling a database connection directly through and reaching the browser. In the case of a Cross-Site Scripting attack it evolves and ends up becoming a complete security breach.

Sniffing Attacks

Data transfer over the WebSocket protocol is done in plain text, similar to HTTP. Therefore, this data is vulnerable to man-in-the-middle attacks. To prevent information leakage, use the WebSocket Secure (wss://) protocol. Like HTTPS, wss doesn’t mean your web application is secure, but ensures that data transmission is encrypted using Transport Layer Security (TLS).

How to Improve WebSocket Security

The vulnerabilities have been covered. We now present some prevention guidelines to help protect your WebSockets.

WSS

You shouldn’t use ws://, it’s not a secure transport. Instead, use wss://, which is a much safer protocol. WSS is secure, so it prevents things like man-in-the-middle attacks. A secure transport prevents many attacks from the start.

In conclusion, WebSockets aren’t your standard socket implementation. WebSockets are versatile, the established connection is always open, and messages can be sent and received continuously. However, DOS attacks, no authentication/authorization, vulnerability to data input attacks are all vulnerabilities that are exploitable. That’s why it’s important to use client input and server data validation, ticket-based authentication, and WSS.

Related content: Read our guide to security testing tools.

Client Input Validation

Arbitrary data. WebSocket connections can easily be established outside a browser. You will deal with arbitrary data no matter what. This data needs validation as well as any other that comes from a client before it gets processed. Why? Because injection attacks like OS, SQL, Blind SQL are possible via WebSockets. 

Server Data Validation

You don’t have to worry about only client data validation. Data that the server returns can also carry problems. Messages received on the client-side should always be processed as data. Assigning these messages directly to DOM or evaluating as code isn’t recommended. In the case of JSON responses, use JSON.parse() in combination with exception handling and if needed custom sanitization methods to parse the data safely.

Ticket-Based Authentication

As mentioned before, WebSocket protocols don’t handle authorization or authentication. How does one increase WebSocket security then? By optimizing and securing your connection. WebSockets pass through all standard HTTP headers that are used for authentication. Then why don’t we use the authentication mechanisms we use for our web views for WebSocket connections?

We can’t customize WebSocket headers from JavaScript. Unfortunately, everyone is limited to the “implicit” auth (cookies) that the browser sends. That’s not all, as the servers that handle WebSockets are usually separate from the ones that handle standard HTTP requests. This greatly hinders shared authorization headers. Thankfully there’s a pattern that helps with the WebSocket authentication problem. A ticket-based authentication system that works like this:

  1. In the case where the client-side code tries to open a WebSocket, the HTTP server gets contacted to allow the client-side code to obtain an (authorization) ticket
  2. Now the ticket gets generated, and it contains a user/account ID, the IP of the one requesting the ticket, a timestamp, and other internal record keeping
  3. The ticket gets stored on the server/database and gets returned to the client
  4. A client can now open the WebSocket connection and send this ticket together with the initial handshake
  5. Now the server has the option of comparing the ticket, evaluating the source IP, verify the safety of the ticket (if it is re-used) etc.
  6. When everything checks out, the WebSocket connection gets verified

Preventing Tunneling

Tunneling arbitrary TCP services via a WebSocket is easy, as we’ve mentioned already. This is a risk that needs to be prevented. The best way to avoid this issue? Just avoid tunneling whenever possible. Using other secured and verified protocols on top of WebSockets is highly recommended. 

Learn more in our detailed guide to web application scanning.

Rate Limiting

Rate limiting is an important way to prevent abuse of your web application or web service. It can protect against bad bots, scraping attacks, and small-scale denial of service (DoS) attacks. In some cases, a malfunctioning client can result in an accidental DoS attack.  

To implement rate limiting, assign a “bucket” to every user, and determine the following parameters:

  • How much websocket traffic is sent by the user per second
  • How much traffic the server can safely process per second
  • Traffic from the same user that exceeds the server’s capacity should be placed in a queue
  • The server should allow a certain timeout period, to allow for bursty traffic by the client followed by a quiet period, in which the server can process the queue
  • After the timeout, messages in the queue should be discarded

Related content: Read our guide to security testing tools.

Origin Header

The WebSocket standard lets you define an Origin header field. This is similar to the AJAX X-Requested-With header. It determines which host a WebSocket connection is coming from. Otherwise the client can communicate with any host over the WebSocket protocol. 

The Origin header is advisory, and can be faked by an attacker. But still, this would require an attacker to change the Origin header on the client browser, which is blocked by modern browsers in most circumstances. So, while it is a good idea to set the Origin field, you should not rely on it for authentication – always combine it with cookies or another authentication mechanism.

SolarWinds Vulnerability: How to Protect Your Organization

Table of Content

  1. SolarWinds Orion Vulnerabilities
  2. Is Your Data at Risk from the SolarWinds Hack?
  3. How to Protect Your Organization
  4. Remediating Affected Systems
  5. Checking your Supply Chain Web and API Application Security

The SolarWinds attack was one of the largest nation-state supply chain attacks we have seen to date. The attack originated from SolarWinds’ Orion network management software and was likely carried out by nation-state adversaries.

The fallout of this hack affected thousands of global organizations, including U.S. federal agencies like the Treasury Department and the Pentagon, and a majority of the Fortune 500. 

SolarWinds Orion Vulnerabilities

According to the official SolarWinds Security advisory, SolarWinds Orion was originally attacked via two vulnerabilities, known as SUNBURST and SUPERNOVA.

What is SUNBURST?

SUNBURST is the main vulnerability used to carry out the SolarWinds supply chain attack. SUNBURST is a vulnerability inserted into the SolarWinds Orion Platform, versions 2019.4 HF 5, 2020.2 unpatched, and 2020.2 HF 1. The vulnerability, when active, allows attackers to compromise the server running the Orion Platform. 

Additional components of the SUNBURST attack mechanism are:

  • SUNSPOT – a sophisticated specially-designed malware that inserts SUNBURST malicious code into Orion during the build process. 
  • TEARDROP and RAINDROP – malware loaders that are used as secondary tools by the SUNBURST backdoor.

What is SUPERNOVA?

SUPERNOVA is malware that was not delivered via the SolarWinds build process as a supply chain attack, but rather, distributed via a vulnerability in the Orion product itself. It has two components:

  • A malicious webshell .dll file named “app_web_logoimagehandler.ashx.b6031896.dll” – designed by the attackers to operate as part of SolarWinds Orion and appear to be part of the product. 
  • An exploited vulnerability in the Orion Platform that enables deployment of the malicious code. Recent updates of the Orion Platform have resolved this vulnerability, so the malware can no longer be deployed.

Additional SolarWinds Vulnerabilities Discovered After the Attack

Cybersecurity researchers at Trustwave have discovered additional vulnerabilities in the Orion Platform, in the months after the initial SolarWinds attack. There is no evidence these vulnerabilities have been exploited by attackers. They are:

  • CVE-2021-25275 – a vulnerability in the interface between Orion and Microsoft Message Queue (MSMQ), which can allow attackers to access secured credentials and gain control over a Windows server running Orion.
  • CVE-2021-25274 – could allow an unauthenticated user to inject malicious code and gain complete control to the Windows operating system on an Orion server.
  • CVE-2021-25276 – vulnerability in the Serv-U FTP utility, allowing anyone who logs in either locally or via RDP to create an admin account and gain full access to the server and attached networks.

Is Your Data at Risk from the SolarWinds Hack?

Thankfully, not all SolarWinds customers are vulnerable to this hack. Only users of the Orion software platform are affected, and specifically only those that loaded the March 2020 update – SolarWinds has confirmed that 18,000 customers have done this.

Specifically, the affected versions are SolarWinds Orion Platform versions 2019.4 HF5, 2020.2 with no hotfix installed, and 2020.2 HF 1. 

Please note that:

  • Not all organizations affected by the vulnerability were hacked. The attackers did not hack all organizations that had the vulnerability, apparently starting with the most valuable targets. 
  • Some organizations were affected without having the vulnerable SolarWinds version, or even if they did not use SolarWinds Orion at all. The same threat actors compromised other software from Microsoft (the Zerologon vulnerability) and VMware (the SUNBURST trojan was discovered in VMware Access and VMware Identity Manager).

How to Protect Your Organization

There are some immediate steps you can take to protect your organization if you’ve been compromised by the SolarWinds attack. These guidelines were provided by the Center for Internet Security (CIS):

  • Test your systems and immediately apply the relevant SolarWinds updates to your vulnerable systems. For example, update 2019.4 HF 5 to version 6, update earlier versions of 2020.2 to 2020.2.1 HF 2, or apply the CVE-2020-10148 security patch (provided by SolarWinds) if you want to continue running 2018.2 HF 6, 2018.4 HF 3 or 2019.2 HF3.
  • Monitor Microsoft 365 Cloud, because FireEye researchers have discovered that SolarWinds attackers can move laterally from local networks into the Microsoft 365 cloud. Learn more in the FireEye white paper. You can check your Microsoft 365 environment for signs of attack using the Azure AD Investigator.

In addition, pay special attention to user behavior that can increase security risk:

  • Run any software as a regular user without administrative privileges, to minimize the impact of attack.
  • Raise awareness so users don’t visit untrusted sites or click on links from an unknown or untrusted source.
  • Educate users on the risks related to hypertext links or email attachments provided by an untrusted source.
  • Apply a least privilege strategy across your systems and services.

Remediating Affected Systems

CIS recommends the following additional steps your organization should take to remediate systems affected by the SolarWinds attack.

Take the following steps to identify if your environment has malicious traffic that could be related to SolarWinds malware:

  1. Examine network traffic since March 2020 and look for any activity with the domain avsvmcloud.com.
  2. If you find any such traffic, look for unexplained external communications from SolarWinds systems.
    1. If there is no additional abnormal traffic, follow the steps for SolarWinds products not affected by the attack below.
    2. If there is additional abnormal traffic, follow the steps for SolarWinds products with malicious traffic below.
  3. If external communications to avsvmcloud.com ceased on 14 December 2020, and this was not the result of actions by security staff, this means the environment is compromised – follow the steps for SolarWinds products with malicious traffic.
  4. In addition, conduct an audit of all systems looking for default credentials and new accounts created; perform an organizational-wide password/credential reset.

Steps for SolarWinds Products Not Affected by the Attack

If your organization is running SolarWinds products that were not affected by the attack, or products that were affected, but you did not find malicious traffic, follow these steps:

  1. Download and install the latest software updates from the SolarWinds portal, and ensure servers running SolarWinds have other security updates and patches.
  2. Apply CIS Benchmarks hardening recommendations for all SolarWinds systems. CIS-CAT Pro is a free tool that can provide hardening recommendations for SolarWinds.
  3. Monitor the environment for malicious communication or suspicious activities.

Steps for SolarWinds Products with Malicious Network Traffic

If you have a product affected by the malicious SolarWinds code and you have seen network traffic both to the malicious domain avsvmcloud.com and an additional command and control destination, follow these steps:

  1. Perform forensic investigation of system memory and host operating systems on any system hosting infected Orion versions
  2. Analyze network traffic for additional malicious activity
  3. Examine SolarWinds host systems for new users, new service accounts, new processes running, or other signs of persistence. Remove all accounts and persistence mechanisms created by attackers.
  4. After forensic investigation, power down or disconnect all infected SolarWinds Orion instances from the network
  5. Add firewall rules blocking traffic from hosts outside of the environment where Orion software is installed

Additional Recommendations

In addition to the above steps, CISA recommends:

  1. Reimaging and rebuild affected systems
  2. Restoring firmware of all network infrastructure managed by SolarWinds to previous known good versions
  3. Resetting credentials across the enterprise for user accounts, SNMP, SSH keys, and certificates, and forcing multi-factor authentication (MFA)
  4. Applying hardened configuration for all affected systems
  5. Following the additional guidelines in the CIA document: Uncovering and Remediating Malicious Activity.

Checking your Supply Chain Web and API Application Security

Currently, there is no specific evidence that indicates the SolarWinds hack involved exploiting a specific web application vulnerability, however there is a possibility especially with exposed APIs. 

The hack involved gaining upload access to a file server which can also be carried out via a vulnerable admin panel. Weak points in your cybersecurity can be exploited to other connected applications and so it is imperative to check not only your own products, but also that of any and all third-party products. 

Bright is a dynamic application security testing (DAST) solution that should be part of your toolset to detect and remediate vulnerabilities across your applications and APIs to mitigate this risk. Contact us now to learn more and request a demo

SQL Injection in PHP Web Applications

What is PHP SQL Injection?

When an attacker exploits a PHP application via an SQL Injection, they can gain access to the application’s database and make the application execute unauthorized injected SQL commands to control the behavior of the application. 

In this article you will learn:

How does PHP SQL Injection work?

To exploit an SQL injection vulnerability in a PHP application, an attacker can use several types of SQL injections. For example, they could enter data in the form fields of the application, which is then passed to the database for processing. If the application can’t properly validate the form input data, and accepts the input without sanitizing it, the attacker can inject SQL statements via these form fields and delete, copy, or modify the contents of the database.

In this blog post we will focus on a few select SQL injection types. More are covered in depth in this blog post – [link].

Common variants of SQL injection include:

  • SQL injection based on user input
  • SQL injection based on cookies
  • SQL injection based on HTTP headers
  • Second-order SQL injection

A successful SQL injection attack on a PHP application can enable an attacker to:

  • Steal credentials
  • Access databases
  • Alter data
  • Access network(s)  

Code Examples of SQL Injection in PHP

Let’s have a look at these examples of SQL Injection:

Making Superusers (PostgreSQL)

$offset = $argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);
?>

The above example is used to split a result set into pages. When someone clicks on the ‘next’ or ‘prev’ link, the $offset is encoded into the URL. While the script is expecting a decimal number, an attacker exploit this by appending a urlencode()’d form of the following code to the URL:

0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passed)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--

When executed, this script would provide the attacker a superuser access. The 0; in the code example above is there to supply a valid offset to the original query in order to terminate it.

Listing Passwords

An easy way to gain passwords is to bypass your search result pages. An attacker only needs to check if there are any submitted variables that are not properly handled, used in SQL statements.

Customisation of WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements can be achieved by setting filters commonly in a prior form.

Databases that support the UNION construct are particularly at risk, where an attacker could attach an entire query to the original in order to list passwords from an arbitrary table. As a result, it is highly recommended that encrypted password fields are used.

$query  = "SELECT id, name, inserted, size FROM products
           WHERE size = '$size'";
$result = odbc_exec($conn, $query);
?>

The attacker can combine the static part of the query with another SELECT statement that will reveal all passwords:

'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

An attractive target for an SQL Injection attack can also be the SQL UPDATE’s. As with SELECT, an attacker can chop and append a new query to the UPDATE statement, however the attacker might change the SET clause. To successfully manipulate the query, the attacker would require some schema information, which they could get by examining the form variable names, or simply via brute force.

Attacking the database host operating system (MSSQL Server)

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
?>

If an attacker submits the value a%’ exec master..xp_cmdshell ‘net user test testpass /ADD’ — to $prod, then the $query will be:

$query  = "SELECT * FROM products
           WHERE id LIKE '%a%'
           exec master..xp_cmdshell 'net user test testpass /ADD' --%'";
$result = mssql_query($query);
?>

The SQL statements in the batch will be executed by the MSSQL server, which includes a command to add a new user to the local accounts database. Should the application be running as sa and the MSSQLSERVER service is running with adequate privileges, the attacker would gain an account he can use to access this machine.

PHP SQL Injection Prevention

Ensure you never trust any kind of input, especially input coming from the client side. To prevent SQL Injections in your PHP applications:

  1. Always use customized users with very limited privileges. 
  2. Use prepared statements with bounds variables. Prepared statements are precompiled SQL commands, which can be used with a specific database access library (such as mysqli) or with the more generic library PDO
  3. Check if the input has the expected data type. PHP has a broadrange of input validation functions
  4. If the application waits for numerical input, ensure you verify data with ctype_digit(). Alternatively, you cansilently change its type using settype(), or use its numeric representation by sprintf().
  5. If binding variables is not supported by the database layer, each non-numeric, user supplied value can be quoted with the database-specific string escape function (e.g. mysql_real_escape_string(), sqlite_escape_string(), etc.) – this removes all special characters in a string so they lose their meaning when used by the database. The whole string now gets passed as a harmless string to the database, instead of being able to participate in query manipulation
  6. Using stored procedures and previously defined cursors to abstract data access ensures users cannot  directly access tables or views

PHP SQL Injection Prevention with Bright

Bright’s cloud-based application security testing scanner Bright tests for SQL Injection, delivering developer friendly remediation guidelines to fix issues.

By shifting DAST scans left and integrating them into the SDLC, developers can detect vulnerabilities early, and remediate them before they hit production. 

Start integrating security testing automation into your development pipelines today with Bright’s FREE scanning account. Sign up here: https://app.brightsec.com/signup

Simply follow the 3-step wizard to start scanning your applications and APIs 

If you want to learn more about different types of SQL Injections this is a must read blog post too!

10 Security Acronyms Every Developer Must Know

The days where security testing is carried out in a penetration test by your security team or a third party firm, are increasingly becoming a thing of the past. Today, developers are leading the charge, as we “shift Left” with ”AppSec testing for developers”.

With DevSecOps and CI/CD, security testing now sits at multiple stages of the development pipeline, especially with developer first application security tools, with conversations about security being held regularly. 

As a developer though, what the hell are all these abbreviations and cybersecurity acronyms that security folk love to use and expect you to know?

As our application security testing tool is widely and increasingly used by developers (you can sign up for a free account here), our ongoing support includes hands-on workshops, where it became very apparent that keeping up with new technologies and their acronyms, as well as getting to grips with common security and vulnerability parler, is a tough ask for many developers.

So, to help you along the way, we’ve put together this cheatsheet of our top 10 most common cybersecurity acronyms – hope it helps, LMKWYT (let me know what you think)

  1. DAST – Dynamic Application Security Testing
  2. SCA – Software Composition Analysis
  3. SAST – Static Application Security Testing
  4. OWASP – Open Web Application Security Project
  5. XSS – Cross-Site Scripting 
  6. CSRF – Cross-Site Request Forgery
  7. SQLi – SQL Injection
  8. XXE – XML External Entity
  9. SSRF – Server Side Request Forgery
  10. Security Champion
  11. You’ve Got the Lingo….Now Start Automating your AppSec Testing

1. DAST – Dynamic Application Security Testing

Dynamic Application Security Testing (DAST), like Bright, is an Application Security Testing methodology in which the application is analysed and tested in operating mode, from the outside-in. As DAST tools don’t have access to the application and API source code, they detect vulnerabilities by performing actual attacks, similar to a real hacker.

Therefore, DAST solutions are a perfect fit if you want a better insight into how your web applications and APIs behave in production. While code scanning is an important part of the process of making your applications more secure, code scanners have many limitations. In addition to having a very high rate of false-positives and being limited to specific development languages and frameworks, some vulnerabilities only exist in the runtime environment, and if you don’t utilize a DAST tool, they will be missed. This is particularly relevant to microservice based architectures, which are becoming the norm.

DAST has typically been performed late in the testing phases, typically just before an application or service is deployed to a production. With a DAST like Bright’s, you can integrate this into the CI/CD, to enable developers to scan each build/commit early and detect and remediate security risks before they become serious. With Bright’s NO false positive reporting, developers can trust the output and start fixing issues!

2. SCA – Software Composition Analysis

SCA is a widely used form of developer application security testing, which identifies security vulnerabilities in your 3rd party dependencies. Run throughout the development pipeline, SCA builds the open source dependency trees for your applications and maps these against a database of known vulnerabilities. It then reports vulnerable open source that has been pulled into your application, to fix or patch accordingly.

SCA is very complimentary to DAST, where running a check on your dependencies and a dynamic test delivers considerable security testing coverage. Read here how you can complete your appsec testing automation with Bright and Snyk

3. SAST – Static Application Security Testing

Static Application Security Testing, or SAST, analyses the source code of an application to detect security vulnerabilities that may exist. SAST is an automated tool that looks for vulnerabilities in newly developed code, carried out during the coding stage. It does this by searching for coding patterns, insecure functions or objects that may lead to security vulnerabilities.

Although SAST can detect vulnerabilities early in the development process, you will notice that the word “may exist” or “may lead to” are used frequently when referring to SAST results. This is because SAST tools generate a large number of false positives. This requires a considerable amount of fine tuning to reduce these and to be more accurate.

What are the differences between SAST and DAST? Check-out our SAST vs. DAST blog.

4. OWASP Top 10

Everyone in security talks about The Open Web Application Security Project, or OWASP. It is a non-profit that works tirelessly to improve the security of software, led by a global community of open source software projects and chapters, to deliver educational and training conferences to guide you on how to produce more secure software.

The most prominent of OWAP’s projects is the ‘OWASP Top 10’. This lists the ten most common types of web application vulnerabilities, updated by the community. 

As a developer, you will regularly hear that the security tool you are using, such as your SAST or DAST, will cover this list. It is not comprehensive, but adopting and testing for this list will minimise your risks as an effective way of enhancing your security culture to produce secure product. Bright’s DAST has you covered here.

With APIs now more prevalent than ever, there is also the OWASP API Top 10. We ran a poll on how mature API security testing processes are in organisations and how often they test their APIs for security vulnerabilities – see the results here. With many security testing tools not able to test APIs, this was typically carried out manually or not at all. Ensuring your DAST tool can test APIs is very important, something NeuraLegoin has full support for, to cover SOAP, REST and GraphQL based API security testing.

For more info, see our post on The Rising Importance of API Security

5. XSS – Cross-Site Scripting

Cross-site scripting (XSS) is a common and dangerous type of attack that plagues almost all web applications, be it older or modern ones. Having been included in the OWASP Top 10 since its inception, it relies on developers using javascript to enhance the experience of end-users of their application, but when the javascript isn’t properly handled it leads to many possible issues, and one of them is XSS. This allows an attacker to execute malicious (usually) javascript code within a user’s browser, to steal sensitive information.

There are three main forms of XSS:

Reflected XSS: This is where the attacker makes the unsuspecting user send a request to the application that contains a payload and the application includes this in the response, causing it to be executed within the browser.

Stored: Where the attacker sends the payload to the application, which is stored in a value that is returned to the user (or users) resulting in the script / payload executing within their browser.

DOM-based XSS: Document Object Model-based Cross-site Scripting. This kind of XSS attack occurs when an application receives some client-side JavaScript that processes data from an unsafe, or untrusted source by writing the data to a potentially dangerous sink within the DOM instead of writing data in HTML which would present a regular XSS.

Learn more on in our article on “The Ultimate Beginners Guide to XSS Vulnerability” and how you can mitigate this common security issue

6. CSRF – Cross-Site Request Forgery

Cross-site Request Forgery (CSRF/XSRF), also known as Sea Surf or Session Riding is a web security vulnerability that tricks a web browser into executing an unwanted action. An  attacker can abuse the trust that a web application has for the victim’s browser. It allows an attacker to partly bypass the same-origin policy, which is meant to prevent different websites from interfering with each other.

When a website sends a data request to another website on behalf of a user along with the user’s session cookie, an attacker can launch a Cross-Site Request Forgery Attack, which abuses a trusting relationship between the victim’s browser and the webserver.

In some cases, an attacker can gain full control of the user’s account or worse, full control of all the application’s functionality and data, if the user has privileged access. The result can be data theft, unauthorized fund transfers, damaged client relationships, changed passwords and many more.

For detailed information, see our blog on Cross-Site Request Forgery and how to prevent CSRF Attacks.

7. SQLi – SQL Injection

Again, a staple on the OWASP Top 10, SQL injections represent a code injection technique used to attack applications and the data they hold. They usually occur when user input is required, for example, username, but the user gives an SQL statement instead.

To make an SQL injection attack, an attacker must first find vulnerable user inputs within the web page or application. When the attacker creates input content and sends it, malicious SQL commands are executed in the database. This way an attacker can gain complete control over the affected database.

There are many types of SQL injection attacks, whether they are user input triggered, or second-order SQL injection attacks. Common ones include:

  1. Union-based SQL Injection
  2. Error-Based SQL Injection
  3. Blind SQL Injection, which can include
    1. Boolean-based SQL Injection
    2. Time-based SQL Injection

For more detailed information on SQL injection, read our article on What Are SQL Injections and How Can They Be Prevented.

8. XXE – XML External Entity

What’s your XXE-cuse..? Another one of the OWASP Top 10, XML external entity (XXE) attacks are targeted against applications that parse XML input. They exploit weakly configured XML parsers, which process XML code that references external entities. XXE attacks can result in port scanning within the internal network, server-side request forgery (SSRF), data exfiltration, use of an organization’s servers to perform denial of service (DoS), and more.

For more info, delve into our blog on Understanding XXE: Attack Types and Prevention Methods

9. SSRF—Server Side Request Forgery

Server-Side Request Forgery (SSRF) attacks allow an attacker to make requests to any domains through a vulnerable server. Attackers achieve this by making the server connect back to itself, to an internal service or resource, or to its own cloud provider.

Attackers exploiting SSRF vulnerabilities can abuse any user inputs that accept URLs or file uploads, causing the server to connect to malformed URLs or external resources..not good!

There are several impacts of an SSRF server side attack that can be very damaging. To read more about these, the three main types of SSRF attacks that cause them and more importantly how to prevent them, read our blog post on 3 Types of SSRF Attacks and How to Prevent Them

10. Security Champion

OK, I concede, this one isn’t an abbreviation or a cybersecurity acronym, but it is a term that is quite rightly becoming more common. 

A security culture is very important for a successful DevOps and AppSec programme. To succeed, security needs to be top of mind for everyone across your pipeline. 

You as developers, QA and security teams must have a close working partnership to break down silos and improve security knowledge.

One effective way to achieve this is to create security champions to act as the voice of security across your teams.

Are you the perfect security champion that can help bridge this gap, by evangelizing, managing and enforcing the security posture with your development team(s) acting as an extended member of the security team?

Learn more about the responsibilities of a security champion and how to get your AppSec program kicked off here

You’ve Got the Lingo….Now Start Automating your AppSec Testing

Security has many technical terms and the ones above merely scratch the surface. Terms get thrown around which can make conversations confusing for developers. Additionally, application security tools compound the matter by being built for security experts and not developers, who are supposed to be using them now as part of their pipeline.
For a developer friendly, intuitive and accurate DAST scanner (NO false positives), try Bright for free by signing up here. We also provide developer focussed remediation guidelines for every finding detected. We speak your language so you can understand the issue and how to fix it. If the lingo gets too confusing (and for continued support by our security engineers), reach out on our Discord and we’ll soon have it translated for you!

SOAP Security: Top Vulnerabilities and How to Prevent Them

Learn what is the purpose of SOAP APIs, how they function, the main difference between REST and SOAP APIs, and what you can do to prevent the 7 most common SOAP API vulnerabilities.

In this article, you will learn:

What are SOAP APIs?

Simple Objects Access Protocol (SOAP) originated in 1998. It’s a web communication protocol that was designed for Microsoft. Nowadays SOAP is used to send data over both HTTP and HTTPS. However, SOAP isn’t limited to just those protocols. SOAP supports XML data format only. Preset standards like a set of encoding rules, messaging structure, and a convention for granting procedure requests and responses are standard practice for SOAP. 

SOAP data format

Unlike REST APIs, which support both JSON and XML, SOAP only supports XML both for requests and responses.

SOAP messages follow a standardized structure as well. Why are SOAP API requests and responses considered heavy? Because they appear as enveloped messages. Each message is made out of four elements that have unique functions for each one:

  • Envelope. The core element of all messages. It tags start and end messages, enveloping it in a sense.
  • Header. The header is an optimal element. It defines extra requirements like authentication.
  • Body. Contains the data needed to process the request or the appropriate response to the user.
  • Fault. Another optional element. Showcases data about errors that can appear throughout API requests and responses.

WS standard protocols

SOAP can also be extended with WS standard protocols. SOAP on its own already provides basic structural elements for messages. But it doesn’t direct the things that go into bodies and headers. Standard protocols augment the main protocol. They specify how you do particular things. WS- is the mark of these protocols and WS-Security is an example. 

WSDL documents

Another important SOAP API feature is the use of WSDL documents. WSDL documents are XML descriptions of a web service that SOAP APIs continually use and are the abbreviation of web-service-communication guidelines. They describe all processes that exposed applications can perform and they define endpoints. This includes data types that are used inside SOAP messages and any action that’s available through the web service. WSDL file services act like signed contracts between servers and clients.

What is SOAP Security?

SOAP security includes strategies and practices for preventing unauthorized access to SOAP messages and user information, tampering with SOAP APIs, and disruption of normal operations. Web Standard Security (WS Security) is a key element in ensuring SOAP security.

WS-Security is a set of principles/guidelines for standardizing SOAP messages using authentication and confidentiality processes. WSS-compliant security methods include digital signatures, XML encryption, and X.509 certificates. XML encryption prevents unauthorized users from reading data when accessing it.

While WS-Security provides enhanced security controls that are built into many SOAP APIs, organizations still need to set up these controls correctly, and ensure they cannot be bypassed. Critical SOAP security practices include input validation and sanitization, ensuring access control, and configuring authentication for all API endpoints, as well as for SAML-based single sign on (SSO) systems.

Are SOAP APIs More Secure than REST APIs?

The short answer is yes, SOAP APIs are more secure. To understand why, let’s explore the differences between these two types of APIs.

SOAP is a format used for message exchange. REST, on the other hand, is an architectural style. REST Sample Implementations use JSON over HTTP. SOAP Sample Implementations use XML over SOAP over HTTP. 

The REST architectural structure focuses on using HTTP Transport. SOAP focuses on restricting your message structure:

  • When it comes to the Data Exchange Format, SOAP is always SOAP-XML. This XML includes an envelope, a header, and a body.
  • REST always uses HTTP as a transport protocol. REST also uses HTTP features like Response headers, Response, Request methods, etc.

In regards to the Message Interchange Format, SOAP uses the SOAP XML format for Request and Response. REST doesn’t need a fixed format. It’s the same thing for Service Definitions. SOAP uses WSDL while REST doesn’t have a standard service definition language. When we’re talking about Transport, SOAP doesn’t restrict the transport protocol that’s used. Both HTTP and MQ are available. REST utilizes the HTTP Transport Protocol.

To summarize the differences:

  • SOAP services offer more comprehensive security measures, but REST services are much easier to implement. 
  • SOAP needs you to define your service via WSDL which comes with a lot of overhead. REST uses JSON that is much simpler to process and parse. 
  • REST doesn’t need a service definition to provide you with a web service

Top 7 SOAP API Vulnerabilities

We have now covered the basics. Now let’s talk about the 7 most common vulnerabilities and how to prevent them. 

The most common SOAP API vulnerabilities include:

SOAP Injections

SQL Injection

SQL injection is a web security vulnerability that could allow an attacker to tamper with database queries made by an application, injecting malicious code into queries. In the context of SOAP APIs, this involves injecting malicious SQL queries into API calls that use SQL syntax as part of their inputs. If your API is vulnerable to SQL injection, attackers can change the content or behavior of an application and in some cases compromise the entire server. 

XML Injection (XXE)

An XML or SOAP injection vulnerability occurs when user input is insecurely injected into a server-side XML document or SOAP message. Attackers can use XML metacharacters to change the structure of the generated XML. Depending on the XML capabilities enabled on the server side, it can interfere with your application’s logic, perform malicious actions and allow attackers to access sensitive data.

Command Injection

Command injection is an attack designed to execute arbitrary commands on the host operating system through a vulnerable application. In the context of SOAP APIs, any API that accepts user inputs and performs operating system commands, such as creating directories or accessing files in the file system, can be vulnerable to command injection.

A command injection attack can occur when an application passes insecure user-supplied data (forms, cookies, HTTP headers, etc.) to the SOAP API, which then passes the data to the system shell. In this type of attack, commands injected by the attacker are typically executed with the privileges of the server side of the SOAP API.

XAML Injections

XAML Injection attacks are made possible when untrusted input is involved. XAML is the markup language that’s used to directly represent object execution and instantiation. What does that entail? Any elements made in XAML are able to interact with system resources. What happens when a hacker gains control of the XamlReader method call input? They can execute malicious code. 

To protect against XAML injection, Microsoft enforces a rule in their IDEs, but this rule is not foolproof and can be disabled. The best prevention practice against this is manually validating and sanitizing the received input (learn more below).

SOAP Action Spoofing

Every HTTP request contains a field called a SOAP action, that is used to perform an action defined on the content. If communication is not encrypted, an attacker can place themselves between the client and the server, and perform a variety of bypass or man-in-the-middle (MitM) attacks that can modify the content of SOAP requests or responses.

SAML Vulnerabilities

Security Assertion Markup Language (SAML) originated way back in 2001. It is an XML-based open standard that provides authorization and authentication services. It lets identity providers pass authorization credentials to a service provider (for example, Salesforce SAML SSO). SAML is a common way to implement single sign on (SSO).

How is SAML vulnerable? Hackers found a way to modify SAML body content, but without invalidating the cryptographic signature. That’s the trick, you bypass the main authentication for any affected SAML service provider. A hacker that obtains access to one or compromises another account can then add comments to any attribute, obtaining an administrator account, for example.

Replay Attacks

The biggest problem with APIs is that they’re open to the public. In the sea of incoming requests, you need to know which are safe and which aren’t. Any web service that’s exposed over an HTTP request is vulnerable to attacks, such as a replay attack. 

What can a hacker do when he acquires the web service request together with valid input parameters? Attack manually over and over again or use automated techniques that repeatedly perform attacks. What kind of damage can these attacks cause? The server’s memory gets consumed. This tanks the server’s performance greatly. 

This attack is even more dangerous when used in conjunction with a malicious code injection in the input parameter. This gives the hacker sensitive data in the response. 

Cross-Site Scripting

Cross-site scripting (also known as XSS) is a web security vulnerability that could allow an attacker to compromise the interaction between a user and a vulnerable API. This allows attackers to bypass same-origin policies that seek to isolate scripts running on different websites from each other. 

Cross-site scripting vulnerabilities typically allow an attacker to impersonate a victim user, perform any actions the user is capable of, and gain access to user data. In the context of a SOAP API, a successful XSS attack would allow the attacker to perform user actions that result in API calls that are processed with the same privileges of the legitimate user.

Broken Access and Authorization

Access control enforces policies to prevent users from operating beyond their expected privileges. Common access control vulnerabilities in SOAP APIs include:

  • Ability to modify URLs, internal application state or HTML pages, to bypass access control checks.
  • Ability to change a primary key to another user’s record, allowing an attacker to view or edit another user’s account.
  • Ability to escalate privileges, such as logging in as a regular user and receiving administrative privileges. 
  • Ability to manipulate or tamper with JSON Web Token (JWT) metadata, cookies, or hidden fields that affect user authorization.
  • Incorrect Cross Origin Resource Sharing (CORS) configuration allowing unauthorized API access.
  • Ability to access authenticated content or operations as unauthenticated users, or force retrieval of privileged content or administrative operations as a standard user. 
  • Ability to access APIs without sufficient control for POST, PUT and DELETE operations.

Denial of Service (DoS)

Denial of service (DoS) attacks on APIs flood the API endpoint with traffic, in order to disrupt service and deny access to legitimate users. DoS attacks can significantly degrade the quality of service experienced by legitimate users of the API, cause significant delays in response, and eventually result in downtime.

DoS attacks are not limited to disruption of service. An attacker could inject and execute arbitrary code into an API during a DoS attack, to access sensitive information or execute commands on the server. 

SOAP Security Best Practices: Preventing SOAP Security Threats

What actions help protect SOAP APIs? Continue reading to find out!

Input Validation

Input parameters are the entry points that are exploited when a hacker wants to access layers of an application. Hackers can inject their malicious code into an API message. This malicious code then endangers your entire application.

Regex Protection is a good security technique. XML or JSON payload, URL Path, Header. These incoming requests need to be evaluated against regular expressions like EXECUTE, DELETE, and UPDATE. Rejecting any detected request that’s vulnerable is important.

Input HTTP Verb Validation deals with HTTP verbs/methods. These include DELETE, GET, POST, PUT, PATCH, HEAD, TRACE, and OPTIONS. All of them need restrictions. The approved verbs are allowed to function while the rest of the methods should only return a valid response code.

Then there’s Headers Validation. Many kinds of Security Headers exist. Content-Length, Accept, Content-Type. All of them need validation against API. It’s also important to always perform validation for obligatory headers. API-specific headers and Authorization for example. In the case of custom-defined headers, we need to make sure to validate proper formatting and value (X-Access-Token).

Validating incoming content-types is also important. How do you validate the Content-Type policy for PUT/POST/DELETE requests? IBy ensuring  the values for the request and the Content-Type header are the same. If the API detects that value does not match type, it returns a Bad Request Response (400).

Lastly, you need to handle Unsupported Resources. Addressing this is easy, by only permitting allowed resources and blocking unknown resources.

Access Control

All APIs need special configuration. Why? So that only approved IP domains or regions are allowed. Any requests that don’t meet the set conditions should get rejected.

There are many different approaches to managing resource access. The most common method is role-based access control. By default users have all permissions denied to ensure full level security. Afterwards administrators grant required privileges to appropriate roles. Several types of permission levels exist. They include:

  • Never (Regardless of role, this function restricts the user completely, making them unable to perform any operation)
  • Always (This access level allows the user to perform operations as they see fit no matter what role they have)
  • Grant (A user can perform an operation unless an entity-level permission disallowed it)
  • Entity (Users that obtained access via entity-level permissions can perform the operation)

Implement Authentication for SOAP APIs

Each security layer in the organization requires comprehensive authentication. Without it, the API is vulnerable, making the data vulnerable as well. For example, hackers that have a valid mobile number are able to steal sensitive data. That’s why we use OAuth/OpenID. They offer complex and potent authentication and authorization mechanisms. It’s recommended to authenticate the end-user and the application as well. 

Usage of 2FA, OAuth, and Nonce tokens improve access control and can also help prevent replay attacks. A Nonce token combines a unique GUID and a timestamp. One token is valid for one request. That way any request is unique, making it free of vulnerabilities. Use signed URLs for providing access to media type resources.

Enable SAML Authentication

If you use SAML for SSO, it is essential to use SAML authentication. The SAML authentication model has two parts:

  • An identity provider  – produces all SAML assertions
  • A service provider (SP) – a consumer of assertions. This could be, for example, G Suite, Office 365, or other SAML-supported cloud applications.

Most SAML assertions are signed with a PKI signature. This signature checks if the assertion is valid or not.

Any cloud application that’s being accessed needs an authentication service – one that acts as an identity provider (IdP) – to collect user credentials and return a response to the accessed cloud application. This response is what we call a SAML assertion. This assertion can contain a reject or accept response only. The user successfully logs into the app if the SAML assertion is confirmed to be valid.

Ensure URLs Never Contain API Keys

Any API needs standard authentication and authorization mechanisms. Yet there are cases where the API key gets sent as a part of URI (Uniform Resource identifier). This makes the key compromised as it’s shown as a plain text in your browser. Sending API keys via the GET method is also a problem. Why? Because they can be stored either in the system logs as cache or in the browser history. This makes them accessible to other users. You never want your API  key to be part of URI and should prefer sending it as part of headers instead of sending it via GET.

Automating SOAP Security with Bright

In summary, SOAP APIs have many advantages. It’s a more secure protocol than REST, it supports automation, and it’s standardized to an incredible degree. Yet, the inherent use of SOAP APIs also brings more overhead to SecOps teams. We’ve listed common vulnerabilities and what you can do to prevent them. However, you can automatically apply SOAP security best practices with an automated security testing solution.

Most legacy Dynamic Application Security Testing (DAST) tools support API security testing. Those that have attempted to make the leap are unable to support SOAP API security testing, resulting in a continued reliance on expensive manual testing, carried out late in the process and often after the API is in production.

With Bright, you can test your SOAP, REST and indeed GraphQL APIs, either as a standalone scanner or integrated seamlessly across your DevOps and CI/CD pipelines. You can now start to detect, prioritise and fix issues early, before they hit production.

By simply uploading the OpenAPI (Swagger) or Postman collections into Bright, you can achieve a comprehensive security scan that will cover the OWASP API Top 10 vulnerabilities. This can be achieved for a full scan against the complate target or for scope defined incremental testing on each new build, feature or merge.

Additionally, Bright has unparalleled support for a range of different authentication mechanisms, including SAML, OIDC, OAuth and more, ensuring you have maximum coverage.

API security testing tools are now a thing of the present and no longer needs to be an afterthought and another human bottleneck in your processes – start automating your security testing.

Get a free account for Bright and start testing today!

What Is a CSRF Token and How Does It Work?

A CSRF (Cross-Site Request Forgery) token is a unique security measure designed to protect web applications from unauthorized or malicious requests. It’s a specific type of token, often referred to as a synchronizer token or challenge token, that verifies the authenticity of requests made by a user. Each CSRF token is unique to an individual user session and is embedded in web forms or requests. When a user submits a form, the server checks the CSRF token to ensure it matches the one it issued, confirming the request’s legitimacy. This token is crucial for security, as it prevents attackers from performing actions on behalf of unsuspecting users. To maximize security, a CSRF token should be a large, unpredictable value, making it extremely difficult for attackers to guess or replicate

In this article you are going to learn:

What is a CSRF token?

A CSRF Token is a secret, unique and unpredictable value a server-side application generates in order to protect CSRF vulnerable resources. 

The tokens are generated and submitted by the server-side application in a subsequent HTTP request made by the client.

After the request is made, the server side application compares the two tokens found in the user session and in the request. If the token is missing or does not match the value within the user session, the request is rejected, the user session terminated and the event logged as a potential CSRF attack.

How should CSRF tokens be generated?

Just like session tokens in general, CSRF tokens should contain significant entropy and be strongly unpredictable.

You can achieve this by using a cryptographic strength pseudo-random number generator (PRNG), seeded with the timestamp when it was created and a static secret.

For further security, you can generate individual tokens by chaining their outputs with user-specific entropy and take a strong hash of the whole structure.

This presents an additional obstacle to a malicious user who attempts to analyze the tokens based on a sample that is issued to him.

In short, here are the principles you should follow when generating and verifying your token:

  • Use a well-established random number generator with enough entropy
  • Make sure tokens can’t be reused. Expire them after a short amount of time
  • Verify the received token is the same as the set token in a safe way, for example, compare hashes
  • Do not send CSRF tokens in HTTP GET requests. This will make sure they are not directly available in the URL and they don’t leak in the Referer header with other referrer information

For example, a CSRF token in PHP can be generated as follows:

$_SESSION[‘token’] = bin2hex(random_bytes(24));

And verify the token as follows:

if (hash_equals($_SESSION[‘token’], $_POST[‘token’])) {
// Action if the token is valid
} else {
// Action if the token is invalid
}

If you prefer a more secure approach, generate separate tokens for each form. Make sure you don’t expose the token directly to the user’s browser. Hash the token using the filename of the form Hash the token with the filename of the form. Here is one example how to do it in PHP:

hash_hmac(‘sha256’, ‘post.php’, $_SESSION[‘internal_token’])

When you verify, compare the hashes. If both the token and the form are valid, the hashes will match.

How should CSRF tokens be transmitted?

CSRF tokens are secrets and should be handled as such in a secure manner throughout their lifecycle.

Try transmitting the token to the client within a hidden HTML form field, using the POST method. This way the token will be included as a request parameter when the form is submitted.

Place the field containing the CSRF token as early as possible within the HTML file. Place the field that contains the token before any non-hidden fields and before any places where user-controllable data is embedded. This way you will mitigate the risk against various techniquest where an attacker can use crafted data to manipulate the HTML document and capture part of its content.

For example:



[...]

You can place the CSRF token into the URL query string, but this approach is less safe, as the query string:

  • Is logged in various locations (client and server-side)
  • Can be transmitted to third parties within the HTTP Referer header
  • Can be displayed on-screen within the user’s browser

To further defend against an attacker who manages to predict or capture another user’s token, insert the CSRF token in the custom HTTP request header via JavaScript. This approach is particularly well suited for AJAX or API endpoints. Browsers usually don’t allow custom headers to be sent cross-domain. The downside of this approach is the limitation for the application to make CSRF-protected requests using XHR, and might be considered over-complicated for many situations.

Never transmit CSRF tokens within cookies.

CSRF protection in Angular

Angular is a popular frontend framework developed by Google. It’s an open-source project and offers its own set of user interface components that work across devices and platforms.

Angular packs the common security measure of reading the CSRF token called “CSRF-TOKEN”, and sets a custom header named “X-XSRF-TOKEN”. However, Angular is just a client-side framework, so to protect against CSRF, your web server must support this protective method as well.

CSRF protection in Django

Django is a free backend framework based on Python. Django focuses on reusability of code and pluggability of modules along with low coupling and rapid development principles.

Django offers middleware for protecting a web server against CSRF attacks. To protect your apps, the middleware must be activated in your project. Also, you have to include the csrf_token tag inside the form elements which point to any in-project URLs.

CSRF protection in Express

Express is a backend web framework for Node.js. It is fast, flexible and minimalistic. It’s free and open source.

Since Express is a minimalistic web framework, it doesn’t support any anti-CSRF measures by default. But it provides a pluggable middleware that helps your web server to protect itself against CSRF attacks.

The middleware is known as “csurf”, and it’s super easy to set up in your project. It offers some bootstrap options as well to configure its functionality.

CSRF protection in Laravel

Laravel is a free, open source web framework for PHP. Laravel supports a modular packaging system and offers numerous utilities to ease the development and maintenance of web applications.

Part of Laravel’s middleware group is middleware named VerifyCsrfToken. VerifyCsrfToken auto-verifies the token in incoming web requests and disregards CSRF-based requests. To use it, just include @csrf in your forms to include the token field.

CSRF protection in React

React is a front-end framework developed by Facebook. It’s free and open source and is mostly used for building mobile or single-page applications.

Unlike Angular, React doesn’t come with a default security measure against CSRF attacks. 

In order to protect a React application against CSRF, you have to introduce a security solution in your app, and have the web server support it.

Luckily, it’s easy to implement CSRF protection in React. You only have to store the CSRF token in your React app and generate relevant headers to send along with the request to the server. The server will quarantine all CSRF requests.

Bright’s technology for CSRF Token security

You can easily stop CSRF attacks by just adding code that requires a CSRF token. To do so, you need to know which applications are vulnerable and where, and Bright can help!

Bright automatically scans every aspect of your apps, providing actionable reports. It seamlessly integrates with the tools and workflows developers already use. Scans are fast as our AI-powered engine can understand application architecture and generate sophisticated and targeted attacks. The results are completely false-positive free, so you can focus on releasing code.

Try Bright today, and start testing for CSRF, XSS, and hundreds of other vulnerabilities in minuteshttps://app.brightsec.com/login

Want to learn more about CSRF?

Have a look at these articles: