Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Author Posts - Cybersecurity

3 Articles
article-image-scripting-with-postman-a-practical-guide-to-postman-scripting-and-security
Confidence Staveley
11 Nov 2024
15 min read
Save for later

Scripting with Postman: A Practical Guide to Postman Scripting and Security

Confidence Staveley
11 Nov 2024
15 min read
IntroductionAPIs are everywhere these days. In fact, they’re responsible for a whopping 73% of internet traffic in 2023, according to the State of API Security in 2024 Report by Imperva. With this level of activity, especially in industries like banking and online retail, securing APIs isn’t just important—it’s essential. The average organization has around 613 API endpoints in production, and as the pressure to deliver faster mounts, that number is only growing. To keep up with this demand while ensuring security, adopting a ‘Shift-left’ approach is crucial. What does that mean? It means integrating security earlier in the development process—right from the design stage, all the way to deployment. By doing this, you’re not just patching up vulnerabilities at the end but embedding security into the very fabric of your API. Getting Started with API Testing API testing plays a huge role in this approach. You’re essentially poking and prodding at the logic layer of your application, checking how it responds, how fast it does so, how accurately it handles data, and whether it can fend off security threats. This is where Postman shines. It’s a widely used tool that’s loved for its ease of use and versatility, making it a perfect fit for your shift-left strategy. With Postman, you can simulate attack scenarios, test for security issues, and validate security measures, all within the same space where you build your APIs. But before we dive into scripting in Postman, let’s get it installed. Installing Postman and Setting Up First things first, if you don’t already have a Postman account, head over to their website to create one. You can sign up using Google if you prefer. Once that’s done, download the version that suits your operating system and get it installed. We’ll need a vulnerable API to test our scripts, and the BreachMe API in my book (API Security For White Hat Hackers) is perfect for this. You can find it here. Follow the documentation to set it up, and don’t forget to import the BreachMe collection into Postman. Just click the import button in the collections tab, and you’re good to go. Postman Scripting Basics Scripts in Postman are where things get really interesting. They allow you to add dynamic behavior to your API requests, mimicking complex workflows and writing test assertions that simulate real-world scenarios. Postman’s sandbox execution environment is written in JavaScript, This means that in order to make a script executable in Postman, it has to be written in Javascript. So, If you’re familiar with Javascript, you’re already halfway there. There are two main types of scripts in postman. The first, pre-request script which is run before a request is rendered to Postman. The second, post-response scripts are scripts that are run after Postman gives a response to a sent request. The order of script execution for a single request is as follows: There are two main types of scripts in Postman: Pre-request Scripts: These run before a request is sent to the API. Post-response Scripts: These kick in after the API responds. The order of script execution for a single request is as follows: Pre-request script You can run these scripts at three levels: the request level, folder level, and collection level. This flexibility means you can apply scripts to individual requests, a group of requests, or even an entire collection. The execution of these scripts will happen in the following order. Dynamic Variables and API Testing During API testing, you often need to work with various user inputs, which can be tedious to create manually each time. One of the coolest features of Postman scripting is the ability to add dynamic behavior to a request. Imagine trying to manually create user inputs for each test—it would be a nightmare. Postman allows you to automate this process, generating variables like random usernames, random IP addresses, email addresses, and passwords on the fly. For example, to generate a dynamic username you can use {{$randomUserName}}. Want a dynamic email? Just use {{$randomEmail}}. And for a password, {{$randomPassword}} has you covered. This makes it easy to send multiple requests to the register endpoint, effectively testing the API.  Postman provides everything and we can now send as many register requests as we need to effectively test the API. Dynamic variables can also be set using pre-request scripts. Post-Response Scripts for Functional Testing Postman can be used to perform essential API testing such as functional testing, this is testing to ensure that the API works/functions in the way it is intended to. When testing functionality, postman allows you to send requests to your API endpoints and validate the responses against expected outcomes. You can check if the API returns the correct data, handles inputs properly, and responds with appropriate status codes (e.g., 200 OK, 404 Not Found). Let’s try that in the above API to check if the login endpoint will return a 200 status code. Navigate to the login endpoint’s script tab and choose the post-response tab.  The script we will use will look like this… Let’s break down the snippet. We’ll use the pm.test() function. The first argument “Status code is 200” will be used as the description of the test. The second argument is a function that will contain the actual test. The pm.response refers to the response object. .to.have.status(200) evaluates whether the response status code is 200.Post-request scripts can be used to set tokens or variables that will be needed throughout the testing of the API. Imagine testing an API and manually copying and pasting variables between requests—tiring, right? This approach ensures the variable is accessible across all requests in the collection, making your testing workflow more efficient, less error-prone, and more secure. Some variables contain sensitive data and may require a bit more protection especially when working in a collaborative environment. Postman recommends using variables in such cases. Let’s take an example of an access token that is short-lived, used by most of the endpoints in the collection, and is set when the login request is successful. To streamline this, we could use a post-response script in the login endpoint to automatically set it. Navigate to the auth folder of the Breachme_API collection and select the login endpoint. Ensure that the username you are trying to log in as is a registered user but using the register login before the login endpoint. When logging in, you’ll require a correct username and password in the body of the request as shown below. The correct credentials will result in a response containing the token. To set it, we will need to get the response; take only the token and set it. The script will look like this: var theResponse =pm.response.json();  pm.collectionVariables.set("access_token", theResponse.token) The first line of code captures the response from the API request and converts it to a JSON object then stores it in a variable theResponse. The pm.response.json() is a Postman function that parses the response body as JSON, making it accessible as a JavaScript object. With the response accessible, we can then get the token using the theResponse.token and set it as a collection variable with the command pm.collectionVariables.set() function. The first parameter will specify the collection variable you want to save it as.  Postman scripts can also be used to validate whether the response contains the expected data. Let’s say you have created a post, you would expect it to have the ‘id’, ‘username’, ‘message’, and maybe an ‘image’. You can use Postman to check if every expected data is returned in the expected format. Let’s check if the register endpoint returns what we expect, with the body {    "username":"user2",    "email":"user2@email.com",    "password":"user2password"  } We expect the response to look like below {    "message": "user created successfully",    "user": {        "id": 2,        "email": "user2@email.com",        "username": "user2",        "is_admin": false,        "password": "#############",        "createdAt": "2024-08-28T22:13:30.000Z"    },    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MiwiZW1haWwiOiJ1c2VyMkBlbWFpbC5jb20iLCJ1c2VybmFtZSI6InVzZXIyIiwiaXNfYWRtaW4iOmZhbHNlLCJwYXNzd29yZCI6IiMjIyMjIyMjIyMjIyMiLCJjcmVhdGVkQXQiOiIyMDI0LTA4LTI4VDIyOjEzOjMwLjAwMFoiLCJpYXQiOjE3MjQ4ODMyMTAsImV4cCI6MTcyNTE0MjQxMH0.Z3fdfRXkePNFoWgX2gSqrTTtOy_AzsnG8yG_wKdnOz4"  } To automate it, we will use the script in the post-response tab of the register endpoint. pm.test("User object has id, email, username, is_admin, password", function () {    const responseData = pm.response.json();    pm.expect(responseData.user).to.have.property("id");    pm.expect(responseData.user).to.have.property("email");    pm.expect(responseData.user).to.have.property("username");    pm.expect(responseData.user).to.have.property("is_admin");    pm.expect(responseData.user).to.have.property("password");  }); To ensure that your API meets performance requirements, you can use a post-response script to measure the response time. The snippet we will use us as seen below: pm.test("Response time is less than 300ms", function () {  pm.expect(pm.response.responseTime).to.be.below(300);  }); The above script uses the pm.test() function with the test description as the first argument and an anonymous function that contains the actual test as the second argument. The pm.expect() function is a Postman function that is used to make assertions, it sets up an expectation for a certain condition. In this case, it expects that the pm.response,responseTime will be below 300 milliseconds. Not meeting this expectation makes the test fail. Conclusion Scripting in Postman isn’t just about convenience—it’s about transforming your testing into a proactive, security-focused process. By using these scripts, you’re not only automating repetitive tasks but also fortifying your API against potential threats. Combine this with other security measures, and you’ll have an API that’s ready to hold its own in the fast-paced world of software development. "As you continue to deepen your understanding of API security and testing, consider exploring "API Security for White Hat Hackers" written by Confidence Staveley. This book is a comprehensive guide that simplifies API security by showing you how to identify and fix vulnerabilities. From emerging threats to best practices, this book helps you defend and safeguard your APIs.Author BioConfidence Staveley is a multi-award-winning cybersecurity leader with a background in software engineering, specializing in application security and cybersecurity strategy. Confidence excels in translating cybersecurity concepts into digestible insights for diverse audiences. Her YouTube series, “API Kitchen,” explains API security using culinary metaphors.nConfidence holds an advanced diploma in software engineering, a bachelor’s degree in IT and business information systems, and a master’s degree in IT management from the University of Bradford, as well as numerous industry certifications such as CISSP, CSSLP, and CCISO. In addition to her advisory roles on many boards, Confidence is the founder of CyberSafe Foundation and MerkleFence.
Read more
  • 0
  • 0
  • 1138

article-image-developers-need-to-say-no-elliot-alderson-on-the-faceapp-controversy-in-a-bonus-podcast-episode-podcast
Richard Gall
12 Aug 2019
5 min read
Save for later

"Developers need to say no" - Elliot Alderson on the FaceApp controversy in a BONUS podcast episode [Podcast]

Richard Gall
12 Aug 2019
5 min read
Last month there was a huge furore around FaceApp, the mobile application that ages your photographs to show you what you might look like as you get older. This was caused by a rapid cycle of misinformation and conjecture. It was thanks to cybersecurity researcher Elliot Alderson - who you might remember from last week's podcast episode - that the world was able to get beyond speculation and find out what was really going on. We got in touch with Elliot shortly after the story broke. He was kind enough to speak to us about the FaceApp furore, and explained what caused the confusion and how he managed to get to the bottom of what was actually going on. You can listen to what he had to say in this special short bonus episode: https://soundcloud.com/packt-podcasts/bonus-security-researcher-elliot-alderson-on-the-faceapp-furore   Elliot says that although FaceApp is problematic, it isn't unique. It poses exactly the same threat to our privacy as the platforms and applications that millions of people use every day. "There is an issue with FaceApp, he tells us. "But there is an issue with Facebook, with SnapChat, with Twitter - it's never a good idea for someone to upload a photo of your face to a random application." This line of argument can be found elsewhere. Arguably the most important lesson we can learn. In this article from Wired, journalist Brian Barrett writes "should you be worried about FaceApp? Sure. But not necessarily more than any other app you let into your photo library." Should you use FaceApp? However, although you might assume that a security professional would simply warn everyone against using these sorts of applications, Elliot says "this application is really trendy. You can see a lot of stars using it on social media, so this is normal - you want to use this application." What you need to consider if want to use FaceApp However, if you do want to use it, you should be careful. "You have to step back a little bit before using it and ask yourself a question" about how money is being made. "this is a free application... there are developers behind this application, they need to live, they need to eat, they need to live, they need to eat - they need to earn money - and in general the answer is with your data." "You are the information." Elliot says. "You can decide to use it, and say okay, I'm ready to lose this part of my privacy in order to use this cool service... or you will... think no, it's not worth it. FaceApp seems to be cool, but my privacy is more important than something trendy like this." The key, then, is to check the terms and conditions of the application. "You have to know that you will have lost a part of your privacy, And if you're okay with that then - okay, go for it, and use the application." "Developers need to say no sometimes." Developer responsibility and code ethics There are clearly question marks for users about FaceApp, or, indeed, any other free application that has access to your data. But what about the developers building these applications? Do they have a part to play in ensuring that applications respect user consent and privacy? "It's complicated for a developer to say no to their project manager" says Elliot. However, this doesn't mean developers should be content to follow orders from management. "Developers need to raise their level... and say okay, but ethics is also important..." Elliot continues, "as a technical guy I need to spread the message internally in my company, and say to the project manager, to the business, to the marketing department okay this is a cool feature but no, we won't do that because this is against our user'." "Developers need to say no sometimes - and companies need to understand that it's not okay to dump as much data as possible from their users." How did Elliot Alderson uncover the truth about FaceApp? One thing that is often forgotten in these stories are the technical processes through which the truth is uncovered. Sure, that might be a little dry or complicated for some, but the fact that there is real detective work in understanding what's actually going on inside an application is incredibly interesting. It also highlights that while software might sometimes appear mysterious or even impenetrable, with the right skills and tools we can see how things actually work. That's not only useful from a technical perspective, it's also a way for all of us to retrieve a small sense of power back from applications built and owned by companies worth billions of dollars. "It's not that easy, but it's not super complicated too," says Elliot. Although he tells us that "the first time you want to do it you need to spend some time on it for sure," once you're set up and ready to go you can find things out remarkably fast. Using a tool called Burp Suite, the whole process was complete in a matter of moments. "Checking FaceApp took literally 5 minutes for me, because everything is already set up on my computer and I just have to install the application and look at the network request." Learn more about Burp Suite with Packt's selection of eBooks and videos here. Follow Elliot Alderson on Twitter: @fs0c131y
Read more
  • 0
  • 0
  • 3298

article-image-listen-we-discuss-what-it-means-to-be-a-hacker-with-adrian-pruteanu-podcast
Richard Gall
26 Apr 2019
2 min read
Save for later

Listen: We discuss what it means to be a hacker with Adrian Pruteanu [Podcast]

Richard Gall
26 Apr 2019
2 min read
With numerous high profile security breaches in recent years, cybersecurity feels like a particularly urgent issue. But while the media - and, indeed, the wider world - loves stories of modern vulnerabilities and mischievous hackers, there's often very little attention paid to what causes insecurity and what can practically be done to solve such problems. To get a better understanding of cybersecurity in 2019, we spoke to Adrian Pruteanu, consultant and self-identifying hacker. He told us about what he actually does as a security consultant, what it's like working with in-house engineering teams, and how red team/blue team projects work in practice. Adrian is the author of Becoming the Hacker, a book that details everything you need to know to properly test your software using the latest pentesting techniques.          What does it really mean to be a hacker? In this podcast episode, we covered a diverse range of topics, all of which help to uncover the reality of working as a pentester. What it means to be a hacker - and how it's misrepresented in the media The biggest cybersecurity challenges in 2019 How a cybersecurity consultant actually works The most important skills needed to work in cybersecurity The difficulties people pose when it comes to security Listen here: https://soundcloud.com/packt-podcasts/a-hacker-is-somebody-driven-by-curiosity-adrian-pruteanu-on-cybersecurity-and-pentesting-tactics
Read more
  • 0
  • 0
  • 4477
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime