The easiest way to stay in an owned system is through the remote access tools of the operating system itself, yes I’m talking about SSH. To detect this type of intrusion, we will program a script that generates an MD5 hash of the authorized keys file and compares it with a previously calculated value, if these values do not match, it will notify us via telegram.
vi /root/sshKeys.py
import requests
import hashlib
import os.path
def sendMessage(msg):
apiKey = "XXXXXXXXXXXXXXXXXX"
userId = "YYYYY"
data = {"chat_id":userId,"text":msg}
url = "https://api.telegram.org/bot{}/sendMessage".format(apiKey)
r = requests.post(url,json=data)
if os.path.exists('/home/kr0m/.ssh/authorized_keys'):
kr0mHash = hashlib.md5(open('/home/kr0m/.ssh/authorized_keys','rb').read()).hexdigest()
#print 'kr0mHash: ' + str(kr0mHash)
if kr0mHash != 'ZZZZZZZZZZZZZZZZZZZZZZZZZZ':
sendMessage('Warning: Kr0m authorizedkeys modified!!')
else:
sendMessage('Warning: Kr0m authorizedkeys deleted!!')
if os.path.exists('/root/.ssh/authorized_keys'):
rootHash = hashlib.md5(open('/root/.ssh/authorized_keys','rb').read()).hexdigest()
#print 'rootHash: ' + str(rootHash)
sendMessage('Warning: Root authorizedkeys created!!')
We schedule the script to perform the check every 5 minutes:
*/5 * * * * python /root/sshKeys.py >/dev/null 2>&1