---
# System prepended metadata

title: Robust Programming
tags: [Secure programming]

---

---
tags: Secure programming
---

# Robust Programming 

:::info
These notes were taken during the course https://www.coursera.org/learn/secure-coding-principles :information_source: 
:::

## Basic Principles

The basic idea is to "program defensively", same mindset as "drive defensively".

- **Paranoia**: Don't trust what you don't generate.
- **Stupidity**: If it can be invoked incorrectly, it will be.
- **Dangerous Implements**: Inconsistent methods across the design patterns (invocations, access, etc.).
- **Can't happen**: Programmers assume the issues can/would not happen. Check for impossible errors.

## Coding practice

### Fragile coding and error handling

- Always check for user input to functions or constructors. Recall **Paranoia**.
- Keep variables inside class private.
- Throw an error message with error code, don't throw something random that would violate the **principle of least astonishment.**
- Don't allow user inputs in any kind of loggers or messages.
- Leave debug code inside, don't remove and comment it if you cannot commit it.

<!-- c specific:
Use of ==nonce==, a monotonic increasing number. Don't return pointers to internal strcuture.

throw an error with a string message. -->


In summary:
- Order of parameters (arguments) not checked - check order
- values of parameters (arguments) arbitary - specify type
- calls with pointers to pointers
- values of parameters not sanity checked - do santiy check
- return values not checked - check return values
- overflow, underflow ignored - integer and arrays

### Cohesion

- Cohesion refers to how well functions work together, you must have different functions for different actions. High cohesion means one method does alot of actions towards different goals, low cohesion means one action is done by one method towards same goal.

### Data/Function hiding

- keep internal structure hidden from the caller.
- Functions intended to be used locally within a class or library should be private/static.

# C 

- `private` functions are declared as `static`.
- Declare interface in `*.h` files.
- `assert()` can be used, but it is not very graceful. It will core dump and terminate the program.
- Avoid passing pointers when ever possible, it is hard to typecheck pointers address. You can check for `NULL`.

# Queue example

```
queue [LIFO]
-> create(size)
    -> success, returns a token
    -> no valid memory
    -> invalid input
-> delete(queue)
    -> success
    -> no such queue
    -> invalid input
-> insert(item) (last in)
    -> success return queue
    -> invalid input
    -> queue overflow
-> remove(item) (first out)
    -> success return item, queue must be have null items
    -> queue empty (underflow)
    -> invalid input
```

