# Code Smell 189 - Not Sanitized Input


> TL;DR: Sanitize everything that comes from outside your control.

# Problems

- Security

# Solutions

1. Use sanitization and input filtering techniques.

# Context

Whenever you get input from an external resource, a security principle requests you to validate and check for potentially harmful inputs.

[SQL Injection](https://en.wikipedia.org/wiki/SQL_injection) is a notable example of a threat.

We can also add [assertions](https://maximilianocontieri.com/code-smell-15-missed-preconditions-1) and invariants to our inputs.

Even better, we can work with [Domain Restricted Objects](https://maximilianocontieri.com/code-smell-178-subsets-violation).

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/d72d1e6617755cd8eff723b4dba90078)
```python
user_input = "abc123!@#"
# This content might not be very safe if we expect just alphanumeric characters
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/2c19c64f268afb946ee8560e19cf444f)
```python
import re

def sanitize(string):
  # Remove any characters that are not letters or numbers
  sanitized_string = re.sub(r'[^a-zA-Z0-9]', '', string)
  
  return sanitized_string

user_input = "abc123!@#"
print(sanitize(user_input))  # Output: "abc123"

```

# Detection

[X] Semi-Automatic 

We can statically check all the inputs and also we can also use penetration testing tools.

# Tags

- Security

# Conclusion

We need to be very cautious with the inputs beyond our control.

# Relations

%[https://maximilianocontieri.com/code-smell-121-string-validations]

%[https://maximilianocontieri.com/code-smell-178-subsets-violation]

%[https://maximilianocontieri.com/code-smell-15-missed-preconditions-1]

# More Info

- [Wikipedia](https://en.wikipedia.org/wiki/SQL_injection)

# Disclaimer

Code Smells are just my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Jess Zoerb](https://unsplash.com/@jzoerb) on [Unsplash](https://unsplash.com/photos/UGCgoVmFZC0)
    
* * *

> Companies should make their own enterprise systems as often as network security companies should manufacture their own aspirin.

_Phil Simon_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
