Skip to content

Instantly share code, notes, and snippets.

@truekonrads
Last active July 13, 2018 03:21
Show Gist options
  • Select an option

  • Save truekonrads/4fd988a4c414384f8e04 to your computer and use it in GitHub Desktop.

Select an option

Save truekonrads/4fd988a4c414384f8e04 to your computer and use it in GitHub Desktop.
SSH and SFTP within same connection
#!/usr/bin/env python
# While doing IR, we found a log entry which suggested that sftp was open, file was uploaded, but we
# couldn't figure out how it was executed as there wasn't a second login attempt to start the script
# This script explains it.
# Feb 3 15:30:17 kali sshd[5222]: Accepted password for joe from 192.168.61.1 port 28568 ssh2
# Feb 3 15:30:17 kali sshd[5222]: pam_unix(sshd:session): session opened for user joe by (uid=0)
# Feb 3 15:30:17 kali sshd[5227]: subsystem request for sftp by user joe
# Feb 3 15:30:20 kali sshd[5222]: pam_unix(sshd:session): session closed for user joe
# C:\Users\Joe\Desktop\>python ssh-sftp-and-exec.py
# [**] Connecting to 192.168.61.172 done!
# [**] Opening a sftp session done!
# [**] Writing a script file /tmp/script.sh done!
# [**] Executing script path /tmp/script.sh done!
# -rw-r--r-- 1 1001 1001 0 03 Feb 15:30 ?
import paramiko,time
script="""#!/bin/sh
touch /tmp/hackedyou
"""
SERVER="192.168.1.1"
USERNAME="joe"
PASSWORD="hacker"
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "[**] Connecting to %s" % SERVER,
ssh.connect(hostname=SERVER,username=USERNAME,password=PASSWORD)
print "done!"
sftpclient=ssh.open_sftp()
print "[**] Opening a sftp session",
f=sftpclient.open("/tmp/script.sh","wb")
print "done!"
print "[**] Writing a script file %s" % "/tmp/script.sh",
f.write(script)
f.close()
print "done!"
print "[**] Executing script path %s" % "/tmp/script.sh",
stdin,stdout,stderr=ssh.exec_command("sh /tmp/script.sh")
print "done!"
time.sleep(3)
print sftpclient.lstat("/tmp/hackedyou")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment