Python Base64 LANGSEC Fail

At work, I validated data before feeding it to Python 3.6 Base64 decoding. Since Base64 has a regular grammar, I validated the input with a regular expression. A coworker suggested to put Base64 decoding in a try-block instead and then catch resulting exceptions. I suspect that person assumed that the base64 module from Python 3.6 checks if its input matches the Base64 grammar. Unsurprisingly, the assumption does not hold:

>>> from base64 import b64decode
>>> # valid base64
... b64decode(b'Vm0=')
b'Vm'
>>> # invalid base64, no multiple of four
... b64decode(b'Vm0==')
b'Vm'
>>> # invalid base64, no multiple of four, overlong padding
... b64decode(b'Vm0===')
b'Vm'
>>> # invalid base64, no multiple of four, padding inside input
... b64decode(b'V=m=0=w')
b'Vm'
>>> # invalid base64, padding inside input
... b64decode(b'V=m=0=w=')
b'Vm'
>>> # invalid base64, no multiple of four, padding inside input
... b64decode(b'V=m=0=w==')
b'Vm'
>>> # invalid base64, no multiple of four, padding inside input, overlong padding
... b64decode(b'V=m=0=w===')
b'Vm'

The above demonstration shows that one cannot trust the Python 3.6 base64 module to throw an exception on invalid input, as it will happily eat garbage and regurgitate the same. As often with input handling bugs, following LANGSEC best practices would have prevented this: Full recognition before processing – no exceptions!