Robust and secure programming Flashcards
Steps to install bandit and analyse a piece of code
pip install bandit and bandit -r path/to/your/code
Three examples of security flaws that bandit can find
Use of dangerous functions, weak cryptographic practices and insecure deserialization.
Name THREE specific techniques that can be used to make programs more robust.
Input validation, error handling and exception management, and defensive programming.
Using a code fragment, explain how “Input validation” works
Input validation is the process of ensuring that user inputs meet certain criteria before proceeding with further processing. def get_positive_integer(): try: user_input = int(input(“Enter a positive integer: “)) if user_input <= 0: print(“Error: Please enter a positive integer.”) else: return user_input except ValueError: print(“Error: Input must be an integer.”)
Using a code fragment, explain how “Defensive programming” works
Defensive programming is a coding style that anticipates potential errors and incorporates safeguards to prevent them.def calculate_average(numbers): if not isinstance(numbers, list): raise TypeError(“Input must be a list of numbers”) if len(numbers) == 0: return 0 total = 0 for num in numbers: if not isinstance(num, (int, float)): raise TypeError(“All elements in the list must be numbers”) total += num return total / len(numbers)
Using a code fragment, explain how “Error handling and exception management” works
Use try/except.def divide_numbers(a, b): try: result = a / b print(“Result of division:”, result) except ZeroDivisionError: print(“Error: Division by zero is not allowed.”) except TypeError: print(“Error: Please provide numeric values for division.”) except Exception as e: print(“An unexpected error occurred:”, e)
The following function, written in Python, takes a file name as input and then shows the contents of the file on the screen. Explain why it is not a robust program? Propose TWO different mechanism to make it robust.
It lacks error handling and resource management. Use try and except to catch any errors while opening and using the file. Use a with statement (context manager) to open the file. This ensures that the file handle is automatically closed when the block of code exits, even if an exception occurs. It helps prevent resource leaks and ensures proper cleanup.
You have been asked to develop a strategy to evaluate the security of the codebase for the control panel software. Describe THREE actions you would take in carrying out this evaluation.
Code Review and Static Analysis
Penetration Testing and Vulnerability Assessment
Threat Modeling and Risk Analysis.
Describe TWO things you should do before including an open-source library in yoursoftware.
Review the License and Assess the Quality and Maintenance.
Describe ONE positive and ONE negative of using open source code inyour project.
Positive: Faster Development
Negative: Dependency Risks.
Robust Programming in Python
Python has built-in exception handling, optional type hints, and extensive testing ecosystem.
Robust Programming in Javascript
Javascript with its evolving error handling capabilities, type safety improvements with TypeScript, and a good collection of testing frameworks.
Assume there is a module named UploadFile(path) which takes a string as its parameter (it is the path of a file on your local computer) and then uploads the file to the server. This function has various outcomes depending on if the upload was successful. Write the code that you would use to run the synchronous UploadFile(path)in a way that doesn’t crash if the upload fails (for example if the file does not exist in the given path)
Wrap it in a try/except clause
Assume that you are using this piece of code (UploadFile(path)) in a critical system. Thus, you have been asked to conduct a static security audit on the code. Give TWO examples and descriptions of the kind of problems you would expect a static security audit to find.
Input Validation Issues: One common problem that a static security audit may find is inadequate input validation. This includes failing to properly validate user input or external data before processing it. For example, if the UploadFile(path) function does not perform sufficient validation on the input file path, an attacker could potentially manipulate the path to access unauthorised files on the system or exploit path traversal vulnerabilities.
Insecure File Handling: Another issue that a static security audit may uncover is insecure file handling practices. This includes improper file permissions, insecure temporary file creation, or lack of proper file sanitization. For instance, if the UploadFile(path) function does not enforce proper file permissions or sanitization when handling uploaded files, it could allow an attacker to overwrite or execute arbitrary files on the system, leading to unauthorized access or code execution vulnerabilities.
Static security audit
The assessment is performed without executing the application’s code. It involves analysing the application’s source code, configuration files, and documentation to identify potential security vulnerabilities, design flaws, or coding errors. Static analysis tools and manual code review techniques are commonly used as well.