#! /usr/bin/env python2

"""
   Demonstrates how to hide passwords in logging messages, based on a tip in https://stackoverflow.com/questions/48380452/mask-out-sensitive-information-in-python-log
"""

import re
import sys
import logging

class SensitiveFormatter(logging.Formatter):
  regexp = re.compile('PASSW(?:OR)?D[\'"]?[ :\t=]*(?:(?:u?[\'"])?)([-a-zA-Z0-9!@#$%^&*()_+=[\]\\|;:,./<>?]+)', re.IGNORECASE)

  @classmethod
  def _filter(cls, s):
    for hit in list(cls.regexp.finditer(s))[-1::-1]:
      sys.stderr.write('Processing {groups} at {start}:{end}\n'.format(
        groups=hit.groups(),
        start=hit.start(1),
        end=hit.end(1),
      ))
      s = s[:hit.start(1)] + ('*'*8) + s[hit.end(1):]
    return s

  def format(self, record):
    original = logging.Formatter.format(self, record)
    return self._filter(original)

LOG_FORMAT = '%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(msg)s'
logging.basicConfig(format=LOG_FORMAT)
log = logging.getLogger()
for handler in logging.root.handlers:
   handler.setFormatter(SensitiveFormatter(LOG_FORMAT))

log.setLevel(logging.DEBUG)

obj = {
        'password': 'secret',
        'list': [
          {
            'PASSWD': 'secret',
          },
        ],
      }

logging.info(obj)
logging.info('Password=shhhhhh')

creds = {u'cimc': {u'login': {u'password': u'Foobar@123', u'user': u'admin'}, u'reason': u'Credentials from /etc/creds', u'scp': {u'ip': '192.200.0.1', u'password': u'Foobar@123', u'user': u'stack'}}, u'em': {u'login': {u'password': u'Foobar@123', u'user': u'ubuntu'}, u'reason': u'Credentials from /etc/creds'}, u'shell': {}, u'sosreport': {}, u'nexus': {u'login': {u'password': u'Foobar@123', u'user': u'admin'}, u'reason': u'Credentials from /etc/creds'}, u'uas': {u'login': {u'password': u'Foobar@123', u'user': u'ubuntu'}, u'reason': u'Credentials from /etc/creds'}, u'cf': {u'login': {u'password': u'Foobar@123', u'user': u'admin'}, u'reason': u'Credentials from /etc/creds'}, u'esc': {u'login': {u'password': u'Foobar@123', u'user': u'admin'}, u'reason': u'Credentials from /etc/creds'}}
logging.info('Credentials: {creds}'.format(**locals()))
